@copilotkit/react-core 2.0.0-rc.61 → 2.0.0-rc.62
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/generative-ui.d.cts +59 -59
- package/dist/generative-ui.d.mts +59 -59
- package/dist/headless.cjs +5 -0
- package/dist/headless.cjs.map +1 -1
- package/dist/headless.d.cts +5 -0
- package/dist/headless.d.cts.map +1 -1
- package/dist/headless.d.mts +5 -0
- package/dist/headless.d.mts.map +1 -1
- package/dist/headless.mjs +5 -0
- package/dist/headless.mjs.map +1 -1
- package/dist/index.cjs +266 -50
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -4
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +14 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +263 -53
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +266 -50
- package/dist/index.umd.js.map +1 -1
- package/dist/v2/index.d.cts +8 -0
- package/dist/v2/index.d.mts +8 -0
- package/package.json +9 -9
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["React","TooltipPrimitive","React","DropdownMenuPrimitive","React","CopilotIcon","ɵAudioRecorder","useCopilotChatConfiguration","CopilotChatDefaultLabels","useLatestRef","ɵComposerController","renderSlot","CopilotIcon","React","useCopilotChatConfiguration","React","React","useLabels","useCopilotChatConfiguration","CopilotChatDefaultLabels","ɵLICENSE_BANNER_STYLE","ɵINLINE_FEATURE_WARNING_STYLE","ɵMcpAppHost","OPEN_GENERATIVE_UI_ACTIVITY_TYPE","ɵOPEN_GENERATIVE_UI_CONTENT_SCHEMA","ɵGENERATE_SANDBOXED_UI_ARGS_SCHEMA","ɵOpenGenerativeUIController","ɵPlaceholderCycler","ToolCallStatus","CopilotKitCore","ɵRendererRegistry","version","stylesheet","MCPAppsActivityType","MCPAppsActivityContentSchema","createGenerativeUIActivityRenderer","createGenerativeUIFunctionCallActivityRenderer","useGenerativeUIRoot","ɵLearningAutoStarter","CopilotKitContext","LicenseContext","GenerativeUIToolCallRenderer","MarkdownRendererProvider","CopilotKitAgentIdContext","GenerativeUIRuntimeContext","useCopilotChatConfiguration","useCopilotChatConfiguration","EMPTY_DEPS","defineToolCallRenderer","ToolCallStatus","useLabels","useCopilotChatConfiguration","CopilotChatDefaultLabels","CopilotIcon","ɵTOOL_CALL_STATUS_ICONS","ɵTOOL_CALL_STATUS_LABEL_KEYS","React","ɵadaptDefaultToolCallRenderProps","useCopilotChatConfiguration","CopilotChatDefaultLabels","React","useCopilotChatConfiguration","useCopilotChatConfiguration","useCopilotChatConfiguration","ɵInterruptController","ɵThreadsController","ɵselectMemories","ɵselectMemoriesIsLoading","ɵselectMemoriesError","ɵselectMemoriesAvailable","ɵselectMemoriesRealtimeStatus","useCopilotChatConfiguration","ɵAttachmentQueue","React","renderSlot","ɵinspectorShortcuts","ɵinspectorKiteIcon","useCopilotChatConfiguration","CopilotChatDefaultLabels","ɵHoverMenuController","CopilotIcon","PopoverPrimitive","React","ɵFeedbackCommentController","ɵCopyFeedback","isReactComponentType","React","useCopilotChatConfiguration","renderSlot","CopilotChatDefaultLabels","Fragment","useShallowStableRef","useMarkdownRenderer","useGenerativeUIRuntime","MarkdownSurfaces","StreamingMarkdownDefaultRenderer","CopilotIcon","ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH","useCopilotChatConfiguration","CopilotChatDefaultLabels","CopilotIcon","useCopilotChatConfiguration","CopilotChatDefaultLabels","renderSlot","useCopilotChatConfiguration","CopilotChatDefaultLabels","CopilotIcon","useCopilotChatConfiguration","CopilotChatDefaultLabels","ɵReasoningDisclosure","renderSlot","CopilotIcon","StreamingMarkdownDefaultRenderer","React","CopilotIcon","React","renderSlot","React","React","useCopilotChatConfiguration","CopilotChatDefaultLabels","CopilotIcon","useCopilotChatConfiguration","renderSlot","isReactComponentType","React","useCopilotChatConfiguration","ɵcreateMessageViewModel","renderSlot","CopilotChatAssistantMessage","CopilotChatUserMessage","CopilotChatReasoningMessage","useCopilotChatConfiguration","CopilotChatDefaultLabels","CopilotIcon","ɵinitialKeyboardState","React","useCopilotChatConfiguration","CopilotChatDefaultLabels","CopilotIcon","renderSlot","CopilotChatInput","StickToBottom","ɵInspectorThreadOverride","useCopilotChatConfiguration","ɵFreshThreadId","ɵChatConnection","CopilotKitCoreRuntimeConnectionStatus","useShallowStableRef","renderSlot","CopilotChatConfigurationProvider","CopilotChatDefaultLabels","GenerativeUIChatSlotContext","CopilotIcon","React","useCopilotChatConfiguration","CopilotChatDefaultLabels","renderSlot","useCopilotChatConfiguration","CopilotChatDefaultLabels","renderSlot","CopilotIcon","CopilotChatConfigurationProvider","ControlledModalOpenScope","useCopilotChatConfiguration","ɵSIDEBAR_DEFAULT_WIDTH","ɵSIDEBAR_TRANSITION_MS","renderSlot","CopilotChatDefaultLabels","CopilotChatView","CopilotChatConfigurationProvider","ControlledModalOpenScope","useCopilotChatConfiguration","CopilotChatDefaultLabels","renderSlot","ɵPOPUP_DEFAULT_WIDTH","ɵPOPUP_DEFAULT_HEIGHT","CopilotChatView","CopilotChatView","React","CopilotPopupView","CopilotChatView","useCopilotChatConfiguration","CopilotKitContext","ɵtoDrawerThread","React","COPILOTKIT_THREADS_DRAWER_TAG","defineToolCallRenderer"],"sources":["../src/components/ui/button.tsx","../src/components/ui/tooltip.tsx","../src/components/ui/dropdown-menu.tsx","../src/components/chat/CopilotChatAudioRecorder.tsx","../src/components/chat/CopilotChatInput.tsx","../src/hooks/use-render-tool-call.tsx","../src/providers/use-owned-core.ts","../package.json","../src/components/CopilotKitInspector.tsx","../src/components/CopilotKitInspectorContext.tsx","../src/components/license-warning-banner.tsx","../src/components/MCPAppsActivityRenderer.tsx","../src/providers/SandboxFunctionsContext.ts","../src/components/OpenGenerativeUIRenderer.tsx","../src/generative-ui/use-standard-ui-fallback.ts","../src/lib/react-core.ts","../src/styles/copilot-kit-styles.tsx","../src/providers/CopilotKitProvider.tsx","../src/hooks/use-render-custom-messages.tsx","../src/hooks/use-render-activity-message.tsx","../src/hooks/tool-registration.ts","../src/hooks/use-frontend-tool.tsx","../src/hooks/use-frontend-tools.tsx","../src/hooks/use-component.tsx","../src/hooks/use-render-tool.tsx","../src/components/chat/CopilotChatToolCallGroup.tsx","../src/hooks/use-default-render-tool.tsx","../src/hooks/use-human-in-the-loop.tsx","../src/hooks/use-agent.tsx","../src/hooks/use-capabilities.tsx","../src/hooks/use-agent-context.tsx","../src/hooks/use-suggestions.tsx","../src/hooks/use-configure-suggestions.tsx","../src/hooks/use-interrupt.tsx","../src/hooks/use-threads.tsx","../src/hooks/use-memories.tsx","../src/hooks/use-learn-from-user-action.tsx","../src/hooks/use-learn-from-user-action-in-current-thread.tsx","../src/hooks/use-attachments.tsx","../src/components/chat/tool-call-display-context.ts","../src/components/chat/CopilotChatToolCallsView.tsx","../src/components/chat/CopilotChatInspectorButton.tsx","../src/components/ui/popover.tsx","../src/components/chat/message-feedback.tsx","../src/components/chat/use-copy-feedback.ts","../src/components/chat/CopilotChatAssistantMessage.tsx","../src/components/chat/Lightbox.tsx","../src/components/chat/CopilotChatAttachmentRenderer.tsx","../src/components/chat/CopilotChatUserMessage.tsx","../src/components/chat/CopilotChatReasoningMessage.tsx","../src/components/chat/CopilotChatSuggestionPill.tsx","../src/components/chat/CopilotChatSuggestionView.tsx","../src/components/chat/scroll-element-context.ts","../src/components/chat/scroll-pinned-context.ts","../src/components/chat/CopilotChatWorkSummary.tsx","../src/components/intelligence-indicator/IntelligenceIndicatorView.tsx","../src/components/intelligence-indicator/IntelligenceIndicator.tsx","../src/components/chat/CopilotChatMessageView.tsx","../src/components/chat/CopilotChatAttachmentQueue.tsx","../src/hooks/use-keyboard-height.tsx","../src/components/chat/last-user-message-context.ts","../src/hooks/use-pin-to-send.ts","../src/components/chat/CopilotChatView.tsx","../src/providers/use-inspector-thread-override.ts","../src/components/chat/CopilotChat.tsx","../src/components/chat/CopilotChatToggleButton.tsx","../src/components/chat/modal-open-control.tsx","../src/components/chat/CopilotModalHeader.tsx","../src/components/chat/CopilotSidebarView.tsx","../src/components/chat/CopilotPopupView.tsx","../src/components/chat/CopilotSidebar.tsx","../src/components/chat/CopilotPopup.tsx","../src/components/chat/CopilotThreadsDrawer.tsx","../src/components/WildcardToolCallRender.tsx"],"sourcesContent":["import * as React from \"react\";\n\nimport { cn } from \"../../lib/utils\";\nimport type { ClassValue } from \"../../lib/utils\";\n\n// Styles live in styles/css/ui/button.css.\nconst variantClasses = {\n default: \"cpk-button-default\",\n destructive: \"cpk-button-destructive\",\n outline: \"cpk-button-outline\",\n secondary: \"cpk-button-secondary\",\n ghost: \"cpk-button-ghost\",\n link: \"cpk-button-link\",\n assistantMessageToolbarButton: \"cpk-button-assistant-message-toolbar\",\n chatInputToolbarPrimary: \"cpk-button-chat-input-toolbar-primary\",\n chatInputToolbarSecondary: \"cpk-button-chat-input-toolbar-secondary\",\n} as const;\n\nconst sizeClasses = {\n default: \"cpk-button-size-default\",\n sm: \"cpk-button-size-sm\",\n lg: \"cpk-button-size-lg\",\n icon: \"cpk-button-size-icon\",\n chatInputToolbarIcon: \"cpk-button-size-chat-input-toolbar-icon\",\n chatInputToolbarIconLabel: \"cpk-button-size-chat-input-toolbar-icon-label\",\n} as const;\n\ntype ButtonVariant = keyof typeof variantClasses;\ntype ButtonSize = keyof typeof sizeClasses;\n\ninterface ButtonVariantProps {\n /** Defaults to `\"default\"`. `null` applies no variant class. */\n variant?: ButtonVariant | null;\n /** Defaults to `\"default\"`. `null` applies no size class. */\n size?: ButtonSize | null;\n}\n\n/**\n * Returns the class names for a button with the given variant and size,\n * followed by `className`.\n */\nfunction buttonVariants({\n variant,\n size,\n className,\n class: classProp,\n}: ButtonVariantProps & {\n className?: ClassValue;\n class?: ClassValue;\n} = {}): string {\n return cn(\n \"cpk-button\",\n variant !== null && variantClasses[variant ?? \"default\"],\n size !== null && sizeClasses[size ?? \"default\"],\n classProp,\n className,\n );\n}\n\nconst Button = React.forwardRef<\n HTMLButtonElement,\n React.ComponentProps<\"button\"> & ButtonVariantProps\n>(function Button({ className, variant, size, ...props }, ref) {\n return (\n <button\n ref={ref}\n data-slot=\"button\"\n className={buttonVariants({ variant, size, className })}\n {...props}\n />\n );\n});\n\nexport { Button, buttonVariants };\n","import * as React from \"react\";\nimport * as TooltipPrimitive from \"@radix-ui/react-tooltip\";\n\nimport { cn } from \"../../lib/utils\";\n\nfunction TooltipProvider({\n delayDuration = 0,\n ...props\n}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {\n return (\n <TooltipPrimitive.Provider\n data-slot=\"tooltip-provider\"\n delayDuration={delayDuration}\n {...props}\n />\n );\n}\n\nfunction Tooltip({\n ...props\n}: React.ComponentProps<typeof TooltipPrimitive.Root>) {\n return (\n <TooltipProvider>\n <TooltipPrimitive.Root data-slot=\"tooltip\" {...props} />\n </TooltipProvider>\n );\n}\n\nconst TooltipTrigger = React.forwardRef<\n HTMLButtonElement,\n React.ComponentProps<typeof TooltipPrimitive.Trigger>\n>(function TooltipTrigger({ ...props }, ref) {\n return (\n <TooltipPrimitive.Trigger\n ref={ref}\n data-slot=\"tooltip-trigger\"\n {...props}\n />\n );\n});\n\nfunction TooltipContent({\n className,\n sideOffset = 0,\n children,\n ...props\n}: React.ComponentProps<typeof TooltipPrimitive.Content>) {\n return (\n <TooltipPrimitive.Portal>\n <TooltipPrimitive.Content\n data-copilotkit\n data-slot=\"tooltip-content\"\n sideOffset={sideOffset}\n className={cn(\"cpk-tooltip\", className)}\n {...props}\n >\n {children}\n <TooltipPrimitive.Arrow className=\"cpk-tooltip-arrow\" />\n </TooltipPrimitive.Content>\n </TooltipPrimitive.Portal>\n );\n}\n\nexport { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };\n","\"use client\";\n\nimport * as React from \"react\";\nimport * as DropdownMenuPrimitive from \"@radix-ui/react-dropdown-menu\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\n\nimport { cn } from \"../../lib/utils\";\n\nfunction DropdownMenu({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {\n return <DropdownMenuPrimitive.Root data-slot=\"dropdown-menu\" {...props} />;\n}\n\nfunction DropdownMenuPortal({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {\n return (\n <DropdownMenuPrimitive.Portal data-slot=\"dropdown-menu-portal\" {...props} />\n );\n}\n\nconst DropdownMenuTrigger = React.forwardRef<\n HTMLButtonElement,\n React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>\n>(function DropdownMenuTrigger({ ...props }, ref) {\n return (\n <DropdownMenuPrimitive.Trigger\n ref={ref}\n data-slot=\"dropdown-menu-trigger\"\n {...props}\n />\n );\n});\n\nfunction DropdownMenuContent({\n className,\n sideOffset = 4,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Content> & {\n // Radix 2.1 forwards this to its focus scope but omits it from public types.\n onOpenAutoFocus?: (event: Event) => void;\n}) {\n return (\n <DropdownMenuPrimitive.Portal>\n <DropdownMenuPrimitive.Content\n data-copilotkit\n data-slot=\"dropdown-menu-content\"\n sideOffset={sideOffset}\n className={cn(\"cpk-dropdown-menu-content\", className)}\n {...props}\n />\n </DropdownMenuPrimitive.Portal>\n );\n}\n\nfunction DropdownMenuGroup({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {\n return (\n <DropdownMenuPrimitive.Group data-slot=\"dropdown-menu-group\" {...props} />\n );\n}\n\nfunction DropdownMenuItem({\n className,\n inset,\n variant = \"default\",\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {\n inset?: boolean;\n variant?: \"default\" | \"destructive\";\n}) {\n return (\n <DropdownMenuPrimitive.Item\n data-slot=\"dropdown-menu-item\"\n data-inset={inset}\n data-variant={variant}\n className={cn(\"cpk-dropdown-menu-item\", className)}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuCheckboxItem({\n className,\n children,\n checked,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {\n return (\n <DropdownMenuPrimitive.CheckboxItem\n data-slot=\"dropdown-menu-checkbox-item\"\n className={cn(\"cpk-dropdown-menu-checkbox-item\", className)}\n checked={checked}\n {...props}\n >\n <span className=\"cpk-dropdown-menu-item-indicator\">\n <DropdownMenuPrimitive.ItemIndicator>\n <CopilotIcon name=\"Check\" className=\"cpk-dropdown-menu-check-icon\" />\n </DropdownMenuPrimitive.ItemIndicator>\n </span>\n {children}\n </DropdownMenuPrimitive.CheckboxItem>\n );\n}\n\nfunction DropdownMenuRadioGroup({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {\n return (\n <DropdownMenuPrimitive.RadioGroup\n data-slot=\"dropdown-menu-radio-group\"\n {...props}\n />\n );\n}\n\nfunction DropdownMenuRadioItem({\n className,\n children,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {\n return (\n <DropdownMenuPrimitive.RadioItem\n data-slot=\"dropdown-menu-radio-item\"\n className={cn(\"cpk-dropdown-menu-radio-item\", className)}\n {...props}\n >\n <span className=\"cpk-dropdown-menu-item-indicator\">\n <DropdownMenuPrimitive.ItemIndicator>\n <CopilotIcon name=\"Circle\" className=\"cpk-dropdown-menu-radio-icon\" />\n </DropdownMenuPrimitive.ItemIndicator>\n </span>\n {children}\n </DropdownMenuPrimitive.RadioItem>\n );\n}\n\nfunction DropdownMenuLabel({\n className,\n inset,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {\n inset?: boolean;\n}) {\n return (\n <DropdownMenuPrimitive.Label\n data-slot=\"dropdown-menu-label\"\n data-inset={inset}\n className={cn(\"cpk-dropdown-menu-label\", className)}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuSeparator({\n className,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {\n return (\n <DropdownMenuPrimitive.Separator\n data-slot=\"dropdown-menu-separator\"\n className={cn(\"cpk-dropdown-menu-separator\", className)}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuShortcut({\n className,\n ...props\n}: React.ComponentProps<\"span\">) {\n return (\n <span\n data-slot=\"dropdown-menu-shortcut\"\n className={cn(\"cpk-dropdown-menu-shortcut\", className)}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuSub({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {\n return <DropdownMenuPrimitive.Sub data-slot=\"dropdown-menu-sub\" {...props} />;\n}\n\nfunction DropdownMenuSubTrigger({\n className,\n inset,\n children,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {\n inset?: boolean;\n}) {\n return (\n <DropdownMenuPrimitive.SubTrigger\n data-slot=\"dropdown-menu-sub-trigger\"\n data-inset={inset}\n className={cn(\"cpk-dropdown-menu-sub-trigger\", className)}\n {...props}\n >\n {children}\n <CopilotIcon\n name=\"ChevronRight\"\n className=\"cpk-dropdown-menu-sub-trigger-icon\"\n />\n </DropdownMenuPrimitive.SubTrigger>\n );\n}\n\nfunction DropdownMenuSubContent({\n className,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {\n return (\n <DropdownMenuPrimitive.SubContent\n data-slot=\"dropdown-menu-sub-content\"\n className={cn(\"cpk-dropdown-menu-sub-content\", className)}\n {...props}\n />\n );\n}\n\nexport {\n DropdownMenu,\n DropdownMenuPortal,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuGroup,\n DropdownMenuLabel,\n DropdownMenuItem,\n DropdownMenuCheckboxItem,\n DropdownMenuRadioGroup,\n DropdownMenuRadioItem,\n DropdownMenuSeparator,\n DropdownMenuShortcut,\n DropdownMenuSub,\n DropdownMenuSubTrigger,\n DropdownMenuSubContent,\n};\n","import {\n useRef,\n useEffect,\n useImperativeHandle,\n forwardRef,\n useState,\n} from \"react\";\nimport { ɵAudioRecorder, ɵcreateWaveformRenderer } from \"@copilotkit/core\";\nimport type { ɵAudioRecorderState } from \"@copilotkit/core\";\nimport { cn } from \"../../lib/utils\";\n\n/** Finite-state machine for every recorder implementation */\nexport type AudioRecorderState = ɵAudioRecorderState;\n\n/** Error subclass so callers can `instanceof`-guard recorder failures */\nexport { ɵAudioRecorderError as AudioRecorderError } from \"@copilotkit/core\";\n\nexport interface AudioRecorderRef {\n state: AudioRecorderState;\n start: () => Promise<void>;\n stop: () => Promise<Blob>;\n dispose: () => void;\n}\n\n/**\n * Records from the microphone and draws the live level as a scrolling\n * waveform. The recording itself is `ɵAudioRecorder` from\n * `@copilotkit/core`; control it through the ref.\n */\nexport const CopilotChatAudioRecorder = forwardRef<\n AudioRecorderRef,\n React.HTMLAttributes<HTMLDivElement>\n>((props, ref) => {\n const { className, ...divProps } = props;\n const canvasRef = useRef<HTMLCanvasElement>(null);\n const [recorder] = useState(() => new ɵAudioRecorder());\n\n useEffect(() => {\n const canvas = canvasRef.current;\n if (!canvas) return;\n const waveform = ɵcreateWaveformRenderer(canvas, recorder);\n return () => waveform.dispose();\n }, [recorder]);\n\n useEffect(() => () => recorder.dispose(), [recorder]);\n\n useImperativeHandle(\n ref,\n () => ({\n get state() {\n return recorder.getSnapshot();\n },\n start: () => recorder.start(),\n stop: () => recorder.stop(),\n dispose: () => recorder.dispose(),\n }),\n [recorder],\n );\n\n return (\n <div className={cn(\"cpk-audio-recorder\", className)} {...divProps}>\n <canvas ref={canvasRef} className=\"cpk-audio-recorder-canvas\" />\n </div>\n );\n});\n\nCopilotChatAudioRecorder.displayName = \"CopilotChatAudioRecorder\";\n","import type { KeyboardEvent, ChangeEvent } from \"react\";\nimport { useLatestRef } from \"../../lib/use-latest-ref\";\nimport React, {\n useState,\n useRef,\n useEffect,\n useLayoutEffect,\n forwardRef,\n useImperativeHandle,\n useCallback,\n useMemo,\n useSyncExternalStore,\n} from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\n\nimport {\n CopilotChatDefaultLabels,\n ɵComposerController,\n ɵcomposerButtonState,\n ɵcreateComposerAutosize,\n ɵnormalizeToolsMenu,\n ɵshowsComposerDisclaimer,\n ɵsyncRecorderToMode,\n} from \"@copilotkit/core\";\nimport type { CopilotChatLabels } from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport { Button } from \"../../components/ui/button\";\nimport {\n Tooltip,\n TooltipContent,\n TooltipTrigger,\n} from \"../../components/ui/tooltip\";\nimport {\n DropdownMenu,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSub,\n DropdownMenuSubTrigger,\n DropdownMenuSubContent,\n DropdownMenuSeparator,\n} from \"../../components/ui/dropdown-menu\";\n\nimport { CopilotChatAudioRecorder } from \"./CopilotChatAudioRecorder\";\nimport type { WithSlots } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport { cn } from \"../../lib/utils\";\n\nexport type CopilotChatInputMode = \"input\" | \"transcribe\" | \"processing\";\n\nexport type ToolsMenuItem = {\n label: string;\n} & (\n | {\n action: () => void;\n items?: never;\n }\n | {\n action?: never;\n items: (ToolsMenuItem | \"-\")[];\n }\n);\n\ntype CopilotChatInputSlots = {\n textArea: typeof CopilotChatInput.TextArea;\n sendButton: typeof CopilotChatInput.SendButton;\n startTranscribeButton: typeof CopilotChatInput.StartTranscribeButton;\n cancelTranscribeButton: typeof CopilotChatInput.CancelTranscribeButton;\n finishTranscribeButton: typeof CopilotChatInput.FinishTranscribeButton;\n addMenuButton: typeof CopilotChatInput.AddMenuButton;\n audioRecorder: typeof CopilotChatAudioRecorder;\n disclaimer: typeof CopilotChatInput.Disclaimer;\n};\n\ntype CopilotChatInputRestProps = {\n mode?: CopilotChatInputMode;\n toolsMenu?: (ToolsMenuItem | \"-\")[];\n autoFocus?: boolean;\n onSubmitMessage?: (value: string) => void;\n onStop?: () => void;\n isRunning?: boolean;\n onStartTranscribe?: () => void;\n onCancelTranscribe?: () => void;\n onFinishTranscribe?: () => void;\n onFinishTranscribeWithAudio?: (audioBlob: Blob) => Promise<void>;\n onAddFile?: () => void;\n value?: string;\n onChange?: (value: string) => void;\n /** Positioning mode for the input container. Default: 'static' */\n positioning?: \"static\" | \"absolute\";\n /** Keyboard height in pixels for mobile keyboard handling */\n keyboardHeight?: number;\n /** Ref for the outer positioning container */\n containerRef?: React.Ref<HTMLDivElement>;\n /** Whether to show the disclaimer. Default: true for absolute positioning, false for static */\n showDisclaimer?: boolean;\n /**\n * Set to `true` when the input sits at the bottom of its container as a\n * flex-last-child (visible position is driven by layout, not CSS\n * positioning). Triggers reservation of bottom space for the fixed\n * CopilotKit license banner via the\n * `--copilotkit-license-banner-offset` CSS var so the two don't overlap.\n *\n * Not needed when `positioning === \"absolute\"`; that mode already pins the\n * input to the bottom and picks up the same reservation automatically.\n * Leave unset (default `false`) for inputs rendered mid-layout such as the\n * welcome screen, where the banner offset would push the input off-center.\n */\n bottomAnchored?: boolean;\n} & Omit<React.HTMLAttributes<HTMLDivElement>, \"onChange\">;\n\ntype CopilotChatInputBaseProps = WithSlots<\n CopilotChatInputSlots,\n CopilotChatInputRestProps\n>;\n\ntype CopilotChatInputChildrenArgs = CopilotChatInputBaseProps extends {\n children?: infer C;\n}\n ? C extends (props: infer P) => React.ReactNode\n ? P\n : never\n : never;\n\nexport type CopilotChatInputProps = Omit<\n CopilotChatInputBaseProps,\n \"children\"\n> & {\n children?: (props: CopilotChatInputChildrenArgs) => React.ReactNode;\n};\n\nconst SLASH_MENU_MAX_VISIBLE_ITEMS = 5;\nconst SLASH_MENU_ITEM_HEIGHT_PX = 40;\n\n/**\n * The chat composer: a text area with the add-menu, voice and send/stop\n * buttons, and a slash-command menu that lists `toolsMenu` items once the text\n * starts with \"/\".\n */\nexport function CopilotChatInput({\n mode = \"input\",\n onSubmitMessage,\n onStop,\n isRunning = false,\n onStartTranscribe,\n onCancelTranscribe,\n onFinishTranscribe,\n onFinishTranscribeWithAudio,\n onAddFile,\n onChange,\n value,\n toolsMenu,\n autoFocus = false,\n positioning = \"static\",\n keyboardHeight = 0,\n containerRef,\n showDisclaimer,\n bottomAnchored = false,\n textArea,\n sendButton,\n startTranscribeButton,\n cancelTranscribeButton,\n finishTranscribeButton,\n addMenuButton,\n audioRecorder,\n disclaimer,\n children,\n className,\n ...props\n}: CopilotChatInputProps) {\n const inputRef = useRef<HTMLTextAreaElement>(null);\n const gridRef = useRef<HTMLDivElement>(null);\n const addButtonContainerRef = useRef<HTMLDivElement>(null);\n const actionsContainerRef = useRef<HTMLDivElement>(null);\n const audioRecorderRef =\n useRef<React.ElementRef<typeof CopilotChatAudioRecorder>>(null);\n const slashMenuRef = useRef<HTMLDivElement>(null);\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n\n // Sizes the text box and picks the compact or expanded layout.\n const [autosize] = useState(() =>\n ɵcreateComposerAutosize({\n getElements: () => ({\n textarea: inputRef.current,\n grid: gridRef.current,\n start: addButtonContainerRef.current,\n actions: actionsContainerRef.current,\n }),\n }),\n );\n const layout = useSyncExternalStore(\n autosize.subscribe,\n autosize.getSnapshot,\n autosize.getSnapshot,\n );\n const isExpanded = mode === \"input\" && layout === \"expanded\";\n\n const previousModalStateRef = useRef<boolean | undefined>(undefined);\n\n // The text, controlled or not, and the slash-command menu: see core's\n // ɵComposerController.\n const onChangeRef = useLatestRef(onChange);\n const [composer] = useState(\n () =>\n new ɵComposerController<ToolsMenuItem>({\n initialValue: value ?? \"\",\n onChange: (next) => onChangeRef.current?.(next),\n }),\n );\n const {\n value: composerValue,\n slashQuery: commandQuery,\n slashCommands: filteredCommands,\n slashHighlightIndex,\n } = useSyncExternalStore(\n composer.subscribe,\n composer.getSnapshot,\n composer.getSnapshot,\n );\n // A controlled value renders at once; the controller catches up below.\n const resolvedValue = value ?? composerValue;\n\n const menu = useMemo(\n () =>\n ɵnormalizeToolsMenu<ToolsMenuItem>(\n toolsMenu,\n onAddFile\n ? { label: labels.chatInputToolbarAddButtonLabel, action: onAddFile }\n : undefined,\n ),\n [labels.chatInputToolbarAddButtonLabel, onAddFile, toolsMenu],\n );\n useLayoutEffect(() => {\n composer.setInputs({ value, mode, menu });\n }, [composer, value, mode, menu]);\n\n useEffect(() => {\n if (!autoFocus) {\n previousModalStateRef.current = config?.isModalOpen;\n return;\n }\n\n if (config?.isModalOpen && !previousModalStateRef.current) {\n inputRef.current?.focus({ preventScroll: true });\n }\n\n previousModalStateRef.current = config?.isModalOpen;\n }, [config?.isModalOpen, autoFocus]);\n\n // Recording follows the mode: it starts in transcribe mode and stops\n // when the mode changes.\n useEffect(() => {\n void ɵsyncRecorderToMode(audioRecorderRef.current, mode);\n }, [mode]);\n\n // Handlers\n const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {\n composer.setValue(e.target.value);\n };\n\n const runCommand = useCallback(\n (item: ToolsMenuItem) => {\n composer.runCommand(item);\n requestAnimationFrame(() => {\n inputRef.current?.focus();\n });\n },\n [composer],\n );\n\n const composerInput = {\n mode,\n isRunning,\n value: resolvedValue,\n canSubmit: !!onSubmitMessage,\n canStop: !!onStop,\n };\n const {\n isProcessing,\n action: buttonAction,\n disabled: buttonDisabled,\n } = ɵcomposerButtonState(composerInput);\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n // Text in the composer means send, even while a run is in flight: after\n // picking one interrupt's option the resume run still streams when the\n // user types the next prompt, and stopping it would lose the next\n // interrupt. Enter stops the run only when the composer is empty.\n const { preventDefault, action } = composer.keyDown(\n {\n key: e.key,\n shiftKey: e.shiftKey,\n isComposing: e.nativeEvent.isComposing,\n keyCode: e.keyCode,\n },\n composerInput,\n );\n if (preventDefault) e.preventDefault();\n if (action === \"command\") {\n requestAnimationFrame(() => {\n inputRef.current?.focus();\n });\n } else if (action === \"stop\") {\n onStop?.();\n } else if (action === \"send\") {\n send();\n }\n };\n\n const send = () => {\n if (!onSubmitMessage) {\n return;\n }\n // Always clears the input after sending, also when controlled:\n // onChange(\"\") tells the parent to reset its state.\n const sent = composer.submit(onSubmitMessage, { value: resolvedValue });\n if (sent) inputRef.current?.focus();\n };\n\n const BoundTextArea = renderSlot(textArea, CopilotChatInput.TextArea, {\n ref: inputRef,\n value: resolvedValue,\n onChange: handleChange,\n onKeyDown: handleKeyDown,\n autoFocus: autoFocus,\n className: isExpanded\n ? \"cpk-chat-input-textarea-expanded\"\n : \"cpk-chat-input-textarea-compact\",\n });\n\n const handleSendButtonClick = () => {\n // The send/stop button is an explicit control: when a run is in flight it\n // renders as a Stop (Square) button, so a click maps to stop regardless of\n // composer contents. The Enter key behaves differently (see handleKeyDown):\n // a non-empty composer + Enter sends a new message rather than stopping.\n if (isProcessing) {\n onStop?.();\n return;\n }\n send();\n };\n\n const BoundAudioRecorder = renderSlot(\n audioRecorder,\n CopilotChatAudioRecorder,\n {\n ref: audioRecorderRef,\n },\n );\n\n const showsStop = buttonAction === \"stop\";\n const BoundSendButton = renderSlot(sendButton, CopilotChatInput.SendButton, {\n onClick: handleSendButtonClick,\n disabled: buttonDisabled,\n \"aria-label\": showsStop\n ? labels.chatInputToolbarStopButtonLabel\n : labels.chatInputToolbarSendButtonLabel,\n children: showsStop ? (\n <CopilotIcon name=\"Square\" className=\"cpk-chat-input-stop-icon\" />\n ) : undefined,\n });\n\n const BoundStartTranscribeButton = renderSlot(\n startTranscribeButton,\n CopilotChatInput.StartTranscribeButton,\n {\n onClick: onStartTranscribe,\n },\n );\n\n const BoundCancelTranscribeButton = renderSlot(\n cancelTranscribeButton,\n CopilotChatInput.CancelTranscribeButton,\n {\n onClick: onCancelTranscribe,\n },\n );\n\n // Handler for finish button - stops recording and passes audio blob\n const handleFinishTranscribe = useCallback(async () => {\n const recorder = audioRecorderRef.current;\n if (recorder && recorder.state === \"recording\") {\n try {\n const audioBlob = await recorder.stop();\n if (onFinishTranscribeWithAudio) {\n await onFinishTranscribeWithAudio(audioBlob);\n }\n } catch (error) {\n console.error(\"Failed to stop recording:\", error);\n }\n }\n // Always call the original handler to reset mode\n onFinishTranscribe?.();\n }, [onFinishTranscribe, onFinishTranscribeWithAudio]);\n\n const BoundFinishTranscribeButton = renderSlot(\n finishTranscribeButton,\n CopilotChatInput.FinishTranscribeButton,\n {\n onClick: handleFinishTranscribe,\n },\n );\n\n const BoundAddMenuButton = renderSlot(\n addMenuButton,\n CopilotChatInput.AddMenuButton,\n {\n disabled: mode === \"transcribe\",\n onAddFile,\n toolsMenu,\n },\n );\n\n const BoundDisclaimer = renderSlot(\n disclaimer,\n CopilotChatInput.Disclaimer,\n {},\n );\n\n const shouldShowDisclaimer = ɵshowsComposerDisclaimer({\n showDisclaimer,\n positioning,\n });\n\n const handleContainerClick = (e: React.MouseEvent<HTMLDivElement>) => {\n // Don't focus if clicking on buttons or other interactive elements\n const target = e.target as HTMLElement;\n if (\n target.tagName !== \"BUTTON\" &&\n !target.closest(\"button\") &&\n inputRef.current &&\n mode === \"input\"\n ) {\n inputRef.current.focus();\n }\n };\n\n useLayoutEffect(() => {\n autosize.evaluate(resolvedValue, mode);\n }, [autosize, resolvedValue, mode]);\n\n useEffect(() => () => autosize.dispose(), [autosize]);\n\n const slashMenuVisible = commandQuery !== null;\n\n useEffect(() => {\n if (!slashMenuVisible || slashHighlightIndex < 0) {\n return;\n }\n\n const active = slashMenuRef.current?.querySelector<HTMLElement>(\n `[data-slash-index=\"${slashHighlightIndex}\"]`,\n );\n active?.scrollIntoView({ block: \"nearest\" });\n }, [slashMenuVisible, slashHighlightIndex]);\n\n const slashMenu = slashMenuVisible ? (\n <div\n data-testid=\"copilot-slash-menu\"\n role=\"listbox\"\n aria-label={labels.chatInputSlashMenuLabel}\n ref={slashMenuRef}\n className=\"cpk-chat-input-slash-menu\"\n style={{\n maxHeight: `${SLASH_MENU_MAX_VISIBLE_ITEMS * SLASH_MENU_ITEM_HEIGHT_PX}px`,\n }}\n >\n {filteredCommands.length === 0 ? (\n <div className=\"cpk-chat-input-slash-menu-empty\">\n {labels.chatInputSlashMenuEmptyText}\n </div>\n ) : (\n filteredCommands.map((item, index) => {\n const isActive = index === slashHighlightIndex;\n return (\n <button\n key={`${item.label}-${index}`}\n type=\"button\"\n role=\"option\"\n aria-selected={isActive}\n data-active={isActive ? \"true\" : undefined}\n data-slash-index={index}\n className=\"cpk-chat-input-slash-menu-item\"\n onMouseEnter={() => composer.highlight(index)}\n onMouseDown={(event) => {\n event.preventDefault();\n runCommand(item);\n }}\n >\n {item.label}\n </button>\n );\n })\n )}\n </div>\n ) : null;\n\n // The input pill (inner component)\n const inputPill = (\n <div\n data-testid=\"copilot-chat-input\"\n // copilotKitInput: V1 compatibility class for custom styling\n className=\"copilotKitInput cpk-chat-input-pill\"\n onClick={handleContainerClick}\n data-layout={isExpanded ? \"expanded\" : \"compact\"}\n >\n <div\n ref={gridRef}\n className=\"cpk-chat-input-grid\"\n data-layout={isExpanded ? \"expanded\" : \"compact\"}\n >\n <div ref={addButtonContainerRef} className=\"cpk-chat-input-start\">\n {BoundAddMenuButton}\n </div>\n <div className=\"cpk-chat-input-field\">\n {mode === \"transcribe\" ? (\n BoundAudioRecorder\n ) : mode === \"processing\" ? (\n <div className=\"cpk-chat-input-processing\">\n <CopilotIcon\n name=\"Loader2\"\n className=\"cpk-chat-input-processing-spinner\"\n />\n </div>\n ) : (\n <>\n {BoundTextArea}\n {slashMenu}\n </>\n )}\n </div>\n <div ref={actionsContainerRef} className=\"cpk-chat-input-actions\">\n {mode === \"transcribe\" ? (\n <>\n {onCancelTranscribe && BoundCancelTranscribeButton}\n {onFinishTranscribe && BoundFinishTranscribeButton}\n </>\n ) : (\n <>\n {onStartTranscribe && BoundStartTranscribeButton}\n {BoundSendButton}\n </>\n )}\n </div>\n </div>\n </div>\n );\n\n // A custom layout takes over the markup only. It returns after every hook\n // above, so the textarea keeps its measuring and auto-grow.\n if (children) {\n const childProps = {\n textArea: BoundTextArea,\n audioRecorder: BoundAudioRecorder,\n sendButton: BoundSendButton,\n startTranscribeButton: BoundStartTranscribeButton,\n cancelTranscribeButton: BoundCancelTranscribeButton,\n finishTranscribeButton: BoundFinishTranscribeButton,\n addMenuButton: BoundAddMenuButton,\n disclaimer: BoundDisclaimer,\n onSubmitMessage,\n onStop,\n isRunning,\n onStartTranscribe,\n onCancelTranscribe,\n onFinishTranscribe,\n onAddFile,\n mode,\n toolsMenu,\n autoFocus,\n positioning,\n keyboardHeight,\n showDisclaimer: shouldShowDisclaimer,\n containerRef,\n } as CopilotChatInputChildrenArgs;\n\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children(childProps)}\n </div>\n );\n }\n\n return (\n <div\n data-copilotkit\n ref={containerRef}\n className={cn(\n \"cpk-chat-input\",\n positioning === \"absolute\" && \"cpk-chat-input-absolute\",\n className,\n )}\n style={{\n transform:\n keyboardHeight > 0 ? `translateY(-${keyboardHeight}px)` : undefined,\n transition: \"transform 0.2s ease-out\",\n // Reserve room when the fixed license banner is visible so it doesn't\n // overlap the input. Applied only for bottom-anchored inputs (either\n // `positioning === \"absolute\"`, or an explicitly-flagged flex-last-child\n // input in run state). The welcome-screen input sits mid-layout and\n // must stay still when the banner is present.\n ...(positioning === \"absolute\" || bottomAnchored\n ? { paddingBottom: \"var(--copilotkit-license-banner-offset, 0px)\" }\n : {}),\n }}\n {...props}\n >\n <div className=\"cpk-chat-input-wrapper\">{inputPill}</div>\n {shouldShowDisclaimer && BoundDisclaimer}\n </div>\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace CopilotChatInput {\n /**\n * The icon-only send button. Its accessible name is\n * `labels.chatInputToolbarSendButtonLabel` unless an `aria-label` is passed;\n * the input passes `labels.chatInputToolbarStopButtonLabel` while the button\n * stops a run.\n */\n export const SendButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ className, children, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <div className=\"cpk-chat-input-send\">\n <Button\n type=\"button\"\n data-testid=\"copilot-send-button\"\n variant=\"chatInputToolbarPrimary\"\n size=\"chatInputToolbarIcon\"\n className={cn(\"cpk-chat-input-send-button\", className)}\n aria-label={labels.chatInputToolbarSendButtonLabel}\n {...props}\n >\n {children ?? (\n <CopilotIcon name=\"ArrowUp\" className=\"cpk-chat-input-send-icon\" />\n )}\n </Button>\n </div>\n );\n };\n\n /**\n * An icon-only toolbar button. `labels[labelKey]` is both its accessible\n * name and its tooltip text.\n */\n export const ToolbarButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement> & {\n icon: React.ReactNode;\n labelKey: keyof CopilotChatLabels;\n defaultClassName?: string;\n }\n > = ({ icon, labelKey, defaultClassName, className, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type=\"button\"\n variant=\"chatInputToolbarSecondary\"\n size=\"chatInputToolbarIcon\"\n className={cn(defaultClassName, className)}\n aria-label={labels[labelKey]}\n {...props}\n >\n {icon}\n </Button>\n </TooltipTrigger>\n <TooltipContent side=\"bottom\">\n <p>{labels[labelKey]}</p>\n </TooltipContent>\n </Tooltip>\n );\n };\n\n export const StartTranscribeButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = (props) => (\n <ToolbarButton\n data-testid=\"copilot-start-transcribe-button\"\n icon={<CopilotIcon name=\"Mic\" className=\"cpk-chat-input-toolbar-icon\" />}\n labelKey=\"chatInputToolbarStartTranscribeButtonLabel\"\n defaultClassName=\"cpk-chat-input-start-transcribe-button\"\n {...props}\n />\n );\n\n export const CancelTranscribeButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = (props) => (\n <ToolbarButton\n data-testid=\"copilot-cancel-transcribe-button\"\n icon={<CopilotIcon name=\"X\" className=\"cpk-chat-input-toolbar-icon\" />}\n labelKey=\"chatInputToolbarCancelTranscribeButtonLabel\"\n defaultClassName=\"cpk-chat-input-cancel-transcribe-button\"\n {...props}\n />\n );\n\n export const FinishTranscribeButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = (props) => (\n <ToolbarButton\n data-testid=\"copilot-finish-transcribe-button\"\n icon={\n <CopilotIcon name=\"Check\" className=\"cpk-chat-input-toolbar-icon\" />\n }\n labelKey=\"chatInputToolbarFinishTranscribeButtonLabel\"\n defaultClassName=\"cpk-chat-input-finish-transcribe-button\"\n {...props}\n />\n );\n\n /**\n * The \"+\" button that opens the attachment and tools menu. Its accessible\n * name and tooltip come from `labels.chatInputToolbarAddButtonLabel`.\n */\n export const AddMenuButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement> & {\n toolsMenu?: (ToolsMenuItem | \"-\")[];\n onAddFile?: () => void;\n }\n > = ({ className, toolsMenu, onAddFile, disabled, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n\n // Defer Radix UI rendering until after hydration to avoid ID mismatches\n const [mounted, setMounted] = useState(false);\n useEffect(() => setMounted(true), []);\n\n const menuItems = useMemo(\n () =>\n ɵnormalizeToolsMenu<ToolsMenuItem>(\n toolsMenu,\n onAddFile\n ? {\n label: labels.chatInputToolbarAddButtonLabel,\n action: onAddFile,\n }\n : undefined,\n ),\n [onAddFile, toolsMenu, labels.chatInputToolbarAddButtonLabel],\n );\n\n const renderMenuItems = useCallback(\n (items: (ToolsMenuItem | \"-\")[]): React.ReactNode =>\n items.map((item, index) => {\n if (item === \"-\") {\n return <DropdownMenuSeparator key={`separator-${index}`} />;\n }\n\n if (item.items && item.items.length > 0) {\n return (\n <DropdownMenuSub key={`group-${index}`}>\n <DropdownMenuSubTrigger>{item.label}</DropdownMenuSubTrigger>\n <DropdownMenuSubContent>\n {renderMenuItems(item.items)}\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n );\n }\n\n return (\n <DropdownMenuItem key={`item-${index}`} onClick={item.action}>\n {item.label}\n </DropdownMenuItem>\n );\n }),\n [],\n );\n\n const hasMenuItems = menuItems.length > 0;\n const isDisabled = disabled || !hasMenuItems;\n\n const button = (\n <Button\n type=\"button\"\n data-testid=\"copilot-add-menu-button\"\n variant=\"chatInputToolbarSecondary\"\n size=\"chatInputToolbarIcon\"\n className={cn(\"cpk-chat-input-add-menu-button\", className)}\n disabled={isDisabled}\n aria-label={labels.chatInputToolbarAddButtonLabel}\n {...props}\n >\n <CopilotIcon name=\"Plus\" className=\"cpk-chat-input-add-menu-icon\" />\n </Button>\n );\n\n // Render plain button during SSR; Radix wrappers only after hydration\n if (!mounted) return button;\n\n return (\n <DropdownMenu>\n <Tooltip>\n <TooltipTrigger asChild>\n <DropdownMenuTrigger asChild>{button}</DropdownMenuTrigger>\n </TooltipTrigger>\n <TooltipContent side=\"bottom\">\n <p className=\"cpk-chat-input-add-menu-tooltip\">\n <span>{labels.chatInputToolbarAddButtonLabel}</span>\n <code className=\"cpk-chat-input-add-menu-shortcut\">/</code>\n </p>\n </TooltipContent>\n </Tooltip>\n {hasMenuItems && (\n <DropdownMenuContent side=\"top\" align=\"start\">\n {renderMenuItems(menuItems)}\n </DropdownMenuContent>\n )}\n </DropdownMenu>\n );\n };\n\n export type TextAreaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>;\n\n export const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(\n function TextArea(\n { style, className, autoFocus, placeholder, ...props },\n ref,\n ) {\n const internalTextareaRef = useRef<HTMLTextAreaElement>(null);\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n\n useImperativeHandle(\n ref,\n () => internalTextareaRef.current as HTMLTextAreaElement,\n );\n\n useEffect(() => {\n if (autoFocus) {\n internalTextareaRef.current?.focus({ preventScroll: true });\n }\n }, [autoFocus]);\n\n return (\n <textarea\n ref={internalTextareaRef}\n data-testid=\"copilot-chat-textarea\"\n placeholder={placeholder ?? labels.chatInputPlaceholder}\n className={cn(\"cpk-chat-input-textarea\", className)}\n style={{\n overflow: \"auto\",\n resize: \"none\",\n ...style,\n }}\n rows={1}\n {...props}\n />\n );\n },\n );\n\n export const AudioRecorder = CopilotChatAudioRecorder;\n\n export const Disclaimer: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({\n className,\n ...props\n }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <div className={cn(\"cpk-chat-input-disclaimer\", className)} {...props}>\n {labels.chatDisclaimerText}\n </div>\n );\n };\n}\n\nCopilotChatInput.TextArea.displayName = \"CopilotChatInput.TextArea\";\nCopilotChatInput.SendButton.displayName = \"CopilotChatInput.SendButton\";\nCopilotChatInput.ToolbarButton.displayName = \"CopilotChatInput.ToolbarButton\";\nCopilotChatInput.StartTranscribeButton.displayName =\n \"CopilotChatInput.StartTranscribeButton\";\nCopilotChatInput.CancelTranscribeButton.displayName =\n \"CopilotChatInput.CancelTranscribeButton\";\nCopilotChatInput.FinishTranscribeButton.displayName =\n \"CopilotChatInput.FinishTranscribeButton\";\nCopilotChatInput.AddMenuButton.displayName = \"CopilotChatInput.AddMenuButton\";\nCopilotChatInput.Disclaimer.displayName = \"CopilotChatInput.Disclaimer\";\n\nexport default CopilotChatInput;\n","import React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\nimport type { ToolCall, ToolMessage } from \"@ag-ui/core\";\nimport {\n ɵbuildToolCallRenderProps,\n ɵdescribeUnrenderedToolCalls,\n ɵgetToolCallRendererNames,\n ɵresolveToolCallAgentId,\n ɵresolveToolCallRenderer,\n} from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport type { ReactToolCallRenderer } from \"../types/react-tool-call-renderer\";\n\nexport interface UseRenderToolCallProps {\n toolCall: ToolCall;\n toolMessage?: ToolMessage;\n}\n\n/**\n * Props for the memoized ToolCallRenderer component\n */\ninterface ToolCallRendererProps {\n toolCall: ToolCall;\n toolMessage?: ToolMessage;\n RenderComponent: ReactToolCallRenderer[\"render\"];\n isExecuting: boolean;\n}\n\n/**\n * Memoized component that renders a single tool call.\n * This prevents unnecessary re-renders when parent components update\n * but the tool call data hasn't changed.\n */\nconst ToolCallRenderer = React.memo(\n function ToolCallRenderer({\n toolCall,\n toolMessage,\n RenderComponent,\n isExecuting,\n }: ToolCallRendererProps) {\n // Rebuild only when the call, its result, or its executing state changes,\n // so `args` keeps a stable reference across unrelated renders.\n const props = useMemo(\n () => ɵbuildToolCallRenderProps(toolCall, toolMessage, { isExecuting }),\n [toolCall, toolMessage, isExecuting],\n );\n return <RenderComponent {...props} />;\n },\n // Custom comparison function to prevent re-renders when tool call data hasn't changed\n (prevProps, nextProps) => {\n // Compare tool call identity and content\n if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;\n if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name)\n return false;\n if (\n prevProps.toolCall.function.arguments !==\n nextProps.toolCall.function.arguments\n )\n return false;\n\n // Compare tool message (result)\n const prevResult = prevProps.toolMessage?.content;\n const nextResult = nextProps.toolMessage?.content;\n if (prevResult !== nextResult) return false;\n\n // Compare executing state\n if (prevProps.isExecuting !== nextProps.isExecuting) return false;\n\n // Compare render component reference\n if (prevProps.RenderComponent !== nextProps.RenderComponent) return false;\n\n return true;\n },\n);\n\nconst IS_DEVELOPMENT = process.env.NODE_ENV !== \"production\";\n\n/**\n * Reports tool calls that resolved to no renderer, once per tool name.\n *\n * A tool call with no renderer paints an empty message container and says\n * nothing else, so the only signal a developer gets today is a blank space in\n * the chat.\n *\n * @param toolNames - The unmatched tool names collected during render.\n * @param registered - The registry as it stands now, re-read at report time.\n * @param alreadyWarned - Names already reported, mutated to keep this once per name.\n */\nfunction warnAboutUnrenderedToolCalls(\n toolNames: readonly string[],\n registered: readonly { readonly name: string }[],\n alreadyWarned: Set<string>,\n): void {\n const fresh = toolNames.filter((name) => !alreadyWarned.has(name));\n const warnings = ɵdescribeUnrenderedToolCalls(fresh, registered);\n for (const { toolName, message } of warnings) {\n alreadyWarned.add(toolName);\n console.warn(message);\n }\n}\n\n/**\n * The tool-call renderers registered on the provider, kept current.\n * @internal\n */\nexport function useToolCallRenderers() {\n const { copilotkit } = useCopilotKit();\n // useSyncExternalStore so the value is current even if subscriptions run in\n // any order.\n return useSyncExternalStore(\n (callback) =>\n copilotkit.subscribe({ onRenderToolCallsChanged: callback }).unsubscribe,\n () => copilotkit.renderToolCalls,\n () => copilotkit.renderToolCalls,\n );\n}\n\n/**\n * Which tool names have a renderer of their own, whether a wildcard (`\"*\"`)\n * renderer is registered, and which of them opted into grouping.\n * @internal\n */\nexport function useToolCallRendererNames() {\n const renderers = useToolCallRenderers();\n return useMemo(() => ɵgetToolCallRendererNames(renderers), [renderers]);\n}\n\n/**\n * Hook that returns a function to render tool calls based on the render functions\n * defined in CopilotKitProvider.\n *\n * @returns A function that takes a tool call and optional tool message and returns the rendered component\n */\nexport function useRenderToolCall() {\n const { copilotkit, executingToolCallIds } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const agentId = ɵresolveToolCallAgentId(config?.agentId, undefined);\n\n // Development-only bookkeeping for the warning below. Collected during render\n // and reported afterwards, because the registry is not settled during render.\n const unrenderedToolNames = useRef<Set<string>>(new Set());\n const warnedToolNames = useRef<Set<string>>(new Set());\n\n const renderToolCalls = useToolCallRenderers();\n\n // `executingToolCallIds` mirrors core's set, which is filled from the first\n // `onToolExecutionStart`. A HITL call resumed on reconnect, before this\n // chat mounted, is therefore already executing on the first render.\n\n const renderToolCall = useCallback(\n ({\n toolCall,\n toolMessage,\n }: UseRenderToolCallProps): React.ReactElement | null => {\n // Rendering shows tool calls from every agent: agentId scoping only\n // affects handler execution (in core). The lookup prefers this agent's\n // renderer, then an unscoped one, then any agent's, then a wildcard.\n const renderConfig = ɵresolveToolCallRenderer(\n renderToolCalls,\n toolCall.function.name,\n agentId,\n );\n\n // No per-tool or wildcard renderer registered → render nothing.\n // Showing an unhandled tool call is opt-in: register a named/wildcard\n // renderer via useRenderTool, or call useDefaultRenderTool() for the\n // built-in card. Auto-painting a default card here would leak internal\n // tool names plus raw args/result JSON into every app's chat in\n // production, so the card must be explicitly enabled.\n if (!renderConfig) {\n if (IS_DEVELOPMENT) {\n unrenderedToolNames.current.add(toolCall.function.name);\n }\n return null;\n }\n\n const isExecuting = executingToolCallIds.has(toolCall.id);\n\n // Use the memoized ToolCallRenderer component to prevent unnecessary re-renders\n return (\n <ToolCallRenderer\n key={toolCall.id}\n toolCall={toolCall}\n toolMessage={toolMessage}\n RenderComponent={renderConfig.render}\n isExecuting={isExecuting}\n />\n );\n },\n [renderToolCalls, executingToolCallIds, agentId],\n );\n\n // Report unmatched tool calls after the commit that rendered them, deferred\n // one task past this subtree's effects. `useRenderTool` registers from an\n // effect in the component that renders the chat, and React runs child effects\n // before parent ones, so at effect time here a renderer the app does register\n // may not be in the registry yet. A timeout puts the check after every effect\n // in the tree, and `warnAboutUnrenderedToolCalls` re-reads the registry then.\n //\n // No dependency array on purpose: the misses live in a ref, so an effect that\n // only reran when `renderToolCalls` changed would never flush the common case\n // of a registry that never changes again.\n useEffect(() => {\n if (!IS_DEVELOPMENT) return;\n if (unrenderedToolNames.current.size === 0) return;\n\n const timer = setTimeout(() => {\n const pending = Array.from(unrenderedToolNames.current);\n unrenderedToolNames.current.clear();\n warnAboutUnrenderedToolCalls(\n pending,\n copilotkit.renderToolCalls,\n warnedToolNames.current,\n );\n }, 0);\n\n return () => clearTimeout(timer);\n });\n\n return renderToolCall;\n}\n","import { useEffect, useReducer, useRef } from \"react\";\nimport type { MutableRefObject } from \"react\";\n\n/** The part of a core this hook needs: something it can dispose. */\ninterface Disposable {\n dispose(): void;\n}\n\n/**\n * @internal Create a core for the provider's lifetime and dispose it on\n * unmount.\n *\n * The dispose waits one task. StrictMode (and Fast Refresh) unmount and\n * remount effects in the same commit, so the remount cancels the pending\n * dispose and the same core keeps working. When effects mount again after the\n * core was really disposed (for example an `<Activity>` that was hidden and\n * shown), the hook creates a new core and renders again: a disposed core is\n * never reused.\n *\n * `ref` holds the current core. The provider owns it, so code that runs\n * before the core exists can read `ref.current`.\n *\n * @example\n * const coreRef = useRef<CopilotKitCoreReact | null>(null);\n * const core = ɵuseOwnedCore(coreRef, () => new CopilotKitCoreReact(config));\n */\nexport function ɵuseOwnedCore<T extends Disposable>(\n ref: MutableRefObject<T | null>,\n create: () => T,\n) {\n const createRef = useRef(create);\n createRef.current = create;\n const pendingDispose = useRef<ReturnType<typeof setTimeout> | undefined>(\n undefined,\n );\n const disposedRef = useRef(false);\n const [, rerender] = useReducer((count: number) => count + 1, 0);\n\n const current = ref.current ?? create();\n ref.current = current;\n\n useEffect(() => {\n clearTimeout(pendingDispose.current);\n pendingDispose.current = undefined;\n let core = ref.current ?? createRef.current();\n if (disposedRef.current) {\n disposedRef.current = false;\n core = createRef.current();\n rerender();\n }\n ref.current = core;\n return () => {\n pendingDispose.current = setTimeout(() => {\n pendingDispose.current = undefined;\n disposedRef.current = true;\n core.dispose();\n }, 0);\n };\n }, [ref]);\n\n return current;\n}\n","","import { version as sdkVersion } from \"../../package.json\";\nimport * as React from \"react\";\nimport type { CopilotKitCore } from \"@copilotkit/core\";\nimport { ɵmountInspector } from \"@copilotkit/web-inspector/mount\";\nimport type { ɵInspectorMount } from \"@copilotkit/web-inspector/mount\";\nimport type { CopilotKitInspectorOpenRequest } from \"./CopilotKitInspectorContext\";\n\nexport interface CopilotKitInspectorProps {\n core?: CopilotKitCore | null;\n onVisibilityChange?: (visible: boolean) => void;\n openRequest?: CopilotKitInspectorOpenRequest | null;\n}\n\nexport const CopilotKitInspector: React.FC<CopilotKitInspectorProps> = ({\n core,\n openRequest,\n onVisibilityChange,\n}) => {\n const hostRef = React.useRef<HTMLSpanElement | null>(null);\n const mountRef = React.useRef<ɵInspectorMount | null>(null);\n const latestCoreRef = React.useRef(core ?? null);\n const visibilityCallbackRef = React.useRef(onVisibilityChange);\n\n latestCoreRef.current = core ?? null;\n visibilityCallbackRef.current = onVisibilityChange;\n\n React.useEffect(() => {\n const host = hostRef.current;\n if (!host) return;\n // The web component loads only on the client to keep SSR output stable.\n const mount = ɵmountInspector(host, latestCoreRef.current, {\n load: () => import(\"@copilotkit/web-inspector\"),\n notificationContext: {\n development: process.env.NODE_ENV === \"development\",\n framework: \"react\",\n sdkVersion,\n },\n });\n mount.onVisibility((visible) => visibilityCallbackRef.current?.(visible));\n mountRef.current = mount;\n return () => {\n mount.dispose();\n if (mountRef.current === mount) mountRef.current = null;\n };\n }, []);\n\n React.useEffect(() => {\n mountRef.current?.setCore(core ?? null);\n }, [core]);\n\n // Runs after the mount effect, so a request present at mount is queued\n // until the element loads.\n React.useEffect(() => {\n if (openRequest) mountRef.current?.open(openRequest);\n }, [openRequest]);\n\n return <span ref={hostRef} style={{ display: \"contents\" }} />;\n};\n\nCopilotKitInspector.displayName = \"CopilotKitInspector\";\n","\"use client\";\n\nimport * as React from \"react\";\n\nexport type CopilotKitInspectorOpenRequest = {\n messageId: string;\n threadId?: string;\n agentId?: string;\n};\n\ntype CopilotKitInspectorContextValue = {\n /** Explicit provider preference, which takes priority over chat preferences. */\n providerEnableInspector?: boolean;\n isInspectorEnabled: boolean;\n openInspector: (request: CopilotKitInspectorOpenRequest) => void;\n};\n\nconst CopilotKitInspectorContext =\n React.createContext<CopilotKitInspectorContextValue>({\n isInspectorEnabled: false,\n openInspector: () => undefined,\n });\n\nexport const CopilotKitInspectorContextProvider =\n CopilotKitInspectorContext.Provider;\n\nexport function useCopilotKitInspector(): CopilotKitInspectorContextValue {\n return React.useContext(CopilotKitInspectorContext);\n}\n","import { useEffect } from \"react\";\nimport {\n CopilotChatDefaultLabels,\n ɵINLINE_FEATURE_WARNING_STYLE,\n ɵLICENSE_BANNER_STYLE,\n ɵgetInlineFeatureWarningSpec,\n ɵgetLicenseBannerSpec,\n ɵreserveLicenseBannerOffset,\n} from \"@copilotkit/core\";\nimport type {\n ɵLicenseBannerDetails,\n ɵLicenseBannerType,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\n\n/** The chat labels in effect, or the default ones outside a chat. */\nfunction useLabels() {\n return useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;\n}\n\ninterface LicenseWarningBannerProps extends ɵLicenseBannerDetails {\n type: ɵLicenseBannerType;\n onDismiss?: () => void;\n}\n\n/**\n * The fixed license banner. Core's `ɵgetLicenseBannerSpec` picks its text,\n * link, and severity; this component renders them.\n */\nexport function LicenseWarningBanner({\n type,\n onDismiss,\n ...details\n}: LicenseWarningBannerProps) {\n const spec = ɵgetLicenseBannerSpec(type, useLabels(), details);\n\n // Publish the banner's reserved bottom offset so the chat input can lift\n // itself above it via padding-bottom: var(--copilotkit-license-banner-offset).\n useEffect(() => ɵreserveLicenseBannerOffset(), []);\n\n return (\n <div\n style={{\n ...ɵLICENSE_BANNER_STYLE.base,\n ...ɵLICENSE_BANNER_STYLE.severity[spec.severity],\n }}\n >\n <span>{spec.message}</span>\n <div style={ɵLICENSE_BANNER_STYLE.actions}>\n <a\n href={spec.actionUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n style={ɵLICENSE_BANNER_STYLE.link}\n >\n {spec.actionLabel}\n </a>\n {onDismiss && (\n <button onClick={onDismiss} style={ɵLICENSE_BANNER_STYLE.dismiss}>\n ×\n </button>\n )}\n </div>\n </div>\n );\n}\n\nexport function InlineFeatureWarning({ featureName }: { featureName: string }) {\n const spec = ɵgetInlineFeatureWarningSpec(featureName, useLabels());\n return (\n <div style={ɵINLINE_FEATURE_WARNING_STYLE.container}>\n {spec.message}{\" \"}\n <a\n href={spec.actionUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n style={ɵINLINE_FEATURE_WARNING_STYLE.link}\n >\n {spec.actionLabel}\n </a>\n </div>\n );\n}\n","\"use client\";\n\nimport React, { useEffect, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport { useCopilotKit } from \"../providers/CopilotKitProvider\";\n\n// The app<->host protocol (ext-apps AppBridge, sandbox proxy, request queue,\n// ui/message + open-link handlers, tool input/result) lives in the shared,\n// framework-agnostic package. This file is now a THIN React adapter over it: it\n// owns the iframe (create/mount/size/remove) and wires the session's reactive\n// hooks to React state; all protocol logic is `bindMcpApp`.\n//\n// The lightweight activity surface (type + content schema + follow-up runner)\n// is re-exported from the package's bridge-free `/activity` entry, so importing\n// it (for the activity registry) does NOT pull the ext-apps bundle. The bridge\n// itself is loaded lazily via a dynamic `import(\"@copilotkit/mcp-apps-renderer\")`\n// inside the effect, so a `<CopilotKitProvider>` app only pays for it when it actually\n// renders an MCP App.\nexport {\n MCPAppsActivityType,\n MCPAppsActivityContentSchema,\n ɵrunMcpFollowUp,\n} from \"@copilotkit/mcp-apps-renderer/activity\";\nexport type {\n MCPAppsActivityContent,\n ɵMcpFollowUpHost,\n} from \"@copilotkit/mcp-apps-renderer/activity\";\n\nimport type { MCPAppsActivityContent } from \"@copilotkit/mcp-apps-renderer/activity\";\nimport { ɵMcpAppHost } from \"@copilotkit/mcp-apps-renderer/activity\";\n\n/**\n * Props for the activity renderer component\n */\ninterface MCPAppsActivityRendererProps {\n activityType: string;\n content: MCPAppsActivityContent;\n message: unknown; // ActivityMessage from @ag-ui/core\n agent: AbstractAgent | undefined;\n /**\n * Restore `allow-same-origin` on the sandbox. Unsafe: the widget runs with\n * the host page's origin. Set via `mcpApps.allowSameOriginFallback` on\n * `CopilotKitProvider`.\n */\n allowSameOriginFallback?: boolean;\n}\n\n/**\n * MCP Apps Extension Activity Renderer\n *\n * Renders MCP Apps UI in a sandboxed iframe with full protocol support. The\n * shared `ɵMcpAppHost` owns the iframe, its size and its state, and binds the\n * protocol session (`bindMcpApp`, loaded lazily); this component only draws\n * the state around it.\n */\nexport const MCPAppsActivityRenderer: React.FC<MCPAppsActivityRendererProps> =\n function MCPAppsActivityRenderer({\n content,\n message,\n agent,\n allowSameOriginFallback,\n }) {\n const { copilotkit } = useCopilotKit();\n const containerRef = useRef<HTMLDivElement>(null);\n // The activity message id: the session follows it in the agent's store.\n const messageId = (message as { id?: string } | undefined)?.id;\n\n // A new host or sandbox setting needs a new host object.\n const app = useMemo(\n () =>\n new ɵMcpAppHost({\n host: copilotkit,\n sessionOptions: { allowSameOriginFallback },\n importRenderer: () => import(\"@copilotkit/mcp-apps-renderer\"),\n }),\n [copilotkit, allowSameOriginFallback],\n );\n\n const state = useSyncExternalStore(\n app.subscribe,\n app.getState,\n app.getState,\n );\n\n useEffect(() => {\n app.setAgent(agent);\n app.setMessageId(messageId);\n }, [app, agent, messageId]);\n useEffect(() => {\n app.setContent(content);\n }, [app, content]);\n useEffect(() => {\n app.setContainer(containerRef.current);\n return () => app.destroy();\n }, [app]);\n\n // prefersBorder: true = border and background; otherwise none.\n const borderStyle = state.prefersBorder\n ? {\n borderRadius: \"8px\",\n backgroundColor: \"#f9f9f9\",\n border: \"1px solid #e0e0e0\",\n }\n : {};\n const shownError = state.error ?? state.contentError;\n\n return (\n <div\n ref={containerRef}\n style={{\n width: \"100%\",\n height: state.size.height ? `${state.size.height}px` : \"auto\",\n minHeight: \"100px\",\n overflow: \"hidden\",\n position: \"relative\",\n ...borderStyle,\n }}\n >\n {state.loading && (\n <div style={{ padding: \"1rem\", color: \"#666\" }}>Loading...</div>\n )}\n {shownError && (\n <div style={{ color: \"red\", padding: \"1rem\" }}>\n Error: {shownError}\n </div>\n )}\n </div>\n );\n };\n","import { createContext, useContext } from \"react\";\nimport type { SandboxFunction } from \"../types/sandbox-function\";\n\nexport const SandboxFunctionsContext = createContext<\n readonly SandboxFunction[]\n>([]);\n\nexport function useSandboxFunctions(): readonly SandboxFunction[] {\n return useContext(SandboxFunctionsContext);\n}\n","\"use client\";\n\nimport React, {\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n OPEN_GENERATIVE_UI_ACTIVITY_TYPE,\n ToolCallStatus,\n ɵGENERATE_SANDBOXED_UI_ARGS_SCHEMA,\n ɵOPEN_GENERATIVE_UI_CONTENT_SCHEMA,\n ɵOpenGenerativeUIController,\n ɵPlaceholderCycler,\n} from \"@copilotkit/core\";\nimport type {\n OpenGenerativeUIContent,\n GenerateSandboxedUiArgs,\n} from \"@copilotkit/core\";\nimport { useSandboxFunctions } from \"../providers/SandboxFunctionsContext\";\n\nexport type { OpenGenerativeUIContent, GenerateSandboxedUiArgs };\n\nexport const OpenGenerativeUIActivityType = OPEN_GENERATIVE_UI_ACTIVITY_TYPE;\n\n/** Validates Open Generative UI activity content (shared with Vue and Angular). */\nexport const OpenGenerativeUIContentSchema = ɵOPEN_GENERATIVE_UI_CONTENT_SCHEMA;\n\n/**\n * Schema for the generateSandboxedUi tool call arguments (shared with Vue and\n * Angular). It also describes the arguments to the model as JSON Schema.\n */\nexport const GenerateSandboxedUiArgsSchema = ɵGENERATE_SANDBOXED_UI_ARGS_SCHEMA;\n\ninterface OpenGenerativeUIActivityRendererProps {\n activityType: string;\n content: OpenGenerativeUIContent;\n message: unknown;\n agent: unknown;\n}\n\n/**\n * Renders an Open Generative UI activity. The core controller throttles the\n * content and runs the websandbox iframes inside the container div.\n */\nexport const OpenGenerativeUIActivityRenderer: React.FC<OpenGenerativeUIActivityRendererProps> =\n function OpenGenerativeUIActivityRenderer({ content }) {\n const [controller] = useState(() => {\n const created = new ɵOpenGenerativeUIController();\n created.setContent(content);\n return created;\n });\n const sandboxFunctions = useSandboxFunctions();\n const containerRef = useRef<HTMLDivElement>(null);\n const state = useSyncExternalStore(\n controller.subscribe,\n controller.getState,\n controller.getState,\n );\n\n useEffect(() => {\n controller.setSandboxFunctions(sandboxFunctions);\n }, [controller, sandboxFunctions]);\n\n useEffect(() => {\n controller.setContent(content);\n }, [controller, content]);\n\n useEffect(() => {\n controller.setHost(containerRef.current);\n return () => controller.destroy();\n }, [controller]);\n\n const hasVisibleSandbox = state.phase !== \"placeholder\";\n\n return (\n <div\n ref={containerRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: `${state.height}px`,\n borderRadius: \"8px\",\n backgroundColor: hasVisibleSandbox ? \"transparent\" : \"#f5f5f5\",\n border: hasVisibleSandbox ? \"none\" : \"1px solid #e0e0e0\",\n display: hasVisibleSandbox ? \"block\" : \"flex\",\n alignItems: hasVisibleSandbox ? undefined : \"center\",\n justifyContent: hasVisibleSandbox ? undefined : \"center\",\n overflow: \"hidden\",\n }}\n >\n {state.showOverlay && (\n <div\n style={{\n position: \"absolute\",\n inset: 0,\n zIndex: 10,\n pointerEvents: \"all\",\n backgroundColor: \"rgba(255, 255, 255, 0.5)\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n }}\n >\n {state.showSpinner && (\n <svg\n width=\"48\"\n height=\"48\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n style={{ animation: \"ck-spin 1s linear infinite\" }}\n >\n <circle\n cx=\"12\"\n cy=\"12\"\n r=\"10\"\n stroke=\"#e0e0e0\"\n strokeWidth=\"3\"\n />\n <path\n d=\"M12 2a10 10 0 0 1 10 10\"\n stroke=\"#999\"\n strokeWidth=\"3\"\n strokeLinecap=\"round\"\n />\n </svg>\n )}\n <style>{`@keyframes ck-spin { to { transform: rotate(360deg) } }`}</style>\n </div>\n )}\n </div>\n );\n };\n\n/**\n * Frontend tool renderer for generateSandboxedUi.\n * Displays placeholder messages while the UI is being generated.\n */\nexport const OpenGenerativeUIToolRenderer: React.FC<\n | {\n name: string;\n args: Partial<GenerateSandboxedUiArgs>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n }\n | {\n name: string;\n args: GenerateSandboxedUiArgs;\n status: ToolCallStatus.Executing;\n result: undefined;\n }\n | {\n name: string;\n args: GenerateSandboxedUiArgs;\n status: ToolCallStatus.Complete;\n result: string;\n }\n> = function OpenGenerativeUIToolRenderer(props) {\n const [cycler] = useState(() => new ɵPlaceholderCycler());\n const { message } = useSyncExternalStore(\n cycler.subscribe,\n cycler.getSnapshot,\n cycler.getSnapshot,\n );\n const isComplete = props.status === ToolCallStatus.Complete;\n\n useEffect(() => {\n cycler.update(props.args.placeholderMessages, isComplete);\n }, [cycler, props.args.placeholderMessages, isComplete]);\n useEffect(() => () => cycler.dispose(), [cycler]);\n\n // Before the first effect, show what the cycler starts with: the newest message.\n const shown =\n message ??\n (isComplete ? undefined : props.args.placeholderMessages?.at(-1));\n // Nothing once complete — the activity renderer handles the UI.\n if (shown === undefined) return null;\n\n return (\n <div\n style={{\n padding: \"8px 12px\",\n color: \"#999\",\n fontSize: \"14px\",\n }}\n >\n {shown}\n </div>\n );\n};\n","import { useEffect, useMemo, useState } from \"react\";\nimport { ɵresolveGenerativeUIDefault } from \"@copilotkit/core\";\nimport type { GenerativeUI } from \"./catalog\";\nimport type { GenerativeUIConfig } from \"./runtime-context\";\n\n/**\n * The standard UI, loaded once on first use. It is a dynamic import so the\n * standard components (chart, map, media, ...) stay out of the main entry:\n * an app that does not use generative UI never downloads them.\n */\nlet standardUIPromise: Promise<GenerativeUI> | undefined;\n\nfunction loadStandardUI(): Promise<GenerativeUI> {\n if (!standardUIPromise) {\n standardUIPromise = import(\"./standard\").then(\n (module) => module.standardUI,\n );\n // A failed load is tried again on the next use.\n standardUIPromise.catch(() => {\n standardUIPromise = undefined;\n });\n }\n return standardUIPromise;\n}\n\n/** The runtime info that decides the fallback. */\nexport interface StandardUIFallbackRuntimeInfo {\n generativeUIEnabled: boolean;\n generativeUIAgents: string[] | undefined;\n}\n\n/**\n * The generative UI config of the provider. That is the `generativeUI` prop\n * when it has a `ui`. Otherwise, when the runtime turns generative UI on, it\n * is the standard UI for the agents of the runtime, once the standard UI has\n * loaded, with the other options of the prop (such as `map` or `theme`).\n * `undefined` while generative UI is off, or still loading.\n */\nexport function useStandardUIFallback(\n generativeUI: GenerativeUIConfig | undefined,\n runtimeInfo: StandardUIFallbackRuntimeInfo | null,\n): GenerativeUIConfig | undefined {\n const fallback = ɵresolveGenerativeUIDefault({\n runtimeEnabled: runtimeInfo?.generativeUIEnabled ?? false,\n runtimeAgents: runtimeInfo?.generativeUIAgents,\n hasUI: !!generativeUI?.ui,\n });\n const active = fallback.active;\n const agentIds = fallback.active ? fallback.agentIds : undefined;\n\n const [standardUI, setStandardUI] = useState<GenerativeUI>();\n useEffect(() => {\n if (!active || standardUI) return;\n let cancelled = false;\n loadStandardUI().then(\n (ui) => {\n if (!cancelled) setStandardUI(ui);\n },\n (error: unknown) => {\n console.error(\n \"[generativeUI] could not load the standard UI for the runtime's generative UI:\",\n error,\n );\n },\n );\n return () => {\n cancelled = true;\n };\n }, [active, standardUI]);\n\n return useMemo(() => {\n if (generativeUI?.ui) return generativeUI;\n if (!active || !standardUI) return undefined;\n return {\n ...generativeUI,\n ui: standardUI,\n agentIds: generativeUI?.agentIds ?? agentIds,\n };\n }, [generativeUI, active, standardUI, agentIds]);\n}\n","import React from \"react\";\nimport type {\n ReactActivityMessageRenderer,\n ReactToolCallRenderer,\n} from \"../types\";\nimport type { ReactCustomMessageRenderer } from \"../types/react-custom-message-renderer\";\nimport { CopilotKitCore, ɵRendererRegistry } from \"@copilotkit/core\";\nimport type {\n CopilotKitCoreConfig,\n CopilotKitCoreSubscriber,\n CopilotKitCoreSubscription,\n ɵRendererKind,\n} from \"@copilotkit/core\";\n\nexport interface CopilotKitCoreReactConfig extends CopilotKitCoreConfig {\n // Add any additional configuration properties specific to the React implementation\n renderToolCalls?: ReactToolCallRenderer<any>[];\n renderActivityMessages?: ReactActivityMessageRenderer<any>[];\n\n // Add custom message renderers\n renderCustomMessages?: ReactCustomMessageRenderer[];\n}\n\nexport interface CopilotKitCoreReactSubscriber extends CopilotKitCoreSubscriber {\n onRenderToolCallsChanged?: (event: {\n copilotkit: CopilotKitCore;\n renderToolCalls: readonly ReactToolCallRenderer<any>[];\n }) => void | Promise<void>;\n onRenderActivityMessagesChanged?: (event: {\n copilotkit: CopilotKitCore;\n renderActivityMessages: readonly ReactActivityMessageRenderer<any>[];\n }) => void | Promise<void>;\n onRenderCustomMessagesChanged?: (event: {\n copilotkit: CopilotKitCore;\n renderCustomMessages: readonly ReactCustomMessageRenderer[];\n }) => void | Promise<void>;\n onInterruptElementChanged?: (event: {\n copilotkit: CopilotKitCore;\n interruptElement: React.ReactElement | null;\n }) => void | Promise<void>;\n}\n\n/**\n * Wait for pending React state updates before the follow-up agent run.\n *\n * When a frontend tool handler calls setState(), React 18 batches the update\n * and schedules a commit via its internal scheduler (MessageChannel). The\n * useAgentContext hook registers context via useLayoutEffect, which runs\n * synchronously after React commits that batch.\n *\n * Awaiting a zero-delay timeout yields to the macrotask queue. React's\n * MessageChannel task runs first, committing the pending state and running\n * useLayoutEffect (which updates the context store). The follow-up runAgent\n * call then reads fresh context.\n */\nfunction waitForReactCommit() {\n return new Promise<void>((resolve) => setTimeout(resolve, 0));\n}\n\nexport class CopilotKitCoreReact extends CopilotKitCore {\n private readonly _renderers: ɵRendererRegistry<\n ReactToolCallRenderer<any>,\n ReactActivityMessageRenderer<any>,\n ReactCustomMessageRenderer\n >;\n\n constructor(config: CopilotKitCoreReactConfig) {\n super({\n ...config,\n ɵwaitForFrameworkUpdates: waitForReactCommit,\n });\n this._renderers = new ɵRendererRegistry({\n toolCalls: config.renderToolCalls,\n activity: config.renderActivityMessages,\n custom: config.renderCustomMessages,\n });\n this._renderers.subscribe((kind) => this.notifyRenderersChanged(kind));\n // The element lives in core's generic interrupt slot; keep the React\n // subscriber event for existing listeners.\n this.ɵsubscribeToInterruptPayload(() => {\n void this.notifySubscribers((subscriber) => {\n const reactSubscriber = subscriber as CopilotKitCoreReactSubscriber;\n return reactSubscriber.onInterruptElementChanged?.({\n copilotkit: this,\n interruptElement: this.interruptElement,\n });\n }, \"Subscriber onInterruptElementChanged error:\");\n });\n }\n\n get renderCustomMessages() {\n return this._renderers.custom;\n }\n\n get renderActivityMessages() {\n return this._renderers.activity;\n }\n\n /**\n * Prop, hook and built-in renderers merged. For one name and agentId, a\n * hook renderer wins over a prop one, and both win over a built-in one.\n */\n get renderToolCalls() {\n return this._renderers.toolCalls;\n }\n\n setRenderActivityMessages(\n renderers: ReactActivityMessageRenderer<any>[],\n ): void {\n this._renderers.setActivity(renderers);\n }\n\n setRenderCustomMessages(renderers: ReactCustomMessageRenderer[]): void {\n this._renderers.setCustom(renderers);\n }\n\n setRenderToolCalls(renderToolCalls: ReactToolCallRenderer<any>[]): void {\n this._renderers.setPropToolCalls(renderToolCalls);\n }\n\n addHookRenderToolCall(entry: ReactToolCallRenderer<any>): void {\n this._renderers.addHookToolCall(entry);\n }\n\n removeHookRenderToolCall(name: string, agentId?: string): void {\n this._renderers.removeHookToolCall(name, agentId);\n }\n\n /**\n * @internal Add a renderer for a tool a built-in feature owns\n * (generative UI). Prop and hook renderers with the same name and agent win\n * over it, and `setRenderToolCalls` never removes it.\n *\n * @returns A function that removes the renderer.\n */\n ɵaddBuiltInRenderToolCall(entry: ReactToolCallRenderer): () => void {\n return this._renderers.addBuiltInToolCall(entry);\n }\n\n private notifyRenderersChanged(kind: ɵRendererKind): void {\n void this.notifySubscribers((subscriber) => {\n const reactSubscriber = subscriber as CopilotKitCoreReactSubscriber;\n switch (kind) {\n case \"toolCalls\":\n return reactSubscriber.onRenderToolCallsChanged?.({\n copilotkit: this,\n renderToolCalls: this.renderToolCalls,\n });\n case \"activity\":\n return reactSubscriber.onRenderActivityMessagesChanged?.({\n copilotkit: this,\n renderActivityMessages: this.renderActivityMessages,\n });\n case \"custom\":\n return reactSubscriber.onRenderCustomMessagesChanged?.({\n copilotkit: this,\n renderCustomMessages: this.renderCustomMessages,\n });\n }\n }, `Subscriber renderer change (${kind}) error:`);\n }\n\n get interruptElement(): React.ReactElement | null {\n return this.ɵinterruptPayload as React.ReactElement | null;\n }\n\n setInterruptElement(element: React.ReactElement | null): void {\n this.ɵsetInterruptPayload(element);\n }\n\n // Override to accept React-specific subscriber type\n subscribe(\n subscriber: CopilotKitCoreReactSubscriber,\n ): CopilotKitCoreSubscription {\n return super.subscribe(subscriber);\n }\n}\n","import React, { createContext, useContext, version } from \"react\";\nimport { stylesheet } from \"@copilotkit/core/styles\";\n\ninterface StyleOptions {\n /** CSP nonce for the `<style>` tag. */\n nonce?: string;\n /** `false` when the app loads `@copilotkit/core/styles.css` itself. */\n inject: boolean;\n}\n\nconst StyleOptionsContext = createContext<StyleOptions>({ inject: true });\n\n/** React 19 moves a `<style precedence>` into `<head>` and keeps one copy. */\nconst hoistsStyles = Number.parseInt(version, 10) >= 19;\n\n/** Passes the provider's style options to `<CopilotKitStyles>`. */\nexport const CopilotStyleOptionsProvider = StyleOptionsContext.Provider;\n\n/**\n * Renders the CSS for CopilotKit's UI, so apps never import a stylesheet.\n * `CopilotChat` (and so `CopilotPopup` and `CopilotSidebar`) renders it for\n * you. Render it yourself only when you build a layout from the chat parts\n * without `CopilotChat`.\n *\n * React 19 moves the tag into `<head>` and keeps one copy, including in the\n * server HTML. React 18 renders it in place, one copy per `CopilotChat`.\n * Each copy holds the same CSS, so a second copy changes nothing.\n *\n * With a CSP nonce the tag always renders in place. React only adds a nonce to\n * a hoisted style when the app renders with `nonce: { style }`, and Next.js\n * passes a plain string, so a hoisted tag would be blocked.\n *\n * Renders nothing when `CopilotKitProvider` has `injectStyles={false}`.\n */\nexport function CopilotKitStyles() {\n const { nonce, inject } = useContext(StyleOptionsContext);\n if (!inject) {\n return null;\n }\n if (nonce || !hoistsStyles) {\n // `dangerouslySetInnerHTML`, because React 18's server escapes `>` and\n // quotes in style text, which breaks the CSS in the server HTML.\n return (\n <style nonce={nonce} dangerouslySetInnerHTML={{ __html: stylesheet }} />\n );\n }\n return (\n <style href=\"copilotkit\" precedence=\"copilotkit\">\n {stylesheet}\n </style>\n );\n}\n","\"use client\";\n\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type {\n ɵCopilotKitProviderBaseOptions,\n ɵRuntimeInfo,\n ɵStableArrayProp,\n} from \"@copilotkit/core\";\nimport {\n ɵLearningAutoStarter,\n ɵassembleActivityRenderers,\n ɵassembleHumanInTheLoop,\n ɵassembleProviderToolRenderers,\n ɵassembleProviderTools,\n ɵhitlRenderProps,\n ɵstableArrayPropWarning,\n ɵtoLearningConfig,\n} from \"@copilotkit/core\";\nimport type React from \"react\";\nimport {\n createElement,\n useMemo,\n useCallback,\n useEffect,\n useLayoutEffect,\n useReducer,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { ɵuseOwnedCore } from \"./use-owned-core\";\nimport type { ReactNode } from \"react\";\n// Context extracted to ../context.ts for cross-platform reuse (React Native)\nimport {\n CopilotKitAgentIdContext,\n CopilotKitContext,\n LicenseContext,\n} from \"../context\";\nimport type { CopilotKitContextValue } from \"../context\";\nexport type { CopilotKitContextValue } from \"../context\";\nexport { CopilotKitContext, useLicenseContext } from \"../context\";\nimport { CopilotKitInspector } from \"../components/CopilotKitInspector\";\nimport { CopilotKitInspectorContextProvider } from \"../components/CopilotKitInspectorContext\";\nimport type { CopilotKitInspectorOpenRequest } from \"../components/CopilotKitInspectorContext\";\nimport { LicenseWarningBanner } from \"../components/license-warning-banner\";\nimport {\n ɵaddOpenGenerativeUIContexts,\n ɵcreateOpenGenerativeUITool,\n ɵisOpenGenerativeUIActive,\n ɵpublicKeyHeaderDefaults,\n ɵreportProviderConfigDiagnostics,\n ɵresolveLicenseState,\n ɵresolveProviderConfig,\n ɵwithHeaderDefaults,\n} from \"@copilotkit/core\";\nimport {\n MCPAppsActivityContentSchema,\n MCPAppsActivityRenderer,\n MCPAppsActivityType,\n} from \"../components/MCPAppsActivityRenderer\";\nimport {\n OpenGenerativeUIActivityType,\n OpenGenerativeUIContentSchema,\n OpenGenerativeUIActivityRenderer,\n OpenGenerativeUIToolRenderer,\n} from \"../components/OpenGenerativeUIRenderer\";\nimport { useGenerativeUIRoot } from \"../generative-ui/use-generative-ui-root\";\nimport { useStandardUIFallback } from \"../generative-ui/use-standard-ui-fallback\";\nimport type { GenerativeUIConfig } from \"../generative-ui/runtime-context\";\nimport {\n createGenerativeUIActivityRenderer,\n createGenerativeUIFunctionCallActivityRenderer,\n GenerativeUIToolCallRenderer,\n} from \"../generative-ui/chat\";\nimport { GenerativeUIRuntimeContext } from \"../generative-ui/runtime-context\";\nimport { CopilotKitCoreReact } from \"../lib/react-core\";\nimport type {\n ReactActivityMessageRenderer,\n ReactToolCallRenderer,\n} from \"../types\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport type { ReactHumanInTheLoop } from \"../types/human-in-the-loop\";\nimport type { ReactCustomMessageRenderer } from \"../types/react-custom-message-renderer\";\nimport type { SandboxFunction } from \"../types/sandbox-function\";\nimport { SandboxFunctionsContext } from \"./SandboxFunctionsContext\";\nimport { MarkdownRendererProvider } from \"./MarkdownRendererContext\";\nimport type { MarkdownRenderer } from \"./MarkdownRendererContext\";\nimport { CopilotStyleOptionsProvider } from \"../styles/copilot-kit-styles\";\nimport { shouldEnableInspector } from \"@copilotkit/shared\";\n\n// Stable frozen defaults keep provider effects from re-running just because a\n// caller omitted an object prop on a rerender.\nconst EMPTY_HEADERS: Readonly<Record<string, string>> = Object.freeze({});\nconst EMPTY_PROPERTIES: Readonly<Record<string, unknown>> = Object.freeze({});\nconst EMPTY_AGENTS: Readonly<Record<string, AbstractAgent>> = Object.freeze({});\n\n// Provider props interface\n/** The MCP Apps renderer with `mcpApps.allowSameOriginFallback` applied. */\nconst SameOriginMCPAppsActivityRenderer: typeof MCPAppsActivityRenderer = (\n props,\n) => <MCPAppsActivityRenderer {...props} allowSameOriginFallback />;\n\nexport interface CopilotKitProviderProps extends ɵCopilotKitProviderBaseOptions {\n children: ReactNode;\n /**\n * CSP nonce for the `<style>` tags CopilotKit adds. Set it when your\n * Content-Security-Policy limits `style-src` to a nonce.\n */\n nonce?: string;\n /**\n * Set to `false` when you import `@copilotkit/core/styles.css` yourself, so\n * browsers cache the CSS as a file. CopilotKit then adds no `<style>` tag.\n * @default true\n */\n injectStyles?: boolean;\n /**\n * The id of the agent every `<CopilotChat>` under this provider talks to,\n * unless a chat names its own with the `agentId` prop.\n *\n * This is the v2 replacement for the v1 `<CopilotKit agent=\"...\">` prop. Set\n * it here and you never need the v1 compatibility provider just to name an\n * agent. Defaults to `\"default\"`.\n */\n agentId?: string;\n renderToolCalls?: ReactToolCallRenderer<any>[];\n renderActivityMessages?: ReactActivityMessageRenderer<any>[];\n renderCustomMessages?: ReactCustomMessageRenderer[];\n /**\n * Global markdown renderer used by assistant/reasoning messages. Overrides the\n * built-in basic renderer. A per-message `markdownRenderer` slot still wins\n * over this. Plug in your own (e.g. a streamdown wrapper) to restore rich\n * rendering — CopilotKit ships only the basic renderer.\n */\n markdownRenderer?: MarkdownRenderer;\n frontendTools?: ReactFrontendTool[];\n humanInTheLoop?: ReactHumanInTheLoop[];\n /**\n * Configuration for OpenGenerativeUI — sandboxed UI generated by the LLM.\n *\n * @example\n * ```tsx\n * <CopilotKitProvider\n * runtimeUrl=\"/api/copilotkit\"\n * openGenerativeUI={{\n * sandboxFunctions: [{ name: \"addToCart\", description: \"…\", parameters: schema, handler: fn }],\n * }}\n * >\n * ```\n */\n openGenerativeUI?: {\n /**\n * Functions made available inside sandboxed iframes.\n * Each function is described to the LLM via agent context and exposed\n * via websandbox's `localApi`.\n *\n * Inside the iframe, call them with:\n * ```js\n * await Websandbox.connection.remote.<functionName>(args)\n * ```\n */\n sandboxFunctions?: SandboxFunction[];\n /**\n * Design guidelines injected as agent context for the `generateSandboxedUi` tool.\n * Override this to control the visual style of generated UIs.\n *\n * A sensible default is provided if omitted.\n */\n designSkill?: string;\n };\n /**\n * Disable the CopilotKit Inspector in development.\n * The Inspector is enabled by default in development browser builds on\n * localhost/loopback. It is always disabled on remote hosts, in production,\n * and during server rendering. Temporary Inspector hides also hide its\n * message shortcuts.\n * An explicit value takes priority over CopilotChat's inspectorTools prop.\n */\n enableInspector?: boolean;\n /**\n * Whether to automatically mount the Intelligence indicator in chat.\n *\n * @default true\n */\n showIntelligenceIndicator?: boolean;\n /**\n * Experimental. Native generative UI: `generativeUI={{ ui }}`, where `ui`\n * comes from `createGenerativeUI`. The agent renders your React components\n * into chat or into `<GenerativeUISurface id>` mounts. Props that match\n * the declared state and events that match the declared functions are\n * bound by the library, and the model does not see them.\n *\n * When it is left out and the runtime turns generative UI on, the provider\n * uses `standardUI` for the agents the runtime names. The standard\n * components load on demand, the first time the runtime turns it on.\n */\n generativeUI?: GenerativeUIConfig;\n /**\n * @deprecated Use `generativeUI`. The provider passes `a2ui` on to\n * `generativeUI`: `a2ui={{ catalog, theme }}` works as\n * `generativeUI={{ ui: catalog, theme }}`. When both props set the same\n * option, `generativeUI` wins. The other v0.9 options (`onAction`,\n * `loadingComponent`, `recovery`, `includeSchema`) have no 2.0 equivalent.\n * See https://docs.copilotkit.ai/generative-ui/components/from-a2ui\n */\n a2ui?: {\n /** A UI from `createGenerativeUI`. It is the `ui` of `generativeUI`. */\n catalog?: GenerativeUIConfig[\"ui\"];\n /** Values for the `--a2ui-*` CSS variables. It is the `theme` of `generativeUI`. */\n theme?: GenerativeUIConfig[\"theme\"];\n };\n}\n\n/**\n * The `generativeUI` prop with the options of the deprecated `a2ui` prop:\n * `a2ui.catalog` is the `ui` and `a2ui.theme` the `theme`, unless\n * `generativeUI` sets them.\n */\nfunction withA2UIOptions(\n generativeUI: GenerativeUIConfig | undefined,\n a2ui: NonNullable<CopilotKitProviderProps[\"a2ui\"]>,\n) {\n const hasA2UIOptions = a2ui.catalog !== undefined || a2ui.theme !== undefined;\n if (!hasA2UIOptions) return generativeUI;\n return {\n ...generativeUI,\n ui: generativeUI?.ui ?? a2ui.catalog,\n theme: generativeUI?.theme ?? a2ui.theme,\n };\n}\n\n// Normalize an array prop to a stable reference, and warn (rule from core)\n// when it changes after mount.\nfunction useStableArrayProp<T>(\n prop: T[] | undefined,\n name: ɵStableArrayProp,\n): T[] {\n const empty = useMemo<T[]>(() => [], []);\n const value = prop ?? empty;\n const initial = useRef(value);\n\n useEffect(() => {\n const warning = ɵstableArrayPropWarning(name, initial.current, value);\n if (warning) console.error(warning);\n }, [value, name]);\n\n return value;\n}\n\n/** Provide a shared core instance and synchronize runtime, tool, and UI configuration. */\nexport const CopilotKitProvider: React.FC<CopilotKitProviderProps> = ({\n children,\n runtimeUrl,\n headers: headersProp = EMPTY_HEADERS,\n credentials,\n nonce,\n injectStyles = true,\n messageFilter,\n publicApiKey,\n publicLicenseKey,\n properties = EMPTY_PROPERTIES,\n agents__unsafe_dev_only: agents = EMPTY_AGENTS,\n selfManagedAgents = EMPTY_AGENTS,\n renderToolCalls,\n renderActivityMessages,\n renderCustomMessages,\n markdownRenderer,\n frontendTools,\n humanInTheLoop,\n openGenerativeUI,\n enableInspector,\n agentId,\n showIntelligenceIndicator = true,\n useSingleEndpoint,\n onError,\n generativeUI,\n a2ui,\n mcpApps,\n defaultThrottleMs,\n debug,\n learning,\n}) => {\n // Memoized so a stable `learning` object keeps a stable config after\n // `autoStart` is removed.\n const learningConfig = useMemo(() => ɵtoLearningConfig(learning), [learning]);\n\n // Keep the server render and the first client render identical. The\n // Inspector only runs in local development. Resolve its host and build\n // policy after hydration instead of branching on `window` during render.\n const [shouldRenderInspector, setShouldRenderInspector] = useState(false);\n const [inspectorVisible, setInspectorVisible] = useState(false);\n\n useEffect(() => {\n setShouldRenderInspector(\n shouldEnableInspector({\n enableInspector,\n isBrowser: true,\n isDevelopment: process.env.NODE_ENV === \"development\",\n hostname: window.location?.hostname,\n }),\n );\n }, [enableInspector]);\n\n const [inspectorOpenRequest, setInspectorOpenRequest] =\n useState<CopilotKitInspectorOpenRequest | null>(null);\n // Core's runtime info snapshot, projected once the core exists (see the\n // subscription effect below). `null` until the first sync.\n const [runtimeInfo, setRuntimeInfo] = useState<ɵRuntimeInfo | null>(null);\n const runtimeOpenGenUIEnabled = runtimeInfo?.openGenerativeUIEnabled ?? false;\n const openGenUIActive = ɵisOpenGenerativeUIActive({\n runtimeEnabled: runtimeOpenGenUIEnabled,\n configured: !!openGenerativeUI,\n });\n // The deprecated `a2ui` prop goes to `generativeUI`, which wins for an\n // option that both set.\n const a2uiCatalog = a2ui?.catalog;\n const a2uiTheme = a2ui?.theme;\n const generativeUIProp = useMemo(\n () =>\n withA2UIOptions(generativeUI, { catalog: a2uiCatalog, theme: a2uiTheme }),\n [generativeUI, a2uiCatalog, a2uiTheme],\n );\n // The app's `generativeUI`, or the standard UI when the runtime turns\n // generative UI on and the app has none (loaded on demand).\n const generativeUIConfig = useStandardUIFallback(\n generativeUIProp,\n runtimeInfo,\n );\n const generativeUIActive = !!generativeUIConfig?.ui;\n const runtimeLicenseStatus = runtimeInfo?.licenseStatus;\n const runtimeEntitlements = runtimeInfo?.runtimeEntitlements;\n const runtimeEntitlementRetryPending =\n runtimeInfo?.runtimeEntitlementRetryPending ?? false;\n\n const requestInspectorOpen = useCallback(\n (request: CopilotKitInspectorOpenRequest) => {\n setInspectorOpenRequest({ ...request });\n },\n [],\n );\n\n const inspectorContextValue = useMemo(\n () => ({\n providerEnableInspector: enableInspector,\n isInspectorEnabled: shouldRenderInspector && inspectorVisible,\n openInspector: requestInspectorOpen,\n }),\n [\n enableInspector,\n shouldRenderInspector,\n inspectorVisible,\n requestInspectorOpen,\n ],\n );\n\n // Normalize array props to stable references with clear dev warnings\n // renderToolCalls warns only when its shape (names + agentId) changes, so\n // parents can pass updated closures (e.g., Storybook state).\n const renderToolCallsList = useStableArrayProp<ReactToolCallRenderer<any>>(\n renderToolCalls,\n \"renderToolCalls\",\n );\n\n const renderCustomMessagesList =\n useStableArrayProp<ReactCustomMessageRenderer>(\n renderCustomMessages,\n \"renderCustomMessages\",\n );\n\n const renderActivityMessagesList = useStableArrayProp<\n ReactActivityMessageRenderer<any>\n >(renderActivityMessages, \"renderActivityMessages\");\n\n // Stable core instance ref, declared here so the human-in-the-loop memo\n // below can read the core lazily. The instance itself is created further\n // down.\n const copilotkitRef = useRef<CopilotKitCoreReact | null>(null);\n\n const mcpAppsAllowSameOrigin = mcpApps?.allowSameOriginFallback === true;\n\n // The app's activity renderers, then the built-in ones (order from core).\n const allActivityRenderers = useMemo(\n () =>\n ɵassembleActivityRenderers<ReactActivityMessageRenderer<any>>({\n app: renderActivityMessagesList,\n builtIns: [\n {\n activityType: MCPAppsActivityType,\n content: MCPAppsActivityContentSchema,\n render: mcpAppsAllowSameOrigin\n ? SameOriginMCPAppsActivityRenderer\n : MCPAppsActivityRenderer,\n },\n openGenUIActive && {\n activityType: OpenGenerativeUIActivityType,\n content: OpenGenerativeUIContentSchema,\n render: OpenGenerativeUIActivityRenderer,\n },\n generativeUIActive && createGenerativeUIActivityRenderer(),\n generativeUIActive &&\n createGenerativeUIFunctionCallActivityRenderer(),\n ],\n }),\n [\n renderActivityMessagesList,\n openGenUIActive,\n generativeUIActive,\n mcpAppsAllowSameOrigin,\n ],\n );\n\n // Key fallback, Copilot Cloud URL, transport and agent merge all come from\n // core.\n const resolvedConfig = useMemo(\n () =>\n ɵresolveProviderConfig({\n runtimeUrl,\n publicApiKey,\n publicLicenseKey,\n useSingleEndpoint,\n agents__unsafe_dev_only: agents,\n selfManagedAgents,\n properties,\n }),\n [\n runtimeUrl,\n publicApiKey,\n publicLicenseKey,\n useSingleEndpoint,\n agents,\n selfManagedAgents,\n properties,\n ],\n );\n const resolvedPublicKey = resolvedConfig.publicKey;\n // Throws in production for a missing runtime config; otherwise warns, once\n // per provider for each message.\n const loggedDiagnosticsRef = useRef(new Set<string>());\n ɵreportProviderConfigDiagnostics(resolvedConfig.diagnostics, {\n isProduction: process.env.NODE_ENV === \"production\",\n logged: loggedDiagnosticsRef.current,\n });\n\n // The latest builder, read when a request is sent (never during render).\n // Assigned during render itself (not in a `useEffect`) so a child effect\n // that fires in the SAME commit as a new builder closure — e.g. a run\n // kicked off from an effect right after a token changed — reads the new\n // closure rather than the previous commit's.\n const headersRef = useRef(headersProp);\n headersRef.current = headersProp;\n const isHeadersBuilder = typeof headersProp === \"function\";\n // The read below can return a sync record or an async promise depending on\n // what `headersRef.current` happens to be at call time, which\n // `CopilotKitHeadersSource`'s shape can't express in one function\n // signature (sync-only OR async-only) — same rationale as the cast inside\n // `ɵwithHeaderDefaults`.\n const stableHeadersBuilder = useCallback(() => {\n const current = headersRef.current;\n return typeof current === \"function\" ? current() : current;\n }, []) as () => Record<string, string>;\n // A record keeps today's identity semantics; a builder is stable.\n const headersInput = isHeadersBuilder ? stableHeadersBuilder : headersProp;\n const headersSource = useMemo(\n () =>\n ɵwithHeaderDefaults(\n headersInput,\n ɵpublicKeyHeaderDefaults(resolvedPublicKey),\n ),\n [headersInput, resolvedPublicKey],\n );\n\n const frontendToolsList = useStableArrayProp<ReactFrontendTool>(\n frontendTools,\n \"frontendTools\",\n );\n const humanInTheLoopList = useStableArrayProp<ReactHumanInTheLoop>(\n humanInTheLoop,\n \"humanInTheLoop\",\n );\n const sandboxFunctionsList = useStableArrayProp<SandboxFunction>(\n openGenerativeUI?.sandboxFunctions,\n \"sandboxFunctions\",\n );\n\n // Built-in frontend tool for generateSandboxedUi — registered only when the runtime has openGenerativeUI enabled\n const builtInFrontendTools = useMemo<ReactFrontendTool[]>(() => {\n if (!openGenUIActive) return [];\n return [\n {\n ...ɵcreateOpenGenerativeUITool(),\n render: OpenGenerativeUIToolRenderer,\n },\n ];\n }, [openGenUIActive]);\n\n // The tools and tool-call renderers for core (assembly rules from core).\n // Human-in-the-loop renders are wrapped once per `humanInTheLoop` change: a\n // new wrapper is a new component type, so React would remount the card.\n const humanInTheLoopAssembly = useMemo(\n () =>\n ɵassembleHumanInTheLoop<\n ReactToolCallRenderer<any>[\"render\"],\n ReactHumanInTheLoop[\"render\"]\n >({\n humanInTheLoop: humanInTheLoopList,\n // Core parks each call by tool call id until the render responds.\n // The core is created further down, so read its registry lazily.\n humanInTheLoopRegistry: () => copilotkitRef.current!.ɵhumanInTheLoop,\n wrapHumanInTheLoopRender: (render, tool, registry) => (props) =>\n createElement(\n render as React.ComponentType<any>,\n ɵhitlRenderProps(props, tool, registry()),\n ),\n }),\n [humanInTheLoopList],\n );\n const allTools = useMemo(\n () =>\n ɵassembleProviderTools({\n frontendTools: frontendToolsList,\n builtInFrontendTools,\n humanInTheLoop: humanInTheLoopAssembly,\n }),\n [frontendToolsList, builtInFrontendTools, humanInTheLoopAssembly],\n );\n const allRenderToolCalls = useMemo(\n () =>\n ɵassembleProviderToolRenderers({\n renderToolCalls: renderToolCallsList,\n frontendTools: frontendToolsList,\n builtInFrontendTools,\n humanInTheLoop: humanInTheLoopAssembly,\n }) as ReactToolCallRenderer[],\n [\n renderToolCallsList,\n frontendToolsList,\n builtInFrontendTools,\n humanInTheLoopAssembly,\n ],\n );\n\n // One core for the provider lifetime (ref declared above), disposed on\n // unmount.\n // Updates are applied via setter effects below rather than recreating the\n // instance.\n const copilotkit = ɵuseOwnedCore(\n copilotkitRef,\n () =>\n new CopilotKitCoreReact({\n runtimeUrl: resolvedConfig.runtimeUrl,\n // Defer the `/info` fetch out of construction. The core is constructed\n // during render, and React can start-and-discard renders (concurrent\n // rendering / Suspense / StrictMode) — a network request in the ctor\n // would fire once per discarded attempt (issue #5801). `connect()`\n // below starts the single request from a commit-phase effect.\n deferInitialConnection: true,\n runtimeTransport: resolvedConfig.runtimeTransport,\n headers: headersSource,\n credentials,\n messageFilter,\n properties: resolvedConfig.properties,\n agents__unsafe_dev_only: resolvedConfig.agents,\n tools: allTools,\n renderToolCalls: allRenderToolCalls,\n renderActivityMessages: allActivityRenderers,\n renderCustomMessages: renderCustomMessagesList,\n debug,\n // Set at construction so child hooks see it on their first render.\n defaultThrottleMs,\n onError,\n learning: learningConfig,\n }),\n );\n const generativeUIRuntime = useGenerativeUIRoot(\n copilotkit,\n generativeUIConfig,\n );\n\n // Project core's runtime info snapshot (one object with every `/info`\n // field, so no field can be missed — a missed `licenseStatus` once pinned\n // the threads drawer to \"Loading threads…\"). The catch-up read after\n // subscribing reflects a status that settled before this effect ran.\n useEffect(() => {\n const syncRuntimeInfo = () => setRuntimeInfo(copilotkit.ɵruntimeInfo);\n const unsubscribe = copilotkit.ɵsubscribeToRuntimeInfo(syncRuntimeInfo);\n syncRuntimeInfo();\n return unsubscribe;\n }, [copilotkit]);\n\n // Subscribe to render tool calls changes to force re-renders\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onRenderToolCallsChanged: () => {\n forceUpdate();\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n // Core tracks executing tool calls from the first `onToolExecutionStart`,\n // so a HITL call resumed on reconnect (before the chat mounts) is already\n // executing when children first read it.\n const subscribeExecutingToolCalls = useCallback(\n (onChange: () => void) =>\n copilotkit.subscribe({ onExecutingToolCallsChanged: onChange })\n .unsubscribe,\n [copilotkit],\n );\n const getExecutingToolCallIds = () => copilotkit.executingToolCallIds;\n const executingToolCallIds = useSyncExternalStore(\n subscribeExecutingToolCalls,\n getExecutingToolCallIds,\n getExecutingToolCallIds,\n );\n\n // Core calls `onError`, and logs the error itself when there is none.\n useEffect(() => {\n copilotkit.setErrorHandler(onError);\n }, [copilotkit, onError]);\n\n useEffect(() => {\n // Core applies the message filter first, so an agent discovered by the\n // connection below is built with it. The generative UI envelope is not in\n // these properties: useGenerativeUIRoot adds it as scoped properties, so\n // this call does not replace it.\n copilotkit.ɵupdateConfig({\n messageFilter,\n runtimeUrl: resolvedConfig.runtimeUrl,\n runtimeTransport: resolvedConfig.runtimeTransport,\n headers: headersSource,\n credentials,\n properties: resolvedConfig.properties,\n agents__unsafe_dev_only: resolvedConfig.agents,\n debug,\n defaultThrottleMs,\n });\n // Start the runtime `/info` connection now that we're in the commit phase.\n // The ctor deferred it (see `deferInitialConnection` above) so discarded\n // renders never fetch; `connect()` is idempotent, so StrictMode's\n // double-invoked effect and re-runs on unrelated prop changes collapse to a\n // single request (a real runtimeUrl/transport change reconnects via the\n // update above). See #5801.\n copilotkit.connect();\n }, [\n copilotkit,\n messageFilter,\n resolvedConfig.runtimeUrl,\n resolvedConfig.runtimeTransport,\n headersSource,\n credentials,\n resolvedConfig.properties,\n resolvedConfig.agents,\n debug,\n defaultThrottleMs,\n ]);\n\n // Start the Trajectory in the commit phase, after the runtime URL is set, so\n // CopilotKit's own runtime traffic is never captured. The starter keeps its\n // generated Trajectory ID across StrictMode's dispose and replay.\n const learningStarterRef = useRef<ɵLearningAutoStarter | null>(null);\n learningStarterRef.current ??= new ɵLearningAutoStarter(copilotkit);\n const learningStarter = learningStarterRef.current;\n useEffect(() => {\n learningStarter.update(learning);\n }, [learningStarter, learning]);\n useEffect(() => () => learningStarter.dispose(), [learningStarter]);\n\n // Sync render/tool arrays to the stable instance via setters.\n // On mount, the constructor already receives the correct initial values,\n // so we skip the first invocation. This is critical because child hooks\n // (e.g., useFrontendTool, useHumanInTheLoop) register tools dynamically\n // via addTool()/setRenderToolCalls() in their own effects, which fire\n // BEFORE parent effects (React fires effects bottom-up). If the parent\n // setter effects ran on mount, they would overwrite the children's tools.\n const didMountRef = useRef(false);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setTools(allTools);\n }, [copilotkit, allTools]);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setRenderToolCalls(allRenderToolCalls);\n }, [copilotkit, allRenderToolCalls]);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setRenderActivityMessages(allActivityRenderers);\n }, [copilotkit, allActivityRenderers]);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setRenderCustomMessages(renderCustomMessagesList);\n }, [copilotkit, renderCustomMessagesList]);\n\n // Mark mount complete — must be declared AFTER the setter effects\n // so it runs last in the effect queue on the initial mount cycle. Reset on\n // cleanup, so a remount (StrictMode) or a replacement core skips the setters\n // again instead of overwriting tools the children just registered.\n useEffect(() => {\n didMountRef.current = true;\n return () => {\n didMountRef.current = false;\n };\n }, [copilotkit]);\n\n // Register the design skill and the sandbox functions as agent context for\n // the generateSandboxedUi tool (entries shared with Vue and Angular).\n const designSkill = openGenerativeUI?.designSkill;\n useLayoutEffect(() => {\n if (!copilotkit || !openGenUIActive) return;\n return ɵaddOpenGenerativeUIContexts(copilotkit, {\n designSkill,\n sandboxFunctions: sandboxFunctionsList,\n });\n }, [copilotkit, designSkill, sandboxFunctionsList, openGenUIActive]);\n\n const contextValue = useMemo<CopilotKitContextValue>(\n () => ({\n copilotkit,\n executingToolCallIds,\n showIntelligenceIndicator,\n }),\n [copilotkit, executingToolCallIds, showIntelligenceIndicator],\n );\n\n // License context and banner, driven by the license authority the runtime\n // reports through /info.\n const licenseState = useMemo(\n () =>\n ɵresolveLicenseState({\n status: runtimeLicenseStatus,\n entitlements: runtimeEntitlements,\n retryPending: runtimeEntitlementRetryPending,\n publicKey: resolvedPublicKey,\n }),\n [\n runtimeLicenseStatus,\n runtimeEntitlements,\n runtimeEntitlementRetryPending,\n resolvedPublicKey,\n ],\n );\n const styleOptions = useMemo(\n () => ({ nonce, inject: injectStyles }),\n [nonce, injectStyles],\n );\n\n return (\n <CopilotStyleOptionsProvider value={styleOptions}>\n <SandboxFunctionsContext.Provider value={sandboxFunctionsList}>\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseState.context}>\n {generativeUIActive && <GenerativeUIToolCallRenderer />}\n <MarkdownRendererProvider renderer={markdownRenderer}>\n <CopilotKitInspectorContextProvider value={inspectorContextValue}>\n {/*\n Publish the provider-level agent default. This is a bare string\n context, NOT a `CopilotChatConfigurationProvider`: that provider\n also owns a thread, so wrapping the application in one would give\n every descendant chat the same inherited threadId. See the\n `CopilotKitAgentIdContext` comment in `../context`.\n */}\n <CopilotKitAgentIdContext.Provider value={agentId}>\n <GenerativeUIRuntimeContext.Provider\n value={generativeUIRuntime}\n >\n {children}\n </GenerativeUIRuntimeContext.Provider>\n </CopilotKitAgentIdContext.Provider>\n {shouldRenderInspector ? (\n <CopilotKitInspector\n core={copilotkit}\n openRequest={inspectorOpenRequest}\n onVisibilityChange={setInspectorVisible}\n />\n ) : null}\n </CopilotKitInspectorContextProvider>\n </MarkdownRendererProvider>\n {/* License warnings — driven by server-reported status */}\n {licenseState.bannerType && (\n <LicenseWarningBanner type={licenseState.bannerType} />\n )}\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n </SandboxFunctionsContext.Provider>\n </CopilotStyleOptionsProvider>\n );\n};\n\n/**\n * Alias of {@link CopilotKitProvider}: the same component under its v1 name,\n * so `<CopilotKit>` keeps working. `CopilotKitProvider` is the preferred name.\n *\n * @alias\n */\nexport const CopilotKit = CopilotKitProvider;\n\n/**\n * Alias of {@link CopilotKitProviderProps}, the props of {@link CopilotKit}.\n * Prefer `CopilotKitProviderProps` in new code.\n */\nexport type CopilotKitProps = CopilotKitProviderProps;\n\n// Re-export useCopilotKit from context for backward compatibility\nexport { useCopilotKit } from \"../context\";\n","import {\n ɵgetCustomMessageRenderProps,\n ɵresolveCustomMessageRenderContext,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration, useCopilotKit } from \"../providers\";\nimport type { ReactCustomMessageRendererPosition } from \"../types/react-custom-message-renderer\";\nimport type { Message } from \"@ag-ui/core\";\n\ninterface UseRenderCustomMessagesParams {\n message: Message;\n position: ReactCustomMessageRendererPosition;\n}\n\nexport function useRenderCustomMessages() {\n const { copilotkit } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n\n if (!config) {\n return null;\n }\n\n const { threadId } = config;\n const { agentId, renderers: customMessageRenderers } =\n ɵresolveCustomMessageRenderContext(\n copilotkit.renderCustomMessages,\n config.agentId,\n );\n\n // No renderer can ever produce output, so hand the caller nothing rather\n // than a function that always returns null. Callers gate expensive work\n // (per-message state-snapshot cloning, memo wrappers) on this being truthy.\n if (!customMessageRenderers.length) {\n return null;\n }\n\n return function (params: UseRenderCustomMessagesParams) {\n const { message, position } = params;\n const agent = copilotkit.getAgent(agentId);\n if (!agent) {\n return null;\n }\n const props = ɵgetCustomMessageRenderProps(copilotkit, {\n agentId,\n threadId,\n agent,\n message,\n position,\n });\n\n // Try each renderer in order and show the first that draws something.\n let result = null;\n for (const renderer of customMessageRenderers) {\n if (!renderer.render) {\n continue;\n }\n const Component = renderer.render;\n result = (\n <Component\n key={`${props.runId}-${message.id}-${position}`}\n {...props}\n />\n );\n if (result) {\n break;\n }\n }\n return result;\n };\n}\n","import type { ActivityMessage } from \"@ag-ui/core\";\nimport {\n ɵdescribeActivityRendererFailure,\n ɵfindActivityRenderer,\n ɵmatchActivityRenderer,\n ɵresolveAgentId,\n} from \"@copilotkit/core\";\nimport { useDefaultAgentId } from \"../context\";\nimport { useCopilotKit, useCopilotChatConfiguration } from \"../providers\";\nimport { useCallback, useMemo } from \"react\";\nimport type { ReactActivityMessageRenderer } from \"../types\";\n\nexport function useRenderActivityMessage() {\n const { copilotkit } = useCopilotKit();\n // The chat's agent, else the provider's default agent.\n const agentId = ɵresolveAgentId({\n chatAgentId: useCopilotChatConfiguration()?.agentId,\n providerAgentId: useDefaultAgentId(),\n });\n\n const renderers = copilotkit.renderActivityMessages;\n\n // Find the renderer for a given activity type\n const findRenderer = useCallback(\n (activityType: string): ReactActivityMessageRenderer<unknown> | null =>\n ɵfindActivityRenderer(renderers, { activityType, agentId }),\n [agentId, renderers],\n );\n\n const renderActivityMessage = useCallback(\n (message: ActivityMessage): React.ReactElement | null => {\n const match = ɵmatchActivityRenderer(renderers, {\n activityType: message.activityType,\n agentId,\n content: message.content,\n });\n\n if (!match.ok) {\n // Explain why a message that has a renderer drew nothing.\n const warning = ɵdescribeActivityRendererFailure(\n message.activityType,\n match,\n );\n if (warning) {\n console.warn(warning.message, ...warning.details);\n }\n return null;\n }\n\n const Component = match.renderer.render;\n const agent = copilotkit.getAgent(agentId);\n\n return (\n <Component\n key={message.id}\n activityType={message.activityType}\n content={match.content}\n message={message}\n agent={agent}\n />\n );\n },\n [agentId, copilotkit, renderers],\n );\n\n return useMemo(\n () => ({ renderActivityMessage, findRenderer }),\n [renderActivityMessage, findRenderer],\n );\n}\n","import { useRef } from \"react\";\n\n/**\n * Deps comparison shared by `useFrontendTool` (and through it\n * `useHumanInTheLoop` and `useComponent`) and `useRenderTool`. Not part of the\n * public API.\n */\n\nconst EMPTY_DEPS: ReadonlyArray<unknown> = [];\n\nfunction isPlainObject(value: object): boolean {\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Plain data (primitives, plain objects, arrays, dates) compares by value.\n * Functions always compare equal: these hooks used to compare\n * `JSON.stringify(deps)`, which turns every function into `null`, and a\n * function that counted as changed would re-register on every render when it\n * is written inline (and loop in a component that also reads\n * `useRenderToolCall`). Everything else (class instances, maps, sets) compares\n * by identity. A cycle inside plain data is safe: a pair already being\n * compared counts as equal for that branch.\n */\nfunction depEqual(a: unknown, b: unknown, seen: Map<object, object>): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a === \"function\" && typeof b === \"function\") return true;\n if (\n typeof a !== \"object\" ||\n typeof b !== \"object\" ||\n a === null ||\n b === null\n ) {\n return false;\n }\n if (a instanceof Date && b instanceof Date) {\n return Object.is(a.getTime(), b.getTime());\n }\n const aIsArray = Array.isArray(a);\n if (aIsArray !== Array.isArray(b)) return false;\n if (!aIsArray && !(isPlainObject(a) && isPlainObject(b))) return false;\n\n if (seen.get(a) === b) return true;\n seen.set(a, b);\n\n if (aIsArray) {\n const left = a as unknown[];\n const right = b as unknown[];\n if (left.length !== right.length) return false;\n for (let i = 0; i < left.length; i++) {\n if (!depEqual(left[i], right[i], seen)) return false;\n }\n return true;\n }\n\n const left = a as Record<string, unknown>;\n const right = b as Record<string, unknown>;\n const leftKeys = Object.keys(left);\n if (leftKeys.length !== Object.keys(right).length) return false;\n for (const key of leftKeys) {\n if (!Object.prototype.hasOwnProperty.call(right, key)) return false;\n if (!depEqual(left[key], right[key], seen)) return false;\n }\n return true;\n}\n\n/** Whether two deps arrays are equal. A change in length is always a change. */\nexport function depsEqual(\n prev: ReadonlyArray<unknown>,\n next: ReadonlyArray<unknown>,\n): boolean {\n if (prev.length !== next.length) return false;\n const seen = new Map<object, object>();\n for (let i = 0; i < prev.length; i++) {\n if (!depEqual(prev[i], next[i], seen)) return false;\n }\n return true;\n}\n\n/**\n * Turns a caller's `deps` array into a number that changes exactly when the\n * deps change, by the rules of {@link depsEqual}. Put the number, not the\n * array, in the registration effect's dependency list: that keeps the list a\n * constant length and never serializes a value.\n */\nexport function useDepsVersion(deps?: ReadonlyArray<unknown>): number {\n const next = deps ?? EMPTY_DEPS;\n const ref = useRef({ deps: next, version: 0 });\n if (ref.current.deps !== next && !depsEqual(ref.current.deps, next)) {\n ref.current = { deps: next, version: ref.current.version + 1 };\n }\n return ref.current.version;\n}\n","import { useLayoutEffect } from \"react\";\nimport { ɵregisterFrontendTools } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport { useDepsVersion } from \"./tool-registration\";\n\n/**\n * Register a frontend tool while the component is mounted. The agent can\n * call it, and its `render` component draws the call in the chat.\n *\n * A tool with the same name and agentId as a tool that is already registered\n * (for example one from the provider's `tools`) overrides it while this\n * component is mounted. When the component unmounts, the overridden tool is\n * active again. The renderer stays registered after unmount, so past tool\n * calls still render in the chat history.\n *\n * @param tool - The tool to register.\n * @param deps - Extra values that re-register the tool when they change. Use\n * it when the handler closes over a value that is not part of the tool.\n *\n * @example\n * ```tsx\n * useFrontendTool({\n * name: \"showWeather\",\n * description: \"Show the weather for a city\",\n * parameters: z.object({ city: z.string() }),\n * handler: async ({ city }) => `Sunny in ${city}`,\n * });\n * ```\n */\nexport function useFrontendTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(tool: ReactFrontendTool<T>, deps?: ReadonlyArray<unknown>) {\n const { copilotkit } = useCopilotKit();\n // Plain data in `deps` compares by value, everything else by identity; see\n // useDepsVersion. Only the resulting number enters the effect's dependency\n // list, so `deps` is never serialized and may hold a circular value such as\n // the agent from useAgent.\n const depsVersion = useDepsVersion(deps);\n\n useLayoutEffect(() => {\n // This registration hides any tool with the same name and agentId (a\n // provider tool or another hook) until this effect cleans up. Unregistering\n // brings the hidden tool back. The renderer stays registered so past calls\n // still render in the chat history.\n return ɵregisterFrontendTools(copilotkit, [tool], (renderer) =>\n copilotkit.addHookRenderToolCall(renderer),\n );\n // Depend on stable keys by default and allow callers to opt into\n // additional dependencies for dynamic tool configuration.\n // tool.available is included so toggling availability re-registers the tool.\n // tool.webmcp is compared by value (it is commonly an object literal), so\n // a changed WebMCP config re-registers without churning on identity.\n }, [\n tool.name,\n tool.available,\n copilotkit,\n depsVersion,\n JSON.stringify(tool.webmcp ?? null),\n ]);\n}\n","import { useLayoutEffect } from \"react\";\nimport { ɵregisterFrontendTools } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\n\nconst EMPTY_DEPS: ReadonlyArray<unknown> = [];\nconst EMPTY_TOOLS: ReadonlyArray<ReactFrontendTool<any>> = [];\n\n/**\n * Register a list of frontend tools whose length can change between renders.\n *\n * `useFrontendTool` registers exactly one tool per call, so it cannot be called\n * in a loop over a runtime-length list without breaking the rules of hooks.\n * This hook runs a single effect over the whole array instead, which makes it\n * safe to build the list from state, props, or a server response.\n *\n * Tools are keyed by `name` plus `agentId`, the same as `useFrontendTool`. A\n * tool that disappears from the array is unregistered on the next render, and\n * every tool is unregistered on unmount. A listed tool hides a tool with the\n * same name and agentId (for example one from the provider's `tools`) until it\n * is unregistered, and then the hidden tool is active again. Renderers stay\n * registered after unmount so past tool calls still render in the chat history.\n *\n * @param tools - The tools to register. May be empty and may change length.\n * @param deps - Extra dependencies that force re-registration, compared by\n * identity like the second argument of `useEffect`. Use this when a handler\n * closes over a value that is not part of the tool definition. Keep the array\n * a constant length across renders.\n *\n * @example\n * Register one tool per item in application state:\n * ```tsx\n * const [reports, setReports] = useState<Report[]>([]);\n *\n * useFrontendTools(\n * reports.map((report) => ({\n * name: `open_${report.id}`,\n * description: `Open the ${report.title} report`,\n * handler: async () => navigate(`/reports/${report.id}`),\n * })),\n * [navigate],\n * );\n * ```\n *\n * @example\n * Register tools described by the backend:\n * ```tsx\n * const { data } = useQuery(fetchToolDescriptors);\n *\n * useFrontendTools(\n * (data ?? []).map((descriptor) => ({\n * name: descriptor.name,\n * description: descriptor.description,\n * parameters: z.object({ query: z.string() }),\n * handler: async ({ query }) => runDescriptor(descriptor.id, query),\n * })),\n * );\n * ```\n */\nexport function useFrontendTools(\n tools: ReadonlyArray<ReactFrontendTool<any>> | undefined,\n deps?: ReadonlyArray<unknown>,\n) {\n const { copilotkit } = useCopilotKit();\n const toolList = tools ?? EMPTY_TOOLS;\n const extraDeps = deps ?? EMPTY_DEPS;\n\n // The array is usually built inline, so its identity changes on every render\n // and cannot be a dependency. Derive a value signature from the fields that\n // decide what the agent sees, so the effect re-runs when the set of tools\n // actually changes and not merely when the caller re-renders.\n //\n // `description` is in the signature even though useFrontendTool does not key\n // on it. A singular caller writes a literal description, so it never changes\n // without the component re-mounting. This hook exists to build tools from\n // data, where the description is usually derived from that data, and a\n // description the agent reads must not go stale while the names stay put.\n const signature = JSON.stringify(\n toolList.map((tool) => [\n tool.name,\n tool.description ?? null,\n tool.agentId ?? null,\n tool.available ?? null,\n tool.webmcp ?? null,\n ]),\n );\n\n useLayoutEffect(() => {\n // Core collapses duplicate names so the last entry wins (as with\n // useFrontendTool), hides earlier tools with the same name and agentId\n // until cleanup, and keeps renderers so past calls still render. The\n // cleanup removes exactly what this run registered: reading the current\n // array would miss a tool dropped before the effect re-ran.\n return ɵregisterFrontendTools(copilotkit, toolList, (renderer) =>\n copilotkit.addHookRenderToolCall(renderer),\n );\n // `signature` is the value-based key for `toolList`, so the array itself is\n // deliberately not a dependency. `available` and `webmcp` are folded into\n // the signature for the same reasons they are dependencies of\n // useFrontendTool: toggling either must re-register the tool.\n //\n // `deps` is spread rather than stringified. JSON.stringify maps a function\n // to null, so a stringified `[navigate]` is the constant \"[null]\", and a\n // changed callback would never re-register. That is exactly the case `deps`\n // exists to cover. Spreading gives the entries React's own identity\n // comparison, the same contract as the second argument of useEffect. Pass a\n // deps array of a constant length, as React requires everywhere else.\n }, [signature, copilotkit, ...extraDeps]);\n}\n","import type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport { ɵcomponentToolDescription } from \"@copilotkit/core\";\nimport type { ComponentType } from \"react\";\nimport { useFrontendTool } from \"./use-frontend-tool\";\n\ntype InferRenderProps<T> = T extends StandardSchemaV1\n ? InferSchemaOutput<T>\n : any;\n\n/**\n * Registers a React component as a frontend tool renderer in chat.\n *\n * This hook is a convenience wrapper around `useFrontendTool` that:\n * - builds a model-facing tool description,\n * - forwards optional schema parameters (any Standard Schema V1 compatible library),\n * - renders your component with tool call parameters.\n *\n * Use this when you want to display a typed visual component for a tool call\n * without manually wiring a full frontend tool object.\n *\n * When `parameters` is provided, render props are inferred from the schema.\n * When omitted, the render component may accept any props.\n *\n * @typeParam TSchema - Schema describing tool parameters, or `undefined` when no schema is given.\n * @param config - Tool registration config.\n * @param deps - Optional dependencies to refresh registration (same semantics as `useEffect`).\n *\n * @example\n * ```tsx\n * // Without parameters — render accepts any props\n * useComponent({\n * name: \"showGreeting\",\n * render: ({ message }: { message: string }) => <div>{message}</div>,\n * });\n * ```\n *\n * @example\n * ```tsx\n * // With parameters — render props inferred from schema\n * useComponent({\n * name: \"showWeatherCard\",\n * parameters: z.object({ city: z.string() }),\n * render: ({ city }) => <div>{city}</div>,\n * });\n * ```\n *\n * @example\n * ```tsx\n * useComponent(\n * {\n * name: \"renderProfile\",\n * parameters: z.object({ userId: z.string() }),\n * render: ProfileCard,\n * agentId: \"support-agent\",\n * },\n * [selectedAgentId],\n * );\n * ```\n */\nexport function useComponent<\n TSchema extends StandardSchemaV1<any, Record<string, unknown>> | undefined =\n undefined,\n>(\n config: {\n name: string;\n description?: string;\n parameters?: TSchema;\n render: ComponentType<NoInfer<InferRenderProps<TSchema>>>;\n agentId?: string;\n followUp?: boolean;\n },\n deps?: ReadonlyArray<unknown>,\n): void {\n const fullDescription = ɵcomponentToolDescription(\n config.name,\n config.description,\n );\n\n useFrontendTool(\n {\n name: config.name,\n description: fullDescription,\n parameters: config.parameters,\n render: ({ args }: { args: unknown }) => {\n const Component = config.render;\n return <Component {...(args as InferRenderProps<TSchema>)} />;\n },\n agentId: config.agentId,\n followUp: config.followUp,\n },\n deps,\n );\n}\n","import { useEffect } from \"react\";\nimport type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport { ToolCallStatus } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport { defineToolCallRenderer } from \"../types/defineToolCallRenderer\";\nimport { useDepsVersion } from \"./tool-registration\";\n\nexport interface RenderToolInProgressProps<S extends StandardSchemaV1> {\n name: string;\n toolCallId: string;\n parameters: Partial<InferSchemaOutput<S>>;\n status: \"inProgress\";\n result: undefined;\n}\n\nexport interface RenderToolExecutingProps<S extends StandardSchemaV1> {\n name: string;\n toolCallId: string;\n parameters: InferSchemaOutput<S>;\n status: \"executing\";\n result: undefined;\n}\n\nexport interface RenderToolCompleteProps<S extends StandardSchemaV1> {\n name: string;\n toolCallId: string;\n parameters: InferSchemaOutput<S>;\n status: \"complete\";\n result: string;\n}\n\nexport type RenderToolProps<S extends StandardSchemaV1> =\n | RenderToolInProgressProps<S>\n | RenderToolExecutingProps<S>\n | RenderToolCompleteProps<S>;\n\ntype RenderToolConfig<S extends StandardSchemaV1> = {\n name: string;\n parameters?: S;\n render: (props: RenderToolProps<S>) => React.ReactElement | null;\n agentId?: string;\n group?: boolean;\n};\n\n/**\n * Registers a wildcard (`\"*\"`) renderer for tool calls.\n *\n * The wildcard renderer is used as a fallback when no exact name-matched\n * renderer is registered for a tool call.\n *\n * @param config - Wildcard renderer configuration.\n * @param deps - Optional dependencies to refresh registration.\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"*\",\n * render: ({ name, status }) => (\n * <div>\n * {status === \"complete\" ? \"✓\" : \"⏳\"} {name}\n * </div>\n * ),\n * },\n * [],\n * );\n * ```\n */\nexport function useRenderTool(\n config: {\n name: \"*\";\n render: (props: any) => React.ReactElement | null;\n agentId?: string;\n /** Let the chat group the calls this renderer draws (see `toolCallDisplay`). */\n group?: boolean;\n },\n deps?: ReadonlyArray<unknown>,\n): void;\n\n/**\n * Registers a name-scoped renderer for tool calls.\n *\n * The provided `parameters` schema defines the typed shape of `props.parameters`\n * in `render` for `executing` and `complete` states. Accepts any Standard Schema V1\n * compatible library (Zod, Valibot, ArkType, etc.).\n *\n * @typeParam S - Schema type describing tool call parameters.\n * @param config - Named renderer configuration.\n * @param deps - Optional dependencies to refresh registration.\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"searchDocs\",\n * parameters: z.object({ query: z.string() }),\n * render: ({ status, parameters, result }) => {\n * if (status === \"inProgress\") return <div>Preparing...</div>;\n * if (status === \"executing\") return <div>Searching {parameters.query}</div>;\n * return <div>{result}</div>;\n * },\n * },\n * [],\n * );\n * ```\n */\nexport function useRenderTool<S extends StandardSchemaV1>(\n config: {\n name: string;\n parameters: S;\n render: (props: RenderToolProps<S>) => React.ReactElement | null;\n agentId?: string;\n /** Let the chat group the calls this renderer draws (see `toolCallDisplay`). */\n group?: boolean;\n },\n deps?: ReadonlyArray<unknown>,\n): void;\n\n/**\n * Registers a renderer entry in CopilotKit's `renderToolCalls` registry.\n *\n * Key behavior:\n * - deduplicates by `agentId:name` (latest registration wins),\n * - keeps renderer entries on cleanup so historical chat tool calls can still render,\n * - refreshes registration when `deps` change.\n *\n * @typeParam S - Schema type describing tool call parameters.\n * @param config - Renderer config for wildcard or named tools.\n * @param deps - Optional dependencies to refresh registration.\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"searchDocs\",\n * parameters: z.object({ query: z.string() }),\n * render: ({ status, parameters, result }) => {\n * if (status === \"executing\") return <div>Searching {parameters.query}</div>;\n * if (status === \"complete\") return <div>{result}</div>;\n * return <div>Preparing...</div>;\n * },\n * },\n * [],\n * );\n * ```\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"summarize\",\n * parameters: z.object({ text: z.string() }),\n * agentId: \"research-agent\",\n * render: ({ name, status }) => <div>{name}: {status}</div>,\n * },\n * [selectedAgentId],\n * );\n * ```\n */\nexport function useRenderTool<S extends StandardSchemaV1>(\n config: RenderToolConfig<S>,\n deps?: ReadonlyArray<unknown>,\n): void {\n const { copilotkit } = useCopilotKit();\n // Plain data in `deps` compares by value, everything else by identity; see\n // useDepsVersion. `deps` is never serialized, so it may hold a circular\n // value such as the agent from useAgent.\n const depsVersion = useDepsVersion(deps);\n\n useEffect(() => {\n // Build the ReactToolCallRenderer via defineToolCallRenderer\n const renderer =\n config.name === \"*\" && !config.parameters\n ? defineToolCallRenderer({\n name: \"*\",\n render: (props) =>\n config.render({ ...props, parameters: props.args }),\n ...(config.agentId ? { agentId: config.agentId } : {}),\n group: config.group,\n })\n : defineToolCallRenderer({\n name: config.name,\n args: config.parameters!,\n // Branch per status so the discriminated union stays correlated\n // when `args` is re-exposed as `parameters`.\n render: (props) => {\n if (props.status === ToolCallStatus.InProgress) {\n return config.render({ ...props, parameters: props.args });\n }\n if (props.status === ToolCallStatus.Executing) {\n return config.render({ ...props, parameters: props.args });\n }\n return config.render({ ...props, parameters: props.args });\n },\n ...(config.agentId ? { agentId: config.agentId } : {}),\n group: config.group,\n });\n\n copilotkit.addHookRenderToolCall(renderer);\n\n // No cleanup removal — keeps renderer for chat history, same as useFrontendTool\n }, [config.name, config.group, copilotkit, depsVersion]);\n}\n","import React, {\n createContext,\n useId,\n useLayoutEffect,\n useRef,\n useState,\n} from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport {\n CopilotChatDefaultLabels,\n ɵTOOL_CALL_STATUS_ICONS,\n ɵTOOL_CALL_STATUS_LABEL_KEYS,\n ɵcountFailedToolCalls,\n ɵformatLabel,\n ɵformatToolNames,\n ɵgetArgumentPreview,\n ɵgetToolCallGroupState,\n ɵstringifyToolCallPayload,\n ɵformatCountLabel,\n} from \"@copilotkit/core\";\nimport type {\n ToolCallEntry,\n ɵToolCallGroupAppearance,\n ɵToolCallRowStatus,\n} from \"@copilotkit/core\";\nimport { cn } from \"../../lib/utils\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\nexport type CopilotChatToolCallGroupAppearance = ɵToolCallGroupAppearance;\n\n/**\n * Set by a group around the calls it shows, so CopilotKit's built-in tool card\n * draws itself as a compact row that fits the group instead of a card.\n * @internal\n */\nexport const ToolCallGroupContext = createContext<{\n appearance: CopilotChatToolCallGroupAppearance;\n failedIds: ReadonlySet<string>;\n /** Each call's row status, by call id. */\n statusById: ReadonlyMap<string, ɵToolCallRowStatus>;\n /** The agent may still finish the group's calls; see `isActive`. */\n active: boolean;\n} | null>(null);\n\n/** The chat labels from the nearest chat configuration, or the defaults. */\nfunction useLabels() {\n const config = useCopilotChatConfiguration();\n return config?.labels ?? CopilotChatDefaultLabels;\n}\n\n/**\n * Height transition between closed and its content's height. Closed content\n * stays mounted (so its state survives) but is inert.\n * @internal\n */\nexport function Collapsible({\n open,\n id,\n className,\n children,\n}: {\n open: boolean;\n id?: string;\n className?: string;\n children: React.ReactNode;\n}) {\n // React only treats `inert` as a prop from 19 on, so set the attribute\n // directly to keep closed content out of the tab order on React 18 too.\n const ref = useRef<HTMLDivElement>(null);\n useLayoutEffect(() => {\n ref.current?.toggleAttribute(\"inert\", !open);\n }, [open]);\n\n return (\n <div\n ref={ref}\n id={id}\n className={cn(\"cpk-collapsible\", className)}\n style={{ gridTemplateRows: open ? \"1fr\" : \"0fr\" }}\n >\n <div className=\"cpk-collapsible-content\">{children}</div>\n </div>\n );\n}\n\nfunction StatusIcon({\n status,\n className,\n}: {\n status: ɵToolCallRowStatus;\n className?: string;\n}) {\n return (\n <CopilotIcon\n name={ɵTOOL_CALL_STATUS_ICONS[status]}\n aria-hidden=\"true\"\n className={cn(\n \"cpk-tool-call-status-icon\",\n status === \"running\" && \"cpk-tool-call-status-icon-running\",\n status === \"failed\" && \"cpk-tool-call-status-icon-failed\",\n className,\n )}\n />\n );\n}\n\nfunction Chevron({ open, className }: { open: boolean; className?: string }) {\n return (\n <CopilotIcon\n name=\"ChevronRight\"\n aria-hidden=\"true\"\n className={cn(\n \"cpk-tool-call-chevron\",\n open && \"cpk-tool-call-chevron-open\",\n className,\n )}\n />\n );\n}\n\nfunction FailedCount({ calls }: { calls: ToolCallEntry[] }) {\n const labels = useLabels();\n const failed = ɵcountFailedToolCalls(calls);\n if (!failed) return null;\n return (\n <span className=\"cpk-tool-call-failed-count\">\n {ɵformatLabel(labels.toolCallFailedCountLabel, { count: failed })}\n </span>\n );\n}\n\nfunction Payload({ label, value }: { label: string; value: unknown }) {\n return (\n <div>\n <div className=\"cpk-tool-call-payload-label\">{label}</div>\n <pre className=\"cpk-tool-call-payload-code\">\n {ɵstringifyToolCallPayload(value)}\n </pre>\n </div>\n );\n}\n\n/**\n * A tool call's arguments and, once it has one, its result.\n * @internal\n */\nexport function ToolCallPayloads({\n parameters,\n result,\n className,\n}: {\n parameters: unknown;\n result: string | undefined;\n className?: string;\n}) {\n const labels = useLabels();\n return (\n <div className={cn(\"cpk-tool-call-payloads\", className)}>\n <Payload label={labels.toolCallArgumentsLabel} value={parameters ?? {}} />\n {result !== undefined && (\n <Payload label={labels.toolCallResultLabel} value={result} />\n )}\n </div>\n );\n}\n\n/**\n * The built-in tool card drawn as a row inside a group: status, name and main\n * argument, opening to the payloads.\n * @internal\n */\nexport function ToolCallRow({\n name,\n parameters,\n result,\n status,\n appearance,\n className,\n ...props\n}: {\n name: string;\n parameters: unknown;\n result: string | undefined;\n status: ɵToolCallRowStatus;\n appearance: \"card\" | \"line\" | \"stack\";\n} & React.HTMLAttributes<HTMLDivElement>) {\n const labels = useLabels();\n const [open, setOpen] = useState(false);\n const detailsId = useId();\n const preview = ɵgetArgumentPreview(parameters);\n\n return (\n <div\n data-copilotkit\n // Rows draw their own divider: interaction capture can wrap each call\n // in a `display: contents` element, which a parent's divide-y misses.\n className={cn(\n \"cpk-tool-call-row\",\n `cpk-tool-call-row-${appearance}`,\n className,\n )}\n {...props}\n >\n <button\n type=\"button\"\n aria-expanded={open}\n aria-controls={detailsId}\n onClick={() => setOpen((value) => !value)}\n className=\"cpk-tool-call-row-button\"\n >\n <StatusIcon status={status} />\n <span\n data-testid=\"copilot-tool-render-name\"\n className={cn(\n \"cpk-tool-call-row-name\",\n status === \"running\" && \"cpk-shimmer\",\n )}\n >\n {name}\n </span>\n {preview && (\n <span className=\"cpk-tool-call-row-preview\">{preview}</span>\n )}\n <span\n data-testid=\"copilot-tool-render-status\"\n className=\"cpk-tool-call-row-status\"\n >\n {labels[ɵTOOL_CALL_STATUS_LABEL_KEYS[status]]}\n </span>\n <Chevron open={open} className=\"cpk-tool-call-row-chevron\" />\n </button>\n <Collapsible open={open} id={detailsId}>\n <ToolCallPayloads\n parameters={parameters}\n result={result}\n className=\"cpk-tool-call-row-payloads\"\n />\n </Collapsible>\n </div>\n );\n}\n\nexport interface CopilotChatToolCallGroupProps extends Omit<\n React.HTMLAttributes<HTMLDivElement>,\n \"children\"\n> {\n /** The calls in the group, in order. */\n calls: ToolCallEntry[];\n /** Renders one call through the registered renderers. */\n renderCall: (call: ToolCallEntry) => React.ReactNode;\n /**\n * - `\"card\"` (default): one card with a summary header and a row per call.\n * - `\"line\"`: a quiet line of text that opens to a list of rows.\n * - `\"stack\"`: the latest call on a stack of the earlier ones.\n */\n appearance?: CopilotChatToolCallGroupAppearance;\n /** The agent is running and nothing follows the group, so more calls may join it. */\n isActive?: boolean;\n}\n\n/**\n * Tool calls made in a row, collapsed into one summary. While a call runs the\n * summary names it (\"Running read_file src/app.ts\"); once they're all done it\n * reads \"Used 3 tools\" and opens to the calls.\n *\n * Each call is drawn by its registered renderer. CopilotKit's built-in card\n * (`useDefaultRenderTool`) draws a compact row inside the card and line\n * appearances and an open stack; a custom wildcard renderer draws whatever it\n * draws.\n */\nexport function CopilotChatToolCallGroup({\n calls,\n renderCall,\n appearance = \"card\",\n isActive = false,\n className,\n ...props\n}: CopilotChatToolCallGroupProps) {\n const labels = useLabels();\n const [open, setOpen] = useState(false);\n const bodyId = useId();\n const {\n latest,\n current,\n preview,\n done,\n failedIds,\n statusById,\n status,\n behind,\n latestStatus,\n latestPreview,\n } = ɵgetToolCallGroupState(calls, isActive, open);\n if (!latest) return null;\n const groupContext = { failedIds, statusById, active: isActive };\n\n const rows = (rowAppearance: \"card\" | \"line\") => (\n <ToolCallGroupContext.Provider\n value={{ ...groupContext, appearance: rowAppearance }}\n >\n {calls.map((call) => (\n <React.Fragment key={call.toolCall.id}>\n {renderCall(call)}\n </React.Fragment>\n ))}\n </ToolCallGroupContext.Provider>\n );\n\n const groupProps = {\n \"data-copilotkit\": true,\n \"data-testid\": \"copilot-tool-call-group\",\n \"data-appearance\": appearance,\n \"data-state\": status,\n ...props,\n };\n\n const runningLabel = current && (\n <>\n <span className=\"cpk-tool-call-group-running cpk-shimmer\">\n {ɵformatLabel(labels.toolCallRunningLabel, {\n name: current.toolCall.function.name,\n })}\n </span>\n {preview && (\n <span className=\"cpk-tool-call-group-preview\">{preview}</span>\n )}\n </>\n );\n\n if (appearance === \"line\") {\n if (calls.length === 1 && !current) {\n return (\n <div\n {...groupProps}\n className={cn(\n \"cpk-tool-call-group cpk-tool-call-group-line cpk-tool-call-group-single\",\n className,\n )}\n >\n <ToolCallGroupContext.Provider\n value={{ ...groupContext, appearance: \"line\" }}\n >\n {renderCall(latest)}\n </ToolCallGroupContext.Provider>\n </div>\n );\n }\n return (\n <div\n {...groupProps}\n className={cn(\n \"cpk-tool-call-group cpk-tool-call-group-line\",\n className,\n )}\n >\n <button\n type=\"button\"\n aria-expanded={open}\n aria-controls={bodyId}\n onClick={() => setOpen((value) => !value)}\n className=\"cpk-tool-call-group-line-toggle\"\n >\n {runningLabel || (\n <>\n <span className=\"cpk-tool-call-group-line-summary\">\n {ɵformatCountLabel(calls.length, {\n one: labels.toolCallUsedToolsOne,\n other: labels.toolCallUsedToolsOther,\n })}\n </span>\n <span className=\"cpk-tool-call-group-line-names\">\n {ɵformatToolNames(calls)}\n </span>\n <FailedCount calls={calls} />\n </>\n )}\n <Chevron open={open} />\n </button>\n <Collapsible open={open} id={bodyId}>\n <div className=\"cpk-tool-call-group-line-body\">{rows(\"line\")}</div>\n </Collapsible>\n </div>\n );\n }\n\n if (appearance === \"stack\") {\n // A lone call is the top card of a stack with nothing behind it yet.\n // One toggle in both states, so it keeps keyboard focus when pressed.\n const layer = \"cpk-tool-call-group-stack-layer\";\n return (\n <div\n {...groupProps}\n className={cn(\n \"cpk-tool-call-group cpk-tool-call-group-stack\",\n className,\n )}\n style={{ paddingBottom: behind * 6, ...props.style }}\n >\n <div className=\"cpk-tool-call-group-stack-pile\">\n {Array.from({ length: behind }, (_, index) => (\n <div\n key={index}\n aria-hidden=\"true\"\n className={cn(layer, \"cpk-tool-call-group-stack-behind\")}\n style={{\n transform: `translateY(${(index + 1) * 6}px) scaleX(${1 - (index + 1) * 0.045})`,\n zIndex: -1 - index,\n opacity: 1 - (index + 1) * 0.28,\n }}\n />\n ))}\n <button\n type=\"button\"\n aria-expanded={open}\n aria-controls={open ? bodyId : undefined}\n onClick={() => setOpen((value) => !value)}\n className={cn(\n \"cpk-tool-call-group-stack-toggle\",\n open\n ? \"cpk-tool-call-group-stack-toggle-open\"\n : [layer, \"cpk-tool-call-group-stack-toggle-closed\"],\n )}\n >\n {open ? (\n <>\n {ɵformatCountLabel(calls.length, {\n one: labels.toolCallToolCallCountOne,\n other: labels.toolCallToolCallCountOther,\n })}\n <FailedCount calls={calls} />\n <span className=\"cpk-tool-call-group-stack-collapse\">\n {labels.toolCallCollapseLabel}\n <Chevron\n open\n className=\"cpk-tool-call-group-stack-collapse-icon\"\n />\n </span>\n </>\n ) : (\n <>\n <span\n key={latest.toolCall.id}\n className=\"cpk-tool-call-group-stack-latest\"\n >\n <StatusIcon status={latestStatus} />\n <span\n className={cn(\n \"cpk-tool-call-group-stack-name\",\n latestStatus === \"running\" && \"cpk-shimmer\",\n )}\n >\n {latest.toolCall.function.name}\n </span>\n {latestPreview && (\n <span className=\"cpk-tool-call-group-stack-preview\">\n {latestPreview}\n </span>\n )}\n {/* The status icon is decorative, so say the status. */}\n <span className=\"cpk-tool-call-group-stack-status\">\n {labels[ɵTOOL_CALL_STATUS_LABEL_KEYS[latestStatus]]}\n </span>\n </span>\n <span className=\"cpk-tool-call-group-stack-meta\">\n <FailedCount calls={calls} />\n <span className=\"cpk-tool-call-group-stack-count\">\n {ɵformatCountLabel(calls.length, {\n one: labels.toolCallCallCountOne,\n other: labels.toolCallCallCountOther,\n })}\n </span>\n <Chevron\n open={false}\n className=\"cpk-tool-call-group-stack-expand-icon\"\n />\n </span>\n </>\n )}\n </button>\n {/* Always mounted, so screen readers hear the closed stack's latest\n call change (\"read_file: Running\", then \"read_file: Done\"); the\n button only names it. */}\n <span aria-live=\"polite\" className=\"cpk-tool-call-group-stack-live\">\n {open\n ? \"\"\n : `${latest.toolCall.function.name}: ${labels[ɵTOOL_CALL_STATUS_LABEL_KEYS[latestStatus]]}`}\n </span>\n </div>\n {open && (\n // Each call gets the collapsed stack's card, easing out of the stack.\n <div id={bodyId} className=\"cpk-tool-call-group-stack-items\">\n <ToolCallGroupContext.Provider\n value={{ ...groupContext, appearance: \"stack\" }}\n >\n {calls.map((call, index) => (\n <div\n key={call.toolCall.id}\n className={cn(layer, \"cpk-tool-call-group-stack-item\")}\n style={{ animationDelay: `${index * 30}ms` }}\n >\n {renderCall(call)}\n </div>\n ))}\n </ToolCallGroupContext.Provider>\n </div>\n )}\n </div>\n );\n }\n\n // card: one call gets the same card as several, so the card a run starts\n // with doesn't change style when the next call joins it.\n return (\n <div\n {...groupProps}\n className={cn(\"cpk-tool-call-group cpk-tool-call-group-card\", className)}\n >\n <button\n type=\"button\"\n aria-expanded={open}\n aria-controls={bodyId}\n onClick={() => setOpen((value) => !value)}\n className=\"cpk-tool-call-group-card-toggle\"\n >\n <StatusIcon status={status} />\n {runningLabel || (\n <>\n <span className=\"cpk-tool-call-group-card-summary\">\n {ɵformatCountLabel(calls.length, {\n one: labels.toolCallUsedToolsOne,\n other: labels.toolCallUsedToolsOther,\n })}\n </span>\n <span className=\"cpk-tool-call-group-card-names\">\n {ɵformatToolNames(calls)}\n </span>\n </>\n )}\n <span className=\"cpk-tool-call-group-card-meta\">\n {status === \"failed\" ? (\n <FailedCount calls={calls} />\n ) : (\n <span className=\"cpk-tool-call-group-card-status\">\n {status !== \"running\"\n ? labels[ɵTOOL_CALL_STATUS_LABEL_KEYS[status]]\n : done > 0 &&\n ɵformatLabel(labels.toolCallDoneCountLabel, { count: done })}\n </span>\n )}\n <Chevron open={open} />\n </span>\n </button>\n <Collapsible open={open} id={bodyId}>\n <div>{rows(\"card\")}</div>\n </Collapsible>\n </div>\n );\n}\n\nexport default CopilotChatToolCallGroup;\n","import React, { useContext, useState } from \"react\";\nimport {\n CopilotChatDefaultLabels,\n ɵadaptDefaultToolCallRenderProps,\n ɵgetToolCallBadge,\n ɵnormalizeToolCallStatus,\n ɵstringifyToolCallAttr,\n ɵstringifyToolCallPayload,\n} from \"@copilotkit/core\";\nimport type {\n ToolCallStatus,\n ɵDefaultToolCallRenderProps,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { useRenderTool } from \"./use-render-tool\";\nimport { cn } from \"../lib/utils\";\nimport {\n ToolCallGroupContext,\n ToolCallRow,\n} from \"../components/chat/CopilotChatToolCallGroup\";\n\n/** What a custom `useDefaultRenderTool` render receives. */\nexport type DefaultRenderProps = ɵDefaultToolCallRenderProps;\n\n/**\n * Shape that `useRenderToolCall` actually invokes a registered `*` renderer\n * with: `{ name, toolCallId, args, status: ToolCallStatus, result }`.\n *\n * `useDefaultRenderTool` accepts user `config.render` typed against the\n * documented {@link DefaultRenderProps}, then wraps it via {@link adaptRendererProps}\n * so the user's function receives the documented shape — not the raw\n * framework-internal one.\n */\ntype RawRendererProps = {\n name: string;\n toolCallId: string;\n args: unknown;\n status: ToolCallStatus;\n result: string | undefined;\n};\n\n/**\n * Convert the framework-internal renderer props (`args`, enum status) into\n * the documented {@link DefaultRenderProps} shape (`parameters`, string-union\n * status) so a user `config.render` always sees the documented contract.\n */\nexport const adaptRendererProps: (\n props: RawRendererProps,\n) => DefaultRenderProps = ɵadaptDefaultToolCallRenderProps;\n\n/**\n * Registers a wildcard (`\"*\"`) tool-call renderer via `useRenderTool`.\n *\n * - Call with no config to use CopilotKit's built-in default tool-call card.\n * - Pass `config.render` to replace the default UI with your own fallback renderer.\n *\n * This is useful when you want a generic renderer for tools that do not have a\n * dedicated `useRenderTool({ name: \"...\" })` registration.\n *\n * @param config - Optional custom wildcard render function.\n * @param deps - Optional dependencies to refresh registration.\n *\n * @example\n * ```tsx\n * useDefaultRenderTool();\n * ```\n *\n * @example\n * ```tsx\n * useDefaultRenderTool({\n * render: ({ name, status }) => <div>{name}: {status}</div>,\n * });\n * ```\n *\n * @example\n * ```tsx\n * useDefaultRenderTool(\n * {\n * render: ({ name, result }) => (\n * <ToolEventRow title={name} payload={result} compact={compactMode} />\n * ),\n * },\n * [compactMode],\n * );\n * ```\n */\nexport function useDefaultRenderTool(\n config?: {\n render?: (props: DefaultRenderProps) => React.ReactElement | null;\n /**\n * Let the chat group calls your `render` draws, like it groups the\n * built-in card's (see `toolCallDisplay` on `CopilotChatMessageView`).\n * Off by default for a custom `render`, since it may draw nothing.\n */\n group?: boolean;\n },\n deps?: ReadonlyArray<unknown>,\n): void {\n const userRender = config?.render;\n\n // When the caller supplies their own render, wrap it so it receives the\n // documented {@link DefaultRenderProps} (parameters, string-union status)\n // even though `useRenderToolCall` invokes the registered render with the\n // framework-internal `{ args, status: ToolCallStatus, ... }` shape.\n const registered: (props: RawRendererProps) => React.ReactElement | null =\n userRender\n ? (raw) => userRender(adaptRendererProps(raw))\n : (raw) => <DefaultToolCallRenderer {...adaptRendererProps(raw)} />;\n\n useRenderTool(\n {\n name: \"*\",\n // `useRenderTool` types the render with the raw framework signature\n // and still requires a `React.ReactElement` return; the wrapper above\n // adapts to the documented shape and may return `null`. We cast through\n // `unknown` to bridge both gaps without `as any`.\n render: registered as unknown as (props: unknown) => React.ReactElement,\n // The built-in card draws a row inside a group; a custom render opts in.\n group: userRender ? config?.group === true : true,\n },\n deps,\n );\n}\n\nexport function DefaultToolCallRenderer({\n name,\n toolCallId,\n parameters,\n status,\n result,\n}: DefaultRenderProps): React.ReactElement {\n const group = useContext(ToolCallGroupContext);\n const labels =\n useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;\n const [isExpanded, setIsExpanded] = useState(false);\n\n // A status a newer runtime could send reads \"unknown\".\n const cardStatus = ɵnormalizeToolCallStatus(status);\n\n // Inside a group of calls, a row that fits the group instead of a card.\n if (group) {\n return (\n <ToolCallRow\n data-testid=\"copilot-tool-render\"\n data-tool-name={name}\n data-tool-call-id={toolCallId}\n data-status={cardStatus}\n data-args={ɵstringifyToolCallAttr(parameters)}\n data-result={ɵstringifyToolCallAttr(result)}\n name={name}\n parameters={parameters}\n result={result}\n status={group.statusById.get(toolCallId) ?? \"done\"}\n appearance={group.appearance}\n />\n );\n }\n\n // Colors the status dot and badge: running, done, or anything else.\n const { tone, labelKey } = ɵgetToolCallBadge(cardStatus);\n const statusLabel = labels[labelKey];\n\n return (\n <div\n data-testid=\"copilot-tool-render\"\n data-tool-name={name}\n data-tool-call-id={toolCallId}\n data-status={cardStatus}\n data-args={ɵstringifyToolCallAttr(parameters)}\n data-result={ɵstringifyToolCallAttr(result)}\n className=\"cpk-default-tool-call\"\n >\n <div className=\"cpk-default-tool-call-card\">\n {/* Header row — always visible. A real <button> with aria-expanded\n and reset styles so it visually matches the previous <div> but\n is keyboard-accessible (Enter/Space toggle natively). */}\n <button\n type=\"button\"\n aria-expanded={isExpanded}\n onClick={() => setIsExpanded(!isExpanded)}\n className=\"cpk-default-tool-call-header\"\n style={{\n font: \"inherit\",\n }}\n >\n <div className=\"cpk-default-tool-call-title\">\n <svg\n className={cn(\n \"cpk-default-tool-call-chevron\",\n isExpanded && \"cpk-default-tool-call-chevron-open\",\n )}\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n strokeWidth={2}\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n d=\"M8.25 4.5l7.5 7.5-7.5 7.5\"\n />\n </svg>\n <span\n className={`cpk-default-tool-call-dot cpk-default-tool-call-dot-${tone}`}\n />\n <span\n data-testid=\"copilot-tool-render-name\"\n className=\"cpk-default-tool-call-name\"\n >\n {name}\n </span>\n </div>\n\n <span\n data-testid=\"copilot-tool-render-status\"\n className={`cpk-default-tool-call-badge cpk-default-tool-call-badge-${tone}`}\n >\n {statusLabel}\n </span>\n </button>\n\n {/* Expandable details */}\n {isExpanded && (\n <div className=\"cpk-default-tool-call-details\">\n <div>\n <div className=\"cpk-default-tool-call-label\">\n {labels.toolCallArgumentsLabel}\n </div>\n <pre className=\"cpk-default-tool-call-code\">\n {ɵstringifyToolCallPayload(parameters ?? {})}\n </pre>\n </div>\n\n {result !== undefined && (\n <div>\n <div className=\"cpk-default-tool-call-label\">\n {labels.toolCallResultLabel}\n </div>\n <pre className=\"cpk-default-tool-call-code\">\n {ɵstringifyToolCallPayload(result)}\n </pre>\n </div>\n )}\n </div>\n )}\n </div>\n </div>\n );\n}\n","import { useCopilotKit } from \"../context\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport type { ReactHumanInTheLoop } from \"../types/human-in-the-loop\";\nimport type { ReactToolCallRenderer } from \"../types/react-tool-call-renderer\";\nimport { ɵbuildHumanInTheLoopTool, ɵhitlRenderProps } from \"@copilotkit/core\";\nimport { useCallback, useLayoutEffect } from \"react\";\nimport React from \"react\";\nimport { useFrontendTool } from \"./use-frontend-tool\";\n\nexport function useHumanInTheLoop<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(tool: ReactHumanInTheLoop<T>, deps?: ReadonlyArray<unknown>) {\n const { copilotkit } = useCopilotKit();\n // Core parks each call by tool call id, so parallel calls of this tool\n // (or of a \"*\" catch-all) each get their own `respond`.\n const registry = copilotkit.ɵhumanInTheLoop;\n\n const RenderComponent: ReactToolCallRenderer<T>[\"render\"] = useCallback(\n (props) =>\n React.createElement(\n tool.render,\n ɵhitlRenderProps<T, typeof props>(props, tool, registry),\n ),\n // eslint-disable-next-line react-hooks/exhaustive-deps -- tool is a fresh object each render; depend on the fields the renderer reads\n [tool.render, tool.name, tool.description, tool.agentId, registry],\n );\n\n const frontendTool: ReactFrontendTool<T> = {\n ...ɵbuildHumanInTheLoopTool<T>(tool, registry),\n render: RenderComponent,\n };\n\n useFrontendTool(frontendTool, deps);\n\n // Human-in-the-loop tools should remove their renderer on unmount\n // since they can't respond to user interactions anymore.\n //\n // This MUST stay a layout effect to match `useFrontendTool`, which registers\n // the renderer in its own layout effect. React runs every cleanup in a phase\n // before any effect of that same phase, but it runs the whole layout phase\n // ahead of the whole passive phase. If this teardown were passive while the\n // registration is layout, a keyed remount would order the outgoing\n // instance's removal *after* the incoming instance's registration and delete\n // the renderer that had just been added, leaving the tool unrenderable.\n useLayoutEffect(() => {\n return () => {\n copilotkit.removeHookRenderToolCall(tool.name, tool.agentId);\n };\n }, [copilotkit, tool.name, tool.agentId]);\n}\n","import { useCopilotKit, useDefaultAgentId } from \"../context\";\nimport { useMemo, useEffect, useReducer, useSyncExternalStore } from \"react\";\nimport {\n ɵgetAgentResolver,\n ɵresolveAgentId,\n ɵresolveAgentThreadId,\n ɵsubscribeToAgentUpdates,\n ɵvalidateAgentBinding,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\n\nexport enum UseAgentUpdate {\n OnMessagesChanged = \"OnMessagesChanged\",\n OnStateChanged = \"OnStateChanged\",\n OnRunStatusChanged = \"OnRunStatusChanged\",\n}\n\nconst ALL_UPDATES: UseAgentUpdate[] = [\n UseAgentUpdate.OnMessagesChanged,\n UseAgentUpdate.OnStateChanged,\n UseAgentUpdate.OnRunStatusChanged,\n];\n\ninterface UseAgentPropsBase {\n updates?: UseAgentUpdate[];\n /**\n * Throttle interval (in milliseconds) for re-renders triggered by\n * `onMessagesChanged` and `onStateChanged` notifications. Useful to reduce\n * re-render frequency during high-frequency streaming updates.\n *\n * Uses a leading+trailing pattern with a shared window — first update\n * fires immediately, subsequent updates within the window are coalesced,\n * and a trailing timer ensures the most recent update fires after the\n * window expires. See `CopilotKitCore.subscribeToAgentWithOptions` in `@copilotkit/core`\n * for details.\n *\n * Resolved as: `throttleMs ?? provider defaultThrottleMs ?? 0`.\n * Passing `throttleMs={0}` explicitly disables throttling even when the\n * provider specifies a non-zero `defaultThrottleMs`.\n *\n * Run lifecycle callbacks (`onRunInitialized`, `onRunFinalized`,\n * `onRunFailed`, `onRunErrorEvent`) always fire immediately.\n *\n * @default undefined\n * When unset, inherits from the provider's `defaultThrottleMs`;\n * if that is also unset, the effective value is `0` (no throttle).\n */\n throttleMs?: number;\n}\n\n/**\n * Thread-scoped variant. `agentId`, `runtimeAgentId`, and `threadId` are a\n * matched set: together they give this hook a *private* agent — registered\n * under the local `agentId`, routing outbound to `runtimeAgentId` — that is\n * safe to pin a thread onto. None of the three is meaningful without the other\n * two, so all are required here.\n */\ninterface UseAgentThreadScopedProps {\n /**\n * The name to register this hook's proxied agent under.\n *\n * Required, and must not already be taken. The usual fallbacks (the chat\n * configuration's agentId, then `DEFAULT_AGENT_ID`) name agents that already\n * exist, and registering over one either throws `already registered` or\n * silently shadows it, depending on whether runtime discovery has landed — so\n * the caller has to name it.\n */\n agentId: string;\n /**\n * Thread to scope the agent's run to. Written onto the underlying agent, so\n * `/agent/run`, `/agent/connect`, and `/agent/stop` address this thread.\n *\n * REQUIRES `runtimeAgentId`. A runtime agent registered under a given id is a\n * singleton, so writing a per-hook threadId directly onto it would let two\n * `useAgent` calls that share an `agentId` clobber each other's thread.\n * Passing a distinct local `agentId` plus the `runtimeAgentId` it routes to\n * gives this hook a private proxied agent to pin the thread onto instead of a\n * shared one.\n */\n threadId: string;\n /**\n * The id of the runtime agent to route outbound requests to, while this hook\n * exposes a distinct local `agentId`. Registers a proxied agent via\n * `CopilotKitCore.registerProxiedAgent`, letting several frontend agents\n * (e.g. one per open thread) mount against a single runtime agent without a\n * shared-singleton collision.\n *\n * When set, `agentId` is the *local* registry id (must not collide with an\n * existing local or runtime-discovered agent) and `runtimeAgentId` is the\n * runtime agent the proxy addresses on `/agent/run` etc.\n *\n * REQUIRES `threadId`. Registering a private agent is only worth doing to\n * scope a thread to it; without a `threadId` the private agent would take its\n * thread from the chat configuration, which is what binding to the shared\n * agent via `agentId` alone already does — just with an extra registration\n * and a local id to keep unique.\n */\n runtimeAgentId: string;\n}\n\n/**\n * Default variant: neither `threadId` nor `runtimeAgentId`. The hook binds to\n * the shared agent registered under `agentId` and leaves its threadId to the\n * chat configuration (or to the agent's own auto-minted UUID).\n *\n * Both props are typed `undefined` here rather than omitted so that supplying\n * either one on its own fails to match *both* branches — that is the\n * type-level enforcement of the all-or-nothing rule.\n */\ninterface UseAgentUnscopedProps {\n /**\n * Agent to bind to. Resolution precedence: this property, then the surrounding\n * chat configuration's agentId, then the global default.\n */\n agentId?: string;\n /** Requires `runtimeAgentId`. See {@link UseAgentThreadScopedProps.threadId}. */\n threadId?: undefined;\n /** Requires `threadId`. See {@link UseAgentThreadScopedProps.runtimeAgentId}. */\n runtimeAgentId?: undefined;\n}\n\n/**\n * Props for {@link useAgent}.\n *\n * There are exactly two valid shapes, and the type admits nothing in between:\n *\n * - **Bind to an agent** — `useAgent()`, `useAgent({ agentId })`. The shared\n * instance from the registry; the thread comes from the chat configuration.\n * - **Bind a private agent to a thread** —\n * `useAgent({ agentId, runtimeAgentId, threadId })`. All three required.\n *\n * So `useAgent({ agentId, threadId })`, `useAgent({ agentId, runtimeAgentId })`,\n * and `useAgent({ runtimeAgentId, threadId })` are all compile errors. Each\n * partial combination is either unsafe (a thread scoped onto a shared singleton)\n * or pointless (a private agent with no thread, or one registered over an id\n * that already belongs to a real agent).\n */\nexport type UseAgentProps = UseAgentPropsBase &\n (UseAgentThreadScopedProps | UseAgentUnscopedProps);\n\nexport function useAgent({\n agentId,\n threadId,\n runtimeAgentId,\n updates,\n throttleMs,\n}: UseAgentProps = {}) {\n // Runtime backstop for the all-or-nothing rule UseAgentProps enforces at\n // compile time (plain JS, `as any`, props widened at a call boundary).\n ɵvalidateAgentBinding({ agentId, threadId, runtimeAgentId });\n\n // Explicit prop, then the surrounding chat configuration (#5533), then the\n // provider default, then DEFAULT_AGENT_ID.\n const chatConfig = useCopilotChatConfiguration();\n const providerAgentId = useDefaultAgentId();\n const resolvedAgentId = ɵresolveAgentId({\n agentId,\n chatAgentId: chatConfig?.agentId,\n providerAgentId,\n });\n\n const { copilotkit } = useCopilotKit();\n const resolver = ɵgetAgentResolver(copilotkit);\n const revision = useSyncExternalStore(\n resolver.subscribe,\n resolver.getSnapshot,\n resolver.getSnapshot,\n );\n // Read the provider-level default so it appears in the effect's dep array.\n // subscribeToAgentWithOptions reads it from the core instance, but React\n // needs the dep to know when to re-subscribe.\n const providerThrottleMs = copilotkit.defaultThrottleMs;\n\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n const updateFlags = useMemo(\n () => updates ?? ALL_UPDATES,\n [JSON.stringify(updates)],\n );\n\n // Thread-scoped path: register a private proxied agent for this hook as one\n // balanced effect (StrictMode-safe: the cleanup unregisters before the\n // remount re-registers). The resolver notifies, so the hook swaps from the\n // provisional stand-in to the real proxy.\n useEffect(() => {\n if (runtimeAgentId == null) return;\n return resolver.bindProxy({ agentId: resolvedAgentId, runtimeAgentId });\n }, [resolver, resolvedAgentId, runtimeAgentId]);\n\n // Keyed on the header generation, not header values: a builder returning a\n // new token on every resolution must not re-resolve (#1937).\n const headersGeneration = copilotkit.ɵheadersGeneration;\n const { agent, isReady } = useMemo(\n () =>\n resolver.resolve({\n agentId: resolvedAgentId,\n runtimeAgentId,\n caller: \"useAgent\",\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n resolver,\n revision,\n resolvedAgentId,\n runtimeAgentId,\n copilotkit.agents,\n copilotkit.runtimeConnectionStatus,\n copilotkit.runtimeUrl,\n copilotkit.runtimeTransport,\n copilotkit.credentials,\n headersGeneration,\n ],\n );\n\n useEffect(\n () =>\n ɵsubscribeToAgentUpdates(copilotkit, agent, {\n updates: updateFlags,\n throttleMs,\n onUpdate: forceUpdate,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [agent, forceUpdate, throttleMs, providerThrottleMs, updateFlags],\n );\n\n // Keep request settings fresh outside useMemo: mutating inside it is unsafe\n // in concurrent mode.\n useEffect(() => {\n resolver.refreshRequestSettings(agent);\n }, [resolver, agent, headersGeneration, copilotkit.credentials]);\n\n // Pin the thread onto the agent. AbstractAgent auto-mints a UUID, so without\n // this the agent ships its own random id in /agent/run, /agent/connect and\n // /agent/stop.\n const resolvedThreadId = ɵresolveAgentThreadId({\n threadId,\n chatThreadId: chatConfig?.threadId,\n chatHasExplicitThreadId: chatConfig?.hasExplicitThreadId,\n });\n useEffect(() => {\n if (!resolvedThreadId) return;\n agent.threadId = resolvedThreadId;\n }, [agent, resolvedThreadId]);\n\n return {\n agent,\n /**\n * Whether `agent` is the real, runtime-synced (or locally-registered) agent\n * rather than a provisional stand-in returned while the runtime is still\n * connecting (or in an error state).\n *\n * `agent` is always a fully-constructed `AbstractAgent`, so calling\n * `agent.subscribe(...)`, `agent.setState(...)`, etc. is always safe. But\n * while `isReady` is `false` the instance is a placeholder that will be\n * swapped for the real agent once the runtime `/info` sync resolves, at\n * which point `agent` changes reference and dependent effects re-run.\n * Guard on `isReady` when you only want to act against the real agent —\n * e.g. subscribing to run-lifecycle events you don't want to miss during\n * the provisional window (#5000).\n */\n isReady,\n };\n}\n","import type { AgentCapabilities } from \"@ag-ui/core\";\nimport { ɵgetAgentCapabilities } from \"@copilotkit/core\";\nimport { useAgent } from \"./use-agent\";\n\n/**\n * Returns the capabilities declared by the given agent (or the agent resolved\n * from the surrounding chat configuration, falling back to the default agent).\n * Capabilities are populated from the runtime `/info` response at connection\n * time. The hook reads them synchronously from the agent instance — there is\n * no separate loading state, but the value will be `undefined` until the\n * runtime handshake completes.\n *\n * @param agentId - Optional agent ID. If omitted, inherits the surrounding\n * chat configuration's agent, falling back to the default agent.\n * @returns The agent's capabilities, or `undefined` if the agent doesn't\n * declare capabilities.\n */\nexport function useCapabilities(\n agentId?: string,\n): AgentCapabilities | undefined {\n const { agent } = useAgent({ agentId });\n return ɵgetAgentCapabilities(agent);\n}\n","import { useCopilotKit } from \"../context\";\nimport { useLayoutEffect, useMemo } from \"react\";\nimport { ɵserializeContextValue } from \"@copilotkit/core\";\nimport type { ɵJsonSerializable } from \"@copilotkit/core\";\n\n/**\n * Represents any value that can be serialized to JSON.\n */\nexport type JsonSerializable = ɵJsonSerializable;\n\n/**\n * Context configuration for useAgentContext.\n * Accepts any value; a value that is not a string is sent as its JSON text.\n */\nexport interface AgentContextInput {\n /** A human-readable description of what this context represents */\n description: string;\n /**\n * The context value. A string is sent as-is; any other value is sent as its\n * JSON text, so it should be JSON-serializable. Interface types and optional\n * fields are accepted.\n */\n value: unknown;\n}\n\nexport function useAgentContext(context: AgentContextInput) {\n const { description, value } = context;\n const { copilotkit } = useCopilotKit();\n\n const stringValue = useMemo(() => ɵserializeContextValue(value), [value]);\n\n useLayoutEffect(() => {\n if (!copilotkit) return;\n\n const id = copilotkit.addContext({ description, value: stringValue });\n return () => {\n copilotkit.removeContext(id);\n };\n }, [description, stringValue, copilotkit]);\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport {\n ɵresolveAgentId,\n ɵsubscribeToAgentSuggestions,\n} from \"@copilotkit/core\";\nimport type { Suggestion } from \"@copilotkit/core\";\nimport { useCopilotKit, useDefaultAgentId } from \"../context\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\n\nexport interface UseSuggestionsOptions {\n agentId?: string;\n}\n\nexport interface UseSuggestionsResult {\n suggestions: Suggestion[];\n reloadSuggestions: () => void;\n clearSuggestions: () => void;\n isLoading: boolean;\n}\n\nexport function useSuggestions({\n agentId,\n}: UseSuggestionsOptions = {}): UseSuggestionsResult {\n const { copilotkit } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const providerAgentId = useDefaultAgentId();\n const resolvedAgentId = useMemo(\n () =>\n ɵresolveAgentId({\n agentId,\n chatAgentId: config?.agentId,\n providerAgentId,\n }),\n [agentId, config?.agentId, providerAgentId],\n );\n\n const [result, setResult] = useState(() =>\n copilotkit.getSuggestions(resolvedAgentId),\n );\n\n useEffect(() => {\n setResult(copilotkit.getSuggestions(resolvedAgentId));\n return ɵsubscribeToAgentSuggestions(copilotkit, resolvedAgentId, setResult);\n }, [copilotkit, resolvedAgentId]);\n\n const reloadSuggestions = useCallback(() => {\n copilotkit.reloadSuggestions(resolvedAgentId);\n // Loading state is handled by onSuggestionsStartedLoading event\n }, [copilotkit, resolvedAgentId]);\n\n const clearSuggestions = useCallback(() => {\n copilotkit.clearSuggestions(resolvedAgentId);\n // State updates are handled by onSuggestionsChanged event\n }, [copilotkit, resolvedAgentId]);\n\n return {\n suggestions: result.suggestions,\n reloadSuggestions,\n clearSuggestions,\n isLoading: result.isLoading,\n };\n}\n","import { useEffect, useRef } from \"react\";\nimport { useCopilotKit, useDefaultAgentId } from \"../context\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { ɵbindSuggestionsConfig, ɵresolveAgentId } from \"@copilotkit/core\";\nimport type {\n ɵSuggestionsBinding,\n ɵSuggestionsConfigInput,\n} from \"@copilotkit/core\";\n\n/**\n * Registers a suggestions configuration (dynamic or static) for the current\n * chat. A global config (no `consumerAgentId`, or `\"*\"`) applies to every\n * agent and loads for the surrounding chat's agent first.\n *\n * Pass `deps` to reload suggestions when values the config reads change.\n *\n * @example\n * useConfigureSuggestions({\n * instructions: \"Suggest concise next steps for the user\",\n * available: \"always\",\n * });\n */\nexport function useConfigureSuggestions(\n config: ɵSuggestionsConfigInput | null | undefined,\n deps?: ReadonlyArray<unknown>,\n): void {\n const { copilotkit } = useCopilotKit();\n const chatConfig = useCopilotChatConfiguration();\n const providerAgentId = useDefaultAgentId();\n const chatAgentId = ɵresolveAgentId({\n chatAgentId: chatConfig?.agentId,\n providerAgentId,\n });\n const extraDeps = deps ?? [];\n\n const bindingRef = useRef<ɵSuggestionsBinding | null>(null);\n const latestRef = useRef({ config, chatAgentId });\n latestRef.current = { config, chatAgentId };\n\n useEffect(() => {\n const latest = latestRef.current;\n const binding = ɵbindSuggestionsConfig(copilotkit, latest.config, {\n chatAgentId: latest.chatAgentId,\n });\n bindingRef.current = binding;\n return () => {\n binding.dispose();\n if (bindingRef.current === binding) bindingRef.current = null;\n };\n }, [copilotkit]);\n\n // The binding compares configs by content, so a new inline object on every\n // render is a no-op.\n useEffect(() => {\n bindingRef.current?.update(config, { chatAgentId });\n }, [config, chatAgentId]);\n\n const depsMountedRef = useRef(false);\n useEffect(() => {\n if (!depsMountedRef.current) {\n depsMountedRef.current = true;\n return;\n }\n if (extraDeps.length > 0) bindingRef.current?.reload();\n }, [extraDeps.length, ...extraDeps]);\n}\n","import React, {\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport type { Interrupt } from \"@ag-ui/client\";\nimport { ɵInterruptController } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport { useAgent } from \"./use-agent\";\nimport type {\n InterruptEvent,\n InterruptRenderProps,\n InterruptHandlerProps,\n} from \"../types/interrupt\";\n\nexport type {\n InterruptEvent,\n InterruptRenderProps,\n InterruptHandlerProps,\n Interrupt,\n};\n\ntype InterruptHandlerFn<TValue, TResult> = (\n props: InterruptHandlerProps<TValue>,\n) => TResult | PromiseLike<TResult>;\n\ntype InterruptResultFromHandler<THandler> = THandler extends (\n ...args: never[]\n) => infer TResult\n ? TResult extends PromiseLike<infer TResolved>\n ? TResolved | null\n : TResult | null\n : null;\n\ntype InterruptResult<TValue, TResult> = InterruptResultFromHandler<\n InterruptHandlerFn<TValue, TResult>\n>;\n\ntype InterruptRenderInChat = boolean | undefined;\n\ntype UseInterruptReturn<TRenderInChat extends InterruptRenderInChat> =\n TRenderInChat extends false\n ? React.ReactElement | null\n : TRenderInChat extends true | undefined\n ? void\n : React.ReactElement | null | void;\n\n/**\n * Configuration options for `useInterrupt`.\n */\ninterface UseInterruptConfigBase<TValue = unknown, TResult = never> {\n /**\n * Render function for the interrupt UI.\n *\n * Receives both the standard `interrupt`/`interrupts` and the legacy `event`.\n * Call `resolve(payload)` to resume with user input, or `cancel()` to cancel.\n */\n render: (\n props: InterruptRenderProps<TValue, InterruptResult<TValue, TResult>>,\n ) => React.ReactElement;\n /**\n * Optional pre-render handler invoked when an interrupt is received.\n * Return a sync or async value to expose as `result` in `render`.\n * Rejecting/throwing falls back to `result = null`.\n */\n handler?: InterruptHandlerFn<TValue, TResult>;\n /**\n * Optional predicate to filter which interrupts this hook handles.\n * Receives the legacy-compatible event (for standard interrupts, `value` is\n * the primary `Interrupt`). Return `false` to ignore.\n */\n enabled?: (event: InterruptEvent<TValue>) => boolean;\n /** Optional agent id. Defaults to the current configured chat agent. */\n agentId?: string;\n}\n\nexport interface UseInterruptInChatConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. */\n renderInChat?: true;\n}\n\nexport interface UseInterruptExternalConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** When false, the hook returns the interrupt element so you can place it yourself. */\n renderInChat: false;\n}\n\nexport interface UseInterruptDynamicConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** Dynamic boolean mode. When non-literal, return type is a union. */\n renderInChat: boolean;\n}\n\nexport type UseInterruptConfig<\n TValue = unknown,\n TResult = never,\n TRenderInChat extends InterruptRenderInChat = undefined,\n> = UseInterruptConfigBase<TValue, TResult> & {\n /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. */\n renderInChat?: TRenderInChat;\n};\n\n/**\n * Handles agent interrupts with optional filtering, preprocessing, and resume behavior.\n *\n * Supports both the AG-UI standard interrupt flow (`RUN_FINISHED` with\n * `outcome.type === \"interrupt\"`) and the legacy custom-event flow\n * (`on_interrupt`). For standard interrupts, `render` receives `interrupt`\n * (the primary one) and `interrupts` (the full open set); call `resolve(payload)`\n * to resume or `cancel()` to cancel. Resuming addresses the targeted interrupt\n * and, once every open interrupt is addressed, submits a single spec `resume`\n * array via `copilotkit.runAgent`.\n *\n * - `renderInChat: true` (default): the element is published into `<CopilotChat>`; returns `void`.\n * - `renderInChat: false`: the hook returns the interrupt element for manual placement.\n *\n * @example\n * ```tsx\n * useInterrupt({\n * render: ({ interrupt, resolve, cancel }) => (\n * <div>\n * <p>{interrupt?.message}</p>\n * <button onClick={() => resolve({ approved: true })}>Approve</button>\n * <button onClick={() => cancel()}>Cancel</button>\n * </div>\n * ),\n * });\n * ```\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport function useInterrupt<\n TResult = never,\n TRenderInChat extends InterruptRenderInChat = undefined,\n>(\n config: UseInterruptConfig<any, TResult, TRenderInChat>,\n): UseInterruptReturn<TRenderInChat> {\n /* eslint-enable @typescript-eslint/no-explicit-any */\n const { copilotkit } = useCopilotKit();\n const { agent } = useAgent({ agentId: config.agentId, updates: [] });\n\n // Read consumer callbacks through refs so inline lambdas neither recreate\n // the controller nor churn the element memo.\n const renderRef = useRef(config.render);\n renderRef.current = config.render;\n const enabledRef = useRef(config.enabled);\n enabledRef.current = config.enabled;\n const handlerRef = useRef(config.handler);\n handlerRef.current = config.handler;\n const copilotkitRef = useRef(copilotkit);\n copilotkitRef.current = copilotkit;\n\n const [controller] = useState(\n () =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new ɵInterruptController<any, TResult>(\n { runAgent: (params) => copilotkitRef.current.runAgent(params) },\n {\n enabled: (event) => enabledRef.current?.(event) ?? true,\n handler: (props) =>\n handlerRef.current ? handlerRef.current(props) : (null as TResult),\n },\n ),\n );\n\n useEffect(() => {\n controller.connect(agent);\n return () => controller.disconnect();\n }, [controller, agent]);\n\n const { renderProps } = useSyncExternalStore(\n controller.subscribe,\n controller.getSnapshot,\n controller.getSnapshot,\n );\n\n const element = useMemo(\n () => (renderProps ? renderRef.current(renderProps) : null),\n [renderProps],\n );\n\n // Publish to core for in-chat rendering. Publish-only.\n useEffect(() => {\n if (config.renderInChat === false) return;\n copilotkit.setInterruptElement(element);\n }, [element, config.renderInChat, copilotkit]);\n\n // Nullify on true unmount only.\n useEffect(() => {\n if (config.renderInChat === false) return;\n return () => {\n copilotkit.setInterruptElement(null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n if (config.renderInChat === false) {\n return element as UseInterruptReturn<TRenderInChat>;\n }\n\n return undefined as UseInterruptReturn<TRenderInChat>;\n}\n","import { useCopilotKit } from \"../context\";\nimport { ɵThreadsController, ɵcreateThreadStore } from \"@copilotkit/core\";\nimport type { ɵThreadSummary } from \"@copilotkit/core\";\nimport { useEffect, useState, useSyncExternalStore } from \"react\";\n\n/**\n * A conversation thread managed by CopilotKit Intelligence.\n *\n * Each thread has a unique `id`, an optional human-readable `name`, and\n * ISO-8601 `createdAt` and `updatedAt` timestamps. `lastRunAt` is the time of\n * the most recent agent run, absent when the thread has never run; prefer it\n * over `updatedAt` for \"last activity\", since rename and archive do not bump\n * it. The shape is core's thread summary, which Angular also exposes.\n */\nexport type Thread = ɵThreadSummary;\n\n/**\n * Configuration for the {@link useThreads} hook.\n *\n * Thread operations are scoped to the runtime-authenticated user and the\n * provided agent on CopilotKit Intelligence.\n */\nexport interface UseThreadsInput {\n /** The ID of the agent whose threads to list and manage. */\n agentId: string;\n /** When `true`, archived threads are included in the list. Defaults to `false`. */\n includeArchived?: boolean;\n /** Maximum number of threads to fetch per page. When set, enables cursor-based pagination. */\n limit?: number;\n /**\n * When `false`, the hook stays inert: no runtime context is dispatched, so\n * NO thread-list fetch or realtime subscription is issued. Used by gated\n * surfaces (e.g. an unlicensed `<CopilotThreadsDrawer>`) that must not touch the\n * network until the gate opens. Defaults to `true`.\n *\n * Flipping `enabled` back to `true` resumes normal fetching on the next\n * effect run; mutations are likewise short-circuited while disabled.\n */\n enabled?: boolean;\n}\n\n/**\n * Return value of the {@link useThreads} hook.\n *\n * The `threads` array is kept in sync with the platform via a realtime\n * WebSocket subscription (when available) and is sorted most-recently-updated\n * first. Mutations reject with an `Error` if the platform request fails.\n */\nexport interface UseThreadsResult {\n /**\n * Threads for the current user/agent pair, sorted by most recently\n * updated first. Updated in realtime when the platform pushes metadata\n * events. Includes archived threads only when `includeArchived` is set.\n */\n threads: Thread[];\n /**\n * `true` while the initial thread list is being fetched from the platform.\n * Subsequent realtime updates do not re-enter the loading state.\n */\n isLoading: boolean;\n /**\n * The most recent error from fetching threads or executing a mutation,\n * or `null` when there is no error. Reset to `null` on the next\n * successful fetch.\n *\n * This channel folds together developer/config errors (missing runtime URL,\n * runtime without thread endpoints) and genuine list-load/mutation failures.\n * End-user surfaces that must not leak config errors should prefer\n * {@link listError}, which excludes the config/runtime-setup errors.\n */\n error: Error | null;\n /**\n * The most recent genuine list-load or mutation error from the platform, or\n * `null`. Unlike {@link error}, this EXCLUDES developer/config errors (a\n * missing runtime URL, or a runtime that does not advertise thread\n * endpoints), so an end-user surface can render it directly without leaking\n * a developer-facing configuration message into the UI. It does report a\n * runtime that refuses to list threads because the caller has no identity\n * (no `identifyUser`), since the list cannot load until that is set.\n */\n listError: Error | null;\n /**\n * The error from the most recent FAILED next-page (fetch-more) load, or\n * `null`. Tracked separately from {@link listError} so a paginated-load\n * failure surfaces an inline \"couldn't load more\" affordance while the\n * already-loaded list stays visible. Cleared when a fetch-more is retried or\n * succeeds.\n */\n fetchMoreError: Error | null;\n /**\n * `true` when there are more threads available to fetch via\n * {@link fetchMoreThreads}. Only meaningful when `limit` is set.\n */\n hasMoreThreads: boolean;\n /**\n * `true` while a subsequent page of threads is being fetched.\n */\n isFetchingMoreThreads: boolean;\n /**\n * `true` while at least one thread mutation (rename, archive, unarchive,\n * delete) is awaiting a server response. Mutations apply optimistically, so\n * this is primarily useful for disabling controls or showing a subtle\n * in-flight indicator.\n */\n isMutating: boolean;\n /**\n * Fetch the next page of threads. No-op when {@link hasMoreThreads} is\n * `false` or a fetch is already in progress.\n */\n fetchMoreThreads: () => void;\n /**\n * Re-fetch the thread list from the platform without clearing the current\n * list. Backs the drawer's error-state Retry and the Active/All filter\n * refetch. No-op until the runtime is connected.\n */\n refetchThreads: () => void;\n /**\n * Reset to a fresh, non-explicit client-side thread so the welcome screen\n * shows. Lazy creation: no row appears in {@link threads} until the new\n * thread's first run persists server-side.\n */\n startNewThread: () => void;\n /**\n * Rename a thread on the platform.\n * Resolves when the server confirms the update; rejects on failure.\n */\n renameThread: (threadId: string, name: string) => Promise<void>;\n /**\n * Archive a thread on the platform.\n * Archived threads are excluded from subsequent list results.\n * Resolves when the server confirms the update; rejects on failure.\n */\n archiveThread: (threadId: string) => Promise<void>;\n /**\n * Restore a previously archived thread on the platform.\n * The thread re-appears in default (non-archived) list results.\n * Resolves when the server confirms the update; rejects on failure.\n */\n unarchiveThread: (threadId: string) => Promise<void>;\n /**\n * Permanently delete a thread from the platform.\n * This is irreversible. Resolves when the server confirms deletion;\n * rejects on failure.\n */\n deleteThread: (threadId: string) => Promise<void>;\n}\n\n/**\n * React hook for listing and managing CopilotKit Intelligence threads.\n *\n * On mount the hook fetches the thread list for the runtime-authenticated user\n * and the given `agentId`. When CopilotKit Intelligence exposes a WebSocket\n * URL, it also opens a realtime subscription so the `threads` array stays\n * current without polling — thread creates, renames, archives, and deletes\n * from any client are reflected immediately.\n *\n * Mutation methods (`renameThread`, `archiveThread`, `unarchiveThread`,\n * `deleteThread`) return promises that resolve once the platform confirms the\n * operation and reject with an `Error` on failure.\n *\n * @param input - Agent identifier and optional list controls.\n * @returns Thread list state and stable mutation callbacks.\n *\n * @example\n * ```tsx\n * import { useThreads } from \"@copilotkit/react-core\";\n *\n * function ThreadList() {\n * const { threads, isLoading, renameThread, deleteThread } = useThreads({\n * agentId: \"agent-1\",\n * });\n *\n * if (isLoading) return <p>Loading…</p>;\n *\n * return (\n * <ul>\n * {threads.map((t) => (\n * <li key={t.id}>\n * {t.name ?? \"Untitled\"}\n * <button onClick={() => renameThread(t.id, \"New name\")}>Rename</button>\n * <button onClick={() => deleteThread(t.id)}>Delete</button>\n * </li>\n * ))}\n * </ul>\n * );\n * }\n * ```\n */\nexport function useThreads({\n agentId,\n includeArchived,\n limit,\n enabled = true,\n}: UseThreadsInput): UseThreadsResult {\n const { copilotkit } = useCopilotKit();\n\n // Core's ɵThreadsController owns the view model: thread projection, the\n // configuration errors, the gated and de-duplicated context dispatch, the\n // registry claim and the mutation guard. This hook feeds it and renders it.\n const [controller] = useState(\n () =>\n new ɵThreadsController(\n ɵcreateThreadStore({ fetch: copilotkit.ɵruntimeFetch }),\n { core: copilotkit, agentId, includeArchived, limit, enabled },\n ),\n );\n const {\n threads,\n isLoading,\n error,\n listError,\n fetchMoreError,\n hasMoreThreads,\n isFetchingMoreThreads,\n isMutating,\n } = useSyncExternalStore(\n controller.subscribe,\n controller.getSnapshot,\n controller.getServerSnapshot,\n );\n\n useEffect(() => controller.start(), [controller]);\n\n useEffect(() => {\n controller.update({\n core: copilotkit,\n agentId,\n includeArchived,\n limit,\n enabled,\n });\n }, [\n controller,\n copilotkit,\n agentId,\n includeArchived,\n limit,\n enabled,\n copilotkit.runtimeUrl,\n copilotkit.runtimeConnectionStatus,\n copilotkit.ɵheadersGeneration,\n copilotkit.intelligence?.wsUrl,\n copilotkit.threadEndpoints?.list,\n copilotkit.threadEndpoints?.mutations,\n ]);\n\n const {\n fetchMoreThreads,\n refetchThreads,\n startNewThread,\n renameThread,\n archiveThread,\n unarchiveThread,\n deleteThread,\n } = controller;\n\n return {\n threads,\n isLoading,\n error,\n listError,\n fetchMoreError,\n hasMoreThreads,\n isFetchingMoreThreads,\n isMutating,\n fetchMoreThreads,\n refetchThreads,\n startNewThread,\n renameThread,\n archiveThread,\n unarchiveThread,\n deleteThread,\n };\n}\n","import { useCopilotKit } from \"../context\";\nimport {\n ɵselectMemories,\n ɵselectMemoriesError,\n ɵselectMemoriesIsLoading,\n ɵselectMemoriesAvailable,\n ɵselectMemoriesRealtimeStatus,\n} from \"@copilotkit/core\";\nimport type {\n Memory,\n MemoryChanges,\n MemoryRealtimeStatus,\n ɵMemoryStore,\n NewMemory,\n} from \"@copilotkit/core\";\nimport { useCallback, useSyncExternalStore } from \"react\";\n\n/**\n * Return value of the {@link useMemories} hook.\n *\n * The `memories` array is the server-authoritative list for the current user.\n * It is hydrated from a REST snapshot and kept current by realtime\n * `memory_metadata` deltas from the store's own channel. Mutations resolve\n * once the platform confirms the operation and reject with an `Error` on\n * failure.\n */\nexport interface UseMemoriesResult {\n /**\n * Memories for the current user, newest first. Updated in realtime when\n * the platform pushes `memory_metadata` events.\n */\n memories: Memory[];\n /**\n * `true` while the initial memory snapshot is being fetched. Subsequent\n * realtime updates do not re-enter the loading state.\n */\n isLoading: boolean;\n /**\n * The most recent error from fetching memories or executing a mutation, or\n * `null` when there is no error. Cleared on the next fetch attempt, on a\n * successful fetch, when the runtime context changes, and on a successful\n * mutation (a failed mutation replaces it with that mutation's error).\n */\n error: Error | null;\n /**\n * `true` when the platform memory routes are available. Set to `false`\n * after a 404 or 501, indicating memory is not supported by the current\n * runtime configuration.\n */\n isAvailable: boolean;\n /**\n * Health of the realtime connection that streams live `memory_metadata`\n * deltas. Distinct from `isAvailable`/`error` (which describe the REST list\n * route): `\"connecting\"` while the socket opens/joins, `\"connected\"` once\n * live deltas are flowing, and `\"unavailable\"` once the socket permanently\n * gives up — at which point the list is a frozen snapshot. Lets the UI drop a\n * \"live\" indicator instead of showing it over stale data.\n */\n realtimeStatus: MemoryRealtimeStatus;\n /**\n * Re-fetch the memory snapshot from the platform. Resolves once the re-pull\n * settles; rejects if it fails or the store is torn down mid-flight.\n */\n refresh: () => Promise<void>;\n /**\n * Create a memory. Resolves to the stored memory (server-authoritative);\n * rejects on failure.\n */\n addMemory: (input: NewMemory) => Promise<Memory>;\n /**\n * Supersede a memory: the old memory is retired and a new one is created.\n * Resolves to the new memory (its `id` differs from `id`); rejects on\n * failure.\n *\n * Supersede is a FULL replacement, not a partial patch: `changes` is the\n * complete definition of the new memory. You must re-supply `content` and\n * `kind`, and an omitted `sourceThreadIds` resets the new memory's source\n * threads to empty — it does not preserve the prior memory's value.\n */\n updateMemory: (id: string, changes: MemoryChanges) => Promise<Memory>;\n /**\n * Retire a memory (non-lossy delete). Resolves when the server confirms;\n * rejects on failure.\n */\n removeMemory: (id: string) => Promise<void>;\n}\n\nfunction useMemoryStoreSelector<T>(\n store: ɵMemoryStore,\n selector: (state: ReturnType<ɵMemoryStore[\"getState\"]>) => T,\n): T {\n return useSyncExternalStore(\n useCallback(\n (onStoreChange) => {\n const subscription = store.select(selector).subscribe(onStoreChange);\n return () => subscription.unsubscribe();\n },\n [store, selector],\n ),\n () => selector(store.getState()),\n // getServerSnapshot: without this third argument React throws\n // \"Missing getServerSnapshot\" during SSR/prerender (e.g. Next.js). The\n // store has no client data while prerendering, so we project from its\n // stable server state.\n () => selector(store.getServerState()),\n );\n}\n\n/**\n * React hook for listing and managing platform memories.\n *\n * Reads the memory store owned and wired by `CopilotKitCore`. On mount the\n * hook exposes the live list plus stable `addMemory` / `updateMemory` /\n * `removeMemory` / `refresh` callbacks. Mutations are server-authoritative:\n * each resolves once the platform confirms the operation and rejects with an\n * `Error` on failure.\n *\n * Realtime updates are automatic: the core's memory store opens its own\n * `user_meta:memories:<joinCode>` channel and applies `memory_metadata` deltas\n * to the list. You can still call `refresh()` to re-pull the REST snapshot on\n * demand.\n *\n * @returns Memory list state and stable mutation callbacks.\n *\n * @example\n * ```tsx\n * import { useMemories } from \"@copilotkit/react-core\";\n *\n * function MemoryList() {\n * const { memories, isLoading, isAvailable, addMemory, removeMemory } =\n * useMemories();\n *\n * if (!isAvailable) return null;\n * if (isLoading) return <p>Loading…</p>;\n *\n * return (\n * <ul>\n * {memories.map((m) => (\n * <li key={m.id}>\n * {m.content}\n * <button onClick={() => removeMemory(m.id)}>Delete</button>\n * </li>\n * ))}\n * </ul>\n * );\n * }\n * ```\n */\nexport function useMemories(): UseMemoriesResult {\n const { copilotkit } = useCopilotKit();\n\n const store = copilotkit.getMemoryStore();\n\n const memories = useMemoryStoreSelector(store, ɵselectMemories);\n const isLoading = useMemoryStoreSelector(store, ɵselectMemoriesIsLoading);\n const error = useMemoryStoreSelector(store, ɵselectMemoriesError);\n const isAvailable = useMemoryStoreSelector(store, ɵselectMemoriesAvailable);\n const realtimeStatus = useMemoryStoreSelector(\n store,\n ɵselectMemoriesRealtimeStatus,\n );\n\n const refresh = useCallback(() => store.refresh(), [store]);\n const addMemory = useCallback(\n (input: NewMemory) => store.addMemory(input),\n [store],\n );\n const updateMemory = useCallback(\n (id: string, changes: MemoryChanges) => store.updateMemory(id, changes),\n [store],\n );\n const removeMemory = useCallback(\n (id: string) => store.removeMemory(id),\n [store],\n );\n\n return {\n memories,\n isLoading,\n error,\n isAvailable,\n realtimeStatus,\n refresh,\n addMemory,\n updateMemory,\n removeMemory,\n };\n}\n","import { useCallback } from \"react\";\nimport { useCopilotKit } from \"../context\";\nimport {\n ɵbuildLearnFromUserActionPayload,\n ɵrecordAnnotation,\n} from \"@copilotkit/core\";\n\n/**\n * Input to {@link UseLearnFromUserActionRecorder}, the function returned\n * by {@link useLearnFromUserAction}. Captures a single UI interaction that\n * CopilotKit Intelligence's auto-curated knowledge base loop will distill\n * into the team's `/project` notes.\n */\nexport interface LearnFromUserActionInput {\n /** Thread the action is associated with. May be unknown to the platform. */\n threadId: string;\n /** Short, agent-readable summary of what the user did. Optional. */\n title?: string | null;\n /** Optional longer explanation. */\n description?: string | null;\n /** Free-form, JSON-serializable snapshot describing the action. Optional. */\n data?: unknown;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n /**\n * Caller-supplied idempotency key. When omitted, `ɵrecordAnnotation` generates a\n * fresh UUID per call so retries collapse to the original row at the\n * platform. Supply your own to keep a single semantic event idempotent\n * across calls (e.g. a React re-render or a manual retry button).\n */\n clientEventId?: string;\n}\n\n/** Outcome returned by the recorder function. */\nexport interface LearnFromUserActionResult {\n /** Platform-assigned id of the user-action row. */\n id: string;\n /** True when the platform recognized this `clientEventId` as a retry. */\n duplicate: boolean;\n}\n\n/** Recorder function returned by {@link useLearnFromUserAction}. */\nexport type UseLearnFromUserActionRecorder = (\n input: LearnFromUserActionInput,\n) => Promise<LearnFromUserActionResult>;\n\n/**\n * Record a user UI interaction in CopilotKit Intelligence's user-actions\n * stream. The platform's auto-curated knowledge base agent reads these\n * (alongside finished agent runs) and writes free-form Obsidian-flavored\n * markdown to `/project`, where any agent in the same project can later\n * read it via the `copilotkit_knowledge_base_shell` MCP tool.\n *\n * The hook returns a stable function. Calling it issues a request to the\n * customer's CopilotKit runtime (`POST ${runtimeUrl}/annotate`), which\n * resolves the Intel user from the BFF's auth and forwards to the\n * platform — the Intel API key never reaches the browser.\n *\n * If `clientEventId` is omitted `recordAnnotation` generates a UUID per call,\n * so a naive double-call (e.g. React 18 strict-mode double-mount, or a retry\n * after a network blip on a fresh Promise) is naturally safe. Supply your\n * own key when a single semantic event must remain idempotent across\n * multiple `learnFromUserAction(...)` calls.\n *\n * @example\n * ```tsx\n * import { useLearnFromUserAction } from \"@copilotkit/react-core\";\n *\n * function SettingsPage({ threadId }) {\n * const learnFromUserAction = useLearnFromUserAction();\n *\n * const onRename = (oldName: string, newName: string) => {\n * void learnFromUserAction({\n * threadId,\n * title: \"Renamed project\",\n * data: { previous: { name: oldName }, next: { name: newName } },\n * });\n * };\n * }\n * ```\n */\nexport function useLearnFromUserAction(): UseLearnFromUserActionRecorder {\n const { copilotkit } = useCopilotKit();\n\n return useCallback(\n async (\n input: LearnFromUserActionInput,\n ): Promise<LearnFromUserActionResult> => {\n const runtimeUrl = copilotkit.runtimeUrl;\n if (!runtimeUrl) {\n throw new Error(\n \"useLearnFromUserAction: runtimeUrl is not configured. Set it on <CopilotKitProvider runtimeUrl=...>.\",\n );\n }\n\n return ɵrecordAnnotation({\n fetch: copilotkit.ɵruntimeFetch,\n runtimeUrl,\n // ɵruntimeFetch already resolves and overlays the current core\n // headers at send time (#1937); no snapshot to pass here.\n headers: {},\n type: \"user_action\",\n payload: ɵbuildLearnFromUserActionPayload(input),\n threadId: input.threadId,\n clientEventId: input.clientEventId,\n occurredAt: input.occurredAt,\n });\n },\n [copilotkit],\n );\n}\n","import { useCallback } from \"react\";\nimport { useCopilotChatConfiguration } from \"../providers\";\nimport type {\n LearnFromUserActionInput,\n LearnFromUserActionResult,\n} from \"./use-learn-from-user-action\";\nimport { useLearnFromUserAction } from \"./use-learn-from-user-action\";\n\n/**\n * Input to {@link UseLearnFromUserActionInCurrentThreadRecorder} — same as\n * {@link LearnFromUserActionInput} minus `threadId`, which is sourced from\n * the surrounding `<CopilotChatConfigurationProvider>` at call time.\n */\nexport type LearnFromUserActionInCurrentThreadInput = Omit<\n LearnFromUserActionInput,\n \"threadId\"\n>;\n\n/** Recorder function returned by {@link useLearnFromUserActionInCurrentThread}. */\nexport type UseLearnFromUserActionInCurrentThreadRecorder = (\n input: LearnFromUserActionInCurrentThreadInput,\n) => Promise<LearnFromUserActionResult>;\n\n/**\n * Record a user UI interaction against the **current chat's** thread. The\n * `threadId` is sourced from the surrounding\n * `<CopilotChatConfigurationProvider>` (the same provider `<CopilotChat>`,\n * `<CopilotSidebar>`, and friends set up), so callers in a chat-aware\n * subtree don't need to thread an id through manually.\n *\n * Throws on **call** (not on mount) when there is no chat-config provider\n * in scope — matches the \"throw on call when runtimeUrl is missing\"\n * behavior of {@link useLearnFromUserAction}. Mounting the hook in a branch\n * that never fires is harmless.\n *\n * The recorder does NOT accept a `threadId` override. If you need to\n * record against an explicit thread, use {@link useLearnFromUserAction}\n * directly — two hooks, two crisp contracts, no mode confusion.\n *\n * This hook always uses `config.threadId`, regardless of whether the\n * surrounding chat config minted it internally or received one from\n * the caller. Auto-minted threads simply mean the action lands under\n * a thread the platform never saw — the writer agent still distills\n * user-action-only threads (it does not require the thread to exist\n * in `cpki.threads`), so the loop keeps learning.\n *\n * @example\n * ```tsx\n * import { useLearnFromUserActionInCurrentThread } from \"@copilotkit/react-core\";\n *\n * function SettingsPanel() {\n * const learnFromUserAction = useLearnFromUserActionInCurrentThread();\n *\n * const onRename = (oldName: string, newName: string) => {\n * void learnFromUserAction({\n * title: \"Renamed project\",\n * data: { previous: { name: oldName }, next: { name: newName } },\n * });\n * };\n *\n * // ...\n * }\n * ```\n */\nexport function useLearnFromUserActionInCurrentThread(): UseLearnFromUserActionInCurrentThreadRecorder {\n const config = useCopilotChatConfiguration();\n const learnFromUserAction = useLearnFromUserAction();\n\n return useCallback(\n async (\n input: LearnFromUserActionInCurrentThreadInput,\n ): Promise<LearnFromUserActionResult> => {\n const threadId = config?.threadId;\n if (!threadId) {\n throw new Error(\n \"useLearnFromUserActionInCurrentThread: no CopilotChatConfigurationProvider in scope. \" +\n \"Wrap the call site in <CopilotChat>, <CopilotSidebar>, or <CopilotChatConfigurationProvider>, \" +\n \"or use `useLearnFromUserAction()` and pass `threadId` explicitly.\",\n );\n }\n return learnFromUserAction({ ...input, threadId });\n },\n [config?.threadId, learnFromUserAction],\n );\n}\n","import React, {\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { ɵAttachmentQueue } from \"@copilotkit/core\";\nimport type { Attachment, AttachmentsConfig } from \"@copilotkit/shared\";\n\nexport interface UseAttachmentsProps {\n config?: AttachmentsConfig;\n}\n\nexport interface UseAttachmentsReturn {\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n enabled: boolean;\n /** Whether the user is dragging a file over the drop zone. */\n dragOver: boolean;\n /** Ref for the hidden file input element. */\n fileInputRef: React.RefObject<HTMLInputElement | null>;\n /** Ref for the container element (used for scoped paste handling). */\n containerRef: React.RefObject<HTMLDivElement | null>;\n /** Process an array of files (validate, upload, add to state). No-op while attachments are disabled. */\n processFiles: (files: File[]) => Promise<void>;\n /** Handler for `<input type=\"file\" onChange>`. */\n handleFileUpload: (e: React.ChangeEvent<HTMLInputElement>) => Promise<void>;\n /** Handler for `onDragOver` on the drop zone. */\n handleDragOver: (e: React.DragEvent) => void;\n /** Handler for `onDragLeave` on the drop zone. */\n handleDragLeave: (e: React.DragEvent) => void;\n /** Handler for `onDrop` on the drop zone. */\n handleDrop: (e: React.DragEvent) => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /**\n * Consume ready attachments and clear the queue.\n * Returns the attachments that were ready; resets the file input.\n * No-ops if the queue is already empty (no state update triggered).\n */\n consumeAttachments: () => Attachment[];\n}\n\n/**\n * Hook that manages file attachment state — uploads, drag-and-drop, paste,\n * and lifecycle. The queue itself (validation, uploads, ready state) lives in\n * `@copilotkit/core`'s `ɵAttachmentQueue`; this hook adds the DOM wiring. All\n * returned callbacks are referentially stable across renders.\n */\nexport function useAttachments({\n config,\n}: UseAttachmentsProps): UseAttachmentsReturn {\n const enabled = config?.enabled ?? false;\n\n const [dragOver, setDragOver] = useState(false);\n const fileInputRef = useRef<HTMLInputElement>(null);\n const containerRef = useRef<HTMLDivElement>(null);\n\n // Keep a ref to the latest config so the queue and stable callbacks read it\n // without appearing in dependency arrays.\n const configRef = useRef(config);\n configRef.current = config;\n\n const [queue] = useState(() => new ɵAttachmentQueue(() => configRef.current));\n const attachments = useSyncExternalStore(\n useCallback((onChange) => queue.subscribe(onChange), [queue]),\n () => queue.getSnapshot(),\n () => queue.getSnapshot(),\n );\n\n const processFiles = useCallback(\n (files: File[]) => queue.processFiles(files),\n [queue],\n );\n\n const processSafely = useCallback(\n async (files: File[], label: string) => {\n try {\n await queue.processFiles(files);\n } catch (error) {\n console.error(`[CopilotKit] ${label}:`, error);\n }\n },\n [queue],\n );\n\n const handleFileUpload = useCallback(\n async (e: React.ChangeEvent<HTMLInputElement>) => {\n const input = e.target;\n if (!input.files?.length) return;\n await processSafely(Array.from(input.files), \"Upload error\");\n // Clear the picker so choosing the same file again fires `change`.\n input.value = \"\";\n },\n [processSafely],\n );\n\n const handleDragOver = useCallback((e: React.DragEvent) => {\n if (!configRef.current?.enabled) return;\n e.preventDefault();\n e.stopPropagation();\n setDragOver(true);\n }, []);\n\n const handleDragLeave = useCallback((e: React.DragEvent) => {\n e.preventDefault();\n e.stopPropagation();\n setDragOver(false);\n }, []);\n\n const handleDrop = useCallback(\n async (e: React.DragEvent) => {\n e.preventDefault();\n e.stopPropagation();\n setDragOver(false);\n const files = Array.from(e.dataTransfer.files);\n if (files.length > 0) await processSafely(files, \"Drop error\");\n },\n [processSafely],\n );\n\n // Clipboard paste handler — scoped to the container\n useEffect(() => {\n if (!enabled) return;\n\n const handlePaste = async (e: ClipboardEvent) => {\n const target = e.target;\n if (!(target instanceof Node) || !containerRef.current?.contains(target))\n return;\n const files = queue.filterPastedFiles(\n Array.from(e.clipboardData?.items ?? []),\n );\n if (files.length === 0) return;\n e.preventDefault();\n await processSafely(files, \"Paste error\");\n };\n\n // handlePaste catches and logs its own failures, so it never rejects.\n const onPaste = (e: ClipboardEvent) => {\n void handlePaste(e);\n };\n document.addEventListener(\"paste\", onPaste);\n return () => document.removeEventListener(\"paste\", onPaste);\n }, [enabled, queue, processSafely]);\n\n const removeAttachment = useCallback(\n (id: string) => queue.remove(id),\n [queue],\n );\n\n const consumeAttachments = useCallback(() => {\n const ready = queue.consumeReady();\n if (ready.length > 0 && fileInputRef.current) {\n fileInputRef.current.value = \"\";\n }\n return ready;\n }, [queue]);\n\n return {\n attachments,\n enabled,\n dragOver,\n fileInputRef,\n containerRef,\n processFiles,\n handleFileUpload,\n handleDragOver,\n handleDragLeave,\n handleDrop,\n removeAttachment,\n consumeAttachments,\n };\n}\n","import { createContext } from \"react\";\nimport type { ɵToolCallDisplayContextValue } from \"@copilotkit/core\";\n\n/**\n * Handed down by the message view so each message's tool calls and text can\n * follow the view's `toolCallDisplay` without every layer passing it along.\n * @internal\n */\nexport type ToolCallDisplayContextValue = ɵToolCallDisplayContextValue;\n\n/** @internal */\nexport const ToolCallDisplayContext =\n createContext<ToolCallDisplayContextValue | null>(null);\n","import React, {\n useCallback,\n useContext,\n useMemo,\n useSyncExternalStore,\n} from \"react\";\nimport type { AssistantMessage, Message, ToolMessage } from \"@ag-ui/core\";\nimport { useRenderToolCall } from \"../../hooks\";\nimport { useCopilotKit } from \"../../context\";\nimport { useToolCallRendererNames } from \"../../hooks/use-render-tool-call\";\nimport type { SlotValue } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport {\n Collapsible,\n CopilotChatToolCallGroup,\n ToolCallGroupContext,\n} from \"./CopilotChatToolCallGroup\";\nimport { ToolCallDisplayContext } from \"./tool-call-display-context\";\nimport {\n ɵgetToolCallGroupState,\n ɵgetToolCallLayouts,\n ɵtoolCallAppearance,\n} from \"@copilotkit/core\";\nimport type {\n CopilotChatToolCallDisplay,\n ToolCallEntry,\n} from \"@copilotkit/core\";\n\nexport type CopilotChatToolCallsViewProps = {\n message: AssistantMessage;\n messages?: Message[];\n /**\n * How to show the calls (see `CopilotChatToolCallDisplay`). Inside a message\n * view it follows the view's `toolCallDisplay`; on its own it defaults to\n * `\"grouped\"`.\n */\n display?: CopilotChatToolCallDisplay;\n /**\n * Draws a group of calls made in a row: a component, a class name for the\n * default group, or props for it (e.g. `{ appearance: \"line\" }`).\n */\n group?: SlotValue<typeof CopilotChatToolCallGroup>;\n};\n\nexport function CopilotChatToolCallsView({\n message,\n messages = [],\n display: displayProp,\n group,\n}: CopilotChatToolCallsViewProps) {\n const renderToolCall = useRenderToolCall();\n const rendererNames = useToolCallRendererNames();\n const { copilotkit } = useCopilotKit();\n const subscribe = useCallback(\n (onChange: () => void) =>\n copilotkit.ɵsubscribeToLearningConfigured(onChange),\n [copilotkit],\n );\n const getSnapshot = () => copilotkit.ɵlearningConfigured;\n // Driven by the learning config, not by the Trajectory: a wrapper that comes\n // and goes with capture state would remount the tool UI on every reconnect.\n // Only adding or removing the config itself changes the tree.\n const learningConfigured = useSyncExternalStore(\n subscribe,\n getSnapshot,\n getSnapshot,\n );\n const context = useContext(ToolCallDisplayContext);\n const display = displayProp ?? context?.display ?? \"grouped\";\n\n // Inside a message view, groups can span messages, so the view lays them\n // out for the whole list; on its own, this message's calls are grouped.\n const viewLayout = context?.layouts.get(message.id);\n const layout = useMemo(() => {\n if (display === \"separate\") return undefined;\n return (\n viewLayout ??\n ɵgetToolCallLayouts([message], messages, rendererNames).get(message.id)\n );\n }, [display, viewLayout, message, messages, rendererNames]);\n\n if (!message.toolCalls || message.toolCalls.length === 0) {\n return null;\n }\n\n const renderCall = (entry: ToolCallEntry) => {\n const rendered = renderToolCall({\n toolCall: entry.toolCall,\n toolMessage: entry.toolMessage,\n });\n if (rendered === null || !learningConfigured) return rendered;\n // The id lets interaction capture attribute clicks to this tool call.\n return (\n <div\n data-tool-call-id={entry.toolCall.id}\n style={{ display: \"contents\" }}\n >\n {rendered}\n </div>\n );\n };\n\n if (!layout) {\n return (\n <>\n {message.toolCalls.map((toolCall) => {\n const toolMessage = messages.find(\n (m) => m.role === \"tool\" && m.toolCallId === toolCall.id,\n ) as ToolMessage | undefined;\n return (\n <React.Fragment key={toolCall.id}>\n {renderCall({ toolCall, toolMessage })}\n </React.Fragment>\n );\n })}\n </>\n );\n }\n\n const workOpen = context?.workOpen.get(message.id);\n // Whether the agent may still finish a trailing group's calls. Without a\n // message view there's no run state, so a call with no result is assumed to\n // be running, as the built-in card has always shown it.\n const groupActive = (trailing: boolean) =>\n trailing && (context ? context.isRunning : true);\n\n return (\n <>\n {layout.segments.map((segment) => {\n if (segment.kind === \"call\") {\n return (\n <React.Fragment key={segment.id}>\n {renderCall(segment.call)}\n </React.Fragment>\n );\n }\n\n if (display === \"turn\") {\n // A row per call, in the open while the agent works; the message\n // view folds them away with the rest of the work once it's done.\n const active = groupActive(segment.trailing);\n const { failedIds, statusById } = ɵgetToolCallGroupState(\n segment.calls,\n active,\n false,\n );\n return (\n <Collapsible\n key={segment.id}\n open={workOpen ?? true}\n className=\"cpk-tool-calls-view-turn\"\n >\n <div className=\"cpk-tool-calls-view-turn-rows\">\n <ToolCallGroupContext.Provider\n value={{ appearance: \"line\", failedIds, statusById, active }}\n >\n {segment.calls.map((call) => (\n <React.Fragment key={call.toolCall.id}>\n {renderCall(call)}\n </React.Fragment>\n ))}\n </ToolCallGroupContext.Provider>\n </div>\n </Collapsible>\n );\n }\n\n return (\n <React.Fragment key={segment.id}>\n {renderSlot(group, CopilotChatToolCallGroup, {\n calls: segment.calls,\n renderCall,\n appearance: ɵtoolCallAppearance(display) ?? \"card\",\n isActive: groupActive(segment.trailing),\n })}\n </React.Fragment>\n );\n })}\n </>\n );\n}\n\nexport default CopilotChatToolCallsView;\n","\"use client\";\n\nimport {\n useEffect,\n useId,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport { cn } from \"../../lib/utils\";\nimport { Button } from \"../ui/button\";\nimport { Tooltip, TooltipTrigger, TooltipContent } from \"../ui/tooltip\";\nimport {\n DropdownMenu,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuLabel,\n DropdownMenuItem,\n DropdownMenuSeparator,\n} from \"../ui/dropdown-menu\";\nimport { useCopilotKitInspector } from \"../CopilotKitInspectorContext\";\nimport {\n CopilotChatDefaultLabels,\n ɵHoverMenuController,\n ɵinspectorKiteFill,\n ɵinspectorKiteIcon,\n ɵinspectorShortcuts,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\nconst subscribeToShortcuts = (listener: () => void) =>\n ɵinspectorShortcuts.subscribe(listener);\nconst getShortcutsHidden = () => ɵinspectorShortcuts.hidden;\nconst getServerShortcutsHidden = () => false;\n\n/** Whether the user hid the Inspector shortcuts until the page reloads. */\nexport function useInspectorShortcutsHidden() {\n return useSyncExternalStore(\n subscribeToShortcuts,\n getShortcutsHidden,\n getServerShortcutsHidden,\n );\n}\n\nconst hideShortcuts = () => ɵinspectorShortcuts.hide();\n\n// Matches the Inspector launcher artwork in web-inspector/src/assets/inspector-logo-kite.svg.\nfunction InspectorKiteIcon({\n className,\n ...props\n}: React.SVGProps<SVGSVGElement>) {\n const id = useId();\n return (\n <svg\n {...props}\n aria-hidden=\"true\"\n className={cn(\"cpk-inspector-button-kite-icon\", className)}\n viewBox={ɵinspectorKiteIcon.viewBox}\n fill=\"none\"\n >\n {ɵinspectorKiteIcon.paths.map((path) => (\n <path\n key={path.d}\n d={path.d}\n fill={ɵinspectorKiteFill(id, path)}\n stroke={path.stroke}\n strokeWidth={path.strokeWidth}\n strokeLinecap={path.strokeLinecap}\n />\n ))}\n <defs>\n {ɵinspectorKiteIcon.gradients.map((gradient) => (\n <linearGradient\n key={gradient.id}\n id={`${id}-${gradient.id}`}\n x1={gradient.x1}\n y1={gradient.y1}\n x2={gradient.x2}\n y2={gradient.y2}\n gradientUnits=\"userSpaceOnUse\"\n >\n {gradient.stops.map((stop) => (\n <stop\n key={`${stop.offset ?? \"0\"}-${stop.color}`}\n offset={stop.offset}\n stopColor={stop.color}\n />\n ))}\n </linearGradient>\n ))}\n </defs>\n </svg>\n );\n}\n\nexport function CopilotChatInspectorButton({\n title,\n className,\n onClick,\n onPointerDown,\n onPointerEnter,\n onPointerLeave,\n onKeyDown,\n disabled,\n ...props\n}: React.ButtonHTMLAttributes<HTMLButtonElement>) {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const { isInspectorEnabled } = useCopilotKitInspector();\n const hidden = useInspectorShortcutsHidden();\n const [menu] = useState(() => new ɵHoverMenuController());\n const { open, dark } = useSyncExternalStore(\n menu.subscribe,\n menu.getSnapshot,\n menu.getSnapshot,\n );\n const trigger = useRef<HTMLButtonElement>(null);\n const primaryLabel = title || labels.assistantMessageToolbarInspectorLabel;\n useEffect(() => menu.dispose, [menu]);\n\n const { cancelClose, scheduleClose } = menu;\n const changeOpen = (next: boolean) => menu.setOpen(next, trigger.current);\n\n if (!isInspectorEnabled || hidden) return null;\n\n return (\n <DropdownMenu open={open} onOpenChange={changeOpen} modal={false}>\n <DropdownMenuTrigger asChild>\n <Button\n {...props}\n ref={trigger}\n type=\"button\"\n disabled={disabled}\n variant=\"assistantMessageToolbarButton\"\n size=\"icon\"\n data-testid=\"copilot-inspector-button\"\n aria-label={`${labels.assistantMessageToolbarInspectorTitle} (${labels.assistantMessageToolbarInspectorLocalOnlyLabel.toLowerCase()})`}\n className={cn(\"cpk-inspector-button\", className)}\n onPointerEnter={(event) => {\n onPointerEnter?.(event);\n menu.pointerEnter({\n pointerType: event.pointerType,\n disabled,\n trigger: trigger.current,\n });\n }}\n onPointerLeave={(event) => {\n onPointerLeave?.(event);\n scheduleClose();\n }}\n onPointerDown={(event) => {\n onPointerDown?.(event);\n // Clicking inspects the message instead of toggling the menu.\n event.preventDefault();\n }}\n onClick={(event) => {\n changeOpen(false);\n onClick?.(event);\n }}\n onKeyDown={(event) => {\n menu.keyboardUsed();\n onKeyDown?.(event);\n if (\n !event.defaultPrevented &&\n (event.key === \"Enter\" || event.key === \" \")\n ) {\n event.preventDefault();\n event.currentTarget.click();\n }\n }}\n >\n <CopilotIcon\n name=\"Wrench\"\n aria-hidden=\"true\"\n className=\"cpk-inspector-button-icon\"\n data-testid=\"copilot-inspector-icon\"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align=\"start\"\n side=\"top\"\n sideOffset={6}\n className={cn(\"cpk-inspector-button-menu\", dark && \"dark\")}\n onPointerEnter={cancelClose}\n onPointerLeave={scheduleClose}\n onKeyDown={menu.keyboardUsed}\n onOpenAutoFocus={(event) => {\n if (menu.openedByHover) event.preventDefault();\n }}\n onCloseAutoFocus={(event) => {\n if (menu.openedByHover) event.preventDefault();\n }}\n onFocusOutside={() => changeOpen(false)}\n >\n <DropdownMenuLabel className=\"cpk-inspector-button-menu-header\">\n <span className=\"cpk-inspector-button-menu-title\">\n {labels.assistantMessageToolbarInspectorTitle}\n </span>\n <Tooltip delayDuration={1000}>\n <TooltipTrigger asChild>\n <span tabIndex={0} className=\"cpk-inspector-button-local-badge\">\n {labels.assistantMessageToolbarInspectorLocalOnlyLabel}\n </span>\n </TooltipTrigger>\n <TooltipContent\n side=\"top\"\n sideOffset={6}\n className={cn(\n \"cpk-inspector-button-local-tooltip\",\n dark && \"dark\",\n )}\n onPointerEnter={cancelClose}\n onPointerLeave={scheduleClose}\n >\n {labels.assistantMessageToolbarInspectorLocalOnlyDescription}\n </TooltipContent>\n </Tooltip>\n </DropdownMenuLabel>\n <DropdownMenuSeparator />\n <DropdownMenuItem asChild>\n <button\n type=\"button\"\n onClick={onClick}\n className=\"cpk-inspector-button-menu-item cpk-inspector-button-inspect-item\"\n >\n <InspectorKiteIcon className=\"cpk-inspector-button-menu-item-icon\" />\n <span>\n <span className=\"cpk-inspector-button-menu-item-label\">\n {primaryLabel}\n </span>\n <span className=\"cpk-inspector-button-menu-item-description\">\n {labels.assistantMessageToolbarInspectorDescription}\n </span>\n </span>\n </button>\n </DropdownMenuItem>\n <DropdownMenuItem\n onSelect={hideShortcuts}\n className=\"cpk-inspector-button-menu-item cpk-inspector-button-hide-item\"\n >\n <CopilotIcon\n name=\"EyeOff\"\n aria-hidden=\"true\"\n className=\"cpk-inspector-button-menu-item-icon\"\n />\n <span>\n <span className=\"cpk-inspector-button-menu-item-label\">\n {labels.assistantMessageToolbarInspectorHideLabel}\n </span>\n <span className=\"cpk-inspector-button-menu-item-description\">\n {labels.assistantMessageToolbarInspectorHideDescription}\n </span>\n </span>\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n );\n}\n","import * as React from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\n\nimport { cn } from \"../../lib/utils\";\n\nfunction Popover({\n ...props\n}: React.ComponentProps<typeof PopoverPrimitive.Root>) {\n return <PopoverPrimitive.Root data-slot=\"popover\" {...props} />;\n}\n\nfunction PopoverAnchor({\n ...props\n}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {\n return <PopoverPrimitive.Anchor data-slot=\"popover-anchor\" {...props} />;\n}\n\n/**\n * Popover content in a portal, so it floats over the page instead of taking\n * room in the layout, with the CopilotKit style scope on it.\n */\nconst PopoverContent = React.forwardRef<\n React.ComponentRef<typeof PopoverPrimitive.Content>,\n React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>\n>(({ className, align = \"start\", sideOffset = 6, ...props }, ref) => (\n <PopoverPrimitive.Portal>\n <PopoverPrimitive.Content\n ref={ref}\n data-copilotkit\n data-copilotkit-popover\n data-slot=\"popover-content\"\n align={align}\n sideOffset={sideOffset}\n className={cn(\"cpk-popover\", className)}\n {...props}\n />\n </PopoverPrimitive.Portal>\n));\nPopoverContent.displayName = \"PopoverContent\";\n\nexport { Popover, PopoverAnchor, PopoverContent };\n","import type { AssistantMessage } from \"@ag-ui/core\";\nimport type { CopilotKitCore } from \"@copilotkit/core\";\nimport {\n ɵFeedbackCommentController,\n ɵgetMessageFeedback,\n ɵgetMessageFeedbackControls,\n ɵisLearningFeedbackEnabled,\n ɵsubscribeToLearningFeedbackEnabled,\n ɵsubscribeToMessageFeedback,\n} from \"@copilotkit/core\";\nimport type {\n ɵMessageFeedbackControls,\n ɵMessageFeedbackScope,\n} from \"@copilotkit/core\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport type { RefObject } from \"react\";\n\n/** The chat whose assistant messages collect feedback for Learning. */\nexport type MessageFeedbackScope = ɵMessageFeedbackScope;\n\n/** Current feedback for one assistant message, and how to change it. */\nexport type MessageFeedbackControls = ɵMessageFeedbackControls;\n\n/**\n * Set by the message view while Learning is on for this chat. Assistant\n * messages without it show thumbs only when the app passes its own handlers\n * or thumb slots.\n */\nexport const MessageFeedbackScopeContext =\n createContext<MessageFeedbackScope | null>(null);\n\n/**\n * Whether the thumbs record feedback for Learning. See core's\n * `ɵisLearningFeedbackEnabled` for the rules.\n */\nexport function useLearningFeedbackEnabled(copilotkit: CopilotKitCore) {\n const subscribe = useCallback(\n (onChange: () => void) =>\n ɵsubscribeToLearningFeedbackEnabled(copilotkit, onChange),\n [copilotkit],\n );\n return useSyncExternalStore(\n subscribe,\n () => ɵisLearningFeedbackEnabled(copilotkit),\n () => false,\n );\n}\n\nconst noSubscription = () => () => {};\n\n/** Feedback controls for `message`, or `null` when this chat collects none. */\nexport function useMessageFeedback(message: AssistantMessage) {\n const scope = useContext(MessageFeedbackScopeContext);\n const subscribe = useCallback(\n (onChange: () => void) =>\n scope\n ? ɵsubscribeToMessageFeedback(scope.agentId, scope.threadId, onChange)\n : noSubscription(),\n [scope],\n );\n const getSnapshot = () =>\n scope\n ? ɵgetMessageFeedback(scope.agentId, scope.threadId, message.id)\n : undefined;\n // Re-renders when this message's rating changes.\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n return scope ? ɵgetMessageFeedbackControls(scope, message) : null;\n}\n\n/** The comment popover of one rated message: when it shows and what it holds. */\nexport interface FeedbackComment {\n readonly open: boolean;\n /** The comment being edited. */\n readonly draft: string;\n readonly setDraft: (draft: string) => void;\n /** Grows each time the field should take focus: after a keyboard rating. */\n readonly focusRequest: number;\n /** The chosen thumb the popover points at. */\n readonly anchor: HTMLElement | null;\n /** Whether a focus request waits; reading it answers the request. */\n readonly takeFocusRequest: () => boolean;\n /** The comment field, for moving focus into it. */\n readonly inputRef: RefObject<HTMLInputElement | null>;\n /** Opens with `comment` in the field. */\n readonly show: ɵFeedbackCommentController[\"show\"];\n /** The pointer or focus reached the rating or the popover. */\n readonly enter: ɵFeedbackCommentController[\"enter\"];\n /**\n * It left them: close soon, unless the user is editing the comment or, when\n * focus left, the pointer is still on the rating or the popover.\n */\n readonly leave: ɵFeedbackCommentController[\"leave\"];\n /** Tracks whether focus is in the comment form. */\n readonly setEditing: (editing: boolean) => void;\n /** Closes, saving a changed comment unless `save` is false. */\n readonly close: ɵFeedbackCommentController[\"close\"];\n /** Moves focus back to the thumb without opening the comment again. */\n readonly returnFocus: (target: HTMLElement | null) => void;\n /** A thumb click; returns whether the app's handler should run. */\n readonly rate: ɵFeedbackCommentController[\"rate\"];\n /** The attributes and handlers of one thumb. */\n readonly thumb: ɵFeedbackCommentController[\"thumb\"];\n /** Points at the chosen thumb when the click gave no element. */\n readonly findAnchor: ɵFeedbackCommentController[\"findAnchor\"];\n /** Closes a comment whose rating changed or whose toolbar hid. */\n readonly sync: ɵFeedbackCommentController[\"sync\"];\n /** Moves focus into the field when a keyboard rating asked for it. */\n readonly focusField: ɵFeedbackCommentController[\"focusField\"];\n /** Saves, closes, and returns focus to the thumb. */\n readonly submit: ɵFeedbackCommentController[\"submit\"];\n /** Escape in the popover; returns whether to stop the event. */\n readonly popoverEscape: ɵFeedbackCommentController[\"popoverEscape\"];\n /** Tab out of the popover, back into the page's order. */\n readonly popoverKeyDown: ɵFeedbackCommentController[\"popoverKeyDown\"];\n /** Focus left the comment form. */\n readonly popoverFocusLeave: ɵFeedbackCommentController[\"popoverFocusLeave\"];\n}\n\n/**\n * Drives the comment popover of a rated message with core's\n * `ɵFeedbackCommentController`, which holds the open and close rules.\n */\nexport function useFeedbackComment(\n controls: MessageFeedbackControls | null,\n): FeedbackComment {\n const latestControls = useRef(controls);\n latestControls.current = controls;\n const inputRef = useRef<HTMLInputElement | null>(null);\n const [controller] = useState(\n () =>\n new ɵFeedbackCommentController({\n getControls: () => latestControls.current,\n getInput: () => inputRef.current,\n }),\n );\n const state = useSyncExternalStore(\n controller.subscribe,\n controller.getSnapshot,\n controller.getSnapshot,\n );\n // A message that unmounts (scrolled out of a virtual list) keeps its edit.\n useEffect(() => controller.dispose, [controller]);\n\n return {\n ...state,\n setDraft: controller.setDraft,\n takeFocusRequest: controller.takeFocusRequest,\n inputRef,\n show: controller.show,\n enter: controller.enter,\n leave: controller.leave,\n setEditing: controller.setEditing,\n close: controller.close,\n returnFocus: controller.returnFocus,\n rate: controller.rate,\n thumb: controller.thumb,\n findAnchor: controller.findAnchor,\n sync: controller.sync,\n focusField: controller.focusField,\n submit: controller.submit,\n popoverEscape: controller.popoverEscape,\n popoverKeyDown: controller.popoverKeyDown,\n popoverFocusLeave: controller.popoverFocusLeave,\n };\n}\n","import { useEffect, useState, useSyncExternalStore } from \"react\";\nimport { ɵCopyFeedback } from \"@copilotkit/core\";\n\n/**\n * The \"copied\" check mark of a copy button, from core's `ɵCopyFeedback`: it\n * shows for two seconds after `markCopied()`, and a second copy restarts the\n * wait.\n */\nexport function useCopyFeedback() {\n const [feedback] = useState(() => new ɵCopyFeedback());\n const copied = useSyncExternalStore(\n feedback.subscribe,\n feedback.getSnapshot,\n feedback.getSnapshot,\n );\n useEffect(() => feedback.dispose, [feedback]);\n return { copied, markCopied: feedback.markCopied };\n}\n","import type { AssistantMessage, Message } from \"@ag-ui/core\";\nimport React, {\n Fragment,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport { CopilotChatDefaultLabels } from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport { cn } from \"../../lib/utils\";\nimport { Button } from \"../../components/ui/button\";\nimport {\n Tooltip,\n TooltipContent,\n TooltipTrigger,\n} from \"../../components/ui/tooltip\";\nimport type { SlotValue, WithSlots } from \"../../lib/slots\";\nimport {\n renderSlot,\n isReactComponentType,\n useShallowStableRef,\n} from \"../../lib/slots\";\nimport { StreamingMarkdownDefaultRenderer } from \"./StreamingMarkdownDefaultRenderer\";\nimport { useMarkdownRenderer } from \"../../providers/MarkdownRendererContext\";\nimport type {\n MarkdownRendererProps,\n DefaultMarkdownRendererProps,\n MarkdownRenderer as MarkdownRendererValue,\n} from \"../../providers/MarkdownRendererContext\";\nimport { copyToClipboard } from \"@copilotkit/shared\";\nimport CopilotChatToolCallsView from \"./CopilotChatToolCallsView\";\nimport { Collapsible } from \"./CopilotChatToolCallGroup\";\nimport { ToolCallDisplayContext } from \"./tool-call-display-context\";\nimport { useCopilotKitInspector } from \"../CopilotKitInspectorContext\";\nimport {\n CopilotChatInspectorButton,\n useInspectorShortcutsHidden,\n} from \"./CopilotChatInspectorButton\";\nimport type { CopilotKitInspectorOpenRequest } from \"../CopilotKitInspectorContext\";\nimport { useGenerativeUIRuntime } from \"../../generative-ui/runtime-context\";\nimport { MarkdownSurfaces } from \"../../generative-ui/markdown/MarkdownSurfaces\";\nimport {\n Popover,\n PopoverAnchor,\n PopoverContent,\n} from \"../../components/ui/popover\";\nimport { useFeedbackComment, useMessageFeedback } from \"./message-feedback\";\nimport type { FeedbackComment } from \"./message-feedback\";\nimport {\n ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH,\n ɵhasAssistantMessageText,\n ɵisOwnFeedbackThumb,\n ɵshouldShowAssistantToolbar,\n} from \"@copilotkit/core\";\nimport { useCopyFeedback } from \"./use-copy-feedback\";\nimport type { ɵMessageFeedbackRating as MessageFeedbackRating } from \"@copilotkit/core\";\n\nexport type CopilotChatFeedbackMessage = AssistantMessage & {\n rawEvent?: unknown;\n};\n\nexport type CopilotChatAssistantMessageProps = WithSlots<\n {\n markdownRenderer: typeof CopilotChatAssistantMessage.MarkdownRenderer;\n toolbar: typeof CopilotChatAssistantMessage.Toolbar;\n copyButton: typeof CopilotChatAssistantMessage.CopyButton;\n inspectorButton: typeof CopilotChatAssistantMessage.InspectorButton;\n thumbsUpButton: typeof CopilotChatAssistantMessage.ThumbsUpButton;\n thumbsDownButton: typeof CopilotChatAssistantMessage.ThumbsDownButton;\n readAloudButton: typeof CopilotChatAssistantMessage.ReadAloudButton;\n regenerateButton: typeof CopilotChatAssistantMessage.RegenerateButton;\n toolCallsView: typeof CopilotChatToolCallsView;\n },\n {\n onThumbsUp?: (message: CopilotChatFeedbackMessage) => void;\n onThumbsDown?: (message: CopilotChatFeedbackMessage) => void;\n onReadAloud?: (message: AssistantMessage) => void;\n onRegenerate?: (message: AssistantMessage) => void;\n message: AssistantMessage;\n messages?: Message[];\n isRunning?: boolean;\n /**\n * Whether this is the last message the chat renders. The message view\n * passes it, because the rendered list can differ from `messages` when\n * `transformMessages` drops, replaces or reorders messages. Defaults to\n * comparing against the last entry of `messages`.\n */\n isLatest?: boolean;\n additionalToolbarItems?: React.ReactNode;\n toolbarVisible?: boolean;\n /**\n * The comment field of a reply rating, inside the popover next to the\n * chosen thumb. Shown only while Automatic Learning records ratings; it\n * renders after `children`, so a `children` layout does not place it.\n */\n feedbackComment?: SlotValue<\n typeof CopilotChatAssistantMessage.FeedbackComment\n >;\n } & React.HTMLAttributes<HTMLDivElement>\n>;\n\nfunction resolveMarkdownRenderer(\n value: MarkdownRendererValue | undefined,\n): React.FC<MarkdownRendererProps & DefaultMarkdownRendererProps> {\n if (!value) return CopilotChatAssistantMessage.MarkdownRenderer;\n if (isReactComponentType(value)) {\n // A provider-supplied component (escape hatch) renders with the bound\n // { content, isStreaming } props; wrap it so the resolved type matches the\n // slot's component type. createElement accepts function or class components.\n const ProvidedRenderer = value;\n const ProvidedMarkdownRenderer: React.FC<\n MarkdownRendererProps & DefaultMarkdownRendererProps\n > = (props) => React.createElement(ProvidedRenderer, props);\n return ProvidedMarkdownRenderer;\n }\n const config = value as DefaultMarkdownRendererProps;\n const ConfiguredRenderer: React.FC<\n MarkdownRendererProps & DefaultMarkdownRendererProps\n > = (props) => (\n // Provider config is the base; props (bound content/isStreaming plus any\n // per-message slot config merged in by renderSlot) override it, so a\n // per-message markdownRenderer wins over the provider per the documented\n // slot -> provider -> built-in resolution order.\n <CopilotChatAssistantMessage.MarkdownRenderer {...config} {...props} />\n );\n return ConfiguredRenderer;\n}\n\n/**\n * In the `\"turn\"` tool-call display, text in a reply's working phase was\n * narration: it fades to muted once a call follows it, and folds away with the\n * rest of the work when the reply is done. The wrapper is there for every\n * message in that display, so text that turns into narration keeps its node\n * (and its place) rather than remounting.\n */\nfunction WorkText({\n messageId,\n children,\n}: {\n messageId: string;\n children: React.ReactElement;\n}) {\n const context = useContext(ToolCallDisplayContext);\n if (context?.display !== \"turn\") return children;\n const open = context.workTextOpen.get(messageId);\n return (\n <Collapsible\n open={open ?? true}\n className=\"cpk-assistant-message-work-text\"\n >\n <div\n className=\"cpk-assistant-message-work-text-content\"\n data-work-text={open === undefined ? \"reply\" : \"narration\"}\n >\n {children}\n </div>\n </Collapsible>\n );\n}\n\n/**\n * Binds the Inspector action to the active chat without making the full\n * assistant message subscribe to chat configuration changes.\n */\nfunction BoundInspectorButton({\n inspectorButton,\n messageId,\n openInspector,\n ...props\n}: {\n inspectorButton: CopilotChatAssistantMessageProps[\"inspectorButton\"];\n messageId: string;\n openInspector: (request: CopilotKitInspectorOpenRequest) => void;\n} & Omit<\n React.ButtonHTMLAttributes<HTMLButtonElement>,\n \"onClick\"\n>): React.ReactElement {\n const chatConfiguration = useCopilotChatConfiguration();\n\n return renderSlot(\n inspectorButton,\n CopilotChatAssistantMessage.InspectorButton,\n {\n ...props,\n onClick: () =>\n openInspector({\n messageId,\n threadId: chatConfiguration?.threadId,\n agentId: chatConfiguration?.agentId,\n }),\n },\n );\n}\n\n/**\n * The comment popover of a rated message, pointing at the chosen thumb. Kept\n * apart so only it, not the whole message, follows chat configuration.\n *\n * The popover lives in a portal, so it keeps keyboard order by hand: Shift+Tab\n * from its start returns to the thumb, Tab from its end moves on to the\n * control after the thumb, and Enter or Escape inside it returns to the thumb.\n */\nfunction FeedbackCommentPopover({\n feedbackComment,\n comment,\n savedComment,\n rating,\n messageId,\n}: {\n feedbackComment:\n | SlotValue<typeof CopilotChatAssistantMessage.FeedbackComment>\n | undefined;\n comment: FeedbackComment;\n savedComment: string;\n rating: MessageFeedbackRating;\n messageId: string;\n}): React.ReactElement {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const contentRef = useRef<HTMLDivElement>(null);\n // Radix reads the anchor through a ref. A new ref per anchor, so nothing\n // changes a ref during render.\n const anchor = useMemo(() => ({ current: comment.anchor }), [comment.anchor]);\n // A keyboard rating moves focus into the field, as the popover opens or,\n // when it was open already, as the field for the new rating renders.\n const { focusRequest, focusField } = comment;\n useEffect(() => focusField(), [focusRequest, focusField]);\n return (\n <Popover\n open={comment.open}\n onOpenChange={(open) => {\n if (!open) comment.close();\n }}\n >\n <PopoverAnchor virtualRef={anchor as React.RefObject<HTMLElement>} />\n <PopoverContent\n ref={contentRef}\n side=\"bottom\"\n collisionPadding={8}\n hideWhenDetached\n aria-label={labels.assistantMessageFeedbackCommentPlaceholder}\n data-copilotkit-ignore\n onOpenAutoFocus={(event) => {\n event.preventDefault();\n focusField();\n }}\n onCloseAutoFocus={(event) => event.preventDefault()}\n onInteractOutside={(event) => {\n // A click on a thumb removes or switches the rating, so closing must\n // not first save the draft as the answer to the rating it replaces.\n if (ɵisOwnFeedbackThumb(event.target, messageId))\n event.preventDefault();\n }}\n onEscapeKeyDown={(event) => {\n // Escape in the comment closes only the comment, not a chat popup\n // around it; with focus elsewhere it also reaches that control.\n if (comment.popoverEscape(contentRef.current))\n event.stopPropagation();\n }}\n onKeyDown={(event) => comment.popoverKeyDown(event, contentRef.current)}\n onPointerEnter={() => comment.enter(\"pointer\")}\n onPointerLeave={() => comment.leave(\"pointer\")}\n className=\"cpk-assistant-message-feedback-popover\"\n >\n {/* Keyed on the rating, so a new rating starts with a fresh field. */}\n <Fragment key={rating}>\n {renderSlot(\n feedbackComment,\n CopilotChatAssistantMessage.FeedbackComment,\n {\n value: comment.draft,\n savedComment,\n inputRef: comment.inputRef,\n onChange: comment.setDraft,\n onSubmit: comment.submit,\n onEditingChange: comment.setEditing,\n onLeave: (next) =>\n comment.popoverFocusLeave(next, contentRef.current, messageId),\n },\n )}\n </Fragment>\n </PopoverContent>\n </Popover>\n );\n}\n\nexport function CopilotChatAssistantMessage({\n message,\n messages,\n isRunning,\n isLatest,\n onThumbsUp,\n onThumbsDown,\n onReadAloud,\n onRegenerate,\n additionalToolbarItems,\n toolbarVisible = true,\n markdownRenderer,\n toolbar,\n copyButton,\n inspectorButton,\n thumbsUpButton,\n thumbsDownButton,\n readAloudButton,\n regenerateButton,\n feedbackComment: feedbackCommentSlot,\n toolCallsView,\n children,\n className,\n ...props\n}: CopilotChatAssistantMessageProps) {\n // Stabilize the provider value so a shallow-equal inline config object (e.g.\n // `markdownRenderer={{ caret: true }}`) with a fresh identity on each provider\n // render doesn't churn resolveMarkdownRenderer's output and remount the\n // markdown subtree (which would throw away streaming parser state). This is a\n // shallow, key-by-key compare — configs whose values are themselves new\n // objects each render (e.g. an inline `nodeRenderers`) or an inline component\n // renderer still change identity, so define those outside render / memoize\n // them, exactly as you would any component prop. Mirrors how slot props are\n // stabilized via the same helper.\n const providerRenderer = useShallowStableRef(useMarkdownRenderer());\n const DefaultMarkdownRenderer = useMemo(\n () => resolveMarkdownRenderer(providerRenderer),\n [providerRenderer],\n );\n\n // Don't show toolbar if message has no content (only tool calls)\n const hasContent = ɵhasAssistantMessageText(message.content);\n const isLatestAssistantMessage =\n message.role === \"assistant\" &&\n (isLatest ?? messages?.[messages.length - 1]?.id === message.id);\n const { isInspectorEnabled, openInspector } = useCopilotKitInspector();\n const shortcutsHidden = useInspectorShortcutsHidden();\n const showInspectorShortcut = isInspectorEnabled && !shortcutsHidden;\n // Set while this chat collects ratings for Learning: the thumbs record them.\n const feedback = useMessageFeedback(message);\n const comment = useFeedbackComment(feedback);\n const root = useRef<HTMLDivElement>(null);\n // A custom thumb that calls `onClick` without an event gives no element:\n // point at the chosen thumb once it renders, before the popover reads it.\n useLayoutEffect(() => comment.findAnchor(root.current));\n /**\n * A thumb click. A keyboard click (`detail` 0) moves focus into the\n * comment; custom thumb slots may call `onClick` without an event.\n */\n const rate = (\n value: MessageFeedbackRating,\n event?: React.MouseEvent<HTMLButtonElement>,\n ) =>\n comment.rate(value, {\n target: event?.currentTarget ?? null,\n keyboard: event?.detail === 0,\n });\n\n /** Props that let the chosen thumb open and point at its comment. */\n const thumbFeedbackProps = (value: MessageFeedbackRating) => {\n const thumb = comment.thumb(value);\n if (!thumb) return {};\n const { handlers } = thumb;\n if (!handlers) return thumb.attributes;\n return {\n ...thumb.attributes,\n onPointerEnter: handlers.pointerEnter,\n onPointerLeave: handlers.pointerLeave,\n onFocus: handlers.focus,\n onBlur: handlers.blur,\n onKeyDown: handlers.keyDown,\n };\n };\n\n const boundMarkdownRenderer = renderSlot(\n markdownRenderer,\n DefaultMarkdownRenderer,\n {\n content: message.content || \"\",\n isStreaming: !!(isRunning && isLatestAssistantMessage),\n messageId: message.id,\n },\n );\n\n const boundCopyButton = renderSlot(\n copyButton,\n CopilotChatAssistantMessage.CopyButton,\n {\n onClick: async () => {\n if (message.content) {\n return await copyToClipboard(message.content);\n }\n return false;\n },\n },\n );\n\n const boundThumbsUpButton = renderSlot(\n thumbsUpButton,\n CopilotChatAssistantMessage.ThumbsUpButton,\n {\n onClick:\n onThumbsUp || feedback\n ? (event?: React.MouseEvent<HTMLButtonElement>) => {\n // The app hears about a rating given, not about one removed.\n if (rate(\"up\", event)) onThumbsUp?.(message);\n }\n : undefined,\n ...thumbFeedbackProps(\"up\"),\n },\n );\n\n const boundInspectorButton = showInspectorShortcut ? (\n <BoundInspectorButton\n inspectorButton={inspectorButton}\n messageId={message.id}\n openInspector={openInspector}\n />\n ) : (\n <></>\n );\n\n const boundThumbsDownButton = renderSlot(\n thumbsDownButton,\n CopilotChatAssistantMessage.ThumbsDownButton,\n {\n onClick:\n onThumbsDown || feedback\n ? (event?: React.MouseEvent<HTMLButtonElement>) => {\n if (rate(\"down\", event)) onThumbsDown?.(message);\n }\n : undefined,\n ...thumbFeedbackProps(\"down\"),\n },\n );\n\n const boundReadAloudButton = renderSlot(\n readAloudButton,\n CopilotChatAssistantMessage.ReadAloudButton,\n {\n onClick: onReadAloud ? () => onReadAloud(message) : undefined,\n },\n );\n\n const boundRegenerateButton = renderSlot(\n regenerateButton,\n CopilotChatAssistantMessage.RegenerateButton,\n {\n onClick: onRegenerate ? () => onRegenerate(message) : undefined,\n },\n );\n\n const boundToolbar = renderSlot(\n toolbar,\n CopilotChatAssistantMessage.Toolbar,\n {\n children: (\n <div className=\"cpk-assistant-message-toolbar-items\">\n {boundCopyButton}\n {(onThumbsUp || thumbsUpButton || feedback) && boundThumbsUpButton}\n {(onThumbsDown || thumbsDownButton || feedback) &&\n boundThumbsDownButton}\n {(onReadAloud || readAloudButton) && boundReadAloudButton}\n {(onRegenerate || regenerateButton) && boundRegenerateButton}\n {additionalToolbarItems}\n {showInspectorShortcut && boundInspectorButton}\n </div>\n ),\n },\n );\n\n const boundToolCallsView = renderSlot(\n toolCallsView,\n CopilotChatToolCallsView,\n {\n message,\n messages,\n },\n );\n\n const shouldShowToolbar = ɵshouldShowAssistantToolbar({\n toolbarVisible,\n hasContent,\n showInspectorShortcut,\n isRunning: !!isRunning,\n isLatest: isLatestAssistantMessage,\n });\n // The popover shows only with the toolbar and a rating. Hiding the toolbar\n // keeps the edit; a rating removed elsewhere or Learning turned off ends it.\n const rating = feedback?.feedback?.rating;\n const { open: commentOpen, sync: syncComment } = comment;\n useEffect(() => {\n // react-doctor-disable-next-line react-doctor/no-pass-data-to-parent -- syncs core's feedback controller, an external store, not a parent's state\n syncComment({ showsToolbar: shouldShowToolbar });\n }, [commentOpen, shouldShowToolbar, rating, syncComment]);\n\n // Floats in a portal next to the chosen thumb, so it never moves the chat.\n const feedbackComment = feedback?.feedback && shouldShowToolbar && (\n <FeedbackCommentPopover\n feedbackComment={feedbackCommentSlot}\n comment={comment}\n savedComment={feedback.feedback.comment ?? \"\"}\n rating={feedback.feedback.rating}\n messageId={message.id}\n />\n );\n\n if (children) {\n return (\n <div\n ref={root}\n data-copilotkit\n data-message-id={message.id}\n style={{ display: \"contents\" }}\n >\n {children({\n markdownRenderer: boundMarkdownRenderer,\n toolbar: boundToolbar,\n toolCallsView: boundToolCallsView,\n copyButton: boundCopyButton,\n inspectorButton: boundInspectorButton,\n thumbsUpButton: boundThumbsUpButton,\n thumbsDownButton: boundThumbsDownButton,\n readAloudButton: boundReadAloudButton,\n regenerateButton: boundRegenerateButton,\n message,\n messages,\n isRunning,\n onThumbsUp,\n onThumbsDown,\n onReadAloud,\n onRegenerate,\n additionalToolbarItems,\n toolbarVisible: shouldShowToolbar,\n })}\n {feedbackComment}\n </div>\n );\n }\n\n return (\n <div\n ref={root}\n data-copilotkit\n data-testid=\"copilot-assistant-message\"\n className={cn(\"copilotKitMessage copilotKitAssistantMessage\", className)}\n {...props}\n data-message-id={message.id}\n >\n <WorkText messageId={message.id}>\n <div className=\"cpk-markdown cpk-assistant-message-markdown\">\n {boundMarkdownRenderer}\n </div>\n </WorkText>\n {boundToolCallsView}\n {shouldShowToolbar && boundToolbar}\n {feedbackComment}\n </div>\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace CopilotChatAssistantMessage {\n export const MarkdownRenderer: React.FC<\n MarkdownRendererProps &\n DefaultMarkdownRendererProps & {\n /** Id of the rendered message. The markdown transport finds its fences by it. */\n messageId?: string;\n }\n > = ({ content, isStreaming, className, messageId, ...config }) => {\n // With the markdown transport, ```a2ui fences render as surfaces. The\n // fences are found by the message id, so without one they stay code.\n const generativeUI = useGenerativeUIRuntime();\n if (generativeUI?.transport === \"markdown\" && messageId !== undefined) {\n return (\n <MarkdownSurfaces\n content={content ?? \"\"}\n messageId={messageId}\n isStreaming={isStreaming}\n className={className}\n {...config}\n />\n );\n }\n return (\n <StreamingMarkdownDefaultRenderer\n content={content ?? \"\"}\n isStreaming={isStreaming}\n className={className}\n {...config}\n />\n );\n };\n\n export const Toolbar: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({\n className,\n ...props\n }) => (\n <div\n data-testid=\"copilot-assistant-toolbar\"\n className={cn(\"cpk-assistant-message-toolbar\", className)}\n {...props}\n />\n );\n\n export const ToolbarButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement> & {\n title: string;\n tooltip?: React.ReactNode;\n tooltipClassName?: string;\n children: React.ReactNode;\n }\n > = ({ title, tooltip, tooltipClassName, children, ...props }) => {\n // Same element whether or not its popup is open, so pointer events stay\n // paired. The popup replaces the tooltip: an open tooltip closes, and a\n // request to open one while the popup shows is ignored, so the tooltip\n // does not reappear when the popup closes under a pointer that left.\n const [tooltipOpen, setTooltipOpen] = useState(false);\n const popupOpen = props[\"aria-expanded\"] === true;\n if (popupOpen && tooltipOpen) setTooltipOpen(false);\n return (\n <Tooltip\n open={tooltipOpen && !popupOpen}\n onOpenChange={(open) => setTooltipOpen(open && !popupOpen)}\n >\n <TooltipTrigger asChild>\n <Button\n type=\"button\"\n variant=\"assistantMessageToolbarButton\"\n aria-label={title}\n {...props}\n >\n {children}\n </Button>\n </TooltipTrigger>\n <TooltipContent side=\"bottom\" className={tooltipClassName}>\n {tooltip ?? <p>{title}</p>}\n </TooltipContent>\n </Tooltip>\n );\n };\n\n export const CopyButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ className, title, onClick, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const { copied, markCopied } = useCopyFeedback();\n\n const handleClick = async (event: React.MouseEvent<HTMLButtonElement>) => {\n if (!onClick) return;\n // onClick may return a boolean indicating copy success\n const result: unknown = await Promise.resolve(onClick(event));\n if (result === true) markCopied();\n };\n\n return (\n <ToolbarButton\n data-testid=\"copilot-copy-button\"\n title={title || labels.assistantMessageToolbarCopyMessageLabel}\n onClick={(event) => {\n void handleClick(event);\n }}\n className={className}\n {...props}\n >\n {copied ? (\n <CopilotIcon\n name=\"Check\"\n className=\"cpk-assistant-message-toolbar-icon\"\n />\n ) : (\n <CopilotIcon\n name=\"Copy\"\n className=\"cpk-assistant-message-toolbar-icon\"\n />\n )}\n </ToolbarButton>\n );\n };\n\n export const InspectorButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = CopilotChatInspectorButton;\n\n export const ThumbsUpButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ title, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <ToolbarButton\n data-testid=\"copilot-thumbs-up-button\"\n title={title || labels.assistantMessageToolbarThumbsUpLabel}\n {...props}\n >\n <CopilotIcon\n name=\"ThumbsUp\"\n className=\"cpk-assistant-message-toolbar-icon\"\n fill={props[\"aria-pressed\"] === true ? \"currentColor\" : \"none\"}\n />\n </ToolbarButton>\n );\n };\n\n export const ThumbsDownButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ title, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <ToolbarButton\n data-testid=\"copilot-thumbs-down-button\"\n title={title || labels.assistantMessageToolbarThumbsDownLabel}\n {...props}\n >\n <CopilotIcon\n name=\"ThumbsDown\"\n className=\"cpk-assistant-message-toolbar-icon\"\n fill={props[\"aria-pressed\"] === true ? \"currentColor\" : \"none\"}\n />\n </ToolbarButton>\n );\n };\n\n /**\n * The comment field of a rating, shown in a popover next to the chosen\n * thumb. Enter saves; Send appears once the text differs from the saved\n * comment. The popover marks itself `data-copilotkit-ignore`, so Learning\n * records the saved comment but not the typing; outside it, mark the\n * field yourself.\n */\n export const FeedbackComment: React.FC<{\n value: string;\n /** The comment already saved. */\n savedComment: string;\n inputRef?: React.Ref<HTMLInputElement>;\n onChange: (value: string) => void;\n onSubmit: () => void;\n onEditingChange?: (editing: boolean) => void;\n /**\n * Focus left the form for `next`, or for no focusable element when null.\n * Not called when the window loses focus.\n */\n onLeave?: (next: Element | null) => void;\n className?: string;\n }> = ({\n value,\n savedComment,\n inputRef,\n onChange,\n onSubmit,\n onEditingChange,\n onLeave,\n className,\n }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const changed = value.trim() !== savedComment;\n\n return (\n <form\n data-testid=\"copilot-feedback-comment\"\n className={cn(\"cpk-assistant-message-feedback-comment\", className)}\n onSubmit={(event) => {\n event.preventDefault();\n onSubmit();\n }}\n onFocus={() => onEditingChange?.(true)}\n onBlur={(event) => {\n const next =\n event.relatedTarget instanceof Element ? event.relatedTarget : null;\n if (event.currentTarget.contains(next)) return;\n // Switching to another window is not leaving the comment.\n if (typeof document !== \"undefined\" && !document.hasFocus()) return;\n onEditingChange?.(false);\n onLeave?.(next);\n }}\n >\n <input\n ref={inputRef}\n value={value}\n maxLength={ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH}\n onChange={(event) => onChange(event.target.value)}\n placeholder={labels.assistantMessageFeedbackCommentPlaceholder}\n aria-label={labels.assistantMessageFeedbackCommentPlaceholder}\n className=\"cpk-assistant-message-feedback-comment-input\"\n />\n {changed && (\n <Button\n type=\"submit\"\n variant=\"assistantMessageToolbarButton\"\n aria-label={labels.assistantMessageFeedbackCommentSubmitLabel}\n title={labels.assistantMessageFeedbackCommentSubmitLabel}\n >\n <CopilotIcon\n name=\"ArrowUp\"\n className=\"cpk-assistant-message-feedback-comment-submit-icon\"\n />\n </Button>\n )}\n </form>\n );\n };\n\n export const ReadAloudButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ title, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <ToolbarButton\n data-testid=\"copilot-read-aloud-button\"\n title={title || labels.assistantMessageToolbarReadAloudLabel}\n {...props}\n >\n <CopilotIcon\n name=\"Volume2\"\n className=\"cpk-assistant-message-read-aloud-icon\"\n />\n </ToolbarButton>\n );\n };\n\n export const RegenerateButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ title, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <ToolbarButton\n data-testid=\"copilot-regenerate-button\"\n title={title || labels.assistantMessageToolbarRegenerateLabel}\n {...props}\n >\n <CopilotIcon\n name=\"RefreshCw\"\n className=\"cpk-assistant-message-toolbar-icon\"\n />\n </ToolbarButton>\n );\n };\n}\n\nCopilotChatAssistantMessage.MarkdownRenderer.displayName =\n \"CopilotChatAssistantMessage.MarkdownRenderer\";\nCopilotChatAssistantMessage.Toolbar.displayName =\n \"CopilotChatAssistantMessage.Toolbar\";\nCopilotChatAssistantMessage.CopyButton.displayName =\n \"CopilotChatAssistantMessage.CopyButton\";\nCopilotChatAssistantMessage.InspectorButton.displayName =\n \"CopilotChatAssistantMessage.InspectorButton\";\nCopilotChatAssistantMessage.ThumbsUpButton.displayName =\n \"CopilotChatAssistantMessage.ThumbsUpButton\";\nCopilotChatAssistantMessage.ThumbsDownButton.displayName =\n \"CopilotChatAssistantMessage.ThumbsDownButton\";\nCopilotChatAssistantMessage.FeedbackComment.displayName =\n \"CopilotChatAssistantMessage.FeedbackComment\";\nCopilotChatAssistantMessage.ReadAloudButton.displayName =\n \"CopilotChatAssistantMessage.ReadAloudButton\";\nCopilotChatAssistantMessage.RegenerateButton.displayName =\n \"CopilotChatAssistantMessage.RegenerateButton\";\n\nexport default CopilotChatAssistantMessage;\n","import React, { useCallback, useEffect, useId, useRef, useState } from \"react\";\nimport { createPortal, flushSync } from \"react-dom\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport {\n CopilotChatDefaultLabels,\n ɵbindDialogFocus,\n ɵmorphViewTransition,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\ninterface LightboxProps {\n onClose: () => void;\n /** Accessible name of the dialog, for example the file name. */\n label?: string;\n children: React.ReactNode;\n}\n\n/**\n * A full-screen preview portalled to `document.body`. It closes on Escape, a\n * click on the backdrop, or its close button, which is named by\n * `labels.attachmentPreviewCloseButtonLabel`.\n *\n * It is a modal dialog for assistive technology: focus moves to the close\n * button when it opens, Tab stays inside it, and focus returns to the\n * element that opened it when it closes.\n */\nexport function Lightbox({ onClose, label, children }: LightboxProps) {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const rootRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const handleKey = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") onClose();\n };\n document.addEventListener(\"keydown\", handleKey);\n return () => document.removeEventListener(\"keydown\", handleKey);\n }, [onClose]);\n\n useEffect(() => {\n const root = rootRef.current;\n if (!root) return;\n return ɵbindDialogFocus(root);\n }, []);\n\n if (typeof document === \"undefined\") return null;\n\n return createPortal(\n <div\n ref={rootRef}\n className=\"cpk-attachment-lightbox\"\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label={label}\n onClick={onClose}\n >\n <button\n type=\"button\"\n onClick={onClose}\n className=\"cpk-attachment-lightbox-close-button\"\n aria-label={labels.attachmentPreviewCloseButtonLabel}\n >\n <CopilotIcon name=\"X\" className=\"cpk-attachment-lightbox-close-icon\" />\n </button>\n\n <div onClick={(e) => e.stopPropagation()}>{children}</div>\n </div>,\n document.body,\n );\n}\n\n/**\n * Hook that manages lightbox open/close and uses the View Transition API to\n * morph the thumbnail into fullscreen content.\n *\n * `view-transition-name` must live on exactly ONE element at a time: on the\n * thumbnail before the change and on the lightbox content (bind `vtName`)\n * after it. `flushSync` commits the change inside the transition so the API\n * can snapshot old → new correctly.\n */\nexport function useLightbox() {\n const thumbnailRef = useRef<HTMLElement>(null);\n const [open, setOpen] = useState(false);\n const vtName = useId();\n\n const openLightbox = useCallback(() => {\n ɵmorphViewTransition(\n thumbnailRef.current,\n vtName,\n () => flushSync(() => setOpen(true)),\n \"open\",\n );\n }, [vtName]);\n\n const closeLightbox = useCallback(() => {\n ɵmorphViewTransition(\n thumbnailRef.current,\n vtName,\n () => flushSync(() => setOpen(false)),\n \"close\",\n );\n }, [vtName]);\n\n return {\n thumbnailRef,\n vtName,\n open,\n openLightbox,\n closeLightbox,\n };\n}\n","import React, { memo, useState } from \"react\";\nimport type { InputContentSource } from \"@copilotkit/shared\";\nimport { getSourceUrl, getDocumentIcon } from \"@copilotkit/shared\";\nimport { CopilotChatDefaultLabels } from \"@copilotkit/core\";\nimport { cn } from \"../../lib/utils\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport { Lightbox, useLightbox } from \"./Lightbox\";\n\ninterface CopilotChatAttachmentRendererProps {\n type: \"image\" | \"audio\" | \"video\" | \"document\";\n source: InputContentSource;\n filename?: string;\n className?: string;\n}\n\n/** The chat labels from the nearest chat configuration, or the defaults. */\nfunction useLabels() {\n const config = useCopilotChatConfiguration();\n return config?.labels ?? CopilotChatDefaultLabels;\n}\n\nconst ImageAttachment = memo(function ImageAttachment({\n src,\n className,\n}: {\n src: string;\n className?: string;\n}) {\n const labels = useLabels();\n const [error, setError] = useState(false);\n const { thumbnailRef, vtName, open, openLightbox, closeLightbox } =\n useLightbox();\n\n if (error) {\n return (\n <div\n className={cn(\n \"cpk-attachment-renderer cpk-attachment-renderer-image-error\",\n className,\n )}\n >\n <span>{labels.attachmentImageLoadErrorText}</span>\n </div>\n );\n }\n\n return (\n <>\n <img\n ref={thumbnailRef as React.Ref<HTMLImageElement>}\n src={src}\n alt={labels.attachmentImageAltText}\n className={cn(\n \"cpk-attachment-renderer cpk-attachment-renderer-image\",\n className,\n )}\n onClick={openLightbox}\n onError={() => setError(true)}\n />\n {open && (\n <Lightbox onClose={closeLightbox} label={labels.attachmentImageAltText}>\n <img\n style={{ viewTransitionName: vtName }}\n src={src}\n alt={labels.attachmentImageAltText}\n className=\"cpk-attachment-renderer-lightbox-image\"\n />\n </Lightbox>\n )}\n </>\n );\n});\n\nconst AudioAttachment = memo(function AudioAttachment({\n src,\n filename,\n className,\n}: {\n src: string;\n filename?: string;\n className?: string;\n}) {\n return (\n <div\n className={cn(\n \"cpk-attachment-renderer cpk-attachment-renderer-audio\",\n className,\n )}\n >\n <audio\n src={src}\n controls\n preload=\"metadata\"\n className=\"cpk-attachment-renderer-audio-player\"\n />\n {filename && (\n <span className=\"cpk-attachment-renderer-audio-filename\">\n {filename}\n </span>\n )}\n </div>\n );\n});\n\nconst VideoAttachment = memo(function VideoAttachment({\n src,\n className,\n}: {\n src: string;\n className?: string;\n}) {\n return (\n <video\n src={src}\n controls\n preload=\"metadata\"\n className={cn(\n \"cpk-attachment-renderer cpk-attachment-renderer-video\",\n className,\n )}\n />\n );\n});\n\nconst DocumentAttachment = memo(function DocumentAttachment({\n src,\n source,\n filename,\n className,\n}: {\n src: string;\n source: InputContentSource;\n filename?: string;\n className?: string;\n}) {\n const labels = useLabels();\n const label = filename || source.mimeType || labels.attachmentDocumentAltText;\n\n // `download` is honoured for same-origin, data: and blob: URLs. Browsers\n // ignore it for cross-origin URLs unless the server sends\n // `Content-Disposition: attachment`; `target=\"_blank\"` keeps those from\n // navigating the chat away and lets the file open in a new tab instead.\n return (\n <a\n href={src}\n download={filename ?? \"\"}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n aria-label={label}\n className={cn(\n \"cpk-attachment-renderer cpk-attachment-renderer-document\",\n className,\n )}\n >\n <span className=\"cpk-attachment-renderer-document-icon\">\n {getDocumentIcon(source.mimeType ?? \"\")}\n </span>\n <span className=\"cpk-attachment-renderer-document-name\">\n {filename || source.mimeType || labels.attachmentUnknownTypeText}\n </span>\n </a>\n );\n});\n\nexport const CopilotChatAttachmentRenderer: React.FC<\n CopilotChatAttachmentRendererProps\n> = ({ type, source, filename, className }) => {\n const src = getSourceUrl(source);\n\n switch (type) {\n case \"image\":\n return <ImageAttachment src={src} className={className} />;\n case \"audio\":\n return (\n <AudioAttachment src={src} filename={filename} className={className} />\n );\n case \"video\":\n return <VideoAttachment src={src} className={className} />;\n case \"document\":\n return (\n <DocumentAttachment\n src={src}\n source={source}\n filename={filename}\n className={className}\n />\n );\n }\n};\n\nexport default CopilotChatAttachmentRenderer;\n","import { useMemo } from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport {\n CopilotChatDefaultLabels,\n ɵflattenUserMessageContent,\n ɵgetBranchNavState,\n ɵgetUserMessageMediaFilename,\n ɵgetUserMessageMediaParts,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport { cn } from \"../../lib/utils\";\nimport { Button } from \"../../components/ui/button\";\nimport type { UserMessage } from \"@ag-ui/core\";\nimport {\n Tooltip,\n TooltipContent,\n TooltipTrigger,\n} from \"../../components/ui/tooltip\";\nimport type { WithSlots } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport { copyToClipboard } from \"@copilotkit/shared\";\nimport { CopilotChatAttachmentRenderer } from \"./CopilotChatAttachmentRenderer\";\nimport { useCopyFeedback } from \"./use-copy-feedback\";\n\nexport interface CopilotChatUserMessageOnEditMessageProps {\n message: UserMessage;\n}\n\nexport interface CopilotChatUserMessageOnSwitchToBranchProps {\n message: UserMessage;\n branchIndex: number;\n numberOfBranches: number;\n}\n\nexport type CopilotChatUserMessageProps = WithSlots<\n {\n messageRenderer: typeof CopilotChatUserMessage.MessageRenderer;\n toolbar: typeof CopilotChatUserMessage.Toolbar;\n copyButton: typeof CopilotChatUserMessage.CopyButton;\n editButton: typeof CopilotChatUserMessage.EditButton;\n branchNavigation: typeof CopilotChatUserMessage.BranchNavigation;\n },\n {\n onEditMessage?: (props: CopilotChatUserMessageOnEditMessageProps) => void;\n onSwitchToBranch?: (\n props: CopilotChatUserMessageOnSwitchToBranchProps,\n ) => void;\n message: UserMessage;\n branchIndex?: number;\n numberOfBranches?: number;\n additionalToolbarItems?: React.ReactNode;\n } & React.HTMLAttributes<HTMLDivElement>\n>;\n\nexport function CopilotChatUserMessage({\n message,\n onEditMessage,\n branchIndex,\n numberOfBranches,\n onSwitchToBranch,\n additionalToolbarItems,\n messageRenderer,\n toolbar,\n copyButton,\n editButton,\n branchNavigation,\n children,\n className,\n ...props\n}: CopilotChatUserMessageProps) {\n const flattenedContent = useMemo(\n () => ɵflattenUserMessageContent(message.content),\n [message.content],\n );\n\n const mediaParts = useMemo(\n () => ɵgetUserMessageMediaParts(message.content),\n [message.content],\n );\n\n const BoundMessageRenderer = renderSlot(\n messageRenderer,\n CopilotChatUserMessage.MessageRenderer,\n {\n content: flattenedContent,\n },\n );\n\n const BoundCopyButton = renderSlot(\n copyButton,\n CopilotChatUserMessage.CopyButton,\n {\n onClick: async () => {\n if (flattenedContent) {\n return await copyToClipboard(flattenedContent);\n }\n return false;\n },\n },\n );\n\n const BoundEditButton = renderSlot(\n editButton,\n CopilotChatUserMessage.EditButton,\n {\n onClick: () => onEditMessage?.({ message }),\n },\n );\n\n const BoundBranchNavigation = renderSlot(\n branchNavigation,\n CopilotChatUserMessage.BranchNavigation,\n {\n currentBranch: branchIndex,\n numberOfBranches,\n onSwitchToBranch,\n message,\n },\n );\n\n const { show: showBranchNavigation } = ɵgetBranchNavState({\n branchIndex: branchIndex ?? 0,\n numberOfBranches: numberOfBranches ?? 1,\n canSwitch: onSwitchToBranch !== undefined,\n });\n\n const BoundToolbar = renderSlot(toolbar, CopilotChatUserMessage.Toolbar, {\n children: (\n <div className=\"cpk-user-message-toolbar-items\">\n {additionalToolbarItems}\n {BoundCopyButton}\n {onEditMessage && BoundEditButton}\n {showBranchNavigation && BoundBranchNavigation}\n </div>\n ),\n });\n\n if (children) {\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children({\n messageRenderer: BoundMessageRenderer,\n toolbar: BoundToolbar,\n copyButton: BoundCopyButton,\n editButton: BoundEditButton,\n branchNavigation: BoundBranchNavigation,\n message,\n branchIndex,\n numberOfBranches,\n additionalToolbarItems,\n })}\n </div>\n );\n }\n\n return (\n <div\n data-copilotkit\n data-testid=\"copilot-user-message\"\n className={cn(\n \"copilotKitMessage copilotKitUserMessage cpk-user-message\",\n className,\n )}\n data-message-id={message.id}\n {...props}\n >\n {mediaParts.length > 0 && (\n <div className=\"cpk-user-message-attachments\">\n {mediaParts.map((part, index) => (\n <CopilotChatAttachmentRenderer\n key={index}\n type={part.type}\n source={part.source}\n filename={ɵgetUserMessageMediaFilename(part)}\n />\n ))}\n </div>\n )}\n {BoundMessageRenderer}\n {BoundToolbar}\n </div>\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace CopilotChatUserMessage {\n export const Container: React.FC<\n React.PropsWithChildren<React.HTMLAttributes<HTMLDivElement>>\n > = ({ children, className, ...props }) => (\n <div className={cn(\"cpk-user-message-container\", className)} {...props}>\n {children}\n </div>\n );\n\n export const MessageRenderer: React.FC<{\n content: string;\n className?: string;\n }> = ({ content, className }) => (\n <div className={cn(\"cpk-user-message-bubble\", className)}>{content}</div>\n );\n\n export const Toolbar: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({\n className,\n ...props\n }) => (\n <div\n data-testid=\"copilot-user-toolbar\"\n className={cn(\"cpk-user-message-toolbar\", className)}\n {...props}\n />\n );\n\n export const ToolbarButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement> & {\n title: string;\n children: React.ReactNode;\n }\n > = ({ title, children, className, ...props }) => {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type=\"button\"\n variant=\"assistantMessageToolbarButton\"\n aria-label={title}\n className={className}\n {...props}\n >\n {children}\n </Button>\n </TooltipTrigger>\n <TooltipContent side=\"bottom\">\n <p>{title}</p>\n </TooltipContent>\n </Tooltip>\n );\n };\n\n export const CopyButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement> & { copied?: boolean }\n > = ({ className, title, onClick, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const { copied, markCopied } = useCopyFeedback();\n\n const handleClick = async (event: React.MouseEvent<HTMLButtonElement>) => {\n if (!onClick) return;\n // onClick may return a boolean indicating copy success\n const result: unknown = await Promise.resolve(onClick(event));\n if (result === true) markCopied();\n };\n\n return (\n <ToolbarButton\n data-testid=\"copilot-user-copy-button\"\n title={title || labels.userMessageToolbarCopyMessageLabel}\n onClick={(event) => {\n void handleClick(event);\n }}\n className={className}\n {...props}\n >\n {copied ? (\n <CopilotIcon name=\"Check\" className=\"cpk-user-message-toolbar-icon\" />\n ) : (\n <CopilotIcon name=\"Copy\" className=\"cpk-user-message-toolbar-icon\" />\n )}\n </ToolbarButton>\n );\n };\n\n export const EditButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ className, title, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <ToolbarButton\n data-testid=\"copilot-edit-button\"\n title={title || labels.userMessageToolbarEditMessageLabel}\n className={className}\n {...props}\n >\n <CopilotIcon name=\"Edit\" className=\"cpk-user-message-toolbar-icon\" />\n </ToolbarButton>\n );\n };\n\n /**\n * Previous/next buttons and an \"n/m\" counter for switching between branches\n * of a user message. Renders only with more than one branch and an\n * `onSwitchToBranch` handler. The buttons are named by\n * `labels.userMessageToolbarPreviousBranchLabel` and\n * `labels.userMessageToolbarNextBranchLabel`.\n */\n export const BranchNavigation: React.FC<\n React.HTMLAttributes<HTMLDivElement> & {\n currentBranch?: number;\n numberOfBranches?: number;\n onSwitchToBranch?: (\n props: CopilotChatUserMessageOnSwitchToBranchProps,\n ) => void;\n message: UserMessage;\n }\n > = ({\n className,\n currentBranch = 0,\n numberOfBranches = 1,\n onSwitchToBranch,\n message,\n ...props\n }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n\n const { show, canGoPrev, canGoNext } = ɵgetBranchNavState({\n branchIndex: currentBranch,\n numberOfBranches,\n canSwitch: onSwitchToBranch !== undefined,\n });\n if (!show) return null;\n\n return (\n <div\n data-testid=\"copilot-branch-navigation\"\n className={cn(\"cpk-user-message-branch-navigation\", className)}\n {...props}\n >\n <Button\n type=\"button\"\n variant=\"assistantMessageToolbarButton\"\n onClick={() =>\n onSwitchToBranch?.({\n branchIndex: currentBranch - 1,\n numberOfBranches,\n message,\n })\n }\n disabled={!canGoPrev}\n className=\"cpk-user-message-branch-button\"\n aria-label={labels.userMessageToolbarPreviousBranchLabel}\n >\n <CopilotIcon\n name=\"ChevronLeft\"\n className=\"cpk-user-message-branch-icon\"\n />\n </Button>\n <span className=\"cpk-user-message-branch-counter\">\n {currentBranch + 1}/{numberOfBranches}\n </span>\n <Button\n type=\"button\"\n variant=\"assistantMessageToolbarButton\"\n onClick={() =>\n onSwitchToBranch?.({\n branchIndex: currentBranch + 1,\n numberOfBranches,\n message,\n })\n }\n disabled={!canGoNext}\n className=\"cpk-user-message-branch-button\"\n aria-label={labels.userMessageToolbarNextBranchLabel}\n >\n <CopilotIcon\n name=\"ChevronRight\"\n className=\"cpk-user-message-branch-icon\"\n />\n </Button>\n </div>\n );\n };\n}\n\nCopilotChatUserMessage.Container.displayName =\n \"CopilotChatUserMessage.Container\";\nCopilotChatUserMessage.MessageRenderer.displayName =\n \"CopilotChatUserMessage.MessageRenderer\";\nCopilotChatUserMessage.Toolbar.displayName = \"CopilotChatUserMessage.Toolbar\";\nCopilotChatUserMessage.ToolbarButton.displayName =\n \"CopilotChatUserMessage.ToolbarButton\";\nCopilotChatUserMessage.CopyButton.displayName =\n \"CopilotChatUserMessage.CopyButton\";\nCopilotChatUserMessage.EditButton.displayName =\n \"CopilotChatUserMessage.EditButton\";\nCopilotChatUserMessage.BranchNavigation.displayName =\n \"CopilotChatUserMessage.BranchNavigation\";\n\nexport default CopilotChatUserMessage;\n","import type { ReasoningMessage, Message } from \"@ag-ui/core\";\nimport { useEffect, useState, useSyncExternalStore } from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport { cn } from \"../../lib/utils\";\nimport { StreamingMarkdownDefaultRenderer } from \"./StreamingMarkdownDefaultRenderer\";\nimport type { WithSlots } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport {\n CopilotChatDefaultLabels,\n ɵgetReasoningHeaderLabel,\n ɵReasoningDisclosure,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\nexport type CopilotChatReasoningMessageProps = WithSlots<\n {\n header: typeof CopilotChatReasoningMessage.Header;\n contentView: typeof CopilotChatReasoningMessage.Content;\n toggle: typeof CopilotChatReasoningMessage.Toggle;\n },\n {\n message: ReasoningMessage;\n messages?: Message[];\n isRunning?: boolean;\n /**\n * Whether this is the last message the chat renders. The message view\n * passes it, because the rendered list can differ from `messages` when\n * `transformMessages` drops, replaces or reorders messages. Defaults to\n * comparing against the last entry of `messages`.\n */\n isLatest?: boolean;\n } & React.HTMLAttributes<HTMLDivElement>\n>;\n\n/**\n * A reasoning message as a collapsible block. While the model reasons it is\n * open and the header shows `labels.reasoningMessageThinkingLabel`; when\n * streaming ends it collapses and the header reads\n * `labels.reasoningMessageThoughtForLabel` (\"Thought for 4 seconds\"). The\n * `header` slot also receives `elapsedSeconds`.\n */\nexport function CopilotChatReasoningMessage({\n message,\n messages,\n isRunning,\n isLatest: isLatestProp,\n header,\n contentView,\n toggle,\n children,\n className,\n ...props\n}: CopilotChatReasoningMessageProps) {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const isLatest =\n isLatestProp ?? messages?.[messages.length - 1]?.id === message.id;\n const isStreaming = !!(isRunning && isLatest);\n const hasContent = !!(message.content && message.content.length > 0);\n\n // Open while streaming, auto-collapse when it ends unless the user\n // toggled, and the elapsed time: see core's ɵReasoningDisclosure.\n const [disclosure] = useState(\n () => new ɵReasoningDisclosure({ isStreaming }),\n );\n const { isOpen, elapsedSeconds: elapsed } = useSyncExternalStore(\n disclosure.subscribe,\n disclosure.getSnapshot,\n disclosure.getSnapshot,\n );\n useEffect(() => {\n disclosure.setStreaming(isStreaming);\n }, [disclosure, isStreaming]);\n useEffect(() => disclosure.dispose, [disclosure]);\n\n const handleToggle = hasContent ? disclosure.toggle : undefined;\n\n const label = ɵgetReasoningHeaderLabel(\n { isStreaming, elapsedSeconds: elapsed },\n labels,\n );\n\n const boundHeader = renderSlot(header, CopilotChatReasoningMessage.Header, {\n isOpen,\n label,\n hasContent,\n isStreaming,\n elapsedSeconds: elapsed,\n onClick: handleToggle,\n });\n\n const boundContent = renderSlot(\n contentView,\n CopilotChatReasoningMessage.Content,\n {\n isStreaming,\n hasContent,\n children: message.content,\n },\n );\n\n const boundToggle = renderSlot(toggle, CopilotChatReasoningMessage.Toggle, {\n isOpen,\n children: boundContent,\n });\n\n if (children) {\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children({\n header: boundHeader,\n contentView: boundContent,\n toggle: boundToggle,\n message,\n messages,\n isRunning,\n })}\n </div>\n );\n }\n\n return (\n <div\n className={cn(\"cpk-reasoning-message\", className)}\n data-message-id={message.id}\n {...props}\n >\n {boundHeader}\n {boundToggle}\n </div>\n );\n}\n\nexport namespace CopilotChatReasoningMessage {\n export const Header: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement> & {\n isOpen?: boolean;\n label?: string;\n hasContent?: boolean;\n isStreaming?: boolean;\n /**\n * Seconds spent reasoning so far, updated every second while streaming.\n * The default label formats it in English (\"Thought for 12 seconds\");\n * a custom header can use it to build a localized label.\n */\n elapsedSeconds?: number;\n }\n > = ({\n isOpen,\n label = \"Thoughts\",\n hasContent,\n isStreaming,\n elapsedSeconds: _elapsedSeconds,\n className,\n children: headerChildren,\n ...headerProps\n }) => {\n const isExpandable = !!hasContent;\n\n return (\n <button\n type=\"button\"\n className={cn(\n \"cpk-reasoning-message-header\",\n isExpandable && \"cpk-reasoning-message-header-expandable\",\n className,\n )}\n aria-expanded={isExpandable ? isOpen : undefined}\n {...headerProps}\n >\n <span className=\"cpk-reasoning-message-label\">{label}</span>\n {isStreaming && !hasContent && (\n <span className=\"cpk-reasoning-message-indicator\">\n <span className=\"cpk-reasoning-message-indicator-dot\" />\n </span>\n )}\n {headerChildren}\n {isExpandable && (\n <CopilotIcon\n name=\"ChevronRight\"\n className={cn(\n \"cpk-reasoning-message-chevron\",\n isOpen && \"cpk-reasoning-message-chevron-open\",\n )}\n />\n )}\n </button>\n );\n };\n\n export const Content: React.FC<\n React.HTMLAttributes<HTMLDivElement> & {\n isStreaming?: boolean;\n hasContent?: boolean;\n }\n > = ({\n isStreaming,\n hasContent,\n className,\n children: contentChildren,\n ...contentProps\n }) => {\n // Don't render the content area at all when there's nothing to show\n if (!hasContent && !isStreaming) return null;\n\n return (\n <div\n className={cn(\"cpk-reasoning-message-content\", className)}\n {...contentProps}\n >\n <div className=\"cpk-reasoning-message-text\">\n {/* Reasoning content always uses the built-in streaming renderer; the\n pluggable provider renderer applies to assistant messages only. */}\n <StreamingMarkdownDefaultRenderer\n content={typeof contentChildren === \"string\" ? contentChildren : \"\"}\n isStreaming={isStreaming}\n />\n {isStreaming && hasContent && (\n <span className=\"cpk-reasoning-message-cursor\">\n <span className=\"cpk-reasoning-message-cursor-dot\" />\n </span>\n )}\n </div>\n </div>\n );\n };\n\n export const Toggle: React.FC<\n React.HTMLAttributes<HTMLDivElement> & {\n isOpen?: boolean;\n }\n > = ({ isOpen, className, children: toggleChildren, ...toggleProps }) => {\n return (\n <div\n className={cn(\"cpk-reasoning-message-toggle\", className)}\n style={{ gridTemplateRows: isOpen ? \"1fr\" : \"0fr\" }}\n {...toggleProps}\n >\n <div className=\"cpk-reasoning-message-toggle-content\">\n {toggleChildren}\n </div>\n </div>\n );\n };\n}\n\nCopilotChatReasoningMessage.Header.displayName =\n \"CopilotChatReasoningMessage.Header\";\nCopilotChatReasoningMessage.Content.displayName =\n \"CopilotChatReasoningMessage.Content\";\nCopilotChatReasoningMessage.Toggle.displayName =\n \"CopilotChatReasoningMessage.Toggle\";\n\nexport default CopilotChatReasoningMessage;\n","import React from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\n\nexport interface CopilotChatSuggestionPillProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {\n /** Optional icon to render on the left side when not loading. */\n icon?: React.ReactNode;\n /** Whether the pill should display a loading spinner. */\n isLoading?: boolean;\n}\n\nexport const CopilotChatSuggestionPill = React.forwardRef<\n HTMLButtonElement,\n CopilotChatSuggestionPillProps\n>(function CopilotChatSuggestionPill(\n { className, children, icon, isLoading, type, ...props },\n ref,\n) {\n const showIcon = !isLoading && icon;\n\n return (\n <button\n ref={ref}\n data-copilotkit\n data-testid=\"copilot-suggestion\"\n data-slot=\"suggestion-pill\"\n className={\n className ? `cpk-suggestion-pill ${className}` : \"cpk-suggestion-pill\"\n }\n type={type ?? \"button\"}\n aria-busy={isLoading || undefined}\n disabled={isLoading || props.disabled}\n {...props}\n >\n {isLoading ? (\n <span className=\"cpk-suggestion-pill-icon\">\n <CopilotIcon\n name=\"Loader2\"\n className=\"cpk-suggestion-pill-spinner\"\n aria-hidden=\"true\"\n />\n </span>\n ) : (\n showIcon && <span className=\"cpk-suggestion-pill-icon\">{icon}</span>\n )}\n <span className=\"cpk-suggestion-pill-label\">{children}</span>\n </button>\n );\n});\n\nCopilotChatSuggestionPill.displayName = \"CopilotChatSuggestionPill\";\n\nexport default CopilotChatSuggestionPill;\n","import React from \"react\";\nimport type { Suggestion } from \"@copilotkit/core\";\nimport type { WithSlots } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport { cn } from \"../../lib/utils\";\nimport type { CopilotChatSuggestionPillProps } from \"./CopilotChatSuggestionPill\";\nimport CopilotChatSuggestionPill from \"./CopilotChatSuggestionPill\";\n\nconst DefaultContainer = React.forwardRef<\n HTMLDivElement,\n React.HTMLAttributes<HTMLDivElement>\n>(function DefaultContainer({ className, ...props }, ref) {\n return (\n <div\n ref={ref}\n data-copilotkit\n data-testid=\"copilot-suggestions\"\n className={cn(\"cpk-suggestion-view\", className)}\n {...props}\n />\n );\n});\n\nexport type CopilotChatSuggestionViewProps = WithSlots<\n {\n container: typeof DefaultContainer;\n suggestion: typeof CopilotChatSuggestionPill;\n },\n {\n suggestions: Suggestion[];\n onSelectSuggestion?: (suggestion: Suggestion, index: number) => void;\n loadingIndexes?: ReadonlyArray<number>;\n } & React.HTMLAttributes<HTMLDivElement>\n>;\n\nexport const CopilotChatSuggestionView = React.forwardRef<\n HTMLDivElement,\n CopilotChatSuggestionViewProps\n>(function CopilotChatSuggestionView(\n {\n suggestions,\n onSelectSuggestion,\n loadingIndexes,\n container,\n suggestion: suggestionSlot,\n className,\n children,\n ...restProps\n },\n ref,\n) {\n const loadingSet = React.useMemo(() => {\n if (!loadingIndexes || loadingIndexes.length === 0) {\n return new Set<number>();\n }\n return new Set(loadingIndexes);\n }, [loadingIndexes]);\n\n const ContainerElement = renderSlot(container, DefaultContainer, {\n ref,\n className,\n ...restProps,\n });\n\n const suggestionElements = suggestions.map((suggestion, index) => {\n const isLoading = loadingSet.has(index) || suggestion.isLoading === true;\n const pill = renderSlot<\n typeof CopilotChatSuggestionPill,\n CopilotChatSuggestionPillProps\n >(suggestionSlot, CopilotChatSuggestionPill, {\n children: suggestion.title,\n className: suggestion.className,\n isLoading,\n type: \"button\",\n onClick: () => onSelectSuggestion?.(suggestion, index),\n });\n\n return React.cloneElement(pill, {\n key: `${suggestion.title}-${index}`,\n });\n });\n\n const boundContainer = React.cloneElement(\n ContainerElement,\n undefined,\n suggestionElements,\n );\n\n if (typeof children === \"function\") {\n const sampleSuggestion = renderSlot<\n typeof CopilotChatSuggestionPill,\n CopilotChatSuggestionPillProps\n >(suggestionSlot, CopilotChatSuggestionPill, {\n children: suggestions[0]?.title ?? \"\",\n isLoading:\n suggestions.length > 0\n ? loadingSet.has(0) || suggestions[0]?.isLoading === true\n : false,\n type: \"button\",\n });\n\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children({\n container: boundContainer,\n suggestion: sampleSuggestion,\n suggestions,\n onSelectSuggestion,\n loadingIndexes,\n className,\n ...restProps,\n })}\n </div>\n );\n }\n\n if (children) {\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {boundContainer}\n {children}\n </div>\n );\n }\n\n return boundContainer;\n});\n\nCopilotChatSuggestionView.displayName = \"CopilotChatSuggestionView\";\n\nexport default CopilotChatSuggestionView;\n","import React from \"react\";\n\n/**\n * Provides the scroll container element to child components that need it for\n * virtualization. Set by CopilotChatView.ScrollView; consumed by\n * CopilotChatMessageView to feed useVirtualizer's getScrollElement.\n *\n * Carries the element itself (not a ref) so that context consumers re-render\n * reactively when the scroll container is first mounted.\n */\nexport const ScrollElementContext = React.createContext<HTMLElement | null>(\n null,\n);\n","import React from \"react\";\n\n/**\n * True while the pin-to-bottom behaviour is actively following the bottom of\n * the thread — i.e. `use-stick-to-bottom` will animate the scroll position to\n * the bottom the next time the content grows.\n *\n * Only CopilotChatView's pin-to-bottom branch provides this. The other scroll\n * modes leave it `false`, which is correct: nothing else writes the scroll\n * position on its own, so no one is competing with the virtualizer.\n *\n * Why this exists: the virtualizer and `use-stick-to-bottom` both write\n * `scrollTop` on the same element. The virtualizer writes it to compensate\n * when a row above the viewport turns out taller than its estimate, so that\n * what the reader is looking at does not shift. That compensation is essential\n * while the reader is scrolled up — and pointless while pinned to the bottom,\n * because the pin is about to move the scroll position anyway. Worse than\n * pointless: the compensation changes the virtual container's height, the pin\n * reads that as content growth and animates, the animation brings unmeasured\n * rows into view, they measure, and the two keep shoving each other.\n *\n * Consumed by CopilotChatMessageView to stand the virtualizer down while the\n * pin owns the scroll position.\n */\nexport const ScrollPinnedContext = React.createContext<boolean>(false);\n","import React, { useEffect, useState } from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport {\n CopilotChatDefaultLabels,\n ɵgetWorkSummaryText,\n} from \"@copilotkit/core\";\nimport type { ToolCallEntry } from \"@copilotkit/core\";\nimport { cn } from \"../../lib/utils\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\nexport interface CopilotChatWorkSummaryProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {\n /** The agent is still working on this reply. */\n isWorking: boolean;\n /** Whether the work (narration and tool calls) is showing. */\n isOpen: boolean;\n /** The tool calls the reply made. */\n calls: ToolCallEntry[];\n /**\n * How long the agent has worked on the reply, in ms, summed over its runs\n * so time spent waiting between them doesn't count. Only known for replies\n * this client watched start; without it the summary shows the tool count.\n */\n elapsedMs?: number;\n /** When the current run started (epoch ms), while the agent is working. */\n workingSince?: number;\n}\n\n/** Re-renders every second while `active`, returning the current time. */\nfunction useNow(active: boolean): number {\n const [now, setNow] = useState(() => Date.now());\n useEffect(() => {\n if (!active) return;\n setNow(Date.now());\n const timer = setInterval(() => setNow(Date.now()), 1000);\n return () => clearInterval(timer);\n }, [active]);\n return now;\n}\n\n/**\n * The line at the top of a reply in the `\"turn\"` tool-call display. While the\n * agent works it reads \"Working 4s\". Once the reply is done it reads \"Worked\n * for 9s\" and \"7 tools\", and toggles the work it folded away. The text comes\n * from the `workSummary...` and `toolCall...` chat labels.\n */\nexport function CopilotChatWorkSummary({\n isWorking,\n isOpen,\n calls,\n elapsedMs,\n workingSince,\n className,\n ...props\n}: CopilotChatWorkSummaryProps) {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const now = useNow(isWorking);\n const text = ɵgetWorkSummaryText({\n isWorking,\n calls,\n elapsedMs,\n workingSince,\n now,\n labels,\n });\n\n return (\n <button\n type=\"button\"\n data-copilotkit\n data-testid=\"copilot-work-summary\"\n data-state={isWorking ? \"working\" : \"done\"}\n aria-expanded={isOpen}\n className={cn(\"cpk-work-summary\", className)}\n {...props}\n >\n <span\n className={cn(\"cpk-work-summary-label\", isWorking && \"cpk-shimmer\")}\n >\n {text.label}\n </span>\n {text.detail !== null && (\n <span\n className={cn(\n \"cpk-work-summary-detail\",\n isWorking && \"cpk-work-summary-timer\",\n )}\n >\n {text.detail}\n </span>\n )}\n {text.failed !== null && (\n <span className=\"cpk-work-summary-failed\">{text.failed}</span>\n )}\n <CopilotIcon\n name=\"ChevronRight\"\n aria-hidden=\"true\"\n className={cn(\n \"cpk-work-summary-chevron\",\n isOpen && \"cpk-work-summary-chevron-open\",\n )}\n />\n </button>\n );\n}\n\nexport default CopilotChatWorkSummary;\n","import React from \"react\";\nimport { cn } from \"../../lib/utils\";\nimport type { Message } from \"@ag-ui/core\";\n\n/** Lifecycle state the brain hands the face. */\nexport type IntelligenceIndicatorStatus = \"in-progress\" | \"finished\";\n\nexport interface IntelligenceIndicatorViewProps extends React.HTMLAttributes<HTMLSpanElement> {\n /** The assistant message this indicator is attached to. */\n message: Message;\n /**\n * Whether the intelligence work is still running (`in-progress`) or\n * has settled (`finished`). Drives the icon morph and chrome\n * fade-out via the `data-status` attribute on the wrapper.\n */\n status: IntelligenceIndicatorStatus;\n /** The visible label, e.g. \"Using CopilotKit Intelligence\". */\n label: string;\n}\n\n/**\n * The presentational \"CopilotKit Intelligence\" face — the default\n * rendered by the {@link IntelligenceIndicator} brain and the default\n * value for the `intelligenceIndicator` slot.\n *\n * Layout: a glassmorphism pill (the `__chrome` layer) wrapping an icon\n * and a label. The icon is two overlaid SVG paths — a spinner arc and a\n * checkmark — whose geometry lives in each path's `d` ATTRIBUTE so it\n * renders in every browser (the CSS `d:` property is Chrome-only).\n *\n * Two states, driven by the `data-status` attribute (see styles/css/intelligence-indicator.css\n * for the exact timing):\n * 1. **In-progress.** The arc spins (CSS rotation) inside the pill and\n * the checkmark is hidden. Label + icon are a saturated purple.\n * 2. **Finished.** The arc fades out mid-spin while the checkmark draws\n * itself in upright (animated `stroke-dashoffset`); the pill chrome\n * fades away; and the label + icon settle from purple to a neutral\n * gray, with the label slanting slightly (a `transform: skewX`\n * faux-italic, so it interpolates with the color instead of snapping\n * and never reflows). The result reads as quiet \"history metadata\"\n * rather than an active spinner. The label text itself never changes\n * — the static check plus the color/slant shift carry the \"done\"\n * meaning, so no wording change is needed.\n *\n * All motion is gated behind `prefers-reduced-motion` (styles/css/intelligence-indicator.css):\n * when reduced motion is requested the arc does not spin and the two\n * states swap instantly, without transitions.\n *\n * Customize via the `intelligenceIndicator` slot on `CopilotChat`:\n * a className string restyles the wrapper, a props object tweaks\n * the default (`{ label }`), and a component replaces it entirely\n * with full control over visuals and timing.\n */\nexport function IntelligenceIndicatorView({\n message,\n status,\n label,\n className,\n ...rest\n}: IntelligenceIndicatorViewProps): React.ReactElement {\n return (\n <span\n className={cn(\"cpk-intelligence-indicator\", className)}\n role=\"status\"\n aria-live=\"polite\"\n data-testid={`cpk-intelligence-indicator-${message.id}`}\n data-status={status}\n title={label}\n {...rest}\n >\n {/* Chrome layer — bg, border, shadow, backdrop-blur. Sits behind\n the content via `position: absolute; inset: 0`. Fades to zero\n opacity once the icon morph completes. */}\n <span className=\"cpk-intelligence-indicator__chrome\" aria-hidden=\"true\" />\n\n {/* Content layer — icon + label. Stays put across the whole\n transition; only its color alpha drops on settle. */}\n <span className=\"cpk-intelligence-indicator__content\">\n <svg\n className=\"cpk-intelligence-indicator__icon\"\n viewBox=\"0 0 24 24\"\n width=\"14\"\n height=\"14\"\n aria-hidden=\"true\"\n >\n {/* Two overlaid paths whose geometry lives in the `d`\n ATTRIBUTE (works in every browser — the CSS `d:` property\n is Blink-only, so a stylesheet-driven `d` renders nothing\n in Safari/Firefox). Both paths set `pathLength={1}` so the\n stylesheet can express dashes as plain fractions of the\n shape. The arc is a full circle shown as a partial ring by\n its dash pattern; it spins while in-progress (CSS) and on\n the status flip fades out mid-spin while the checkmark\n draws itself in (see styles/css/intelligence-indicator.css). */}\n <path\n className=\"cpk-intelligence-indicator__icon-arc\"\n pathLength={1}\n d=\"M 12 3 C 17 3 21 7 21 12 C 21 17 17 21 12 21 C 7 21 3 17 3 12 C 3 7 7 3 12 3\"\n />\n <path\n className=\"cpk-intelligence-indicator__icon-check\"\n pathLength={1}\n d=\"M 5 12.5 L 9 16.5 L 19 6.5\"\n />\n </svg>\n <span className=\"cpk-intelligence-indicator__label\">{label}</span>\n </span>\n </span>\n );\n}\n","import React, { useEffect, useMemo, useState } from \"react\";\nimport type { Message } from \"@ag-ui/core\";\nimport { useCopilotKit } from \"../../providers/CopilotKitProvider\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport { useAgent, UseAgentUpdate } from \"../../hooks/use-agent\";\nimport { renderSlot } from \"../../lib/slots\";\nimport type { SlotValue } from \"../../lib/slots\";\nimport { IntelligenceIndicatorView } from \"./IntelligenceIndicatorView\";\n\n/**\n * Grace window before showing the spinner. A matching tool call must\n * remain unresolved (no `tool`-role result message in `agent.messages`)\n * for at least this long before the indicator transitions out of\n * `hidden`. This filters out history-replay flashes — during\n * `connectAgent` replay, tool calls and their results arrive\n * back-to-back in sub-millisecond bursts, so the timer is cancelled\n * before it fires. Live runs cross the threshold easily because the\n * tool actually has to execute.\n */\nconst PENDING_THRESHOLD_MS = 100;\n\n/**\n * Tool-name regex patterns that trigger the indicator. Matches any tool\n * name *containing* the Intelligence MCP server's canonical tool name, so\n * both the bare `copilotkit_knowledge_base_shell` and the namespaced\n * `mcp__<server>__copilotkit_knowledge_base_shell` form (emitted by\n * `@ag-ui/mcp-middleware`) light up the pill. If we add per-instance\n * customization later (e.g. a `CopilotKitProvider` prop or a runtime-info\n * field), this constant becomes the fallback.\n */\nconst DEFAULT_TOOL_PATTERNS: readonly RegExp[] = [\n /copilotkit_knowledge_base_shell/,\n];\n\n/**\n * Phase machine. Once `finished` is reached the indicator persists\n * indefinitely; placement (one indicator per turn, at the turn's first\n * bash-using message) is owned by `getIntelligenceTurnAnchors`, not by\n * this machine.\n */\nexport type Phase = \"hidden\" | \"spinner\" | \"finished\";\n\n/**\n * Phase to start in when an indicator first mounts. A turn that is already\n * complete at mount jumps straight to `finished` — no `hidden` flash, no\n * spinner blip — which is what makes scrolled-back / replayed history render\n * its indicators directly in the finished state.\n *\n * Pure and timing-free on purpose: the grace window ({@link\n * PENDING_THRESHOLD_MS}) only controls *when* the live transition is applied;\n * these functions decide *what* it resolves to, so the decision can be unit\n * tested deterministically without any timers.\n */\nexport function initialIndicatorPhase(turnComplete: boolean): Phase {\n return turnComplete ? \"finished\" : \"hidden\";\n}\n\n/**\n * Phase the grace window resolves to once it elapses:\n * - completed turn → `finished` (replay-flash suppression: a tool whose\n * result lands within the window skips the spinner entirely),\n * - a still-pending matching tool call → `spinner`,\n * - otherwise stay `hidden` (the matching tool call hasn't landed yet).\n */\nexport function resolveGracePhase(\n turnComplete: boolean,\n hasPending: boolean,\n): Phase {\n if (turnComplete) return \"finished\";\n if (hasPending) return \"spinner\";\n return \"hidden\";\n}\n\nexport interface IntelligenceIndicatorProps {\n /** The message this indicator is attached to. */\n message: Message;\n /**\n * Agent id whose run state the indicator tracks. Pass through from\n * the surrounding chat configuration; mounting from\n * `CopilotChatMessageView` resolves this automatically.\n */\n agentId: string;\n /**\n * Optional override for the visible label. Defaults to\n * \"CopilotKit Intelligence\".\n */\n label?: string;\n /**\n * Slot override for the presentational face. A className string, a\n * props object, or a full replacement component — see\n * {@link IntelligenceIndicatorView}. Forwarded from the\n * `intelligenceIndicator` slot on `CopilotChat`.\n */\n intelligenceIndicator?: SlotValue<typeof IntelligenceIndicatorView>;\n}\n\nconst isMatchingToolCallName = (name: unknown): boolean =>\n typeof name === \"string\" && DEFAULT_TOOL_PATTERNS.some((p) => p.test(name));\n\nconst messageHasMatchingToolCall = (m: Message): boolean => {\n if (m.role !== \"assistant\") return false;\n const tcs = Array.isArray(m.toolCalls) ? m.toolCalls : [];\n return tcs.some((tc) => isMatchingToolCallName(tc?.function?.name));\n};\n\n/**\n * Stable turn id for the messages that precede the first user message (a turn\n * with no opening user message of its own). Used as the React key so the\n * indicator for that turn never collides with a real user-message id.\n */\nexport const INTELLIGENCE_TURN_HEAD = \"__cpk_turn_head__\";\n\n/**\n * Map each Intelligence-using turn to its anchor message — the FIRST bash-using\n * assistant message of the turn — and a stable turn id (the id of the user\n * message that opened the turn, or {@link INTELLIGENCE_TURN_HEAD} for the\n * pre-first-user turn). Returns `Map<anchorMessageId, turnId>`.\n *\n * Anchoring to the FIRST (not last) bash-using message keeps the indicator\n * fixed in place for the whole turn: later bash steps don't reposition it, so\n * the spinner never abruptly jumps mid-turn (bug 1). `CopilotChatMessageView`\n * emits exactly one `IntelligenceIndicator` per entry, keyed by the turn id and\n * positioned at the anchor; the per-turn key also lets every past turn keep its\n * own indicator in scroll-back.\n *\n * `visibleMessages` is what actually renders, when that differs from\n * `messages` (the chat's `transformMessages`). Turns are still read from the\n * full list, so hiding a user message does not merge its turn into the one\n * before it, and anchors are only chosen among visible messages. A message the\n * transform built itself joins the turn of the visible message before it.\n */\nexport function getIntelligenceTurnAnchors(\n messages: readonly Message[],\n visibleMessages: readonly Message[] = messages,\n): Map<string, string> {\n const turnOfMessage = new Map<string, string>();\n let turnId = INTELLIGENCE_TURN_HEAD;\n for (const m of messages) {\n if (m.role === \"user\") turnId = m.id;\n turnOfMessage.set(m.id, turnId);\n }\n\n const anchors = new Map<string, string>();\n const anchoredTurns = new Set<string>();\n let currentTurn = INTELLIGENCE_TURN_HEAD;\n for (const m of visibleMessages) {\n currentTurn = turnOfMessage.get(m.id) ?? currentTurn;\n if (m.role === \"user\") continue;\n // First bash-using message of the turn wins; later ones don't move it.\n if (!anchoredTurns.has(currentTurn) && messageHasMatchingToolCall(m)) {\n anchors.set(m.id, currentTurn);\n anchoredTurns.add(currentTurn);\n }\n }\n return anchors;\n}\n\n/**\n * \"Tool-call-like\" messages do NOT count as a real follow-up: tool\n * result messages, assistant messages that carry tool calls, and\n * empty-content assistant messages (which some providers emit as a\n * standalone wrapper around a batch of tool calls). A real follow-up\n * is anything else — most importantly an assistant message with prose\n * content, or a fresh user message.\n */\nconst isToolCallLikeMessage = (m: Message): boolean => {\n if (m.role === \"tool\") return true;\n if (m.role === \"assistant\") {\n const tcs = Array.isArray(m.toolCalls) ? m.toolCalls : [];\n if (tcs.length > 0) return true;\n const content = m.content;\n return typeof content !== \"string\" || content.trim().length === 0;\n }\n return false;\n};\n\n/**\n * The \"Using CopilotKit Intelligence\" indicator brain. Auto-mounted by\n * `CopilotChatMessageView` — once per Intelligence-using turn, at that\n * turn's anchor message and keyed by the turn id (see\n * {@link getIntelligenceTurnAnchors}). Callers do not register this\n * themselves. It owns the run subscription and the phase machine and\n * renders its swappable face via the `intelligenceIndicator` slot.\n *\n * Placement (which message anchors the turn) is decided by the view, so\n * this component does not self-gate its own placement; it only derives\n * in-progress/finished for the turn it was mounted on.\n *\n * Render gates (all must hold):\n * 1. `copilotkit.intelligence !== undefined`\n * 2. The (anchor) message is an assistant message with at least one\n * tool call whose name matches {@link DEFAULT_TOOL_PATTERNS}.\n * 3. The phase machine is past `hidden`.\n *\n * Because the view keys each indicator by its turn id, the instance moves\n * with the anchor across a hand-off (no remount, no spinner restart), and\n * every prior Intelligence-using turn keeps its own persistent indicator\n * in chat history.\n *\n * Phase machine (per-instance, all timers local):\n * - Starts in `hidden`, unless the message mounts onto an\n * already-completed turn (no pending work, agent stopped or a\n * real follow-up already present), in which case the lazy\n * `useState` initializer starts directly in `finished`. This is\n * what avoids a \"hidden flash\" on history replay.\n * - `hidden → spinner` once a matching tool call has been pending\n * (no `tool`-role result with a matching `toolCallId`) for\n * {@link PENDING_THRESHOLD_MS}. Replay flashes (tool call + result\n * in the same tick) never cross this threshold.\n * - `hidden → finished` if after the grace window the turn is\n * already complete (no pending work AND\n * `sawRealFollowup || !agent.isRunning`). Handles very fast tools\n * whose result lands within the grace window.\n * - `spinner → finished` as soon as EITHER `agent.isRunning` flips\n * false OR a non-tool-call-like message appears later in\n * `agent.messages` (i.e. the agent produced a \"real\" follow-up —\n * prose answer or a new user turn).\n * - `finished` is terminal: the indicator settles into its\n * persistent tag form and stays mounted.\n */\nexport function IntelligenceIndicator(\n props: IntelligenceIndicatorProps,\n): React.ReactElement | null {\n const {\n message,\n agentId,\n label = \"CopilotKit Intelligence\",\n intelligenceIndicator,\n } = props;\n\n const { copilotkit } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const { agent } = useAgent({\n agentId,\n updates: [\n UseAgentUpdate.OnRunStatusChanged,\n UseAgentUpdate.OnMessagesChanged,\n ],\n });\n\n // IDs of matching tool calls on this message.\n const matchingToolCallIds = useMemo<readonly string[]>(() => {\n if (message.role !== \"assistant\") return [];\n const tcs = Array.isArray(message.toolCalls) ? message.toolCalls : [];\n const ids: string[] = [];\n for (const tc of tcs) {\n if (isMatchingToolCallName(tc?.function?.name) && tc?.id) {\n ids.push(tc.id);\n }\n }\n return ids;\n }, [message]);\n\n // Pending = at least one matching tool call has no corresponding\n // `tool`-role result message in `agent.messages`.\n const hasPending = useMemo(() => {\n if (matchingToolCallIds.length === 0) return false;\n const resolved = new Set<string>();\n for (const m of agent.messages) {\n if (m.role === \"tool\" && m.toolCallId) resolved.add(m.toolCallId);\n }\n return matchingToolCallIds.some((id) => !resolved.has(id));\n }, [matchingToolCallIds, agent.messages]);\n\n // True once the agent has produced a \"real\" message *after* this\n // assistant message — prose, a new user turn, etc. Tool-call-like\n // messages do not count (they're part of the same tool flow).\n const sawRealFollowup = useMemo(() => {\n const idx = agent.messages.findIndex((m) => m.id === message.id);\n if (idx < 0) return false;\n for (let i = idx + 1; i < agent.messages.length; i += 1) {\n if (!isToolCallLikeMessage(agent.messages[i]!)) return true;\n }\n return false;\n }, [agent.messages, message.id]);\n\n // Turn-completion signal — set the moment the agent stops running or\n // a \"real\" follow-up (prose / user turn) appears after this message.\n // Independent of whether the pending tool call resolved; if the run\n // finishes with a still-unresolved match (rare in production, common\n // in tests), the indicator should still settle.\n const turnComplete = sawRealFollowup || !agent.isRunning;\n\n // Lazy init: if this indicator mounts onto a message whose turn has\n // already completed (e.g. history replay finished before mount),\n // skip directly to `finished` — no `hidden` flash, no spinner blip.\n const [phase, setPhase] = useState<Phase>(() =>\n initialIndicatorPhase(turnComplete),\n );\n\n // hidden → spinner OR hidden → finished (after grace window). The grace\n // window only controls the *timing*; `resolveGracePhase` owns the decision.\n // Resolving back to `hidden` (matching tool call not landed yet) is a\n // no-op `setPhase`, preserving the \"only leave hidden once decided\" rule.\n useEffect(() => {\n if (phase !== \"hidden\") return undefined;\n const t = setTimeout(() => {\n setPhase(resolveGracePhase(turnComplete, hasPending));\n }, PENDING_THRESHOLD_MS);\n return () => clearTimeout(t);\n }, [phase, hasPending, turnComplete]);\n\n // spinner → finished\n useEffect(() => {\n if (phase !== \"spinner\") return undefined;\n if (turnComplete) {\n setPhase(\"finished\");\n }\n return undefined;\n }, [phase, turnComplete]);\n\n // ─── Render gates ────────────────────────────────────────────────────\n // Hooks above MUST run unconditionally; bail with `null` only after.\n\n if (copilotkit.intelligence === undefined) return null;\n if (!config) return null;\n if (phase === \"hidden\") return null;\n\n if (message.role !== \"assistant\") return null;\n if (!messageHasMatchingToolCall(message)) return null;\n\n // Placement (which message anchors this turn's indicator) is decided by\n // `CopilotChatMessageView` via `getIntelligenceTurnAnchors`, which mounts\n // exactly one instance per turn keyed by the turn id. The brain therefore\n // does not decide its own placement; it only owns the run-status →\n // in-progress/finished derivation for the turn it anchors.\n\n // ─── Render the (swappable) face ──────────────────────────────────────\n\n const status = phase === \"finished\" ? \"finished\" : \"in-progress\";\n\n return renderSlot(intelligenceIndicator, IntelligenceIndicatorView, {\n message,\n status,\n label,\n });\n}\n","import React, {\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { observeElementRect, useVirtualizer } from \"@tanstack/react-virtual\";\nimport type { VirtualItem, Virtualizer } from \"@tanstack/react-virtual\";\nimport { ScrollElementContext } from \"./scroll-element-context\";\nimport { ScrollPinnedContext } from \"./scroll-pinned-context\";\nimport type { WithSlots } from \"../../lib/slots\";\nimport { renderSlot, isReactComponentType } from \"../../lib/slots\";\nimport CopilotChatAssistantMessage from \"./CopilotChatAssistantMessage\";\nimport type {\n CopilotChatAssistantMessageProps,\n CopilotChatFeedbackMessage,\n} from \"./CopilotChatAssistantMessage\";\nimport type { CopilotChatUserMessageProps } from \"./CopilotChatUserMessage\";\nimport type { CopilotChatReasoningMessageProps } from \"./CopilotChatReasoningMessage\";\nimport CopilotChatUserMessage from \"./CopilotChatUserMessage\";\nimport CopilotChatReasoningMessage from \"./CopilotChatReasoningMessage\";\nimport {\n MessageFeedbackScopeContext,\n useLearningFeedbackEnabled,\n} from \"./message-feedback\";\nimport type { MessageFeedbackScope } from \"./message-feedback\";\nimport CopilotChatWorkSummary from \"./CopilotChatWorkSummary\";\nimport { Collapsible } from \"./CopilotChatToolCallGroup\";\nimport { ToolCallDisplayContext } from \"./tool-call-display-context\";\nimport type { ToolCallDisplayContextValue } from \"./tool-call-display-context\";\nimport {\n ɵcreateMessageViewModel,\n ɵdeduplicateMessages,\n ɵduplicateMessagesWarning,\n ɵgetMessageRunStateSnapshot,\n ɵresolveAgentId,\n} from \"@copilotkit/core\";\nimport type {\n CopilotChatToolCallDisplay,\n ToolCallEntry,\n} from \"@copilotkit/core\";\nimport { useToolCallRendererNames } from \"../../hooks/use-render-tool-call\";\nimport type {\n ActivityMessage,\n AssistantMessage,\n Message,\n ReasoningMessage,\n ToolMessage,\n UserMessage,\n} from \"@ag-ui/core\";\nimport { cn } from \"../../lib/utils\";\nimport { useRenderActivityMessage, useRenderCustomMessages } from \"../../hooks\";\nimport { useCopilotKit } from \"../../providers/CopilotKitProvider\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport {\n IntelligenceIndicator,\n getIntelligenceTurnAnchors,\n} from \"../intelligence-indicator\";\nimport type { IntelligenceIndicatorView } from \"../intelligence-indicator\";\nimport { useDefaultAgentId } from \"../../context\";\nimport {\n commitRowKeyStore,\n createRowKeyStore,\n resolveRowRenderKeysById,\n} from \"@copilotkit/shared\";\nimport type { RowKeyStore } from \"@copilotkit/shared\";\n\n/**\n * Resolves a slot value into a { Component, slotProps } pair, handling the three\n * slot forms: a component type, a className string, or a partial-props object.\n */\nfunction resolveSlotComponent<T extends React.ComponentType<any>>(\n slot: unknown,\n DefaultComponent: T,\n): { Component: T; slotProps: Partial<React.ComponentProps<T>> | undefined } {\n if (isReactComponentType(slot)) {\n return { Component: slot as T, slotProps: undefined };\n }\n if (typeof slot === \"string\") {\n return {\n Component: DefaultComponent,\n slotProps: { className: slot } as unknown as Partial<\n React.ComponentProps<T>\n >,\n };\n }\n if (slot && typeof slot === \"object\") {\n return {\n Component: DefaultComponent,\n slotProps: slot as Partial<React.ComponentProps<T>>,\n };\n }\n return { Component: DefaultComponent, slotProps: undefined };\n}\n\n/**\n * Memoized wrapper for assistant messages to prevent re-renders when other messages change.\n */\nconst MemoizedAssistantMessage = React.memo(\n function MemoizedAssistantMessage({\n message,\n messages,\n isRunning,\n isLatest,\n AssistantMessageComponent,\n slotProps,\n }: {\n message: AssistantMessage;\n messages: Message[];\n isRunning: boolean;\n isLatest: boolean;\n AssistantMessageComponent: typeof CopilotChatAssistantMessage;\n slotProps?: Partial<\n React.ComponentProps<typeof CopilotChatAssistantMessage>\n >;\n }) {\n return (\n <AssistantMessageComponent\n message={message}\n messages={messages}\n isRunning={isRunning}\n isLatest={isLatest}\n {...slotProps}\n />\n );\n },\n (prevProps, nextProps) => {\n // Only re-render if this specific message changed\n if (prevProps.message.id !== nextProps.message.id) return false;\n if (prevProps.message.content !== nextProps.message.content) return false;\n\n // Compare tool calls if present\n const prevToolCalls = prevProps.message.toolCalls;\n const nextToolCalls = nextProps.message.toolCalls;\n if (prevToolCalls?.length !== nextToolCalls?.length) return false;\n if (prevToolCalls && nextToolCalls) {\n for (let i = 0; i < prevToolCalls.length; i++) {\n const prevTc = prevToolCalls[i]!;\n const nextTc = nextToolCalls[i]!;\n if (prevTc.id !== nextTc.id) return false;\n if (prevTc.function.arguments !== nextTc.function.arguments)\n return false;\n }\n }\n\n // Check if tool results changed for this message's tool calls.\n // Tool results are separate messages with role=\"tool\" that reference tool call IDs.\n if (prevToolCalls && prevToolCalls.length > 0) {\n const toolCallIds = new Set(prevToolCalls.map((tc) => tc.id));\n\n const prevToolResults = prevProps.messages.filter(\n (m): m is ToolMessage =>\n m.role === \"tool\" && toolCallIds.has(m.toolCallId),\n );\n const nextToolResults = nextProps.messages.filter(\n (m): m is ToolMessage =>\n m.role === \"tool\" && toolCallIds.has(m.toolCallId),\n );\n\n if (prevToolResults.length !== nextToolResults.length) return false;\n\n for (let i = 0; i < prevToolResults.length; i++) {\n if (prevToolResults[i]!.content !== nextToolResults[i]!.content)\n return false;\n }\n }\n\n // A message renders as in-progress (toolbar hidden) only while it is the\n // latest one and the run is going. Re-render when that flips, including a\n // message that stops being the latest mid-run; not for every change in\n // either flag, so earlier messages stay put while a new one streams in.\n if (\n (prevProps.isRunning && prevProps.isLatest) !==\n (nextProps.isRunning && nextProps.isLatest)\n )\n return false;\n\n // Check if component reference changed\n if (\n prevProps.AssistantMessageComponent !==\n nextProps.AssistantMessageComponent\n )\n return false;\n\n // Check if slot props changed\n if (prevProps.slotProps !== nextProps.slotProps) return false;\n\n return true;\n },\n);\n\n/**\n * Memoized wrapper for user messages to prevent re-renders when other messages change.\n */\nconst MemoizedUserMessage = React.memo(\n function MemoizedUserMessage({\n message,\n UserMessageComponent,\n slotProps,\n }: {\n message: UserMessage;\n UserMessageComponent: typeof CopilotChatUserMessage;\n slotProps?: Partial<React.ComponentProps<typeof CopilotChatUserMessage>>;\n }) {\n return <UserMessageComponent message={message} {...slotProps} />;\n },\n (prevProps, nextProps) => {\n // Only re-render if this specific message changed\n if (prevProps.message.id !== nextProps.message.id) return false;\n if (prevProps.message.content !== nextProps.message.content) return false;\n if (prevProps.UserMessageComponent !== nextProps.UserMessageComponent)\n return false;\n // Check if slot props changed\n if (prevProps.slotProps !== nextProps.slotProps) return false;\n return true;\n },\n);\n\n/**\n * Memoized wrapper for activity messages to prevent re-renders when other messages change.\n */\nconst MemoizedActivityMessage = React.memo(\n function MemoizedActivityMessage({\n message,\n renderActivityMessage,\n }: {\n message: ActivityMessage;\n renderActivityMessage: (\n message: ActivityMessage,\n ) => React.ReactElement | null;\n }) {\n return renderActivityMessage(message);\n },\n (prevProps, nextProps) => {\n // Message ID changed = different message, must re-render\n if (prevProps.message.id !== nextProps.message.id) return false;\n\n // Activity type changed = must re-render\n if (prevProps.message.activityType !== nextProps.message.activityType)\n return false;\n\n // Compare content using JSON.stringify (native code, handles deep comparison)\n if (\n JSON.stringify(prevProps.message.content) !==\n JSON.stringify(nextProps.message.content)\n )\n return false;\n\n return true;\n },\n);\n\n/**\n * Memoized wrapper for reasoning messages to prevent re-renders when other messages change.\n */\nconst MemoizedReasoningMessage = React.memo(\n function MemoizedReasoningMessage({\n message,\n messages,\n isRunning,\n isLatest,\n ReasoningMessageComponent,\n slotProps,\n }: {\n message: ReasoningMessage;\n messages: Message[];\n isRunning: boolean;\n isLatest: boolean;\n ReasoningMessageComponent: typeof CopilotChatReasoningMessage;\n slotProps?: Partial<\n React.ComponentProps<typeof CopilotChatReasoningMessage>\n >;\n }) {\n return (\n <ReasoningMessageComponent\n message={message}\n messages={messages}\n isRunning={isRunning}\n isLatest={isLatest}\n {...slotProps}\n />\n );\n },\n (prevProps, nextProps) => {\n // Only re-render if this specific message changed\n if (prevProps.message.id !== nextProps.message.id) return false;\n if (prevProps.message.content !== nextProps.message.content) return false;\n\n // Re-render when \"latest\" status changes (e.g. reasoning message is no longer the last message\n // because a text message was added after it — this transitions isStreaming from true to false)\n if (prevProps.isLatest !== nextProps.isLatest) return false;\n\n // Only care about isRunning if this message is CURRENTLY the latest\n if (nextProps.isLatest && prevProps.isRunning !== nextProps.isRunning)\n return false;\n\n // Check if component reference changed\n if (\n prevProps.ReasoningMessageComponent !==\n nextProps.ReasoningMessageComponent\n )\n return false;\n\n // Check if slot props changed\n if (prevProps.slotProps !== nextProps.slotProps) return false;\n\n return true;\n },\n);\n\n/**\n * Memoized wrapper for custom messages to prevent re-renders when other messages change.\n */\nconst MemoizedCustomMessage = React.memo(\n function MemoizedCustomMessage({\n message,\n position,\n renderCustomMessage,\n }: {\n message: Message;\n position: \"before\" | \"after\";\n renderCustomMessage: (params: {\n message: Message;\n position: \"before\" | \"after\";\n }) => React.ReactElement | null;\n stateSnapshot?: unknown;\n }) {\n return renderCustomMessage({ message, position });\n },\n (prevProps, nextProps) => {\n // Only re-render if the message or position changed\n if (prevProps.message.id !== nextProps.message.id) return false;\n if (prevProps.position !== nextProps.position) return false;\n // Compare message content - for assistant messages this is a string, for others may differ\n if (prevProps.message.content !== nextProps.message.content) return false;\n if (prevProps.message.role !== nextProps.message.role) return false;\n // Compare state snapshot - custom renderers may depend on state\n if (\n JSON.stringify(prevProps.stateSnapshot) !==\n JSON.stringify(nextProps.stateSnapshot)\n )\n return false;\n // Note: We don't compare renderCustomMessage function reference because it changes\n // frequently. The message and state comparison is sufficient to determine if a re-render is needed.\n return true;\n },\n);\n\n/** What the view passes the wrapper of a message group. */\nexport interface MessageGroupWrapperProps<S = unknown> {\n /** The group's key, as returned by `groupMessages`. */\n groupKey: string;\n /** The messages in the group, in order. */\n messages: Message[];\n /** The default rendering of the group's messages. */\n children: React.ReactNode;\n /**\n * State the view keeps for this group, keyed by `groupKey`. It survives the\n * row leaving the window and the wrapper remounting, is dropped once the key\n * no longer appears, and is cleared when the thread changes. `undefined`\n * until first set.\n */\n state: S | undefined;\n setState: (next: S) => void;\n}\n\n/** Several messages rendered as one row, inside an app-provided wrapper. */\nexport interface MessageGroup<S = unknown> {\n type: \"group\";\n /**\n * Identifies the group across renders: its React key and the key its state\n * is held under. Keep it stable while the thread streams, e.g. the id of the\n * group's first message.\n */\n key: string;\n messages: Message[];\n /**\n * Define it once at module level. A component created inside\n * `groupMessages` is a new type on every call and remounts each time.\n */\n wrapper: React.ComponentType<MessageGroupWrapperProps<S>>;\n}\n\n/** One row of the message list: a single message, or a group of them. */\nexport type MessageRow = { type: \"message\"; message: Message } | MessageGroup;\n\n/** The key the virtualizer gives a row; measured sizes are stored under it. */\ntype RowSizeKey = ReturnType<\n Virtualizer<HTMLElement, Element>[\"options\"][\"getItemKey\"]\n>;\n\n/** A row holding a single message, rendered as it would be ungrouped. */\nexport function messageRow(message: Message): MessageRow {\n return { type: \"message\", message };\n}\n\n/** A row holding a group of messages, rendered inside `wrapper`. */\nexport function messageGroup<S>(\n group: Omit<MessageGroup<S>, \"type\">,\n): MessageRow {\n // A group's state type is between it and its own wrapper; the row list only\n // hands back what that wrapper set. Erased once here so groups with\n // different state types can share one array.\n return { type: \"group\", ...group } as unknown as MessageGroup;\n}\n\nconst GROUP_ROW_KEY_PREFIX = \"copilotkit-group:\";\n\nexport type CopilotChatMessageViewProps = Omit<\n WithSlots<\n {\n // Props-based, like CopilotChatView's `input` (#7158): a plain FC\n // assigns without the message components' namespace statics (Header,\n // Toolbar, MarkdownRenderer, …), which resolveSlotComponent never reads.\n assistantMessage: React.ComponentType<CopilotChatAssistantMessageProps>;\n userMessage: React.ComponentType<CopilotChatUserMessageProps>;\n reasoningMessage: React.ComponentType<CopilotChatReasoningMessageProps>;\n cursor: typeof CopilotChatMessageView.Cursor;\n intelligenceIndicator: typeof IntelligenceIndicatorView;\n /** The \"Working… / Worked for 9s\" line of the `\"turn\"` tool-call display. */\n workSummary: typeof CopilotChatWorkSummary;\n },\n {\n isRunning?: boolean;\n messages?: Message[];\n /**\n * Reshapes the message list before it renders: drop, replace or reorder\n * messages with the whole list in view. Receives the list after duplicate\n * ids are merged. Row keys, virtualization and rendering all work off\n * the returned list, so a dropped message takes no row.\n *\n * Tool-call cards still look up their results in the full list, so\n * hiding tool-result messages here does not strip results from them.\n *\n * Memoized on the input list and this function — pass a stable function\n * (e.g. `useCallback`) or it reruns on every render.\n */\n transformMessages?: (messages: Message[]) => Message[];\n /**\n * Splits the message list into rows. Return `messageRow(message)` for a\n * message that renders on its own, and `messageGroup({ key, messages,\n * wrapper })` for messages that render together inside `wrapper` — a\n * collapsible block of tool calls, say. Receives the list after\n * `transformMessages`. Each row is one virtualized row.\n *\n * Return each message in at most one row. Tool-call cards still find\n * their results in the full list.\n *\n * Memoized on its input and this function — pass a stable function.\n */\n groupMessages?: (messages: Message[]) => MessageRow[];\n /**\n * Whether reply thumbs record ratings for Automatic Learning once a\n * Trajectory has started. Defaults to `true`; set `false` to keep the\n * thumbs to your own `onThumbsUp` / `onThumbsDown` handlers and slots.\n */\n messageFeedback?: boolean;\n /**\n * How tool calls show. Defaults to `\"grouped\"`: calls made in a row\n * share one card that opens to a row per call. `\"line\"` and `\"stacked\"`\n * group them too; `\"turn\"` folds a reply's whole working phase into\n * \"Worked for 9s\" once it's done; `\"separate\"` gives every call its own\n * card. Calls with a renderer of their own always show on their own.\n */\n toolCallDisplay?: CopilotChatToolCallDisplay;\n } & React.HTMLAttributes<HTMLDivElement>\n >,\n \"children\"\n> & {\n children?: (props: {\n isRunning: boolean;\n messages: Message[];\n messageElements: React.ReactElement[];\n interruptElement: React.ReactElement | null;\n }) => React.ReactElement;\n};\n\n// Above this many messages, activate TanStack Virtual to avoid mounting the\n// full DOM tree. Below the threshold the overhead of virtualization isn't\n// worth it and the simpler flat render is faster.\nconst VIRTUALIZE_THRESHOLD = 50;\n\nexport function CopilotChatMessageView({\n messages = [],\n assistantMessage,\n userMessage,\n reasoningMessage,\n cursor,\n intelligenceIndicator,\n workSummary,\n isRunning = false,\n transformMessages,\n groupMessages,\n messageFeedback = true,\n toolCallDisplay = \"grouped\",\n children,\n className,\n ...props\n}: CopilotChatMessageViewProps) {\n const isPinnedToBottom = useContext(ScrollPinnedContext);\n const renderCustomMessage = useRenderCustomMessages();\n const { renderActivityMessage } = useRenderActivityMessage();\n const { copilotkit, showIntelligenceIndicator = true } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const providerAgentId = useDefaultAgentId();\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n // Subscribe to state changes so custom message renderers re-render when state updates.\n useEffect(() => {\n if (!config?.agentId) return;\n const agent = copilotkit.getAgent(config.agentId);\n if (!agent) return;\n\n const subscription = agent.subscribe({\n onStateChanged: forceUpdate,\n });\n return () => subscription.unsubscribe();\n }, [config?.agentId, copilotkit, forceUpdate]);\n\n // Subscribe to interrupt element changes for in-chat rendering.\n const [interruptElement, setInterruptElement] =\n useState<React.ReactElement | null>(null);\n useEffect(() => {\n setInterruptElement(copilotkit.interruptElement);\n const subscription = copilotkit.subscribe({\n onInterruptElementChanged: ({ interruptElement }) => {\n setInterruptElement(interruptElement);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n // The run state a custom message renderer sees, used for memoization.\n const getStateSnapshotForMessage = (messageId: string): unknown =>\n config\n ? ɵgetMessageRunStateSnapshot(copilotkit, {\n agentId: config.agentId,\n threadId: config.threadId,\n messageId,\n })\n : undefined;\n\n const deduplicatedMessages = useMemo(\n () => ɵdeduplicateMessages(messages),\n [messages],\n );\n\n // What actually renders. Everything below — row keys, virtualization,\n // rendering — works off this list. Tool-result lookups keep using the full\n // `messages`, so a transform that hides tool results cannot break the cards\n // that display them.\n const transformedMessages = useMemo(\n () =>\n transformMessages\n ? transformMessages(deduplicatedMessages)\n : deduplicatedMessages,\n [deduplicatedMessages, transformMessages],\n );\n\n // One entry per virtualized row. Without grouping, every message is its own.\n const rows = useMemo<MessageRow[]>(\n () =>\n groupMessages\n ? groupMessages(transformedMessages)\n : transformedMessages.map(messageRow),\n [transformedMessages, groupMessages],\n );\n\n // Every message that renders, in the order it renders, whether on its own\n // row or inside a group. The message-level machinery below (row keys, the\n // latest message, Intelligence anchors) reads this, not `rows`.\n const renderedMessages = useMemo(\n () =>\n groupMessages\n ? rows.flatMap((row) =>\n row.type === \"group\" ? row.messages : [row.message],\n )\n : transformedMessages,\n [rows, groupMessages, transformedMessages],\n );\n\n // \"Latest\" means the last row on screen, not the last entry of `messages`:\n // a transform can drop, replace or reorder the tail. Streaming state and the\n // assistant toolbar key off this.\n const latestRenderedId = renderedMessages[renderedMessages.length - 1]?.id;\n\n // ---------------------------------------------------------------------------\n // Tool-call display\n // ---------------------------------------------------------------------------\n // Groups of calls can span messages (an agent often sends each call as its\n // own message), so they're laid out here for the whole list and handed to\n // each message's tool-call view through context.\n const rendererNames = useToolCallRendererNames();\n // The list's tool-call layout and turn state live in core. Calling `update`\n // during render is safe: it caches by input and records each run start or\n // end once, so repeating a render changes nothing. A user's open or close of\n // a reply's work is the only change it reports by itself.\n const [viewModel] = useState(ɵcreateMessageViewModel);\n useSyncExternalStore(\n useCallback((onChange) => viewModel.subscribe(onChange), [viewModel]),\n () => viewModel.getSnapshot(),\n () => viewModel.getSnapshot(),\n );\n const {\n layouts: toolCallLayouts,\n turnByFirstMessage,\n latestTurnKey,\n workOpen,\n workTextOpen,\n showCursor,\n pendingWorkSummary,\n } = viewModel.update({\n display: toolCallDisplay,\n messages,\n rendered: renderedMessages,\n isRunning,\n rendererNames,\n now: Date.now(),\n });\n\n const toolCallDisplayContext = useMemo<ToolCallDisplayContextValue>(\n () => ({\n display: toolCallDisplay,\n isRunning,\n layouts: toolCallLayouts,\n workOpen,\n workTextOpen,\n }),\n [toolCallDisplay, isRunning, toolCallLayouts, workOpen, workTextOpen],\n );\n\n const renderWorkSummary = (turnKey: string, calls: ToolCallEntry[]) => {\n const working = viewModel.isTurnWorking(turnKey);\n const open = viewModel.isTurnOpen(turnKey);\n const times = viewModel.getWorkTime(turnKey);\n return (\n <Collapsible\n key={`work-summary-${turnKey}`}\n open={working || calls.length > 0}\n >\n <div className=\"cpk-message-view-work-summary\">\n {renderSlot(workSummary, CopilotChatWorkSummary, {\n isWorking: working,\n isOpen: open,\n calls,\n elapsedMs: times?.elapsedMs,\n workingSince: times?.workingSince,\n onClick: () => viewModel.toggleTurn(turnKey),\n })}\n </div>\n </Collapsible>\n );\n };\n\n // Row keys are looked up by message id, so two rendered messages sharing an\n // id would share a React key. Deduplication already ran on the input, so a\n // repeat here can only come from the transform.\n const transformDuplicateId = useMemo(() => {\n if (\n process.env.NODE_ENV === \"production\" ||\n (!transformMessages && !groupMessages)\n ) {\n return;\n }\n const seen = new Set<string>();\n for (const message of renderedMessages) {\n if (seen.has(message.id)) return message.id;\n seen.add(message.id);\n }\n }, [renderedMessages, transformMessages, groupMessages]);\n useEffect(() => {\n if (transformDuplicateId === undefined) return;\n console.warn(\n groupMessages\n ? `[CopilotKit] CopilotChatMessageView: the message with id \"${transformDuplicateId}\" renders more than once. ` +\n \"`groupMessages` should place each message in at most one row, and `transformMessages` return each id at most once.\"\n : `[CopilotKit] CopilotChatMessageView: \\`transformMessages\\` returned more than one message with id \"${transformDuplicateId}\". ` +\n \"Return each id at most once; a message you create needs its own id, stable across renders.\",\n );\n }, [transformDuplicateId, groupMessages]);\n\n // Group keys are React keys and state keys, so two groups sharing one would\n // share both.\n const duplicateGroupKey = useMemo(() => {\n if (process.env.NODE_ENV === \"production\" || !groupMessages) return;\n const seen = new Set<string>();\n for (const row of rows) {\n if (row.type !== \"group\") continue;\n if (seen.has(row.key)) return row.key;\n seen.add(row.key);\n }\n }, [rows, groupMessages]);\n useEffect(() => {\n if (duplicateGroupKey === undefined) return;\n console.warn(\n `[CopilotKit] CopilotChatMessageView: \\`groupMessages\\` returned more than one group with key \"${duplicateGroupKey}\". ` +\n \"Give each group its own key, stable across renders.\",\n );\n }, [duplicateGroupKey]);\n\n // Stable per-row React keys. Backends can re-key a message mid-stream, and\n // keying rows by the canonical id remounts the row on that swap (the HITL\n // chat flash). See @copilotkit/shared row-render-keys for the mechanism.\n const rowKeyStoreRef = useRef<RowKeyStore | null>(null);\n rowKeyStoreRef.current ??= createRowKeyStore();\n const rowKeyStore = rowKeyStoreRef.current;\n\n const rowRenderKeys = useMemo(\n () => resolveRowRenderKeysById(rowKeyStore, renderedMessages),\n [rowKeyStore, renderedMessages],\n );\n\n // Record what this commit rendered, never what a render merely proposed: an\n // anchor from a render React goes on to abandon would re-key a committed row\n // and remount it. Layout phase, so the store is current before any later\n // render reads it.\n useLayoutEffect(() => {\n commitRowKeyStore(rowKeyStore, renderedMessages);\n }, [rowKeyStore, renderedMessages]);\n\n // A group's key, made stable the same way: a key that is a message id (the\n // documented choice is the group's first message) resolves through\n // `rowRenderKeys`, so a backend renaming that message mid-stream neither\n // remounts the group nor loses its state.\n const stableGroupKey = (key: string): string => rowRenderKeys.get(key) ?? key;\n const rowKey = (row: MessageRow): string =>\n row.type === \"group\"\n ? `${GROUP_ROW_KEY_PREFIX}${stableGroupKey(row.key)}`\n : (rowRenderKeys.get(row.message.id) ?? row.message.id);\n\n // The key of each row, in order. The array is replaced only when a key\n // changes, so the virtualizer's `getItemKey` below keeps its identity while\n // a message streams.\n const rowKeysRef = useRef<string[]>([]);\n const nextRowKeys = rows.map(rowKey);\n if (\n nextRowKeys.length !== rowKeysRef.current.length ||\n nextRowKeys.some((key, index) => key !== rowKeysRef.current[index])\n ) {\n rowKeysRef.current = nextRowKeys;\n }\n const rowKeys = rowKeysRef.current;\n\n // State each group's wrapper keeps here rather than in itself, so it\n // survives the row being windowed out and the wrapper remounting. Cleared\n // when the thread changes; pruned to the groups still on the list. One\n // setter per group, kept with its state, so a wrapper that depends on\n // `setState` in an effect or memo sees the same function every render.\n const groupStateRef = useRef<Map<string, unknown>>(new Map());\n const groupSettersRef = useRef<Map<string, (next: unknown) => void>>(\n new Map(),\n );\n const groupStateThreadRef = useRef(config?.threadId);\n if (groupStateThreadRef.current !== config?.threadId) {\n groupStateThreadRef.current = config?.threadId;\n groupStateRef.current = new Map();\n groupSettersRef.current = new Map();\n }\n const groupSetter = (key: string): ((next: unknown) => void) => {\n let setter = groupSettersRef.current.get(key);\n if (!setter) {\n setter = (next) => {\n groupStateRef.current.set(key, next);\n forceUpdate();\n };\n groupSettersRef.current.set(key, setter);\n }\n return setter;\n };\n useLayoutEffect(() => {\n const live = new Set<string>();\n for (const row of rows) {\n if (row.type === \"group\") live.add(stableGroupKey(row.key));\n }\n for (const store of [groupStateRef.current, groupSettersRef.current]) {\n for (const key of store.keys()) if (!live.has(key)) store.delete(key);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- stableGroupKey reads rowRenderKeys\n }, [rows, rowRenderKeys]);\n\n if (process.env.NODE_ENV === \"development\") {\n const warning = ɵduplicateMessagesWarning(\n messages.length,\n deduplicatedMessages.length,\n );\n if (warning) console.warn(warning);\n }\n\n // Resolve slot values once per prop change rather than inside renderMessageBlock.\n // resolveSlotComponent returns a new object every call when the slot is a CSS\n // class string, which would defeat MemoizedAssistantMessage's slotProps\n // reference-equality check and cause all completed messages to re-render.\n const { Component: AssistantComponent, slotProps: assistantSlotProps } =\n useMemo(\n () => resolveSlotComponent(assistantMessage, CopilotChatAssistantMessage),\n [assistantMessage],\n );\n const agentId = config?.agentId;\n const threadId = config?.threadId;\n const learningFeedbackEnabled = useLearningFeedbackEnabled(copilotkit);\n const feedbackScope = useMemo<MessageFeedbackScope | null>(\n () =>\n messageFeedback &&\n learningFeedbackEnabled &&\n agentId !== undefined &&\n threadId !== undefined\n ? { copilotkit, agentId, threadId }\n : null,\n [messageFeedback, learningFeedbackEnabled, copilotkit, agentId, threadId],\n );\n const assistantSlotPropsWithFeedback = useMemo(() => {\n const onThumbsUp = assistantSlotProps?.onThumbsUp as\n | ((message: CopilotChatFeedbackMessage) => void)\n | undefined;\n const onThumbsDown = assistantSlotProps?.onThumbsDown as\n | ((message: CopilotChatFeedbackMessage) => void)\n | undefined;\n if (!onThumbsUp && !onThumbsDown) return assistantSlotProps;\n\n const withRawEvent = (\n message: AssistantMessage,\n ): CopilotChatFeedbackMessage => {\n const rawEvent =\n agentId === undefined || threadId === undefined\n ? undefined\n : copilotkit.getRawEventForMessage(agentId, threadId, message.id);\n return rawEvent === undefined ? message : { ...message, rawEvent };\n };\n\n return {\n ...assistantSlotProps,\n ...(onThumbsUp && {\n onThumbsUp: (message: AssistantMessage) =>\n onThumbsUp(withRawEvent(message)),\n }),\n ...(onThumbsDown && {\n onThumbsDown: (message: AssistantMessage) =>\n onThumbsDown(withRawEvent(message)),\n }),\n };\n }, [assistantSlotProps, agentId, threadId, copilotkit]);\n const { Component: UserComponent, slotProps: userSlotProps } = useMemo(\n () => resolveSlotComponent(userMessage, CopilotChatUserMessage),\n [userMessage],\n );\n const { Component: ReasoningComponent, slotProps: reasoningSlotProps } =\n useMemo(\n () => resolveSlotComponent(reasoningMessage, CopilotChatReasoningMessage),\n [reasoningMessage],\n );\n\n // ---------------------------------------------------------------------------\n // Virtualization\n // ---------------------------------------------------------------------------\n // Receive the scroll container from context. ScrollView provides the element\n // as state (not a ref) so this component re-renders reactively when the\n // container first mounts. clientHeight === 0 means no real layout (jsdom) —\n // skip virtualization so tests run the flat path.\n const scrollElementFromCtx = useContext(ScrollElementContext);\n const scrollElement =\n scrollElementFromCtx && scrollElementFromCtx.clientHeight > 0\n ? scrollElementFromCtx\n : null;\n\n // Warn once in dev when a scroll element is provided but has no height —\n // this silently disables virtualization (e.g. chat inside display:none tab).\n useEffect(() => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n scrollElementFromCtx &&\n scrollElementFromCtx.clientHeight === 0\n ) {\n console.warn(\n \"[CopilotKit] Chat scroll container has clientHeight=0 — virtualization disabled. \" +\n \"Ensure the chat is rendered in a visible container with a non-zero height.\",\n );\n }\n }, [scrollElementFromCtx]);\n\n // Virtualize only when we have a scroll element and enough messages. The\n // `children` render prop delegates layout to the caller, so we keep\n // messageElements flat for that case.\n const shouldVirtualize =\n !!scrollElement &&\n !children &&\n renderedMessages.length > VIRTUALIZE_THRESHOLD;\n\n // Warn once in dev when the `children` render prop is the only thing keeping\n // a long thread off the virtual path. Nothing else signals it: the chat just\n // mounts every message and gets slower as the thread grows.\n const childrenDisabledVirtualization =\n !!children &&\n !!scrollElement &&\n renderedMessages.length > VIRTUALIZE_THRESHOLD;\n const warnedChildrenRef = useRef(false);\n useEffect(() => {\n if (\n process.env.NODE_ENV === \"production\" ||\n !childrenDisabledVirtualization ||\n warnedChildrenRef.current\n ) {\n return;\n }\n warnedChildrenRef.current = true;\n console.warn(\n `[CopilotKit] CopilotChatMessageView: the \\`children\\` render prop disables virtualization, ` +\n `so all ${renderedMessages.length} messages are mounted. ` +\n (transformMessages || groupMessages\n ? \"`transformMessages` and `groupMessages` keep virtualization on by themselves; drop `children` to use them.\"\n : \"To reshape the list and keep virtualization, use `transformMessages` instead, or `groupMessages` to render several messages as one row.\"),\n );\n }, [\n childrenDisabledVirtualization,\n renderedMessages.length,\n transformMessages,\n ]);\n\n // Mean of the rows measured so far in this thread, used as the estimate for\n // rows that have not been measured yet. A flat 100 px estimate is off by\n // roughly an order of magnitude for a message carrying a code block, so the\n // total size lurches every time such a row is measured; an estimate drawn\n // from this thread's own rows keeps those corrections small.\n //\n // Sizes are kept per row rather than as a running sum because a row is\n // re-measured every time its ResizeObserver fires — a streaming message\n // reports a new height on every chunk — and treating each of those as a\n // fresh sample would drag the mean toward whatever that one row happened to\n // be mid-stream. Held in a ref because feeding it back through state would\n // re-render on every measure.\n const measuredRef = React.useRef({\n total: 0,\n sizes: new Map<RowSizeKey, number>(),\n });\n\n const resizeAnchorRef = React.useRef<{\n index: number;\n offset: number;\n ready: boolean;\n } | null>(null);\n const restoringVisibilityRef = React.useRef(false);\n const isPinnedToBottomRef = React.useRef(isPinnedToBottom);\n\n // The instance from the previous render. A prepend reads the old layout\n // from it before this render gives the virtualizer the new rows.\n const virtualizerRef = React.useRef<Virtualizer<HTMLElement, Element> | null>(\n null,\n );\n\n // The thread changes when the first message changes and the new history\n // either belongs to another configured thread or shares no message with the\n // old one. Loading older history or trimming the oldest messages keeps the\n // thread (#8149), the same rule CopilotChatView uses for its bottom pin.\n // Read from the untransformed list: a transform that hides or reorders the\n // head is not a thread change.\n //\n // Done during render rather than in an effect because rows are measured\n // from ref callbacks, which run before layout effects — resetting there\n // would discard the new thread's first measurements instead of the old\n // thread's.\n const historyRef = React.useRef({\n messages: deduplicatedMessages,\n threadId,\n generation: 0,\n });\n const history = historyRef.current;\n if (history.messages !== deduplicatedMessages) {\n const previousFirstId = history.messages[0]?.id;\n if (previousFirstId !== deduplicatedMessages[0]?.id) {\n const previousIds = new Set(history.messages.map((m) => m.id));\n const sameThread =\n history.threadId === threadId &&\n deduplicatedMessages.some((m) => previousIds.has(m.id));\n if (sameThread) {\n keepReadingRowThroughHistoryChange();\n } else {\n history.generation += 1;\n resizeAnchorRef.current = null;\n measuredRef.current = { total: 0, sizes: new Map() };\n }\n }\n history.messages = deduplicatedMessages;\n history.threadId = threadId;\n }\n const historyGeneration = history.generation;\n\n // Rows were added or removed above the reader. Remember the row at the top\n // of the viewport, by key, at its index in the new rows, and let the\n // resize-anchor restore below hold it there while the new rows settle.\n function keepReadingRowThroughHistoryChange() {\n const instance = virtualizerRef.current;\n const element = instance?.scrollElement;\n if (\n !instance ||\n !element ||\n instance.options.count === 0 ||\n element.clientHeight === 0 ||\n isPinnedToBottomRef.current ||\n restoringVisibilityRef.current\n )\n return;\n const offset = element.scrollTop;\n const item = instance.getVirtualItemForOffset(offset);\n const index = item ? rowKeys.indexOf(String(item.key)) : -1;\n resizeAnchorRef.current =\n item && index >= 0\n ? { index, offset: offset - item.start, ready: true }\n : null;\n }\n\n const estimateRowSize = React.useCallback(() => {\n const { total, sizes } = measuredRef.current;\n return sizes.size > 0 ? Math.max(1, Math.round(total / sizes.size)) : 100;\n }, []);\n\n const measuredWidthRef = React.useRef<number | null>(null);\n const captureResizeAnchor = React.useCallback(\n (instance: Virtualizer<HTMLElement, Element>) => {\n const width = instance.scrollElement?.clientWidth;\n if (\n !width ||\n instance.scrollElement?.clientHeight === 0 ||\n restoringVisibilityRef.current ||\n isPinnedToBottomRef.current ||\n instance.options.count === 0 ||\n measuredWidthRef.current === null ||\n width === measuredWidthRef.current\n )\n return;\n if (resizeAnchorRef.current) {\n // A second resize can arrive before the previous anchor is released.\n // Keep its reading position, but let the old release callback expire.\n if (resizeAnchorRef.current.ready) {\n resizeAnchorRef.current = {\n ...resizeAnchorRef.current,\n ready: false,\n };\n }\n return;\n }\n const offset = instance.scrollElement?.scrollTop ?? 0;\n const anchor = instance.getVirtualItemForOffset(offset);\n if (anchor) {\n resizeAnchorRef.current = {\n index: anchor.index,\n offset: offset - anchor.start,\n ready: false,\n };\n }\n },\n [],\n );\n const measureRowElement = React.useCallback(\n (\n el: Element,\n _entry: ResizeObserverEntry | undefined,\n instance: Virtualizer<HTMLElement, Element>,\n ) => {\n // Row refs and observers can run before the container observer. Capture\n // the old reading position before any row reports its resized height.\n captureResizeAnchor(instance);\n const height = el?.getBoundingClientRect().height ?? 0;\n const index = Number((el as HTMLElement | null)?.dataset?.index);\n // Keyed by row, not index, so a row keeps its size when history is\n // added above it.\n const key = Number.isInteger(index)\n ? instance.options.getItemKey(index)\n : undefined;\n if (height > 0 && key !== undefined) {\n const { total, sizes } = measuredRef.current;\n measuredRef.current.total = total - (sizes.get(key) ?? 0) + height;\n sizes.set(key, height);\n }\n // A hidden row keeps its last visible measurement.\n return height > 0\n ? height\n : (key !== undefined && measuredRef.current.sizes.get(key)) || 100;\n },\n [captureResizeAnchor],\n );\n\n const shouldAdjustScrollOnResize = React.useCallback(\n (\n item: VirtualItem,\n _delta: number,\n instance: Virtualizer<HTMLElement, Element>,\n ) => {\n // While the pin is following the bottom it owns the scroll position;\n // compensating as well is what makes the two fight (see below).\n if (\n isPinnedToBottomRef.current ||\n resizeAnchorRef.current ||\n restoringVisibilityRef.current\n )\n return false;\n // Otherwise keep the rule this property replaces rather than\n // compensating for every resize: only a row starting above the current\n // scroll offset can shift what the reader is looking at when it\n // changes size. Moving the scroll position for a row *below* the\n // viewport — an overscanned row settling, say — is the same unwanted\n // motion, just in the other direction. `scrollAdjustments` is not on\n // the public type but is part of that rule; leaving it out would drop\n // the corrections already applied.\n const scrollAdjustments =\n (instance as unknown as { scrollAdjustments?: number })\n .scrollAdjustments ?? 0;\n return item.start < (instance.scrollOffset ?? 0) + scrollAdjustments;\n },\n [],\n );\n\n const observeScrollRect = React.useCallback(\n (\n instance: Virtualizer<HTMLElement, Element>,\n notify: (rect: { width: number; height: number }) => void,\n ) => {\n let frame: number | undefined;\n let pendingRect: { width: number; height: number } | undefined;\n const disconnect = observeElementRect(instance, (rect) => {\n if (instance.scrollElement?.clientHeight === 0) {\n restoringVisibilityRef.current = true;\n resizeAnchorRef.current = null;\n if (frame !== undefined) cancelAnimationFrame(frame);\n frame = undefined;\n pendingRect = undefined;\n notify(rect);\n return;\n }\n const width = instance.scrollElement?.clientWidth ?? rect.width;\n const previousWidth = measuredWidthRef.current;\n if (width > 0 && width !== previousWidth) {\n captureResizeAnchor(instance);\n if (previousWidth !== null) {\n pendingRect = rect;\n if (frame === undefined) {\n // Resizing the spacer inside ResizeObserver can feed back into\n // the bottom pin's observer. Commit the new layout next frame.\n frame = requestAnimationFrame(() => {\n frame = undefined;\n const nextRect = pendingRect!;\n pendingRect = undefined;\n if (!instance.scrollElement?.clientHeight) return;\n measuredWidthRef.current = instance.scrollElement.clientWidth;\n if (resizeAnchorRef.current)\n resizeAnchorRef.current.ready = true;\n // Flush pending row updates before invalidating the cached prefix.\n instance.getTotalSize();\n measuredRef.current = { total: 0, sizes: new Map() };\n // Seed the new estimate before rebuilding offscreen offsets.\n instance.elementsCache.forEach((element) => {\n measureRowElement(element, undefined, instance);\n });\n instance.measure();\n instance.getTotalSize();\n // Already-resized rows may not emit another notification.\n instance.elementsCache.forEach((element) => {\n instance.measureElement(element);\n });\n notify(nextRect);\n });\n }\n return;\n }\n measuredWidthRef.current = width;\n }\n if (pendingRect) {\n pendingRect = rect;\n } else {\n notify(rect);\n }\n });\n return () => {\n disconnect?.();\n if (frame !== undefined) {\n cancelAnimationFrame(frame);\n }\n resizeAnchorRef.current = null;\n };\n },\n [captureResizeAnchor, measureRowElement],\n );\n\n const getItemKey = React.useCallback(\n (index: number) => rowKeys[index] ?? index,\n [rowKeys],\n );\n const virtualizer = useVirtualizer({\n // count=0 disables the virtualizer without changing hook call order.\n count: shouldVirtualize ? rows.length : 0,\n // Cache sizes by row so that a row keeps its size when rows are added\n // above it.\n getItemKey,\n // A disabled virtualizer must not reconnect and reset a flat list's\n // scroll offset when a hidden host becomes visible again.\n getScrollElement: () => (shouldVirtualize ? scrollElement : null),\n observeElementRect: observeScrollRect,\n estimateSize: estimateRowSize,\n overscan: 5,\n measureElement: measureRowElement,\n // Assume a 600 px viewport before the real element is measured so that\n // the first virtual render shows ~6 items rather than 0.\n initialRect: { width: 0, height: 600 },\n });\n virtualizerRef.current = virtualizer;\n\n // While the pin-to-bottom behaviour is following the bottom it is already\n // going to move the scroll position, and its ResizeObserver reads our\n // total-size changes as content growth. Compensating here as well makes the\n // two fight: each correction triggers an animation, the animation pulls\n // unmeasured rows into view, measuring them moves the total again. Stand\n // down while it is pinned; keep compensating when the reader has scrolled\n // up, which is the case the compensation is actually for.\n //\n // This is an instance property on the virtualizer rather than one of its\n // options, so it has to be assigned. Assigned during render (not in an\n // effect) because a row can be measured before effects run. The read goes\n // through a ref so the assigned function stays referentially stable.\n isPinnedToBottomRef.current = isPinnedToBottom;\n virtualizer.shouldAdjustScrollPositionOnItemSizeChange =\n shouldAdjustScrollOnResize;\n\n // Restore the reading row only after the resized spacer has committed;\n // scrolling sooner can clamp the target to its previous total height.\n useLayoutEffect(() => {\n const anchor = resizeAnchorRef.current;\n if (!anchor?.ready || restoringVisibilityRef.current) return;\n const position = virtualizer.getOffsetForIndex(anchor.index, \"start\");\n if (position && !isPinnedToBottomRef.current) {\n const target = position[0] + anchor.offset;\n if (Math.abs((scrollElement?.scrollTop ?? 0) - target) > 0.5) {\n virtualizer.scrollToOffset(target);\n }\n }\n // Keep the anchor through the row measurements caused by this render.\n // Each measurement cancels and reschedules this release until layout settles.\n const frame = requestAnimationFrame(() => {\n if (resizeAnchorRef.current === anchor) resizeAnchorRef.current = null;\n });\n return () => cancelAnimationFrame(frame);\n });\n\n // Scroll to the bottom when virtual mode first activates or the thread\n // changes (see `historyGeneration` above). For streaming new messages,\n // use-stick-to-bottom handles auto-scroll via content height growth detection\n // on the virtualizer's total-size div — same as the flat path. Adding\n // renderedMessages.length here would forcibly yank the user to the bottom\n // on every streaming chunk even if they've scrolled up to read history.\n const lastEndAlignedGenerationRef = React.useRef<number | undefined>(\n undefined,\n );\n useLayoutEffect(() => {\n if (!shouldVirtualize || !rows.length) return;\n // Resizing a hidden host can temporarily disable virtualization. Do not\n // align again when the same message list becomes measurable once more.\n if (lastEndAlignedGenerationRef.current === historyGeneration) return;\n lastEndAlignedGenerationRef.current = historyGeneration;\n virtualizer.scrollToIndex(rows.length - 1, {\n align: \"end\",\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [shouldVirtualize, historyGeneration]);\n\n // Map each Intelligence-using turn's anchor message → stable turn id. One\n // indicator is emitted per turn (keyed by the turn id) at its anchor, so it\n // moves with the anchor without remounting. `getIntelligenceTurnAnchors`\n // only yields anchors for turns that invoked the knowledge-base tool, so\n // non-Intelligence turns naturally produce an empty map (and the indicator\n // itself also hard-gates on intelligence mode).\n const intelligenceTurnAnchors = useMemo(\n () => getIntelligenceTurnAnchors(deduplicatedMessages, renderedMessages),\n [deduplicatedMessages, renderedMessages],\n );\n\n // ---------------------------------------------------------------------------\n // Per-message rendering helper (shared by flat and virtual paths)\n // ---------------------------------------------------------------------------\n const renderMessageBlock = (message: Message): React.ReactElement[] => {\n const elements: (React.ReactElement | null | undefined)[] = [];\n // Only custom message renderers consume the snapshot, and resolving it\n // deep-clones the agent's whole state (LangGraph's includes the `messages`\n // channel). Computing it unconditionally cost one clone per message per\n // render even when no renderer was registered.\n const stateSnapshot = renderCustomMessage\n ? getStateSnapshotForMessage(message.id)\n : undefined;\n // Row key only — everything keyed to message identity (state snapshots,\n // tool lookups) must keep using message.id.\n const messageKey = rowRenderKeys.get(message.id) ?? message.id;\n\n const turn = turnByFirstMessage.get(message.id);\n if (turn) elements.push(renderWorkSummary(turn.key, turn.calls));\n\n if (renderCustomMessage) {\n elements.push(\n <MemoizedCustomMessage\n key={`${messageKey}-custom-before`}\n message={message}\n position=\"before\"\n renderCustomMessage={renderCustomMessage}\n stateSnapshot={stateSnapshot}\n />,\n );\n }\n\n if (message.role === \"assistant\") {\n elements.push(\n <MemoizedAssistantMessage\n key={messageKey}\n message={message as AssistantMessage}\n messages={messages}\n isRunning={isRunning}\n isLatest={message.id === latestRenderedId}\n AssistantMessageComponent={AssistantComponent}\n slotProps={assistantSlotPropsWithFeedback}\n />,\n );\n } else if (message.role === \"user\") {\n elements.push(\n <MemoizedUserMessage\n key={messageKey}\n message={message as UserMessage}\n UserMessageComponent={UserComponent}\n slotProps={userSlotProps}\n />,\n );\n } else if (message.role === \"activity\") {\n elements.push(\n <MemoizedActivityMessage\n key={messageKey}\n message={message as ActivityMessage}\n renderActivityMessage={renderActivityMessage}\n />,\n );\n } else if (message.role === \"reasoning\") {\n const reasoning = (\n <MemoizedReasoningMessage\n key={messageKey}\n message={message as ReasoningMessage}\n messages={messages}\n isRunning={isRunning}\n isLatest={message.id === latestRenderedId}\n ReasoningMessageComponent={ReasoningComponent}\n slotProps={reasoningSlotProps}\n />\n );\n // Reasoning during a reply's working phase folds away with the work.\n // Always wrapped in this display, so reasoning that turns into work\n // keeps its node (and its \"Thought for\" timer) instead of remounting.\n elements.push(\n toolCallDisplay === \"turn\" ? (\n <Collapsible key={messageKey} open={workOpen.get(message.id) ?? true}>\n {reasoning}\n </Collapsible>\n ) : (\n reasoning\n ),\n );\n }\n\n if (renderCustomMessage) {\n elements.push(\n <MemoizedCustomMessage\n key={`${messageKey}-custom-after`}\n message={message}\n position=\"after\"\n renderCustomMessage={renderCustomMessage}\n stateSnapshot={stateSnapshot}\n />,\n );\n }\n\n // Auto-mount the IntelligenceIndicator once per Intelligence-using turn,\n // at that turn's anchor message (its first bash-using assistant), keyed by\n // the stable turn id. Keying by turn (not message) means the indicator\n // moves with the anchor across a hand-off without remounting, and past\n // turns keep their own indicator.\n const intelligenceTurnId = showIntelligenceIndicator\n ? intelligenceTurnAnchors.get(message.id)\n : undefined;\n if (intelligenceTurnId !== undefined) {\n elements.push(\n <IntelligenceIndicator\n key={`intelligence-${intelligenceTurnId}`}\n message={message}\n agentId={ɵresolveAgentId({\n chatAgentId: config?.agentId,\n providerAgentId,\n })}\n intelligenceIndicator={intelligenceIndicator}\n />,\n );\n }\n\n return elements.filter(Boolean) as React.ReactElement[];\n };\n\n const renderRow = (row: MessageRow): React.ReactElement[] => {\n if (row.type === \"message\") return renderMessageBlock(row.message);\n const Wrapper = row.wrapper;\n const stateKey = stableGroupKey(row.key);\n return [\n <Wrapper\n key={rowKey(row)}\n groupKey={row.key}\n messages={row.messages}\n state={groupStateRef.current.get(stateKey)}\n setState={groupSetter(stateKey)}\n >\n {row.messages.flatMap(renderMessageBlock)}\n </Wrapper>,\n ];\n };\n\n const virtualModeRef = useRef(shouldVirtualize);\n virtualModeRef.current = shouldVirtualize;\n\n // Re-entering virtual mode can re-estimate rows above the viewport. A pixel\n // scrollTop then identifies different content, so retain the first visible\n // row and its offset within the viewport instead.\n useEffect(() => {\n const element = scrollElementFromCtx;\n if (!element) return;\n let anchor: { key: string; offset: number } | null = null;\n let suspended = false;\n let frame = 0;\n\n const visibleRows = () =>\n Array.from(element.querySelectorAll<HTMLElement>(\"[data-scroll-anchor]\"));\n const remember = () => {\n if (suspended || element.clientHeight === 0 || !virtualModeRef.current)\n return;\n if (isPinnedToBottomRef.current) {\n anchor = null;\n return;\n }\n const viewport = element.getBoundingClientRect();\n const row = visibleRows().find((row) => {\n const bounds = row.getBoundingClientRect();\n return bounds.bottom > viewport.top && bounds.top < viewport.bottom;\n });\n if (row) {\n anchor = {\n key: row.dataset.scrollAnchor!,\n offset: row.getBoundingClientRect().top - viewport.top,\n };\n }\n };\n const observer = new ResizeObserver(() => {\n if (element.clientHeight === 0) {\n suspended = true;\n // Hide/show owns restoration until its saved row has settled. Width\n // changes may invalidate measurements, but must not also move it.\n restoringVisibilityRef.current = true;\n resizeAnchorRef.current = null;\n cancelAnimationFrame(frame);\n return;\n }\n if (!suspended || !anchor) {\n suspended = false;\n restoringVisibilityRef.current = false;\n remember();\n return;\n }\n cancelAnimationFrame(frame);\n let attempts = 0;\n let stableFrames = 0;\n const restore = () => {\n if (!anchor || element.clientHeight === 0) return;\n if (isPinnedToBottomRef.current) {\n anchor = null;\n suspended = false;\n restoringVisibilityRef.current = false;\n return;\n }\n const index = rowKeysRef.current.indexOf(anchor.key);\n if (index < 0) {\n anchor = null;\n suspended = false;\n restoringVisibilityRef.current = false;\n return;\n }\n const row = visibleRows().find(\n (row) => row.dataset.scrollAnchor === anchor!.key,\n );\n if (row) {\n const delta =\n row.getBoundingClientRect().top -\n element.getBoundingClientRect().top -\n anchor.offset;\n element.scrollTop += delta;\n stableFrames = Math.abs(delta) < 1 ? stableFrames + 1 : 0;\n } else {\n // Bring an unmounted anchor into range, then refine its measured\n // position on the next frame rather than using an estimated height.\n const offset = virtualizer.getOffsetForIndex(index, \"start\")?.[0];\n if (offset !== undefined)\n virtualizer.scrollToOffset(offset - anchor.offset);\n stableFrames = 0;\n }\n if (++attempts < 60 && stableFrames < 3) {\n frame = requestAnimationFrame(restore);\n } else {\n suspended = false;\n restoringVisibilityRef.current = false;\n remember();\n }\n };\n frame = requestAnimationFrame(restore);\n });\n const interrupt = () => {\n cancelAnimationFrame(frame);\n anchor = null;\n suspended = false;\n restoringVisibilityRef.current = false;\n resizeAnchorRef.current = null;\n };\n element.addEventListener(\"scroll\", remember, { passive: true });\n element.addEventListener(\"wheel\", interrupt, { passive: true });\n element.addEventListener(\"touchstart\", interrupt, { passive: true });\n element.addEventListener(\"keydown\", interrupt);\n observer.observe(element);\n remember();\n return () => {\n cancelAnimationFrame(frame);\n observer.disconnect();\n restoringVisibilityRef.current = false;\n element.removeEventListener(\"scroll\", remember);\n element.removeEventListener(\"wheel\", interrupt);\n element.removeEventListener(\"touchstart\", interrupt);\n element.removeEventListener(\"keydown\", interrupt);\n };\n }, [scrollElementFromCtx, virtualizer, historyGeneration]);\n\n // Build the flat element list only when we're not virtualizing (avoids\n // creating 500 React elements that we'd immediately discard).\n const messageElements: React.ReactElement[] = shouldVirtualize\n ? []\n : rows.flatMap(renderRow);\n\n // ---------------------------------------------------------------------------\n // children render prop (custom layout, always non-virtual)\n // ---------------------------------------------------------------------------\n if (children) {\n return (\n <MessageFeedbackScopeContext.Provider value={feedbackScope}>\n <ToolCallDisplayContext.Provider value={toolCallDisplayContext}>\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children({\n messageElements,\n messages,\n isRunning,\n interruptElement,\n })}\n </div>\n </ToolCallDisplayContext.Provider>\n </MessageFeedbackScopeContext.Provider>\n );\n }\n\n // ---------------------------------------------------------------------------\n // Render — shared wrapper, conditional inner content (virtual vs flat)\n // ---------------------------------------------------------------------------\n return (\n <MessageFeedbackScopeContext.Provider value={feedbackScope}>\n <ToolCallDisplayContext.Provider value={toolCallDisplayContext}>\n <div\n data-copilotkit\n data-testid=\"copilot-message-list\"\n className={cn(\"copilotKitMessages cpk-message-view\", className)}\n {...props}\n >\n {shouldVirtualize ? (\n // Virtual path: only visible items are in the DOM; outer div maintains\n // total scroll height so the scrollbar reflects the full list size.\n <div\n style={{\n height: virtualizer.getTotalSize(),\n position: \"relative\",\n overflowAnchor: \"none\",\n }}\n >\n {virtualizer.getVirtualItems().map((virtualItem) => {\n const row = rows[virtualItem.index]!;\n return (\n <div\n key={rowKey(row)}\n data-index={virtualItem.index}\n data-scroll-anchor={rowKey(row)}\n ref={virtualizer.measureElement}\n style={{\n position: \"absolute\",\n top: 0,\n left: 0,\n width: \"100%\",\n transform: `translateY(${virtualItem.start}px)`,\n }}\n >\n {renderRow(row)}\n </div>\n );\n })}\n </div>\n ) : (\n messageElements\n )}\n {interruptElement}\n {pendingWorkSummary && renderWorkSummary(latestTurnKey, [])}\n {showCursor && (\n <div className=\"cpk-message-view-cursor-container\">\n {renderSlot(cursor, CopilotChatMessageView.Cursor, {})}\n </div>\n )}\n </div>\n </ToolCallDisplayContext.Provider>\n </MessageFeedbackScopeContext.Provider>\n );\n}\n\nCopilotChatMessageView.Cursor = function Cursor({\n className,\n ...props\n}: React.HTMLAttributes<HTMLDivElement>) {\n return (\n <div\n data-testid=\"copilot-loading-cursor\"\n className={cn(\"cpk-message-view-cursor\", className)}\n {...props}\n />\n );\n};\n\nexport default CopilotChatMessageView;\n","import React, { useEffect, useState } from \"react\";\nimport type { Attachment } from \"@copilotkit/shared\";\nimport {\n formatFileSize,\n getSourceUrl,\n getDocumentIcon,\n} from \"@copilotkit/shared\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport { cn } from \"../../lib/utils\";\nimport { Lightbox, useLightbox } from \"./Lightbox\";\nimport {\n CopilotChatDefaultLabels,\n ɵcanPreviewDocument,\n ɵcreateObjectUrlFromSource,\n ɵdecodeTextSource,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\ninterface CopilotChatAttachmentQueueProps {\n attachments: Attachment[];\n onRemoveAttachment: (id: string) => void;\n className?: string;\n}\n\n/**\n * The attachments queued in the composer, each with a preview and a remove\n * button named by `labels.attachmentRemoveButtonLabel`.\n */\nexport const CopilotChatAttachmentQueue: React.FC<\n CopilotChatAttachmentQueueProps\n> = ({ attachments, onRemoveAttachment, className }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n if (attachments.length === 0) return null;\n\n return (\n <div\n data-testid=\"copilot-attachment-queue\"\n className={cn(\"cpk-attachment-queue\", className)}\n >\n {attachments.map((attachment) => {\n const isMedia =\n attachment.type === \"image\" || attachment.type === \"video\";\n return (\n <div\n key={attachment.id}\n className={cn(\n \"cpk-attachment-queue-item\",\n isMedia\n ? \"cpk-attachment-queue-item-media\"\n : attachment.type === \"audio\"\n ? \"cpk-attachment-queue-item-audio\"\n : \"cpk-attachment-queue-item-document\",\n )}\n >\n {attachment.status === \"uploading\" && <UploadingOverlay />}\n <AttachmentPreview attachment={attachment} />\n <button\n onClick={() => onRemoveAttachment(attachment.id)}\n className=\"cpk-attachment-queue-remove-button\"\n aria-label={labels.attachmentRemoveButtonLabel}\n >\n ✕\n </button>\n </div>\n );\n })}\n </div>\n );\n};\n\n// ---------------------------------------------------------------------------\n// Shared\n// ---------------------------------------------------------------------------\n\nfunction UploadingOverlay() {\n return (\n <div className=\"cpk-attachment-queue-uploading-overlay\">\n <div className=\"cpk-attachment-queue-uploading-spinner\" />\n </div>\n );\n}\n\nfunction AttachmentPreview({ attachment }: { attachment: Attachment }) {\n if (attachment.status === \"uploading\") {\n return <div className=\"cpk-attachment-queue-placeholder\" />;\n }\n\n switch (attachment.type) {\n case \"image\":\n return <ImagePreview attachment={attachment} />;\n case \"audio\":\n return <AudioPreview attachment={attachment} />;\n case \"video\":\n return <VideoPreview attachment={attachment} />;\n case \"document\":\n return <DocumentPreview attachment={attachment} />;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Image\n// ---------------------------------------------------------------------------\n\nfunction ImagePreview({ attachment }: { attachment: Attachment }) {\n const src = getSourceUrl(attachment.source);\n const { thumbnailRef, vtName, open, openLightbox, closeLightbox } =\n useLightbox();\n\n return (\n <>\n <img\n ref={thumbnailRef as React.Ref<HTMLImageElement>}\n src={src}\n alt={attachment.filename || \"Image attachment\"}\n className=\"cpk-attachment-queue-image\"\n onClick={openLightbox}\n />\n {open && (\n <Lightbox\n onClose={closeLightbox}\n label={attachment.filename || \"Image attachment\"}\n >\n <img\n style={{ viewTransitionName: vtName }}\n src={src}\n alt={attachment.filename || \"Image attachment\"}\n className=\"cpk-attachment-queue-lightbox-image\"\n />\n </Lightbox>\n )}\n </>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Audio\n// ---------------------------------------------------------------------------\n\nfunction AudioPreview({ attachment }: { attachment: Attachment }) {\n const src = getSourceUrl(attachment.source);\n return (\n <div className=\"cpk-attachment-queue-audio\">\n <audio\n src={src}\n controls\n preload=\"metadata\"\n className=\"cpk-attachment-queue-audio-player\"\n />\n {attachment.filename && (\n <span className=\"cpk-attachment-queue-audio-filename\">\n {attachment.filename}\n </span>\n )}\n </div>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Video – thumbnail with play button; click opens lightbox with full controls\n// ---------------------------------------------------------------------------\n\n/**\n * A video thumbnail with a play button, named by\n * `labels.attachmentPlayVideoButtonLabel`, that opens the full player in a\n * lightbox.\n */\nfunction VideoPreview({ attachment }: { attachment: Attachment }) {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const src = getSourceUrl(attachment.source);\n const { thumbnailRef, vtName, open, openLightbox, closeLightbox } =\n useLightbox();\n\n return (\n <>\n <div\n ref={thumbnailRef as React.Ref<HTMLDivElement>}\n className=\"cpk-attachment-queue-video\"\n >\n {attachment.thumbnail ? (\n <img\n src={attachment.thumbnail}\n alt={attachment.filename || \"Video thumbnail\"}\n className=\"cpk-attachment-queue-video-thumbnail\"\n />\n ) : (\n <video\n src={src}\n preload=\"metadata\"\n muted\n className=\"cpk-attachment-queue-video-thumbnail\"\n />\n )}\n </div>\n <button\n onClick={openLightbox}\n className=\"cpk-attachment-queue-video-play-button\"\n aria-label={labels.attachmentPlayVideoButtonLabel}\n >\n <div className=\"cpk-attachment-queue-video-play-badge\">\n <CopilotIcon\n name=\"Play\"\n className=\"cpk-attachment-queue-video-play-icon\"\n />\n </div>\n </button>\n {open && (\n <Lightbox\n onClose={closeLightbox}\n label={attachment.filename || \"Video attachment\"}\n >\n <video\n style={{ viewTransitionName: vtName }}\n src={src}\n controls\n autoPlay\n className=\"cpk-attachment-queue-lightbox-video\"\n />\n </Lightbox>\n )}\n </>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Document – click opens lightbox with PDF/text preview or info card\n// ---------------------------------------------------------------------------\n\n/**\n * A URL a frame can show for the attachment. Base64 data becomes a blob:\n * URL (browsers block data: URLs for PDFs), revoked on unmount.\n */\nfunction useBlobUrl(attachment: Attachment): string | null {\n const [url, setUrl] = useState<string | null>(null);\n\n useEffect(() => {\n if (attachment.source.type !== \"data\") return;\n const objectUrl = ɵcreateObjectUrlFromSource(attachment.source);\n setUrl(objectUrl?.url ?? null);\n return objectUrl?.revoke;\n }, [\n attachment.source.type,\n attachment.source.value,\n attachment.source.mimeType,\n ]);\n\n if (attachment.source.type === \"url\") return attachment.source.value;\n return url;\n}\n\nfunction DocumentLightboxContent({\n attachment,\n vtName,\n}: {\n attachment: Attachment;\n vtName: string;\n}) {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const mimeType = attachment.source.mimeType;\n const blobUrl = useBlobUrl(attachment);\n const preview = ɵcanPreviewDocument(mimeType);\n\n if (preview === \"pdf\") {\n if (!blobUrl) return null;\n return (\n <iframe\n style={{ viewTransitionName: vtName }}\n src={blobUrl}\n title={attachment.filename || \"PDF preview\"}\n className=\"cpk-attachment-queue-pdf-preview\"\n />\n );\n }\n\n if (preview === \"text\") {\n const textContent = ɵdecodeTextSource(attachment.source);\n return (\n <div\n style={{ viewTransitionName: vtName }}\n className=\"cpk-attachment-queue-text-preview\"\n >\n {attachment.filename && (\n <div className=\"cpk-attachment-queue-text-preview-filename\">\n {attachment.filename}\n </div>\n )}\n {textContent ? (\n <pre className=\"cpk-attachment-queue-text-preview-content\">\n {textContent}\n </pre>\n ) : blobUrl ? (\n <iframe\n src={blobUrl}\n title={attachment.filename || \"Text preview\"}\n className=\"cpk-attachment-queue-text-preview-frame\"\n />\n ) : null}\n </div>\n );\n }\n\n // Fallback: info card for non-previewable documents\n return (\n <div\n style={{ viewTransitionName: vtName }}\n className=\"cpk-attachment-queue-document-card\"\n >\n <div className=\"cpk-attachment-queue-document-card-icon\">\n {getDocumentIcon(mimeType ?? \"\")}\n </div>\n <div className=\"cpk-attachment-queue-document-card-details\">\n <div className=\"cpk-attachment-queue-document-card-name\">\n {attachment.filename || labels.attachmentDocumentLabel}\n </div>\n <div className=\"cpk-attachment-queue-document-card-meta\">\n {mimeType || labels.attachmentUnknownTypeText}\n {attachment.size != null && ` · ${formatFileSize(attachment.size)}`}\n </div>\n </div>\n <div className=\"cpk-attachment-queue-document-card-note\">\n {labels.attachmentNoPreviewText}\n </div>\n </div>\n );\n}\n\nfunction DocumentPreview({ attachment }: { attachment: Attachment }) {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const { thumbnailRef, vtName, open, openLightbox, closeLightbox } =\n useLightbox();\n\n const mimeType = attachment.source.mimeType;\n const previewable = ɵcanPreviewDocument(mimeType) !== null;\n\n return (\n <>\n <div\n ref={thumbnailRef as React.Ref<HTMLDivElement>}\n className={cn(\n \"cpk-attachment-queue-document\",\n previewable && \"cpk-attachment-queue-document-previewable\",\n )}\n onClick={previewable ? openLightbox : undefined}\n >\n <div className=\"cpk-attachment-queue-document-icon\">\n {getDocumentIcon(mimeType ?? \"\")}\n </div>\n <div className=\"cpk-attachment-queue-document-info\">\n <span className=\"cpk-attachment-queue-document-name\">\n {attachment.filename || labels.attachmentDocumentLabel}\n </span>\n {attachment.size != null && (\n <span className=\"cpk-attachment-queue-document-size\">\n {formatFileSize(attachment.size)}\n </span>\n )}\n </div>\n </div>\n {open && (\n <Lightbox\n onClose={closeLightbox}\n label={attachment.filename || labels.attachmentDocumentLabel}\n >\n <DocumentLightboxContent attachment={attachment} vtName={vtName} />\n </Lightbox>\n )}\n </>\n );\n}\n","import { useState, useEffect } from \"react\";\nimport { ɵinitialKeyboardState, ɵwatchKeyboardState } from \"@copilotkit/core\";\nimport type { ɵKeyboardState } from \"@copilotkit/core\";\n\nexport type KeyboardState = ɵKeyboardState;\n\n/**\n * Hook to detect mobile keyboard appearance and calculate available viewport height.\n * Uses the Visual Viewport API to track keyboard state on mobile devices.\n *\n * @returns KeyboardState object with keyboard information\n */\nexport function useKeyboardHeight(): KeyboardState {\n const [keyboardState, setKeyboardState] = useState(ɵinitialKeyboardState);\n useEffect(() => ɵwatchKeyboardState(setKeyboardState), []);\n return keyboardState;\n}\n","import React from \"react\";\n\n/**\n * Context used by `CopilotChatView` to announce the latest user message\n * to descendants (notably `usePinToSend`), so scroll logic can anchor\n * the viewport to the most recent user turn in \"pin-to-send\" mode.\n *\n * `sendNonce` increments on each new send so repeated IDs (e.g., message\n * edits that preserve the ID) still trigger dependent effects.\n */\nexport type LastUserMessageState = {\n id: string | null;\n sendNonce: number;\n};\n\nexport const LastUserMessageContext = React.createContext<LastUserMessageState>(\n {\n id: null,\n sendNonce: 0,\n },\n);\n","import { useContext, useEffect, useRef } from \"react\";\nimport { ɵpinMessageToTop } from \"@copilotkit/core\";\nimport { LastUserMessageContext } from \"../components/chat/last-user-message-context\";\n\nexport type UsePinToSendOptions = {\n scrollRef: React.RefObject<HTMLElement | null>;\n contentRef: React.RefObject<HTMLElement | null>;\n spacerRef: React.RefObject<HTMLElement | null>;\n topOffset?: number;\n};\n\n/**\n * Pins the latest sent user message near the top of the chat while the reply\n * streams below it. Core's `ɵpinMessageToTop` does the measuring and\n * scrolling; this hook runs it once per send.\n */\nexport function usePinToSend({\n scrollRef,\n contentRef,\n spacerRef,\n topOffset = 16,\n}: UsePinToSendOptions): void {\n const { id, sendNonce } = useContext(LastUserMessageContext);\n const lastNonceRef = useRef<number>(-1);\n\n useEffect(() => {\n if (sendNonce === lastNonceRef.current) return;\n const previousNonce = lastNonceRef.current;\n lastNonceRef.current = sendNonce;\n\n if (!id) return;\n const scrollEl = scrollRef.current;\n const contentEl = contentRef.current;\n const spacerEl = spacerRef.current;\n if (!scrollEl || !contentEl || !spacerEl) return;\n\n const unpin = ɵpinMessageToTop({\n scrollEl,\n contentEl,\n spacerEl,\n messageId: id,\n topOffset,\n });\n return () => {\n // Torn down before the scroll ran, as React's StrictMode does right\n // after mount (the first send mounts the message list): let the next\n // run pin this send again. Skipping it would leave the spacer at its\n // full height for good, with nothing to shrink it as the reply grows.\n if (!unpin()) lastNonceRef.current = previousNonce;\n };\n }, [id, sendNonce, scrollRef, contentRef, spacerRef, topOffset]);\n}\n","import React, {\n useCallback,\n useRef,\n useState,\n useEffect,\n useLayoutEffect,\n} from \"react\";\nimport { ScrollElementContext } from \"./scroll-element-context\";\nimport type { WithSlots, SlotValue } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport CopilotChatMessageView from \"./CopilotChatMessageView\";\nimport type { CopilotChatMessageViewProps } from \"./CopilotChatMessageView\";\nimport type { IntelligenceIndicatorView } from \"../intelligence-indicator\";\nimport type {\n CopilotChatInputProps,\n CopilotChatInputMode,\n} from \"./CopilotChatInput\";\nimport CopilotChatInput from \"./CopilotChatInput\";\nimport CopilotChatSuggestionView from \"./CopilotChatSuggestionView\";\nimport {\n ɵgetChatViewState,\n ɵisContentScrolledToBottom,\n ɵisScrolledToBottom,\n ɵwatchElementHeight,\n} from \"@copilotkit/core\";\nimport type { Suggestion } from \"@copilotkit/core\";\nimport type { Message } from \"@ag-ui/core\";\nimport type { Attachment } from \"@copilotkit/shared\";\nimport { CopilotChatAttachmentQueue } from \"./CopilotChatAttachmentQueue\";\nimport { StickToBottom, useStickToBottomContext } from \"use-stick-to-bottom\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport { Button } from \"../../components/ui/button\";\nimport { cn } from \"../../lib/utils\";\nimport { CopilotChatDefaultLabels } from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport { useKeyboardHeight } from \"../../hooks/use-keyboard-height\";\nimport { ScrollPinnedContext } from \"./scroll-pinned-context\";\nimport { ɵnormalizeAutoScroll as normalizeAutoScroll } from \"@copilotkit/core\";\nimport type { ɵAutoScrollMode as AutoScrollMode } from \"@copilotkit/core\";\nimport { usePinToSend } from \"../../hooks/use-pin-to-send\";\n\n// Vertical gap between the scroll-to-bottom button and the input container.\nconst SCROLL_BUTTON_OFFSET = 16;\n\n// Forward declaration for WelcomeScreen component type\nexport type WelcomeScreenProps = WithSlots<\n {\n welcomeMessage: React.FC<React.HTMLAttributes<HTMLDivElement>>;\n },\n {\n input: React.ReactElement;\n suggestionView: React.ReactElement;\n } & React.HTMLAttributes<HTMLDivElement>\n>;\n\nexport type CopilotChatViewProps = WithSlots<\n {\n // Props-based for the same reason as `input` below: renderSlot only\n // renders the slot, so CopilotChatMessageView's statics (Cursor) are not\n // required of a replacement.\n messageView: React.ComponentType<CopilotChatMessageViewProps>;\n scrollView: typeof CopilotChatView.ScrollView;\n // Widened to the props-based form so a plain FC / call signature assigns\n // without the CopilotChatInput namespace statics — see #7158, same shape as\n // CopilotChat's `chatView` after #7156.\n input: React.ComponentType<CopilotChatInputProps>;\n suggestionView: typeof CopilotChatSuggestionView;\n },\n {\n messages?: Message[];\n autoScroll?: AutoScrollMode | boolean;\n isRunning?: boolean;\n suggestions?: Suggestion[];\n suggestionLoadingIndexes?: ReadonlyArray<number>;\n onSelectSuggestion?: (suggestion: Suggestion, index: number) => void;\n welcomeScreen?: SlotValue<React.FC<WelcomeScreenProps>> | boolean;\n // Input behavior props\n onSubmitMessage?: (value: string) => void;\n onStop?: () => void;\n inputMode?: CopilotChatInputMode;\n inputValue?: string;\n onInputChange?: (value: string) => void;\n onStartTranscribe?: () => void;\n onCancelTranscribe?: () => void;\n onFinishTranscribe?: () => void;\n onFinishTranscribeWithAudio?: (audioBlob: Blob) => Promise<void>;\n // Attachment props\n attachments?: Attachment[];\n onRemoveAttachment?: (id: string) => void;\n onAddFile?: () => void;\n dragOver?: boolean;\n onDragOver?: (e: React.DragEvent) => void;\n onDragLeave?: (e: React.DragEvent) => void;\n onDrop?: (e: React.DragEvent) => void;\n /**\n * When `true`, suppresses the welcome screen while a thread's initial\n * connect is in flight. Prevents the \"How can I help you today?\" flash\n * that would otherwise appear between mounting an empty agent instance\n * and the bootstrap messages arriving from /connect.\n */\n isConnecting?: boolean;\n /**\n * Indicator shown while `isConnecting` is `true` and no messages have\n * arrived yet, so restoring a thread's history doesn't render as an\n * empty panel. Pass `false` to disable it, or a component, className, or\n * props object to customize it.\n */\n connectingIndicator?:\n | SlotValue<React.FC<React.HTMLAttributes<HTMLDivElement>>>\n | boolean;\n /**\n * When `true`, the caller has explicitly picked a thread (via `threadId`\n * prop or `CopilotChatConfigurationProvider`). Suppresses the welcome\n * screen unconditionally — a caller-managed thread targets a specific\n * conversation and should render its messages (or an empty panel during\n * connect) rather than a generic \"start a new chat\" greeting.\n */\n hasExplicitThreadId?: boolean;\n /**\n * Slot for the \"Using CopilotKit Intelligence\" indicator. Pass-through\n * to `CopilotChatMessageView`'s `intelligenceIndicator` slot — accepts a\n * className string, a props object, or a replacement component.\n */\n intelligenceIndicator?: SlotValue<typeof IntelligenceIndicatorView>;\n } & Omit<React.HTMLAttributes<HTMLDivElement>, \"inputMode\">\n>;\n\nfunction DropOverlay() {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <div className=\"cpk-chat-view-drop-overlay\">\n <div className=\"cpk-chat-view-drop-overlay-content\">\n <CopilotIcon\n name=\"Upload\"\n className=\"cpk-chat-view-drop-overlay-icon\"\n />\n <span className=\"cpk-chat-view-drop-overlay-label\">\n {labels.chatDropFilesLabel}\n </span>\n </div>\n </div>\n );\n}\n\nexport function CopilotChatView({\n messageView,\n input,\n scrollView,\n suggestionView,\n welcomeScreen,\n messages = [],\n autoScroll = true,\n isRunning = false,\n suggestions,\n suggestionLoadingIndexes,\n onSelectSuggestion,\n // Input behavior props\n onSubmitMessage,\n onStop,\n inputMode,\n inputValue,\n onInputChange,\n onStartTranscribe,\n onCancelTranscribe,\n onFinishTranscribe,\n onFinishTranscribeWithAudio,\n // Attachment props\n attachments,\n onRemoveAttachment,\n onAddFile,\n dragOver,\n onDragOver,\n onDragLeave,\n onDrop,\n isConnecting = false,\n connectingIndicator,\n hasExplicitThreadId = false,\n // Pass-through to CopilotChatMessageView's intelligenceIndicator slot\n intelligenceIndicator,\n children,\n className,\n ...props\n}: CopilotChatViewProps) {\n // Element-as-state via callback ref. The overlay wrapper only renders on the\n // chat-view branch (the welcome-screen branch omits it), so a plain\n // useRef + `[]` useEffect would observe `null` on mount whenever the chat\n // starts on the welcome screen and never re-attach after the user sends\n // their first message — leaving inputContainerHeight at 0 and the scroll\n // content's reserved bottom padding at 32px instead of ~input height. The\n // result is the last messages scrolling underneath the absolute-positioned\n // input pill. Subscribing to element state lets the observer attach (and\n // detach) reactively as the overlay mounts/unmounts.\n // Use the provider's thread identity when available. A standalone view\n // changes identity only when its new history has no messages in common with\n // the previous nonempty list. Prepending or trimming history is not a switch.\n const configuredThreadId = useCopilotChatConfiguration()?.threadId;\n const [fallbackThreadId, setFallbackThreadId] = useState(messages[0]?.id);\n const previousMessageIds = useRef(new Set<string>());\n useEffect(() => {\n const firstMessage = messages[0];\n if (firstMessage === undefined) return;\n const overlaps = messages.some((message) =>\n previousMessageIds.current.has(message.id),\n );\n previousMessageIds.current = new Set(messages.map((message) => message.id));\n if (!overlaps) setFallbackThreadId(firstMessage.id);\n }, [messages]);\n const scrollThreadId = configuredThreadId ?? fallbackThreadId;\n const [inputContainerEl, setInputContainerEl] =\n useState<HTMLDivElement | null>(null);\n const [inputContainerHeight, setInputContainerHeight] = useState(0);\n const [isResizing, setIsResizing] = useState(false);\n\n // Track keyboard state for mobile\n const { isKeyboardOpen, keyboardHeight } = useKeyboardHeight();\n\n // Track input container height changes. While the height settles, the\n // scroll-to-bottom button hides (see ɵwatchElementHeight).\n useEffect(() => {\n const element = inputContainerEl;\n if (!element) {\n // Reset measured height so the scroll content's paddingBottom doesn't\n // hold a stale value if the overlay unmounts (e.g. messages cleared\n // and the welcome screen returns).\n setInputContainerHeight(0);\n setIsResizing(false);\n return;\n }\n return ɵwatchElementHeight(element, (state) => {\n setInputContainerHeight(state.height);\n setIsResizing(state.isResizing);\n });\n }, [inputContainerEl]);\n\n const BoundMessageView = renderSlot(messageView, CopilotChatMessageView, {\n messages,\n isRunning,\n intelligenceIndicator,\n });\n\n const BoundInput = renderSlot(input, CopilotChatInput, {\n onSubmitMessage,\n onStop,\n mode: inputMode,\n value: inputValue,\n onChange: onInputChange,\n isRunning,\n onStartTranscribe,\n onCancelTranscribe,\n onFinishTranscribe,\n onFinishTranscribeWithAudio,\n onAddFile,\n positioning: \"static\",\n keyboardHeight: isKeyboardOpen ? keyboardHeight : 0,\n showDisclaimer: true,\n // The parent overlay wrapper handles absolute bottom-0 positioning.\n // `bottomAnchored` still triggers the license-banner offset padding\n // inside CopilotChatInput. The welcome-screen input (below) intentionally\n // omits this flag.\n bottomAnchored: true,\n } as CopilotChatInputProps);\n\n // Suggestions, the welcome screen and the bottom padding follow core's\n // rules (ɵgetChatViewState): no suggestions while connecting or running, no\n // generic welcome for a connecting or caller-picked thread.\n const {\n hasSuggestions,\n showWelcomeScreen,\n showConnectingIndicator,\n paddingBottom,\n } = ɵgetChatViewState({\n messageCount: messages.length,\n suggestionCount: Array.isArray(suggestions) ? suggestions.length : 0,\n isRunning,\n isConnecting,\n hasExplicitThreadId,\n // Type assertion needed because TypeScript doesn't fully propagate `| boolean` through WithSlots\n welcomeScreenEnabled: (welcomeScreen as unknown) !== false,\n inputContainerHeight,\n connectingIndicatorEnabled: connectingIndicator !== false,\n });\n const BoundSuggestionView = hasSuggestions\n ? renderSlot(suggestionView, CopilotChatSuggestionView, {\n suggestions,\n loadingIndexes: suggestionLoadingIndexes,\n onSelectSuggestion,\n className: \"cpk-chat-view-suggestion-view\",\n })\n : null;\n\n // Show a loading indicator while a thread's initial connect is in flight\n // and nothing has been restored yet. Once the first message arrives the\n // message view takes over, even if the bootstrap stream is still replaying.\n const BoundConnectingIndicator = showConnectingIndicator\n ? renderSlot(\n typeof connectingIndicator === \"boolean\"\n ? undefined\n : connectingIndicator,\n CopilotChatView.ConnectingIndicator,\n {},\n )\n : null;\n\n const BoundScrollView = renderSlot(scrollView, CopilotChatView.ScrollView, {\n autoScroll,\n scrollThreadId,\n inputContainerHeight,\n isResizing,\n children: (\n <div\n data-testid=\"copilot-scroll-content\"\n style={{\n paddingBottom: `${paddingBottom}px`,\n }}\n >\n <div className=\"cpk-chat-view-feed\">\n {BoundConnectingIndicator}\n {BoundMessageView}\n {hasSuggestions ? (\n <div className=\"cpk-chat-view-suggestions\">\n {BoundSuggestionView}\n </div>\n ) : null}\n </div>\n </div>\n ),\n });\n\n if (showWelcomeScreen) {\n // Create a separate input for welcome screen with static positioning and disclaimer visible\n const BoundInputForWelcome = renderSlot(input, CopilotChatInput, {\n onSubmitMessage,\n onStop,\n mode: inputMode,\n value: inputValue,\n onChange: onInputChange,\n isRunning,\n onStartTranscribe,\n onCancelTranscribe,\n onFinishTranscribe,\n onFinishTranscribeWithAudio,\n onAddFile,\n positioning: \"static\",\n showDisclaimer: true,\n } as CopilotChatInputProps);\n\n // Convert boolean `true` to undefined (use default), and exclude `false` since we've checked for it\n const welcomeScreenSlot = (\n welcomeScreen === true ? undefined : welcomeScreen\n ) as SlotValue<React.FC<WelcomeScreenProps>> | undefined;\n // Wrap the input with attachment queue above it\n const inputWithAttachments = (\n <div className=\"cpk-chat-view-welcome-input-group\">\n {attachments && attachments.length > 0 && (\n <CopilotChatAttachmentQueue\n attachments={attachments}\n onRemoveAttachment={(id) => onRemoveAttachment?.(id)}\n className=\"cpk-chat-view-welcome-attachment-queue\"\n />\n )}\n {BoundInputForWelcome}\n </div>\n );\n\n const BoundWelcomeScreen = renderSlot(\n welcomeScreenSlot,\n CopilotChatView.WelcomeScreen,\n {\n input: inputWithAttachments,\n suggestionView: BoundSuggestionView ?? <></>,\n },\n );\n\n return (\n <div\n data-copilotkit\n data-testid=\"copilot-chat\"\n data-copilot-running={isRunning ? \"true\" : \"false\"}\n data-copilot-connecting={isConnecting ? \"true\" : \"false\"}\n onDragOver={onDragOver}\n onDragLeave={onDragLeave}\n onDrop={onDrop}\n className={cn(\"copilotKitChat cpk-chat-view\", className)}\n {...props}\n >\n {dragOver && <DropOverlay />}\n {BoundWelcomeScreen}\n </div>\n );\n }\n\n if (children) {\n return (\n <div\n data-copilotkit\n data-copilot-connecting={isConnecting ? \"true\" : \"false\"}\n style={{ display: \"contents\" }}\n >\n {children({\n messageView: BoundMessageView,\n input: BoundInput,\n scrollView: BoundScrollView,\n suggestionView: BoundSuggestionView ?? <></>,\n })}\n </div>\n );\n }\n\n return (\n <div\n data-copilotkit\n data-testid=\"copilot-chat\"\n data-copilot-running={isRunning ? \"true\" : \"false\"}\n data-copilot-connecting={isConnecting ? \"true\" : \"false\"}\n onDragOver={onDragOver}\n onDragLeave={onDragLeave}\n onDrop={onDrop}\n className={cn(\"copilotKitChat cpk-chat-view\", className)}\n {...props}\n >\n {dragOver && <DropOverlay />}\n {BoundScrollView}\n\n <div\n ref={setInputContainerEl}\n data-testid=\"copilot-input-overlay\"\n className=\"cpk-chat-view-input-overlay\"\n >\n {attachments && attachments.length > 0 && (\n <div className=\"cpk-chat-view-attachments\">\n <CopilotChatAttachmentQueue\n attachments={attachments}\n onRemoveAttachment={(id) => onRemoveAttachment?.(id)}\n className=\"cpk-chat-view-attachment-queue\"\n />\n </div>\n )}\n {BoundInput}\n </div>\n </div>\n );\n}\n\nexport namespace CopilotChatView {\n // Inner component that has access to StickToBottom context\n const ScrollContent: React.FC<{\n children: React.ReactNode;\n scrollToBottomButton?: SlotValue<\n React.FC<React.ButtonHTMLAttributes<HTMLButtonElement>>\n >;\n feather?: SlotValue<React.FC<React.HTMLAttributes<HTMLDivElement>>>;\n inputContainerHeight: number;\n isResizing: boolean;\n scrollThreadId?: string;\n }> = ({\n children,\n scrollToBottomButton,\n feather,\n inputContainerHeight,\n isResizing,\n scrollThreadId,\n }) => {\n const { isAtBottom, scrollToBottom, stopScroll, scrollRef, state } =\n useStickToBottomContext();\n\n // Capture the scroll element in state so the context value is reactive —\n // consumers re-render when the element is first set rather than reading a\n // ref that silently stays null until after their own layout effects fire.\n const [scrollEl, setScrollEl] = useState<HTMLElement | null>(null);\n const readingOffsetRef = useRef<number | null>(null);\n const pinIntentRef = useRef(false);\n const stateRef = useRef(state);\n stateRef.current = state;\n useLayoutEffect(() => {\n setScrollEl(scrollRef.current ?? null);\n // scrollRef is a stable object; omitting from deps is intentional.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // A hidden chat has no viewport. The stick-to-bottom observer can mistake\n // that collapse for reaching the end and re-enable its scroll lock. Keep\n // the reader's last visible offset until the viewport is measurable again.\n useEffect(() => {\n if (!scrollEl) return;\n\n let hidden = false;\n let resumeBottom = false;\n let pendingFrame = 0;\n let resumeFrame = 0;\n let settleFrame = 0;\n readingOffsetRef.current = null;\n const rememberScroll = () => {\n if (hidden || scrollEl.clientHeight === 0) return;\n if (resumeBottom) {\n // Ignore scroll events from the collapsed layout until the pending\n // bottom pin has been restarted against the restored viewport.\n readingOffsetRef.current = null;\n return;\n }\n if (pinIntentRef.current) {\n // Keyboard, touch, and scrollbar input can escape the pin without a\n // wheel event. The library reports that escape after its scroll\n // callback, so the scheduled frame below sees the updated state.\n if (stateRef.current.escapedFromLock) {\n pinIntentRef.current = false;\n } else {\n readingOffsetRef.current = null;\n if (!stateRef.current.isNearBottom) return;\n pinIntentRef.current = false;\n }\n }\n // Geometry alone is misleading during an active smooth pin: it may\n // still be far from the end while intentionally moving there.\n readingOffsetRef.current =\n !stateRef.current.isAtBottom &&\n (stateRef.current.escapedFromLock || !stateRef.current.isNearBottom)\n ? scrollEl.scrollTop\n : null;\n };\n const onScroll = () => {\n rememberScroll();\n // The library updates escape state after its scroll event callback.\n // Re-read it on the next frame for programmatic scrolls too.\n cancelAnimationFrame(pendingFrame);\n pendingFrame = requestAnimationFrame(rememberScroll);\n };\n const onWheel = (event: WheelEvent) => {\n if (event.deltaY < 0) {\n pinIntentRef.current = false;\n resumeBottom = false;\n }\n };\n const resizeObserver = new ResizeObserver(() => {\n if (scrollEl.clientHeight === 0) {\n hidden = true;\n resumeBottom =\n pinIntentRef.current || readingOffsetRef.current === null;\n if (!resumeBottom) stopScroll();\n } else if (hidden) {\n hidden = false;\n if (resumeBottom) {\n // Cancel the old animation before starting a new one against the\n // restored viewport; otherwise its queued frame can override us.\n stopScroll();\n // The library's animation may have stopped at zero height. Wait\n // for the restored layout before calculating its new bottom.\n resumeFrame = requestAnimationFrame(() => {\n // Let the library's scroll event from the zero-height collapse\n // finish before starting a fresh pin animation.\n settleFrame = requestAnimationFrame(() => {\n if (scrollEl.clientHeight > 0 && resumeBottom) {\n resumeBottom = false;\n pinIntentRef.current = true;\n void scrollToBottom({ animation: \"instant\" });\n }\n });\n });\n } else if (readingOffsetRef.current !== null) {\n stopScroll();\n scrollEl.scrollTop = readingOffsetRef.current;\n }\n }\n });\n\n rememberScroll();\n scrollEl.addEventListener(\"scroll\", onScroll);\n scrollEl.addEventListener(\"wheel\", onWheel, { passive: true });\n resizeObserver.observe(scrollEl);\n return () => {\n scrollEl.removeEventListener(\"scroll\", onScroll);\n scrollEl.removeEventListener(\"wheel\", onWheel);\n cancelAnimationFrame(pendingFrame);\n cancelAnimationFrame(resumeFrame);\n cancelAnimationFrame(settleFrame);\n resizeObserver.disconnect();\n };\n }, [scrollEl, scrollToBottom, stopScroll, scrollThreadId]);\n\n const startBottomPin = useCallback(\n (instant = false) => {\n readingOffsetRef.current = null;\n pinIntentRef.current = true;\n void scrollToBottom(instant ? { animation: \"instant\" } : undefined);\n },\n [scrollToBottom],\n );\n\n const previousScrollThreadId = useRef(scrollThreadId);\n useEffect(() => {\n if (previousScrollThreadId.current === scrollThreadId) return;\n previousScrollThreadId.current = scrollThreadId;\n // A new conversation should start at its end even if the old one had\n // escaped the pin while its host was hidden.\n startBottomPin(true);\n }, [scrollThreadId, startBottomPin]);\n\n const BoundFeather = renderSlot(feather, CopilotChatView.Feather, {});\n\n return (\n // Provide the scroll element so CopilotChatMessageView can feed it to\n // useVirtualizer's getScrollElement. Using state (not the raw ref) means\n // the context value updates reactively when the element mounts.\n <ScrollElementContext.Provider value={scrollEl}>\n {/* While the pin is following the bottom it is the sole owner of the\n scroll position; the virtualizer stands down (see\n ScrollPinnedContext).\n\n `state.isAtBottom`, not the context's `isAtBottom`: the latter is\n `isAtBottom || isNearBottom`. Scrolling up a little — still inside\n the near-bottom band — clears `state.isAtBottom`, which is what the\n pin's animation loop checks before it moves anything, while the\n combined flag stays true. Using the combined flag would stand the\n virtualizer down in a window where nothing owns the scroll\n position.\n\n `state` is a stable object, so this is only read again when\n something re-renders us. Every transition *out* of the pin sets\n `escapedFromLock` in the same breath, and that is one of the deps\n of the memo behind this context, so the re-render is there for the\n case that matters. The way back in can lag a render, which leaves\n the virtualizer compensating slightly longer than it needs to —\n the harmless direction, and what it does by default anyway.\n\n The scroll-to-bottom button keeps the combined flag: it should\n stay hidden anywhere in the near-bottom band. */}\n <ScrollPinnedContext.Provider value={state.isAtBottom}>\n <>\n <StickToBottom.Content\n className=\"cpk-chat-view-scroll-viewport\"\n style={{ flex: \"1 1 0%\", minHeight: 0 }}\n >\n <div className=\"cpk-chat-view-scroll-content\">{children}</div>\n </StickToBottom.Content>\n\n {BoundFeather}\n\n {/* Scroll to bottom button - hidden during resize */}\n {!isAtBottom && !isResizing && (\n <div\n className=\"cpk-chat-view-scroll-to-bottom\"\n style={{\n bottom: `${inputContainerHeight + SCROLL_BUTTON_OFFSET}px`,\n }}\n >\n {renderSlot(\n scrollToBottomButton,\n CopilotChatView.ScrollToBottomButton,\n {\n onClick: () => startBottomPin(),\n },\n )}\n </div>\n )}\n </>\n </ScrollPinnedContext.Provider>\n </ScrollElementContext.Provider>\n );\n };\n\n // Internal component for pin-to-send scroll behavior — not exported on CopilotChatView.\n const PinToSendScrollContainer: React.FC<\n React.HTMLAttributes<HTMLDivElement> & {\n scrollRef: React.MutableRefObject<HTMLElement | null>;\n contentRef: React.MutableRefObject<HTMLDivElement | null>;\n scrollToBottom: () => void;\n scrollToBottomButton?: SlotValue<\n React.FC<React.ButtonHTMLAttributes<HTMLButtonElement>>\n >;\n feather?: SlotValue<React.FC<React.HTMLAttributes<HTMLDivElement>>>;\n inputContainerHeight: number;\n isResizing: boolean;\n nonAutoScrollEl: HTMLElement | null;\n nonAutoScrollRefCallback: (el: HTMLElement | null) => void;\n showScrollButton: boolean;\n }\n > = ({\n children,\n scrollRef,\n contentRef,\n scrollToBottom,\n scrollToBottomButton,\n feather,\n inputContainerHeight,\n isResizing,\n nonAutoScrollEl,\n nonAutoScrollRefCallback,\n showScrollButton,\n className,\n ...props\n }) => {\n const spacerRef = useRef<HTMLDivElement>(null);\n\n usePinToSend({\n scrollRef,\n contentRef,\n spacerRef,\n topOffset: 16,\n });\n\n // The feather and scroll-to-bottom button live OUTSIDE the scroll\n // container. `position: absolute` children of an `overflow: auto` element\n // are positioned relative to the scroll *content*, which means they\n // scroll away with it. Placing them as siblings of the scroll container\n // (inside a `relative` wrapper) keeps them pinned to the viewport bottom.\n const BoundFeather = renderSlot(feather, CopilotChatView.Feather, {});\n\n return (\n <ScrollElementContext.Provider value={nonAutoScrollEl}>\n <div className={cn(\"cpk-chat-view-scroll-area\", className)}>\n <div\n ref={nonAutoScrollRefCallback}\n className=\"cpk-chat-view-scroll-viewport\"\n {...props}\n >\n <div ref={contentRef} className=\"cpk-chat-view-scroll-content\">\n {children}\n </div>\n <div\n ref={spacerRef}\n data-pin-to-send-spacer\n aria-hidden=\"true\"\n style={{ height: 0, flex: \"0 0 auto\" }}\n />\n </div>\n {BoundFeather}\n {/* Scroll to bottom button */}\n {showScrollButton && !isResizing && (\n <div\n className=\"cpk-chat-view-scroll-to-bottom\"\n style={{\n bottom: `${inputContainerHeight + SCROLL_BUTTON_OFFSET}px`,\n }}\n >\n {renderSlot(\n scrollToBottomButton,\n CopilotChatView.ScrollToBottomButton,\n {\n onClick: () => scrollToBottom(),\n },\n )}\n </div>\n )}\n </div>\n </ScrollElementContext.Provider>\n );\n };\n\n export const ScrollView: React.FC<\n React.HTMLAttributes<HTMLDivElement> & {\n autoScroll?: AutoScrollMode | boolean;\n scrollThreadId?: string;\n scrollToBottomButton?: SlotValue<\n React.FC<React.ButtonHTMLAttributes<HTMLButtonElement>>\n >;\n feather?: SlotValue<React.FC<React.HTMLAttributes<HTMLDivElement>>>;\n inputContainerHeight?: number;\n isResizing?: boolean;\n }\n > = ({\n children,\n autoScroll = \"pin-to-bottom\",\n scrollThreadId,\n scrollToBottomButton,\n feather,\n inputContainerHeight = 0,\n isResizing = false,\n className,\n ...props\n }) => {\n const mode = normalizeAutoScroll(autoScroll);\n const [hasMounted, setHasMounted] = useState(false);\n // Plain refs for the \"none\" and \"pin-to-send\" paths. Do NOT use\n // useStickToBottom() here — its internal effects would attach scroll-following\n // behavior to these refs and fight pin-to-send. The \"pin-to-bottom\" path\n // gets its refs via <StickToBottom> below, scoped to that branch only.\n const scrollRef = useRef<HTMLElement | null>(null);\n const contentRef = useRef<HTMLDivElement | null>(null);\n const scrollToBottom = useCallback(() => {\n const el = scrollRef.current;\n if (el) el.scrollTo({ top: el.scrollHeight, behavior: \"smooth\" });\n }, []);\n const [showScrollButton, setShowScrollButton] = useState(false);\n // Tracks the scroll container element for the non-autoScroll path so the\n // context value is reactive (element state, not a ref).\n const [nonAutoScrollEl, setNonAutoScrollEl] = useState<HTMLElement | null>(\n null,\n );\n\n // Callback ref that keeps scrollRef in sync with the DOM element while also\n // updating context state — eliminates the need for a useLayoutEffect.\n const nonAutoScrollRefCallback = useCallback(\n (el: HTMLElement | null) => {\n scrollRef.current = el;\n setNonAutoScrollEl(el);\n },\n // scrollRef is a stable ref object; safe to omit.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [],\n );\n\n useEffect(() => {\n setHasMounted(true);\n }, []);\n\n // Monitor scroll position for non-autoscroll mode\n useEffect(() => {\n if (mode === \"pin-to-bottom\") return; // Skip for autoscroll mode\n\n const scrollElement = nonAutoScrollEl;\n if (!scrollElement) return;\n const contentElement = contentRef.current;\n\n // The button shows while messages sit below the viewport. That is the\n // end of the messages, not the scroll height: in \"pin-to-send\" mode an\n // empty spacer under them lets a sent message reach the top, and\n // scrolling into it would only clear the screen.\n const checkScroll = () => {\n const isAtBottom = contentElement\n ? ɵisContentScrolledToBottom(scrollElement, contentElement)\n : ɵisScrolledToBottom(scrollElement);\n setShowScrollButton(!isAtBottom);\n };\n\n checkScroll();\n scrollElement.addEventListener(\"scroll\", checkScroll);\n\n // Also check when the viewport or the messages resize: a reply that\n // streams past the bottom needs the button before anyone scrolls.\n const resizeObserver = new ResizeObserver(checkScroll);\n resizeObserver.observe(scrollElement);\n if (contentElement) resizeObserver.observe(contentElement);\n\n return () => {\n scrollElement.removeEventListener(\"scroll\", checkScroll);\n resizeObserver.disconnect();\n };\n }, [nonAutoScrollEl, mode]);\n\n if (!hasMounted) {\n return (\n <div className=\"cpk-chat-view-scroll-area cpk-chat-view-scroll-viewport\">\n <div className=\"cpk-chat-view-scroll-content\">{children}</div>\n </div>\n );\n }\n\n if (mode === \"none\") {\n const BoundFeather = renderSlot(feather, CopilotChatView.Feather, {});\n\n return (\n // Provide the scroll element so CopilotChatMessageView can use it for\n // useVirtualizer. Element state (not a ref) keeps the context reactive.\n <ScrollElementContext.Provider value={nonAutoScrollEl}>\n <div\n ref={nonAutoScrollRefCallback}\n className={cn(\n \"cpk-chat-view-scroll-area cpk-chat-view-scroll-viewport\",\n className,\n )}\n {...props}\n >\n <div ref={contentRef} className=\"cpk-chat-view-scroll-content\">\n {children}\n </div>\n\n {BoundFeather}\n\n {/* Scroll to bottom button for manual mode */}\n {showScrollButton && !isResizing && (\n <div\n className=\"cpk-chat-view-scroll-to-bottom\"\n style={{\n bottom: `${inputContainerHeight + SCROLL_BUTTON_OFFSET}px`,\n }}\n >\n {renderSlot(\n scrollToBottomButton,\n CopilotChatView.ScrollToBottomButton,\n {\n onClick: () => scrollToBottom(),\n },\n )}\n </div>\n )}\n </div>\n </ScrollElementContext.Provider>\n );\n }\n\n if (mode === \"pin-to-send\") {\n return (\n <PinToSendScrollContainer\n scrollRef={scrollRef}\n contentRef={contentRef}\n scrollToBottom={scrollToBottom}\n scrollToBottomButton={scrollToBottomButton}\n feather={feather}\n inputContainerHeight={inputContainerHeight}\n isResizing={isResizing}\n nonAutoScrollEl={nonAutoScrollEl}\n nonAutoScrollRefCallback={nonAutoScrollRefCallback}\n showScrollButton={showScrollButton}\n className={className}\n {...props}\n >\n {children}\n </PinToSendScrollContainer>\n );\n }\n\n // mode === \"pin-to-bottom\" (default)\n return (\n <StickToBottom\n className={cn(\"cpk-chat-view-scroll-view\", className)}\n resize=\"smooth\"\n initial=\"smooth\"\n {...props}\n >\n <ScrollContent\n scrollThreadId={scrollThreadId}\n scrollToBottomButton={scrollToBottomButton}\n feather={feather}\n inputContainerHeight={inputContainerHeight}\n isResizing={isResizing}\n >\n {children}\n </ScrollContent>\n </StickToBottom>\n );\n };\n\n /**\n * Scrolls the message list to the latest message. Shown while the user is\n * scrolled up; its accessible name is `labels.chatScrollToBottomLabel`.\n */\n export const ScrollToBottomButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ className, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <Button\n data-testid=\"copilot-scroll-to-bottom\"\n variant=\"outline\"\n size=\"sm\"\n className={cn(\"cpk-chat-view-scroll-to-bottom-button\", className)}\n aria-label={labels.chatScrollToBottomLabel}\n {...props}\n >\n <CopilotIcon\n name=\"ChevronDown\"\n className=\"cpk-chat-view-scroll-to-bottom-icon\"\n />\n </Button>\n );\n };\n\n // Default renders an empty div — no visual, but the element is still in the\n // tree so a slot override of the form `scrollView={{ feather: \"my-class\" }}`\n // can apply classes (and any consumer with a full component override gets\n // the className/style forwarding they expect).\n export const Feather: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({\n className,\n ...props\n }) => <div className={className} {...props} />;\n\n /**\n * Default indicator shown while a thread's history is being restored.\n * Renders a spinner plus visually hidden `labels.chatConnectingLabel` text\n * inside a `role=\"status\"` region. Replace it via the `connectingIndicator`\n * slot.\n */\n export const ConnectingIndicator: React.FC<\n React.HTMLAttributes<HTMLDivElement>\n > = ({ className, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n\n return (\n <div\n data-testid=\"copilot-connecting-indicator\"\n role=\"status\"\n className={cn(\"cpk-chat-view-connecting-indicator\", className)}\n {...props}\n >\n <CopilotIcon\n name=\"Loader2\"\n className=\"cpk-chat-view-connecting-spinner\"\n />\n {/* Screen readers announce a status region's text content, not its\n aria-label, so the label is visually hidden text. */}\n <span className=\"cpk-chat-view-connecting-label\">\n {labels.chatConnectingLabel}\n </span>\n </div>\n );\n };\n\n export const WelcomeMessage: React.FC<\n React.HTMLAttributes<HTMLDivElement>\n > = ({ className, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n\n return (\n <h1 className={cn(\"cpk-chat-view-welcome-message\", className)} {...props}>\n {labels.welcomeMessageText}\n </h1>\n );\n };\n\n export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({\n welcomeMessage,\n input,\n suggestionView,\n className,\n children,\n ...props\n }) => {\n // Render the welcomeMessage slot internally\n const BoundWelcomeMessage = renderSlot(\n welcomeMessage,\n CopilotChatView.WelcomeMessage,\n {},\n );\n\n if (children) {\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children({\n welcomeMessage: BoundWelcomeMessage,\n input,\n suggestionView,\n className,\n ...props,\n })}\n </div>\n );\n }\n\n return (\n <div\n data-testid=\"copilot-welcome-screen\"\n className={cn(\"cpk-chat-view-welcome-screen\", className)}\n {...props}\n >\n <div className=\"cpk-chat-view-welcome-screen-content\">\n {/* Welcome message */}\n <div className=\"cpk-chat-view-welcome-screen-message\">\n {BoundWelcomeMessage}\n </div>\n\n {/* Input */}\n <div className=\"cpk-chat-view-welcome-screen-input\">{input}</div>\n\n {/* Suggestions */}\n <div className=\"cpk-chat-view-welcome-screen-suggestions\">\n {suggestionView}\n </div>\n </div>\n </div>\n );\n };\n}\n\nexport default CopilotChatView;\n","import { useEffect, useState, useSyncExternalStore } from \"react\";\nimport { ɵInspectorThreadOverride } from \"@copilotkit/core\";\n\n/**\n * Apply the Inspector's \"view this thread\" requests to a chat. Core's\n * `ɵInspectorThreadOverride` owns the state machine; this hook binds it to\n * the component's lifetime and React's render cycle.\n */\nexport function useInspectorThreadOverride(args: {\n agentId: string;\n baseThreadId: string;\n}): {\n inspectorThreadId: string | null;\n inspectorRequestId: string | null;\n failInspectorOverride: (requestId: string) => void;\n} {\n const [controller] = useState(() => new ɵInspectorThreadOverride(args));\n const override = useSyncExternalStore(\n controller.subscribe,\n controller.getSnapshot,\n controller.getSnapshot,\n );\n\n const { agentId, baseThreadId } = args;\n useEffect(() => {\n controller.update({ agentId, baseThreadId });\n }, [controller, agentId, baseThreadId]);\n\n return {\n inspectorThreadId: override?.threadId ?? null,\n inspectorRequestId: override?.requestId ?? null,\n failInspectorOverride: controller.fail,\n };\n}\n","import { useAgent } from \"../../hooks/use-agent\";\nimport { useAttachments } from \"../../hooks/use-attachments\";\nimport { useSuggestions } from \"../../hooks/use-suggestions\";\nimport type { CopilotChatViewProps } from \"./CopilotChatView\";\nimport { CopilotChatView } from \"./CopilotChatView\";\nimport type { CopilotChatInputMode } from \"./CopilotChatInput\";\nimport {\n CopilotChatConfigurationProvider,\n useCopilotChatConfiguration,\n} from \"../../providers/CopilotChatConfigurationProvider\";\nimport { randomUUID } from \"@copilotkit/shared\";\nimport type { AttachmentsConfig } from \"@copilotkit/shared\";\nimport {\n CopilotChatDefaultLabels,\n CopilotKitCoreErrorCode,\n CopilotKitCoreRuntimeConnectionStatus,\n ɵChatConnection,\n ɵcreateChatSubmitter,\n ɵcreateLastUserMessageTracker,\n ɵcreateThreadStore,\n ɵFreshThreadId,\n ɵmessagesFingerprint,\n ɵresolveAgentId,\n ɵresolveChatNotice,\n ɵsubscribeToAgentErrors,\n} from \"@copilotkit/core\";\nimport type {\n CopilotChatLabels,\n Suggestion,\n ɵChatRunScope,\n ɵThreadRuntimeContext,\n ɵThreadStore,\n} from \"@copilotkit/core\";\nimport React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n useCopilotKit,\n useDefaultAgentId,\n useLicenseContext,\n} from \"../../context\";\nimport { InlineFeatureWarning } from \"../../components/license-warning-banner\";\nimport type { SlotValue } from \"../../lib/slots\";\nimport { renderSlot, useShallowStableRef } from \"../../lib/slots\";\nimport { LastUserMessageContext } from \"./last-user-message-context\";\nimport type { LastUserMessageState } from \"./last-user-message-context\";\nimport { useInspectorThreadOverride } from \"../../providers/use-inspector-thread-override\";\nimport { GenerativeUIChatSlotContext } from \"../../generative-ui/chat\";\nimport type { GenerativeUIChatSurfaceProps } from \"../../generative-ui/chat\";\nimport {\n CopilotKitInspectorContextProvider,\n useCopilotKitInspector,\n} from \"../CopilotKitInspectorContext\";\nimport { CopilotKitStyles } from \"../../styles/copilot-kit-styles\";\n\nexport type CopilotChatProps = Omit<\n CopilotChatViewProps,\n | \"messages\"\n | \"isRunning\"\n | \"suggestions\"\n | \"suggestionLoadingIndexes\"\n | \"onSelectSuggestion\"\n // Attachment state props — managed internally based on `attachments` config\n | \"attachments\"\n | \"onRemoveAttachment\"\n | \"onAddFile\"\n | \"dragOver\"\n | \"onDragOver\"\n | \"onDragLeave\"\n | \"onDrop\"\n // CopilotChat defines its own agent-error `onError` below and never passes\n // it to the view's <div>, so the DOM `onError` attribute is left out.\n | \"onError\"\n // Redeclared below, deprecated: the chat sets it from its own state\n | \"inputMode\"\n> & {\n /**\n * @deprecated Has no effect. `CopilotChat` sets the input mode from its own\n * transcription state. To set it yourself, render `CopilotChatView` and pass\n * `inputMode` there.\n */\n inputMode?: CopilotChatViewProps[\"inputMode\"];\n agentId?: string;\n threadId?: string;\n labels?: Partial<CopilotChatLabels>;\n /**\n * Enable Inspector message shortcuts for this chat (enabled by default).\n * An explicit CopilotKit provider enableInspector value takes priority.\n * Shortcuts only appear in local development while Inspector is visible.\n */\n inspectorTools?: boolean;\n /** Accepts a className, partial props, or any component with CopilotChatView props — static namespace members are not required. */\n chatView?: SlotValue<React.ComponentType<CopilotChatViewProps>>;\n isModalDefaultOpen?: boolean;\n /** Enable multimodal file attachments (images, audio, video, documents). */\n attachments?: AttachmentsConfig;\n /**\n * Error handler scoped to this chat's agent. Fires in addition to the\n * provider-level onError (does not suppress it). Receives only errors\n * whose context.agentId matches this chat's agent.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n /**\n * Throttle interval (in milliseconds) for re-renders triggered by message\n * change notifications. Overrides the provider-level `defaultThrottleMs`\n * for this chat instance. Forwarded to the internal `useAgent()` hook,\n * which resolves the effective throttle value.\n *\n * @default undefined — inherits from provider `defaultThrottleMs`;\n * if that is also unset, re-renders are unthrottled. Note: passing\n * `throttleMs={0}` explicitly disables throttling for this instance\n * even when the provider specifies a non-zero `defaultThrottleMs`.\n */\n throttleMs?: number;\n /**\n * Experimental. Wrapper for generative UI surfaces rendered in this chat.\n * Receives `{ surfaceId, isStreaming, error, children }`.\n */\n generativeUISurface?: React.ComponentType<GenerativeUIChatSurfaceProps>;\n};\nexport function CopilotChat({\n agentId,\n threadId,\n labels,\n inspectorTools,\n chatView,\n isModalDefaultOpen,\n attachments: attachmentsConfig,\n onError,\n throttleMs,\n generativeUISurface,\n ...props\n}: CopilotChatProps) {\n // Check for existing configuration provider\n const existingConfig = useCopilotChatConfiguration();\n const inspector = useCopilotKitInspector();\n const inspectorContextValue = useMemo(\n () => ({\n ...inspector,\n isInspectorEnabled:\n inspector.isInspectorEnabled &&\n (inspector.providerEnableInspector ?? inspectorTools ?? true),\n }),\n [inspector, inspectorTools],\n );\n\n // Apply priority: props > existing config > defaults\n const providerAgentId = useDefaultAgentId();\n const resolvedAgentId = ɵresolveAgentId({\n agentId,\n chatAgentId: existingConfig?.agentId,\n providerAgentId,\n });\n const providedThreadId = threadId ?? existingConfig?.threadId;\n const [freshThreadId] = useState(() => new ɵFreshThreadId());\n const baseThreadId = useMemo(\n () => freshThreadId.resolve(providedThreadId),\n [freshThreadId, providedThreadId],\n );\n // \"Explicit\" means a caller actually picked this thread — via the\n // `threadId` prop on CopilotChat or a wrapping provider that marked its\n // threadId as caller-chosen. An auto-minted UUID leaking down through a\n // CopilotChatConfigurationProvider (e.g. from the v1 CopilotKit →\n // ThreadsProvider chain) does NOT count; treating it as explicit is\n // what made /connect fire against 404s and the welcome screen stay\n // hidden for fresh empty chats.\n const baseHasExplicitThreadId =\n !!threadId || !!existingConfig?.hasExplicitThreadId;\n const { inspectorThreadId, inspectorRequestId, failInspectorOverride } =\n useInspectorThreadOverride({\n agentId: resolvedAgentId,\n baseThreadId,\n });\n const resolvedThreadId = inspectorThreadId ?? baseThreadId;\n const hasExplicitThreadId =\n inspectorThreadId !== null || baseHasExplicitThreadId;\n\n const { agent, isReady } = useAgent({\n agentId: resolvedAgentId,\n throttleMs,\n });\n const { copilotkit } = useCopilotKit();\n const { suggestions: autoSuggestions } = useSuggestions({\n agentId: resolvedAgentId,\n });\n\n const { checkFeature } = useLicenseContext();\n const isChatLicensed = checkFeature(\"chat\");\n\n useEffect(() => {\n if (!isChatLicensed) {\n console.warn(\n '[CopilotKit] Warning: \"chat\" feature is not licensed. Visit copilotkit.ai/pricing',\n );\n }\n }, [isChatLicensed]);\n\n // onError subscription — forward core errors scoped to this chat's agent\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n if (!onErrorRef.current) return;\n return ɵsubscribeToAgentErrors(copilotkit, resolvedAgentId, (event) =>\n onErrorRef.current?.(event),\n );\n }, [copilotkit, resolvedAgentId]);\n\n // Loads the thread this chat shows. Owns the connect's abort, detach and\n // \"connecting\" state, and ends a failed Inspector override.\n const failInspectorOverrideRef = useRef(failInspectorOverride);\n failInspectorOverrideRef.current = failInspectorOverride;\n const [connection] = useState(\n () =>\n new ɵChatConnection({\n core: copilotkit,\n onInspectorOverrideFailed: (requestId) =>\n failInspectorOverrideRef.current(requestId),\n }),\n );\n const { threads } = connection;\n useSyncExternalStore(\n useCallback((onChange) => connection.subscribe(onChange), [connection]),\n () => connection.getSnapshot(),\n () => connection.getSnapshot(),\n );\n\n // Transcription state\n const [transcribeMode, setTranscribeMode] =\n useState<CopilotChatInputMode>(\"input\");\n const [inputValue, setInputValue] = useState(\"\");\n // The submitter reads and writes the input between renders (a transcript\n // appended after an await, a blocked send restored), so it goes through a\n // ref that is always the latest value.\n const inputValueRef = useRef(inputValue);\n inputValueRef.current = inputValue;\n\n // Attachments\n const {\n attachments: selectedAttachments,\n enabled: attachmentsEnabled,\n dragOver,\n fileInputRef,\n containerRef: chatContainerRef,\n handleFileUpload,\n handleDragOver,\n handleDragLeave,\n handleDrop,\n removeAttachment,\n consumeAttachments,\n } = useAttachments({ config: attachmentsConfig });\n\n // A send waits for the run in flight, so the submitter re-checks the\n // \"uploading\" guard after the wait against FRESH state, not this render's.\n const selectedAttachmentsRef = useRef(selectedAttachments);\n useEffect(() => {\n selectedAttachmentsRef.current = selectedAttachments;\n }, [selectedAttachments]);\n\n // Check if transcription is enabled\n const isTranscriptionEnabled = copilotkit.audioFileTranscriptionEnabled;\n\n // Check if browser supports MediaRecorder\n const isMediaRecorderSupported =\n typeof window !== \"undefined\" && typeof MediaRecorder !== \"undefined\";\n\n const {\n messageView: providedMessageView,\n suggestionView: providedSuggestionView,\n onStop: providedStopHandler,\n ...restProps\n } = props;\n\n // When the caller picked a thread, the welcome screen stays hidden until\n // its connect settles, so switching threads does not flash it while the\n // thread's messages load.\n const isConnecting = connection.isConnecting({\n threadId: resolvedThreadId,\n explicit: hasExplicitThreadId,\n });\n const activeConnectCountRef = useRef(0);\n const trackConnection = useCallback(\n (connect: () => Promise<void>) => {\n void connection.track(connect);\n },\n [connection],\n );\n const pendingRunActivityReconnectRef = useRef(false);\n const runActivityReconnectGenerationRef = useRef(0);\n const activeLocalRunIdsRef = useRef<Set<string>>(new Set());\n // In-flight runs this client started on the agent by any path (the input,\n // `copilotkit.runAgent`, a frontend-tool follow-up). Kept apart from\n // `activeLocalRunIdsRef`, whose pinned ids span a whole follow-up chain.\n const observedLocalRunIdsRef = useRef<Set<string>>(new Set());\n const recentlyLocalRunIdsRef = useRef<\n Map<string, ReturnType<typeof setTimeout>>\n >(new Map());\n const activeWakeRunIdsRef = useRef<Set<string>>(new Set());\n const recentlyWakeRunIdsRef = useRef<\n Map<string, ReturnType<typeof setTimeout>>\n >(new Map());\n const pendingWakeRunIdRef = useRef<string | undefined>(undefined);\n const startRunActivityReconnectRef = useRef<\n ((generation: number) => void) | null\n >(null);\n const runtimeStatus =\n copilotkit.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connected\n ? \"Connected\"\n : copilotkit.runtimeConnectionStatus;\n const hasNativeIntelligenceRunActivity =\n hasExplicitThreadId &&\n runtimeStatus === \"Connected\" &&\n !!copilotkit.intelligence?.wsUrl &&\n copilotkit.threadEndpoints?.realtimeMetadata === true;\n const [standaloneRunActivityStore] = useState<ɵThreadStore>(() =>\n ɵcreateThreadStore({\n fetch: copilotkit.ɵruntimeFetch,\n }),\n );\n\n const rememberRecentlyLocalRunId = useCallback((runId: string) => {\n const existingTimeout = recentlyLocalRunIdsRef.current.get(runId);\n if (existingTimeout) {\n clearTimeout(existingTimeout);\n }\n\n const timeout = setTimeout(() => {\n recentlyLocalRunIdsRef.current.delete(runId);\n }, 30_000);\n recentlyLocalRunIdsRef.current.set(runId, timeout);\n }, []);\n\n const rememberRecentlyWakeRunId = useCallback((runId: string) => {\n const existingTimeout = recentlyWakeRunIdsRef.current.get(runId);\n if (existingTimeout) {\n clearTimeout(existingTimeout);\n }\n\n const timeout = setTimeout(() => {\n recentlyWakeRunIdsRef.current.delete(runId);\n }, 30_000);\n recentlyWakeRunIdsRef.current.set(runId, timeout);\n }, []);\n\n const isLocalActiveRunActivity = useCallback(\n (notification: { agentId?: string; runId?: string; eventType: string }) => {\n if (notification.agentId && notification.agentId !== resolvedAgentId) {\n return false;\n }\n if (\n !notification.runId ||\n (!activeLocalRunIdsRef.current.has(notification.runId) &&\n !observedLocalRunIdsRef.current.has(notification.runId) &&\n !recentlyLocalRunIdsRef.current.has(notification.runId))\n ) {\n return false;\n }\n\n const eventType = notification.eventType.toUpperCase();\n return (\n eventType === \"RUN_STARTED\" ||\n eventType === \"RUN_FINISHED\" ||\n eventType === \"RUN_ERROR\"\n );\n },\n [resolvedAgentId],\n );\n\n useEffect(() => {\n const recentlyLocalRunIds = recentlyLocalRunIdsRef.current;\n const recentlyWakeRunIds = recentlyWakeRunIdsRef.current;\n return () => {\n recentlyLocalRunIds.forEach((timeout) => {\n clearTimeout(timeout);\n });\n recentlyLocalRunIds.clear();\n recentlyWakeRunIds.forEach((timeout) => {\n clearTimeout(timeout);\n });\n recentlyWakeRunIds.clear();\n };\n }, []);\n\n useEffect(() => {\n // Pins the thread on the agent and connects a thread the caller picked.\n // A switch to a fresh thread (startNewThread, the drawer's \"+ New\")\n // empties the agent so the welcome screen shows; moving in or out of an\n // Inspector override stops the run. Release aborts a connect still\n // loading, which keeps StrictMode's remount from sending a second\n // /connect.\n const handle = connection.open(\n {\n agent,\n threadId: resolvedThreadId,\n explicit: hasExplicitThreadId,\n inspectorRequestId,\n },\n {\n onStart: () => {\n activeConnectCountRef.current += 1;\n },\n onSettled: (current) => {\n activeConnectCountRef.current = Math.max(\n 0,\n activeConnectCountRef.current - 1,\n );\n if (!current || activeConnectCountRef.current !== 0) return;\n const startReconnect = startRunActivityReconnectRef.current;\n if (pendingRunActivityReconnectRef.current && startReconnect) {\n pendingRunActivityReconnectRef.current = false;\n startReconnect(runActivityReconnectGenerationRef.current);\n }\n },\n },\n );\n return () => handle.release();\n }, [\n connection,\n resolvedThreadId,\n agent,\n resolvedAgentId,\n hasExplicitThreadId,\n inspectorRequestId,\n ]);\n\n useEffect(() => {\n if (!hasNativeIntelligenceRunActivity) return;\n\n const registeredThreadStore = copilotkit.getThreadStore(resolvedAgentId);\n const threadStore = registeredThreadStore ?? standaloneRunActivityStore;\n if (!threadStore?.subscribeToRunActivity) return;\n const ownsStandaloneStore = registeredThreadStore === undefined;\n if (ownsStandaloneStore) {\n threadStore.start();\n const context: ɵThreadRuntimeContext | null = copilotkit.runtimeUrl\n ? {\n runtimeUrl: copilotkit.runtimeUrl,\n wsUrl: copilotkit.intelligence?.wsUrl,\n agentId: resolvedAgentId,\n }\n : null;\n threadStore.setContext(context);\n }\n\n const generation = runActivityReconnectGenerationRef.current + 1;\n runActivityReconnectGenerationRef.current = generation;\n let detached = false;\n let wakeReconnectActive = false;\n let pendingAgentIdleDrain: ReturnType<typeof setTimeout> | null = null;\n const hasActiveAgentRun = () =>\n activeLocalRunIdsRef.current.size > 0 || agent.isRunning;\n const scheduleAgentIdleDrain = () => {\n if (pendingAgentIdleDrain !== null) return;\n pendingAgentIdleDrain = setTimeout(() => {\n pendingAgentIdleDrain = null;\n if (\n detached ||\n runActivityReconnectGenerationRef.current !== generation ||\n !pendingRunActivityReconnectRef.current\n ) {\n return;\n }\n if (hasActiveAgentRun()) {\n scheduleAgentIdleDrain();\n return;\n }\n startRunActivityReconnectRef.current?.(generation);\n }, 10);\n };\n\n const connect = async () => {\n activeConnectCountRef.current += 1;\n wakeReconnectActive = true;\n const wakeRunId = pendingWakeRunIdRef.current;\n pendingWakeRunIdRef.current = undefined;\n if (wakeRunId) {\n activeWakeRunIdsRef.current.add(wakeRunId);\n }\n let didConnect = false;\n try {\n await copilotkit.connectAgent({ agent });\n didConnect = true;\n } catch (error) {\n if (!detached) throw error;\n } finally {\n if (wakeRunId) {\n activeWakeRunIdsRef.current.delete(wakeRunId);\n if (didConnect) {\n rememberRecentlyWakeRunId(wakeRunId);\n }\n }\n activeConnectCountRef.current = Math.max(\n 0,\n activeConnectCountRef.current - 1,\n );\n wakeReconnectActive = false;\n const canDrainPendingReconnect =\n !detached &&\n runActivityReconnectGenerationRef.current === generation &&\n activeConnectCountRef.current === 0;\n\n if (\n canDrainPendingReconnect &&\n pendingRunActivityReconnectRef.current\n ) {\n pendingRunActivityReconnectRef.current = false;\n trackConnection(connect);\n }\n }\n };\n\n startRunActivityReconnectRef.current = (requestedGeneration) => {\n if (\n detached ||\n requestedGeneration !== generation ||\n runActivityReconnectGenerationRef.current !== generation\n ) {\n return;\n }\n if (hasActiveAgentRun()) {\n pendingRunActivityReconnectRef.current = true;\n scheduleAgentIdleDrain();\n return;\n }\n if (activeConnectCountRef.current > 0) {\n if (!wakeReconnectActive) {\n pendingRunActivityReconnectRef.current = true;\n }\n return;\n }\n pendingRunActivityReconnectRef.current = false;\n trackConnection(connect);\n };\n\n const subscription = threadStore.subscribeToRunActivity((notification) => {\n if (notification.threadId !== resolvedThreadId) return;\n if (notification.agentId && notification.agentId !== resolvedAgentId) {\n return;\n }\n if (isLocalActiveRunActivity(notification)) return;\n if (\n notification.runId &&\n (activeWakeRunIdsRef.current.has(notification.runId) ||\n recentlyWakeRunIdsRef.current.has(notification.runId))\n ) {\n return;\n }\n pendingWakeRunIdRef.current = notification.runId;\n startRunActivityReconnectRef.current?.(generation);\n });\n\n const observedLocalRunIds = observedLocalRunIdsRef.current;\n const localRunSubscription = agent.subscribe({\n onRunInitialized: ({ input }) => {\n observedLocalRunIds.add(input.runId);\n },\n onRunFinalized: ({ input }) => {\n observedLocalRunIds.delete(input.runId);\n rememberRecentlyLocalRunId(input.runId);\n },\n });\n\n return () => {\n detached = true;\n pendingRunActivityReconnectRef.current = false;\n pendingWakeRunIdRef.current = undefined;\n if (pendingAgentIdleDrain !== null) {\n clearTimeout(pendingAgentIdleDrain);\n pendingAgentIdleDrain = null;\n }\n if (startRunActivityReconnectRef.current) {\n startRunActivityReconnectRef.current = null;\n }\n if (wakeReconnectActive) {\n agent.detachActiveRun().catch(() => {});\n }\n activeWakeRunIdsRef.current.clear();\n subscription.unsubscribe();\n localRunSubscription.unsubscribe();\n if (ownsStandaloneStore) {\n threadStore.setContext(null);\n threadStore.stop();\n }\n };\n // copilotkit is intentionally excluded — it is a stable ref that never changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n agent,\n resolvedAgentId,\n resolvedThreadId,\n hasExplicitThreadId,\n hasNativeIntelligenceRunActivity,\n copilotkit.runtimeConnectionStatus,\n copilotkit.runtimeUrl,\n copilotkit.ɵheadersGeneration,\n copilotkit.intelligence?.wsUrl,\n copilotkit.threadEndpoints?.realtimeMetadata,\n standaloneRunActivityStore,\n isLocalActiveRunActivity,\n rememberRecentlyLocalRunId,\n rememberRecentlyWakeRunId,\n trackConnection,\n ]);\n\n // Each send gets a fresh Intelligence run id, so the run-activity stream can\n // tell this client's own runs from runs started elsewhere.\n const prepareRun = (): ɵChatRunScope => {\n const localRunId = hasNativeIntelligenceRunActivity\n ? randomUUID()\n : undefined;\n if (localRunId) activeLocalRunIdsRef.current.add(localRunId);\n return {\n runId: localRunId,\n settle: () => {\n if (localRunId) {\n activeLocalRunIdsRef.current.delete(localRunId);\n rememberRecentlyLocalRunId(localRunId);\n }\n const startReconnect = startRunActivityReconnectRef.current;\n const canReconnect =\n pendingRunActivityReconnectRef.current &&\n activeLocalRunIdsRef.current.size === 0 &&\n activeConnectCountRef.current === 0 &&\n startReconnect !== null;\n if (canReconnect) {\n pendingRunActivityReconnectRef.current = false;\n startReconnect(runActivityReconnectGenerationRef.current);\n }\n },\n };\n };\n const prepareRunRef = useRef(prepareRun);\n prepareRunRef.current = prepareRun;\n const agentRef = useRef(agent);\n agentRef.current = agent;\n\n // The send side — queueing behind the run in flight and the thread's\n // connection, the upload guard, stop, and transcription — lives in core.\n const [submitter] = useState(() =>\n ɵcreateChatSubmitter({\n core: copilotkit,\n getAgent: () => agentRef.current,\n input: {\n get: () => inputValueRef.current,\n set: (value) => {\n inputValueRef.current = value;\n setInputValue(value);\n },\n },\n attachments: {\n isUploading: () =>\n selectedAttachmentsRef.current.some((a) => a.status === \"uploading\"),\n consumeReady: consumeAttachments,\n },\n threads,\n prepareRun: () => prepareRunRef.current(),\n }),\n );\n const { notice, isTranscribing } = useSyncExternalStore(\n useCallback((onChange) => submitter.subscribe(onChange), [submitter]),\n () => submitter.getSnapshot(),\n () => submitter.getSnapshot(),\n );\n // Clears the notice timer on unmount. Not `dispose()`: StrictMode remounts\n // the same component instance, which keeps its submitter.\n useEffect(() => () => submitter.showNotice(null), [submitter]);\n\n // The view and DOM props expect void callbacks, so these handlers keep\n // the submitter's and the attachment handlers' promises fire-and-forget.\n const onSubmitInput = useCallback(\n (value: string) => {\n void submitter.submit(value);\n },\n [submitter],\n );\n\n const handleSelectSuggestion = useCallback(\n (suggestion: Suggestion) => {\n void submitter.selectSuggestion(suggestion);\n },\n [submitter],\n );\n\n const dropFiles = useCallback(\n (e: React.DragEvent) => {\n void handleDrop(e);\n },\n [handleDrop],\n );\n const uploadFiles = useCallback(\n (e: React.ChangeEvent<HTMLInputElement>) => {\n void handleFileUpload(e);\n },\n [handleFileUpload],\n );\n\n const stopCurrentRun = useCallback(() => submitter.stop(), [submitter]);\n\n // Transcription handlers\n const handleStartTranscribe = useCallback(() => {\n submitter.showNotice(null);\n setTranscribeMode(\"transcribe\");\n }, [submitter]);\n\n const handleCancelTranscribe = useCallback(() => {\n submitter.showNotice(null);\n setTranscribeMode(\"input\");\n }, [submitter]);\n\n const handleFinishTranscribe = useCallback(() => {\n setTranscribeMode(\"input\");\n }, []);\n\n // Transcribe the audio blob from CopilotChatInput into the input\n const handleFinishTranscribeWithAudio = useCallback(\n (audioBlob: Blob) => submitter.transcribe(audioBlob),\n [submitter],\n );\n\n // Stabilize slot object references so inline props (new object reference on\n // every parent render) don't defeat MemoizedSlotWrapper's shallow equality\n // check and cause unnecessary re-renders of the message list on each keystroke.\n const stableMessageView = useShallowStableRef(\n typeof providedMessageView === \"string\"\n ? { className: providedMessageView }\n : providedMessageView,\n );\n const stableSuggestionView = useShallowStableRef(providedSuggestionView);\n\n // Stabilize the `onAddFile` handler. Without useCallback, a new arrow\n // function is created inline on every render, causing CopilotChatView to\n // re-render on every keystroke even when nothing else changed.\n const handleAddFile = useCallback(() => {\n // Delay to let Radix dropdown menu close before triggering file input\n setTimeout(() => {\n fileInputRef.current?.click();\n }, 100);\n }, []);\n\n // Use shallow spread instead of ts-deepmerge. ts-deepmerge deep-clones plain\n // objects even from a single source, which would defeat the reference\n // stability we just established for stableMessageView and other slot values.\n const mergedProps: Partial<CopilotChatViewProps> = {\n isRunning: agent.isRunning,\n // HIDE suggestion pills until the runtime is ready, mirroring the\n // `onSubmitMessage` gate below. Static `available:\"always\"` pills render\n // during the provisional window (before `/info` swaps the real agent in),\n // so a click before `isReady` would commit `suggestion.message` to the\n // doomed provisional agent and run against it — the same empty-assistant\n // loss the typed-message gate prevents. Withholding `onSelectSuggestion`\n // alone leaves the pill VISUALLY ENABLED but inert (a click silently drops\n // the user's intent), so instead we do not surface the pills at all until\n // the real agent is bound: passing an empty list keeps `hasSuggestions`\n // false in the view (the same mechanism that hides pills while connecting /\n // running). Once `isReady` flips true the real suggestions appear and the\n // handler goes live. The `onSelectSuggestion` gate is retained as\n // defense-in-depth for any custom chatView slot that renders its own pills.\n suggestions: isReady ? autoSuggestions : [],\n onSelectSuggestion: isReady ? handleSelectSuggestion : undefined,\n suggestionView: stableSuggestionView,\n ...restProps,\n };\n if (stableMessageView !== undefined)\n mergedProps.messageView = stableMessageView;\n\n const hasMessages = agent.messages.length > 0;\n const shouldAllowStop = agent.isRunning && hasMessages;\n const effectiveStopHandler = shouldAllowStop\n ? (providedStopHandler ?? stopCurrentRun)\n : providedStopHandler;\n\n // Determine if transcription feature should be available\n const showTranscription = isTranscriptionEnabled && isMediaRecorderSupported;\n\n // Determine mode: transcribing takes priority, then transcribe mode, then default to input\n const effectiveMode: CopilotChatInputMode = isTranscribing\n ? \"processing\"\n : transcribeMode;\n\n // Memoize messages array — only create a new reference when content changes.\n // The fingerprint is cheaper than a deep compare: it keeps base64 uploads out\n // of the key, and still changes for streamed text, streamed tool arguments,\n // added parts, and replaced activity content.\n const messagesMemoKey = ɵmessagesFingerprint(agent.messages);\n const messages = useMemo(\n () => [...agent.messages],\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [messagesMemoKey],\n );\n\n // The latest user message and a send counter, for pin-to-send scrolling.\n // Messages the chat starts with (a restored thread) do not count as a send.\n // `update` keeps the same object until the last user message changes, so\n // calling it during render is safe.\n const [lastUserMessageTracker] = useState(() =>\n ɵcreateLastUserMessageTracker(messages),\n );\n const lastUserMessageState: LastUserMessageState =\n lastUserMessageTracker.update(messages);\n\n const finalProps: CopilotChatViewProps = {\n ...mergedProps,\n messages,\n // Input behavior props\n // Gate submission on runtime readiness. While `isReady` is false the\n // `agent` returned by useAgent is a provisional stand-in that `/info` will\n // swap out; a message committed to it (and the composer cleared) is lost\n // on that swap, surfacing as an empty assistant response. Withholding\n // `onSubmitMessage` disables the send control (canSend keys off it) and\n // makes Enter a no-op that preserves the composer text until the real\n // agent is bound.\n onSubmitMessage: isReady ? onSubmitInput : undefined,\n onStop: effectiveStopHandler,\n inputMode: effectiveMode,\n inputValue,\n onInputChange: setInputValue,\n // Only provide transcription handlers if feature is available\n onStartTranscribe: showTranscription ? handleStartTranscribe : undefined,\n onCancelTranscribe: showTranscription ? handleCancelTranscribe : undefined,\n onFinishTranscribe: showTranscription ? handleFinishTranscribe : undefined,\n onFinishTranscribeWithAudio: showTranscription\n ? handleFinishTranscribeWithAudio\n : undefined,\n // Attachment props\n attachments: selectedAttachments,\n onRemoveAttachment: removeAttachment,\n onAddFile: attachmentsEnabled ? handleAddFile : undefined,\n dragOver,\n onDragOver: handleDragOver,\n onDragLeave: handleDragLeave,\n onDrop: dropFiles,\n isConnecting,\n hasExplicitThreadId,\n };\n\n // Always create a provider with merged values\n // This ensures priority: props > existing config > defaults\n const RenderedChatView = renderSlot(chatView, CopilotChatView, finalProps);\n\n return (\n <CopilotChatConfigurationProvider\n agentId={resolvedAgentId}\n threadId={resolvedThreadId}\n hasExplicitThreadId={hasExplicitThreadId}\n labels={labels}\n isModalDefaultOpen={isModalDefaultOpen}\n >\n <div ref={chatContainerRef} style={{ display: \"contents\" }}>\n <CopilotKitStyles />\n {attachmentsEnabled && (\n <input\n type=\"file\"\n multiple\n ref={fileInputRef}\n onChange={uploadFiles}\n accept={attachmentsConfig?.accept ?? \"*/*\"}\n style={{ display: \"none\" }}\n />\n )}\n {!isChatLicensed && <InlineFeatureWarning featureName=\"Chat\" />}\n {notice && (\n <div\n style={{\n position: \"absolute\",\n bottom: \"100px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n backgroundColor: \"#ef4444\",\n color: \"white\",\n padding: \"8px 16px\",\n borderRadius: \"8px\",\n fontSize: \"14px\",\n zIndex: 50,\n }}\n >\n {ɵresolveChatNotice(notice, {\n ...CopilotChatDefaultLabels,\n ...existingConfig?.labels,\n ...labels,\n })}\n </div>\n )}\n <LastUserMessageContext.Provider value={lastUserMessageState}>\n <CopilotKitInspectorContextProvider value={inspectorContextValue}>\n <GenerativeUIChatSlotContext.Provider value={generativeUISurface}>\n {RenderedChatView}\n </GenerativeUIChatSlotContext.Provider>\n </CopilotKitInspectorContextProvider>\n </LastUserMessageContext.Provider>\n </div>\n </CopilotChatConfigurationProvider>\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace CopilotChat {\n export const View = CopilotChatView;\n}\n","import type { MouseEvent } from \"react\";\nimport React, { useState } from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\n\nimport type { SlotValue } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport { cn } from \"../../lib/utils\";\nimport { CopilotChatDefaultLabels } from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\nconst ICON_CLASS = \"cpk-chat-toggle-button-icon\";\n\n// The button passes ICON_CLASS through `className`; standalone use falls back\n// to it so the icon keeps its size.\nconst DefaultOpenIcon: React.FC<React.SVGProps<SVGSVGElement>> = ({\n className,\n ...props\n}) => (\n <CopilotIcon\n className={className ?? ICON_CLASS}\n strokeWidth={1.75}\n fill=\"currentColor\"\n {...props}\n name=\"MessageCircle\"\n />\n);\n\nconst DefaultCloseIcon: React.FC<React.SVGProps<SVGSVGElement>> = ({\n className,\n ...props\n}) => (\n <CopilotIcon\n className={className ?? ICON_CLASS}\n strokeWidth={1.75}\n {...props}\n name=\"X\"\n />\n);\n\nDefaultOpenIcon.displayName = \"CopilotChatToggleButton.OpenIcon\";\nDefaultCloseIcon.displayName = \"CopilotChatToggleButton.CloseIcon\";\n\nexport interface CopilotChatToggleButtonProps extends Omit<\n React.ButtonHTMLAttributes<HTMLButtonElement>,\n \"children\"\n> {\n /** Optional slot override for the chat (closed) icon. */\n openIcon?: SlotValue<typeof DefaultOpenIcon>;\n /** Optional slot override for the close icon. */\n closeIcon?: SlotValue<typeof DefaultCloseIcon>;\n}\n\nconst ICON_TRANSITION_STYLE: React.CSSProperties = Object.freeze({\n transition:\n \"opacity 120ms ease-out, transform 260ms cubic-bezier(0.22, 1, 0.36, 1)\",\n});\n\nconst ICON_WRAPPER_CLASS = \"cpk-chat-toggle-button-icon-wrapper\";\n\nexport const CopilotChatToggleButton = React.forwardRef<\n HTMLButtonElement,\n CopilotChatToggleButtonProps\n>(function CopilotChatToggleButton(\n { openIcon, closeIcon, className, ...buttonProps },\n ref,\n) {\n const { onClick, type, disabled, ...restProps } = buttonProps;\n\n const configuration = useCopilotChatConfiguration();\n const labels = configuration?.labels ?? CopilotChatDefaultLabels;\n\n const [fallbackOpen, setFallbackOpen] = useState(false);\n\n const isOpen = configuration?.isModalOpen ?? fallbackOpen;\n const setModalOpen = configuration?.setModalOpen ?? setFallbackOpen;\n\n const handleClick = (event: MouseEvent<HTMLButtonElement>) => {\n if (disabled) {\n return;\n }\n\n if (onClick) {\n onClick(event);\n }\n\n if (event.defaultPrevented) {\n return;\n }\n\n const nextOpen = !isOpen;\n setModalOpen(nextOpen);\n };\n\n const renderedOpenIcon = renderSlot(openIcon, DefaultOpenIcon, {\n className: ICON_CLASS,\n \"aria-hidden\": true,\n focusable: false,\n });\n\n const renderedCloseIcon = renderSlot(closeIcon, DefaultCloseIcon, {\n className: ICON_CLASS,\n \"aria-hidden\": true,\n focusable: false,\n });\n\n const openIconElement = (\n <span\n aria-hidden=\"true\"\n data-slot=\"chat-toggle-button-open-icon\"\n className={ICON_WRAPPER_CLASS}\n style={{\n ...ICON_TRANSITION_STYLE,\n opacity: isOpen ? 0 : 1,\n transform: `scale(${isOpen ? 0.75 : 1}) rotate(${isOpen ? 90 : 0}deg)`,\n }}\n >\n {renderedOpenIcon}\n </span>\n );\n\n const closeIconElement = (\n <span\n aria-hidden=\"true\"\n data-slot=\"chat-toggle-button-close-icon\"\n className={ICON_WRAPPER_CLASS}\n style={{\n ...ICON_TRANSITION_STYLE,\n opacity: isOpen ? 1 : 0,\n transform: `scale(${isOpen ? 1 : 0.75}) rotate(${isOpen ? 0 : -90}deg)`,\n }}\n >\n {renderedCloseIcon}\n </span>\n );\n\n return (\n <button\n ref={ref}\n type={type ?? \"button\"}\n data-copilotkit\n data-testid=\"copilot-chat-toggle\"\n data-slot=\"chat-toggle-button\"\n data-state={isOpen ? \"open\" : \"closed\"}\n className={cn(\"copilotKitButton cpk-chat-toggle-button\", className)}\n aria-label={\n isOpen ? labels.chatToggleCloseLabel : labels.chatToggleOpenLabel\n }\n aria-pressed={isOpen}\n disabled={disabled}\n onClick={handleClick}\n {...restProps}\n >\n {openIconElement}\n {closeIconElement}\n </button>\n );\n});\nCopilotChatToggleButton.displayName = \"CopilotChatToggleButton\";\nexport default CopilotChatToggleButton;\n\nexport {\n DefaultOpenIcon as CopilotChatToggleButtonOpenIcon,\n DefaultCloseIcon as CopilotChatToggleButtonCloseIcon,\n};\n","import React, { createContext, useContext, useMemo } from \"react\";\n\n/**\n * The host-supplied controlled open state for a prebuilt modal surface\n * (`<CopilotSidebar>`, `<CopilotPopup>`).\n */\nexport interface ModalOpenControl {\n /** Controlled open state. `undefined` leaves the surface uncontrolled. */\n open?: boolean;\n /** Called with the requested state when the surface asks to open or close. */\n onOpenChange?: (open: boolean) => void;\n}\n\nconst ModalOpenControlContext = createContext<ModalOpenControl>({});\n\nexport interface ModalOpenControlProviderProps extends ModalOpenControl {\n children: React.ReactNode;\n}\n\n/**\n * Carries `open` / `onOpenChange` from a prebuilt surface down to the view that\n * owns the modal state.\n *\n * A context is required rather than plain props because `<CopilotSidebar>`\n * hands its view to `<CopilotChat>` as a `chatView` **component**. Threading a\n * value that changes (like `open`) through that component's identity would mint\n * a new element type on every toggle, and React unmounts and remounts the whole\n * chat subtree when the element type changes. That is the remount class of bug\n * already fixed for `<CopilotPopup>` on resize. Context keeps the override\n * identity stable while still re-rendering the view when `open` changes.\n */\nexport function ModalOpenControlProvider({\n open,\n onOpenChange,\n children,\n}: ModalOpenControlProviderProps) {\n const value = useMemo<ModalOpenControl>(\n () => ({ open, onOpenChange }),\n [open, onOpenChange],\n );\n\n return (\n <ModalOpenControlContext.Provider value={value}>\n {children}\n </ModalOpenControlContext.Provider>\n );\n}\n\n/**\n * Reads the controlled open state supplied by the surrounding prebuilt\n * surface. Returns an empty control (uncontrolled) when there is none.\n *\n * @returns The host's `open` / `onOpenChange` pair.\n */\nexport function useModalOpenControl(): ModalOpenControl {\n return useContext(ModalOpenControlContext);\n}\n","import React, { useCallback, useEffect, useState } from \"react\";\n\nimport { cn } from \"../../lib/utils\";\nimport {\n CopilotChatDefaultLabels,\n ɵwatchMobileViewport,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport type { WithSlots } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\n\ntype HeaderSlots = {\n titleContent: typeof CopilotModalHeader.Title;\n closeButton: typeof CopilotModalHeader.CloseButton;\n drawerLauncher: typeof CopilotModalHeader.DrawerLauncher;\n};\n\ntype HeaderRestProps = {\n title?: string;\n} & Omit<React.HTMLAttributes<HTMLDivElement>, \"children\">;\n\n/**\n * Payload handed to the optional `children` render function. `drawerLauncher`\n * is nullable because the launcher is rendered only when a drawer has\n * registered — when none is present, custom layouts receive `null` and can omit\n * the launcher slot entirely.\n */\ntype HeaderChildrenPayload = {\n titleContent: React.ReactElement;\n closeButton: React.ReactElement;\n drawerLauncher: React.ReactElement | null;\n title?: string;\n} & Omit<HeaderRestProps, \"title\">;\n\nexport type CopilotModalHeaderProps = Omit<\n WithSlots<HeaderSlots, HeaderRestProps>,\n \"children\"\n> & {\n children?: (props: HeaderChildrenPayload) => React.ReactNode;\n};\n\n/**\n * Reactively tracks whether the viewport is in the mobile range (≤767px) — the\n * same breakpoint the drawer + chat coordination use. SSR-safe: starts `false`\n * (desktop) so the server render and first client render agree, then syncs on\n * mount and on resize.\n */\nfunction useIsMobileViewport() {\n const [isMobile, setIsMobile] = useState(false);\n useEffect(() => ɵwatchMobileViewport(setIsMobile), []);\n return isMobile;\n}\n\nexport function CopilotModalHeader({\n title,\n titleContent,\n closeButton,\n drawerLauncher,\n children,\n className,\n ...rest\n}: CopilotModalHeaderProps) {\n const configuration = useCopilotChatConfiguration();\n\n const fallbackTitle =\n configuration?.labels.modalHeaderTitle ??\n CopilotChatDefaultLabels.modalHeaderTitle;\n const resolvedTitle = title ?? fallbackTitle;\n\n // The thread-list launcher renders ONLY when a <CopilotThreadsDrawer> wrapper has\n // registered with the chat configuration AND the viewport is mobile. On\n // desktop the drawer is an in-flow, persistent panel (it ignores `open`), so\n // an \"open the drawer\" launcher there is a dead no-op — it only does anything\n // for the mobile off-canvas drawer. Chats with no drawer get no launcher and\n // no behavior change.\n const isMobile = useIsMobileViewport();\n const drawerRegistered =\n (configuration?.drawerRegistered ?? false) && isMobile;\n\n const handleClose = useCallback(() => {\n configuration?.setModalOpen?.(false);\n }, [configuration]);\n\n const handleToggleDrawer = useCallback(() => {\n configuration?.setDrawerOpen?.(!configuration.drawerOpen);\n }, [configuration]);\n\n const BoundTitle = renderSlot(titleContent, CopilotModalHeader.Title, {\n children: resolvedTitle,\n });\n\n const BoundCloseButton = renderSlot(\n closeButton,\n CopilotModalHeader.CloseButton,\n {\n onClick: handleClose,\n },\n );\n\n // Only bind the launcher slot when a drawer is registered. When no drawer is\n // present, `BoundDrawerLauncher` is null and nothing is rendered.\n const BoundDrawerLauncher = drawerRegistered\n ? renderSlot(drawerLauncher, CopilotModalHeader.DrawerLauncher, {\n onClick: handleToggleDrawer,\n \"aria-expanded\": configuration?.drawerOpen ?? false,\n })\n : null;\n\n if (children) {\n return children({\n titleContent: BoundTitle,\n closeButton: BoundCloseButton,\n drawerLauncher: BoundDrawerLauncher,\n title: resolvedTitle,\n ...rest,\n });\n }\n\n return (\n <header\n data-testid=\"copilot-modal-header\"\n data-slot=\"copilot-modal-header\"\n className={cn(\"copilotKitHeader cpk-modal-header\", className)}\n {...rest}\n >\n <div className=\"cpk-modal-header-content\">\n <div className=\"cpk-modal-header-start\">\n {BoundDrawerLauncher ?? <span aria-hidden=\"true\" />}\n </div>\n <div className=\"cpk-modal-header-center\">{BoundTitle}</div>\n <div className=\"cpk-modal-header-end\">{BoundCloseButton}</div>\n </div>\n </header>\n );\n}\n\nCopilotModalHeader.displayName = \"CopilotModalHeader\";\n\nexport namespace CopilotModalHeader {\n export const Title: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({\n children,\n className,\n ...props\n }) => (\n <div\n data-testid=\"copilot-header-title\"\n className={cn(\"cpk-modal-header-title\", className)}\n {...props}\n >\n {children}\n </div>\n );\n\n /**\n * Closes the popup or sidebar. Its accessible name is\n * `labels.modalHeaderCloseButtonLabel`.\n */\n export const CloseButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ className, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <button\n type=\"button\"\n data-testid=\"copilot-close-button\"\n className={cn(\"cpk-modal-header-close-button\", className)}\n aria-label={labels.modalHeaderCloseButtonLabel}\n {...props}\n >\n <CopilotIcon\n name=\"X\"\n className=\"cpk-modal-header-close-icon\"\n aria-hidden=\"true\"\n />\n </button>\n );\n };\n\n /**\n * The thread-list launcher button. Rendered in the header ONLY when a\n * `<CopilotThreadsDrawer>` wrapper has registered with the chat configuration; it\n * toggles the drawer open state. The stable `data-testid` is the focus-return\n * target for the drawer wrapper on cancel/back/backdrop/Escape.\n */\n export const DrawerLauncher: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ className, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <button\n type=\"button\"\n data-testid=\"copilot-threads-drawer-launcher\"\n className={cn(\"cpk-modal-header-drawer-launcher\", className)}\n aria-label={labels.modalHeaderThreadsButtonLabel}\n {...props}\n >\n <CopilotIcon\n name=\"PanelLeftOpen\"\n className=\"cpk-modal-header-drawer-launcher-icon\"\n aria-hidden=\"true\"\n />\n </button>\n );\n };\n}\n\nCopilotModalHeader.Title.displayName = \"CopilotModalHeader.Title\";\nCopilotModalHeader.CloseButton.displayName = \"CopilotModalHeader.CloseButton\";\nCopilotModalHeader.DrawerLauncher.displayName =\n \"CopilotModalHeader.DrawerLauncher\";\n\nexport default CopilotModalHeader;\n","import React, { useEffect, useLayoutEffect, useRef, useState } from \"react\";\n\nimport type {\n CopilotChatViewProps,\n WelcomeScreenProps,\n} from \"./CopilotChatView\";\nimport CopilotChatView from \"./CopilotChatView\";\nimport {\n CopilotChatDefaultLabels,\n ɵSIDEBAR_DEFAULT_WIDTH,\n ɵSIDEBAR_TRANSITION_MS,\n ɵcreateDockedSidebar,\n ɵdimensionToCss,\n ɵwatchElementWidth,\n} from \"@copilotkit/core\";\nimport type { ɵDockedSidebar } from \"@copilotkit/core\";\nimport {\n ControlledModalOpenScope,\n CopilotChatConfigurationProvider,\n useCopilotChatConfiguration,\n} from \"../../providers/CopilotChatConfigurationProvider\";\nimport { useModalOpenControl } from \"./modal-open-control\";\nimport CopilotChatToggleButton from \"./CopilotChatToggleButton\";\nimport { cn } from \"../../lib/utils\";\nimport { CopilotModalHeader } from \"./CopilotModalHeader\";\nimport type { CopilotModalHeaderProps } from \"./CopilotModalHeader\";\nimport type { SlotValue } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\n\nexport type CopilotSidebarViewProps = CopilotChatViewProps & {\n /** Accepts a className, partial props, or any component with CopilotModalHeader props — static namespace members are not required. */\n header?: SlotValue<React.ComponentType<CopilotModalHeaderProps>>;\n toggleButton?: SlotValue<typeof CopilotChatToggleButton>;\n width?: number | string;\n defaultOpen?: boolean;\n position?: \"left\" | \"right\";\n};\n\n/**\n * The chat in a side panel: a `complementary` region named by\n * `labels.sidebarLabel`, with a header, the chat view and a toggle button.\n */\nexport function CopilotSidebarView({\n header,\n toggleButton,\n width,\n defaultOpen = true,\n position = \"right\",\n ...props\n}: CopilotSidebarViewProps) {\n // Controlled open state supplied by `<CopilotSidebar open onOpenChange>`.\n const { open, onOpenChange } = useModalOpenControl();\n // The scope is needed for either half: `open` pins the state, and\n // `onOpenChange` reports requests even while the sidebar manages itself.\n const hasOpenControl = open !== undefined || onOpenChange !== undefined;\n\n const internal = (\n <CopilotSidebarViewInternal\n header={header}\n toggleButton={toggleButton}\n width={width}\n position={position}\n {...props}\n />\n );\n\n return (\n // Seed the underlying uncontrolled state from `open` so it starts aligned\n // with the host. The scope below is what the surface actually renders, so\n // this only matters if the host later drops `open` and hands control back:\n // the sidebar then stays where it was instead of jumping to `defaultOpen`.\n <CopilotChatConfigurationProvider isModalDefaultOpen={open ?? defaultOpen}>\n {hasOpenControl ? (\n <ControlledModalOpenScope open={open} onOpenChange={onOpenChange}>\n {internal}\n </ControlledModalOpenScope>\n ) : (\n internal\n )}\n </CopilotChatConfigurationProvider>\n );\n}\n\nfunction CopilotSidebarViewInternal({\n header,\n toggleButton,\n width,\n position = \"right\",\n ...props\n}: Omit<CopilotSidebarViewProps, \"defaultOpen\">) {\n const configuration = useCopilotChatConfiguration();\n\n const isSidebarOpen = configuration?.isModalOpen ?? false;\n\n const sidebarRef = useRef<HTMLDivElement | null>(null);\n const [measuredWidth, setMeasuredWidth] = useState<number | string>(\n width ?? ɵSIDEBAR_DEFAULT_WIDTH,\n );\n // The `width` prop wins over the measured width, also when it changes\n // after mount.\n const sidebarWidth = width ?? measuredWidth;\n\n useEffect(() => {\n // If width is explicitly provided, don't measure\n if (width !== undefined) {\n return;\n }\n const element = sidebarRef.current;\n if (!element) {\n return;\n }\n return ɵwatchElementWidth(element, setMeasuredWidth);\n }, [width]);\n\n const widthCss = ɵdimensionToCss(sidebarWidth, ɵSIDEBAR_DEFAULT_WIDTH);\n\n // The page makes room on the docked edge (desktop only). Layout effects run\n // before paint, so defaultOpen={true} never shows a layout shift: the\n // margin is already there on the first frame.\n const dockRef = useRef<ɵDockedSidebar | null>(null);\n useLayoutEffect(() => {\n const dock = ɵcreateDockedSidebar(document, {\n transitionMs: ɵSIDEBAR_TRANSITION_MS,\n });\n dockRef.current = dock;\n return () => {\n dock.dispose();\n dockRef.current = null;\n };\n }, []);\n\n useLayoutEffect(() => {\n dockRef.current?.set({\n open: isSidebarOpen,\n position,\n width: widthCss,\n });\n }, [isSidebarOpen, position, widthCss]);\n\n const headerElement = renderSlot(header, CopilotModalHeader, {});\n const toggleButtonElement = renderSlot(\n toggleButton,\n CopilotChatToggleButton,\n position === \"left\"\n ? { className: \"cpk-sidebar-view-toggle-button-left\" }\n : {},\n );\n\n return (\n <>\n {toggleButtonElement}\n <aside\n ref={sidebarRef}\n data-copilotkit\n data-testid=\"copilot-sidebar\"\n data-copilot-sidebar\n data-position={position}\n className={cn(\n \"copilotKitSidebar copilotKitWindow cpk-sidebar-view\",\n // Slides off its edge (data-position) when closed.\n !isSidebarOpen && \"cpk-sidebar-view-closed\",\n )}\n style={\n {\n // Use CSS custom property for responsive width\n \"--sidebar-width\": widthCss,\n // Safe area insets for iOS\n paddingTop: \"env(safe-area-inset-top)\",\n paddingBottom: \"env(safe-area-inset-bottom)\",\n } as React.CSSProperties\n }\n aria-hidden={!isSidebarOpen}\n aria-label={\n configuration?.labels.sidebarLabel ??\n CopilotChatDefaultLabels.sidebarLabel\n }\n role=\"complementary\"\n >\n <div className=\"cpk-sidebar-view-panel\">\n {headerElement}\n <div className=\"cpk-sidebar-view-chat\" data-sidebar-chat>\n <CopilotChatView {...props} />\n </div>\n </div>\n </aside>\n </>\n );\n}\n\nCopilotSidebarView.displayName = \"CopilotSidebarView\";\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace CopilotSidebarView {\n /**\n * Sidebar-specific welcome screen layout:\n * - Suggestions at the top\n * - Welcome message in the middle\n * - Input fixed at the bottom (like normal chat)\n */\n export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({\n welcomeMessage,\n input,\n suggestionView,\n className,\n children,\n ...props\n }) => {\n // Render the welcomeMessage slot internally\n const BoundWelcomeMessage = renderSlot(\n welcomeMessage,\n CopilotChatView.WelcomeMessage,\n {},\n );\n\n if (children) {\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children({\n welcomeMessage: BoundWelcomeMessage,\n input,\n suggestionView,\n className,\n ...props,\n })}\n </div>\n );\n }\n\n return (\n <div\n className={cn(\"cpk-sidebar-view-welcome-screen\", className)}\n {...props}\n >\n {/* Welcome message - centered vertically */}\n <div className=\"cpk-sidebar-view-welcome-screen-message\">\n {BoundWelcomeMessage}\n </div>\n\n {/* Suggestions and input at bottom */}\n <div className=\"cpk-sidebar-view-welcome-screen-footer\">\n <div className=\"cpk-sidebar-view-welcome-screen-content\">\n {/* Suggestions above input */}\n <div className=\"cpk-sidebar-view-welcome-screen-suggestions\">\n {suggestionView}\n </div>\n {input}\n </div>\n </div>\n </div>\n );\n };\n}\n\nexport default CopilotSidebarView;\n","import React, {\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport type {\n CopilotChatViewProps,\n WelcomeScreenProps,\n} from \"./CopilotChatView\";\nimport CopilotChatView from \"./CopilotChatView\";\nimport CopilotChatToggleButton from \"./CopilotChatToggleButton\";\nimport { CopilotModalHeader } from \"./CopilotModalHeader\";\nimport type { CopilotModalHeaderProps } from \"./CopilotModalHeader\";\nimport { cn } from \"../../lib/utils\";\nimport type { SlotValue } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport {\n CopilotChatDefaultLabels,\n ɵPOPUP_DEFAULT_HEIGHT,\n ɵPOPUP_DEFAULT_WIDTH,\n ɵbindPopupDismiss,\n ɵcreateExitPresence,\n ɵdimensionToCss,\n} from \"@copilotkit/core\";\nimport {\n ControlledModalOpenScope,\n CopilotChatConfigurationProvider,\n useCopilotChatConfiguration,\n} from \"../../providers/CopilotChatConfigurationProvider\";\nimport { useModalOpenControl } from \"./modal-open-control\";\n\nexport type CopilotPopupViewProps = CopilotChatViewProps & {\n /** Accepts a className, partial props, or any component with CopilotModalHeader props — static namespace members are not required. */\n header?: SlotValue<React.ComponentType<CopilotModalHeaderProps>>;\n toggleButton?: SlotValue<typeof CopilotChatToggleButton>;\n width?: number | string;\n height?: number | string;\n clickOutsideToClose?: boolean;\n defaultOpen?: boolean;\n};\n\nexport function CopilotPopupView({\n header,\n toggleButton,\n width,\n height,\n clickOutsideToClose,\n defaultOpen = true,\n className,\n ...restProps\n}: CopilotPopupViewProps) {\n // Controlled open state supplied by `<CopilotPopup open onOpenChange>`.\n const { open, onOpenChange } = useModalOpenControl();\n // The scope is needed for either half: `open` pins the state, and\n // `onOpenChange` reports requests even while the popup manages itself.\n const hasOpenControl = open !== undefined || onOpenChange !== undefined;\n\n const internal = (\n <CopilotPopupViewInternal\n header={header}\n toggleButton={toggleButton}\n width={width}\n height={height}\n clickOutsideToClose={clickOutsideToClose}\n className={className}\n {...restProps}\n />\n );\n\n return (\n // Seed the underlying uncontrolled state from `open` so it starts aligned\n // with the host. The scope below is what the surface actually renders, so\n // this only matters if the host later drops `open` and hands control back:\n // the popup then stays where it was instead of jumping to `defaultOpen`.\n <CopilotChatConfigurationProvider isModalDefaultOpen={open ?? defaultOpen}>\n {hasOpenControl ? (\n <ControlledModalOpenScope open={open} onOpenChange={onOpenChange}>\n {internal}\n </ControlledModalOpenScope>\n ) : (\n internal\n )}\n </CopilotChatConfigurationProvider>\n );\n}\n\nfunction CopilotPopupViewInternal({\n header,\n toggleButton,\n width,\n height,\n clickOutsideToClose,\n className,\n ...restProps\n}: Omit<CopilotPopupViewProps, \"defaultOpen\">) {\n const configuration = useCopilotChatConfiguration();\n const isPopupOpen = configuration?.isModalOpen ?? false;\n const setModalOpen = configuration?.setModalOpen;\n const labels = configuration?.labels ?? CopilotChatDefaultLabels;\n\n const containerRef = useRef<HTMLDivElement>(null);\n // Core keeps the closed popup rendered while its exit animation plays.\n const [presence] = useState(() => ɵcreateExitPresence(isPopupOpen));\n const { isRendered, isClosing: isAnimatingOut } = useSyncExternalStore(\n presence.subscribe,\n presence.getState,\n presence.getState,\n );\n useEffect(() => {\n presence.setOpen(isPopupOpen);\n }, [presence, isPopupOpen]);\n useEffect(() => () => presence.dispose(), [presence]);\n\n // Escape, a click outside (when enabled), and focus once the popup opens.\n useEffect(() => {\n if (!isPopupOpen) {\n return;\n }\n return ɵbindPopupDismiss({\n getContainer: () => containerRef.current,\n onDismiss: () => setModalOpen?.(false),\n clickOutsideToClose: clickOutsideToClose === true,\n });\n }, [isPopupOpen, clickOutsideToClose, setModalOpen]);\n\n const headerElement = useMemo(\n () => renderSlot(header, CopilotModalHeader, {}),\n [header],\n );\n const toggleButtonElement = useMemo(\n () => renderSlot(toggleButton, CopilotChatToggleButton, {}),\n [toggleButton],\n );\n\n const resolvedWidth = ɵdimensionToCss(width, ɵPOPUP_DEFAULT_WIDTH);\n const resolvedHeight = ɵdimensionToCss(height, ɵPOPUP_DEFAULT_HEIGHT);\n\n const popupStyle = useMemo(\n () =>\n ({\n \"--copilot-popup-width\": resolvedWidth,\n \"--copilot-popup-height\": resolvedHeight,\n \"--copilot-popup-max-width\": \"calc(100vw - 3rem)\",\n \"--copilot-popup-max-height\": \"calc(100dvh - 7.5rem)\",\n paddingTop: \"env(safe-area-inset-top)\",\n paddingBottom: \"env(safe-area-inset-bottom)\",\n paddingLeft: \"env(safe-area-inset-left)\",\n paddingRight: \"env(safe-area-inset-right)\",\n }) as React.CSSProperties,\n [resolvedHeight, resolvedWidth],\n );\n\n const popupContent = isRendered ? (\n <div data-copilotkit className=\"cpk-popup-view\">\n <div\n ref={containerRef}\n tabIndex={-1}\n role=\"dialog\"\n aria-label={labels.modalHeaderTitle}\n data-testid=\"copilot-popup\"\n data-copilot-popup\n className={cn(\n \"copilotKitPopup copilotKitWindow cpk-popup-view-window\",\n isPopupOpen && !isAnimatingOut && \"cpk-popup-view-window-open\",\n )}\n style={popupStyle}\n >\n {headerElement}\n <div className=\"cpk-popup-view-chat\" data-popup-chat>\n <CopilotChatView\n {...restProps}\n className={cn(\"cpk-popup-view-chat-view\", className)}\n />\n </div>\n </div>\n </div>\n ) : null;\n\n return (\n <>\n {toggleButtonElement}\n {popupContent}\n </>\n );\n}\n\nCopilotPopupView.displayName = \"CopilotPopupView\";\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace CopilotPopupView {\n /**\n * Popup-specific welcome screen layout:\n * - Welcome message centered vertically\n * - Suggestions just above input\n * - Input fixed at the bottom\n */\n export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({\n welcomeMessage,\n input,\n suggestionView,\n className,\n children,\n ...props\n }) => {\n // Render the welcomeMessage slot internally\n const BoundWelcomeMessage = renderSlot(\n welcomeMessage,\n CopilotChatView.WelcomeMessage,\n {},\n );\n\n if (children) {\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children({\n welcomeMessage: BoundWelcomeMessage,\n input,\n suggestionView,\n className,\n ...props,\n })}\n </div>\n );\n }\n\n return (\n <div\n className={cn(\"cpk-popup-view-welcome-screen\", className)}\n {...props}\n >\n {/* Welcome message - centered vertically */}\n <div className=\"cpk-popup-view-welcome-screen-message\">\n {BoundWelcomeMessage}\n </div>\n\n {/* Suggestions and input at bottom */}\n <div>\n {/* Suggestions above input */}\n <div className=\"cpk-popup-view-welcome-screen-suggestions\">\n {suggestionView}\n </div>\n {input}\n </div>\n </div>\n );\n };\n}\n\nexport default CopilotPopupView;\n","import React, { useEffect, useMemo } from \"react\";\nimport { useLicenseContext } from \"../../providers/CopilotKitProvider\";\nimport { InlineFeatureWarning } from \"../license-warning-banner\";\n\nimport type { CopilotChatProps } from \"./CopilotChat\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatViewProps } from \"./CopilotChatView\";\nimport CopilotChatView from \"./CopilotChatView\";\nimport type { CopilotSidebarViewProps } from \"./CopilotSidebarView\";\nimport { CopilotSidebarView } from \"./CopilotSidebarView\";\nimport { ModalOpenControlProvider } from \"./modal-open-control\";\n\nexport type CopilotSidebarProps = Omit<CopilotChatProps, \"chatView\"> & {\n header?: CopilotSidebarViewProps[\"header\"];\n toggleButton?: CopilotSidebarViewProps[\"toggleButton\"];\n defaultOpen?: boolean;\n /**\n * Controlled open state. When supplied, the host owns whether the sidebar is\n * open: the sidebar renders this value and never changes it on its own.\n * Pair it with `onOpenChange` to react to the toggle button. Omit it (and use\n * `defaultOpen`) to let the sidebar manage its own state.\n */\n open?: boolean;\n /**\n * Called with the requested state whenever the sidebar asks to open or close\n * (the toggle button, or the thread drawer on mobile). In controlled mode\n * nothing moves until the host updates `open`.\n */\n onOpenChange?: (open: boolean) => void;\n width?: number | string;\n position?: CopilotSidebarViewProps[\"position\"];\n};\n\nexport function CopilotSidebar({\n header,\n toggleButton,\n defaultOpen,\n open,\n onOpenChange,\n width,\n position,\n ...chatProps\n}: CopilotSidebarProps) {\n const { checkFeature } = useLicenseContext();\n const isSidebarLicensed = checkFeature(\"sidebar\");\n\n useEffect(() => {\n if (!isSidebarLicensed) {\n console.warn(\n '[CopilotKit] Warning: \"sidebar\" feature is not licensed. Visit copilotkit.ai/pricing',\n );\n }\n }, [isSidebarLicensed]);\n\n const SidebarViewOverride = useMemo(() => {\n const Component: React.FC<CopilotChatViewProps> = (viewProps) => {\n const {\n header: viewHeader,\n toggleButton: viewToggleButton,\n width: viewWidth,\n defaultOpen: viewDefaultOpen,\n position: viewPosition,\n ...restProps\n } = viewProps as CopilotSidebarViewProps;\n\n return (\n <CopilotSidebarView\n {...(restProps as CopilotSidebarViewProps)}\n header={header ?? viewHeader}\n toggleButton={toggleButton ?? viewToggleButton}\n width={width ?? viewWidth}\n defaultOpen={defaultOpen ?? viewDefaultOpen}\n position={position ?? viewPosition}\n />\n );\n };\n\n return Object.assign(Component, CopilotChatView);\n }, [header, toggleButton, width, defaultOpen, position]);\n\n return (\n <>\n {!isSidebarLicensed && <InlineFeatureWarning featureName=\"Sidebar\" />}\n {/*\n `open` / `onOpenChange` travel by context, not through\n SidebarViewOverride. The override is memoized on its own props, so a\n changing `open` would mint a new component identity on every toggle and\n remount the whole chat subtree.\n */}\n <ModalOpenControlProvider open={open} onOpenChange={onOpenChange}>\n <CopilotChat\n welcomeScreen={CopilotSidebarView.WelcomeScreen}\n {...chatProps}\n isModalDefaultOpen={defaultOpen}\n chatView={SidebarViewOverride}\n />\n </ModalOpenControlProvider>\n </>\n );\n}\n\nCopilotSidebar.displayName = \"CopilotSidebar\";\n\nexport default CopilotSidebar;\n","import React, { useContext, useEffect, useMemo } from \"react\";\nimport { useLicenseContext } from \"../../providers/CopilotKitProvider\";\nimport { InlineFeatureWarning } from \"../license-warning-banner\";\n\nimport type { CopilotChatProps } from \"./CopilotChat\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatViewProps } from \"./CopilotChatView\";\nimport CopilotChatView from \"./CopilotChatView\";\nimport type { CopilotPopupViewProps } from \"./CopilotPopupView\";\nimport CopilotPopupView from \"./CopilotPopupView\";\nimport { ModalOpenControlProvider } from \"./modal-open-control\";\n\n/**\n * Carries the popup shell props (header, toggle, width, height, …) to the\n * chatView override without baking them into the override's component\n * identity. Width/height change on every resize; if they were `useMemo`\n * dependencies of the override component, each change would mint a new\n * component function, and rendering a new element *type* makes React unmount\n * and remount the entire chat subtree — resetting scrollTop to 0 and firing\n * `initial=\"smooth\"`, which visibly scrolls the message list from top to\n * bottom on every resize. Routing them through context keeps the override\n * identity stable (no remount) while still re-rendering CopilotPopupView with\n * the new dimensions on change.\n */\ntype PopupShellProps = {\n header?: CopilotPopupViewProps[\"header\"];\n toggleButton?: CopilotPopupViewProps[\"toggleButton\"];\n width?: CopilotPopupViewProps[\"width\"];\n height?: CopilotPopupViewProps[\"height\"];\n clickOutsideToClose?: CopilotPopupViewProps[\"clickOutsideToClose\"];\n defaultOpen?: boolean;\n};\n\nconst PopupShellPropsContext = React.createContext<PopupShellProps>({});\n\n// Stable override component. Its identity never changes, so the chat subtree\n// is never remounted on resize. Popup props flow in via context, so changing\n// width/height re-renders CopilotPopupView (a style update) instead.\nconst PopupViewOverride: React.FC<CopilotChatViewProps> = (viewProps) => {\n const {\n header: viewHeader,\n toggleButton: viewToggleButton,\n width: viewWidth,\n height: viewHeight,\n clickOutsideToClose: viewClickOutsideToClose,\n defaultOpen: viewDefaultOpen,\n ...restProps\n } = viewProps as CopilotPopupViewProps;\n\n const shell = useContext(PopupShellPropsContext);\n\n return (\n <CopilotPopupView\n {...(restProps as CopilotPopupViewProps)}\n header={shell.header ?? viewHeader}\n toggleButton={shell.toggleButton ?? viewToggleButton}\n width={shell.width ?? viewWidth}\n height={shell.height ?? viewHeight}\n clickOutsideToClose={shell.clickOutsideToClose ?? viewClickOutsideToClose}\n defaultOpen={shell.defaultOpen ?? viewDefaultOpen}\n />\n );\n};\n\n// Preserve the static slot members (WelcomeScreen, etc.) that callers reach\n// through the CopilotChatView namespace. The cast restores those statics on\n// the type after Object.assign, matching the shape CopilotChat's `chatView`\n// slot expects (typeof CopilotChatView).\nconst PopupViewOverrideWithStatics = Object.assign(\n PopupViewOverride,\n CopilotChatView,\n) as typeof CopilotChatView;\n\nexport type CopilotPopupProps = Omit<CopilotChatProps, \"chatView\"> & {\n header?: CopilotPopupViewProps[\"header\"];\n toggleButton?: CopilotPopupViewProps[\"toggleButton\"];\n defaultOpen?: boolean;\n /**\n * Controlled open state. When supplied, the host owns whether the popup is\n * open: the popup renders this value and never changes it on its own. Pair it\n * with `onOpenChange` to react to the toggle button and to click-outside.\n * Omit it (and use `defaultOpen`) to let the popup manage its own state.\n */\n open?: boolean;\n /**\n * Called with the requested state whenever the popup asks to open or close\n * (the toggle button, click-outside, or the thread drawer on mobile). In\n * controlled mode nothing moves until the host updates `open`.\n */\n onOpenChange?: (open: boolean) => void;\n width?: CopilotPopupViewProps[\"width\"];\n height?: CopilotPopupViewProps[\"height\"];\n clickOutsideToClose?: CopilotPopupViewProps[\"clickOutsideToClose\"];\n};\n\nexport function CopilotPopup({\n header,\n toggleButton,\n defaultOpen,\n open,\n onOpenChange,\n width,\n height,\n clickOutsideToClose,\n ...chatProps\n}: CopilotPopupProps) {\n const { checkFeature } = useLicenseContext();\n const isPopupLicensed = checkFeature(\"popup\");\n\n useEffect(() => {\n if (!isPopupLicensed) {\n console.warn(\n '[CopilotKit] Warning: \"popup\" feature is not licensed. Visit copilotkit.ai/pricing',\n );\n }\n }, [isPopupLicensed]);\n\n const shellProps = useMemo<PopupShellProps>(\n () => ({\n header,\n toggleButton,\n width,\n height,\n clickOutsideToClose,\n defaultOpen,\n }),\n [clickOutsideToClose, header, toggleButton, height, width, defaultOpen],\n );\n\n return (\n <>\n {!isPopupLicensed && <InlineFeatureWarning featureName=\"Popup\" />}\n <PopupShellPropsContext.Provider value={shellProps}>\n <ModalOpenControlProvider open={open} onOpenChange={onOpenChange}>\n <CopilotChat\n welcomeScreen={CopilotPopupView.WelcomeScreen}\n {...chatProps}\n isModalDefaultOpen={defaultOpen}\n chatView={PopupViewOverrideWithStatics}\n />\n </ModalOpenControlProvider>\n </PopupShellPropsContext.Provider>\n </>\n );\n}\n\nCopilotPopup.displayName = \"CopilotPopup\";\n\nexport default CopilotPopup;\n","\"use client\";\n\nimport React, {\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport {\n defineCopilotKitThreadsDrawer,\n COPILOTKIT_THREADS_DRAWER_TAG,\n} from \"@copilotkit/web-components/threads-drawer\";\nimport type {\n CopilotKitThreadsDrawer as CopilotKitThreadsDrawerElement,\n ThreadSelectedDetail,\n ArchiveDetail,\n UnarchiveDetail,\n DeleteDetail,\n OpenChangeDetail,\n RetryDetail,\n} from \"@copilotkit/web-components/threads-drawer\";\n// TODO(ENT-1051): import `CollapseChangeDetail` from\n// \"@copilotkit/web-components/threads-drawer\" once the parallel element PR that\n// adds the collapse feature (property `collapsible` + event `collapse-change`)\n// lands and is published; declared locally here because the built element types\n// in this worktree predate it.\ntype CollapseChangeDetail = { collapsed: boolean };\nimport {\n ɵcreateThreadsDrawerActions,\n ɵgetThreadsDrawerElementProps,\n ɵresolveAgentId,\n ɵresolveThreadsLicense,\n ɵtoDrawerThread,\n} from \"@copilotkit/core\";\nimport { useThreads } from \"../../hooks/use-threads\";\nimport type { Thread } from \"../../hooks/use-threads\";\nimport { useLicenseContext } from \"../../providers/CopilotKitProvider\";\nimport { CopilotKitContext, useDefaultAgentId } from \"../../context\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\n/**\n * Per-row content render function. Receives a thread and returns the React\n * node to project into the element's `slot=\"row:{id}\"`. Returning `null`\n * (or omitting the prop) falls back to the element's built-in row name.\n */\nexport type CopilotThreadsDrawerRowRenderer = (\n thread: Thread,\n) => React.ReactNode;\n\n/**\n * Props for {@link CopilotThreadsDrawer}.\n *\n * The drawer is a thin controller around the framework-agnostic\n * `<copilotkit-threads-drawer>` custom element. It feeds the element domain data\n * (threads/loading/error from {@link useThreads}, the active thread from the\n * chat configuration) and routes the element's outbound DOM events back into\n * core thread operations and chat-configuration changes.\n */\nexport interface CopilotThreadsDrawerProps {\n /**\n * The agent whose threads to list and manage. Defaults to the agent of the\n * surrounding chat configuration, or the platform default when none is set.\n */\n agentId?: string;\n /**\n * Optional escape-hatch called when the user picks a thread row. The wrapper\n * additionally focuses the chat input. When omitted, the wrapper drives the\n * surrounding chat configuration directly (`setActiveThreadId`), so a bare\n * `<CopilotThreadsDrawer>` switches the rendered thread with no host wiring. Provide\n * this only to take control of the active thread yourself (e.g. a v1\n * `setThreadId`); when provided it is preferred over the provider.\n */\n onThreadSelect?: (threadId: string) => void;\n /**\n * Optional escape-hatch called when the user starts a new thread (the\n * element's \"+ New\" button). The wrapper always resets the core thread store\n * to a fresh, non-explicit client-side thread (`startNewThread`). When this\n * is omitted, the wrapper also resets the surrounding chat configuration to a\n * fresh non-explicit thread (`startNewThread`) so the welcome screen shows\n * with no host wiring. Provide this only to clear your own active thread;\n * when provided it is preferred over the provider.\n */\n onNewThread?: () => void;\n /** Called when the Upgrade CTA is clicked. */\n onLicensed?: () => void;\n /**\n * Destination the locked view's Upgrade CTA opens in a new tab. Defaults to\n * the element's built-in CopilotKit Intelligence docs URL when omitted. Set\n * to an empty string to suppress the default navigation and handle the click\n * yourself via `onLicensed`.\n */\n licenseUrl?: string;\n /**\n * Optional per-row content. Rendered as light-DOM children with\n * `slot=\"row:{id}\"` so the element projects them in place of the default\n * row name. Return `null` for a given row to keep the element's default.\n */\n renderRow?: CopilotThreadsDrawerRowRenderer;\n /**\n * Accessible + default-header label for the drawer region. Sets the custom\n * element's `aria-label` and the default header text (shown when no\n * `slot=\"header\"` content is projected). Defaults to the element's built-in\n * `\"Threads\"` when omitted.\n */\n label?: string;\n /**\n * Heading for the \"Recent Conversations\" section above the thread list. Sets\n * the custom element's `recent-label` attribute. Defaults to the element's\n * built-in `\"Recent Conversations\"` when omitted.\n */\n recentLabel?: string;\n /**\n * Whether the drawer offers a collapse toggle. Sets the custom element's\n * `collapsible` PROPERTY. When `false`, the drawer has no collapse toggle and\n * is always expanded. Defaults to the element's built-in `true` when omitted.\n */\n collapsible?: boolean;\n /**\n * Called when the drawer's collapsed state changes (via the element's collapse\n * toggle), with the new collapsed state. Mirrors the element's\n * `collapse-change` event.\n */\n onCollapseChange?: (collapsed: boolean) => void;\n /**\n * Page size for thread pagination. When set, threads are fetched in pages of\n * this size and the drawer shows a \"Load more\" control while more remain.\n * When omitted, the full list loads at once and no pagination control shows.\n */\n limit?: number;\n /**\n * `data-testid` set on the underlying custom element (handy in tests and for\n * targeting from a host page). Defaults to `\"copilot-threads-drawer\"`.\n */\n \"data-testid\"?: string;\n}\n\n/**\n * React wrapper for the shadow-DOM `<copilotkit-threads-drawer>` threads drawer.\n *\n * Responsibilities:\n * - Registers the custom element on the client (SSR-safe; nothing renders\n * during prerender to avoid hydration mismatch).\n * - Feeds the element domain data: `threads`, `loading`, `error`,\n * `activeThreadId`, `licensed`, fetch-more state.\n * - Routes the element's outbound events to core thread operations\n * ({@link useThreads}) and chat-configuration changes.\n * - Registers with the surrounding chat configuration so the header\n * thread-list launcher appears, and binds the element `open` state to the\n * configuration's `drawerOpen`.\n *\n * Intelligence gating is two-pronged: the locked view shows when the runtime\n * reports no active entitlement OR the `threads` feature is unavailable. While\n * unavailable, the thread fetch is skipped entirely so the drawer issues no\n * network requests.\n *\n * Thread switching needs no host wiring: when `onThreadSelect`/`onNewThread`\n * are omitted, the wrapper drives the surrounding chat configuration directly\n * ({@link CopilotChatConfigurationValue.setActiveThreadId} /\n * {@link CopilotChatConfigurationValue.startNewThread}), so a bare drawer\n * connects to the picked thread and shows the welcome screen on \"+ New\". Pass\n * the callbacks only to take control yourself.\n *\n * @example\n * ```tsx\n * // Callback-free: the drawer drives the chat configuration itself.\n * <CopilotKitProvider runtimeUrl=\"/api/copilotkit\">\n * <CopilotChat />\n * <CopilotThreadsDrawer />\n * </CopilotKitProvider>\n * ```\n */\nexport function CopilotThreadsDrawer({\n agentId,\n onThreadSelect,\n onNewThread,\n onLicensed,\n licenseUrl,\n renderRow,\n label,\n recentLabel,\n collapsible,\n onCollapseChange,\n limit,\n \"data-testid\": dataTestId = \"copilot-threads-drawer\",\n}: CopilotThreadsDrawerProps): React.ReactElement | null {\n const configuration = useCopilotChatConfiguration();\n // `unknown` (an entitlement lookup that did not recover) is not a settled\n // negative, so core treats it as licensed and lets the threads endpoint\n // decide; `null` (not reported yet) is pending, never the locked view.\n // A runtime that connects without reporting a license (no Intelligence)\n // ends the pending. `useThreads` below re-renders this component on every\n // connection change, so this read stays current.\n const copilotkit = useContext(CopilotKitContext)?.copilotkit;\n const { licensed, licensePending } = ɵresolveThreadsLicense(\n useLicenseContext(),\n copilotkit?.ɵruntimeInfo,\n );\n\n const providerAgentId = useDefaultAgentId();\n const resolvedAgentId = ɵresolveAgentId({\n agentId,\n chatAgentId: configuration?.agentId,\n providerAgentId,\n });\n const activeThreadId = configuration?.threadId ?? null;\n\n // While unlicensed, skip the thread fetch entirely: the element shows only\n // its locked view and no `/threads` request is issued.\n const {\n threads,\n isLoading,\n listError,\n fetchMoreError,\n hasMoreThreads,\n isFetchingMoreThreads,\n archiveThread,\n unarchiveThread,\n deleteThread,\n fetchMoreThreads,\n refetchThreads,\n startNewThread,\n } = useThreads({\n agentId: resolvedAgentId,\n includeArchived: true,\n enabled: licensed,\n ...(limit !== undefined ? { limit } : {}),\n });\n\n const drawerThreads = useMemo(() => threads.map(ɵtoDrawerThread), [threads]);\n\n const elementRef = useRef<CopilotKitThreadsDrawerElement | null>(null);\n\n // Register the custom element on the client only. `customElements` is absent\n // during SSR/prerender; gating the render below on `mounted` keeps the server\n // output empty so there is no hydration mismatch or layout shift.\n const [mounted, setMounted] = useState(false);\n useEffect(() => {\n defineCopilotKitThreadsDrawer();\n setMounted(true);\n }, []);\n\n // Announce presence to the surrounding chat configuration so the header\n // launcher renders; de-register on unmount. Depend on the stable\n // `registerDrawer` callback, NOT the whole `configuration` object — the\n // object's identity changes on every drawer/modal/label update, which would\n // otherwise churn register/de-register each render and momentarily drop\n // `drawerRegistered` (flickering the header launcher).\n const registerDrawer = configuration?.registerDrawer;\n useEffect(() => {\n if (!registerDrawer) return;\n return registerDrawer();\n }, [registerDrawer]);\n\n // Drive the chat configuration's drawerOpen from the element's open-change\n // event, and reflect drawerOpen back onto the element below.\n //\n // Provider-less fallback: without a surrounding chat configuration there is no\n // shared open-state to bind to, so the wrapper keeps its own local open-state.\n // It starts CLOSED — matching the provider's own `ownDrawerOpen` default of\n // `false` — so a bare `<CopilotThreadsDrawer>` does not render stuck-open and the\n // element's open-change events still toggle it.\n const [localDrawerOpen, setLocalDrawerOpen] = useState(false);\n const drawerOpen = configuration ? configuration.drawerOpen : localDrawerOpen;\n const setDrawerOpen = configuration\n ? configuration.setDrawerOpen\n : setLocalDrawerOpen;\n\n // --- Event handlers (stable via refs to the latest closures) -------------\n // The element is imperatively wired with addEventListener once; we keep the\n // latest handler implementations in a ref so listeners need not be re-bound\n // every render (which would churn on each thread/loading change).\n\n // Prefer the host callbacks when provided; otherwise drive the surrounding\n // chat configuration directly so a bare `<CopilotThreadsDrawer>` works callback-free.\n // Core owns the drawer actions. They read the latest values through refs,\n // so they are created once.\n const latestRef = useRef({\n threads: {\n startNewThread,\n archiveThread,\n unarchiveThread,\n deleteThread,\n fetchMoreThreads,\n refetchThreads,\n },\n configuration,\n callbacks: { onThreadSelect, onNewThread },\n });\n latestRef.current = {\n threads: {\n startNewThread,\n archiveThread,\n unarchiveThread,\n deleteThread,\n fetchMoreThreads,\n refetchThreads,\n },\n configuration,\n callbacks: { onThreadSelect, onNewThread },\n };\n const [actions] = useState(() =>\n ɵcreateThreadsDrawerActions({\n getThreads: () => latestRef.current.threads,\n getConfig: () => latestRef.current.configuration,\n getCallbacks: () => latestRef.current.callbacks,\n getElement: () => elementRef.current,\n }),\n );\n const handleThreadSelected = actions.selectThread;\n const handleNewThread = actions.newThread;\n const handleArchive = actions.archive;\n const handleUnarchive = actions.unarchive;\n const handleDelete = actions.remove;\n const handleFilterChange = actions.refetch;\n const handleRetry = actions.retry;\n\n const handleOpenChange = useCallback(\n (open: boolean) => {\n setDrawerOpen(open);\n },\n [setDrawerOpen],\n );\n\n const handleLicensed = useCallback(() => {\n onLicensed?.();\n }, [onLicensed]);\n\n const handleLoadMore = actions.loadMore;\n\n const handleCollapseChange = useCallback(\n (collapsed: boolean) => {\n onCollapseChange?.(collapsed);\n },\n [onCollapseChange],\n );\n\n // Keep a ref to the live handlers so the addEventListener effect can stay\n // stable (bind once) while still calling the freshest closures.\n const handlersRef = useRef({\n handleThreadSelected,\n handleNewThread,\n handleArchive,\n handleUnarchive,\n handleDelete,\n handleFilterChange,\n handleRetry,\n handleOpenChange,\n handleLicensed,\n handleLoadMore,\n handleCollapseChange,\n });\n handlersRef.current = {\n handleThreadSelected,\n handleNewThread,\n handleArchive,\n handleUnarchive,\n handleDelete,\n handleFilterChange,\n handleRetry,\n handleOpenChange,\n handleLicensed,\n handleLoadMore,\n handleCollapseChange,\n };\n\n // Bind the outbound DOM events once the element exists. Listeners are\n // bound a single time and cleaned up on unmount; they dispatch through the\n // handlers ref so they always invoke the latest closures.\n useEffect(() => {\n const el = elementRef.current;\n if (!el) return;\n\n const onThreadSelected = (event: Event) => {\n const detail = (event as CustomEvent<ThreadSelectedDetail>).detail;\n handlersRef.current.handleThreadSelected(detail.threadId);\n };\n const onNewThreadEvent = () => handlersRef.current.handleNewThread();\n const onArchive = (event: Event) => {\n const detail = (event as CustomEvent<ArchiveDetail>).detail;\n handlersRef.current.handleArchive(detail.threadId);\n };\n const onUnarchive = (event: Event) => {\n const detail = (event as CustomEvent<UnarchiveDetail>).detail;\n handlersRef.current.handleUnarchive(detail.threadId);\n };\n const onDelete = (event: Event) => {\n const detail = (event as CustomEvent<DeleteDetail>).detail;\n handlersRef.current.handleDelete(detail.threadId);\n };\n const onFilterChange = (_event: Event) => {\n handlersRef.current.handleFilterChange();\n };\n const onOpenChangeEvent = (event: Event) => {\n const detail = (event as CustomEvent<OpenChangeDetail>).detail;\n handlersRef.current.handleOpenChange(detail.open);\n };\n const onRetry = (event: Event) => {\n const detail = (event as CustomEvent<RetryDetail>).detail;\n handlersRef.current.handleRetry(detail.scope);\n };\n const onLicensedEvent = () => handlersRef.current.handleLicensed();\n const onLoadMore = () => handlersRef.current.handleLoadMore();\n const onCollapseChangeEvent = (event: Event) => {\n const detail = (event as CustomEvent<CollapseChangeDetail>).detail;\n handlersRef.current.handleCollapseChange(detail.collapsed);\n };\n\n el.addEventListener(\"thread-selected\", onThreadSelected);\n el.addEventListener(\"new-thread\", onNewThreadEvent);\n el.addEventListener(\"archive\", onArchive);\n el.addEventListener(\"unarchive\", onUnarchive);\n el.addEventListener(\"delete\", onDelete);\n el.addEventListener(\"filter-change\", onFilterChange);\n el.addEventListener(\"open-change\", onOpenChangeEvent);\n el.addEventListener(\"retry\", onRetry);\n el.addEventListener(\"licensed\", onLicensedEvent);\n el.addEventListener(\"load-more\", onLoadMore);\n el.addEventListener(\"collapse-change\", onCollapseChangeEvent);\n\n return () => {\n el.removeEventListener(\"thread-selected\", onThreadSelected);\n el.removeEventListener(\"new-thread\", onNewThreadEvent);\n el.removeEventListener(\"archive\", onArchive);\n el.removeEventListener(\"unarchive\", onUnarchive);\n el.removeEventListener(\"delete\", onDelete);\n el.removeEventListener(\"filter-change\", onFilterChange);\n el.removeEventListener(\"open-change\", onOpenChangeEvent);\n el.removeEventListener(\"retry\", onRetry);\n el.removeEventListener(\"licensed\", onLicensedEvent);\n el.removeEventListener(\"load-more\", onLoadMore);\n el.removeEventListener(\"collapse-change\", onCollapseChangeEvent);\n };\n // Re-bind only after the first client mount (deps: [mounted]); the element\n // ref is stable thereafter.\n }, [mounted]);\n\n // Assign object/array/boolean PROPERTIES imperatively. React would otherwise\n // set these as string attributes, which a custom element cannot accept for\n // arrays/objects. Setting them as instance properties is the correct interop.\n useEffect(() => {\n const el = elementRef.current;\n if (!el) return;\n el.threads = drawerThreads;\n }, [drawerThreads, mounted]);\n\n useEffect(() => {\n const el = elementRef.current;\n if (!el) return;\n // While the license is still resolving, the element shows its loading\n // state and stays \"licensed\", so the locked view never flashes.\n const elementProps = ɵgetThreadsDrawerElementProps({\n loading: isLoading,\n licensed,\n licensePending,\n });\n el.loading = elementProps.loading;\n // Only genuine list-load/mutation errors reach the end user. Developer/\n // config errors (missing runtime URL, runtime without thread endpoints) are\n // excluded via `listError` so they never leak into the drawer's error UI.\n el.error = listError ? listError.message : null;\n el.activeThreadId = activeThreadId;\n el.licensed = elementProps.licensed;\n el.hasMore = hasMoreThreads;\n el.fetchingMore = isFetchingMoreThreads;\n // Dedicated fetch-more error channel: drives the element's inline\n // \"couldn't load more — retry\" panel without disturbing the loaded list or\n // the initial-list `error`. The `retry{scope:\"fetch-more\"}` handler\n // becomes reachable once this panel renders.\n el.fetchMoreError = fetchMoreError ? fetchMoreError.message : null;\n }, [\n isLoading,\n listError,\n fetchMoreError,\n activeThreadId,\n licensed,\n licensePending,\n hasMoreThreads,\n isFetchingMoreThreads,\n mounted,\n ]);\n\n // Bind the element's controlled `open` to the chat configuration's\n // drawerOpen, so the header launcher and the element stay in sync.\n useEffect(() => {\n const el = elementRef.current;\n if (!el) return;\n el.open = drawerOpen;\n }, [drawerOpen, mounted]);\n\n // Mirror the optional `label` onto the element (its accessible + default\n // header text). Leave the element's built-in default (\"Threads\") in place\n // when the prop is omitted, rather than clobbering it with undefined.\n useEffect(() => {\n const el = elementRef.current;\n if (!el) return;\n if (label !== undefined) el.label = label;\n }, [label, mounted]);\n\n // Mirror the optional `licenseUrl` onto the element (the locked view's\n // Upgrade CTA destination). Leave the element's built-in default in place\n // when the prop is omitted, rather than clobbering it with undefined.\n useEffect(() => {\n const el = elementRef.current;\n if (!el) return;\n if (licenseUrl !== undefined) el.licenseUrl = licenseUrl;\n }, [licenseUrl, mounted]);\n\n // Mirror the optional `collapsible` onto the element as a PROPERTY (a\n // default-true boolean, exactly like `licensed` — a string attribute cannot\n // represent it since any non-empty value is truthy). Leave the element's\n // built-in default (`true`) in place when the prop is omitted, rather than\n // clobbering it with undefined.\n useEffect(() => {\n const el = elementRef.current;\n if (!el) return;\n if (collapsible !== undefined) {\n // TODO(ENT-1051): drop the intersection cast once the published element\n // type declares `collapsible` (see the local CollapseChangeDetail note).\n (\n el as CopilotKitThreadsDrawerElement & { collapsible: boolean }\n ).collapsible = collapsible;\n }\n }, [collapsible, mounted]);\n\n // Per-row light-DOM children projected via `slot=\"row:{id}\"`.\n const rowChildren = useMemo(() => {\n if (!renderRow) return null;\n return drawerThreads.map((drawerThread) => {\n const fullThread = threads.find((t) => t.id === drawerThread.id);\n if (!fullThread) return null;\n const content = renderRow(fullThread);\n if (content === null || content === undefined) return null;\n return (\n <div key={drawerThread.id} slot={`row:${drawerThread.id}`}>\n {content}\n </div>\n );\n });\n }, [renderRow, drawerThreads, threads]);\n\n // SSR / pre-mount: render nothing so the server output matches the initial\n // client render (the element is not yet registered), avoiding hydration\n // mismatch and layout shift.\n if (!mounted) return null;\n\n return React.createElement(\n COPILOTKIT_THREADS_DRAWER_TAG,\n {\n ref: elementRef,\n \"data-testid\": dataTestId,\n // Pass the section heading label as an attribute; omit it entirely when\n // unset so the element keeps its built-in default rather than receiving\n // an `undefined` that would clobber it.\n ...(recentLabel !== undefined ? { \"recent-label\": recentLabel } : {}),\n },\n rowChildren,\n );\n}\n\nCopilotThreadsDrawer.displayName = \"CopilotThreadsDrawer\";\n\nexport default CopilotThreadsDrawer;\n","import { defineToolCallRenderer } from \"../types/defineToolCallRenderer\";\nimport {\n DefaultToolCallRenderer,\n adaptRendererProps,\n} from \"../hooks/use-default-render-tool\";\n\n/**\n * Catch-all (`\"*\"`) tool-call renderer that shows CopilotKit's default\n * tool-call card for any tool without a dedicated renderer.\n */\nexport const WildcardToolCallRender = defineToolCallRenderer({\n name: \"*\",\n group: true,\n render: (props) => <DefaultToolCallRenderer {...adaptRendererProps(props)} />,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAM,iBAAiB;CACrB,SAAS;CACT,aAAa;CACb,SAAS;CACT,WAAW;CACX,OAAO;CACP,MAAM;CACN,+BAA+B;CAC/B,yBAAyB;CACzB,2BAA2B;CAC5B;AAED,MAAM,cAAc;CAClB,SAAS;CACT,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,sBAAsB;CACtB,2BAA2B;CAC5B;;;;;AAgBD,SAAS,eAAe,EACtB,SACA,MACA,WACA,OAAO,cAIL,EAAE,EAAU;AACd,kCACE,cACA,YAAY,QAAQ,eAAe,WAAW,YAC9C,SAAS,QAAQ,YAAY,QAAQ,YACrC,WACA,UACD;;AAGH,MAAM,SAASA,MAAM,WAGnB,SA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AAC;AAKvC,KAAI,CAAC,QAAS,QAAO;AAErB,QAAOC,cAAM,cACXC,yEACA;EACE,KAAK;EACL,eAAe;EAIf,GAAI,gBAAgB,SAAY,EAAE,gBAAgB,aAAa,GAAG,EAAE;EACrE,EACD,YACD;;AAGH,qBAAqB,cAAc;;;;;;;;ACviBnC,MAAa,yBAAyBC,oCAAuB;CAC3D,MAAM;CACN,OAAO;CACP,SAAS,UAAU,2CAAC,2BAAwB,GAAI,mBAAmB,MAAM,GAAI;CAC9E,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["React","TooltipPrimitive","React","DropdownMenuPrimitive","React","CopilotIcon","ɵAudioRecorder","useCopilotChatConfiguration","CopilotChatDefaultLabels","useLatestRef","ɵComposerController","renderSlot","CopilotIcon","React","useCopilotChatConfiguration","React","React","useLabels","useCopilotChatConfiguration","CopilotChatDefaultLabels","ɵLICENSE_BANNER_STYLE","ɵINLINE_FEATURE_WARNING_STYLE","ɵMcpAppHost","OPEN_GENERATIVE_UI_ACTIVITY_TYPE","ɵOPEN_GENERATIVE_UI_CONTENT_SCHEMA","ɵGENERATE_SANDBOXED_UI_ARGS_SCHEMA","ɵOpenGenerativeUIController","ɵPlaceholderCycler","ToolCallStatus","CopilotKitCore","ɵRendererRegistry","version","stylesheet","MCPAppsActivityType","MCPAppsActivityContentSchema","createGenerativeUIActivityRenderer","createGenerativeUIFunctionCallActivityRenderer","useGenerativeUIRoot","ɵLearningAutoStarter","CopilotKitContext","LicenseContext","GenerativeUIToolCallRenderer","MarkdownRendererProvider","CopilotKitAgentIdContext","GenerativeUIRuntimeContext","useCopilotChatConfiguration","useCopilotChatConfiguration","EMPTY_DEPS","defineToolCallRenderer","ToolCallStatus","useLabels","useCopilotChatConfiguration","CopilotChatDefaultLabels","CopilotIcon","ɵTOOL_CALL_STATUS_ICONS","ɵTOOL_CALL_STATUS_LABEL_KEYS","React","ɵadaptDefaultToolCallRenderProps","useCopilotChatConfiguration","CopilotChatDefaultLabels","React","useCopilotChatConfiguration","useCopilotChatConfiguration","useCopilotChatConfiguration","ɵInterruptController","ɵThreadsController","ɵselectMemories","ɵselectMemoriesIsLoading","ɵselectMemoriesError","ɵselectMemoriesAvailable","ɵselectMemoriesRealtimeStatus","useCopilotChatConfiguration","ɵAttachmentQueue","React","renderSlot","ɵinspectorShortcuts","ɵinspectorKiteIcon","useCopilotChatConfiguration","CopilotChatDefaultLabels","ɵHoverMenuController","CopilotIcon","PopoverPrimitive","React","ɵFeedbackCommentController","ɵCopyFeedback","isReactComponentType","React","useCopilotChatConfiguration","renderSlot","CopilotChatDefaultLabels","Fragment","useShallowStableRef","useMarkdownRenderer","useGenerativeUIRuntime","MarkdownSurfaces","StreamingMarkdownDefaultRenderer","CopilotIcon","ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH","useCopilotChatConfiguration","CopilotChatDefaultLabels","CopilotIcon","useCopilotChatConfiguration","CopilotChatDefaultLabels","renderSlot","useCopilotChatConfiguration","CopilotChatDefaultLabels","CopilotIcon","useCopilotChatConfiguration","CopilotChatDefaultLabels","ɵReasoningDisclosure","renderSlot","CopilotIcon","StreamingMarkdownDefaultRenderer","React","CopilotIcon","React","renderSlot","React","React","useCopilotChatConfiguration","CopilotChatDefaultLabels","CopilotIcon","useCopilotChatConfiguration","renderSlot","isReactComponentType","React","useCopilotChatConfiguration","ɵcreateMessageViewModel","renderSlot","CopilotChatAssistantMessage","CopilotChatUserMessage","CopilotChatReasoningMessage","useCopilotChatConfiguration","CopilotChatDefaultLabels","CopilotIcon","ɵinitialKeyboardState","React","useCopilotChatConfiguration","CopilotChatDefaultLabels","CopilotIcon","renderSlot","CopilotChatInput","StickToBottom","ɵInspectorThreadOverride","useCopilotChatConfiguration","ɵFreshThreadId","ɵChatConnection","CopilotKitCoreRuntimeConnectionStatus","useShallowStableRef","renderSlot","CopilotChatConfigurationProvider","CopilotChatDefaultLabels","GenerativeUIChatSlotContext","CopilotIcon","React","useCopilotChatConfiguration","CopilotChatDefaultLabels","renderSlot","useCopilotChatConfiguration","CopilotChatDefaultLabels","renderSlot","CopilotIcon","CopilotChatConfigurationProvider","ControlledModalOpenScope","useCopilotChatConfiguration","ɵSIDEBAR_DEFAULT_WIDTH","ɵSIDEBAR_TRANSITION_MS","renderSlot","CopilotChatDefaultLabels","CopilotChatView","CopilotChatConfigurationProvider","ControlledModalOpenScope","useCopilotChatConfiguration","CopilotChatDefaultLabels","renderSlot","ɵPOPUP_DEFAULT_WIDTH","ɵPOPUP_DEFAULT_HEIGHT","CopilotChatView","CopilotChatView","React","CopilotPopupView","CopilotChatView","useCopilotChatConfiguration","CopilotKitContext","ɵtoDrawerThread","React","COPILOTKIT_THREADS_DRAWER_TAG","defineToolCallRenderer"],"sources":["../src/components/ui/button.tsx","../src/components/ui/tooltip.tsx","../src/components/ui/dropdown-menu.tsx","../src/components/chat/CopilotChatAudioRecorder.tsx","../src/components/chat/CopilotChatInput.tsx","../src/hooks/use-render-tool-call.tsx","../src/providers/use-owned-core.ts","../package.json","../src/components/CopilotKitInspector.tsx","../src/components/CopilotKitInspectorContext.tsx","../src/components/license-warning-banner.tsx","../src/components/MCPAppsActivityRenderer.tsx","../src/providers/SandboxFunctionsContext.ts","../src/components/OpenGenerativeUIRenderer.tsx","../src/generative-ui/use-standard-ui-fallback.ts","../src/lib/react-core.ts","../src/styles/copilot-kit-styles.tsx","../src/providers/CopilotKitProvider.tsx","../src/hooks/use-render-custom-messages.tsx","../src/hooks/use-render-activity-message.tsx","../src/hooks/tool-registration.ts","../src/hooks/use-frontend-tool.tsx","../src/hooks/use-frontend-tools.tsx","../src/hooks/use-component.tsx","../src/hooks/use-render-tool.tsx","../src/components/chat/CopilotChatToolCallGroup.tsx","../src/hooks/use-default-render-tool.tsx","../src/hooks/use-human-in-the-loop.tsx","../src/hooks/use-agent.tsx","../src/hooks/use-capabilities.tsx","../src/hooks/use-agent-context.tsx","../src/hooks/use-suggestions.tsx","../src/hooks/use-configure-suggestions.tsx","../src/hooks/use-interrupt.tsx","../src/hooks/use-threads.tsx","../src/hooks/use-memories.tsx","../src/hooks/use-learn-from-user-action.tsx","../src/hooks/use-learn-from-user-action-in-current-thread.tsx","../src/hooks/use-attachments.tsx","../src/components/chat/tool-call-display-context.ts","../src/components/chat/CopilotChatToolCallsView.tsx","../src/components/chat/CopilotChatInspectorButton.tsx","../src/components/ui/popover.tsx","../src/components/chat/message-feedback.tsx","../src/components/chat/use-copy-feedback.ts","../src/components/chat/CopilotChatAssistantMessage.tsx","../src/components/chat/Lightbox.tsx","../src/components/chat/CopilotChatAttachmentRenderer.tsx","../src/components/chat/CopilotChatUserMessage.tsx","../src/components/chat/CopilotChatReasoningMessage.tsx","../src/components/chat/CopilotChatSuggestionPill.tsx","../src/components/chat/CopilotChatSuggestionView.tsx","../src/components/chat/scroll-element-context.ts","../src/components/chat/scroll-pinned-context.ts","../src/components/chat/CopilotChatWorkSummary.tsx","../src/components/intelligence-indicator/IntelligenceIndicatorView.tsx","../src/components/intelligence-indicator/IntelligenceIndicator.tsx","../src/components/chat/CopilotChatMessageView.tsx","../src/components/chat/CopilotChatAttachmentQueue.tsx","../src/hooks/use-keyboard-height.tsx","../src/components/chat/last-user-message-context.ts","../src/hooks/use-pin-to-send.ts","../src/components/chat/CopilotChatView.tsx","../src/providers/use-inspector-thread-override.ts","../src/components/chat/CopilotChat.tsx","../src/components/chat/CopilotChatToggleButton.tsx","../src/components/chat/modal-open-control.tsx","../src/components/chat/CopilotModalHeader.tsx","../src/components/chat/CopilotSidebarView.tsx","../src/components/chat/CopilotPopupView.tsx","../src/components/chat/CopilotSidebar.tsx","../src/components/chat/CopilotPopup.tsx","../src/components/chat/CopilotThreadsDrawer.tsx","../src/components/WildcardToolCallRender.tsx"],"sourcesContent":["import * as React from \"react\";\n\nimport { cn } from \"../../lib/utils\";\nimport type { ClassValue } from \"../../lib/utils\";\n\n// Styles live in styles/css/ui/button.css.\nconst variantClasses = {\n default: \"cpk-button-default\",\n destructive: \"cpk-button-destructive\",\n outline: \"cpk-button-outline\",\n secondary: \"cpk-button-secondary\",\n ghost: \"cpk-button-ghost\",\n link: \"cpk-button-link\",\n assistantMessageToolbarButton: \"cpk-button-assistant-message-toolbar\",\n chatInputToolbarPrimary: \"cpk-button-chat-input-toolbar-primary\",\n chatInputToolbarSecondary: \"cpk-button-chat-input-toolbar-secondary\",\n} as const;\n\nconst sizeClasses = {\n default: \"cpk-button-size-default\",\n sm: \"cpk-button-size-sm\",\n lg: \"cpk-button-size-lg\",\n icon: \"cpk-button-size-icon\",\n chatInputToolbarIcon: \"cpk-button-size-chat-input-toolbar-icon\",\n chatInputToolbarIconLabel: \"cpk-button-size-chat-input-toolbar-icon-label\",\n} as const;\n\ntype ButtonVariant = keyof typeof variantClasses;\ntype ButtonSize = keyof typeof sizeClasses;\n\ninterface ButtonVariantProps {\n /** Defaults to `\"default\"`. `null` applies no variant class. */\n variant?: ButtonVariant | null;\n /** Defaults to `\"default\"`. `null` applies no size class. */\n size?: ButtonSize | null;\n}\n\n/**\n * Returns the class names for a button with the given variant and size,\n * followed by `className`.\n */\nfunction buttonVariants({\n variant,\n size,\n className,\n class: classProp,\n}: ButtonVariantProps & {\n className?: ClassValue;\n class?: ClassValue;\n} = {}): string {\n return cn(\n \"cpk-button\",\n variant !== null && variantClasses[variant ?? \"default\"],\n size !== null && sizeClasses[size ?? \"default\"],\n classProp,\n className,\n );\n}\n\nconst Button = React.forwardRef<\n HTMLButtonElement,\n React.ComponentProps<\"button\"> & ButtonVariantProps\n>(function Button({ className, variant, size, ...props }, ref) {\n return (\n <button\n ref={ref}\n data-slot=\"button\"\n className={buttonVariants({ variant, size, className })}\n {...props}\n />\n );\n});\n\nexport { Button, buttonVariants };\n","import * as React from \"react\";\nimport * as TooltipPrimitive from \"@radix-ui/react-tooltip\";\n\nimport { cn } from \"../../lib/utils\";\n\nfunction TooltipProvider({\n delayDuration = 0,\n ...props\n}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {\n return (\n <TooltipPrimitive.Provider\n data-slot=\"tooltip-provider\"\n delayDuration={delayDuration}\n {...props}\n />\n );\n}\n\nfunction Tooltip({\n ...props\n}: React.ComponentProps<typeof TooltipPrimitive.Root>) {\n return (\n <TooltipProvider>\n <TooltipPrimitive.Root data-slot=\"tooltip\" {...props} />\n </TooltipProvider>\n );\n}\n\nconst TooltipTrigger = React.forwardRef<\n HTMLButtonElement,\n React.ComponentProps<typeof TooltipPrimitive.Trigger>\n>(function TooltipTrigger({ ...props }, ref) {\n return (\n <TooltipPrimitive.Trigger\n ref={ref}\n data-slot=\"tooltip-trigger\"\n {...props}\n />\n );\n});\n\nfunction TooltipContent({\n className,\n sideOffset = 0,\n children,\n ...props\n}: React.ComponentProps<typeof TooltipPrimitive.Content>) {\n return (\n <TooltipPrimitive.Portal>\n <TooltipPrimitive.Content\n data-copilotkit\n data-slot=\"tooltip-content\"\n sideOffset={sideOffset}\n className={cn(\"cpk-tooltip\", className)}\n {...props}\n >\n {children}\n <TooltipPrimitive.Arrow className=\"cpk-tooltip-arrow\" />\n </TooltipPrimitive.Content>\n </TooltipPrimitive.Portal>\n );\n}\n\nexport { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };\n","\"use client\";\n\nimport * as React from \"react\";\nimport * as DropdownMenuPrimitive from \"@radix-ui/react-dropdown-menu\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\n\nimport { cn } from \"../../lib/utils\";\n\nfunction DropdownMenu({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {\n return <DropdownMenuPrimitive.Root data-slot=\"dropdown-menu\" {...props} />;\n}\n\nfunction DropdownMenuPortal({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {\n return (\n <DropdownMenuPrimitive.Portal data-slot=\"dropdown-menu-portal\" {...props} />\n );\n}\n\nconst DropdownMenuTrigger = React.forwardRef<\n HTMLButtonElement,\n React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>\n>(function DropdownMenuTrigger({ ...props }, ref) {\n return (\n <DropdownMenuPrimitive.Trigger\n ref={ref}\n data-slot=\"dropdown-menu-trigger\"\n {...props}\n />\n );\n});\n\nfunction DropdownMenuContent({\n className,\n sideOffset = 4,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Content> & {\n // Radix 2.1 forwards this to its focus scope but omits it from public types.\n onOpenAutoFocus?: (event: Event) => void;\n}) {\n return (\n <DropdownMenuPrimitive.Portal>\n <DropdownMenuPrimitive.Content\n data-copilotkit\n data-slot=\"dropdown-menu-content\"\n sideOffset={sideOffset}\n className={cn(\"cpk-dropdown-menu-content\", className)}\n {...props}\n />\n </DropdownMenuPrimitive.Portal>\n );\n}\n\nfunction DropdownMenuGroup({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {\n return (\n <DropdownMenuPrimitive.Group data-slot=\"dropdown-menu-group\" {...props} />\n );\n}\n\nfunction DropdownMenuItem({\n className,\n inset,\n variant = \"default\",\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {\n inset?: boolean;\n variant?: \"default\" | \"destructive\";\n}) {\n return (\n <DropdownMenuPrimitive.Item\n data-slot=\"dropdown-menu-item\"\n data-inset={inset}\n data-variant={variant}\n className={cn(\"cpk-dropdown-menu-item\", className)}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuCheckboxItem({\n className,\n children,\n checked,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {\n return (\n <DropdownMenuPrimitive.CheckboxItem\n data-slot=\"dropdown-menu-checkbox-item\"\n className={cn(\"cpk-dropdown-menu-checkbox-item\", className)}\n checked={checked}\n {...props}\n >\n <span className=\"cpk-dropdown-menu-item-indicator\">\n <DropdownMenuPrimitive.ItemIndicator>\n <CopilotIcon name=\"Check\" className=\"cpk-dropdown-menu-check-icon\" />\n </DropdownMenuPrimitive.ItemIndicator>\n </span>\n {children}\n </DropdownMenuPrimitive.CheckboxItem>\n );\n}\n\nfunction DropdownMenuRadioGroup({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {\n return (\n <DropdownMenuPrimitive.RadioGroup\n data-slot=\"dropdown-menu-radio-group\"\n {...props}\n />\n );\n}\n\nfunction DropdownMenuRadioItem({\n className,\n children,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {\n return (\n <DropdownMenuPrimitive.RadioItem\n data-slot=\"dropdown-menu-radio-item\"\n className={cn(\"cpk-dropdown-menu-radio-item\", className)}\n {...props}\n >\n <span className=\"cpk-dropdown-menu-item-indicator\">\n <DropdownMenuPrimitive.ItemIndicator>\n <CopilotIcon name=\"Circle\" className=\"cpk-dropdown-menu-radio-icon\" />\n </DropdownMenuPrimitive.ItemIndicator>\n </span>\n {children}\n </DropdownMenuPrimitive.RadioItem>\n );\n}\n\nfunction DropdownMenuLabel({\n className,\n inset,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {\n inset?: boolean;\n}) {\n return (\n <DropdownMenuPrimitive.Label\n data-slot=\"dropdown-menu-label\"\n data-inset={inset}\n className={cn(\"cpk-dropdown-menu-label\", className)}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuSeparator({\n className,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {\n return (\n <DropdownMenuPrimitive.Separator\n data-slot=\"dropdown-menu-separator\"\n className={cn(\"cpk-dropdown-menu-separator\", className)}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuShortcut({\n className,\n ...props\n}: React.ComponentProps<\"span\">) {\n return (\n <span\n data-slot=\"dropdown-menu-shortcut\"\n className={cn(\"cpk-dropdown-menu-shortcut\", className)}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuSub({\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {\n return <DropdownMenuPrimitive.Sub data-slot=\"dropdown-menu-sub\" {...props} />;\n}\n\nfunction DropdownMenuSubTrigger({\n className,\n inset,\n children,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {\n inset?: boolean;\n}) {\n return (\n <DropdownMenuPrimitive.SubTrigger\n data-slot=\"dropdown-menu-sub-trigger\"\n data-inset={inset}\n className={cn(\"cpk-dropdown-menu-sub-trigger\", className)}\n {...props}\n >\n {children}\n <CopilotIcon\n name=\"ChevronRight\"\n className=\"cpk-dropdown-menu-sub-trigger-icon\"\n />\n </DropdownMenuPrimitive.SubTrigger>\n );\n}\n\nfunction DropdownMenuSubContent({\n className,\n ...props\n}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {\n return (\n <DropdownMenuPrimitive.SubContent\n data-slot=\"dropdown-menu-sub-content\"\n className={cn(\"cpk-dropdown-menu-sub-content\", className)}\n {...props}\n />\n );\n}\n\nexport {\n DropdownMenu,\n DropdownMenuPortal,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuGroup,\n DropdownMenuLabel,\n DropdownMenuItem,\n DropdownMenuCheckboxItem,\n DropdownMenuRadioGroup,\n DropdownMenuRadioItem,\n DropdownMenuSeparator,\n DropdownMenuShortcut,\n DropdownMenuSub,\n DropdownMenuSubTrigger,\n DropdownMenuSubContent,\n};\n","import {\n useRef,\n useEffect,\n useImperativeHandle,\n forwardRef,\n useState,\n} from \"react\";\nimport { ɵAudioRecorder, ɵcreateWaveformRenderer } from \"@copilotkit/core\";\nimport type { ɵAudioRecorderState } from \"@copilotkit/core\";\nimport { cn } from \"../../lib/utils\";\n\n/** Finite-state machine for every recorder implementation */\nexport type AudioRecorderState = ɵAudioRecorderState;\n\n/** Error subclass so callers can `instanceof`-guard recorder failures */\nexport { ɵAudioRecorderError as AudioRecorderError } from \"@copilotkit/core\";\n\nexport interface AudioRecorderRef {\n state: AudioRecorderState;\n start: () => Promise<void>;\n stop: () => Promise<Blob>;\n dispose: () => void;\n}\n\n/**\n * Records from the microphone and draws the live level as a scrolling\n * waveform. The recording itself is `ɵAudioRecorder` from\n * `@copilotkit/core`; control it through the ref.\n */\nexport const CopilotChatAudioRecorder = forwardRef<\n AudioRecorderRef,\n React.HTMLAttributes<HTMLDivElement>\n>((props, ref) => {\n const { className, ...divProps } = props;\n const canvasRef = useRef<HTMLCanvasElement>(null);\n const [recorder] = useState(() => new ɵAudioRecorder());\n\n useEffect(() => {\n const canvas = canvasRef.current;\n if (!canvas) return;\n const waveform = ɵcreateWaveformRenderer(canvas, recorder);\n return () => waveform.dispose();\n }, [recorder]);\n\n useEffect(() => () => recorder.dispose(), [recorder]);\n\n useImperativeHandle(\n ref,\n () => ({\n get state() {\n return recorder.getSnapshot();\n },\n start: () => recorder.start(),\n stop: () => recorder.stop(),\n dispose: () => recorder.dispose(),\n }),\n [recorder],\n );\n\n return (\n <div className={cn(\"cpk-audio-recorder\", className)} {...divProps}>\n <canvas ref={canvasRef} className=\"cpk-audio-recorder-canvas\" />\n </div>\n );\n});\n\nCopilotChatAudioRecorder.displayName = \"CopilotChatAudioRecorder\";\n","import type { KeyboardEvent, ChangeEvent } from \"react\";\nimport { useLatestRef } from \"../../lib/use-latest-ref\";\nimport React, {\n useState,\n useRef,\n useEffect,\n useLayoutEffect,\n forwardRef,\n useImperativeHandle,\n useCallback,\n useMemo,\n useSyncExternalStore,\n} from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\n\nimport {\n CopilotChatDefaultLabels,\n ɵComposerController,\n ɵcomposerButtonState,\n ɵcreateComposerAutosize,\n ɵnormalizeToolsMenu,\n ɵshowsComposerDisclaimer,\n ɵsyncRecorderToMode,\n} from \"@copilotkit/core\";\nimport type { CopilotChatLabels } from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport { Button } from \"../../components/ui/button\";\nimport {\n Tooltip,\n TooltipContent,\n TooltipTrigger,\n} from \"../../components/ui/tooltip\";\nimport {\n DropdownMenu,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSub,\n DropdownMenuSubTrigger,\n DropdownMenuSubContent,\n DropdownMenuSeparator,\n} from \"../../components/ui/dropdown-menu\";\n\nimport { CopilotChatAudioRecorder } from \"./CopilotChatAudioRecorder\";\nimport type { WithSlots } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport { cn } from \"../../lib/utils\";\n\nexport type CopilotChatInputMode = \"input\" | \"transcribe\" | \"processing\";\n\nexport type ToolsMenuItem = {\n label: string;\n} & (\n | {\n action: () => void;\n items?: never;\n }\n | {\n action?: never;\n items: (ToolsMenuItem | \"-\")[];\n }\n);\n\ntype CopilotChatInputSlots = {\n textArea: typeof CopilotChatInput.TextArea;\n sendButton: typeof CopilotChatInput.SendButton;\n startTranscribeButton: typeof CopilotChatInput.StartTranscribeButton;\n cancelTranscribeButton: typeof CopilotChatInput.CancelTranscribeButton;\n finishTranscribeButton: typeof CopilotChatInput.FinishTranscribeButton;\n addMenuButton: typeof CopilotChatInput.AddMenuButton;\n audioRecorder: typeof CopilotChatAudioRecorder;\n disclaimer: typeof CopilotChatInput.Disclaimer;\n};\n\ntype CopilotChatInputRestProps = {\n mode?: CopilotChatInputMode;\n toolsMenu?: (ToolsMenuItem | \"-\")[];\n autoFocus?: boolean;\n onSubmitMessage?: (value: string) => void;\n onStop?: () => void;\n isRunning?: boolean;\n onStartTranscribe?: () => void;\n onCancelTranscribe?: () => void;\n onFinishTranscribe?: () => void;\n onFinishTranscribeWithAudio?: (audioBlob: Blob) => Promise<void>;\n onAddFile?: () => void;\n value?: string;\n onChange?: (value: string) => void;\n /** Positioning mode for the input container. Default: 'static' */\n positioning?: \"static\" | \"absolute\";\n /** Keyboard height in pixels for mobile keyboard handling */\n keyboardHeight?: number;\n /** Ref for the outer positioning container */\n containerRef?: React.Ref<HTMLDivElement>;\n /** Whether to show the disclaimer. Default: true for absolute positioning, false for static */\n showDisclaimer?: boolean;\n /**\n * Set to `true` when the input sits at the bottom of its container as a\n * flex-last-child (visible position is driven by layout, not CSS\n * positioning). Triggers reservation of bottom space for the fixed\n * CopilotKit license banner via the\n * `--copilotkit-license-banner-offset` CSS var so the two don't overlap.\n *\n * Not needed when `positioning === \"absolute\"`; that mode already pins the\n * input to the bottom and picks up the same reservation automatically.\n * Leave unset (default `false`) for inputs rendered mid-layout such as the\n * welcome screen, where the banner offset would push the input off-center.\n */\n bottomAnchored?: boolean;\n} & Omit<React.HTMLAttributes<HTMLDivElement>, \"onChange\">;\n\ntype CopilotChatInputBaseProps = WithSlots<\n CopilotChatInputSlots,\n CopilotChatInputRestProps\n>;\n\ntype CopilotChatInputChildrenArgs = CopilotChatInputBaseProps extends {\n children?: infer C;\n}\n ? C extends (props: infer P) => React.ReactNode\n ? P\n : never\n : never;\n\nexport type CopilotChatInputProps = Omit<\n CopilotChatInputBaseProps,\n \"children\"\n> & {\n children?: (props: CopilotChatInputChildrenArgs) => React.ReactNode;\n};\n\nconst SLASH_MENU_MAX_VISIBLE_ITEMS = 5;\nconst SLASH_MENU_ITEM_HEIGHT_PX = 40;\n\n/**\n * The chat composer: a text area with the add-menu, voice and send/stop\n * buttons, and a slash-command menu that lists `toolsMenu` items once the text\n * starts with \"/\".\n */\nexport function CopilotChatInput({\n mode = \"input\",\n onSubmitMessage,\n onStop,\n isRunning = false,\n onStartTranscribe,\n onCancelTranscribe,\n onFinishTranscribe,\n onFinishTranscribeWithAudio,\n onAddFile,\n onChange,\n value,\n toolsMenu,\n autoFocus = false,\n positioning = \"static\",\n keyboardHeight = 0,\n containerRef,\n showDisclaimer,\n bottomAnchored = false,\n textArea,\n sendButton,\n startTranscribeButton,\n cancelTranscribeButton,\n finishTranscribeButton,\n addMenuButton,\n audioRecorder,\n disclaimer,\n children,\n className,\n ...props\n}: CopilotChatInputProps) {\n const inputRef = useRef<HTMLTextAreaElement>(null);\n const gridRef = useRef<HTMLDivElement>(null);\n const addButtonContainerRef = useRef<HTMLDivElement>(null);\n const actionsContainerRef = useRef<HTMLDivElement>(null);\n const audioRecorderRef =\n useRef<React.ElementRef<typeof CopilotChatAudioRecorder>>(null);\n const slashMenuRef = useRef<HTMLDivElement>(null);\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n\n // Sizes the text box and picks the compact or expanded layout.\n const [autosize] = useState(() =>\n ɵcreateComposerAutosize({\n getElements: () => ({\n textarea: inputRef.current,\n grid: gridRef.current,\n start: addButtonContainerRef.current,\n actions: actionsContainerRef.current,\n }),\n }),\n );\n const layout = useSyncExternalStore(\n autosize.subscribe,\n autosize.getSnapshot,\n autosize.getSnapshot,\n );\n const isExpanded = mode === \"input\" && layout === \"expanded\";\n\n const previousModalStateRef = useRef<boolean | undefined>(undefined);\n\n // The text, controlled or not, and the slash-command menu: see core's\n // ɵComposerController.\n const onChangeRef = useLatestRef(onChange);\n const [composer] = useState(\n () =>\n new ɵComposerController<ToolsMenuItem>({\n initialValue: value ?? \"\",\n onChange: (next) => onChangeRef.current?.(next),\n }),\n );\n const {\n value: composerValue,\n slashQuery: commandQuery,\n slashCommands: filteredCommands,\n slashHighlightIndex,\n } = useSyncExternalStore(\n composer.subscribe,\n composer.getSnapshot,\n composer.getSnapshot,\n );\n // A controlled value renders at once; the controller catches up below.\n const resolvedValue = value ?? composerValue;\n\n const menu = useMemo(\n () =>\n ɵnormalizeToolsMenu<ToolsMenuItem>(\n toolsMenu,\n onAddFile\n ? { label: labels.chatInputToolbarAddButtonLabel, action: onAddFile }\n : undefined,\n ),\n [labels.chatInputToolbarAddButtonLabel, onAddFile, toolsMenu],\n );\n useLayoutEffect(() => {\n composer.setInputs({ value, mode, menu });\n }, [composer, value, mode, menu]);\n\n useEffect(() => {\n if (!autoFocus) {\n previousModalStateRef.current = config?.isModalOpen;\n return;\n }\n\n if (config?.isModalOpen && !previousModalStateRef.current) {\n inputRef.current?.focus({ preventScroll: true });\n }\n\n previousModalStateRef.current = config?.isModalOpen;\n }, [config?.isModalOpen, autoFocus]);\n\n // Recording follows the mode: it starts in transcribe mode and stops\n // when the mode changes.\n useEffect(() => {\n void ɵsyncRecorderToMode(audioRecorderRef.current, mode);\n }, [mode]);\n\n // Handlers\n const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {\n composer.setValue(e.target.value);\n };\n\n const runCommand = useCallback(\n (item: ToolsMenuItem) => {\n composer.runCommand(item);\n requestAnimationFrame(() => {\n inputRef.current?.focus();\n });\n },\n [composer],\n );\n\n const composerInput = {\n mode,\n isRunning,\n value: resolvedValue,\n canSubmit: !!onSubmitMessage,\n canStop: !!onStop,\n };\n const {\n isProcessing,\n action: buttonAction,\n disabled: buttonDisabled,\n } = ɵcomposerButtonState(composerInput);\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n // Text in the composer means send, even while a run is in flight: after\n // picking one interrupt's option the resume run still streams when the\n // user types the next prompt, and stopping it would lose the next\n // interrupt. Enter stops the run only when the composer is empty.\n const { preventDefault, action } = composer.keyDown(\n {\n key: e.key,\n shiftKey: e.shiftKey,\n isComposing: e.nativeEvent.isComposing,\n keyCode: e.keyCode,\n },\n composerInput,\n );\n if (preventDefault) e.preventDefault();\n if (action === \"command\") {\n requestAnimationFrame(() => {\n inputRef.current?.focus();\n });\n } else if (action === \"stop\") {\n onStop?.();\n } else if (action === \"send\") {\n send();\n }\n };\n\n const send = () => {\n if (!onSubmitMessage) {\n return;\n }\n // Always clears the input after sending, also when controlled:\n // onChange(\"\") tells the parent to reset its state.\n const sent = composer.submit(onSubmitMessage, { value: resolvedValue });\n if (sent) inputRef.current?.focus();\n };\n\n const BoundTextArea = renderSlot(textArea, CopilotChatInput.TextArea, {\n ref: inputRef,\n value: resolvedValue,\n onChange: handleChange,\n onKeyDown: handleKeyDown,\n autoFocus: autoFocus,\n className: isExpanded\n ? \"cpk-chat-input-textarea-expanded\"\n : \"cpk-chat-input-textarea-compact\",\n });\n\n const handleSendButtonClick = () => {\n // The send/stop button is an explicit control: when a run is in flight it\n // renders as a Stop (Square) button, so a click maps to stop regardless of\n // composer contents. The Enter key behaves differently (see handleKeyDown):\n // a non-empty composer + Enter sends a new message rather than stopping.\n if (isProcessing) {\n onStop?.();\n return;\n }\n send();\n };\n\n const BoundAudioRecorder = renderSlot(\n audioRecorder,\n CopilotChatAudioRecorder,\n {\n ref: audioRecorderRef,\n },\n );\n\n const showsStop = buttonAction === \"stop\";\n const BoundSendButton = renderSlot(sendButton, CopilotChatInput.SendButton, {\n onClick: handleSendButtonClick,\n disabled: buttonDisabled,\n \"aria-label\": showsStop\n ? labels.chatInputToolbarStopButtonLabel\n : labels.chatInputToolbarSendButtonLabel,\n children: showsStop ? (\n <CopilotIcon name=\"Square\" className=\"cpk-chat-input-stop-icon\" />\n ) : undefined,\n });\n\n const BoundStartTranscribeButton = renderSlot(\n startTranscribeButton,\n CopilotChatInput.StartTranscribeButton,\n {\n onClick: onStartTranscribe,\n },\n );\n\n const BoundCancelTranscribeButton = renderSlot(\n cancelTranscribeButton,\n CopilotChatInput.CancelTranscribeButton,\n {\n onClick: onCancelTranscribe,\n },\n );\n\n // Handler for finish button - stops recording and passes audio blob\n const handleFinishTranscribe = useCallback(async () => {\n const recorder = audioRecorderRef.current;\n if (recorder && recorder.state === \"recording\") {\n try {\n const audioBlob = await recorder.stop();\n if (onFinishTranscribeWithAudio) {\n await onFinishTranscribeWithAudio(audioBlob);\n }\n } catch (error) {\n console.error(\"Failed to stop recording:\", error);\n }\n }\n // Always call the original handler to reset mode\n onFinishTranscribe?.();\n }, [onFinishTranscribe, onFinishTranscribeWithAudio]);\n\n const BoundFinishTranscribeButton = renderSlot(\n finishTranscribeButton,\n CopilotChatInput.FinishTranscribeButton,\n {\n onClick: handleFinishTranscribe,\n },\n );\n\n const BoundAddMenuButton = renderSlot(\n addMenuButton,\n CopilotChatInput.AddMenuButton,\n {\n disabled: mode === \"transcribe\",\n onAddFile,\n toolsMenu,\n },\n );\n\n const BoundDisclaimer = renderSlot(\n disclaimer,\n CopilotChatInput.Disclaimer,\n {},\n );\n\n const shouldShowDisclaimer = ɵshowsComposerDisclaimer({\n showDisclaimer,\n positioning,\n });\n\n const handleContainerClick = (e: React.MouseEvent<HTMLDivElement>) => {\n // Don't focus if clicking on buttons or other interactive elements\n const target = e.target as HTMLElement;\n if (\n target.tagName !== \"BUTTON\" &&\n !target.closest(\"button\") &&\n inputRef.current &&\n mode === \"input\"\n ) {\n inputRef.current.focus();\n }\n };\n\n useLayoutEffect(() => {\n autosize.evaluate(resolvedValue, mode);\n }, [autosize, resolvedValue, mode]);\n\n useEffect(() => () => autosize.dispose(), [autosize]);\n\n const slashMenuVisible = commandQuery !== null;\n\n useEffect(() => {\n if (!slashMenuVisible || slashHighlightIndex < 0) {\n return;\n }\n\n const active = slashMenuRef.current?.querySelector<HTMLElement>(\n `[data-slash-index=\"${slashHighlightIndex}\"]`,\n );\n active?.scrollIntoView({ block: \"nearest\" });\n }, [slashMenuVisible, slashHighlightIndex]);\n\n const slashMenu = slashMenuVisible ? (\n <div\n data-testid=\"copilot-slash-menu\"\n role=\"listbox\"\n aria-label={labels.chatInputSlashMenuLabel}\n ref={slashMenuRef}\n className=\"cpk-chat-input-slash-menu\"\n style={{\n maxHeight: `${SLASH_MENU_MAX_VISIBLE_ITEMS * SLASH_MENU_ITEM_HEIGHT_PX}px`,\n }}\n >\n {filteredCommands.length === 0 ? (\n <div className=\"cpk-chat-input-slash-menu-empty\">\n {labels.chatInputSlashMenuEmptyText}\n </div>\n ) : (\n filteredCommands.map((item, index) => {\n const isActive = index === slashHighlightIndex;\n return (\n <button\n key={`${item.label}-${index}`}\n type=\"button\"\n role=\"option\"\n aria-selected={isActive}\n data-active={isActive ? \"true\" : undefined}\n data-slash-index={index}\n className=\"cpk-chat-input-slash-menu-item\"\n onMouseEnter={() => composer.highlight(index)}\n onMouseDown={(event) => {\n event.preventDefault();\n runCommand(item);\n }}\n >\n {item.label}\n </button>\n );\n })\n )}\n </div>\n ) : null;\n\n // The input pill (inner component)\n const inputPill = (\n <div\n data-testid=\"copilot-chat-input\"\n // copilotKitInput: V1 compatibility class for custom styling\n className=\"copilotKitInput cpk-chat-input-pill\"\n onClick={handleContainerClick}\n data-layout={isExpanded ? \"expanded\" : \"compact\"}\n >\n <div\n ref={gridRef}\n className=\"cpk-chat-input-grid\"\n data-layout={isExpanded ? \"expanded\" : \"compact\"}\n >\n <div ref={addButtonContainerRef} className=\"cpk-chat-input-start\">\n {BoundAddMenuButton}\n </div>\n <div className=\"cpk-chat-input-field\">\n {mode === \"transcribe\" ? (\n BoundAudioRecorder\n ) : mode === \"processing\" ? (\n <div className=\"cpk-chat-input-processing\">\n <CopilotIcon\n name=\"Loader2\"\n className=\"cpk-chat-input-processing-spinner\"\n />\n </div>\n ) : (\n <>\n {BoundTextArea}\n {slashMenu}\n </>\n )}\n </div>\n <div ref={actionsContainerRef} className=\"cpk-chat-input-actions\">\n {mode === \"transcribe\" ? (\n <>\n {onCancelTranscribe && BoundCancelTranscribeButton}\n {onFinishTranscribe && BoundFinishTranscribeButton}\n </>\n ) : (\n <>\n {onStartTranscribe && BoundStartTranscribeButton}\n {BoundSendButton}\n </>\n )}\n </div>\n </div>\n </div>\n );\n\n // A custom layout takes over the markup only. It returns after every hook\n // above, so the textarea keeps its measuring and auto-grow.\n if (children) {\n const childProps = {\n textArea: BoundTextArea,\n audioRecorder: BoundAudioRecorder,\n sendButton: BoundSendButton,\n startTranscribeButton: BoundStartTranscribeButton,\n cancelTranscribeButton: BoundCancelTranscribeButton,\n finishTranscribeButton: BoundFinishTranscribeButton,\n addMenuButton: BoundAddMenuButton,\n disclaimer: BoundDisclaimer,\n onSubmitMessage,\n onStop,\n isRunning,\n onStartTranscribe,\n onCancelTranscribe,\n onFinishTranscribe,\n onAddFile,\n mode,\n toolsMenu,\n autoFocus,\n positioning,\n keyboardHeight,\n showDisclaimer: shouldShowDisclaimer,\n containerRef,\n } as CopilotChatInputChildrenArgs;\n\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children(childProps)}\n </div>\n );\n }\n\n return (\n <div\n data-copilotkit\n ref={containerRef}\n className={cn(\n \"cpk-chat-input\",\n positioning === \"absolute\" && \"cpk-chat-input-absolute\",\n className,\n )}\n style={{\n transform:\n keyboardHeight > 0 ? `translateY(-${keyboardHeight}px)` : undefined,\n transition: \"transform 0.2s ease-out\",\n // Reserve room when the fixed license banner is visible so it doesn't\n // overlap the input. Applied only for bottom-anchored inputs (either\n // `positioning === \"absolute\"`, or an explicitly-flagged flex-last-child\n // input in run state). The welcome-screen input sits mid-layout and\n // must stay still when the banner is present.\n ...(positioning === \"absolute\" || bottomAnchored\n ? { paddingBottom: \"var(--copilotkit-license-banner-offset, 0px)\" }\n : {}),\n }}\n {...props}\n >\n <div className=\"cpk-chat-input-wrapper\">{inputPill}</div>\n {shouldShowDisclaimer && BoundDisclaimer}\n </div>\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace CopilotChatInput {\n /**\n * The icon-only send button. Its accessible name is\n * `labels.chatInputToolbarSendButtonLabel` unless an `aria-label` is passed;\n * the input passes `labels.chatInputToolbarStopButtonLabel` while the button\n * stops a run.\n */\n export const SendButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ className, children, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <div className=\"cpk-chat-input-send\">\n <Button\n type=\"button\"\n data-testid=\"copilot-send-button\"\n variant=\"chatInputToolbarPrimary\"\n size=\"chatInputToolbarIcon\"\n className={cn(\"cpk-chat-input-send-button\", className)}\n aria-label={labels.chatInputToolbarSendButtonLabel}\n {...props}\n >\n {children ?? (\n <CopilotIcon name=\"ArrowUp\" className=\"cpk-chat-input-send-icon\" />\n )}\n </Button>\n </div>\n );\n };\n\n /**\n * An icon-only toolbar button. `labels[labelKey]` is both its accessible\n * name and its tooltip text.\n */\n export const ToolbarButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement> & {\n icon: React.ReactNode;\n labelKey: keyof CopilotChatLabels;\n defaultClassName?: string;\n }\n > = ({ icon, labelKey, defaultClassName, className, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type=\"button\"\n variant=\"chatInputToolbarSecondary\"\n size=\"chatInputToolbarIcon\"\n className={cn(defaultClassName, className)}\n aria-label={labels[labelKey]}\n {...props}\n >\n {icon}\n </Button>\n </TooltipTrigger>\n <TooltipContent side=\"bottom\">\n <p>{labels[labelKey]}</p>\n </TooltipContent>\n </Tooltip>\n );\n };\n\n export const StartTranscribeButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = (props) => (\n <ToolbarButton\n data-testid=\"copilot-start-transcribe-button\"\n icon={<CopilotIcon name=\"Mic\" className=\"cpk-chat-input-toolbar-icon\" />}\n labelKey=\"chatInputToolbarStartTranscribeButtonLabel\"\n defaultClassName=\"cpk-chat-input-start-transcribe-button\"\n {...props}\n />\n );\n\n export const CancelTranscribeButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = (props) => (\n <ToolbarButton\n data-testid=\"copilot-cancel-transcribe-button\"\n icon={<CopilotIcon name=\"X\" className=\"cpk-chat-input-toolbar-icon\" />}\n labelKey=\"chatInputToolbarCancelTranscribeButtonLabel\"\n defaultClassName=\"cpk-chat-input-cancel-transcribe-button\"\n {...props}\n />\n );\n\n export const FinishTranscribeButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = (props) => (\n <ToolbarButton\n data-testid=\"copilot-finish-transcribe-button\"\n icon={\n <CopilotIcon name=\"Check\" className=\"cpk-chat-input-toolbar-icon\" />\n }\n labelKey=\"chatInputToolbarFinishTranscribeButtonLabel\"\n defaultClassName=\"cpk-chat-input-finish-transcribe-button\"\n {...props}\n />\n );\n\n /**\n * The \"+\" button that opens the attachment and tools menu. Its accessible\n * name and tooltip come from `labels.chatInputToolbarAddButtonLabel`.\n */\n export const AddMenuButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement> & {\n toolsMenu?: (ToolsMenuItem | \"-\")[];\n onAddFile?: () => void;\n }\n > = ({ className, toolsMenu, onAddFile, disabled, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n\n // Defer Radix UI rendering until after hydration to avoid ID mismatches\n const [mounted, setMounted] = useState(false);\n useEffect(() => setMounted(true), []);\n\n const menuItems = useMemo(\n () =>\n ɵnormalizeToolsMenu<ToolsMenuItem>(\n toolsMenu,\n onAddFile\n ? {\n label: labels.chatInputToolbarAddButtonLabel,\n action: onAddFile,\n }\n : undefined,\n ),\n [onAddFile, toolsMenu, labels.chatInputToolbarAddButtonLabel],\n );\n\n const renderMenuItems = useCallback(\n (items: (ToolsMenuItem | \"-\")[]): React.ReactNode =>\n items.map((item, index) => {\n if (item === \"-\") {\n return <DropdownMenuSeparator key={`separator-${index}`} />;\n }\n\n if (item.items && item.items.length > 0) {\n return (\n <DropdownMenuSub key={`group-${index}`}>\n <DropdownMenuSubTrigger>{item.label}</DropdownMenuSubTrigger>\n <DropdownMenuSubContent>\n {renderMenuItems(item.items)}\n </DropdownMenuSubContent>\n </DropdownMenuSub>\n );\n }\n\n return (\n <DropdownMenuItem key={`item-${index}`} onClick={item.action}>\n {item.label}\n </DropdownMenuItem>\n );\n }),\n [],\n );\n\n const hasMenuItems = menuItems.length > 0;\n const isDisabled = disabled || !hasMenuItems;\n\n const button = (\n <Button\n type=\"button\"\n data-testid=\"copilot-add-menu-button\"\n variant=\"chatInputToolbarSecondary\"\n size=\"chatInputToolbarIcon\"\n className={cn(\"cpk-chat-input-add-menu-button\", className)}\n disabled={isDisabled}\n aria-label={labels.chatInputToolbarAddButtonLabel}\n {...props}\n >\n <CopilotIcon name=\"Plus\" className=\"cpk-chat-input-add-menu-icon\" />\n </Button>\n );\n\n // Render plain button during SSR; Radix wrappers only after hydration\n if (!mounted) return button;\n\n return (\n <DropdownMenu>\n <Tooltip>\n <TooltipTrigger asChild>\n <DropdownMenuTrigger asChild>{button}</DropdownMenuTrigger>\n </TooltipTrigger>\n <TooltipContent side=\"bottom\">\n <p className=\"cpk-chat-input-add-menu-tooltip\">\n <span>{labels.chatInputToolbarAddButtonLabel}</span>\n <code className=\"cpk-chat-input-add-menu-shortcut\">/</code>\n </p>\n </TooltipContent>\n </Tooltip>\n {hasMenuItems && (\n <DropdownMenuContent side=\"top\" align=\"start\">\n {renderMenuItems(menuItems)}\n </DropdownMenuContent>\n )}\n </DropdownMenu>\n );\n };\n\n export type TextAreaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>;\n\n export const TextArea = forwardRef<HTMLTextAreaElement, TextAreaProps>(\n function TextArea(\n { style, className, autoFocus, placeholder, ...props },\n ref,\n ) {\n const internalTextareaRef = useRef<HTMLTextAreaElement>(null);\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n\n useImperativeHandle(\n ref,\n () => internalTextareaRef.current as HTMLTextAreaElement,\n );\n\n useEffect(() => {\n if (autoFocus) {\n internalTextareaRef.current?.focus({ preventScroll: true });\n }\n }, [autoFocus]);\n\n return (\n <textarea\n ref={internalTextareaRef}\n data-testid=\"copilot-chat-textarea\"\n placeholder={placeholder ?? labels.chatInputPlaceholder}\n className={cn(\"cpk-chat-input-textarea\", className)}\n style={{\n overflow: \"auto\",\n resize: \"none\",\n ...style,\n }}\n rows={1}\n {...props}\n />\n );\n },\n );\n\n export const AudioRecorder = CopilotChatAudioRecorder;\n\n export const Disclaimer: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({\n className,\n ...props\n }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <div className={cn(\"cpk-chat-input-disclaimer\", className)} {...props}>\n {labels.chatDisclaimerText}\n </div>\n );\n };\n}\n\nCopilotChatInput.TextArea.displayName = \"CopilotChatInput.TextArea\";\nCopilotChatInput.SendButton.displayName = \"CopilotChatInput.SendButton\";\nCopilotChatInput.ToolbarButton.displayName = \"CopilotChatInput.ToolbarButton\";\nCopilotChatInput.StartTranscribeButton.displayName =\n \"CopilotChatInput.StartTranscribeButton\";\nCopilotChatInput.CancelTranscribeButton.displayName =\n \"CopilotChatInput.CancelTranscribeButton\";\nCopilotChatInput.FinishTranscribeButton.displayName =\n \"CopilotChatInput.FinishTranscribeButton\";\nCopilotChatInput.AddMenuButton.displayName = \"CopilotChatInput.AddMenuButton\";\nCopilotChatInput.Disclaimer.displayName = \"CopilotChatInput.Disclaimer\";\n\nexport default CopilotChatInput;\n","import React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useSyncExternalStore,\n} from \"react\";\nimport type { ToolCall, ToolMessage } from \"@ag-ui/core\";\nimport {\n ɵbuildToolCallRenderProps,\n ɵdescribeUnrenderedToolCalls,\n ɵgetToolCallRendererNames,\n ɵresolveToolCallAgentId,\n ɵresolveToolCallRenderer,\n} from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport type { ReactToolCallRenderer } from \"../types/react-tool-call-renderer\";\n\nexport interface UseRenderToolCallProps {\n toolCall: ToolCall;\n toolMessage?: ToolMessage;\n}\n\n/**\n * Props for the memoized ToolCallRenderer component\n */\ninterface ToolCallRendererProps {\n toolCall: ToolCall;\n toolMessage?: ToolMessage;\n RenderComponent: ReactToolCallRenderer[\"render\"];\n isExecuting: boolean;\n}\n\n/**\n * Memoized component that renders a single tool call.\n * This prevents unnecessary re-renders when parent components update\n * but the tool call data hasn't changed.\n */\nconst ToolCallRenderer = React.memo(\n function ToolCallRenderer({\n toolCall,\n toolMessage,\n RenderComponent,\n isExecuting,\n }: ToolCallRendererProps) {\n // Rebuild only when the call, its result, or its executing state changes,\n // so `args` keeps a stable reference across unrelated renders.\n const props = useMemo(\n () => ɵbuildToolCallRenderProps(toolCall, toolMessage, { isExecuting }),\n [toolCall, toolMessage, isExecuting],\n );\n return <RenderComponent {...props} />;\n },\n // Custom comparison function to prevent re-renders when tool call data hasn't changed\n (prevProps, nextProps) => {\n // Compare tool call identity and content\n if (prevProps.toolCall.id !== nextProps.toolCall.id) return false;\n if (prevProps.toolCall.function.name !== nextProps.toolCall.function.name)\n return false;\n if (\n prevProps.toolCall.function.arguments !==\n nextProps.toolCall.function.arguments\n )\n return false;\n\n // Compare tool message (result)\n const prevResult = prevProps.toolMessage?.content;\n const nextResult = nextProps.toolMessage?.content;\n if (prevResult !== nextResult) return false;\n\n // Compare executing state\n if (prevProps.isExecuting !== nextProps.isExecuting) return false;\n\n // Compare render component reference\n if (prevProps.RenderComponent !== nextProps.RenderComponent) return false;\n\n return true;\n },\n);\n\nconst IS_DEVELOPMENT = process.env.NODE_ENV !== \"production\";\n\n/**\n * Reports tool calls that resolved to no renderer, once per tool name.\n *\n * A tool call with no renderer paints an empty message container and says\n * nothing else, so the only signal a developer gets today is a blank space in\n * the chat.\n *\n * @param toolNames - The unmatched tool names collected during render.\n * @param registered - The registry as it stands now, re-read at report time.\n * @param alreadyWarned - Names already reported, mutated to keep this once per name.\n */\nfunction warnAboutUnrenderedToolCalls(\n toolNames: readonly string[],\n registered: readonly { readonly name: string }[],\n alreadyWarned: Set<string>,\n): void {\n const fresh = toolNames.filter((name) => !alreadyWarned.has(name));\n const warnings = ɵdescribeUnrenderedToolCalls(fresh, registered);\n for (const { toolName, message } of warnings) {\n alreadyWarned.add(toolName);\n console.warn(message);\n }\n}\n\n/**\n * The tool-call renderers registered on the provider, kept current.\n * @internal\n */\nexport function useToolCallRenderers() {\n const { copilotkit } = useCopilotKit();\n // useSyncExternalStore so the value is current even if subscriptions run in\n // any order.\n return useSyncExternalStore(\n (callback) =>\n copilotkit.subscribe({ onRenderToolCallsChanged: callback }).unsubscribe,\n () => copilotkit.renderToolCalls,\n () => copilotkit.renderToolCalls,\n );\n}\n\n/**\n * Which tool names have a renderer of their own, whether a wildcard (`\"*\"`)\n * renderer is registered, and which of them opted into grouping.\n * @internal\n */\nexport function useToolCallRendererNames() {\n const renderers = useToolCallRenderers();\n return useMemo(() => ɵgetToolCallRendererNames(renderers), [renderers]);\n}\n\n/**\n * Hook that returns a function to render tool calls based on the render functions\n * defined in CopilotKitProvider.\n *\n * @returns A function that takes a tool call and optional tool message and returns the rendered component\n */\nexport function useRenderToolCall() {\n const { copilotkit, executingToolCallIds } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const agentId = ɵresolveToolCallAgentId(config?.agentId, undefined);\n\n // Development-only bookkeeping for the warning below. Collected during render\n // and reported afterwards, because the registry is not settled during render.\n const unrenderedToolNames = useRef<Set<string>>(new Set());\n const warnedToolNames = useRef<Set<string>>(new Set());\n\n const renderToolCalls = useToolCallRenderers();\n\n // `executingToolCallIds` mirrors core's set, which is filled from the first\n // `onToolExecutionStart`. A HITL call resumed on reconnect, before this\n // chat mounted, is therefore already executing on the first render.\n\n const renderToolCall = useCallback(\n ({\n toolCall,\n toolMessage,\n }: UseRenderToolCallProps): React.ReactElement | null => {\n // Rendering shows tool calls from every agent: agentId scoping only\n // affects handler execution (in core). The lookup prefers this agent's\n // renderer, then an unscoped one, then any agent's, then a wildcard.\n const renderConfig = ɵresolveToolCallRenderer(\n renderToolCalls,\n toolCall.function.name,\n agentId,\n );\n\n // No per-tool or wildcard renderer registered → render nothing.\n // Showing an unhandled tool call is opt-in: register a named/wildcard\n // renderer via useRenderTool, or call useDefaultRenderTool() for the\n // built-in card. Auto-painting a default card here would leak internal\n // tool names plus raw args/result JSON into every app's chat in\n // production, so the card must be explicitly enabled.\n if (!renderConfig) {\n if (IS_DEVELOPMENT) {\n unrenderedToolNames.current.add(toolCall.function.name);\n }\n return null;\n }\n\n const isExecuting = executingToolCallIds.has(toolCall.id);\n\n // Use the memoized ToolCallRenderer component to prevent unnecessary re-renders\n return (\n <ToolCallRenderer\n key={toolCall.id}\n toolCall={toolCall}\n toolMessage={toolMessage}\n RenderComponent={renderConfig.render}\n isExecuting={isExecuting}\n />\n );\n },\n [renderToolCalls, executingToolCallIds, agentId],\n );\n\n // Report unmatched tool calls after the commit that rendered them, deferred\n // one task past this subtree's effects. `useRenderTool` registers from an\n // effect in the component that renders the chat, and React runs child effects\n // before parent ones, so at effect time here a renderer the app does register\n // may not be in the registry yet. A timeout puts the check after every effect\n // in the tree, and `warnAboutUnrenderedToolCalls` re-reads the registry then.\n //\n // No dependency array on purpose: the misses live in a ref, so an effect that\n // only reran when `renderToolCalls` changed would never flush the common case\n // of a registry that never changes again.\n useEffect(() => {\n if (!IS_DEVELOPMENT) return;\n if (unrenderedToolNames.current.size === 0) return;\n\n const timer = setTimeout(() => {\n const pending = Array.from(unrenderedToolNames.current);\n unrenderedToolNames.current.clear();\n warnAboutUnrenderedToolCalls(\n pending,\n copilotkit.renderToolCalls,\n warnedToolNames.current,\n );\n }, 0);\n\n return () => clearTimeout(timer);\n });\n\n return renderToolCall;\n}\n","import { useEffect, useReducer, useRef } from \"react\";\nimport type { MutableRefObject } from \"react\";\n\n/** The part of a core this hook needs: something it can dispose. */\ninterface Disposable {\n dispose(): void;\n}\n\n/**\n * @internal Create a core for the provider's lifetime and dispose it on\n * unmount.\n *\n * The dispose waits one task. StrictMode (and Fast Refresh) unmount and\n * remount effects in the same commit, so the remount cancels the pending\n * dispose and the same core keeps working. When effects mount again after the\n * core was really disposed (for example an `<Activity>` that was hidden and\n * shown), the hook creates a new core and renders again: a disposed core is\n * never reused.\n *\n * `ref` holds the current core. The provider owns it, so code that runs\n * before the core exists can read `ref.current`.\n *\n * @example\n * const coreRef = useRef<CopilotKitCoreReact | null>(null);\n * const core = ɵuseOwnedCore(coreRef, () => new CopilotKitCoreReact(config));\n */\nexport function ɵuseOwnedCore<T extends Disposable>(\n ref: MutableRefObject<T | null>,\n create: () => T,\n) {\n const createRef = useRef(create);\n createRef.current = create;\n const pendingDispose = useRef<ReturnType<typeof setTimeout> | undefined>(\n undefined,\n );\n const disposedRef = useRef(false);\n const [, rerender] = useReducer((count: number) => count + 1, 0);\n\n const current = ref.current ?? create();\n ref.current = current;\n\n useEffect(() => {\n clearTimeout(pendingDispose.current);\n pendingDispose.current = undefined;\n let core = ref.current ?? createRef.current();\n if (disposedRef.current) {\n disposedRef.current = false;\n core = createRef.current();\n rerender();\n }\n ref.current = core;\n return () => {\n pendingDispose.current = setTimeout(() => {\n pendingDispose.current = undefined;\n disposedRef.current = true;\n core.dispose();\n }, 0);\n };\n }, [ref]);\n\n return current;\n}\n","","import { version as sdkVersion } from \"../../package.json\";\nimport * as React from \"react\";\nimport type { CopilotKitCore } from \"@copilotkit/core\";\nimport { ɵmountInspector } from \"@copilotkit/web-inspector/mount\";\nimport type { ɵInspectorMount } from \"@copilotkit/web-inspector/mount\";\nimport type { CopilotKitInspectorOpenRequest } from \"./CopilotKitInspectorContext\";\n\nexport interface CopilotKitInspectorProps {\n core?: CopilotKitCore | null;\n onVisibilityChange?: (visible: boolean) => void;\n openRequest?: CopilotKitInspectorOpenRequest | null;\n}\n\nexport const CopilotKitInspector: React.FC<CopilotKitInspectorProps> = ({\n core,\n openRequest,\n onVisibilityChange,\n}) => {\n const hostRef = React.useRef<HTMLSpanElement | null>(null);\n const mountRef = React.useRef<ɵInspectorMount | null>(null);\n const latestCoreRef = React.useRef(core ?? null);\n const visibilityCallbackRef = React.useRef(onVisibilityChange);\n\n latestCoreRef.current = core ?? null;\n visibilityCallbackRef.current = onVisibilityChange;\n\n React.useEffect(() => {\n const host = hostRef.current;\n if (!host) return;\n // The web component loads only on the client to keep SSR output stable.\n const mount = ɵmountInspector(host, latestCoreRef.current, {\n load: () => import(\"@copilotkit/web-inspector\"),\n notificationContext: {\n development: process.env.NODE_ENV === \"development\",\n framework: \"react\",\n sdkVersion,\n },\n });\n mount.onVisibility((visible) => visibilityCallbackRef.current?.(visible));\n mountRef.current = mount;\n return () => {\n mount.dispose();\n if (mountRef.current === mount) mountRef.current = null;\n };\n }, []);\n\n React.useEffect(() => {\n mountRef.current?.setCore(core ?? null);\n }, [core]);\n\n // Runs after the mount effect, so a request present at mount is queued\n // until the element loads.\n React.useEffect(() => {\n if (openRequest) mountRef.current?.open(openRequest);\n }, [openRequest]);\n\n return <span ref={hostRef} style={{ display: \"contents\" }} />;\n};\n\nCopilotKitInspector.displayName = \"CopilotKitInspector\";\n","\"use client\";\n\nimport * as React from \"react\";\n\nexport type CopilotKitInspectorOpenRequest = {\n messageId: string;\n threadId?: string;\n agentId?: string;\n};\n\ntype CopilotKitInspectorContextValue = {\n /** Explicit provider preference, which takes priority over chat preferences. */\n providerEnableInspector?: boolean;\n isInspectorEnabled: boolean;\n openInspector: (request: CopilotKitInspectorOpenRequest) => void;\n};\n\nconst CopilotKitInspectorContext =\n React.createContext<CopilotKitInspectorContextValue>({\n isInspectorEnabled: false,\n openInspector: () => undefined,\n });\n\nexport const CopilotKitInspectorContextProvider =\n CopilotKitInspectorContext.Provider;\n\nexport function useCopilotKitInspector(): CopilotKitInspectorContextValue {\n return React.useContext(CopilotKitInspectorContext);\n}\n","import { useEffect } from \"react\";\nimport {\n CopilotChatDefaultLabels,\n ɵINLINE_FEATURE_WARNING_STYLE,\n ɵLICENSE_BANNER_STYLE,\n ɵgetInlineFeatureWarningSpec,\n ɵgetLicenseBannerSpec,\n ɵreserveLicenseBannerOffset,\n} from \"@copilotkit/core\";\nimport type {\n ɵLicenseBannerDetails,\n ɵLicenseBannerType,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\n\n/** The chat labels in effect, or the default ones outside a chat. */\nfunction useLabels() {\n return useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;\n}\n\ninterface LicenseWarningBannerProps extends ɵLicenseBannerDetails {\n type: ɵLicenseBannerType;\n onDismiss?: () => void;\n}\n\n/**\n * The fixed license banner. Core's `ɵgetLicenseBannerSpec` picks its text,\n * link, and severity; this component renders them.\n */\nexport function LicenseWarningBanner({\n type,\n onDismiss,\n ...details\n}: LicenseWarningBannerProps) {\n const spec = ɵgetLicenseBannerSpec(type, useLabels(), details);\n\n // Publish the banner's reserved bottom offset so the chat input can lift\n // itself above it via padding-bottom: var(--copilotkit-license-banner-offset).\n useEffect(() => ɵreserveLicenseBannerOffset(), []);\n\n return (\n <div\n style={{\n ...ɵLICENSE_BANNER_STYLE.base,\n ...ɵLICENSE_BANNER_STYLE.severity[spec.severity],\n }}\n >\n <span>{spec.message}</span>\n <div style={ɵLICENSE_BANNER_STYLE.actions}>\n <a\n href={spec.actionUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n style={ɵLICENSE_BANNER_STYLE.link}\n >\n {spec.actionLabel}\n </a>\n {onDismiss && (\n <button onClick={onDismiss} style={ɵLICENSE_BANNER_STYLE.dismiss}>\n ×\n </button>\n )}\n </div>\n </div>\n );\n}\n\nexport function InlineFeatureWarning({ featureName }: { featureName: string }) {\n const spec = ɵgetInlineFeatureWarningSpec(featureName, useLabels());\n return (\n <div style={ɵINLINE_FEATURE_WARNING_STYLE.container}>\n {spec.message}{\" \"}\n <a\n href={spec.actionUrl}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n style={ɵINLINE_FEATURE_WARNING_STYLE.link}\n >\n {spec.actionLabel}\n </a>\n </div>\n );\n}\n","\"use client\";\n\nimport React, { useEffect, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport { useCopilotKit } from \"../providers/CopilotKitProvider\";\n\n// The app<->host protocol (ext-apps AppBridge, sandbox proxy, request queue,\n// ui/message + open-link handlers, tool input/result) lives in the shared,\n// framework-agnostic package. This file is now a THIN React adapter over it: it\n// owns the iframe (create/mount/size/remove) and wires the session's reactive\n// hooks to React state; all protocol logic is `bindMcpApp`.\n//\n// The lightweight activity surface (type + content schema + follow-up runner)\n// is re-exported from the package's bridge-free `/activity` entry, so importing\n// it (for the activity registry) does NOT pull the ext-apps bundle. The bridge\n// itself is loaded lazily via a dynamic `import(\"@copilotkit/mcp-apps-renderer\")`\n// inside the effect, so a `<CopilotKitProvider>` app only pays for it when it actually\n// renders an MCP App.\nexport {\n MCPAppsActivityType,\n MCPAppsActivityContentSchema,\n ɵrunMcpFollowUp,\n} from \"@copilotkit/mcp-apps-renderer/activity\";\nexport type {\n MCPAppsActivityContent,\n ɵMcpFollowUpHost,\n} from \"@copilotkit/mcp-apps-renderer/activity\";\n\nimport type { MCPAppsActivityContent } from \"@copilotkit/mcp-apps-renderer/activity\";\nimport { ɵMcpAppHost } from \"@copilotkit/mcp-apps-renderer/activity\";\n\n/**\n * Props for the activity renderer component\n */\ninterface MCPAppsActivityRendererProps {\n activityType: string;\n content: MCPAppsActivityContent;\n message: unknown; // ActivityMessage from @ag-ui/core\n agent: AbstractAgent | undefined;\n /**\n * Restore `allow-same-origin` on the sandbox. Unsafe: the widget runs with\n * the host page's origin. Set via `mcpApps.allowSameOriginFallback` on\n * `CopilotKitProvider`.\n */\n allowSameOriginFallback?: boolean;\n /**\n * Accept `ui/update-model-context`. Set via `mcpApps.modelContext` on\n * `CopilotKitProvider`.\n */\n modelContext?: boolean;\n}\n\n/**\n * MCP Apps Extension Activity Renderer\n *\n * Renders MCP Apps UI in a sandboxed iframe with full protocol support. The\n * shared `ɵMcpAppHost` owns the iframe, its size and its state, and binds the\n * protocol session (`bindMcpApp`, loaded lazily); this component only draws\n * the state around it.\n */\nexport const MCPAppsActivityRenderer: React.FC<MCPAppsActivityRendererProps> =\n function MCPAppsActivityRenderer({\n content,\n message,\n agent,\n allowSameOriginFallback,\n modelContext,\n }) {\n const { copilotkit } = useCopilotKit();\n const containerRef = useRef<HTMLDivElement>(null);\n // The activity message id: the session follows it in the agent's store.\n const messageId = (message as { id?: string } | undefined)?.id;\n\n // A new host or sandbox setting needs a new host object.\n const app = useMemo(\n () =>\n new ɵMcpAppHost({\n host: copilotkit,\n sessionOptions: { allowSameOriginFallback, modelContext },\n importRenderer: () => import(\"@copilotkit/mcp-apps-renderer\"),\n }),\n [copilotkit, allowSameOriginFallback, modelContext],\n );\n\n const state = useSyncExternalStore(\n app.subscribe,\n app.getState,\n app.getState,\n );\n\n useEffect(() => {\n app.setAgent(agent);\n app.setMessageId(messageId);\n }, [app, agent, messageId]);\n useEffect(() => {\n app.setContent(content);\n }, [app, content]);\n useEffect(() => {\n app.setContainer(containerRef.current);\n return () => app.destroy();\n }, [app]);\n\n // prefersBorder: true = border and background; otherwise none.\n const borderStyle = state.prefersBorder\n ? {\n borderRadius: \"8px\",\n backgroundColor: \"#f9f9f9\",\n border: \"1px solid #e0e0e0\",\n }\n : {};\n const shownError = state.error ?? state.contentError;\n\n return (\n <div\n ref={containerRef}\n style={{\n width: \"100%\",\n height: state.size.height ? `${state.size.height}px` : \"auto\",\n minHeight: \"100px\",\n overflow: \"hidden\",\n position: \"relative\",\n ...borderStyle,\n }}\n >\n {state.loading && (\n <div style={{ padding: \"1rem\", color: \"#666\" }}>Loading...</div>\n )}\n {shownError && (\n <div style={{ color: \"red\", padding: \"1rem\" }}>\n Error: {shownError}\n </div>\n )}\n </div>\n );\n };\n","import { createContext, useContext } from \"react\";\nimport type { SandboxFunction } from \"../types/sandbox-function\";\n\nexport const SandboxFunctionsContext = createContext<\n readonly SandboxFunction[]\n>([]);\n\nexport function useSandboxFunctions(): readonly SandboxFunction[] {\n return useContext(SandboxFunctionsContext);\n}\n","\"use client\";\n\nimport React, {\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n OPEN_GENERATIVE_UI_ACTIVITY_TYPE,\n ToolCallStatus,\n ɵGENERATE_SANDBOXED_UI_ARGS_SCHEMA,\n ɵOPEN_GENERATIVE_UI_CONTENT_SCHEMA,\n ɵOpenGenerativeUIController,\n ɵPlaceholderCycler,\n} from \"@copilotkit/core\";\nimport type {\n OpenGenerativeUIContent,\n GenerateSandboxedUiArgs,\n} from \"@copilotkit/core\";\nimport { useSandboxFunctions } from \"../providers/SandboxFunctionsContext\";\n\nexport type { OpenGenerativeUIContent, GenerateSandboxedUiArgs };\n\nexport const OpenGenerativeUIActivityType = OPEN_GENERATIVE_UI_ACTIVITY_TYPE;\n\n/** Validates Open Generative UI activity content (shared with Vue and Angular). */\nexport const OpenGenerativeUIContentSchema = ɵOPEN_GENERATIVE_UI_CONTENT_SCHEMA;\n\n/**\n * Schema for the generateSandboxedUi tool call arguments (shared with Vue and\n * Angular). It also describes the arguments to the model as JSON Schema.\n */\nexport const GenerateSandboxedUiArgsSchema = ɵGENERATE_SANDBOXED_UI_ARGS_SCHEMA;\n\ninterface OpenGenerativeUIActivityRendererProps {\n activityType: string;\n content: OpenGenerativeUIContent;\n message: unknown;\n agent: unknown;\n}\n\n/**\n * Renders an Open Generative UI activity. The core controller throttles the\n * content and runs the websandbox iframes inside the container div.\n */\nexport const OpenGenerativeUIActivityRenderer: React.FC<OpenGenerativeUIActivityRendererProps> =\n function OpenGenerativeUIActivityRenderer({ content }) {\n const [controller] = useState(() => {\n const created = new ɵOpenGenerativeUIController();\n created.setContent(content);\n return created;\n });\n const sandboxFunctions = useSandboxFunctions();\n const containerRef = useRef<HTMLDivElement>(null);\n const state = useSyncExternalStore(\n controller.subscribe,\n controller.getState,\n controller.getState,\n );\n\n useEffect(() => {\n controller.setSandboxFunctions(sandboxFunctions);\n }, [controller, sandboxFunctions]);\n\n useEffect(() => {\n controller.setContent(content);\n }, [controller, content]);\n\n useEffect(() => {\n controller.setHost(containerRef.current);\n return () => controller.destroy();\n }, [controller]);\n\n const hasVisibleSandbox = state.phase !== \"placeholder\";\n\n return (\n <div\n ref={containerRef}\n style={{\n position: \"relative\",\n width: \"100%\",\n height: `${state.height}px`,\n borderRadius: \"8px\",\n backgroundColor: hasVisibleSandbox ? \"transparent\" : \"#f5f5f5\",\n border: hasVisibleSandbox ? \"none\" : \"1px solid #e0e0e0\",\n display: hasVisibleSandbox ? \"block\" : \"flex\",\n alignItems: hasVisibleSandbox ? undefined : \"center\",\n justifyContent: hasVisibleSandbox ? undefined : \"center\",\n overflow: \"hidden\",\n }}\n >\n {state.showOverlay && (\n <div\n style={{\n position: \"absolute\",\n inset: 0,\n zIndex: 10,\n pointerEvents: \"all\",\n backgroundColor: \"rgba(255, 255, 255, 0.5)\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n }}\n >\n {state.showSpinner && (\n <svg\n width=\"48\"\n height=\"48\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n style={{ animation: \"ck-spin 1s linear infinite\" }}\n >\n <circle\n cx=\"12\"\n cy=\"12\"\n r=\"10\"\n stroke=\"#e0e0e0\"\n strokeWidth=\"3\"\n />\n <path\n d=\"M12 2a10 10 0 0 1 10 10\"\n stroke=\"#999\"\n strokeWidth=\"3\"\n strokeLinecap=\"round\"\n />\n </svg>\n )}\n <style>{`@keyframes ck-spin { to { transform: rotate(360deg) } }`}</style>\n </div>\n )}\n </div>\n );\n };\n\n/**\n * Frontend tool renderer for generateSandboxedUi.\n * Displays placeholder messages while the UI is being generated.\n */\nexport const OpenGenerativeUIToolRenderer: React.FC<\n | {\n name: string;\n args: Partial<GenerateSandboxedUiArgs>;\n status: ToolCallStatus.InProgress;\n result: undefined;\n }\n | {\n name: string;\n args: GenerateSandboxedUiArgs;\n status: ToolCallStatus.Executing;\n result: undefined;\n }\n | {\n name: string;\n args: GenerateSandboxedUiArgs;\n status: ToolCallStatus.Complete;\n result: string;\n }\n> = function OpenGenerativeUIToolRenderer(props) {\n const [cycler] = useState(() => new ɵPlaceholderCycler());\n const { message } = useSyncExternalStore(\n cycler.subscribe,\n cycler.getSnapshot,\n cycler.getSnapshot,\n );\n const isComplete = props.status === ToolCallStatus.Complete;\n\n useEffect(() => {\n cycler.update(props.args.placeholderMessages, isComplete);\n }, [cycler, props.args.placeholderMessages, isComplete]);\n useEffect(() => () => cycler.dispose(), [cycler]);\n\n // Before the first effect, show what the cycler starts with: the newest message.\n const shown =\n message ??\n (isComplete ? undefined : props.args.placeholderMessages?.at(-1));\n // Nothing once complete — the activity renderer handles the UI.\n if (shown === undefined) return null;\n\n return (\n <div\n style={{\n padding: \"8px 12px\",\n color: \"#999\",\n fontSize: \"14px\",\n }}\n >\n {shown}\n </div>\n );\n};\n","import { useEffect, useMemo, useState } from \"react\";\nimport { ɵresolveGenerativeUIDefault } from \"@copilotkit/core\";\nimport type { GenerativeUI } from \"./catalog\";\nimport type { GenerativeUIConfig } from \"./runtime-context\";\n\n/**\n * The standard UI, loaded once on first use. It is a dynamic import so the\n * standard components (chart, map, media, ...) stay out of the main entry:\n * an app that does not use generative UI never downloads them.\n */\nlet standardUIPromise: Promise<GenerativeUI> | undefined;\n\nfunction loadStandardUI(): Promise<GenerativeUI> {\n if (!standardUIPromise) {\n standardUIPromise = import(\"./standard\").then(\n (module) => module.standardUI,\n );\n // A failed load is tried again on the next use.\n standardUIPromise.catch(() => {\n standardUIPromise = undefined;\n });\n }\n return standardUIPromise;\n}\n\n/** The runtime info that decides the fallback. */\nexport interface StandardUIFallbackRuntimeInfo {\n generativeUIEnabled: boolean;\n generativeUIAgents: string[] | undefined;\n}\n\n/**\n * The generative UI config of the provider. That is the `generativeUI` prop\n * when it has a `ui`. Otherwise, when the runtime turns generative UI on, it\n * is the standard UI for the agents of the runtime, once the standard UI has\n * loaded, with the other options of the prop (such as `map` or `theme`).\n * `undefined` while generative UI is off, or still loading.\n */\nexport function useStandardUIFallback(\n generativeUI: GenerativeUIConfig | undefined,\n runtimeInfo: StandardUIFallbackRuntimeInfo | null,\n): GenerativeUIConfig | undefined {\n const fallback = ɵresolveGenerativeUIDefault({\n runtimeEnabled: runtimeInfo?.generativeUIEnabled ?? false,\n runtimeAgents: runtimeInfo?.generativeUIAgents,\n hasUI: !!generativeUI?.ui,\n });\n const active = fallback.active;\n const agentIds = fallback.active ? fallback.agentIds : undefined;\n\n const [standardUI, setStandardUI] = useState<GenerativeUI>();\n useEffect(() => {\n if (!active || standardUI) return;\n let cancelled = false;\n loadStandardUI().then(\n (ui) => {\n if (!cancelled) setStandardUI(ui);\n },\n (error: unknown) => {\n console.error(\n \"[generativeUI] could not load the standard UI for the runtime's generative UI:\",\n error,\n );\n },\n );\n return () => {\n cancelled = true;\n };\n }, [active, standardUI]);\n\n return useMemo(() => {\n if (generativeUI?.ui) return generativeUI;\n if (!active || !standardUI) return undefined;\n return {\n ...generativeUI,\n ui: standardUI,\n agentIds: generativeUI?.agentIds ?? agentIds,\n };\n }, [generativeUI, active, standardUI, agentIds]);\n}\n","import React from \"react\";\nimport type {\n ReactActivityMessageRenderer,\n ReactToolCallRenderer,\n} from \"../types\";\nimport type { ReactCustomMessageRenderer } from \"../types/react-custom-message-renderer\";\nimport { CopilotKitCore, ɵRendererRegistry } from \"@copilotkit/core\";\nimport type {\n CopilotKitCoreConfig,\n CopilotKitCoreSubscriber,\n CopilotKitCoreSubscription,\n ɵRendererKind,\n} from \"@copilotkit/core\";\n\nexport interface CopilotKitCoreReactConfig extends CopilotKitCoreConfig {\n // Add any additional configuration properties specific to the React implementation\n renderToolCalls?: ReactToolCallRenderer<any>[];\n renderActivityMessages?: ReactActivityMessageRenderer<any>[];\n\n // Add custom message renderers\n renderCustomMessages?: ReactCustomMessageRenderer[];\n}\n\nexport interface CopilotKitCoreReactSubscriber extends CopilotKitCoreSubscriber {\n onRenderToolCallsChanged?: (event: {\n copilotkit: CopilotKitCore;\n renderToolCalls: readonly ReactToolCallRenderer<any>[];\n }) => void | Promise<void>;\n onRenderActivityMessagesChanged?: (event: {\n copilotkit: CopilotKitCore;\n renderActivityMessages: readonly ReactActivityMessageRenderer<any>[];\n }) => void | Promise<void>;\n onRenderCustomMessagesChanged?: (event: {\n copilotkit: CopilotKitCore;\n renderCustomMessages: readonly ReactCustomMessageRenderer[];\n }) => void | Promise<void>;\n onInterruptElementChanged?: (event: {\n copilotkit: CopilotKitCore;\n interruptElement: React.ReactElement | null;\n }) => void | Promise<void>;\n}\n\n/**\n * Wait for pending React state updates before the follow-up agent run.\n *\n * When a frontend tool handler calls setState(), React 18 batches the update\n * and schedules a commit via its internal scheduler (MessageChannel). The\n * useAgentContext hook registers context via useLayoutEffect, which runs\n * synchronously after React commits that batch.\n *\n * Awaiting a zero-delay timeout yields to the macrotask queue. React's\n * MessageChannel task runs first, committing the pending state and running\n * useLayoutEffect (which updates the context store). The follow-up runAgent\n * call then reads fresh context.\n */\nfunction waitForReactCommit() {\n return new Promise<void>((resolve) => setTimeout(resolve, 0));\n}\n\nexport class CopilotKitCoreReact extends CopilotKitCore {\n private readonly _renderers: ɵRendererRegistry<\n ReactToolCallRenderer<any>,\n ReactActivityMessageRenderer<any>,\n ReactCustomMessageRenderer\n >;\n\n constructor(config: CopilotKitCoreReactConfig) {\n super({\n ...config,\n ɵwaitForFrameworkUpdates: waitForReactCommit,\n });\n this._renderers = new ɵRendererRegistry({\n toolCalls: config.renderToolCalls,\n activity: config.renderActivityMessages,\n custom: config.renderCustomMessages,\n });\n this._renderers.subscribe((kind) => this.notifyRenderersChanged(kind));\n // The element lives in core's generic interrupt slot; keep the React\n // subscriber event for existing listeners.\n this.ɵsubscribeToInterruptPayload(() => {\n void this.notifySubscribers((subscriber) => {\n const reactSubscriber = subscriber as CopilotKitCoreReactSubscriber;\n return reactSubscriber.onInterruptElementChanged?.({\n copilotkit: this,\n interruptElement: this.interruptElement,\n });\n }, \"Subscriber onInterruptElementChanged error:\");\n });\n }\n\n get renderCustomMessages() {\n return this._renderers.custom;\n }\n\n get renderActivityMessages() {\n return this._renderers.activity;\n }\n\n /**\n * Prop, hook and built-in renderers merged. For one name and agentId, a\n * hook renderer wins over a prop one, and both win over a built-in one.\n */\n get renderToolCalls() {\n return this._renderers.toolCalls;\n }\n\n setRenderActivityMessages(\n renderers: ReactActivityMessageRenderer<any>[],\n ): void {\n this._renderers.setActivity(renderers);\n }\n\n setRenderCustomMessages(renderers: ReactCustomMessageRenderer[]): void {\n this._renderers.setCustom(renderers);\n }\n\n setRenderToolCalls(renderToolCalls: ReactToolCallRenderer<any>[]): void {\n this._renderers.setPropToolCalls(renderToolCalls);\n }\n\n addHookRenderToolCall(entry: ReactToolCallRenderer<any>): void {\n this._renderers.addHookToolCall(entry);\n }\n\n removeHookRenderToolCall(name: string, agentId?: string): void {\n this._renderers.removeHookToolCall(name, agentId);\n }\n\n /**\n * @internal Add a renderer for a tool a built-in feature owns\n * (generative UI). Prop and hook renderers with the same name and agent win\n * over it, and `setRenderToolCalls` never removes it.\n *\n * @returns A function that removes the renderer.\n */\n ɵaddBuiltInRenderToolCall(entry: ReactToolCallRenderer): () => void {\n return this._renderers.addBuiltInToolCall(entry);\n }\n\n private notifyRenderersChanged(kind: ɵRendererKind): void {\n void this.notifySubscribers((subscriber) => {\n const reactSubscriber = subscriber as CopilotKitCoreReactSubscriber;\n switch (kind) {\n case \"toolCalls\":\n return reactSubscriber.onRenderToolCallsChanged?.({\n copilotkit: this,\n renderToolCalls: this.renderToolCalls,\n });\n case \"activity\":\n return reactSubscriber.onRenderActivityMessagesChanged?.({\n copilotkit: this,\n renderActivityMessages: this.renderActivityMessages,\n });\n case \"custom\":\n return reactSubscriber.onRenderCustomMessagesChanged?.({\n copilotkit: this,\n renderCustomMessages: this.renderCustomMessages,\n });\n }\n }, `Subscriber renderer change (${kind}) error:`);\n }\n\n get interruptElement(): React.ReactElement | null {\n return this.ɵinterruptPayload as React.ReactElement | null;\n }\n\n setInterruptElement(element: React.ReactElement | null): void {\n this.ɵsetInterruptPayload(element);\n }\n\n // Override to accept React-specific subscriber type\n subscribe(\n subscriber: CopilotKitCoreReactSubscriber,\n ): CopilotKitCoreSubscription {\n return super.subscribe(subscriber);\n }\n}\n","import React, { createContext, useContext, version } from \"react\";\nimport { stylesheet } from \"@copilotkit/core/styles\";\n\ninterface StyleOptions {\n /** CSP nonce for the `<style>` tag. */\n nonce?: string;\n /** `false` when the app loads `@copilotkit/core/styles.css` itself. */\n inject: boolean;\n}\n\nconst StyleOptionsContext = createContext<StyleOptions>({ inject: true });\n\n/** React 19 moves a `<style precedence>` into `<head>` and keeps one copy. */\nconst hoistsStyles = Number.parseInt(version, 10) >= 19;\n\n/** Passes the provider's style options to `<CopilotKitStyles>`. */\nexport const CopilotStyleOptionsProvider = StyleOptionsContext.Provider;\n\n/**\n * Renders the CSS for CopilotKit's UI, so apps never import a stylesheet.\n * `CopilotChat` (and so `CopilotPopup` and `CopilotSidebar`) renders it for\n * you. Render it yourself only when you build a layout from the chat parts\n * without `CopilotChat`.\n *\n * React 19 moves the tag into `<head>` and keeps one copy, including in the\n * server HTML. React 18 renders it in place, one copy per `CopilotChat`.\n * Each copy holds the same CSS, so a second copy changes nothing.\n *\n * With a CSP nonce the tag always renders in place. React only adds a nonce to\n * a hoisted style when the app renders with `nonce: { style }`, and Next.js\n * passes a plain string, so a hoisted tag would be blocked.\n *\n * Renders nothing when `CopilotKitProvider` has `injectStyles={false}`.\n */\nexport function CopilotKitStyles() {\n const { nonce, inject } = useContext(StyleOptionsContext);\n if (!inject) {\n return null;\n }\n if (nonce || !hoistsStyles) {\n // `dangerouslySetInnerHTML`, because React 18's server escapes `>` and\n // quotes in style text, which breaks the CSS in the server HTML.\n return (\n <style nonce={nonce} dangerouslySetInnerHTML={{ __html: stylesheet }} />\n );\n }\n return (\n <style href=\"copilotkit\" precedence=\"copilotkit\">\n {stylesheet}\n </style>\n );\n}\n","\"use client\";\n\nimport type { AbstractAgent } from \"@ag-ui/client\";\nimport type {\n ɵCopilotKitProviderBaseOptions,\n ɵRuntimeInfo,\n ɵStableArrayProp,\n} from \"@copilotkit/core\";\nimport {\n ɵLearningAutoStarter,\n ɵassembleActivityRenderers,\n ɵassembleHumanInTheLoop,\n ɵassembleProviderToolRenderers,\n ɵassembleProviderTools,\n ɵhitlRenderProps,\n ɵstableArrayPropWarning,\n ɵtoLearningConfig,\n} from \"@copilotkit/core\";\nimport type React from \"react\";\nimport {\n createElement,\n useMemo,\n useCallback,\n useEffect,\n useLayoutEffect,\n useReducer,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { ɵuseOwnedCore } from \"./use-owned-core\";\nimport type { ReactNode } from \"react\";\n// Context extracted to ../context.ts for cross-platform reuse (React Native)\nimport {\n CopilotKitAgentIdContext,\n CopilotKitContext,\n LicenseContext,\n} from \"../context\";\nimport type { CopilotKitContextValue } from \"../context\";\nexport type { CopilotKitContextValue } from \"../context\";\nexport { CopilotKitContext, useLicenseContext } from \"../context\";\nimport { CopilotKitInspector } from \"../components/CopilotKitInspector\";\nimport { CopilotKitInspectorContextProvider } from \"../components/CopilotKitInspectorContext\";\nimport type { CopilotKitInspectorOpenRequest } from \"../components/CopilotKitInspectorContext\";\nimport { LicenseWarningBanner } from \"../components/license-warning-banner\";\nimport {\n ɵaddOpenGenerativeUIContexts,\n ɵcreateOpenGenerativeUITool,\n ɵisOpenGenerativeUIActive,\n ɵpublicKeyHeaderDefaults,\n ɵreportProviderConfigDiagnostics,\n ɵresolveLicenseState,\n ɵresolveProviderConfig,\n ɵwithHeaderDefaults,\n} from \"@copilotkit/core\";\nimport {\n MCPAppsActivityContentSchema,\n MCPAppsActivityRenderer,\n MCPAppsActivityType,\n} from \"../components/MCPAppsActivityRenderer\";\nimport {\n OpenGenerativeUIActivityType,\n OpenGenerativeUIContentSchema,\n OpenGenerativeUIActivityRenderer,\n OpenGenerativeUIToolRenderer,\n} from \"../components/OpenGenerativeUIRenderer\";\nimport { useGenerativeUIRoot } from \"../generative-ui/use-generative-ui-root\";\nimport { useStandardUIFallback } from \"../generative-ui/use-standard-ui-fallback\";\nimport type { GenerativeUIConfig } from \"../generative-ui/runtime-context\";\nimport {\n createGenerativeUIActivityRenderer,\n createGenerativeUIFunctionCallActivityRenderer,\n GenerativeUIToolCallRenderer,\n} from \"../generative-ui/chat\";\nimport { GenerativeUIRuntimeContext } from \"../generative-ui/runtime-context\";\nimport { CopilotKitCoreReact } from \"../lib/react-core\";\nimport type {\n ReactActivityMessageRenderer,\n ReactToolCallRenderer,\n} from \"../types\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport type { ReactHumanInTheLoop } from \"../types/human-in-the-loop\";\nimport type { ReactCustomMessageRenderer } from \"../types/react-custom-message-renderer\";\nimport type { SandboxFunction } from \"../types/sandbox-function\";\nimport { SandboxFunctionsContext } from \"./SandboxFunctionsContext\";\nimport { MarkdownRendererProvider } from \"./MarkdownRendererContext\";\nimport type { MarkdownRenderer } from \"./MarkdownRendererContext\";\nimport { CopilotStyleOptionsProvider } from \"../styles/copilot-kit-styles\";\nimport { shouldEnableInspector } from \"@copilotkit/shared\";\n\n// Stable frozen defaults keep provider effects from re-running just because a\n// caller omitted an object prop on a rerender.\nconst EMPTY_HEADERS: Readonly<Record<string, string>> = Object.freeze({});\nconst EMPTY_PROPERTIES: Readonly<Record<string, unknown>> = Object.freeze({});\nconst EMPTY_AGENTS: Readonly<Record<string, AbstractAgent>> = Object.freeze({});\n\n// Provider props interface\nexport interface CopilotKitProviderProps extends ɵCopilotKitProviderBaseOptions {\n children: ReactNode;\n /**\n * CSP nonce for the `<style>` tags CopilotKit adds. Set it when your\n * Content-Security-Policy limits `style-src` to a nonce.\n */\n nonce?: string;\n /**\n * Set to `false` when you import `@copilotkit/core/styles.css` yourself, so\n * browsers cache the CSS as a file. CopilotKit then adds no `<style>` tag.\n * @default true\n */\n injectStyles?: boolean;\n /**\n * The id of the agent every `<CopilotChat>` under this provider talks to,\n * unless a chat names its own with the `agentId` prop.\n *\n * This is the v2 replacement for the v1 `<CopilotKit agent=\"...\">` prop. Set\n * it here and you never need the v1 compatibility provider just to name an\n * agent. Defaults to `\"default\"`.\n */\n agentId?: string;\n renderToolCalls?: ReactToolCallRenderer<any>[];\n renderActivityMessages?: ReactActivityMessageRenderer<any>[];\n renderCustomMessages?: ReactCustomMessageRenderer[];\n /**\n * Global markdown renderer used by assistant/reasoning messages. Overrides the\n * built-in basic renderer. A per-message `markdownRenderer` slot still wins\n * over this. Plug in your own (e.g. a streamdown wrapper) to restore rich\n * rendering — CopilotKit ships only the basic renderer.\n */\n markdownRenderer?: MarkdownRenderer;\n frontendTools?: ReactFrontendTool[];\n humanInTheLoop?: ReactHumanInTheLoop[];\n /**\n * Configuration for OpenGenerativeUI — sandboxed UI generated by the LLM.\n *\n * @example\n * ```tsx\n * <CopilotKitProvider\n * runtimeUrl=\"/api/copilotkit\"\n * openGenerativeUI={{\n * sandboxFunctions: [{ name: \"addToCart\", description: \"…\", parameters: schema, handler: fn }],\n * }}\n * >\n * ```\n */\n openGenerativeUI?: {\n /**\n * Functions made available inside sandboxed iframes.\n * Each function is described to the LLM via agent context and exposed\n * via websandbox's `localApi`.\n *\n * Inside the iframe, call them with:\n * ```js\n * await Websandbox.connection.remote.<functionName>(args)\n * ```\n */\n sandboxFunctions?: SandboxFunction[];\n /**\n * Design guidelines injected as agent context for the `generateSandboxedUi` tool.\n * Override this to control the visual style of generated UIs.\n *\n * A sensible default is provided if omitted.\n */\n designSkill?: string;\n };\n /**\n * Disable the CopilotKit Inspector in development.\n * The Inspector is enabled by default in development browser builds on\n * localhost/loopback. It is always disabled on remote hosts, in production,\n * and during server rendering. Temporary Inspector hides also hide its\n * message shortcuts.\n * An explicit value takes priority over CopilotChat's inspectorTools prop.\n */\n enableInspector?: boolean;\n /**\n * Whether to automatically mount the Intelligence indicator in chat.\n *\n * @default true\n */\n showIntelligenceIndicator?: boolean;\n /**\n * Experimental. Native generative UI: `generativeUI={{ ui }}`, where `ui`\n * comes from `createGenerativeUI`. The agent renders your React components\n * into chat or into `<GenerativeUISurface id>` mounts. Props that match\n * the declared state and events that match the declared functions are\n * bound by the library, and the model does not see them.\n *\n * When it is left out and the runtime turns generative UI on, the provider\n * uses `standardUI` for the agents the runtime names. The standard\n * components load on demand, the first time the runtime turns it on.\n */\n generativeUI?: GenerativeUIConfig;\n /**\n * @deprecated Use `generativeUI`. The provider passes `a2ui` on to\n * `generativeUI`: `a2ui={{ catalog, theme }}` works as\n * `generativeUI={{ ui: catalog, theme }}`. When both props set the same\n * option, `generativeUI` wins. The other v0.9 options (`onAction`,\n * `loadingComponent`, `recovery`, `includeSchema`) have no 2.0 equivalent.\n * See https://docs.copilotkit.ai/generative-ui/components/from-a2ui\n */\n a2ui?: {\n /** A UI from `createGenerativeUI`. It is the `ui` of `generativeUI`. */\n catalog?: GenerativeUIConfig[\"ui\"];\n /** Values for the `--a2ui-*` CSS variables. It is the `theme` of `generativeUI`. */\n theme?: GenerativeUIConfig[\"theme\"];\n };\n}\n\n/**\n * The `generativeUI` prop with the options of the deprecated `a2ui` prop:\n * `a2ui.catalog` is the `ui` and `a2ui.theme` the `theme`, unless\n * `generativeUI` sets them.\n */\nfunction withA2UIOptions(\n generativeUI: GenerativeUIConfig | undefined,\n a2ui: NonNullable<CopilotKitProviderProps[\"a2ui\"]>,\n) {\n const hasA2UIOptions = a2ui.catalog !== undefined || a2ui.theme !== undefined;\n if (!hasA2UIOptions) return generativeUI;\n return {\n ...generativeUI,\n ui: generativeUI?.ui ?? a2ui.catalog,\n theme: generativeUI?.theme ?? a2ui.theme,\n };\n}\n\n// Normalize an array prop to a stable reference, and warn (rule from core)\n// when it changes after mount.\nfunction useStableArrayProp<T>(\n prop: T[] | undefined,\n name: ɵStableArrayProp,\n): T[] {\n const empty = useMemo<T[]>(() => [], []);\n const value = prop ?? empty;\n const initial = useRef(value);\n\n useEffect(() => {\n const warning = ɵstableArrayPropWarning(name, initial.current, value);\n if (warning) console.error(warning);\n }, [value, name]);\n\n return value;\n}\n\n/** Provide a shared core instance and synchronize runtime, tool, and UI configuration. */\nexport const CopilotKitProvider: React.FC<CopilotKitProviderProps> = ({\n children,\n runtimeUrl,\n headers: headersProp = EMPTY_HEADERS,\n credentials,\n nonce,\n injectStyles = true,\n messageFilter,\n publicApiKey,\n publicLicenseKey,\n properties = EMPTY_PROPERTIES,\n agents__unsafe_dev_only: agents = EMPTY_AGENTS,\n selfManagedAgents = EMPTY_AGENTS,\n renderToolCalls,\n renderActivityMessages,\n renderCustomMessages,\n markdownRenderer,\n frontendTools,\n humanInTheLoop,\n openGenerativeUI,\n enableInspector,\n agentId,\n showIntelligenceIndicator = true,\n useSingleEndpoint,\n onError,\n generativeUI,\n a2ui,\n mcpApps,\n defaultThrottleMs,\n debug,\n learning,\n}) => {\n // Memoized so a stable `learning` object keeps a stable config after\n // `autoStart` is removed.\n const learningConfig = useMemo(() => ɵtoLearningConfig(learning), [learning]);\n\n // Keep the server render and the first client render identical. The\n // Inspector only runs in local development. Resolve its host and build\n // policy after hydration instead of branching on `window` during render.\n const [shouldRenderInspector, setShouldRenderInspector] = useState(false);\n const [inspectorVisible, setInspectorVisible] = useState(false);\n\n useEffect(() => {\n setShouldRenderInspector(\n shouldEnableInspector({\n enableInspector,\n isBrowser: true,\n isDevelopment: process.env.NODE_ENV === \"development\",\n hostname: window.location?.hostname,\n }),\n );\n }, [enableInspector]);\n\n const [inspectorOpenRequest, setInspectorOpenRequest] =\n useState<CopilotKitInspectorOpenRequest | null>(null);\n // Core's runtime info snapshot, projected once the core exists (see the\n // subscription effect below). `null` until the first sync.\n const [runtimeInfo, setRuntimeInfo] = useState<ɵRuntimeInfo | null>(null);\n const runtimeOpenGenUIEnabled = runtimeInfo?.openGenerativeUIEnabled ?? false;\n const openGenUIActive = ɵisOpenGenerativeUIActive({\n runtimeEnabled: runtimeOpenGenUIEnabled,\n configured: !!openGenerativeUI,\n });\n // The deprecated `a2ui` prop goes to `generativeUI`, which wins for an\n // option that both set.\n const a2uiCatalog = a2ui?.catalog;\n const a2uiTheme = a2ui?.theme;\n const generativeUIProp = useMemo(\n () =>\n withA2UIOptions(generativeUI, { catalog: a2uiCatalog, theme: a2uiTheme }),\n [generativeUI, a2uiCatalog, a2uiTheme],\n );\n // The app's `generativeUI`, or the standard UI when the runtime turns\n // generative UI on and the app has none (loaded on demand).\n const generativeUIConfig = useStandardUIFallback(\n generativeUIProp,\n runtimeInfo,\n );\n const generativeUIActive = !!generativeUIConfig?.ui;\n const runtimeLicenseStatus = runtimeInfo?.licenseStatus;\n const runtimeEntitlements = runtimeInfo?.runtimeEntitlements;\n const runtimeEntitlementRetryPending =\n runtimeInfo?.runtimeEntitlementRetryPending ?? false;\n\n const requestInspectorOpen = useCallback(\n (request: CopilotKitInspectorOpenRequest) => {\n setInspectorOpenRequest({ ...request });\n },\n [],\n );\n\n const inspectorContextValue = useMemo(\n () => ({\n providerEnableInspector: enableInspector,\n isInspectorEnabled: shouldRenderInspector && inspectorVisible,\n openInspector: requestInspectorOpen,\n }),\n [\n enableInspector,\n shouldRenderInspector,\n inspectorVisible,\n requestInspectorOpen,\n ],\n );\n\n // Normalize array props to stable references with clear dev warnings\n // renderToolCalls warns only when its shape (names + agentId) changes, so\n // parents can pass updated closures (e.g., Storybook state).\n const renderToolCallsList = useStableArrayProp<ReactToolCallRenderer<any>>(\n renderToolCalls,\n \"renderToolCalls\",\n );\n\n const renderCustomMessagesList =\n useStableArrayProp<ReactCustomMessageRenderer>(\n renderCustomMessages,\n \"renderCustomMessages\",\n );\n\n const renderActivityMessagesList = useStableArrayProp<\n ReactActivityMessageRenderer<any>\n >(renderActivityMessages, \"renderActivityMessages\");\n\n // Stable core instance ref, declared here so the human-in-the-loop memo\n // below can read the core lazily. The instance itself is created further\n // down.\n const copilotkitRef = useRef<CopilotKitCoreReact | null>(null);\n\n const mcpAppsAllowSameOrigin = mcpApps?.allowSameOriginFallback === true;\n const mcpAppsModelContext = mcpApps?.modelContext === true;\n // Keyed on the two booleans, not on the `mcpApps` object, so an inline\n // `mcpApps={{ ... }}` does not remount every widget on each render.\n const mcpAppsRenderer = useMemo<typeof MCPAppsActivityRenderer>(\n () =>\n mcpAppsAllowSameOrigin || mcpAppsModelContext\n ? (props) => (\n <MCPAppsActivityRenderer\n {...props}\n allowSameOriginFallback={mcpAppsAllowSameOrigin}\n modelContext={mcpAppsModelContext}\n />\n )\n : MCPAppsActivityRenderer,\n [mcpAppsAllowSameOrigin, mcpAppsModelContext],\n );\n\n // The app's activity renderers, then the built-in ones (order from core).\n const allActivityRenderers = useMemo(\n () =>\n ɵassembleActivityRenderers<ReactActivityMessageRenderer<any>>({\n app: renderActivityMessagesList,\n builtIns: [\n {\n activityType: MCPAppsActivityType,\n content: MCPAppsActivityContentSchema,\n render: mcpAppsRenderer,\n },\n openGenUIActive && {\n activityType: OpenGenerativeUIActivityType,\n content: OpenGenerativeUIContentSchema,\n render: OpenGenerativeUIActivityRenderer,\n },\n generativeUIActive && createGenerativeUIActivityRenderer(),\n generativeUIActive &&\n createGenerativeUIFunctionCallActivityRenderer(),\n ],\n }),\n [\n renderActivityMessagesList,\n openGenUIActive,\n generativeUIActive,\n mcpAppsRenderer,\n ],\n );\n\n // Key fallback, Copilot Cloud URL, transport and agent merge all come from\n // core.\n const resolvedConfig = useMemo(\n () =>\n ɵresolveProviderConfig({\n runtimeUrl,\n publicApiKey,\n publicLicenseKey,\n useSingleEndpoint,\n agents__unsafe_dev_only: agents,\n selfManagedAgents,\n properties,\n }),\n [\n runtimeUrl,\n publicApiKey,\n publicLicenseKey,\n useSingleEndpoint,\n agents,\n selfManagedAgents,\n properties,\n ],\n );\n const resolvedPublicKey = resolvedConfig.publicKey;\n // Throws in production for a missing runtime config; otherwise warns, once\n // per provider for each message.\n const loggedDiagnosticsRef = useRef(new Set<string>());\n ɵreportProviderConfigDiagnostics(resolvedConfig.diagnostics, {\n isProduction: process.env.NODE_ENV === \"production\",\n logged: loggedDiagnosticsRef.current,\n });\n\n // The latest builder, read when a request is sent (never during render).\n // Assigned during render itself (not in a `useEffect`) so a child effect\n // that fires in the SAME commit as a new builder closure — e.g. a run\n // kicked off from an effect right after a token changed — reads the new\n // closure rather than the previous commit's.\n const headersRef = useRef(headersProp);\n headersRef.current = headersProp;\n const isHeadersBuilder = typeof headersProp === \"function\";\n // The read below can return a sync record or an async promise depending on\n // what `headersRef.current` happens to be at call time, which\n // `CopilotKitHeadersSource`'s shape can't express in one function\n // signature (sync-only OR async-only) — same rationale as the cast inside\n // `ɵwithHeaderDefaults`.\n const stableHeadersBuilder = useCallback(() => {\n const current = headersRef.current;\n return typeof current === \"function\" ? current() : current;\n }, []) as () => Record<string, string>;\n // A record keeps today's identity semantics; a builder is stable.\n const headersInput = isHeadersBuilder ? stableHeadersBuilder : headersProp;\n const headersSource = useMemo(\n () =>\n ɵwithHeaderDefaults(\n headersInput,\n ɵpublicKeyHeaderDefaults(resolvedPublicKey),\n ),\n [headersInput, resolvedPublicKey],\n );\n\n const frontendToolsList = useStableArrayProp<ReactFrontendTool>(\n frontendTools,\n \"frontendTools\",\n );\n const humanInTheLoopList = useStableArrayProp<ReactHumanInTheLoop>(\n humanInTheLoop,\n \"humanInTheLoop\",\n );\n const sandboxFunctionsList = useStableArrayProp<SandboxFunction>(\n openGenerativeUI?.sandboxFunctions,\n \"sandboxFunctions\",\n );\n\n // Built-in frontend tool for generateSandboxedUi — registered only when the runtime has openGenerativeUI enabled\n const builtInFrontendTools = useMemo<ReactFrontendTool[]>(() => {\n if (!openGenUIActive) return [];\n return [\n {\n ...ɵcreateOpenGenerativeUITool(),\n render: OpenGenerativeUIToolRenderer,\n },\n ];\n }, [openGenUIActive]);\n\n // The tools and tool-call renderers for core (assembly rules from core).\n // Human-in-the-loop renders are wrapped once per `humanInTheLoop` change: a\n // new wrapper is a new component type, so React would remount the card.\n const humanInTheLoopAssembly = useMemo(\n () =>\n ɵassembleHumanInTheLoop<\n ReactToolCallRenderer<any>[\"render\"],\n ReactHumanInTheLoop[\"render\"]\n >({\n humanInTheLoop: humanInTheLoopList,\n // Core parks each call by tool call id until the render responds.\n // The core is created further down, so read its registry lazily.\n humanInTheLoopRegistry: () => copilotkitRef.current!.ɵhumanInTheLoop,\n wrapHumanInTheLoopRender: (render, tool, registry) => (props) =>\n createElement(\n render as React.ComponentType<any>,\n ɵhitlRenderProps(props, tool, registry()),\n ),\n }),\n [humanInTheLoopList],\n );\n const allTools = useMemo(\n () =>\n ɵassembleProviderTools({\n frontendTools: frontendToolsList,\n builtInFrontendTools,\n humanInTheLoop: humanInTheLoopAssembly,\n }),\n [frontendToolsList, builtInFrontendTools, humanInTheLoopAssembly],\n );\n const allRenderToolCalls = useMemo(\n () =>\n ɵassembleProviderToolRenderers({\n renderToolCalls: renderToolCallsList,\n frontendTools: frontendToolsList,\n builtInFrontendTools,\n humanInTheLoop: humanInTheLoopAssembly,\n }) as ReactToolCallRenderer[],\n [\n renderToolCallsList,\n frontendToolsList,\n builtInFrontendTools,\n humanInTheLoopAssembly,\n ],\n );\n\n // One core for the provider lifetime (ref declared above), disposed on\n // unmount.\n // Updates are applied via setter effects below rather than recreating the\n // instance.\n const copilotkit = ɵuseOwnedCore(\n copilotkitRef,\n () =>\n new CopilotKitCoreReact({\n runtimeUrl: resolvedConfig.runtimeUrl,\n // Defer the `/info` fetch out of construction. The core is constructed\n // during render, and React can start-and-discard renders (concurrent\n // rendering / Suspense / StrictMode) — a network request in the ctor\n // would fire once per discarded attempt (issue #5801). `connect()`\n // below starts the single request from a commit-phase effect.\n deferInitialConnection: true,\n runtimeTransport: resolvedConfig.runtimeTransport,\n headers: headersSource,\n credentials,\n messageFilter,\n properties: resolvedConfig.properties,\n agents__unsafe_dev_only: resolvedConfig.agents,\n tools: allTools,\n renderToolCalls: allRenderToolCalls,\n renderActivityMessages: allActivityRenderers,\n renderCustomMessages: renderCustomMessagesList,\n debug,\n // Set at construction so child hooks see it on their first render.\n defaultThrottleMs,\n onError,\n learning: learningConfig,\n }),\n );\n const generativeUIRuntime = useGenerativeUIRoot(\n copilotkit,\n generativeUIConfig,\n );\n\n // Project core's runtime info snapshot (one object with every `/info`\n // field, so no field can be missed — a missed `licenseStatus` once pinned\n // the threads drawer to \"Loading threads…\"). The catch-up read after\n // subscribing reflects a status that settled before this effect ran.\n useEffect(() => {\n const syncRuntimeInfo = () => setRuntimeInfo(copilotkit.ɵruntimeInfo);\n const unsubscribe = copilotkit.ɵsubscribeToRuntimeInfo(syncRuntimeInfo);\n syncRuntimeInfo();\n return unsubscribe;\n }, [copilotkit]);\n\n // Subscribe to render tool calls changes to force re-renders\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onRenderToolCallsChanged: () => {\n forceUpdate();\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit]);\n\n // Core tracks executing tool calls from the first `onToolExecutionStart`,\n // so a HITL call resumed on reconnect (before the chat mounts) is already\n // executing when children first read it.\n const subscribeExecutingToolCalls = useCallback(\n (onChange: () => void) =>\n copilotkit.subscribe({ onExecutingToolCallsChanged: onChange })\n .unsubscribe,\n [copilotkit],\n );\n const getExecutingToolCallIds = () => copilotkit.executingToolCallIds;\n const executingToolCallIds = useSyncExternalStore(\n subscribeExecutingToolCalls,\n getExecutingToolCallIds,\n getExecutingToolCallIds,\n );\n\n // Core calls `onError`, and logs the error itself when there is none.\n useEffect(() => {\n copilotkit.setErrorHandler(onError);\n }, [copilotkit, onError]);\n\n useEffect(() => {\n // Core applies the message filter first, so an agent discovered by the\n // connection below is built with it. The generative UI envelope is not in\n // these properties: useGenerativeUIRoot adds it as scoped properties, so\n // this call does not replace it.\n copilotkit.ɵupdateConfig({\n messageFilter,\n runtimeUrl: resolvedConfig.runtimeUrl,\n runtimeTransport: resolvedConfig.runtimeTransport,\n headers: headersSource,\n credentials,\n properties: resolvedConfig.properties,\n agents__unsafe_dev_only: resolvedConfig.agents,\n debug,\n defaultThrottleMs,\n });\n // Start the runtime `/info` connection now that we're in the commit phase.\n // The ctor deferred it (see `deferInitialConnection` above) so discarded\n // renders never fetch; `connect()` is idempotent, so StrictMode's\n // double-invoked effect and re-runs on unrelated prop changes collapse to a\n // single request (a real runtimeUrl/transport change reconnects via the\n // update above). See #5801.\n copilotkit.connect();\n }, [\n copilotkit,\n messageFilter,\n resolvedConfig.runtimeUrl,\n resolvedConfig.runtimeTransport,\n headersSource,\n credentials,\n resolvedConfig.properties,\n resolvedConfig.agents,\n debug,\n defaultThrottleMs,\n ]);\n\n // Start the Trajectory in the commit phase, after the runtime URL is set, so\n // CopilotKit's own runtime traffic is never captured. The starter keeps its\n // generated Trajectory ID across StrictMode's dispose and replay.\n const learningStarterRef = useRef<ɵLearningAutoStarter | null>(null);\n learningStarterRef.current ??= new ɵLearningAutoStarter(copilotkit);\n const learningStarter = learningStarterRef.current;\n useEffect(() => {\n learningStarter.update(learning);\n }, [learningStarter, learning]);\n useEffect(() => () => learningStarter.dispose(), [learningStarter]);\n\n // Sync render/tool arrays to the stable instance via setters.\n // On mount, the constructor already receives the correct initial values,\n // so we skip the first invocation. This is critical because child hooks\n // (e.g., useFrontendTool, useHumanInTheLoop) register tools dynamically\n // via addTool()/setRenderToolCalls() in their own effects, which fire\n // BEFORE parent effects (React fires effects bottom-up). If the parent\n // setter effects ran on mount, they would overwrite the children's tools.\n const didMountRef = useRef(false);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setTools(allTools);\n }, [copilotkit, allTools]);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setRenderToolCalls(allRenderToolCalls);\n }, [copilotkit, allRenderToolCalls]);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setRenderActivityMessages(allActivityRenderers);\n }, [copilotkit, allActivityRenderers]);\n\n useEffect(() => {\n if (!didMountRef.current) return;\n copilotkit.setRenderCustomMessages(renderCustomMessagesList);\n }, [copilotkit, renderCustomMessagesList]);\n\n // Mark mount complete — must be declared AFTER the setter effects\n // so it runs last in the effect queue on the initial mount cycle. Reset on\n // cleanup, so a remount (StrictMode) or a replacement core skips the setters\n // again instead of overwriting tools the children just registered.\n useEffect(() => {\n didMountRef.current = true;\n return () => {\n didMountRef.current = false;\n };\n }, [copilotkit]);\n\n // Register the design skill and the sandbox functions as agent context for\n // the generateSandboxedUi tool (entries shared with Vue and Angular).\n const designSkill = openGenerativeUI?.designSkill;\n useLayoutEffect(() => {\n if (!copilotkit || !openGenUIActive) return;\n return ɵaddOpenGenerativeUIContexts(copilotkit, {\n designSkill,\n sandboxFunctions: sandboxFunctionsList,\n });\n }, [copilotkit, designSkill, sandboxFunctionsList, openGenUIActive]);\n\n const contextValue = useMemo<CopilotKitContextValue>(\n () => ({\n copilotkit,\n executingToolCallIds,\n showIntelligenceIndicator,\n }),\n [copilotkit, executingToolCallIds, showIntelligenceIndicator],\n );\n\n // License context and banner, driven by the license authority the runtime\n // reports through /info.\n const licenseState = useMemo(\n () =>\n ɵresolveLicenseState({\n status: runtimeLicenseStatus,\n entitlements: runtimeEntitlements,\n retryPending: runtimeEntitlementRetryPending,\n publicKey: resolvedPublicKey,\n }),\n [\n runtimeLicenseStatus,\n runtimeEntitlements,\n runtimeEntitlementRetryPending,\n resolvedPublicKey,\n ],\n );\n const styleOptions = useMemo(\n () => ({ nonce, inject: injectStyles }),\n [nonce, injectStyles],\n );\n\n return (\n <CopilotStyleOptionsProvider value={styleOptions}>\n <SandboxFunctionsContext.Provider value={sandboxFunctionsList}>\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseState.context}>\n {generativeUIActive && <GenerativeUIToolCallRenderer />}\n <MarkdownRendererProvider renderer={markdownRenderer}>\n <CopilotKitInspectorContextProvider value={inspectorContextValue}>\n {/*\n Publish the provider-level agent default. This is a bare string\n context, NOT a `CopilotChatConfigurationProvider`: that provider\n also owns a thread, so wrapping the application in one would give\n every descendant chat the same inherited threadId. See the\n `CopilotKitAgentIdContext` comment in `../context`.\n */}\n <CopilotKitAgentIdContext.Provider value={agentId}>\n <GenerativeUIRuntimeContext.Provider\n value={generativeUIRuntime}\n >\n {children}\n </GenerativeUIRuntimeContext.Provider>\n </CopilotKitAgentIdContext.Provider>\n {shouldRenderInspector ? (\n <CopilotKitInspector\n core={copilotkit}\n openRequest={inspectorOpenRequest}\n onVisibilityChange={setInspectorVisible}\n />\n ) : null}\n </CopilotKitInspectorContextProvider>\n </MarkdownRendererProvider>\n {/* License warnings — driven by server-reported status */}\n {licenseState.bannerType && (\n <LicenseWarningBanner type={licenseState.bannerType} />\n )}\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n </SandboxFunctionsContext.Provider>\n </CopilotStyleOptionsProvider>\n );\n};\n\n/**\n * Alias of {@link CopilotKitProvider}: the same component under its v1 name,\n * so `<CopilotKit>` keeps working. `CopilotKitProvider` is the preferred name.\n *\n * @alias\n */\nexport const CopilotKit = CopilotKitProvider;\n\n/**\n * Alias of {@link CopilotKitProviderProps}, the props of {@link CopilotKit}.\n * Prefer `CopilotKitProviderProps` in new code.\n */\nexport type CopilotKitProps = CopilotKitProviderProps;\n\n// Re-export useCopilotKit from context for backward compatibility\nexport { useCopilotKit } from \"../context\";\n","import {\n ɵgetCustomMessageRenderProps,\n ɵresolveCustomMessageRenderContext,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration, useCopilotKit } from \"../providers\";\nimport type { ReactCustomMessageRendererPosition } from \"../types/react-custom-message-renderer\";\nimport type { Message } from \"@ag-ui/core\";\n\ninterface UseRenderCustomMessagesParams {\n message: Message;\n position: ReactCustomMessageRendererPosition;\n}\n\nexport function useRenderCustomMessages() {\n const { copilotkit } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n\n if (!config) {\n return null;\n }\n\n const { threadId } = config;\n const { agentId, renderers: customMessageRenderers } =\n ɵresolveCustomMessageRenderContext(\n copilotkit.renderCustomMessages,\n config.agentId,\n );\n\n // No renderer can ever produce output, so hand the caller nothing rather\n // than a function that always returns null. Callers gate expensive work\n // (per-message state-snapshot cloning, memo wrappers) on this being truthy.\n if (!customMessageRenderers.length) {\n return null;\n }\n\n return function (params: UseRenderCustomMessagesParams) {\n const { message, position } = params;\n const agent = copilotkit.getAgent(agentId);\n if (!agent) {\n return null;\n }\n const props = ɵgetCustomMessageRenderProps(copilotkit, {\n agentId,\n threadId,\n agent,\n message,\n position,\n });\n\n // Try each renderer in order and show the first that draws something.\n let result = null;\n for (const renderer of customMessageRenderers) {\n if (!renderer.render) {\n continue;\n }\n const Component = renderer.render;\n result = (\n <Component\n key={`${props.runId}-${message.id}-${position}`}\n {...props}\n />\n );\n if (result) {\n break;\n }\n }\n return result;\n };\n}\n","import type { ActivityMessage } from \"@ag-ui/core\";\nimport {\n ɵdescribeActivityRendererFailure,\n ɵfindActivityRenderer,\n ɵmatchActivityRenderer,\n ɵresolveAgentId,\n} from \"@copilotkit/core\";\nimport { useDefaultAgentId } from \"../context\";\nimport { useCopilotKit, useCopilotChatConfiguration } from \"../providers\";\nimport { useCallback, useMemo } from \"react\";\nimport type { ReactActivityMessageRenderer } from \"../types\";\n\nexport function useRenderActivityMessage() {\n const { copilotkit } = useCopilotKit();\n // The chat's agent, else the provider's default agent.\n const agentId = ɵresolveAgentId({\n chatAgentId: useCopilotChatConfiguration()?.agentId,\n providerAgentId: useDefaultAgentId(),\n });\n\n const renderers = copilotkit.renderActivityMessages;\n\n // Find the renderer for a given activity type\n const findRenderer = useCallback(\n (activityType: string): ReactActivityMessageRenderer<unknown> | null =>\n ɵfindActivityRenderer(renderers, { activityType, agentId }),\n [agentId, renderers],\n );\n\n const renderActivityMessage = useCallback(\n (message: ActivityMessage): React.ReactElement | null => {\n const match = ɵmatchActivityRenderer(renderers, {\n activityType: message.activityType,\n agentId,\n content: message.content,\n });\n\n if (!match.ok) {\n // Explain why a message that has a renderer drew nothing.\n const warning = ɵdescribeActivityRendererFailure(\n message.activityType,\n match,\n );\n if (warning) {\n console.warn(warning.message, ...warning.details);\n }\n return null;\n }\n\n const Component = match.renderer.render;\n const agent = copilotkit.getAgent(agentId);\n\n return (\n <Component\n key={message.id}\n activityType={message.activityType}\n content={match.content}\n message={message}\n agent={agent}\n />\n );\n },\n [agentId, copilotkit, renderers],\n );\n\n return useMemo(\n () => ({ renderActivityMessage, findRenderer }),\n [renderActivityMessage, findRenderer],\n );\n}\n","import { useRef } from \"react\";\n\n/**\n * Deps comparison shared by `useFrontendTool` (and through it\n * `useHumanInTheLoop` and `useComponent`) and `useRenderTool`. Not part of the\n * public API.\n */\n\nconst EMPTY_DEPS: ReadonlyArray<unknown> = [];\n\nfunction isPlainObject(value: object): boolean {\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Plain data (primitives, plain objects, arrays, dates) compares by value.\n * Functions always compare equal: these hooks used to compare\n * `JSON.stringify(deps)`, which turns every function into `null`, and a\n * function that counted as changed would re-register on every render when it\n * is written inline (and loop in a component that also reads\n * `useRenderToolCall`). Everything else (class instances, maps, sets) compares\n * by identity. A cycle inside plain data is safe: a pair already being\n * compared counts as equal for that branch.\n */\nfunction depEqual(a: unknown, b: unknown, seen: Map<object, object>): boolean {\n if (Object.is(a, b)) return true;\n if (typeof a === \"function\" && typeof b === \"function\") return true;\n if (\n typeof a !== \"object\" ||\n typeof b !== \"object\" ||\n a === null ||\n b === null\n ) {\n return false;\n }\n if (a instanceof Date && b instanceof Date) {\n return Object.is(a.getTime(), b.getTime());\n }\n const aIsArray = Array.isArray(a);\n if (aIsArray !== Array.isArray(b)) return false;\n if (!aIsArray && !(isPlainObject(a) && isPlainObject(b))) return false;\n\n if (seen.get(a) === b) return true;\n seen.set(a, b);\n\n if (aIsArray) {\n const left = a as unknown[];\n const right = b as unknown[];\n if (left.length !== right.length) return false;\n for (let i = 0; i < left.length; i++) {\n if (!depEqual(left[i], right[i], seen)) return false;\n }\n return true;\n }\n\n const left = a as Record<string, unknown>;\n const right = b as Record<string, unknown>;\n const leftKeys = Object.keys(left);\n if (leftKeys.length !== Object.keys(right).length) return false;\n for (const key of leftKeys) {\n if (!Object.prototype.hasOwnProperty.call(right, key)) return false;\n if (!depEqual(left[key], right[key], seen)) return false;\n }\n return true;\n}\n\n/** Whether two deps arrays are equal. A change in length is always a change. */\nexport function depsEqual(\n prev: ReadonlyArray<unknown>,\n next: ReadonlyArray<unknown>,\n): boolean {\n if (prev.length !== next.length) return false;\n const seen = new Map<object, object>();\n for (let i = 0; i < prev.length; i++) {\n if (!depEqual(prev[i], next[i], seen)) return false;\n }\n return true;\n}\n\n/**\n * Turns a caller's `deps` array into a number that changes exactly when the\n * deps change, by the rules of {@link depsEqual}. Put the number, not the\n * array, in the registration effect's dependency list: that keeps the list a\n * constant length and never serializes a value.\n */\nexport function useDepsVersion(deps?: ReadonlyArray<unknown>): number {\n const next = deps ?? EMPTY_DEPS;\n const ref = useRef({ deps: next, version: 0 });\n if (ref.current.deps !== next && !depsEqual(ref.current.deps, next)) {\n ref.current = { deps: next, version: ref.current.version + 1 };\n }\n return ref.current.version;\n}\n","import { useLayoutEffect } from \"react\";\nimport { ɵregisterFrontendTools } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport { useDepsVersion } from \"./tool-registration\";\n\n/**\n * Register a frontend tool while the component is mounted. The agent can\n * call it, and its `render` component draws the call in the chat.\n *\n * A tool with the same name and agentId as a tool that is already registered\n * (for example one from the provider's `tools`) overrides it while this\n * component is mounted. When the component unmounts, the overridden tool is\n * active again. The renderer stays registered after unmount, so past tool\n * calls still render in the chat history.\n *\n * @param tool - The tool to register.\n * @param deps - Extra values that re-register the tool when they change. Use\n * it when the handler closes over a value that is not part of the tool.\n *\n * @example\n * ```tsx\n * useFrontendTool({\n * name: \"showWeather\",\n * description: \"Show the weather for a city\",\n * parameters: z.object({ city: z.string() }),\n * handler: async ({ city }) => `Sunny in ${city}`,\n * });\n * ```\n */\nexport function useFrontendTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(tool: ReactFrontendTool<T>, deps?: ReadonlyArray<unknown>) {\n const { copilotkit } = useCopilotKit();\n // Plain data in `deps` compares by value, everything else by identity; see\n // useDepsVersion. Only the resulting number enters the effect's dependency\n // list, so `deps` is never serialized and may hold a circular value such as\n // the agent from useAgent.\n const depsVersion = useDepsVersion(deps);\n\n useLayoutEffect(() => {\n // This registration hides any tool with the same name and agentId (a\n // provider tool or another hook) until this effect cleans up. Unregistering\n // brings the hidden tool back. The renderer stays registered so past calls\n // still render in the chat history.\n return ɵregisterFrontendTools(copilotkit, [tool], (renderer) =>\n copilotkit.addHookRenderToolCall(renderer),\n );\n // Depend on stable keys by default and allow callers to opt into\n // additional dependencies for dynamic tool configuration.\n // tool.available is included so toggling availability re-registers the tool.\n // tool.webmcp is compared by value (it is commonly an object literal), so\n // a changed WebMCP config re-registers without churning on identity.\n }, [\n tool.name,\n tool.available,\n copilotkit,\n depsVersion,\n JSON.stringify(tool.webmcp ?? null),\n ]);\n}\n","import { useLayoutEffect } from \"react\";\nimport { ɵregisterFrontendTools } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\n\nconst EMPTY_DEPS: ReadonlyArray<unknown> = [];\nconst EMPTY_TOOLS: ReadonlyArray<ReactFrontendTool<any>> = [];\n\n/**\n * Register a list of frontend tools whose length can change between renders.\n *\n * `useFrontendTool` registers exactly one tool per call, so it cannot be called\n * in a loop over a runtime-length list without breaking the rules of hooks.\n * This hook runs a single effect over the whole array instead, which makes it\n * safe to build the list from state, props, or a server response.\n *\n * Tools are keyed by `name` plus `agentId`, the same as `useFrontendTool`. A\n * tool that disappears from the array is unregistered on the next render, and\n * every tool is unregistered on unmount. A listed tool hides a tool with the\n * same name and agentId (for example one from the provider's `tools`) until it\n * is unregistered, and then the hidden tool is active again. Renderers stay\n * registered after unmount so past tool calls still render in the chat history.\n *\n * @param tools - The tools to register. May be empty and may change length.\n * @param deps - Extra dependencies that force re-registration, compared by\n * identity like the second argument of `useEffect`. Use this when a handler\n * closes over a value that is not part of the tool definition. Keep the array\n * a constant length across renders.\n *\n * @example\n * Register one tool per item in application state:\n * ```tsx\n * const [reports, setReports] = useState<Report[]>([]);\n *\n * useFrontendTools(\n * reports.map((report) => ({\n * name: `open_${report.id}`,\n * description: `Open the ${report.title} report`,\n * handler: async () => navigate(`/reports/${report.id}`),\n * })),\n * [navigate],\n * );\n * ```\n *\n * @example\n * Register tools described by the backend:\n * ```tsx\n * const { data } = useQuery(fetchToolDescriptors);\n *\n * useFrontendTools(\n * (data ?? []).map((descriptor) => ({\n * name: descriptor.name,\n * description: descriptor.description,\n * parameters: z.object({ query: z.string() }),\n * handler: async ({ query }) => runDescriptor(descriptor.id, query),\n * })),\n * );\n * ```\n */\nexport function useFrontendTools(\n tools: ReadonlyArray<ReactFrontendTool<any>> | undefined,\n deps?: ReadonlyArray<unknown>,\n) {\n const { copilotkit } = useCopilotKit();\n const toolList = tools ?? EMPTY_TOOLS;\n const extraDeps = deps ?? EMPTY_DEPS;\n\n // The array is usually built inline, so its identity changes on every render\n // and cannot be a dependency. Derive a value signature from the fields that\n // decide what the agent sees, so the effect re-runs when the set of tools\n // actually changes and not merely when the caller re-renders.\n //\n // `description` is in the signature even though useFrontendTool does not key\n // on it. A singular caller writes a literal description, so it never changes\n // without the component re-mounting. This hook exists to build tools from\n // data, where the description is usually derived from that data, and a\n // description the agent reads must not go stale while the names stay put.\n const signature = JSON.stringify(\n toolList.map((tool) => [\n tool.name,\n tool.description ?? null,\n tool.agentId ?? null,\n tool.available ?? null,\n tool.webmcp ?? null,\n ]),\n );\n\n useLayoutEffect(() => {\n // Core collapses duplicate names so the last entry wins (as with\n // useFrontendTool), hides earlier tools with the same name and agentId\n // until cleanup, and keeps renderers so past calls still render. The\n // cleanup removes exactly what this run registered: reading the current\n // array would miss a tool dropped before the effect re-ran.\n return ɵregisterFrontendTools(copilotkit, toolList, (renderer) =>\n copilotkit.addHookRenderToolCall(renderer),\n );\n // `signature` is the value-based key for `toolList`, so the array itself is\n // deliberately not a dependency. `available` and `webmcp` are folded into\n // the signature for the same reasons they are dependencies of\n // useFrontendTool: toggling either must re-register the tool.\n //\n // `deps` is spread rather than stringified. JSON.stringify maps a function\n // to null, so a stringified `[navigate]` is the constant \"[null]\", and a\n // changed callback would never re-register. That is exactly the case `deps`\n // exists to cover. Spreading gives the entries React's own identity\n // comparison, the same contract as the second argument of useEffect. Pass a\n // deps array of a constant length, as React requires everywhere else.\n }, [signature, copilotkit, ...extraDeps]);\n}\n","import type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport { ɵcomponentToolDescription } from \"@copilotkit/core\";\nimport type { ComponentType } from \"react\";\nimport { useFrontendTool } from \"./use-frontend-tool\";\n\ntype InferRenderProps<T> = T extends StandardSchemaV1\n ? InferSchemaOutput<T>\n : any;\n\n/**\n * Registers a React component as a frontend tool renderer in chat.\n *\n * This hook is a convenience wrapper around `useFrontendTool` that:\n * - builds a model-facing tool description,\n * - forwards optional schema parameters (any Standard Schema V1 compatible library),\n * - renders your component with tool call parameters.\n *\n * Use this when you want to display a typed visual component for a tool call\n * without manually wiring a full frontend tool object.\n *\n * When `parameters` is provided, render props are inferred from the schema.\n * When omitted, the render component may accept any props.\n *\n * @typeParam TSchema - Schema describing tool parameters, or `undefined` when no schema is given.\n * @param config - Tool registration config.\n * @param deps - Optional dependencies to refresh registration (same semantics as `useEffect`).\n *\n * @example\n * ```tsx\n * // Without parameters — render accepts any props\n * useComponent({\n * name: \"showGreeting\",\n * render: ({ message }: { message: string }) => <div>{message}</div>,\n * });\n * ```\n *\n * @example\n * ```tsx\n * // With parameters — render props inferred from schema\n * useComponent({\n * name: \"showWeatherCard\",\n * parameters: z.object({ city: z.string() }),\n * render: ({ city }) => <div>{city}</div>,\n * });\n * ```\n *\n * @example\n * ```tsx\n * useComponent(\n * {\n * name: \"renderProfile\",\n * parameters: z.object({ userId: z.string() }),\n * render: ProfileCard,\n * agentId: \"support-agent\",\n * },\n * [selectedAgentId],\n * );\n * ```\n */\nexport function useComponent<\n TSchema extends StandardSchemaV1<any, Record<string, unknown>> | undefined =\n undefined,\n>(\n config: {\n name: string;\n description?: string;\n parameters?: TSchema;\n render: ComponentType<NoInfer<InferRenderProps<TSchema>>>;\n agentId?: string;\n followUp?: boolean;\n },\n deps?: ReadonlyArray<unknown>,\n): void {\n const fullDescription = ɵcomponentToolDescription(\n config.name,\n config.description,\n );\n\n useFrontendTool(\n {\n name: config.name,\n description: fullDescription,\n parameters: config.parameters,\n render: ({ args }: { args: unknown }) => {\n const Component = config.render;\n return <Component {...(args as InferRenderProps<TSchema>)} />;\n },\n agentId: config.agentId,\n followUp: config.followUp,\n },\n deps,\n );\n}\n","import { useEffect } from \"react\";\nimport type { StandardSchemaV1, InferSchemaOutput } from \"@copilotkit/shared\";\nimport { ToolCallStatus } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport { defineToolCallRenderer } from \"../types/defineToolCallRenderer\";\nimport { useDepsVersion } from \"./tool-registration\";\n\nexport interface RenderToolInProgressProps<S extends StandardSchemaV1> {\n name: string;\n toolCallId: string;\n parameters: Partial<InferSchemaOutput<S>>;\n status: \"inProgress\";\n result: undefined;\n}\n\nexport interface RenderToolExecutingProps<S extends StandardSchemaV1> {\n name: string;\n toolCallId: string;\n parameters: InferSchemaOutput<S>;\n status: \"executing\";\n result: undefined;\n}\n\nexport interface RenderToolCompleteProps<S extends StandardSchemaV1> {\n name: string;\n toolCallId: string;\n parameters: InferSchemaOutput<S>;\n status: \"complete\";\n result: string;\n}\n\nexport type RenderToolProps<S extends StandardSchemaV1> =\n | RenderToolInProgressProps<S>\n | RenderToolExecutingProps<S>\n | RenderToolCompleteProps<S>;\n\ntype RenderToolConfig<S extends StandardSchemaV1> = {\n name: string;\n parameters?: S;\n render: (props: RenderToolProps<S>) => React.ReactElement | null;\n agentId?: string;\n group?: boolean;\n};\n\n/**\n * Registers a wildcard (`\"*\"`) renderer for tool calls.\n *\n * The wildcard renderer is used as a fallback when no exact name-matched\n * renderer is registered for a tool call.\n *\n * @param config - Wildcard renderer configuration.\n * @param deps - Optional dependencies to refresh registration.\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"*\",\n * render: ({ name, status }) => (\n * <div>\n * {status === \"complete\" ? \"✓\" : \"⏳\"} {name}\n * </div>\n * ),\n * },\n * [],\n * );\n * ```\n */\nexport function useRenderTool(\n config: {\n name: \"*\";\n render: (props: any) => React.ReactElement | null;\n agentId?: string;\n /** Let the chat group the calls this renderer draws (see `toolCallDisplay`). */\n group?: boolean;\n },\n deps?: ReadonlyArray<unknown>,\n): void;\n\n/**\n * Registers a name-scoped renderer for tool calls.\n *\n * The provided `parameters` schema defines the typed shape of `props.parameters`\n * in `render` for `executing` and `complete` states. Accepts any Standard Schema V1\n * compatible library (Zod, Valibot, ArkType, etc.).\n *\n * @typeParam S - Schema type describing tool call parameters.\n * @param config - Named renderer configuration.\n * @param deps - Optional dependencies to refresh registration.\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"searchDocs\",\n * parameters: z.object({ query: z.string() }),\n * render: ({ status, parameters, result }) => {\n * if (status === \"inProgress\") return <div>Preparing...</div>;\n * if (status === \"executing\") return <div>Searching {parameters.query}</div>;\n * return <div>{result}</div>;\n * },\n * },\n * [],\n * );\n * ```\n */\nexport function useRenderTool<S extends StandardSchemaV1>(\n config: {\n name: string;\n parameters: S;\n render: (props: RenderToolProps<S>) => React.ReactElement | null;\n agentId?: string;\n /** Let the chat group the calls this renderer draws (see `toolCallDisplay`). */\n group?: boolean;\n },\n deps?: ReadonlyArray<unknown>,\n): void;\n\n/**\n * Registers a renderer entry in CopilotKit's `renderToolCalls` registry.\n *\n * Key behavior:\n * - deduplicates by `agentId:name` (latest registration wins),\n * - keeps renderer entries on cleanup so historical chat tool calls can still render,\n * - refreshes registration when `deps` change.\n *\n * @typeParam S - Schema type describing tool call parameters.\n * @param config - Renderer config for wildcard or named tools.\n * @param deps - Optional dependencies to refresh registration.\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"searchDocs\",\n * parameters: z.object({ query: z.string() }),\n * render: ({ status, parameters, result }) => {\n * if (status === \"executing\") return <div>Searching {parameters.query}</div>;\n * if (status === \"complete\") return <div>{result}</div>;\n * return <div>Preparing...</div>;\n * },\n * },\n * [],\n * );\n * ```\n *\n * @example\n * ```tsx\n * useRenderTool(\n * {\n * name: \"summarize\",\n * parameters: z.object({ text: z.string() }),\n * agentId: \"research-agent\",\n * render: ({ name, status }) => <div>{name}: {status}</div>,\n * },\n * [selectedAgentId],\n * );\n * ```\n */\nexport function useRenderTool<S extends StandardSchemaV1>(\n config: RenderToolConfig<S>,\n deps?: ReadonlyArray<unknown>,\n): void {\n const { copilotkit } = useCopilotKit();\n // Plain data in `deps` compares by value, everything else by identity; see\n // useDepsVersion. `deps` is never serialized, so it may hold a circular\n // value such as the agent from useAgent.\n const depsVersion = useDepsVersion(deps);\n\n useEffect(() => {\n // Build the ReactToolCallRenderer via defineToolCallRenderer\n const renderer =\n config.name === \"*\" && !config.parameters\n ? defineToolCallRenderer({\n name: \"*\",\n render: (props) =>\n config.render({ ...props, parameters: props.args }),\n ...(config.agentId ? { agentId: config.agentId } : {}),\n group: config.group,\n })\n : defineToolCallRenderer({\n name: config.name,\n args: config.parameters!,\n // Branch per status so the discriminated union stays correlated\n // when `args` is re-exposed as `parameters`.\n render: (props) => {\n if (props.status === ToolCallStatus.InProgress) {\n return config.render({ ...props, parameters: props.args });\n }\n if (props.status === ToolCallStatus.Executing) {\n return config.render({ ...props, parameters: props.args });\n }\n return config.render({ ...props, parameters: props.args });\n },\n ...(config.agentId ? { agentId: config.agentId } : {}),\n group: config.group,\n });\n\n copilotkit.addHookRenderToolCall(renderer);\n\n // No cleanup removal — keeps renderer for chat history, same as useFrontendTool\n }, [config.name, config.group, copilotkit, depsVersion]);\n}\n","import React, {\n createContext,\n useId,\n useLayoutEffect,\n useRef,\n useState,\n} from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport {\n CopilotChatDefaultLabels,\n ɵTOOL_CALL_STATUS_ICONS,\n ɵTOOL_CALL_STATUS_LABEL_KEYS,\n ɵcountFailedToolCalls,\n ɵformatLabel,\n ɵformatToolNames,\n ɵgetArgumentPreview,\n ɵgetToolCallGroupState,\n ɵstringifyToolCallPayload,\n ɵformatCountLabel,\n} from \"@copilotkit/core\";\nimport type {\n ToolCallEntry,\n ɵToolCallGroupAppearance,\n ɵToolCallRowStatus,\n} from \"@copilotkit/core\";\nimport { cn } from \"../../lib/utils\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\nexport type CopilotChatToolCallGroupAppearance = ɵToolCallGroupAppearance;\n\n/**\n * Set by a group around the calls it shows, so CopilotKit's built-in tool card\n * draws itself as a compact row that fits the group instead of a card.\n * @internal\n */\nexport const ToolCallGroupContext = createContext<{\n appearance: CopilotChatToolCallGroupAppearance;\n failedIds: ReadonlySet<string>;\n /** Each call's row status, by call id. */\n statusById: ReadonlyMap<string, ɵToolCallRowStatus>;\n /** The agent may still finish the group's calls; see `isActive`. */\n active: boolean;\n} | null>(null);\n\n/** The chat labels from the nearest chat configuration, or the defaults. */\nfunction useLabels() {\n const config = useCopilotChatConfiguration();\n return config?.labels ?? CopilotChatDefaultLabels;\n}\n\n/**\n * Height transition between closed and its content's height. Closed content\n * stays mounted (so its state survives) but is inert.\n * @internal\n */\nexport function Collapsible({\n open,\n id,\n className,\n children,\n}: {\n open: boolean;\n id?: string;\n className?: string;\n children: React.ReactNode;\n}) {\n // React only treats `inert` as a prop from 19 on, so set the attribute\n // directly to keep closed content out of the tab order on React 18 too.\n const ref = useRef<HTMLDivElement>(null);\n useLayoutEffect(() => {\n ref.current?.toggleAttribute(\"inert\", !open);\n }, [open]);\n\n return (\n <div\n ref={ref}\n id={id}\n className={cn(\"cpk-collapsible\", className)}\n style={{ gridTemplateRows: open ? \"1fr\" : \"0fr\" }}\n >\n <div className=\"cpk-collapsible-content\">{children}</div>\n </div>\n );\n}\n\nfunction StatusIcon({\n status,\n className,\n}: {\n status: ɵToolCallRowStatus;\n className?: string;\n}) {\n return (\n <CopilotIcon\n name={ɵTOOL_CALL_STATUS_ICONS[status]}\n aria-hidden=\"true\"\n className={cn(\n \"cpk-tool-call-status-icon\",\n status === \"running\" && \"cpk-tool-call-status-icon-running\",\n status === \"failed\" && \"cpk-tool-call-status-icon-failed\",\n className,\n )}\n />\n );\n}\n\nfunction Chevron({ open, className }: { open: boolean; className?: string }) {\n return (\n <CopilotIcon\n name=\"ChevronRight\"\n aria-hidden=\"true\"\n className={cn(\n \"cpk-tool-call-chevron\",\n open && \"cpk-tool-call-chevron-open\",\n className,\n )}\n />\n );\n}\n\nfunction FailedCount({ calls }: { calls: ToolCallEntry[] }) {\n const labels = useLabels();\n const failed = ɵcountFailedToolCalls(calls);\n if (!failed) return null;\n return (\n <span className=\"cpk-tool-call-failed-count\">\n {ɵformatLabel(labels.toolCallFailedCountLabel, { count: failed })}\n </span>\n );\n}\n\nfunction Payload({ label, value }: { label: string; value: unknown }) {\n return (\n <div>\n <div className=\"cpk-tool-call-payload-label\">{label}</div>\n <pre className=\"cpk-tool-call-payload-code\">\n {ɵstringifyToolCallPayload(value)}\n </pre>\n </div>\n );\n}\n\n/**\n * A tool call's arguments and, once it has one, its result.\n * @internal\n */\nexport function ToolCallPayloads({\n parameters,\n result,\n className,\n}: {\n parameters: unknown;\n result: string | undefined;\n className?: string;\n}) {\n const labels = useLabels();\n return (\n <div className={cn(\"cpk-tool-call-payloads\", className)}>\n <Payload label={labels.toolCallArgumentsLabel} value={parameters ?? {}} />\n {result !== undefined && (\n <Payload label={labels.toolCallResultLabel} value={result} />\n )}\n </div>\n );\n}\n\n/**\n * The built-in tool card drawn as a row inside a group: status, name and main\n * argument, opening to the payloads.\n * @internal\n */\nexport function ToolCallRow({\n name,\n parameters,\n result,\n status,\n appearance,\n className,\n ...props\n}: {\n name: string;\n parameters: unknown;\n result: string | undefined;\n status: ɵToolCallRowStatus;\n appearance: \"card\" | \"line\" | \"stack\";\n} & React.HTMLAttributes<HTMLDivElement>) {\n const labels = useLabels();\n const [open, setOpen] = useState(false);\n const detailsId = useId();\n const preview = ɵgetArgumentPreview(parameters);\n\n return (\n <div\n data-copilotkit\n // Rows draw their own divider: interaction capture can wrap each call\n // in a `display: contents` element, which a parent's divide-y misses.\n className={cn(\n \"cpk-tool-call-row\",\n `cpk-tool-call-row-${appearance}`,\n className,\n )}\n {...props}\n >\n <button\n type=\"button\"\n aria-expanded={open}\n aria-controls={detailsId}\n onClick={() => setOpen((value) => !value)}\n className=\"cpk-tool-call-row-button\"\n >\n <StatusIcon status={status} />\n <span\n data-testid=\"copilot-tool-render-name\"\n className={cn(\n \"cpk-tool-call-row-name\",\n status === \"running\" && \"cpk-shimmer\",\n )}\n >\n {name}\n </span>\n {preview && (\n <span className=\"cpk-tool-call-row-preview\">{preview}</span>\n )}\n <span\n data-testid=\"copilot-tool-render-status\"\n className=\"cpk-tool-call-row-status\"\n >\n {labels[ɵTOOL_CALL_STATUS_LABEL_KEYS[status]]}\n </span>\n <Chevron open={open} className=\"cpk-tool-call-row-chevron\" />\n </button>\n <Collapsible open={open} id={detailsId}>\n <ToolCallPayloads\n parameters={parameters}\n result={result}\n className=\"cpk-tool-call-row-payloads\"\n />\n </Collapsible>\n </div>\n );\n}\n\nexport interface CopilotChatToolCallGroupProps extends Omit<\n React.HTMLAttributes<HTMLDivElement>,\n \"children\"\n> {\n /** The calls in the group, in order. */\n calls: ToolCallEntry[];\n /** Renders one call through the registered renderers. */\n renderCall: (call: ToolCallEntry) => React.ReactNode;\n /**\n * - `\"card\"` (default): one card with a summary header and a row per call.\n * - `\"line\"`: a quiet line of text that opens to a list of rows.\n * - `\"stack\"`: the latest call on a stack of the earlier ones.\n */\n appearance?: CopilotChatToolCallGroupAppearance;\n /** The agent is running and nothing follows the group, so more calls may join it. */\n isActive?: boolean;\n}\n\n/**\n * Tool calls made in a row, collapsed into one summary. While a call runs the\n * summary names it (\"Running read_file src/app.ts\"); once they're all done it\n * reads \"Used 3 tools\" and opens to the calls.\n *\n * Each call is drawn by its registered renderer. CopilotKit's built-in card\n * (`useDefaultRenderTool`) draws a compact row inside the card and line\n * appearances and an open stack; a custom wildcard renderer draws whatever it\n * draws.\n */\nexport function CopilotChatToolCallGroup({\n calls,\n renderCall,\n appearance = \"card\",\n isActive = false,\n className,\n ...props\n}: CopilotChatToolCallGroupProps) {\n const labels = useLabels();\n const [open, setOpen] = useState(false);\n const bodyId = useId();\n const {\n latest,\n current,\n preview,\n done,\n failedIds,\n statusById,\n status,\n behind,\n latestStatus,\n latestPreview,\n } = ɵgetToolCallGroupState(calls, isActive, open);\n if (!latest) return null;\n const groupContext = { failedIds, statusById, active: isActive };\n\n const rows = (rowAppearance: \"card\" | \"line\") => (\n <ToolCallGroupContext.Provider\n value={{ ...groupContext, appearance: rowAppearance }}\n >\n {calls.map((call) => (\n <React.Fragment key={call.toolCall.id}>\n {renderCall(call)}\n </React.Fragment>\n ))}\n </ToolCallGroupContext.Provider>\n );\n\n const groupProps = {\n \"data-copilotkit\": true,\n \"data-testid\": \"copilot-tool-call-group\",\n \"data-appearance\": appearance,\n \"data-state\": status,\n ...props,\n };\n\n const runningLabel = current && (\n <>\n <span className=\"cpk-tool-call-group-running cpk-shimmer\">\n {ɵformatLabel(labels.toolCallRunningLabel, {\n name: current.toolCall.function.name,\n })}\n </span>\n {preview && (\n <span className=\"cpk-tool-call-group-preview\">{preview}</span>\n )}\n </>\n );\n\n if (appearance === \"line\") {\n if (calls.length === 1 && !current) {\n return (\n <div\n {...groupProps}\n className={cn(\n \"cpk-tool-call-group cpk-tool-call-group-line cpk-tool-call-group-single\",\n className,\n )}\n >\n <ToolCallGroupContext.Provider\n value={{ ...groupContext, appearance: \"line\" }}\n >\n {renderCall(latest)}\n </ToolCallGroupContext.Provider>\n </div>\n );\n }\n return (\n <div\n {...groupProps}\n className={cn(\n \"cpk-tool-call-group cpk-tool-call-group-line\",\n className,\n )}\n >\n <button\n type=\"button\"\n aria-expanded={open}\n aria-controls={bodyId}\n onClick={() => setOpen((value) => !value)}\n className=\"cpk-tool-call-group-line-toggle\"\n >\n {runningLabel || (\n <>\n <span className=\"cpk-tool-call-group-line-summary\">\n {ɵformatCountLabel(calls.length, {\n one: labels.toolCallUsedToolsOne,\n other: labels.toolCallUsedToolsOther,\n })}\n </span>\n <span className=\"cpk-tool-call-group-line-names\">\n {ɵformatToolNames(calls)}\n </span>\n <FailedCount calls={calls} />\n </>\n )}\n <Chevron open={open} />\n </button>\n <Collapsible open={open} id={bodyId}>\n <div className=\"cpk-tool-call-group-line-body\">{rows(\"line\")}</div>\n </Collapsible>\n </div>\n );\n }\n\n if (appearance === \"stack\") {\n // A lone call is the top card of a stack with nothing behind it yet.\n // One toggle in both states, so it keeps keyboard focus when pressed.\n const layer = \"cpk-tool-call-group-stack-layer\";\n return (\n <div\n {...groupProps}\n className={cn(\n \"cpk-tool-call-group cpk-tool-call-group-stack\",\n className,\n )}\n style={{ paddingBottom: behind * 6, ...props.style }}\n >\n <div className=\"cpk-tool-call-group-stack-pile\">\n {Array.from({ length: behind }, (_, index) => (\n <div\n key={index}\n aria-hidden=\"true\"\n className={cn(layer, \"cpk-tool-call-group-stack-behind\")}\n style={{\n transform: `translateY(${(index + 1) * 6}px) scaleX(${1 - (index + 1) * 0.045})`,\n zIndex: -1 - index,\n opacity: 1 - (index + 1) * 0.28,\n }}\n />\n ))}\n <button\n type=\"button\"\n aria-expanded={open}\n aria-controls={open ? bodyId : undefined}\n onClick={() => setOpen((value) => !value)}\n className={cn(\n \"cpk-tool-call-group-stack-toggle\",\n open\n ? \"cpk-tool-call-group-stack-toggle-open\"\n : [layer, \"cpk-tool-call-group-stack-toggle-closed\"],\n )}\n >\n {open ? (\n <>\n {ɵformatCountLabel(calls.length, {\n one: labels.toolCallToolCallCountOne,\n other: labels.toolCallToolCallCountOther,\n })}\n <FailedCount calls={calls} />\n <span className=\"cpk-tool-call-group-stack-collapse\">\n {labels.toolCallCollapseLabel}\n <Chevron\n open\n className=\"cpk-tool-call-group-stack-collapse-icon\"\n />\n </span>\n </>\n ) : (\n <>\n <span\n key={latest.toolCall.id}\n className=\"cpk-tool-call-group-stack-latest\"\n >\n <StatusIcon status={latestStatus} />\n <span\n className={cn(\n \"cpk-tool-call-group-stack-name\",\n latestStatus === \"running\" && \"cpk-shimmer\",\n )}\n >\n {latest.toolCall.function.name}\n </span>\n {latestPreview && (\n <span className=\"cpk-tool-call-group-stack-preview\">\n {latestPreview}\n </span>\n )}\n {/* The status icon is decorative, so say the status. */}\n <span className=\"cpk-tool-call-group-stack-status\">\n {labels[ɵTOOL_CALL_STATUS_LABEL_KEYS[latestStatus]]}\n </span>\n </span>\n <span className=\"cpk-tool-call-group-stack-meta\">\n <FailedCount calls={calls} />\n <span className=\"cpk-tool-call-group-stack-count\">\n {ɵformatCountLabel(calls.length, {\n one: labels.toolCallCallCountOne,\n other: labels.toolCallCallCountOther,\n })}\n </span>\n <Chevron\n open={false}\n className=\"cpk-tool-call-group-stack-expand-icon\"\n />\n </span>\n </>\n )}\n </button>\n {/* Always mounted, so screen readers hear the closed stack's latest\n call change (\"read_file: Running\", then \"read_file: Done\"); the\n button only names it. */}\n <span aria-live=\"polite\" className=\"cpk-tool-call-group-stack-live\">\n {open\n ? \"\"\n : `${latest.toolCall.function.name}: ${labels[ɵTOOL_CALL_STATUS_LABEL_KEYS[latestStatus]]}`}\n </span>\n </div>\n {open && (\n // Each call gets the collapsed stack's card, easing out of the stack.\n <div id={bodyId} className=\"cpk-tool-call-group-stack-items\">\n <ToolCallGroupContext.Provider\n value={{ ...groupContext, appearance: \"stack\" }}\n >\n {calls.map((call, index) => (\n <div\n key={call.toolCall.id}\n className={cn(layer, \"cpk-tool-call-group-stack-item\")}\n style={{ animationDelay: `${index * 30}ms` }}\n >\n {renderCall(call)}\n </div>\n ))}\n </ToolCallGroupContext.Provider>\n </div>\n )}\n </div>\n );\n }\n\n // card: one call gets the same card as several, so the card a run starts\n // with doesn't change style when the next call joins it.\n return (\n <div\n {...groupProps}\n className={cn(\"cpk-tool-call-group cpk-tool-call-group-card\", className)}\n >\n <button\n type=\"button\"\n aria-expanded={open}\n aria-controls={bodyId}\n onClick={() => setOpen((value) => !value)}\n className=\"cpk-tool-call-group-card-toggle\"\n >\n <StatusIcon status={status} />\n {runningLabel || (\n <>\n <span className=\"cpk-tool-call-group-card-summary\">\n {ɵformatCountLabel(calls.length, {\n one: labels.toolCallUsedToolsOne,\n other: labels.toolCallUsedToolsOther,\n })}\n </span>\n <span className=\"cpk-tool-call-group-card-names\">\n {ɵformatToolNames(calls)}\n </span>\n </>\n )}\n <span className=\"cpk-tool-call-group-card-meta\">\n {status === \"failed\" ? (\n <FailedCount calls={calls} />\n ) : (\n <span className=\"cpk-tool-call-group-card-status\">\n {status !== \"running\"\n ? labels[ɵTOOL_CALL_STATUS_LABEL_KEYS[status]]\n : done > 0 &&\n ɵformatLabel(labels.toolCallDoneCountLabel, { count: done })}\n </span>\n )}\n <Chevron open={open} />\n </span>\n </button>\n <Collapsible open={open} id={bodyId}>\n <div>{rows(\"card\")}</div>\n </Collapsible>\n </div>\n );\n}\n\nexport default CopilotChatToolCallGroup;\n","import React, { useContext, useState } from \"react\";\nimport {\n CopilotChatDefaultLabels,\n ɵadaptDefaultToolCallRenderProps,\n ɵgetToolCallBadge,\n ɵnormalizeToolCallStatus,\n ɵstringifyToolCallAttr,\n ɵstringifyToolCallPayload,\n} from \"@copilotkit/core\";\nimport type {\n ToolCallStatus,\n ɵDefaultToolCallRenderProps,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { useRenderTool } from \"./use-render-tool\";\nimport { cn } from \"../lib/utils\";\nimport {\n ToolCallGroupContext,\n ToolCallRow,\n} from \"../components/chat/CopilotChatToolCallGroup\";\n\n/** What a custom `useDefaultRenderTool` render receives. */\nexport type DefaultRenderProps = ɵDefaultToolCallRenderProps;\n\n/**\n * Shape that `useRenderToolCall` actually invokes a registered `*` renderer\n * with: `{ name, toolCallId, args, status: ToolCallStatus, result }`.\n *\n * `useDefaultRenderTool` accepts user `config.render` typed against the\n * documented {@link DefaultRenderProps}, then wraps it via {@link adaptRendererProps}\n * so the user's function receives the documented shape — not the raw\n * framework-internal one.\n */\ntype RawRendererProps = {\n name: string;\n toolCallId: string;\n args: unknown;\n status: ToolCallStatus;\n result: string | undefined;\n};\n\n/**\n * Convert the framework-internal renderer props (`args`, enum status) into\n * the documented {@link DefaultRenderProps} shape (`parameters`, string-union\n * status) so a user `config.render` always sees the documented contract.\n */\nexport const adaptRendererProps: (\n props: RawRendererProps,\n) => DefaultRenderProps = ɵadaptDefaultToolCallRenderProps;\n\n/**\n * Registers a wildcard (`\"*\"`) tool-call renderer via `useRenderTool`.\n *\n * - Call with no config to use CopilotKit's built-in default tool-call card.\n * - Pass `config.render` to replace the default UI with your own fallback renderer.\n *\n * This is useful when you want a generic renderer for tools that do not have a\n * dedicated `useRenderTool({ name: \"...\" })` registration.\n *\n * @param config - Optional custom wildcard render function.\n * @param deps - Optional dependencies to refresh registration.\n *\n * @example\n * ```tsx\n * useDefaultRenderTool();\n * ```\n *\n * @example\n * ```tsx\n * useDefaultRenderTool({\n * render: ({ name, status }) => <div>{name}: {status}</div>,\n * });\n * ```\n *\n * @example\n * ```tsx\n * useDefaultRenderTool(\n * {\n * render: ({ name, result }) => (\n * <ToolEventRow title={name} payload={result} compact={compactMode} />\n * ),\n * },\n * [compactMode],\n * );\n * ```\n */\nexport function useDefaultRenderTool(\n config?: {\n render?: (props: DefaultRenderProps) => React.ReactElement | null;\n /**\n * Let the chat group calls your `render` draws, like it groups the\n * built-in card's (see `toolCallDisplay` on `CopilotChatMessageView`).\n * Off by default for a custom `render`, since it may draw nothing.\n */\n group?: boolean;\n },\n deps?: ReadonlyArray<unknown>,\n): void {\n const userRender = config?.render;\n\n // When the caller supplies their own render, wrap it so it receives the\n // documented {@link DefaultRenderProps} (parameters, string-union status)\n // even though `useRenderToolCall` invokes the registered render with the\n // framework-internal `{ args, status: ToolCallStatus, ... }` shape.\n const registered: (props: RawRendererProps) => React.ReactElement | null =\n userRender\n ? (raw) => userRender(adaptRendererProps(raw))\n : (raw) => <DefaultToolCallRenderer {...adaptRendererProps(raw)} />;\n\n useRenderTool(\n {\n name: \"*\",\n // `useRenderTool` types the render with the raw framework signature\n // and still requires a `React.ReactElement` return; the wrapper above\n // adapts to the documented shape and may return `null`. We cast through\n // `unknown` to bridge both gaps without `as any`.\n render: registered as unknown as (props: unknown) => React.ReactElement,\n // The built-in card draws a row inside a group; a custom render opts in.\n group: userRender ? config?.group === true : true,\n },\n deps,\n );\n}\n\nexport function DefaultToolCallRenderer({\n name,\n toolCallId,\n parameters,\n status,\n result,\n}: DefaultRenderProps): React.ReactElement {\n const group = useContext(ToolCallGroupContext);\n const labels =\n useCopilotChatConfiguration()?.labels ?? CopilotChatDefaultLabels;\n const [isExpanded, setIsExpanded] = useState(false);\n\n // A status a newer runtime could send reads \"unknown\".\n const cardStatus = ɵnormalizeToolCallStatus(status);\n\n // Inside a group of calls, a row that fits the group instead of a card.\n if (group) {\n return (\n <ToolCallRow\n data-testid=\"copilot-tool-render\"\n data-tool-name={name}\n data-tool-call-id={toolCallId}\n data-status={cardStatus}\n data-args={ɵstringifyToolCallAttr(parameters)}\n data-result={ɵstringifyToolCallAttr(result)}\n name={name}\n parameters={parameters}\n result={result}\n status={group.statusById.get(toolCallId) ?? \"done\"}\n appearance={group.appearance}\n />\n );\n }\n\n // Colors the status dot and badge: running, done, or anything else.\n const { tone, labelKey } = ɵgetToolCallBadge(cardStatus);\n const statusLabel = labels[labelKey];\n\n return (\n <div\n data-testid=\"copilot-tool-render\"\n data-tool-name={name}\n data-tool-call-id={toolCallId}\n data-status={cardStatus}\n data-args={ɵstringifyToolCallAttr(parameters)}\n data-result={ɵstringifyToolCallAttr(result)}\n className=\"cpk-default-tool-call\"\n >\n <div className=\"cpk-default-tool-call-card\">\n {/* Header row — always visible. A real <button> with aria-expanded\n and reset styles so it visually matches the previous <div> but\n is keyboard-accessible (Enter/Space toggle natively). */}\n <button\n type=\"button\"\n aria-expanded={isExpanded}\n onClick={() => setIsExpanded(!isExpanded)}\n className=\"cpk-default-tool-call-header\"\n style={{\n font: \"inherit\",\n }}\n >\n <div className=\"cpk-default-tool-call-title\">\n <svg\n className={cn(\n \"cpk-default-tool-call-chevron\",\n isExpanded && \"cpk-default-tool-call-chevron-open\",\n )}\n fill=\"none\"\n viewBox=\"0 0 24 24\"\n strokeWidth={2}\n stroke=\"currentColor\"\n >\n <path\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n d=\"M8.25 4.5l7.5 7.5-7.5 7.5\"\n />\n </svg>\n <span\n className={`cpk-default-tool-call-dot cpk-default-tool-call-dot-${tone}`}\n />\n <span\n data-testid=\"copilot-tool-render-name\"\n className=\"cpk-default-tool-call-name\"\n >\n {name}\n </span>\n </div>\n\n <span\n data-testid=\"copilot-tool-render-status\"\n className={`cpk-default-tool-call-badge cpk-default-tool-call-badge-${tone}`}\n >\n {statusLabel}\n </span>\n </button>\n\n {/* Expandable details */}\n {isExpanded && (\n <div className=\"cpk-default-tool-call-details\">\n <div>\n <div className=\"cpk-default-tool-call-label\">\n {labels.toolCallArgumentsLabel}\n </div>\n <pre className=\"cpk-default-tool-call-code\">\n {ɵstringifyToolCallPayload(parameters ?? {})}\n </pre>\n </div>\n\n {result !== undefined && (\n <div>\n <div className=\"cpk-default-tool-call-label\">\n {labels.toolCallResultLabel}\n </div>\n <pre className=\"cpk-default-tool-call-code\">\n {ɵstringifyToolCallPayload(result)}\n </pre>\n </div>\n )}\n </div>\n )}\n </div>\n </div>\n );\n}\n","import { useCopilotKit } from \"../context\";\nimport type { ReactFrontendTool } from \"../types/frontend-tool\";\nimport type { ReactHumanInTheLoop } from \"../types/human-in-the-loop\";\nimport type { ReactToolCallRenderer } from \"../types/react-tool-call-renderer\";\nimport { ɵbuildHumanInTheLoopTool, ɵhitlRenderProps } from \"@copilotkit/core\";\nimport { useCallback, useLayoutEffect } from \"react\";\nimport React from \"react\";\nimport { useFrontendTool } from \"./use-frontend-tool\";\n\nexport function useHumanInTheLoop<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(tool: ReactHumanInTheLoop<T>, deps?: ReadonlyArray<unknown>) {\n const { copilotkit } = useCopilotKit();\n // Core parks each call by tool call id, so parallel calls of this tool\n // (or of a \"*\" catch-all) each get their own `respond`.\n const registry = copilotkit.ɵhumanInTheLoop;\n\n const RenderComponent: ReactToolCallRenderer<T>[\"render\"] = useCallback(\n (props) =>\n React.createElement(\n tool.render,\n ɵhitlRenderProps<T, typeof props>(props, tool, registry),\n ),\n // eslint-disable-next-line react-hooks/exhaustive-deps -- tool is a fresh object each render; depend on the fields the renderer reads\n [tool.render, tool.name, tool.description, tool.agentId, registry],\n );\n\n const frontendTool: ReactFrontendTool<T> = {\n ...ɵbuildHumanInTheLoopTool<T>(tool, registry),\n render: RenderComponent,\n };\n\n useFrontendTool(frontendTool, deps);\n\n // Human-in-the-loop tools should remove their renderer on unmount\n // since they can't respond to user interactions anymore.\n //\n // This MUST stay a layout effect to match `useFrontendTool`, which registers\n // the renderer in its own layout effect. React runs every cleanup in a phase\n // before any effect of that same phase, but it runs the whole layout phase\n // ahead of the whole passive phase. If this teardown were passive while the\n // registration is layout, a keyed remount would order the outgoing\n // instance's removal *after* the incoming instance's registration and delete\n // the renderer that had just been added, leaving the tool unrenderable.\n useLayoutEffect(() => {\n return () => {\n copilotkit.removeHookRenderToolCall(tool.name, tool.agentId);\n };\n }, [copilotkit, tool.name, tool.agentId]);\n}\n","import { useCopilotKit, useDefaultAgentId } from \"../context\";\nimport { useMemo, useEffect, useReducer, useSyncExternalStore } from \"react\";\nimport {\n ɵgetAgentResolver,\n ɵresolveAgentId,\n ɵresolveAgentThreadId,\n ɵsubscribeToAgentUpdates,\n ɵvalidateAgentBinding,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\n\nexport enum UseAgentUpdate {\n OnMessagesChanged = \"OnMessagesChanged\",\n OnStateChanged = \"OnStateChanged\",\n OnRunStatusChanged = \"OnRunStatusChanged\",\n}\n\nconst ALL_UPDATES: UseAgentUpdate[] = [\n UseAgentUpdate.OnMessagesChanged,\n UseAgentUpdate.OnStateChanged,\n UseAgentUpdate.OnRunStatusChanged,\n];\n\ninterface UseAgentPropsBase {\n updates?: UseAgentUpdate[];\n /**\n * Throttle interval (in milliseconds) for re-renders triggered by\n * `onMessagesChanged` and `onStateChanged` notifications. Useful to reduce\n * re-render frequency during high-frequency streaming updates.\n *\n * Uses a leading+trailing pattern with a shared window — first update\n * fires immediately, subsequent updates within the window are coalesced,\n * and a trailing timer ensures the most recent update fires after the\n * window expires. See `CopilotKitCore.subscribeToAgentWithOptions` in `@copilotkit/core`\n * for details.\n *\n * Resolved as: `throttleMs ?? provider defaultThrottleMs ?? 0`.\n * Passing `throttleMs={0}` explicitly disables throttling even when the\n * provider specifies a non-zero `defaultThrottleMs`.\n *\n * Run lifecycle callbacks (`onRunInitialized`, `onRunFinalized`,\n * `onRunFailed`, `onRunErrorEvent`) always fire immediately.\n *\n * @default undefined\n * When unset, inherits from the provider's `defaultThrottleMs`;\n * if that is also unset, the effective value is `0` (no throttle).\n */\n throttleMs?: number;\n}\n\n/**\n * Thread-scoped variant. `agentId`, `runtimeAgentId`, and `threadId` are a\n * matched set: together they give this hook a *private* agent — registered\n * under the local `agentId`, routing outbound to `runtimeAgentId` — that is\n * safe to pin a thread onto. None of the three is meaningful without the other\n * two, so all are required here.\n */\ninterface UseAgentThreadScopedProps {\n /**\n * The name to register this hook's proxied agent under.\n *\n * Required, and must not already be taken. The usual fallbacks (the chat\n * configuration's agentId, then `DEFAULT_AGENT_ID`) name agents that already\n * exist, and registering over one either throws `already registered` or\n * silently shadows it, depending on whether runtime discovery has landed — so\n * the caller has to name it.\n */\n agentId: string;\n /**\n * Thread to scope the agent's run to. Written onto the underlying agent, so\n * `/agent/run`, `/agent/connect`, and `/agent/stop` address this thread.\n *\n * REQUIRES `runtimeAgentId`. A runtime agent registered under a given id is a\n * singleton, so writing a per-hook threadId directly onto it would let two\n * `useAgent` calls that share an `agentId` clobber each other's thread.\n * Passing a distinct local `agentId` plus the `runtimeAgentId` it routes to\n * gives this hook a private proxied agent to pin the thread onto instead of a\n * shared one.\n */\n threadId: string;\n /**\n * The id of the runtime agent to route outbound requests to, while this hook\n * exposes a distinct local `agentId`. Registers a proxied agent via\n * `CopilotKitCore.registerProxiedAgent`, letting several frontend agents\n * (e.g. one per open thread) mount against a single runtime agent without a\n * shared-singleton collision.\n *\n * When set, `agentId` is the *local* registry id (must not collide with an\n * existing local or runtime-discovered agent) and `runtimeAgentId` is the\n * runtime agent the proxy addresses on `/agent/run` etc.\n *\n * REQUIRES `threadId`. Registering a private agent is only worth doing to\n * scope a thread to it; without a `threadId` the private agent would take its\n * thread from the chat configuration, which is what binding to the shared\n * agent via `agentId` alone already does — just with an extra registration\n * and a local id to keep unique.\n */\n runtimeAgentId: string;\n}\n\n/**\n * Default variant: neither `threadId` nor `runtimeAgentId`. The hook binds to\n * the shared agent registered under `agentId` and leaves its threadId to the\n * chat configuration (or to the agent's own auto-minted UUID).\n *\n * Both props are typed `undefined` here rather than omitted so that supplying\n * either one on its own fails to match *both* branches — that is the\n * type-level enforcement of the all-or-nothing rule.\n */\ninterface UseAgentUnscopedProps {\n /**\n * Agent to bind to. Resolution precedence: this property, then the surrounding\n * chat configuration's agentId, then the global default.\n */\n agentId?: string;\n /** Requires `runtimeAgentId`. See {@link UseAgentThreadScopedProps.threadId}. */\n threadId?: undefined;\n /** Requires `threadId`. See {@link UseAgentThreadScopedProps.runtimeAgentId}. */\n runtimeAgentId?: undefined;\n}\n\n/**\n * Props for {@link useAgent}.\n *\n * There are exactly two valid shapes, and the type admits nothing in between:\n *\n * - **Bind to an agent** — `useAgent()`, `useAgent({ agentId })`. The shared\n * instance from the registry; the thread comes from the chat configuration.\n * - **Bind a private agent to a thread** —\n * `useAgent({ agentId, runtimeAgentId, threadId })`. All three required.\n *\n * So `useAgent({ agentId, threadId })`, `useAgent({ agentId, runtimeAgentId })`,\n * and `useAgent({ runtimeAgentId, threadId })` are all compile errors. Each\n * partial combination is either unsafe (a thread scoped onto a shared singleton)\n * or pointless (a private agent with no thread, or one registered over an id\n * that already belongs to a real agent).\n */\nexport type UseAgentProps = UseAgentPropsBase &\n (UseAgentThreadScopedProps | UseAgentUnscopedProps);\n\n/**\n * Returns the selected agent and its readiness, subscribing to agent updates.\n * Uses a shared agent by default, or a private proxy when `agentId`,\n * `runtimeAgentId`, and `threadId` are supplied together.\n */\nexport function useAgent({\n agentId,\n threadId,\n runtimeAgentId,\n updates,\n throttleMs,\n}: UseAgentProps = {}) {\n // Runtime backstop for the all-or-nothing rule UseAgentProps enforces at\n // compile time (plain JS, `as any`, props widened at a call boundary).\n ɵvalidateAgentBinding({ agentId, threadId, runtimeAgentId });\n\n // Explicit prop, then the surrounding chat configuration (#5533), then the\n // provider default, then DEFAULT_AGENT_ID.\n const chatConfig = useCopilotChatConfiguration();\n const providerAgentId = useDefaultAgentId();\n const resolvedAgentId = ɵresolveAgentId({\n agentId,\n chatAgentId: chatConfig?.agentId,\n providerAgentId,\n });\n\n const { copilotkit } = useCopilotKit();\n const resolver = ɵgetAgentResolver(copilotkit);\n const revision = useSyncExternalStore(\n resolver.subscribe,\n resolver.getSnapshot,\n resolver.getSnapshot,\n );\n // Read the provider-level default so it appears in the effect's dep array.\n // subscribeToAgentWithOptions reads it from the core instance, but React\n // needs the dep to know when to re-subscribe.\n const providerThrottleMs = copilotkit.defaultThrottleMs;\n\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n const updateFlags = useMemo(\n () => updates ?? ALL_UPDATES,\n [JSON.stringify(updates)],\n );\n\n // Thread-scoped path: register a private proxied agent for this hook as one\n // balanced effect (StrictMode-safe: the cleanup unregisters before the\n // remount re-registers). The resolver notifies, so the hook swaps from the\n // provisional stand-in to the real proxy.\n useEffect(() => {\n if (runtimeAgentId == null) return;\n return resolver.bindProxy({ agentId: resolvedAgentId, runtimeAgentId });\n }, [resolver, resolvedAgentId, runtimeAgentId]);\n\n // Keyed on the header generation, not header values: a builder returning a\n // new token on every resolution must not re-resolve (#1937).\n const headersGeneration = copilotkit.ɵheadersGeneration;\n const { agent, isReady } = useMemo(\n () =>\n resolver.resolve({\n agentId: resolvedAgentId,\n runtimeAgentId,\n caller: \"useAgent\",\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n resolver,\n revision,\n resolvedAgentId,\n runtimeAgentId,\n copilotkit.agents,\n copilotkit.runtimeConnectionStatus,\n copilotkit.runtimeUrl,\n copilotkit.runtimeTransport,\n copilotkit.credentials,\n headersGeneration,\n ],\n );\n\n useEffect(\n () =>\n ɵsubscribeToAgentUpdates(copilotkit, agent, {\n updates: updateFlags,\n throttleMs,\n onUpdate: forceUpdate,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [agent, forceUpdate, throttleMs, providerThrottleMs, updateFlags],\n );\n\n // Keep request settings fresh outside useMemo: mutating inside it is unsafe\n // in concurrent mode.\n useEffect(() => {\n resolver.refreshRequestSettings(agent);\n }, [resolver, agent, headersGeneration, copilotkit.credentials]);\n\n // Pin the thread onto the agent. AbstractAgent auto-mints a UUID, so without\n // this the agent ships its own random id in /agent/run, /agent/connect and\n // /agent/stop.\n const resolvedThreadId = ɵresolveAgentThreadId({\n threadId,\n chatThreadId: chatConfig?.threadId,\n chatHasExplicitThreadId: chatConfig?.hasExplicitThreadId,\n });\n useEffect(() => {\n if (!resolvedThreadId) return;\n agent.threadId = resolvedThreadId;\n }, [agent, resolvedThreadId]);\n\n return {\n agent,\n /**\n * Whether `agent` is the real, runtime-synced (or locally-registered) agent\n * rather than a provisional stand-in returned while the runtime is still\n * connecting (or in an error state).\n *\n * `agent` is always a fully-constructed `AbstractAgent`, so calling\n * `agent.subscribe(...)`, `agent.setState(...)`, etc. is always safe. But\n * while `isReady` is `false` the instance is a placeholder that will be\n * swapped for the real agent once the runtime `/info` sync resolves, at\n * which point `agent` changes reference and dependent effects re-run.\n * Guard on `isReady` when you only want to act against the real agent —\n * e.g. subscribing to run-lifecycle events you don't want to miss during\n * the provisional window (#5000).\n */\n isReady,\n };\n}\n","import type { AgentCapabilities } from \"@ag-ui/core\";\nimport { ɵgetAgentCapabilities } from \"@copilotkit/core\";\nimport { useAgent } from \"./use-agent\";\n\n/**\n * Returns the capabilities declared by the given agent (or the agent resolved\n * from the surrounding chat configuration, falling back to the default agent).\n * Capabilities are populated from the runtime `/info` response at connection\n * time. The hook reads them synchronously from the agent instance — there is\n * no separate loading state, but the value will be `undefined` until the\n * runtime handshake completes.\n *\n * @param agentId - Optional agent ID. If omitted, inherits the surrounding\n * chat configuration's agent, falling back to the default agent.\n * @returns The agent's capabilities, or `undefined` if the agent doesn't\n * declare capabilities.\n */\nexport function useCapabilities(\n agentId?: string,\n): AgentCapabilities | undefined {\n const { agent } = useAgent({ agentId });\n return ɵgetAgentCapabilities(agent);\n}\n","import { useCopilotKit } from \"../context\";\nimport { useLayoutEffect, useMemo } from \"react\";\nimport { ɵserializeContextValue } from \"@copilotkit/core\";\nimport type { ɵJsonSerializable } from \"@copilotkit/core\";\n\n/**\n * Represents any value that can be serialized to JSON.\n */\nexport type JsonSerializable = ɵJsonSerializable;\n\n/**\n * Context configuration for useAgentContext.\n * Accepts any value; a value that is not a string is sent as its JSON text.\n */\nexport interface AgentContextInput {\n /** A human-readable description of what this context represents */\n description: string;\n /**\n * The context value. A string is sent as-is; any other value is sent as its\n * JSON text, so it should be JSON-serializable. Interface types and optional\n * fields are accepted.\n */\n value: unknown;\n}\n\nexport function useAgentContext(context: AgentContextInput) {\n const { description, value } = context;\n const { copilotkit } = useCopilotKit();\n\n const stringValue = useMemo(() => ɵserializeContextValue(value), [value]);\n\n useLayoutEffect(() => {\n if (!copilotkit) return;\n\n const id = copilotkit.addContext({ description, value: stringValue });\n return () => {\n copilotkit.removeContext(id);\n };\n }, [description, stringValue, copilotkit]);\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport {\n ɵresolveAgentId,\n ɵsubscribeToAgentSuggestions,\n} from \"@copilotkit/core\";\nimport type { Suggestion } from \"@copilotkit/core\";\nimport { useCopilotKit, useDefaultAgentId } from \"../context\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\n\nexport interface UseSuggestionsOptions {\n agentId?: string;\n}\n\nexport interface UseSuggestionsResult {\n suggestions: Suggestion[];\n reloadSuggestions: () => void;\n clearSuggestions: () => void;\n isLoading: boolean;\n}\n\nexport function useSuggestions({\n agentId,\n}: UseSuggestionsOptions = {}): UseSuggestionsResult {\n const { copilotkit } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const providerAgentId = useDefaultAgentId();\n const resolvedAgentId = useMemo(\n () =>\n ɵresolveAgentId({\n agentId,\n chatAgentId: config?.agentId,\n providerAgentId,\n }),\n [agentId, config?.agentId, providerAgentId],\n );\n\n const [result, setResult] = useState(() =>\n copilotkit.getSuggestions(resolvedAgentId),\n );\n\n useEffect(() => {\n setResult(copilotkit.getSuggestions(resolvedAgentId));\n return ɵsubscribeToAgentSuggestions(copilotkit, resolvedAgentId, setResult);\n }, [copilotkit, resolvedAgentId]);\n\n const reloadSuggestions = useCallback(() => {\n copilotkit.reloadSuggestions(resolvedAgentId);\n // Loading state is handled by onSuggestionsStartedLoading event\n }, [copilotkit, resolvedAgentId]);\n\n const clearSuggestions = useCallback(() => {\n copilotkit.clearSuggestions(resolvedAgentId);\n // State updates are handled by onSuggestionsChanged event\n }, [copilotkit, resolvedAgentId]);\n\n return {\n suggestions: result.suggestions,\n reloadSuggestions,\n clearSuggestions,\n isLoading: result.isLoading,\n };\n}\n","import { useEffect, useRef } from \"react\";\nimport { useCopilotKit, useDefaultAgentId } from \"../context\";\nimport { useCopilotChatConfiguration } from \"../providers/CopilotChatConfigurationProvider\";\nimport { ɵbindSuggestionsConfig, ɵresolveAgentId } from \"@copilotkit/core\";\nimport type {\n ɵSuggestionsBinding,\n ɵSuggestionsConfigInput,\n} from \"@copilotkit/core\";\n\n/**\n * Registers a suggestions configuration (dynamic or static) for the current\n * chat. A global config (no `consumerAgentId`, or `\"*\"`) applies to every\n * agent and loads for the surrounding chat's agent first.\n *\n * Pass `deps` to reload suggestions when values the config reads change.\n *\n * @example\n * useConfigureSuggestions({\n * instructions: \"Suggest concise next steps for the user\",\n * available: \"always\",\n * });\n */\nexport function useConfigureSuggestions(\n config: ɵSuggestionsConfigInput | null | undefined,\n deps?: ReadonlyArray<unknown>,\n): void {\n const { copilotkit } = useCopilotKit();\n const chatConfig = useCopilotChatConfiguration();\n const providerAgentId = useDefaultAgentId();\n const chatAgentId = ɵresolveAgentId({\n chatAgentId: chatConfig?.agentId,\n providerAgentId,\n });\n const extraDeps = deps ?? [];\n\n const bindingRef = useRef<ɵSuggestionsBinding | null>(null);\n const latestRef = useRef({ config, chatAgentId });\n latestRef.current = { config, chatAgentId };\n\n useEffect(() => {\n const latest = latestRef.current;\n const binding = ɵbindSuggestionsConfig(copilotkit, latest.config, {\n chatAgentId: latest.chatAgentId,\n });\n bindingRef.current = binding;\n return () => {\n binding.dispose();\n if (bindingRef.current === binding) bindingRef.current = null;\n };\n }, [copilotkit]);\n\n // The binding compares configs by content, so a new inline object on every\n // render is a no-op.\n useEffect(() => {\n bindingRef.current?.update(config, { chatAgentId });\n }, [config, chatAgentId]);\n\n const depsMountedRef = useRef(false);\n useEffect(() => {\n if (!depsMountedRef.current) {\n depsMountedRef.current = true;\n return;\n }\n if (extraDeps.length > 0) bindingRef.current?.reload();\n }, [extraDeps.length, ...extraDeps]);\n}\n","import React, {\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport type { Interrupt } from \"@ag-ui/client\";\nimport { ɵInterruptController } from \"@copilotkit/core\";\nimport { useCopilotKit } from \"../context\";\nimport { useAgent } from \"./use-agent\";\nimport type {\n InterruptEvent,\n InterruptRenderProps,\n InterruptHandlerProps,\n} from \"../types/interrupt\";\n\nexport type {\n InterruptEvent,\n InterruptRenderProps,\n InterruptHandlerProps,\n Interrupt,\n};\n\ntype InterruptHandlerFn<TValue, TResult> = (\n props: InterruptHandlerProps<TValue>,\n) => TResult | PromiseLike<TResult>;\n\ntype InterruptResultFromHandler<THandler> = THandler extends (\n ...args: never[]\n) => infer TResult\n ? TResult extends PromiseLike<infer TResolved>\n ? TResolved | null\n : TResult | null\n : null;\n\ntype InterruptResult<TValue, TResult> = InterruptResultFromHandler<\n InterruptHandlerFn<TValue, TResult>\n>;\n\ntype InterruptRenderInChat = boolean | undefined;\n\ntype UseInterruptReturn<TRenderInChat extends InterruptRenderInChat> =\n TRenderInChat extends false\n ? React.ReactElement | null\n : TRenderInChat extends true | undefined\n ? void\n : React.ReactElement | null | void;\n\n/**\n * Configuration options for `useInterrupt`.\n */\ninterface UseInterruptConfigBase<TValue = unknown, TResult = never> {\n /**\n * Render function for the interrupt UI.\n *\n * Receives both the standard `interrupt`/`interrupts` and the legacy `event`.\n * Call `resolve(payload)` to resume with user input, or `cancel()` to cancel.\n */\n render: (\n props: InterruptRenderProps<TValue, InterruptResult<TValue, TResult>>,\n ) => React.ReactElement;\n /**\n * Optional pre-render handler invoked when an interrupt is received.\n * Return a sync or async value to expose as `result` in `render`.\n * Rejecting/throwing falls back to `result = null`.\n */\n handler?: InterruptHandlerFn<TValue, TResult>;\n /**\n * Optional predicate to filter which interrupts this hook handles.\n * Receives the legacy-compatible event (for standard interrupts, `value` is\n * the primary `Interrupt`). Return `false` to ignore.\n */\n enabled?: (event: InterruptEvent<TValue>) => boolean;\n /** Optional agent id. Defaults to the current configured chat agent. */\n agentId?: string;\n}\n\nexport interface UseInterruptInChatConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. */\n renderInChat?: true;\n}\n\nexport interface UseInterruptExternalConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** When false, the hook returns the interrupt element so you can place it yourself. */\n renderInChat: false;\n}\n\nexport interface UseInterruptDynamicConfig<\n TValue = unknown,\n TResult = never,\n> extends UseInterruptConfigBase<TValue, TResult> {\n /** Dynamic boolean mode. When non-literal, return type is a union. */\n renderInChat: boolean;\n}\n\nexport type UseInterruptConfig<\n TValue = unknown,\n TResult = never,\n TRenderInChat extends InterruptRenderInChat = undefined,\n> = UseInterruptConfigBase<TValue, TResult> & {\n /** When true (default), the interrupt UI renders inside `<CopilotChat>` automatically. */\n renderInChat?: TRenderInChat;\n};\n\n/**\n * Handles agent interrupts with optional filtering, preprocessing, and resume behavior.\n *\n * Supports both the AG-UI standard interrupt flow (`RUN_FINISHED` with\n * `outcome.type === \"interrupt\"`) and the legacy custom-event flow\n * (`on_interrupt`). For standard interrupts, `render` receives `interrupt`\n * (the primary one) and `interrupts` (the full open set); call `resolve(payload)`\n * to resume or `cancel()` to cancel. Resuming addresses the targeted interrupt\n * and, once every open interrupt is addressed, submits a single spec `resume`\n * array via `copilotkit.runAgent`.\n *\n * - `renderInChat: true` (default): the element is published into `<CopilotChat>`; returns `void`.\n * - `renderInChat: false`: the hook returns the interrupt element for manual placement.\n *\n * @example\n * ```tsx\n * useInterrupt({\n * render: ({ interrupt, resolve, cancel }) => (\n * <div>\n * <p>{interrupt?.message}</p>\n * <button onClick={() => resolve({ approved: true })}>Approve</button>\n * <button onClick={() => cancel()}>Cancel</button>\n * </div>\n * ),\n * });\n * ```\n */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport function useInterrupt<\n TResult = never,\n TRenderInChat extends InterruptRenderInChat = undefined,\n>(\n config: UseInterruptConfig<any, TResult, TRenderInChat>,\n): UseInterruptReturn<TRenderInChat> {\n /* eslint-enable @typescript-eslint/no-explicit-any */\n const { copilotkit } = useCopilotKit();\n const { agent } = useAgent({ agentId: config.agentId, updates: [] });\n\n // Read consumer callbacks through refs so inline lambdas neither recreate\n // the controller nor churn the element memo.\n const renderRef = useRef(config.render);\n renderRef.current = config.render;\n const enabledRef = useRef(config.enabled);\n enabledRef.current = config.enabled;\n const handlerRef = useRef(config.handler);\n handlerRef.current = config.handler;\n const copilotkitRef = useRef(copilotkit);\n copilotkitRef.current = copilotkit;\n\n const [controller] = useState(\n () =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new ɵInterruptController<any, TResult>(\n { runAgent: (params) => copilotkitRef.current.runAgent(params) },\n {\n enabled: (event) => enabledRef.current?.(event) ?? true,\n handler: (props) =>\n handlerRef.current ? handlerRef.current(props) : (null as TResult),\n },\n ),\n );\n\n useEffect(() => {\n controller.connect(agent);\n return () => controller.disconnect();\n }, [controller, agent]);\n\n const { renderProps } = useSyncExternalStore(\n controller.subscribe,\n controller.getSnapshot,\n controller.getSnapshot,\n );\n\n const element = useMemo(\n () => (renderProps ? renderRef.current(renderProps) : null),\n [renderProps],\n );\n\n // Publish to core for in-chat rendering. Publish-only.\n useEffect(() => {\n if (config.renderInChat === false) return;\n copilotkit.setInterruptElement(element);\n }, [element, config.renderInChat, copilotkit]);\n\n // Nullify on true unmount only.\n useEffect(() => {\n if (config.renderInChat === false) return;\n return () => {\n copilotkit.setInterruptElement(null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n if (config.renderInChat === false) {\n return element as UseInterruptReturn<TRenderInChat>;\n }\n\n return undefined as UseInterruptReturn<TRenderInChat>;\n}\n","import { useCopilotKit } from \"../context\";\nimport { ɵThreadsController, ɵcreateThreadStore } from \"@copilotkit/core\";\nimport type { ɵThreadSummary } from \"@copilotkit/core\";\nimport { useEffect, useState, useSyncExternalStore } from \"react\";\n\n/**\n * A conversation thread managed by CopilotKit Intelligence.\n *\n * Each thread has a unique `id`, an optional human-readable `name`, and\n * ISO-8601 `createdAt` and `updatedAt` timestamps. `lastRunAt` is the time of\n * the most recent agent run, absent when the thread has never run; prefer it\n * over `updatedAt` for \"last activity\", since rename and archive do not bump\n * it. The shape is core's thread summary, which Angular also exposes.\n */\nexport type Thread = ɵThreadSummary;\n\n/**\n * Configuration for the {@link useThreads} hook.\n *\n * Thread operations are scoped to the runtime-authenticated user and the\n * provided agent on CopilotKit Intelligence.\n */\nexport interface UseThreadsInput {\n /** The ID of the agent whose threads to list and manage. */\n agentId: string;\n /** When `true`, archived threads are included in the list. Defaults to `false`. */\n includeArchived?: boolean;\n /** Maximum number of threads to fetch per page. When set, enables cursor-based pagination. */\n limit?: number;\n /**\n * When `false`, the hook stays inert: no runtime context is dispatched, so\n * NO thread-list fetch or realtime subscription is issued. Used by gated\n * surfaces (e.g. an unlicensed `<CopilotThreadsDrawer>`) that must not touch the\n * network until the gate opens. Defaults to `true`.\n *\n * Flipping `enabled` back to `true` resumes normal fetching on the next\n * effect run; mutations are likewise short-circuited while disabled.\n */\n enabled?: boolean;\n}\n\n/**\n * Return value of the {@link useThreads} hook.\n *\n * The `threads` array is kept in sync with the platform via a realtime\n * WebSocket subscription (when available) and is sorted most-recently-updated\n * first. Mutations reject with an `Error` if the platform request fails.\n */\nexport interface UseThreadsResult {\n /**\n * Threads for the current user/agent pair, sorted by most recently\n * updated first. Updated in realtime when the platform pushes metadata\n * events. Includes archived threads only when `includeArchived` is set.\n */\n threads: Thread[];\n /**\n * `true` while the initial thread list is being fetched from the platform.\n * Subsequent realtime updates do not re-enter the loading state.\n */\n isLoading: boolean;\n /**\n * The most recent error from fetching threads or executing a mutation,\n * or `null` when there is no error. Reset to `null` on the next\n * successful fetch.\n *\n * This channel folds together developer/config errors (missing runtime URL,\n * runtime without thread endpoints) and genuine list-load/mutation failures.\n * End-user surfaces that must not leak config errors should prefer\n * {@link listError}, which excludes the config/runtime-setup errors.\n */\n error: Error | null;\n /**\n * The most recent genuine list-load or mutation error from the platform, or\n * `null`. Unlike {@link error}, this EXCLUDES developer/config errors (a\n * missing runtime URL, or a runtime that does not advertise thread\n * endpoints), so an end-user surface can render it directly without leaking\n * a developer-facing configuration message into the UI. It does report a\n * runtime that refuses to list threads because the caller has no identity\n * (no `identifyUser`), since the list cannot load until that is set.\n */\n listError: Error | null;\n /**\n * The error from the most recent FAILED next-page (fetch-more) load, or\n * `null`. Tracked separately from {@link listError} so a paginated-load\n * failure surfaces an inline \"couldn't load more\" affordance while the\n * already-loaded list stays visible. Cleared when a fetch-more is retried or\n * succeeds.\n */\n fetchMoreError: Error | null;\n /**\n * `true` when there are more threads available to fetch via\n * {@link fetchMoreThreads}. Only meaningful when `limit` is set.\n */\n hasMoreThreads: boolean;\n /**\n * `true` while a subsequent page of threads is being fetched.\n */\n isFetchingMoreThreads: boolean;\n /**\n * `true` while at least one thread mutation (rename, archive, unarchive,\n * delete) is awaiting a server response. Mutations apply optimistically, so\n * this is primarily useful for disabling controls or showing a subtle\n * in-flight indicator.\n */\n isMutating: boolean;\n /**\n * Fetch the next page of threads. No-op when {@link hasMoreThreads} is\n * `false` or a fetch is already in progress.\n */\n fetchMoreThreads: () => void;\n /**\n * Re-fetch the thread list from the platform without clearing the current\n * list. Backs the drawer's error-state Retry and the Active/All filter\n * refetch. No-op until the runtime is connected.\n */\n refetchThreads: () => void;\n /**\n * Reset to a fresh, non-explicit client-side thread so the welcome screen\n * shows. Lazy creation: no row appears in {@link threads} until the new\n * thread's first run persists server-side.\n */\n startNewThread: () => void;\n /**\n * Rename a thread on the platform.\n * Resolves when the server confirms the update; rejects on failure.\n */\n renameThread: (threadId: string, name: string) => Promise<void>;\n /**\n * Archive a thread on the platform.\n * Archived threads are excluded from subsequent list results.\n * Resolves when the server confirms the update; rejects on failure.\n */\n archiveThread: (threadId: string) => Promise<void>;\n /**\n * Restore a previously archived thread on the platform.\n * The thread re-appears in default (non-archived) list results.\n * Resolves when the server confirms the update; rejects on failure.\n */\n unarchiveThread: (threadId: string) => Promise<void>;\n /**\n * Permanently delete a thread from the platform.\n * This is irreversible. Resolves when the server confirms deletion;\n * rejects on failure.\n */\n deleteThread: (threadId: string) => Promise<void>;\n}\n\n/**\n * React hook for listing and managing CopilotKit Intelligence threads.\n *\n * On mount the hook fetches the thread list for the runtime-authenticated user\n * and the given `agentId`. When CopilotKit Intelligence exposes a WebSocket\n * URL, it also opens a realtime subscription so the `threads` array stays\n * current without polling — thread creates, renames, archives, and deletes\n * from any client are reflected immediately.\n *\n * Mutation methods (`renameThread`, `archiveThread`, `unarchiveThread`,\n * `deleteThread`) return promises that resolve once the platform confirms the\n * operation and reject with an `Error` on failure.\n *\n * @param input - Agent identifier and optional list controls.\n * @returns Thread list state and stable mutation callbacks.\n *\n * @example\n * ```tsx\n * import { useThreads } from \"@copilotkit/react-core\";\n *\n * function ThreadList() {\n * const { threads, isLoading, renameThread, deleteThread } = useThreads({\n * agentId: \"agent-1\",\n * });\n *\n * if (isLoading) return <p>Loading…</p>;\n *\n * return (\n * <ul>\n * {threads.map((t) => (\n * <li key={t.id}>\n * {t.name ?? \"Untitled\"}\n * <button onClick={() => renameThread(t.id, \"New name\")}>Rename</button>\n * <button onClick={() => deleteThread(t.id)}>Delete</button>\n * </li>\n * ))}\n * </ul>\n * );\n * }\n * ```\n */\nexport function useThreads({\n agentId,\n includeArchived,\n limit,\n enabled = true,\n}: UseThreadsInput): UseThreadsResult {\n const { copilotkit } = useCopilotKit();\n\n // Core's ɵThreadsController owns the view model: thread projection, the\n // configuration errors, the gated and de-duplicated context dispatch, the\n // registry claim and the mutation guard. This hook feeds it and renders it.\n const [controller] = useState(\n () =>\n new ɵThreadsController(\n ɵcreateThreadStore({ fetch: copilotkit.ɵruntimeFetch }),\n { core: copilotkit, agentId, includeArchived, limit, enabled },\n ),\n );\n const {\n threads,\n isLoading,\n error,\n listError,\n fetchMoreError,\n hasMoreThreads,\n isFetchingMoreThreads,\n isMutating,\n } = useSyncExternalStore(\n controller.subscribe,\n controller.getSnapshot,\n controller.getServerSnapshot,\n );\n\n useEffect(() => controller.start(), [controller]);\n\n useEffect(() => {\n controller.update({\n core: copilotkit,\n agentId,\n includeArchived,\n limit,\n enabled,\n });\n }, [\n controller,\n copilotkit,\n agentId,\n includeArchived,\n limit,\n enabled,\n copilotkit.runtimeUrl,\n copilotkit.runtimeConnectionStatus,\n copilotkit.ɵheadersGeneration,\n copilotkit.intelligence?.wsUrl,\n copilotkit.threadEndpoints?.list,\n copilotkit.threadEndpoints?.mutations,\n ]);\n\n const {\n fetchMoreThreads,\n refetchThreads,\n startNewThread,\n renameThread,\n archiveThread,\n unarchiveThread,\n deleteThread,\n } = controller;\n\n return {\n threads,\n isLoading,\n error,\n listError,\n fetchMoreError,\n hasMoreThreads,\n isFetchingMoreThreads,\n isMutating,\n fetchMoreThreads,\n refetchThreads,\n startNewThread,\n renameThread,\n archiveThread,\n unarchiveThread,\n deleteThread,\n };\n}\n","import { useCopilotKit } from \"../context\";\nimport {\n ɵselectMemories,\n ɵselectMemoriesError,\n ɵselectMemoriesIsLoading,\n ɵselectMemoriesAvailable,\n ɵselectMemoriesRealtimeStatus,\n} from \"@copilotkit/core\";\nimport type {\n Memory,\n MemoryChanges,\n MemoryRealtimeStatus,\n ɵMemoryStore,\n NewMemory,\n} from \"@copilotkit/core\";\nimport { useCallback, useSyncExternalStore } from \"react\";\n\n/**\n * Return value of the {@link useMemories} hook.\n *\n * The `memories` array is the server-authoritative list for the current user.\n * It is hydrated from a REST snapshot and kept current by realtime\n * `memory_metadata` deltas from the store's own channel. Mutations resolve\n * once the platform confirms the operation and reject with an `Error` on\n * failure.\n */\nexport interface UseMemoriesResult {\n /**\n * Memories for the current user, newest first. Updated in realtime when\n * the platform pushes `memory_metadata` events.\n */\n memories: Memory[];\n /**\n * `true` while the initial memory snapshot is being fetched. Subsequent\n * realtime updates do not re-enter the loading state.\n */\n isLoading: boolean;\n /**\n * The most recent error from fetching memories or executing a mutation, or\n * `null` when there is no error. Cleared on the next fetch attempt, on a\n * successful fetch, when the runtime context changes, and on a successful\n * mutation (a failed mutation replaces it with that mutation's error).\n */\n error: Error | null;\n /**\n * `true` when the platform memory routes are available. Set to `false`\n * after a 404 or 501, indicating memory is not supported by the current\n * runtime configuration.\n */\n isAvailable: boolean;\n /**\n * Health of the realtime connection that streams live `memory_metadata`\n * deltas. Distinct from `isAvailable`/`error` (which describe the REST list\n * route): `\"connecting\"` while the socket opens/joins, `\"connected\"` once\n * live deltas are flowing, and `\"unavailable\"` once the socket permanently\n * gives up — at which point the list is a frozen snapshot. Lets the UI drop a\n * \"live\" indicator instead of showing it over stale data.\n */\n realtimeStatus: MemoryRealtimeStatus;\n /**\n * Re-fetch the memory snapshot from the platform. Resolves once the re-pull\n * settles; rejects if it fails or the store is torn down mid-flight.\n */\n refresh: () => Promise<void>;\n /**\n * Create a memory. Resolves to the stored memory (server-authoritative);\n * rejects on failure.\n */\n addMemory: (input: NewMemory) => Promise<Memory>;\n /**\n * Supersede a memory: the old memory is retired and a new one is created.\n * Resolves to the new memory (its `id` differs from `id`); rejects on\n * failure.\n *\n * Supersede is a FULL replacement, not a partial patch: `changes` is the\n * complete definition of the new memory. You must re-supply `content` and\n * `kind`, and an omitted `sourceThreadIds` resets the new memory's source\n * threads to empty — it does not preserve the prior memory's value.\n */\n updateMemory: (id: string, changes: MemoryChanges) => Promise<Memory>;\n /**\n * Retire a memory (non-lossy delete). Resolves when the server confirms;\n * rejects on failure.\n */\n removeMemory: (id: string) => Promise<void>;\n}\n\nfunction useMemoryStoreSelector<T>(\n store: ɵMemoryStore,\n selector: (state: ReturnType<ɵMemoryStore[\"getState\"]>) => T,\n): T {\n return useSyncExternalStore(\n useCallback(\n (onStoreChange) => {\n const subscription = store.select(selector).subscribe(onStoreChange);\n return () => subscription.unsubscribe();\n },\n [store, selector],\n ),\n () => selector(store.getState()),\n // getServerSnapshot: without this third argument React throws\n // \"Missing getServerSnapshot\" during SSR/prerender (e.g. Next.js). The\n // store has no client data while prerendering, so we project from its\n // stable server state.\n () => selector(store.getServerState()),\n );\n}\n\n/**\n * React hook for listing and managing platform memories.\n *\n * Reads the memory store owned and wired by `CopilotKitCore`. On mount the\n * hook exposes the live list plus stable `addMemory` / `updateMemory` /\n * `removeMemory` / `refresh` callbacks. Mutations are server-authoritative:\n * each resolves once the platform confirms the operation and rejects with an\n * `Error` on failure.\n *\n * Realtime updates are automatic: the core's memory store opens its own\n * `user_meta:memories:<joinCode>` channel and applies `memory_metadata` deltas\n * to the list. You can still call `refresh()` to re-pull the REST snapshot on\n * demand.\n *\n * @returns Memory list state and stable mutation callbacks.\n *\n * @example\n * ```tsx\n * import { useMemories } from \"@copilotkit/react-core\";\n *\n * function MemoryList() {\n * const { memories, isLoading, isAvailable, addMemory, removeMemory } =\n * useMemories();\n *\n * if (!isAvailable) return null;\n * if (isLoading) return <p>Loading…</p>;\n *\n * return (\n * <ul>\n * {memories.map((m) => (\n * <li key={m.id}>\n * {m.content}\n * <button onClick={() => removeMemory(m.id)}>Delete</button>\n * </li>\n * ))}\n * </ul>\n * );\n * }\n * ```\n */\nexport function useMemories(): UseMemoriesResult {\n const { copilotkit } = useCopilotKit();\n\n const store = copilotkit.getMemoryStore();\n\n const memories = useMemoryStoreSelector(store, ɵselectMemories);\n const isLoading = useMemoryStoreSelector(store, ɵselectMemoriesIsLoading);\n const error = useMemoryStoreSelector(store, ɵselectMemoriesError);\n const isAvailable = useMemoryStoreSelector(store, ɵselectMemoriesAvailable);\n const realtimeStatus = useMemoryStoreSelector(\n store,\n ɵselectMemoriesRealtimeStatus,\n );\n\n const refresh = useCallback(() => store.refresh(), [store]);\n const addMemory = useCallback(\n (input: NewMemory) => store.addMemory(input),\n [store],\n );\n const updateMemory = useCallback(\n (id: string, changes: MemoryChanges) => store.updateMemory(id, changes),\n [store],\n );\n const removeMemory = useCallback(\n (id: string) => store.removeMemory(id),\n [store],\n );\n\n return {\n memories,\n isLoading,\n error,\n isAvailable,\n realtimeStatus,\n refresh,\n addMemory,\n updateMemory,\n removeMemory,\n };\n}\n","import { useCallback } from \"react\";\nimport { useCopilotKit } from \"../context\";\nimport {\n ɵbuildLearnFromUserActionPayload,\n ɵrecordAnnotation,\n} from \"@copilotkit/core\";\n\n/**\n * Input to {@link UseLearnFromUserActionRecorder}, the function returned\n * by {@link useLearnFromUserAction}. Captures a single UI interaction that\n * CopilotKit Intelligence's auto-curated knowledge base loop will distill\n * into the team's `/project` notes.\n */\nexport interface LearnFromUserActionInput {\n /** Thread the action is associated with. May be unknown to the platform. */\n threadId: string;\n /** Short, agent-readable summary of what the user did. Optional. */\n title?: string | null;\n /** Optional longer explanation. */\n description?: string | null;\n /** Free-form, JSON-serializable snapshot describing the action. Optional. */\n data?: unknown;\n /** ISO-8601 client-asserted timestamp. Defaults to server NOW() when absent. */\n occurredAt?: string;\n /**\n * Caller-supplied idempotency key. When omitted, `ɵrecordAnnotation` generates a\n * fresh UUID per call so retries collapse to the original row at the\n * platform. Supply your own to keep a single semantic event idempotent\n * across calls (e.g. a React re-render or a manual retry button).\n */\n clientEventId?: string;\n}\n\n/** Outcome returned by the recorder function. */\nexport interface LearnFromUserActionResult {\n /** Platform-assigned id of the user-action row. */\n id: string;\n /** True when the platform recognized this `clientEventId` as a retry. */\n duplicate: boolean;\n}\n\n/** Recorder function returned by {@link useLearnFromUserAction}. */\nexport type UseLearnFromUserActionRecorder = (\n input: LearnFromUserActionInput,\n) => Promise<LearnFromUserActionResult>;\n\n/**\n * Record a user UI interaction in CopilotKit Intelligence's user-actions\n * stream. The platform's auto-curated knowledge base agent reads these\n * (alongside finished agent runs) and writes free-form Obsidian-flavored\n * markdown to `/project`, where any agent in the same project can later\n * read it via the `copilotkit_knowledge_base_shell` MCP tool.\n *\n * The hook returns a stable function. Calling it issues a request to the\n * customer's CopilotKit runtime (`POST ${runtimeUrl}/annotate`), which\n * resolves the Intel user from the BFF's auth and forwards to the\n * platform — the Intel API key never reaches the browser.\n *\n * If `clientEventId` is omitted `recordAnnotation` generates a UUID per call,\n * so a naive double-call (e.g. React 18 strict-mode double-mount, or a retry\n * after a network blip on a fresh Promise) is naturally safe. Supply your\n * own key when a single semantic event must remain idempotent across\n * multiple `learnFromUserAction(...)` calls.\n *\n * @example\n * ```tsx\n * import { useLearnFromUserAction } from \"@copilotkit/react-core\";\n *\n * function SettingsPage({ threadId }) {\n * const learnFromUserAction = useLearnFromUserAction();\n *\n * const onRename = (oldName: string, newName: string) => {\n * void learnFromUserAction({\n * threadId,\n * title: \"Renamed project\",\n * data: { previous: { name: oldName }, next: { name: newName } },\n * });\n * };\n * }\n * ```\n */\nexport function useLearnFromUserAction(): UseLearnFromUserActionRecorder {\n const { copilotkit } = useCopilotKit();\n\n return useCallback(\n async (\n input: LearnFromUserActionInput,\n ): Promise<LearnFromUserActionResult> => {\n const runtimeUrl = copilotkit.runtimeUrl;\n if (!runtimeUrl) {\n throw new Error(\n \"useLearnFromUserAction: runtimeUrl is not configured. Set it on <CopilotKitProvider runtimeUrl=...>.\",\n );\n }\n\n return ɵrecordAnnotation({\n fetch: copilotkit.ɵruntimeFetch,\n runtimeUrl,\n // ɵruntimeFetch already resolves and overlays the current core\n // headers at send time (#1937); no snapshot to pass here.\n headers: {},\n type: \"user_action\",\n payload: ɵbuildLearnFromUserActionPayload(input),\n threadId: input.threadId,\n clientEventId: input.clientEventId,\n occurredAt: input.occurredAt,\n });\n },\n [copilotkit],\n );\n}\n","import { useCallback } from \"react\";\nimport { useCopilotChatConfiguration } from \"../providers\";\nimport type {\n LearnFromUserActionInput,\n LearnFromUserActionResult,\n} from \"./use-learn-from-user-action\";\nimport { useLearnFromUserAction } from \"./use-learn-from-user-action\";\n\n/**\n * Input to {@link UseLearnFromUserActionInCurrentThreadRecorder} — same as\n * {@link LearnFromUserActionInput} minus `threadId`, which is sourced from\n * the surrounding `<CopilotChatConfigurationProvider>` at call time.\n */\nexport type LearnFromUserActionInCurrentThreadInput = Omit<\n LearnFromUserActionInput,\n \"threadId\"\n>;\n\n/** Recorder function returned by {@link useLearnFromUserActionInCurrentThread}. */\nexport type UseLearnFromUserActionInCurrentThreadRecorder = (\n input: LearnFromUserActionInCurrentThreadInput,\n) => Promise<LearnFromUserActionResult>;\n\n/**\n * Record a user UI interaction against the **current chat's** thread. The\n * `threadId` is sourced from the surrounding\n * `<CopilotChatConfigurationProvider>` (the same provider `<CopilotChat>`,\n * `<CopilotSidebar>`, and friends set up), so callers in a chat-aware\n * subtree don't need to thread an id through manually.\n *\n * Throws on **call** (not on mount) when there is no chat-config provider\n * in scope — matches the \"throw on call when runtimeUrl is missing\"\n * behavior of {@link useLearnFromUserAction}. Mounting the hook in a branch\n * that never fires is harmless.\n *\n * The recorder does NOT accept a `threadId` override. If you need to\n * record against an explicit thread, use {@link useLearnFromUserAction}\n * directly — two hooks, two crisp contracts, no mode confusion.\n *\n * This hook always uses `config.threadId`, regardless of whether the\n * surrounding chat config minted it internally or received one from\n * the caller. Auto-minted threads simply mean the action lands under\n * a thread the platform never saw — the writer agent still distills\n * user-action-only threads (it does not require the thread to exist\n * in `cpki.threads`), so the loop keeps learning.\n *\n * @example\n * ```tsx\n * import { useLearnFromUserActionInCurrentThread } from \"@copilotkit/react-core\";\n *\n * function SettingsPanel() {\n * const learnFromUserAction = useLearnFromUserActionInCurrentThread();\n *\n * const onRename = (oldName: string, newName: string) => {\n * void learnFromUserAction({\n * title: \"Renamed project\",\n * data: { previous: { name: oldName }, next: { name: newName } },\n * });\n * };\n *\n * // ...\n * }\n * ```\n */\nexport function useLearnFromUserActionInCurrentThread(): UseLearnFromUserActionInCurrentThreadRecorder {\n const config = useCopilotChatConfiguration();\n const learnFromUserAction = useLearnFromUserAction();\n\n return useCallback(\n async (\n input: LearnFromUserActionInCurrentThreadInput,\n ): Promise<LearnFromUserActionResult> => {\n const threadId = config?.threadId;\n if (!threadId) {\n throw new Error(\n \"useLearnFromUserActionInCurrentThread: no CopilotChatConfigurationProvider in scope. \" +\n \"Wrap the call site in <CopilotChat>, <CopilotSidebar>, or <CopilotChatConfigurationProvider>, \" +\n \"or use `useLearnFromUserAction()` and pass `threadId` explicitly.\",\n );\n }\n return learnFromUserAction({ ...input, threadId });\n },\n [config?.threadId, learnFromUserAction],\n );\n}\n","import React, {\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { ɵAttachmentQueue } from \"@copilotkit/core\";\nimport type { Attachment, AttachmentsConfig } from \"@copilotkit/shared\";\n\nexport interface UseAttachmentsProps {\n config?: AttachmentsConfig;\n}\n\nexport interface UseAttachmentsReturn {\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n enabled: boolean;\n /** Whether the user is dragging a file over the drop zone. */\n dragOver: boolean;\n /** Ref for the hidden file input element. */\n fileInputRef: React.RefObject<HTMLInputElement | null>;\n /** Ref for the container element (used for scoped paste handling). */\n containerRef: React.RefObject<HTMLDivElement | null>;\n /** Process an array of files (validate, upload, add to state). No-op while attachments are disabled. */\n processFiles: (files: File[]) => Promise<void>;\n /** Handler for `<input type=\"file\" onChange>`. */\n handleFileUpload: (e: React.ChangeEvent<HTMLInputElement>) => Promise<void>;\n /** Handler for `onDragOver` on the drop zone. */\n handleDragOver: (e: React.DragEvent) => void;\n /** Handler for `onDragLeave` on the drop zone. */\n handleDragLeave: (e: React.DragEvent) => void;\n /** Handler for `onDrop` on the drop zone. */\n handleDrop: (e: React.DragEvent) => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /**\n * Consume ready attachments and clear the queue.\n * Returns the attachments that were ready; resets the file input.\n * No-ops if the queue is already empty (no state update triggered).\n */\n consumeAttachments: () => Attachment[];\n}\n\n/**\n * Hook that manages file attachment state — uploads, drag-and-drop, paste,\n * and lifecycle. The queue itself (validation, uploads, ready state) lives in\n * `@copilotkit/core`'s `ɵAttachmentQueue`; this hook adds the DOM wiring. All\n * returned callbacks are referentially stable across renders.\n */\nexport function useAttachments({\n config,\n}: UseAttachmentsProps): UseAttachmentsReturn {\n const enabled = config?.enabled ?? false;\n\n const [dragOver, setDragOver] = useState(false);\n const fileInputRef = useRef<HTMLInputElement>(null);\n const containerRef = useRef<HTMLDivElement>(null);\n\n // Keep a ref to the latest config so the queue and stable callbacks read it\n // without appearing in dependency arrays.\n const configRef = useRef(config);\n configRef.current = config;\n\n const [queue] = useState(() => new ɵAttachmentQueue(() => configRef.current));\n const attachments = useSyncExternalStore(\n useCallback((onChange) => queue.subscribe(onChange), [queue]),\n () => queue.getSnapshot(),\n () => queue.getSnapshot(),\n );\n\n const processFiles = useCallback(\n (files: File[]) => queue.processFiles(files),\n [queue],\n );\n\n const processSafely = useCallback(\n async (files: File[], label: string) => {\n try {\n await queue.processFiles(files);\n } catch (error) {\n console.error(`[CopilotKit] ${label}:`, error);\n }\n },\n [queue],\n );\n\n const handleFileUpload = useCallback(\n async (e: React.ChangeEvent<HTMLInputElement>) => {\n const input = e.target;\n if (!input.files?.length) return;\n await processSafely(Array.from(input.files), \"Upload error\");\n // Clear the picker so choosing the same file again fires `change`.\n input.value = \"\";\n },\n [processSafely],\n );\n\n const handleDragOver = useCallback((e: React.DragEvent) => {\n if (!configRef.current?.enabled) return;\n e.preventDefault();\n e.stopPropagation();\n setDragOver(true);\n }, []);\n\n const handleDragLeave = useCallback((e: React.DragEvent) => {\n e.preventDefault();\n e.stopPropagation();\n setDragOver(false);\n }, []);\n\n const handleDrop = useCallback(\n async (e: React.DragEvent) => {\n e.preventDefault();\n e.stopPropagation();\n setDragOver(false);\n const files = Array.from(e.dataTransfer.files);\n if (files.length > 0) await processSafely(files, \"Drop error\");\n },\n [processSafely],\n );\n\n // Clipboard paste handler — scoped to the container\n useEffect(() => {\n if (!enabled) return;\n\n const handlePaste = async (e: ClipboardEvent) => {\n const target = e.target;\n if (!(target instanceof Node) || !containerRef.current?.contains(target))\n return;\n const files = queue.filterPastedFiles(\n Array.from(e.clipboardData?.items ?? []),\n );\n if (files.length === 0) return;\n e.preventDefault();\n await processSafely(files, \"Paste error\");\n };\n\n // handlePaste catches and logs its own failures, so it never rejects.\n const onPaste = (e: ClipboardEvent) => {\n void handlePaste(e);\n };\n document.addEventListener(\"paste\", onPaste);\n return () => document.removeEventListener(\"paste\", onPaste);\n }, [enabled, queue, processSafely]);\n\n const removeAttachment = useCallback(\n (id: string) => queue.remove(id),\n [queue],\n );\n\n const consumeAttachments = useCallback(() => {\n const ready = queue.consumeReady();\n if (ready.length > 0 && fileInputRef.current) {\n fileInputRef.current.value = \"\";\n }\n return ready;\n }, [queue]);\n\n return {\n attachments,\n enabled,\n dragOver,\n fileInputRef,\n containerRef,\n processFiles,\n handleFileUpload,\n handleDragOver,\n handleDragLeave,\n handleDrop,\n removeAttachment,\n consumeAttachments,\n };\n}\n","import { createContext } from \"react\";\nimport type { ɵToolCallDisplayContextValue } from \"@copilotkit/core\";\n\n/**\n * Handed down by the message view so each message's tool calls and text can\n * follow the view's `toolCallDisplay` without every layer passing it along.\n * @internal\n */\nexport type ToolCallDisplayContextValue = ɵToolCallDisplayContextValue;\n\n/** @internal */\nexport const ToolCallDisplayContext =\n createContext<ToolCallDisplayContextValue | null>(null);\n","import React, {\n useCallback,\n useContext,\n useMemo,\n useSyncExternalStore,\n} from \"react\";\nimport type { AssistantMessage, Message, ToolMessage } from \"@ag-ui/core\";\nimport { useRenderToolCall } from \"../../hooks\";\nimport { useCopilotKit } from \"../../context\";\nimport { useToolCallRendererNames } from \"../../hooks/use-render-tool-call\";\nimport type { SlotValue } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport {\n Collapsible,\n CopilotChatToolCallGroup,\n ToolCallGroupContext,\n} from \"./CopilotChatToolCallGroup\";\nimport { ToolCallDisplayContext } from \"./tool-call-display-context\";\nimport {\n ɵgetToolCallGroupState,\n ɵgetToolCallLayouts,\n ɵtoolCallAppearance,\n} from \"@copilotkit/core\";\nimport type {\n CopilotChatToolCallDisplay,\n ToolCallEntry,\n} from \"@copilotkit/core\";\n\nexport type CopilotChatToolCallsViewProps = {\n message: AssistantMessage;\n messages?: Message[];\n /**\n * How to show the calls (see `CopilotChatToolCallDisplay`). Inside a message\n * view it follows the view's `toolCallDisplay`; on its own it defaults to\n * `\"grouped\"`.\n */\n display?: CopilotChatToolCallDisplay;\n /**\n * Draws a group of calls made in a row: a component, a class name for the\n * default group, or props for it (e.g. `{ appearance: \"line\" }`).\n */\n group?: SlotValue<typeof CopilotChatToolCallGroup>;\n};\n\nexport function CopilotChatToolCallsView({\n message,\n messages = [],\n display: displayProp,\n group,\n}: CopilotChatToolCallsViewProps) {\n const renderToolCall = useRenderToolCall();\n const rendererNames = useToolCallRendererNames();\n const { copilotkit } = useCopilotKit();\n const subscribe = useCallback(\n (onChange: () => void) =>\n copilotkit.ɵsubscribeToLearningConfigured(onChange),\n [copilotkit],\n );\n const getSnapshot = () => copilotkit.ɵlearningConfigured;\n // Driven by the learning config, not by the Trajectory: a wrapper that comes\n // and goes with capture state would remount the tool UI on every reconnect.\n // Only adding or removing the config itself changes the tree.\n const learningConfigured = useSyncExternalStore(\n subscribe,\n getSnapshot,\n getSnapshot,\n );\n const context = useContext(ToolCallDisplayContext);\n const display = displayProp ?? context?.display ?? \"grouped\";\n\n // Inside a message view, groups can span messages, so the view lays them\n // out for the whole list; on its own, this message's calls are grouped.\n const viewLayout = context?.layouts.get(message.id);\n const layout = useMemo(() => {\n if (display === \"separate\") return undefined;\n return (\n viewLayout ??\n ɵgetToolCallLayouts([message], messages, rendererNames).get(message.id)\n );\n }, [display, viewLayout, message, messages, rendererNames]);\n\n if (!message.toolCalls || message.toolCalls.length === 0) {\n return null;\n }\n\n const renderCall = (entry: ToolCallEntry) => {\n const rendered = renderToolCall({\n toolCall: entry.toolCall,\n toolMessage: entry.toolMessage,\n });\n if (rendered === null || !learningConfigured) return rendered;\n // The id lets interaction capture attribute clicks to this tool call.\n return (\n <div\n data-tool-call-id={entry.toolCall.id}\n style={{ display: \"contents\" }}\n >\n {rendered}\n </div>\n );\n };\n\n if (!layout) {\n return (\n <>\n {message.toolCalls.map((toolCall) => {\n const toolMessage = messages.find(\n (m) => m.role === \"tool\" && m.toolCallId === toolCall.id,\n ) as ToolMessage | undefined;\n return (\n <React.Fragment key={toolCall.id}>\n {renderCall({ toolCall, toolMessage })}\n </React.Fragment>\n );\n })}\n </>\n );\n }\n\n const workOpen = context?.workOpen.get(message.id);\n // Whether the agent may still finish a trailing group's calls. Without a\n // message view there's no run state, so a call with no result is assumed to\n // be running, as the built-in card has always shown it.\n const groupActive = (trailing: boolean) =>\n trailing && (context ? context.isRunning : true);\n\n return (\n <>\n {layout.segments.map((segment) => {\n if (segment.kind === \"call\") {\n return (\n <React.Fragment key={segment.id}>\n {renderCall(segment.call)}\n </React.Fragment>\n );\n }\n\n if (display === \"turn\") {\n // A row per call, in the open while the agent works; the message\n // view folds them away with the rest of the work once it's done.\n const active = groupActive(segment.trailing);\n const { failedIds, statusById } = ɵgetToolCallGroupState(\n segment.calls,\n active,\n false,\n );\n return (\n <Collapsible\n key={segment.id}\n open={workOpen ?? true}\n className=\"cpk-tool-calls-view-turn\"\n >\n <div className=\"cpk-tool-calls-view-turn-rows\">\n <ToolCallGroupContext.Provider\n value={{ appearance: \"line\", failedIds, statusById, active }}\n >\n {segment.calls.map((call) => (\n <React.Fragment key={call.toolCall.id}>\n {renderCall(call)}\n </React.Fragment>\n ))}\n </ToolCallGroupContext.Provider>\n </div>\n </Collapsible>\n );\n }\n\n return (\n <React.Fragment key={segment.id}>\n {renderSlot(group, CopilotChatToolCallGroup, {\n calls: segment.calls,\n renderCall,\n appearance: ɵtoolCallAppearance(display) ?? \"card\",\n isActive: groupActive(segment.trailing),\n })}\n </React.Fragment>\n );\n })}\n </>\n );\n}\n\nexport default CopilotChatToolCallsView;\n","\"use client\";\n\nimport {\n useEffect,\n useId,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport { cn } from \"../../lib/utils\";\nimport { Button } from \"../ui/button\";\nimport { Tooltip, TooltipTrigger, TooltipContent } from \"../ui/tooltip\";\nimport {\n DropdownMenu,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuLabel,\n DropdownMenuItem,\n DropdownMenuSeparator,\n} from \"../ui/dropdown-menu\";\nimport { useCopilotKitInspector } from \"../CopilotKitInspectorContext\";\nimport {\n CopilotChatDefaultLabels,\n ɵHoverMenuController,\n ɵinspectorKiteFill,\n ɵinspectorKiteIcon,\n ɵinspectorShortcuts,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\nconst subscribeToShortcuts = (listener: () => void) =>\n ɵinspectorShortcuts.subscribe(listener);\nconst getShortcutsHidden = () => ɵinspectorShortcuts.hidden;\nconst getServerShortcutsHidden = () => false;\n\n/** Whether the user hid the Inspector shortcuts until the page reloads. */\nexport function useInspectorShortcutsHidden() {\n return useSyncExternalStore(\n subscribeToShortcuts,\n getShortcutsHidden,\n getServerShortcutsHidden,\n );\n}\n\nconst hideShortcuts = () => ɵinspectorShortcuts.hide();\n\n// Matches the Inspector launcher artwork in web-inspector/src/assets/inspector-logo-kite.svg.\nfunction InspectorKiteIcon({\n className,\n ...props\n}: React.SVGProps<SVGSVGElement>) {\n const id = useId();\n return (\n <svg\n {...props}\n aria-hidden=\"true\"\n className={cn(\"cpk-inspector-button-kite-icon\", className)}\n viewBox={ɵinspectorKiteIcon.viewBox}\n fill=\"none\"\n >\n {ɵinspectorKiteIcon.paths.map((path) => (\n <path\n key={path.d}\n d={path.d}\n fill={ɵinspectorKiteFill(id, path)}\n stroke={path.stroke}\n strokeWidth={path.strokeWidth}\n strokeLinecap={path.strokeLinecap}\n />\n ))}\n <defs>\n {ɵinspectorKiteIcon.gradients.map((gradient) => (\n <linearGradient\n key={gradient.id}\n id={`${id}-${gradient.id}`}\n x1={gradient.x1}\n y1={gradient.y1}\n x2={gradient.x2}\n y2={gradient.y2}\n gradientUnits=\"userSpaceOnUse\"\n >\n {gradient.stops.map((stop) => (\n <stop\n key={`${stop.offset ?? \"0\"}-${stop.color}`}\n offset={stop.offset}\n stopColor={stop.color}\n />\n ))}\n </linearGradient>\n ))}\n </defs>\n </svg>\n );\n}\n\nexport function CopilotChatInspectorButton({\n title,\n className,\n onClick,\n onPointerDown,\n onPointerEnter,\n onPointerLeave,\n onKeyDown,\n disabled,\n ...props\n}: React.ButtonHTMLAttributes<HTMLButtonElement>) {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const { isInspectorEnabled } = useCopilotKitInspector();\n const hidden = useInspectorShortcutsHidden();\n const [menu] = useState(() => new ɵHoverMenuController());\n const { open, dark } = useSyncExternalStore(\n menu.subscribe,\n menu.getSnapshot,\n menu.getSnapshot,\n );\n const trigger = useRef<HTMLButtonElement>(null);\n const primaryLabel = title || labels.assistantMessageToolbarInspectorLabel;\n useEffect(() => menu.dispose, [menu]);\n\n const { cancelClose, scheduleClose } = menu;\n const changeOpen = (next: boolean) => menu.setOpen(next, trigger.current);\n\n if (!isInspectorEnabled || hidden) return null;\n\n return (\n <DropdownMenu open={open} onOpenChange={changeOpen} modal={false}>\n <DropdownMenuTrigger asChild>\n <Button\n {...props}\n ref={trigger}\n type=\"button\"\n disabled={disabled}\n variant=\"assistantMessageToolbarButton\"\n size=\"icon\"\n data-testid=\"copilot-inspector-button\"\n aria-label={`${labels.assistantMessageToolbarInspectorTitle} (${labels.assistantMessageToolbarInspectorLocalOnlyLabel.toLowerCase()})`}\n className={cn(\"cpk-inspector-button\", className)}\n onPointerEnter={(event) => {\n onPointerEnter?.(event);\n menu.pointerEnter({\n pointerType: event.pointerType,\n disabled,\n trigger: trigger.current,\n });\n }}\n onPointerLeave={(event) => {\n onPointerLeave?.(event);\n scheduleClose();\n }}\n onPointerDown={(event) => {\n onPointerDown?.(event);\n // Clicking inspects the message instead of toggling the menu.\n event.preventDefault();\n }}\n onClick={(event) => {\n changeOpen(false);\n onClick?.(event);\n }}\n onKeyDown={(event) => {\n menu.keyboardUsed();\n onKeyDown?.(event);\n if (\n !event.defaultPrevented &&\n (event.key === \"Enter\" || event.key === \" \")\n ) {\n event.preventDefault();\n event.currentTarget.click();\n }\n }}\n >\n <CopilotIcon\n name=\"Wrench\"\n aria-hidden=\"true\"\n className=\"cpk-inspector-button-icon\"\n data-testid=\"copilot-inspector-icon\"\n />\n </Button>\n </DropdownMenuTrigger>\n <DropdownMenuContent\n align=\"start\"\n side=\"top\"\n sideOffset={6}\n className={cn(\"cpk-inspector-button-menu\", dark && \"dark\")}\n onPointerEnter={cancelClose}\n onPointerLeave={scheduleClose}\n onKeyDown={menu.keyboardUsed}\n onOpenAutoFocus={(event) => {\n if (menu.openedByHover) event.preventDefault();\n }}\n onCloseAutoFocus={(event) => {\n if (menu.openedByHover) event.preventDefault();\n }}\n onFocusOutside={() => changeOpen(false)}\n >\n <DropdownMenuLabel className=\"cpk-inspector-button-menu-header\">\n <span className=\"cpk-inspector-button-menu-title\">\n {labels.assistantMessageToolbarInspectorTitle}\n </span>\n <Tooltip delayDuration={1000}>\n <TooltipTrigger asChild>\n <span tabIndex={0} className=\"cpk-inspector-button-local-badge\">\n {labels.assistantMessageToolbarInspectorLocalOnlyLabel}\n </span>\n </TooltipTrigger>\n <TooltipContent\n side=\"top\"\n sideOffset={6}\n className={cn(\n \"cpk-inspector-button-local-tooltip\",\n dark && \"dark\",\n )}\n onPointerEnter={cancelClose}\n onPointerLeave={scheduleClose}\n >\n {labels.assistantMessageToolbarInspectorLocalOnlyDescription}\n </TooltipContent>\n </Tooltip>\n </DropdownMenuLabel>\n <DropdownMenuSeparator />\n <DropdownMenuItem asChild>\n <button\n type=\"button\"\n onClick={onClick}\n className=\"cpk-inspector-button-menu-item cpk-inspector-button-inspect-item\"\n >\n <InspectorKiteIcon className=\"cpk-inspector-button-menu-item-icon\" />\n <span>\n <span className=\"cpk-inspector-button-menu-item-label\">\n {primaryLabel}\n </span>\n <span className=\"cpk-inspector-button-menu-item-description\">\n {labels.assistantMessageToolbarInspectorDescription}\n </span>\n </span>\n </button>\n </DropdownMenuItem>\n <DropdownMenuItem\n onSelect={hideShortcuts}\n className=\"cpk-inspector-button-menu-item cpk-inspector-button-hide-item\"\n >\n <CopilotIcon\n name=\"EyeOff\"\n aria-hidden=\"true\"\n className=\"cpk-inspector-button-menu-item-icon\"\n />\n <span>\n <span className=\"cpk-inspector-button-menu-item-label\">\n {labels.assistantMessageToolbarInspectorHideLabel}\n </span>\n <span className=\"cpk-inspector-button-menu-item-description\">\n {labels.assistantMessageToolbarInspectorHideDescription}\n </span>\n </span>\n </DropdownMenuItem>\n </DropdownMenuContent>\n </DropdownMenu>\n );\n}\n","import * as React from \"react\";\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\";\n\nimport { cn } from \"../../lib/utils\";\n\nfunction Popover({\n ...props\n}: React.ComponentProps<typeof PopoverPrimitive.Root>) {\n return <PopoverPrimitive.Root data-slot=\"popover\" {...props} />;\n}\n\nfunction PopoverAnchor({\n ...props\n}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {\n return <PopoverPrimitive.Anchor data-slot=\"popover-anchor\" {...props} />;\n}\n\n/**\n * Popover content in a portal, so it floats over the page instead of taking\n * room in the layout, with the CopilotKit style scope on it.\n */\nconst PopoverContent = React.forwardRef<\n React.ComponentRef<typeof PopoverPrimitive.Content>,\n React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>\n>(({ className, align = \"start\", sideOffset = 6, ...props }, ref) => (\n <PopoverPrimitive.Portal>\n <PopoverPrimitive.Content\n ref={ref}\n data-copilotkit\n data-copilotkit-popover\n data-slot=\"popover-content\"\n align={align}\n sideOffset={sideOffset}\n className={cn(\"cpk-popover\", className)}\n {...props}\n />\n </PopoverPrimitive.Portal>\n));\nPopoverContent.displayName = \"PopoverContent\";\n\nexport { Popover, PopoverAnchor, PopoverContent };\n","import type { AssistantMessage } from \"@ag-ui/core\";\nimport type { CopilotKitCore } from \"@copilotkit/core\";\nimport {\n ɵFeedbackCommentController,\n ɵgetMessageFeedback,\n ɵgetMessageFeedbackControls,\n ɵisLearningFeedbackEnabled,\n ɵsubscribeToLearningFeedbackEnabled,\n ɵsubscribeToMessageFeedback,\n} from \"@copilotkit/core\";\nimport type {\n ɵMessageFeedbackControls,\n ɵMessageFeedbackScope,\n} from \"@copilotkit/core\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport type { RefObject } from \"react\";\n\n/** The chat whose assistant messages collect feedback for Learning. */\nexport type MessageFeedbackScope = ɵMessageFeedbackScope;\n\n/** Current feedback for one assistant message, and how to change it. */\nexport type MessageFeedbackControls = ɵMessageFeedbackControls;\n\n/**\n * Set by the message view while Learning is on for this chat. Assistant\n * messages without it show thumbs only when the app passes its own handlers\n * or thumb slots.\n */\nexport const MessageFeedbackScopeContext =\n createContext<MessageFeedbackScope | null>(null);\n\n/**\n * Whether the thumbs record feedback for Learning. See core's\n * `ɵisLearningFeedbackEnabled` for the rules.\n */\nexport function useLearningFeedbackEnabled(copilotkit: CopilotKitCore) {\n const subscribe = useCallback(\n (onChange: () => void) =>\n ɵsubscribeToLearningFeedbackEnabled(copilotkit, onChange),\n [copilotkit],\n );\n return useSyncExternalStore(\n subscribe,\n () => ɵisLearningFeedbackEnabled(copilotkit),\n () => false,\n );\n}\n\nconst noSubscription = () => () => {};\n\n/** Feedback controls for `message`, or `null` when this chat collects none. */\nexport function useMessageFeedback(message: AssistantMessage) {\n const scope = useContext(MessageFeedbackScopeContext);\n const subscribe = useCallback(\n (onChange: () => void) =>\n scope\n ? ɵsubscribeToMessageFeedback(scope.agentId, scope.threadId, onChange)\n : noSubscription(),\n [scope],\n );\n const getSnapshot = () =>\n scope\n ? ɵgetMessageFeedback(scope.agentId, scope.threadId, message.id)\n : undefined;\n // Re-renders when this message's rating changes.\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n return scope ? ɵgetMessageFeedbackControls(scope, message) : null;\n}\n\n/** The comment popover of one rated message: when it shows and what it holds. */\nexport interface FeedbackComment {\n readonly open: boolean;\n /** The comment being edited. */\n readonly draft: string;\n readonly setDraft: (draft: string) => void;\n /** Grows each time the field should take focus: after a keyboard rating. */\n readonly focusRequest: number;\n /** The chosen thumb the popover points at. */\n readonly anchor: HTMLElement | null;\n /** Whether a focus request waits; reading it answers the request. */\n readonly takeFocusRequest: () => boolean;\n /** The comment field, for moving focus into it. */\n readonly inputRef: RefObject<HTMLInputElement | null>;\n /** Opens with `comment` in the field. */\n readonly show: ɵFeedbackCommentController[\"show\"];\n /** The pointer or focus reached the rating or the popover. */\n readonly enter: ɵFeedbackCommentController[\"enter\"];\n /**\n * It left them: close soon, unless the user is editing the comment or, when\n * focus left, the pointer is still on the rating or the popover.\n */\n readonly leave: ɵFeedbackCommentController[\"leave\"];\n /** Tracks whether focus is in the comment form. */\n readonly setEditing: (editing: boolean) => void;\n /** Closes, saving a changed comment unless `save` is false. */\n readonly close: ɵFeedbackCommentController[\"close\"];\n /** Moves focus back to the thumb without opening the comment again. */\n readonly returnFocus: (target: HTMLElement | null) => void;\n /** A thumb click; returns whether the app's handler should run. */\n readonly rate: ɵFeedbackCommentController[\"rate\"];\n /** The attributes and handlers of one thumb. */\n readonly thumb: ɵFeedbackCommentController[\"thumb\"];\n /** Points at the chosen thumb when the click gave no element. */\n readonly findAnchor: ɵFeedbackCommentController[\"findAnchor\"];\n /** Closes a comment whose rating changed or whose toolbar hid. */\n readonly sync: ɵFeedbackCommentController[\"sync\"];\n /** Moves focus into the field when a keyboard rating asked for it. */\n readonly focusField: ɵFeedbackCommentController[\"focusField\"];\n /** Saves, closes, and returns focus to the thumb. */\n readonly submit: ɵFeedbackCommentController[\"submit\"];\n /** Escape in the popover; returns whether to stop the event. */\n readonly popoverEscape: ɵFeedbackCommentController[\"popoverEscape\"];\n /** Tab out of the popover, back into the page's order. */\n readonly popoverKeyDown: ɵFeedbackCommentController[\"popoverKeyDown\"];\n /** Focus left the comment form. */\n readonly popoverFocusLeave: ɵFeedbackCommentController[\"popoverFocusLeave\"];\n}\n\n/**\n * Drives the comment popover of a rated message with core's\n * `ɵFeedbackCommentController`, which holds the open and close rules.\n */\nexport function useFeedbackComment(\n controls: MessageFeedbackControls | null,\n): FeedbackComment {\n const latestControls = useRef(controls);\n latestControls.current = controls;\n const inputRef = useRef<HTMLInputElement | null>(null);\n const [controller] = useState(\n () =>\n new ɵFeedbackCommentController({\n getControls: () => latestControls.current,\n getInput: () => inputRef.current,\n }),\n );\n const state = useSyncExternalStore(\n controller.subscribe,\n controller.getSnapshot,\n controller.getSnapshot,\n );\n // A message that unmounts (scrolled out of a virtual list) keeps its edit.\n useEffect(() => controller.dispose, [controller]);\n\n return {\n ...state,\n setDraft: controller.setDraft,\n takeFocusRequest: controller.takeFocusRequest,\n inputRef,\n show: controller.show,\n enter: controller.enter,\n leave: controller.leave,\n setEditing: controller.setEditing,\n close: controller.close,\n returnFocus: controller.returnFocus,\n rate: controller.rate,\n thumb: controller.thumb,\n findAnchor: controller.findAnchor,\n sync: controller.sync,\n focusField: controller.focusField,\n submit: controller.submit,\n popoverEscape: controller.popoverEscape,\n popoverKeyDown: controller.popoverKeyDown,\n popoverFocusLeave: controller.popoverFocusLeave,\n };\n}\n","import { useEffect, useState, useSyncExternalStore } from \"react\";\nimport { ɵCopyFeedback } from \"@copilotkit/core\";\n\n/**\n * The \"copied\" check mark of a copy button, from core's `ɵCopyFeedback`: it\n * shows for two seconds after `markCopied()`, and a second copy restarts the\n * wait.\n */\nexport function useCopyFeedback() {\n const [feedback] = useState(() => new ɵCopyFeedback());\n const copied = useSyncExternalStore(\n feedback.subscribe,\n feedback.getSnapshot,\n feedback.getSnapshot,\n );\n useEffect(() => feedback.dispose, [feedback]);\n return { copied, markCopied: feedback.markCopied };\n}\n","import type { AssistantMessage, Message } from \"@ag-ui/core\";\nimport React, {\n Fragment,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport { CopilotChatDefaultLabels } from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport { cn } from \"../../lib/utils\";\nimport { Button } from \"../../components/ui/button\";\nimport {\n Tooltip,\n TooltipContent,\n TooltipTrigger,\n} from \"../../components/ui/tooltip\";\nimport type { SlotValue, WithSlots } from \"../../lib/slots\";\nimport {\n renderSlot,\n isReactComponentType,\n useShallowStableRef,\n} from \"../../lib/slots\";\nimport { StreamingMarkdownDefaultRenderer } from \"./StreamingMarkdownDefaultRenderer\";\nimport { useMarkdownRenderer } from \"../../providers/MarkdownRendererContext\";\nimport type {\n MarkdownRendererProps,\n DefaultMarkdownRendererProps,\n MarkdownRenderer as MarkdownRendererValue,\n} from \"../../providers/MarkdownRendererContext\";\nimport { copyToClipboard } from \"@copilotkit/shared\";\nimport CopilotChatToolCallsView from \"./CopilotChatToolCallsView\";\nimport { Collapsible } from \"./CopilotChatToolCallGroup\";\nimport { ToolCallDisplayContext } from \"./tool-call-display-context\";\nimport { useCopilotKitInspector } from \"../CopilotKitInspectorContext\";\nimport {\n CopilotChatInspectorButton,\n useInspectorShortcutsHidden,\n} from \"./CopilotChatInspectorButton\";\nimport type { CopilotKitInspectorOpenRequest } from \"../CopilotKitInspectorContext\";\nimport { useGenerativeUIRuntime } from \"../../generative-ui/runtime-context\";\nimport { MarkdownSurfaces } from \"../../generative-ui/markdown/MarkdownSurfaces\";\nimport {\n Popover,\n PopoverAnchor,\n PopoverContent,\n} from \"../../components/ui/popover\";\nimport { useFeedbackComment, useMessageFeedback } from \"./message-feedback\";\nimport type { FeedbackComment } from \"./message-feedback\";\nimport {\n ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH,\n ɵhasAssistantMessageText,\n ɵisOwnFeedbackThumb,\n ɵshouldShowAssistantToolbar,\n} from \"@copilotkit/core\";\nimport { useCopyFeedback } from \"./use-copy-feedback\";\nimport type { ɵMessageFeedbackRating as MessageFeedbackRating } from \"@copilotkit/core\";\n\nexport type CopilotChatFeedbackMessage = AssistantMessage & {\n rawEvent?: unknown;\n};\n\nexport type CopilotChatAssistantMessageProps = WithSlots<\n {\n markdownRenderer: typeof CopilotChatAssistantMessage.MarkdownRenderer;\n toolbar: typeof CopilotChatAssistantMessage.Toolbar;\n copyButton: typeof CopilotChatAssistantMessage.CopyButton;\n inspectorButton: typeof CopilotChatAssistantMessage.InspectorButton;\n thumbsUpButton: typeof CopilotChatAssistantMessage.ThumbsUpButton;\n thumbsDownButton: typeof CopilotChatAssistantMessage.ThumbsDownButton;\n readAloudButton: typeof CopilotChatAssistantMessage.ReadAloudButton;\n regenerateButton: typeof CopilotChatAssistantMessage.RegenerateButton;\n toolCallsView: typeof CopilotChatToolCallsView;\n },\n {\n onThumbsUp?: (message: CopilotChatFeedbackMessage) => void;\n onThumbsDown?: (message: CopilotChatFeedbackMessage) => void;\n onReadAloud?: (message: AssistantMessage) => void;\n onRegenerate?: (message: AssistantMessage) => void;\n message: AssistantMessage;\n messages?: Message[];\n isRunning?: boolean;\n /**\n * Whether this is the last message the chat renders. The message view\n * passes it, because the rendered list can differ from `messages` when\n * `transformMessages` drops, replaces or reorders messages. Defaults to\n * comparing against the last entry of `messages`.\n */\n isLatest?: boolean;\n additionalToolbarItems?: React.ReactNode;\n toolbarVisible?: boolean;\n /**\n * The comment field of a reply rating, inside the popover next to the\n * chosen thumb. Shown only while Automatic Learning records ratings; it\n * renders after `children`, so a `children` layout does not place it.\n */\n feedbackComment?: SlotValue<\n typeof CopilotChatAssistantMessage.FeedbackComment\n >;\n } & React.HTMLAttributes<HTMLDivElement>\n>;\n\nfunction resolveMarkdownRenderer(\n value: MarkdownRendererValue | undefined,\n): React.FC<MarkdownRendererProps & DefaultMarkdownRendererProps> {\n if (!value) return CopilotChatAssistantMessage.MarkdownRenderer;\n if (isReactComponentType(value)) {\n // A provider-supplied component (escape hatch) renders with the bound\n // { content, isStreaming } props; wrap it so the resolved type matches the\n // slot's component type. createElement accepts function or class components.\n const ProvidedRenderer = value;\n const ProvidedMarkdownRenderer: React.FC<\n MarkdownRendererProps & DefaultMarkdownRendererProps\n > = (props) => React.createElement(ProvidedRenderer, props);\n return ProvidedMarkdownRenderer;\n }\n const config = value as DefaultMarkdownRendererProps;\n const ConfiguredRenderer: React.FC<\n MarkdownRendererProps & DefaultMarkdownRendererProps\n > = (props) => (\n // Provider config is the base; props (bound content/isStreaming plus any\n // per-message slot config merged in by renderSlot) override it, so a\n // per-message markdownRenderer wins over the provider per the documented\n // slot -> provider -> built-in resolution order.\n <CopilotChatAssistantMessage.MarkdownRenderer {...config} {...props} />\n );\n return ConfiguredRenderer;\n}\n\n/**\n * In the `\"turn\"` tool-call display, text in a reply's working phase was\n * narration: it fades to muted once a call follows it, and folds away with the\n * rest of the work when the reply is done. The wrapper is there for every\n * message in that display, so text that turns into narration keeps its node\n * (and its place) rather than remounting.\n */\nfunction WorkText({\n messageId,\n children,\n}: {\n messageId: string;\n children: React.ReactElement;\n}) {\n const context = useContext(ToolCallDisplayContext);\n if (context?.display !== \"turn\") return children;\n const open = context.workTextOpen.get(messageId);\n return (\n <Collapsible\n open={open ?? true}\n className=\"cpk-assistant-message-work-text\"\n >\n <div\n className=\"cpk-assistant-message-work-text-content\"\n data-work-text={open === undefined ? \"reply\" : \"narration\"}\n >\n {children}\n </div>\n </Collapsible>\n );\n}\n\n/**\n * Binds the Inspector action to the active chat without making the full\n * assistant message subscribe to chat configuration changes.\n */\nfunction BoundInspectorButton({\n inspectorButton,\n messageId,\n openInspector,\n ...props\n}: {\n inspectorButton: CopilotChatAssistantMessageProps[\"inspectorButton\"];\n messageId: string;\n openInspector: (request: CopilotKitInspectorOpenRequest) => void;\n} & Omit<\n React.ButtonHTMLAttributes<HTMLButtonElement>,\n \"onClick\"\n>): React.ReactElement {\n const chatConfiguration = useCopilotChatConfiguration();\n\n return renderSlot(\n inspectorButton,\n CopilotChatAssistantMessage.InspectorButton,\n {\n ...props,\n onClick: () =>\n openInspector({\n messageId,\n threadId: chatConfiguration?.threadId,\n agentId: chatConfiguration?.agentId,\n }),\n },\n );\n}\n\n/**\n * The comment popover of a rated message, pointing at the chosen thumb. Kept\n * apart so only it, not the whole message, follows chat configuration.\n *\n * The popover lives in a portal, so it keeps keyboard order by hand: Shift+Tab\n * from its start returns to the thumb, Tab from its end moves on to the\n * control after the thumb, and Enter or Escape inside it returns to the thumb.\n */\nfunction FeedbackCommentPopover({\n feedbackComment,\n comment,\n savedComment,\n rating,\n messageId,\n}: {\n feedbackComment:\n | SlotValue<typeof CopilotChatAssistantMessage.FeedbackComment>\n | undefined;\n comment: FeedbackComment;\n savedComment: string;\n rating: MessageFeedbackRating;\n messageId: string;\n}): React.ReactElement {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const contentRef = useRef<HTMLDivElement>(null);\n // Radix reads the anchor through a ref. A new ref per anchor, so nothing\n // changes a ref during render.\n const anchor = useMemo(() => ({ current: comment.anchor }), [comment.anchor]);\n // A keyboard rating moves focus into the field, as the popover opens or,\n // when it was open already, as the field for the new rating renders.\n const { focusRequest, focusField } = comment;\n useEffect(() => focusField(), [focusRequest, focusField]);\n return (\n <Popover\n open={comment.open}\n onOpenChange={(open) => {\n if (!open) comment.close();\n }}\n >\n <PopoverAnchor virtualRef={anchor as React.RefObject<HTMLElement>} />\n <PopoverContent\n ref={contentRef}\n side=\"bottom\"\n collisionPadding={8}\n hideWhenDetached\n aria-label={labels.assistantMessageFeedbackCommentPlaceholder}\n data-copilotkit-ignore\n onOpenAutoFocus={(event) => {\n event.preventDefault();\n focusField();\n }}\n onCloseAutoFocus={(event) => event.preventDefault()}\n onInteractOutside={(event) => {\n // A click on a thumb removes or switches the rating, so closing must\n // not first save the draft as the answer to the rating it replaces.\n if (ɵisOwnFeedbackThumb(event.target, messageId))\n event.preventDefault();\n }}\n onEscapeKeyDown={(event) => {\n // Escape in the comment closes only the comment, not a chat popup\n // around it; with focus elsewhere it also reaches that control.\n if (comment.popoverEscape(contentRef.current))\n event.stopPropagation();\n }}\n onKeyDown={(event) => comment.popoverKeyDown(event, contentRef.current)}\n onPointerEnter={() => comment.enter(\"pointer\")}\n onPointerLeave={() => comment.leave(\"pointer\")}\n className=\"cpk-assistant-message-feedback-popover\"\n >\n {/* Keyed on the rating, so a new rating starts with a fresh field. */}\n <Fragment key={rating}>\n {renderSlot(\n feedbackComment,\n CopilotChatAssistantMessage.FeedbackComment,\n {\n value: comment.draft,\n savedComment,\n inputRef: comment.inputRef,\n onChange: comment.setDraft,\n onSubmit: comment.submit,\n onEditingChange: comment.setEditing,\n onLeave: (next) =>\n comment.popoverFocusLeave(next, contentRef.current, messageId),\n },\n )}\n </Fragment>\n </PopoverContent>\n </Popover>\n );\n}\n\nexport function CopilotChatAssistantMessage({\n message,\n messages,\n isRunning,\n isLatest,\n onThumbsUp,\n onThumbsDown,\n onReadAloud,\n onRegenerate,\n additionalToolbarItems,\n toolbarVisible = true,\n markdownRenderer,\n toolbar,\n copyButton,\n inspectorButton,\n thumbsUpButton,\n thumbsDownButton,\n readAloudButton,\n regenerateButton,\n feedbackComment: feedbackCommentSlot,\n toolCallsView,\n children,\n className,\n ...props\n}: CopilotChatAssistantMessageProps) {\n // Stabilize the provider value so a shallow-equal inline config object (e.g.\n // `markdownRenderer={{ caret: true }}`) with a fresh identity on each provider\n // render doesn't churn resolveMarkdownRenderer's output and remount the\n // markdown subtree (which would throw away streaming parser state). This is a\n // shallow, key-by-key compare — configs whose values are themselves new\n // objects each render (e.g. an inline `nodeRenderers`) or an inline component\n // renderer still change identity, so define those outside render / memoize\n // them, exactly as you would any component prop. Mirrors how slot props are\n // stabilized via the same helper.\n const providerRenderer = useShallowStableRef(useMarkdownRenderer());\n const DefaultMarkdownRenderer = useMemo(\n () => resolveMarkdownRenderer(providerRenderer),\n [providerRenderer],\n );\n\n // Don't show toolbar if message has no content (only tool calls)\n const hasContent = ɵhasAssistantMessageText(message.content);\n const isLatestAssistantMessage =\n message.role === \"assistant\" &&\n (isLatest ?? messages?.[messages.length - 1]?.id === message.id);\n const { isInspectorEnabled, openInspector } = useCopilotKitInspector();\n const shortcutsHidden = useInspectorShortcutsHidden();\n const showInspectorShortcut = isInspectorEnabled && !shortcutsHidden;\n // Set while this chat collects ratings for Learning: the thumbs record them.\n const feedback = useMessageFeedback(message);\n const comment = useFeedbackComment(feedback);\n const root = useRef<HTMLDivElement>(null);\n // A custom thumb that calls `onClick` without an event gives no element:\n // point at the chosen thumb once it renders, before the popover reads it.\n useLayoutEffect(() => comment.findAnchor(root.current));\n /**\n * A thumb click. A keyboard click (`detail` 0) moves focus into the\n * comment; custom thumb slots may call `onClick` without an event.\n */\n const rate = (\n value: MessageFeedbackRating,\n event?: React.MouseEvent<HTMLButtonElement>,\n ) =>\n comment.rate(value, {\n target: event?.currentTarget ?? null,\n keyboard: event?.detail === 0,\n });\n\n /** Props that let the chosen thumb open and point at its comment. */\n const thumbFeedbackProps = (value: MessageFeedbackRating) => {\n const thumb = comment.thumb(value);\n if (!thumb) return {};\n const { handlers } = thumb;\n if (!handlers) return thumb.attributes;\n return {\n ...thumb.attributes,\n onPointerEnter: handlers.pointerEnter,\n onPointerLeave: handlers.pointerLeave,\n onFocus: handlers.focus,\n onBlur: handlers.blur,\n onKeyDown: handlers.keyDown,\n };\n };\n\n const boundMarkdownRenderer = renderSlot(\n markdownRenderer,\n DefaultMarkdownRenderer,\n {\n content: message.content || \"\",\n isStreaming: !!(isRunning && isLatestAssistantMessage),\n messageId: message.id,\n },\n );\n\n const boundCopyButton = renderSlot(\n copyButton,\n CopilotChatAssistantMessage.CopyButton,\n {\n onClick: async () => {\n if (message.content) {\n return await copyToClipboard(message.content);\n }\n return false;\n },\n },\n );\n\n const boundThumbsUpButton = renderSlot(\n thumbsUpButton,\n CopilotChatAssistantMessage.ThumbsUpButton,\n {\n onClick:\n onThumbsUp || feedback\n ? (event?: React.MouseEvent<HTMLButtonElement>) => {\n // The app hears about a rating given, not about one removed.\n if (rate(\"up\", event)) onThumbsUp?.(message);\n }\n : undefined,\n ...thumbFeedbackProps(\"up\"),\n },\n );\n\n const boundInspectorButton = showInspectorShortcut ? (\n <BoundInspectorButton\n inspectorButton={inspectorButton}\n messageId={message.id}\n openInspector={openInspector}\n />\n ) : (\n <></>\n );\n\n const boundThumbsDownButton = renderSlot(\n thumbsDownButton,\n CopilotChatAssistantMessage.ThumbsDownButton,\n {\n onClick:\n onThumbsDown || feedback\n ? (event?: React.MouseEvent<HTMLButtonElement>) => {\n if (rate(\"down\", event)) onThumbsDown?.(message);\n }\n : undefined,\n ...thumbFeedbackProps(\"down\"),\n },\n );\n\n const boundReadAloudButton = renderSlot(\n readAloudButton,\n CopilotChatAssistantMessage.ReadAloudButton,\n {\n onClick: onReadAloud ? () => onReadAloud(message) : undefined,\n },\n );\n\n const boundRegenerateButton = renderSlot(\n regenerateButton,\n CopilotChatAssistantMessage.RegenerateButton,\n {\n onClick: onRegenerate ? () => onRegenerate(message) : undefined,\n },\n );\n\n const boundToolbar = renderSlot(\n toolbar,\n CopilotChatAssistantMessage.Toolbar,\n {\n children: (\n <div className=\"cpk-assistant-message-toolbar-items\">\n {boundCopyButton}\n {(onThumbsUp || thumbsUpButton || feedback) && boundThumbsUpButton}\n {(onThumbsDown || thumbsDownButton || feedback) &&\n boundThumbsDownButton}\n {(onReadAloud || readAloudButton) && boundReadAloudButton}\n {(onRegenerate || regenerateButton) && boundRegenerateButton}\n {additionalToolbarItems}\n {showInspectorShortcut && boundInspectorButton}\n </div>\n ),\n },\n );\n\n const boundToolCallsView = renderSlot(\n toolCallsView,\n CopilotChatToolCallsView,\n {\n message,\n messages,\n },\n );\n\n const shouldShowToolbar = ɵshouldShowAssistantToolbar({\n toolbarVisible,\n hasContent,\n showInspectorShortcut,\n isRunning: !!isRunning,\n isLatest: isLatestAssistantMessage,\n });\n // The popover shows only with the toolbar and a rating. Hiding the toolbar\n // keeps the edit; a rating removed elsewhere or Learning turned off ends it.\n const rating = feedback?.feedback?.rating;\n const { open: commentOpen, sync: syncComment } = comment;\n useEffect(() => {\n // react-doctor-disable-next-line react-doctor/no-pass-data-to-parent -- syncs core's feedback controller, an external store, not a parent's state\n syncComment({ showsToolbar: shouldShowToolbar });\n }, [commentOpen, shouldShowToolbar, rating, syncComment]);\n\n // Floats in a portal next to the chosen thumb, so it never moves the chat.\n const feedbackComment = feedback?.feedback && shouldShowToolbar && (\n <FeedbackCommentPopover\n feedbackComment={feedbackCommentSlot}\n comment={comment}\n savedComment={feedback.feedback.comment ?? \"\"}\n rating={feedback.feedback.rating}\n messageId={message.id}\n />\n );\n\n if (children) {\n return (\n <div\n ref={root}\n data-copilotkit\n data-message-id={message.id}\n style={{ display: \"contents\" }}\n >\n {children({\n markdownRenderer: boundMarkdownRenderer,\n toolbar: boundToolbar,\n toolCallsView: boundToolCallsView,\n copyButton: boundCopyButton,\n inspectorButton: boundInspectorButton,\n thumbsUpButton: boundThumbsUpButton,\n thumbsDownButton: boundThumbsDownButton,\n readAloudButton: boundReadAloudButton,\n regenerateButton: boundRegenerateButton,\n message,\n messages,\n isRunning,\n onThumbsUp,\n onThumbsDown,\n onReadAloud,\n onRegenerate,\n additionalToolbarItems,\n toolbarVisible: shouldShowToolbar,\n })}\n {feedbackComment}\n </div>\n );\n }\n\n return (\n <div\n ref={root}\n data-copilotkit\n data-testid=\"copilot-assistant-message\"\n className={cn(\"copilotKitMessage copilotKitAssistantMessage\", className)}\n {...props}\n data-message-id={message.id}\n >\n <WorkText messageId={message.id}>\n <div className=\"cpk-markdown cpk-assistant-message-markdown\">\n {boundMarkdownRenderer}\n </div>\n </WorkText>\n {boundToolCallsView}\n {shouldShowToolbar && boundToolbar}\n {feedbackComment}\n </div>\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace CopilotChatAssistantMessage {\n export const MarkdownRenderer: React.FC<\n MarkdownRendererProps &\n DefaultMarkdownRendererProps & {\n /** Id of the rendered message. The markdown transport finds its fences by it. */\n messageId?: string;\n }\n > = ({ content, isStreaming, className, messageId, ...config }) => {\n // With the markdown transport, ```a2ui fences render as surfaces. The\n // fences are found by the message id, so without one they stay code.\n const generativeUI = useGenerativeUIRuntime();\n if (generativeUI?.transport === \"markdown\" && messageId !== undefined) {\n return (\n <MarkdownSurfaces\n content={content ?? \"\"}\n messageId={messageId}\n isStreaming={isStreaming}\n className={className}\n {...config}\n />\n );\n }\n return (\n <StreamingMarkdownDefaultRenderer\n content={content ?? \"\"}\n isStreaming={isStreaming}\n className={className}\n {...config}\n />\n );\n };\n\n export const Toolbar: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({\n className,\n ...props\n }) => (\n <div\n data-testid=\"copilot-assistant-toolbar\"\n className={cn(\"cpk-assistant-message-toolbar\", className)}\n {...props}\n />\n );\n\n export const ToolbarButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement> & {\n title: string;\n tooltip?: React.ReactNode;\n tooltipClassName?: string;\n children: React.ReactNode;\n }\n > = ({ title, tooltip, tooltipClassName, children, ...props }) => {\n // Same element whether or not its popup is open, so pointer events stay\n // paired. The popup replaces the tooltip: an open tooltip closes, and a\n // request to open one while the popup shows is ignored, so the tooltip\n // does not reappear when the popup closes under a pointer that left.\n const [tooltipOpen, setTooltipOpen] = useState(false);\n const popupOpen = props[\"aria-expanded\"] === true;\n if (popupOpen && tooltipOpen) setTooltipOpen(false);\n return (\n <Tooltip\n open={tooltipOpen && !popupOpen}\n onOpenChange={(open) => setTooltipOpen(open && !popupOpen)}\n >\n <TooltipTrigger asChild>\n <Button\n type=\"button\"\n variant=\"assistantMessageToolbarButton\"\n aria-label={title}\n {...props}\n >\n {children}\n </Button>\n </TooltipTrigger>\n <TooltipContent side=\"bottom\" className={tooltipClassName}>\n {tooltip ?? <p>{title}</p>}\n </TooltipContent>\n </Tooltip>\n );\n };\n\n export const CopyButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ className, title, onClick, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const { copied, markCopied } = useCopyFeedback();\n\n const handleClick = async (event: React.MouseEvent<HTMLButtonElement>) => {\n if (!onClick) return;\n // onClick may return a boolean indicating copy success\n const result: unknown = await Promise.resolve(onClick(event));\n if (result === true) markCopied();\n };\n\n return (\n <ToolbarButton\n data-testid=\"copilot-copy-button\"\n title={title || labels.assistantMessageToolbarCopyMessageLabel}\n onClick={(event) => {\n void handleClick(event);\n }}\n className={className}\n {...props}\n >\n {copied ? (\n <CopilotIcon\n name=\"Check\"\n className=\"cpk-assistant-message-toolbar-icon\"\n />\n ) : (\n <CopilotIcon\n name=\"Copy\"\n className=\"cpk-assistant-message-toolbar-icon\"\n />\n )}\n </ToolbarButton>\n );\n };\n\n export const InspectorButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = CopilotChatInspectorButton;\n\n export const ThumbsUpButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ title, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <ToolbarButton\n data-testid=\"copilot-thumbs-up-button\"\n title={title || labels.assistantMessageToolbarThumbsUpLabel}\n {...props}\n >\n <CopilotIcon\n name=\"ThumbsUp\"\n className=\"cpk-assistant-message-toolbar-icon\"\n fill={props[\"aria-pressed\"] === true ? \"currentColor\" : \"none\"}\n />\n </ToolbarButton>\n );\n };\n\n export const ThumbsDownButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ title, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <ToolbarButton\n data-testid=\"copilot-thumbs-down-button\"\n title={title || labels.assistantMessageToolbarThumbsDownLabel}\n {...props}\n >\n <CopilotIcon\n name=\"ThumbsDown\"\n className=\"cpk-assistant-message-toolbar-icon\"\n fill={props[\"aria-pressed\"] === true ? \"currentColor\" : \"none\"}\n />\n </ToolbarButton>\n );\n };\n\n /**\n * The comment field of a rating, shown in a popover next to the chosen\n * thumb. Enter saves; Send appears once the text differs from the saved\n * comment. The popover marks itself `data-copilotkit-ignore`, so Learning\n * records the saved comment but not the typing; outside it, mark the\n * field yourself.\n */\n export const FeedbackComment: React.FC<{\n value: string;\n /** The comment already saved. */\n savedComment: string;\n inputRef?: React.Ref<HTMLInputElement>;\n onChange: (value: string) => void;\n onSubmit: () => void;\n onEditingChange?: (editing: boolean) => void;\n /**\n * Focus left the form for `next`, or for no focusable element when null.\n * Not called when the window loses focus.\n */\n onLeave?: (next: Element | null) => void;\n className?: string;\n }> = ({\n value,\n savedComment,\n inputRef,\n onChange,\n onSubmit,\n onEditingChange,\n onLeave,\n className,\n }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const changed = value.trim() !== savedComment;\n\n return (\n <form\n data-testid=\"copilot-feedback-comment\"\n className={cn(\"cpk-assistant-message-feedback-comment\", className)}\n onSubmit={(event) => {\n event.preventDefault();\n onSubmit();\n }}\n onFocus={() => onEditingChange?.(true)}\n onBlur={(event) => {\n const next =\n event.relatedTarget instanceof Element ? event.relatedTarget : null;\n if (event.currentTarget.contains(next)) return;\n // Switching to another window is not leaving the comment.\n if (typeof document !== \"undefined\" && !document.hasFocus()) return;\n onEditingChange?.(false);\n onLeave?.(next);\n }}\n >\n <input\n ref={inputRef}\n value={value}\n maxLength={ɵMESSAGE_FEEDBACK_MAX_COMMENT_LENGTH}\n onChange={(event) => onChange(event.target.value)}\n placeholder={labels.assistantMessageFeedbackCommentPlaceholder}\n aria-label={labels.assistantMessageFeedbackCommentPlaceholder}\n className=\"cpk-assistant-message-feedback-comment-input\"\n />\n {changed && (\n <Button\n type=\"submit\"\n variant=\"assistantMessageToolbarButton\"\n aria-label={labels.assistantMessageFeedbackCommentSubmitLabel}\n title={labels.assistantMessageFeedbackCommentSubmitLabel}\n >\n <CopilotIcon\n name=\"ArrowUp\"\n className=\"cpk-assistant-message-feedback-comment-submit-icon\"\n />\n </Button>\n )}\n </form>\n );\n };\n\n export const ReadAloudButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ title, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <ToolbarButton\n data-testid=\"copilot-read-aloud-button\"\n title={title || labels.assistantMessageToolbarReadAloudLabel}\n {...props}\n >\n <CopilotIcon\n name=\"Volume2\"\n className=\"cpk-assistant-message-read-aloud-icon\"\n />\n </ToolbarButton>\n );\n };\n\n export const RegenerateButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ title, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <ToolbarButton\n data-testid=\"copilot-regenerate-button\"\n title={title || labels.assistantMessageToolbarRegenerateLabel}\n {...props}\n >\n <CopilotIcon\n name=\"RefreshCw\"\n className=\"cpk-assistant-message-toolbar-icon\"\n />\n </ToolbarButton>\n );\n };\n}\n\nCopilotChatAssistantMessage.MarkdownRenderer.displayName =\n \"CopilotChatAssistantMessage.MarkdownRenderer\";\nCopilotChatAssistantMessage.Toolbar.displayName =\n \"CopilotChatAssistantMessage.Toolbar\";\nCopilotChatAssistantMessage.CopyButton.displayName =\n \"CopilotChatAssistantMessage.CopyButton\";\nCopilotChatAssistantMessage.InspectorButton.displayName =\n \"CopilotChatAssistantMessage.InspectorButton\";\nCopilotChatAssistantMessage.ThumbsUpButton.displayName =\n \"CopilotChatAssistantMessage.ThumbsUpButton\";\nCopilotChatAssistantMessage.ThumbsDownButton.displayName =\n \"CopilotChatAssistantMessage.ThumbsDownButton\";\nCopilotChatAssistantMessage.FeedbackComment.displayName =\n \"CopilotChatAssistantMessage.FeedbackComment\";\nCopilotChatAssistantMessage.ReadAloudButton.displayName =\n \"CopilotChatAssistantMessage.ReadAloudButton\";\nCopilotChatAssistantMessage.RegenerateButton.displayName =\n \"CopilotChatAssistantMessage.RegenerateButton\";\n\nexport default CopilotChatAssistantMessage;\n","import React, { useCallback, useEffect, useId, useRef, useState } from \"react\";\nimport { createPortal, flushSync } from \"react-dom\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport {\n CopilotChatDefaultLabels,\n ɵbindDialogFocus,\n ɵmorphViewTransition,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\ninterface LightboxProps {\n onClose: () => void;\n /** Accessible name of the dialog, for example the file name. */\n label?: string;\n children: React.ReactNode;\n}\n\n/**\n * A full-screen preview portalled to `document.body`. It closes on Escape, a\n * click on the backdrop, or its close button, which is named by\n * `labels.attachmentPreviewCloseButtonLabel`.\n *\n * It is a modal dialog for assistive technology: focus moves to the close\n * button when it opens, Tab stays inside it, and focus returns to the\n * element that opened it when it closes.\n */\nexport function Lightbox({ onClose, label, children }: LightboxProps) {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const rootRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const handleKey = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") onClose();\n };\n document.addEventListener(\"keydown\", handleKey);\n return () => document.removeEventListener(\"keydown\", handleKey);\n }, [onClose]);\n\n useEffect(() => {\n const root = rootRef.current;\n if (!root) return;\n return ɵbindDialogFocus(root);\n }, []);\n\n if (typeof document === \"undefined\") return null;\n\n return createPortal(\n <div\n ref={rootRef}\n className=\"cpk-attachment-lightbox\"\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label={label}\n onClick={onClose}\n >\n <button\n type=\"button\"\n onClick={onClose}\n className=\"cpk-attachment-lightbox-close-button\"\n aria-label={labels.attachmentPreviewCloseButtonLabel}\n >\n <CopilotIcon name=\"X\" className=\"cpk-attachment-lightbox-close-icon\" />\n </button>\n\n <div onClick={(e) => e.stopPropagation()}>{children}</div>\n </div>,\n document.body,\n );\n}\n\n/**\n * Hook that manages lightbox open/close and uses the View Transition API to\n * morph the thumbnail into fullscreen content.\n *\n * `view-transition-name` must live on exactly ONE element at a time: on the\n * thumbnail before the change and on the lightbox content (bind `vtName`)\n * after it. `flushSync` commits the change inside the transition so the API\n * can snapshot old → new correctly.\n */\nexport function useLightbox() {\n const thumbnailRef = useRef<HTMLElement>(null);\n const [open, setOpen] = useState(false);\n const vtName = useId();\n\n const openLightbox = useCallback(() => {\n ɵmorphViewTransition(\n thumbnailRef.current,\n vtName,\n () => flushSync(() => setOpen(true)),\n \"open\",\n );\n }, [vtName]);\n\n const closeLightbox = useCallback(() => {\n ɵmorphViewTransition(\n thumbnailRef.current,\n vtName,\n () => flushSync(() => setOpen(false)),\n \"close\",\n );\n }, [vtName]);\n\n return {\n thumbnailRef,\n vtName,\n open,\n openLightbox,\n closeLightbox,\n };\n}\n","import React, { memo, useState } from \"react\";\nimport type { InputContentSource } from \"@copilotkit/shared\";\nimport { getSourceUrl, getDocumentIcon } from \"@copilotkit/shared\";\nimport { CopilotChatDefaultLabels } from \"@copilotkit/core\";\nimport { cn } from \"../../lib/utils\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport { Lightbox, useLightbox } from \"./Lightbox\";\n\ninterface CopilotChatAttachmentRendererProps {\n type: \"image\" | \"audio\" | \"video\" | \"document\";\n source: InputContentSource;\n filename?: string;\n className?: string;\n}\n\n/** The chat labels from the nearest chat configuration, or the defaults. */\nfunction useLabels() {\n const config = useCopilotChatConfiguration();\n return config?.labels ?? CopilotChatDefaultLabels;\n}\n\nconst ImageAttachment = memo(function ImageAttachment({\n src,\n className,\n}: {\n src: string;\n className?: string;\n}) {\n const labels = useLabels();\n const [error, setError] = useState(false);\n const { thumbnailRef, vtName, open, openLightbox, closeLightbox } =\n useLightbox();\n\n if (error) {\n return (\n <div\n className={cn(\n \"cpk-attachment-renderer cpk-attachment-renderer-image-error\",\n className,\n )}\n >\n <span>{labels.attachmentImageLoadErrorText}</span>\n </div>\n );\n }\n\n return (\n <>\n <img\n ref={thumbnailRef as React.Ref<HTMLImageElement>}\n src={src}\n alt={labels.attachmentImageAltText}\n className={cn(\n \"cpk-attachment-renderer cpk-attachment-renderer-image\",\n className,\n )}\n onClick={openLightbox}\n onError={() => setError(true)}\n />\n {open && (\n <Lightbox onClose={closeLightbox} label={labels.attachmentImageAltText}>\n <img\n style={{ viewTransitionName: vtName }}\n src={src}\n alt={labels.attachmentImageAltText}\n className=\"cpk-attachment-renderer-lightbox-image\"\n />\n </Lightbox>\n )}\n </>\n );\n});\n\nconst AudioAttachment = memo(function AudioAttachment({\n src,\n filename,\n className,\n}: {\n src: string;\n filename?: string;\n className?: string;\n}) {\n return (\n <div\n className={cn(\n \"cpk-attachment-renderer cpk-attachment-renderer-audio\",\n className,\n )}\n >\n <audio\n src={src}\n controls\n preload=\"metadata\"\n className=\"cpk-attachment-renderer-audio-player\"\n />\n {filename && (\n <span className=\"cpk-attachment-renderer-audio-filename\">\n {filename}\n </span>\n )}\n </div>\n );\n});\n\nconst VideoAttachment = memo(function VideoAttachment({\n src,\n className,\n}: {\n src: string;\n className?: string;\n}) {\n return (\n <video\n src={src}\n controls\n preload=\"metadata\"\n className={cn(\n \"cpk-attachment-renderer cpk-attachment-renderer-video\",\n className,\n )}\n />\n );\n});\n\nconst DocumentAttachment = memo(function DocumentAttachment({\n src,\n source,\n filename,\n className,\n}: {\n src: string;\n source: InputContentSource;\n filename?: string;\n className?: string;\n}) {\n const labels = useLabels();\n const label = filename || source.mimeType || labels.attachmentDocumentAltText;\n\n // `download` is honoured for same-origin, data: and blob: URLs. Browsers\n // ignore it for cross-origin URLs unless the server sends\n // `Content-Disposition: attachment`; `target=\"_blank\"` keeps those from\n // navigating the chat away and lets the file open in a new tab instead.\n return (\n <a\n href={src}\n download={filename ?? \"\"}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n aria-label={label}\n className={cn(\n \"cpk-attachment-renderer cpk-attachment-renderer-document\",\n className,\n )}\n >\n <span className=\"cpk-attachment-renderer-document-icon\">\n {getDocumentIcon(source.mimeType ?? \"\")}\n </span>\n <span className=\"cpk-attachment-renderer-document-name\">\n {filename || source.mimeType || labels.attachmentUnknownTypeText}\n </span>\n </a>\n );\n});\n\nexport const CopilotChatAttachmentRenderer: React.FC<\n CopilotChatAttachmentRendererProps\n> = ({ type, source, filename, className }) => {\n const src = getSourceUrl(source);\n\n switch (type) {\n case \"image\":\n return <ImageAttachment src={src} className={className} />;\n case \"audio\":\n return (\n <AudioAttachment src={src} filename={filename} className={className} />\n );\n case \"video\":\n return <VideoAttachment src={src} className={className} />;\n case \"document\":\n return (\n <DocumentAttachment\n src={src}\n source={source}\n filename={filename}\n className={className}\n />\n );\n }\n};\n\nexport default CopilotChatAttachmentRenderer;\n","import { useMemo } from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport {\n CopilotChatDefaultLabels,\n ɵflattenUserMessageContent,\n ɵgetBranchNavState,\n ɵgetUserMessageMediaFilename,\n ɵgetUserMessageMediaParts,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport { cn } from \"../../lib/utils\";\nimport { Button } from \"../../components/ui/button\";\nimport type { UserMessage } from \"@ag-ui/core\";\nimport {\n Tooltip,\n TooltipContent,\n TooltipTrigger,\n} from \"../../components/ui/tooltip\";\nimport type { WithSlots } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport { copyToClipboard } from \"@copilotkit/shared\";\nimport { CopilotChatAttachmentRenderer } from \"./CopilotChatAttachmentRenderer\";\nimport { useCopyFeedback } from \"./use-copy-feedback\";\n\nexport interface CopilotChatUserMessageOnEditMessageProps {\n message: UserMessage;\n}\n\nexport interface CopilotChatUserMessageOnSwitchToBranchProps {\n message: UserMessage;\n branchIndex: number;\n numberOfBranches: number;\n}\n\nexport type CopilotChatUserMessageProps = WithSlots<\n {\n messageRenderer: typeof CopilotChatUserMessage.MessageRenderer;\n toolbar: typeof CopilotChatUserMessage.Toolbar;\n copyButton: typeof CopilotChatUserMessage.CopyButton;\n editButton: typeof CopilotChatUserMessage.EditButton;\n branchNavigation: typeof CopilotChatUserMessage.BranchNavigation;\n },\n {\n onEditMessage?: (props: CopilotChatUserMessageOnEditMessageProps) => void;\n onSwitchToBranch?: (\n props: CopilotChatUserMessageOnSwitchToBranchProps,\n ) => void;\n message: UserMessage;\n branchIndex?: number;\n numberOfBranches?: number;\n additionalToolbarItems?: React.ReactNode;\n } & React.HTMLAttributes<HTMLDivElement>\n>;\n\nexport function CopilotChatUserMessage({\n message,\n onEditMessage,\n branchIndex,\n numberOfBranches,\n onSwitchToBranch,\n additionalToolbarItems,\n messageRenderer,\n toolbar,\n copyButton,\n editButton,\n branchNavigation,\n children,\n className,\n ...props\n}: CopilotChatUserMessageProps) {\n const flattenedContent = useMemo(\n () => ɵflattenUserMessageContent(message.content),\n [message.content],\n );\n\n const mediaParts = useMemo(\n () => ɵgetUserMessageMediaParts(message.content),\n [message.content],\n );\n\n const BoundMessageRenderer = renderSlot(\n messageRenderer,\n CopilotChatUserMessage.MessageRenderer,\n {\n content: flattenedContent,\n },\n );\n\n const BoundCopyButton = renderSlot(\n copyButton,\n CopilotChatUserMessage.CopyButton,\n {\n onClick: async () => {\n if (flattenedContent) {\n return await copyToClipboard(flattenedContent);\n }\n return false;\n },\n },\n );\n\n const BoundEditButton = renderSlot(\n editButton,\n CopilotChatUserMessage.EditButton,\n {\n onClick: () => onEditMessage?.({ message }),\n },\n );\n\n const BoundBranchNavigation = renderSlot(\n branchNavigation,\n CopilotChatUserMessage.BranchNavigation,\n {\n currentBranch: branchIndex,\n numberOfBranches,\n onSwitchToBranch,\n message,\n },\n );\n\n const { show: showBranchNavigation } = ɵgetBranchNavState({\n branchIndex: branchIndex ?? 0,\n numberOfBranches: numberOfBranches ?? 1,\n canSwitch: onSwitchToBranch !== undefined,\n });\n\n const BoundToolbar = renderSlot(toolbar, CopilotChatUserMessage.Toolbar, {\n children: (\n <div className=\"cpk-user-message-toolbar-items\">\n {additionalToolbarItems}\n {BoundCopyButton}\n {onEditMessage && BoundEditButton}\n {showBranchNavigation && BoundBranchNavigation}\n </div>\n ),\n });\n\n if (children) {\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children({\n messageRenderer: BoundMessageRenderer,\n toolbar: BoundToolbar,\n copyButton: BoundCopyButton,\n editButton: BoundEditButton,\n branchNavigation: BoundBranchNavigation,\n message,\n branchIndex,\n numberOfBranches,\n additionalToolbarItems,\n })}\n </div>\n );\n }\n\n return (\n <div\n data-copilotkit\n data-testid=\"copilot-user-message\"\n className={cn(\n \"copilotKitMessage copilotKitUserMessage cpk-user-message\",\n className,\n )}\n data-message-id={message.id}\n {...props}\n >\n {mediaParts.length > 0 && (\n <div className=\"cpk-user-message-attachments\">\n {mediaParts.map((part, index) => (\n <CopilotChatAttachmentRenderer\n key={index}\n type={part.type}\n source={part.source}\n filename={ɵgetUserMessageMediaFilename(part)}\n />\n ))}\n </div>\n )}\n {BoundMessageRenderer}\n {BoundToolbar}\n </div>\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace CopilotChatUserMessage {\n export const Container: React.FC<\n React.PropsWithChildren<React.HTMLAttributes<HTMLDivElement>>\n > = ({ children, className, ...props }) => (\n <div className={cn(\"cpk-user-message-container\", className)} {...props}>\n {children}\n </div>\n );\n\n export const MessageRenderer: React.FC<{\n content: string;\n className?: string;\n }> = ({ content, className }) => (\n <div className={cn(\"cpk-user-message-bubble\", className)}>{content}</div>\n );\n\n export const Toolbar: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({\n className,\n ...props\n }) => (\n <div\n data-testid=\"copilot-user-toolbar\"\n className={cn(\"cpk-user-message-toolbar\", className)}\n {...props}\n />\n );\n\n export const ToolbarButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement> & {\n title: string;\n children: React.ReactNode;\n }\n > = ({ title, children, className, ...props }) => {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <Button\n type=\"button\"\n variant=\"assistantMessageToolbarButton\"\n aria-label={title}\n className={className}\n {...props}\n >\n {children}\n </Button>\n </TooltipTrigger>\n <TooltipContent side=\"bottom\">\n <p>{title}</p>\n </TooltipContent>\n </Tooltip>\n );\n };\n\n export const CopyButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement> & { copied?: boolean }\n > = ({ className, title, onClick, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const { copied, markCopied } = useCopyFeedback();\n\n const handleClick = async (event: React.MouseEvent<HTMLButtonElement>) => {\n if (!onClick) return;\n // onClick may return a boolean indicating copy success\n const result: unknown = await Promise.resolve(onClick(event));\n if (result === true) markCopied();\n };\n\n return (\n <ToolbarButton\n data-testid=\"copilot-user-copy-button\"\n title={title || labels.userMessageToolbarCopyMessageLabel}\n onClick={(event) => {\n void handleClick(event);\n }}\n className={className}\n {...props}\n >\n {copied ? (\n <CopilotIcon name=\"Check\" className=\"cpk-user-message-toolbar-icon\" />\n ) : (\n <CopilotIcon name=\"Copy\" className=\"cpk-user-message-toolbar-icon\" />\n )}\n </ToolbarButton>\n );\n };\n\n export const EditButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ className, title, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <ToolbarButton\n data-testid=\"copilot-edit-button\"\n title={title || labels.userMessageToolbarEditMessageLabel}\n className={className}\n {...props}\n >\n <CopilotIcon name=\"Edit\" className=\"cpk-user-message-toolbar-icon\" />\n </ToolbarButton>\n );\n };\n\n /**\n * Previous/next buttons and an \"n/m\" counter for switching between branches\n * of a user message. Renders only with more than one branch and an\n * `onSwitchToBranch` handler. The buttons are named by\n * `labels.userMessageToolbarPreviousBranchLabel` and\n * `labels.userMessageToolbarNextBranchLabel`.\n */\n export const BranchNavigation: React.FC<\n React.HTMLAttributes<HTMLDivElement> & {\n currentBranch?: number;\n numberOfBranches?: number;\n onSwitchToBranch?: (\n props: CopilotChatUserMessageOnSwitchToBranchProps,\n ) => void;\n message: UserMessage;\n }\n > = ({\n className,\n currentBranch = 0,\n numberOfBranches = 1,\n onSwitchToBranch,\n message,\n ...props\n }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n\n const { show, canGoPrev, canGoNext } = ɵgetBranchNavState({\n branchIndex: currentBranch,\n numberOfBranches,\n canSwitch: onSwitchToBranch !== undefined,\n });\n if (!show) return null;\n\n return (\n <div\n data-testid=\"copilot-branch-navigation\"\n className={cn(\"cpk-user-message-branch-navigation\", className)}\n {...props}\n >\n <Button\n type=\"button\"\n variant=\"assistantMessageToolbarButton\"\n onClick={() =>\n onSwitchToBranch?.({\n branchIndex: currentBranch - 1,\n numberOfBranches,\n message,\n })\n }\n disabled={!canGoPrev}\n className=\"cpk-user-message-branch-button\"\n aria-label={labels.userMessageToolbarPreviousBranchLabel}\n >\n <CopilotIcon\n name=\"ChevronLeft\"\n className=\"cpk-user-message-branch-icon\"\n />\n </Button>\n <span className=\"cpk-user-message-branch-counter\">\n {currentBranch + 1}/{numberOfBranches}\n </span>\n <Button\n type=\"button\"\n variant=\"assistantMessageToolbarButton\"\n onClick={() =>\n onSwitchToBranch?.({\n branchIndex: currentBranch + 1,\n numberOfBranches,\n message,\n })\n }\n disabled={!canGoNext}\n className=\"cpk-user-message-branch-button\"\n aria-label={labels.userMessageToolbarNextBranchLabel}\n >\n <CopilotIcon\n name=\"ChevronRight\"\n className=\"cpk-user-message-branch-icon\"\n />\n </Button>\n </div>\n );\n };\n}\n\nCopilotChatUserMessage.Container.displayName =\n \"CopilotChatUserMessage.Container\";\nCopilotChatUserMessage.MessageRenderer.displayName =\n \"CopilotChatUserMessage.MessageRenderer\";\nCopilotChatUserMessage.Toolbar.displayName = \"CopilotChatUserMessage.Toolbar\";\nCopilotChatUserMessage.ToolbarButton.displayName =\n \"CopilotChatUserMessage.ToolbarButton\";\nCopilotChatUserMessage.CopyButton.displayName =\n \"CopilotChatUserMessage.CopyButton\";\nCopilotChatUserMessage.EditButton.displayName =\n \"CopilotChatUserMessage.EditButton\";\nCopilotChatUserMessage.BranchNavigation.displayName =\n \"CopilotChatUserMessage.BranchNavigation\";\n\nexport default CopilotChatUserMessage;\n","import type { ReasoningMessage, Message } from \"@ag-ui/core\";\nimport { useEffect, useState, useSyncExternalStore } from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport { cn } from \"../../lib/utils\";\nimport { StreamingMarkdownDefaultRenderer } from \"./StreamingMarkdownDefaultRenderer\";\nimport type { WithSlots } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport {\n CopilotChatDefaultLabels,\n ɵgetReasoningHeaderLabel,\n ɵReasoningDisclosure,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\nexport type CopilotChatReasoningMessageProps = WithSlots<\n {\n header: typeof CopilotChatReasoningMessage.Header;\n contentView: typeof CopilotChatReasoningMessage.Content;\n toggle: typeof CopilotChatReasoningMessage.Toggle;\n },\n {\n message: ReasoningMessage;\n messages?: Message[];\n isRunning?: boolean;\n /**\n * Whether this is the last message the chat renders. The message view\n * passes it, because the rendered list can differ from `messages` when\n * `transformMessages` drops, replaces or reorders messages. Defaults to\n * comparing against the last entry of `messages`.\n */\n isLatest?: boolean;\n } & React.HTMLAttributes<HTMLDivElement>\n>;\n\n/**\n * A reasoning message as a collapsible block. While the model reasons it is\n * open and the header shows `labels.reasoningMessageThinkingLabel`; when\n * streaming ends it collapses and the header reads\n * `labels.reasoningMessageThoughtForLabel` (\"Thought for 4 seconds\"). The\n * `header` slot also receives `elapsedSeconds`.\n */\nexport function CopilotChatReasoningMessage({\n message,\n messages,\n isRunning,\n isLatest: isLatestProp,\n header,\n contentView,\n toggle,\n children,\n className,\n ...props\n}: CopilotChatReasoningMessageProps) {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const isLatest =\n isLatestProp ?? messages?.[messages.length - 1]?.id === message.id;\n const isStreaming = !!(isRunning && isLatest);\n const hasContent = !!(message.content && message.content.length > 0);\n\n // Open while streaming, auto-collapse when it ends unless the user\n // toggled, and the elapsed time: see core's ɵReasoningDisclosure.\n const [disclosure] = useState(\n () => new ɵReasoningDisclosure({ isStreaming }),\n );\n const { isOpen, elapsedSeconds: elapsed } = useSyncExternalStore(\n disclosure.subscribe,\n disclosure.getSnapshot,\n disclosure.getSnapshot,\n );\n useEffect(() => {\n disclosure.setStreaming(isStreaming);\n }, [disclosure, isStreaming]);\n useEffect(() => disclosure.dispose, [disclosure]);\n\n const handleToggle = hasContent ? disclosure.toggle : undefined;\n\n const label = ɵgetReasoningHeaderLabel(\n { isStreaming, elapsedSeconds: elapsed },\n labels,\n );\n\n const boundHeader = renderSlot(header, CopilotChatReasoningMessage.Header, {\n isOpen,\n label,\n hasContent,\n isStreaming,\n elapsedSeconds: elapsed,\n onClick: handleToggle,\n });\n\n const boundContent = renderSlot(\n contentView,\n CopilotChatReasoningMessage.Content,\n {\n isStreaming,\n hasContent,\n children: message.content,\n },\n );\n\n const boundToggle = renderSlot(toggle, CopilotChatReasoningMessage.Toggle, {\n isOpen,\n children: boundContent,\n });\n\n if (children) {\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children({\n header: boundHeader,\n contentView: boundContent,\n toggle: boundToggle,\n message,\n messages,\n isRunning,\n })}\n </div>\n );\n }\n\n return (\n <div\n className={cn(\"cpk-reasoning-message\", className)}\n data-message-id={message.id}\n {...props}\n >\n {boundHeader}\n {boundToggle}\n </div>\n );\n}\n\nexport namespace CopilotChatReasoningMessage {\n export const Header: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement> & {\n isOpen?: boolean;\n label?: string;\n hasContent?: boolean;\n isStreaming?: boolean;\n /**\n * Seconds spent reasoning so far, updated every second while streaming.\n * The default label formats it in English (\"Thought for 12 seconds\");\n * a custom header can use it to build a localized label.\n */\n elapsedSeconds?: number;\n }\n > = ({\n isOpen,\n label = \"Thoughts\",\n hasContent,\n isStreaming,\n elapsedSeconds: _elapsedSeconds,\n className,\n children: headerChildren,\n ...headerProps\n }) => {\n const isExpandable = !!hasContent;\n\n return (\n <button\n type=\"button\"\n className={cn(\n \"cpk-reasoning-message-header\",\n isExpandable && \"cpk-reasoning-message-header-expandable\",\n className,\n )}\n aria-expanded={isExpandable ? isOpen : undefined}\n {...headerProps}\n >\n <span\n className={cn(\n \"cpk-reasoning-message-label\",\n isStreaming && \"cpk-shimmer\",\n )}\n >\n {label}\n </span>\n {isStreaming && !hasContent && (\n <span className=\"cpk-reasoning-message-indicator\">\n <span className=\"cpk-reasoning-message-indicator-dot\" />\n </span>\n )}\n {headerChildren}\n {isExpandable && (\n <CopilotIcon\n name=\"ChevronRight\"\n className={cn(\n \"cpk-reasoning-message-chevron\",\n isOpen && \"cpk-reasoning-message-chevron-open\",\n )}\n />\n )}\n </button>\n );\n };\n\n export const Content: React.FC<\n React.HTMLAttributes<HTMLDivElement> & {\n isStreaming?: boolean;\n hasContent?: boolean;\n }\n > = ({\n isStreaming,\n hasContent,\n className,\n children: contentChildren,\n ...contentProps\n }) => {\n // Don't render the content area at all when there's nothing to show\n if (!hasContent && !isStreaming) return null;\n\n return (\n <div\n className={cn(\"cpk-reasoning-message-content\", className)}\n {...contentProps}\n >\n <div className=\"cpk-reasoning-message-text\">\n {/* Reasoning content always uses the built-in streaming renderer; the\n pluggable provider renderer applies to assistant messages only. */}\n <StreamingMarkdownDefaultRenderer\n content={typeof contentChildren === \"string\" ? contentChildren : \"\"}\n isStreaming={isStreaming}\n />\n {isStreaming && hasContent && (\n <span className=\"cpk-reasoning-message-cursor\">\n <span className=\"cpk-reasoning-message-cursor-dot\" />\n </span>\n )}\n </div>\n </div>\n );\n };\n\n export const Toggle: React.FC<\n React.HTMLAttributes<HTMLDivElement> & {\n isOpen?: boolean;\n }\n > = ({ isOpen, className, children: toggleChildren, ...toggleProps }) => {\n return (\n <div\n className={cn(\"cpk-reasoning-message-toggle\", className)}\n style={{ gridTemplateRows: isOpen ? \"1fr\" : \"0fr\" }}\n {...toggleProps}\n >\n <div className=\"cpk-reasoning-message-toggle-content\">\n {toggleChildren}\n </div>\n </div>\n );\n };\n}\n\nCopilotChatReasoningMessage.Header.displayName =\n \"CopilotChatReasoningMessage.Header\";\nCopilotChatReasoningMessage.Content.displayName =\n \"CopilotChatReasoningMessage.Content\";\nCopilotChatReasoningMessage.Toggle.displayName =\n \"CopilotChatReasoningMessage.Toggle\";\n\nexport default CopilotChatReasoningMessage;\n","import React from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\n\nexport interface CopilotChatSuggestionPillProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {\n /** Optional icon to render on the left side when not loading. */\n icon?: React.ReactNode;\n /** Whether the pill should display a loading spinner. */\n isLoading?: boolean;\n}\n\nexport const CopilotChatSuggestionPill = React.forwardRef<\n HTMLButtonElement,\n CopilotChatSuggestionPillProps\n>(function CopilotChatSuggestionPill(\n { className, children, icon, isLoading, type, ...props },\n ref,\n) {\n const showIcon = !isLoading && icon;\n\n return (\n <button\n ref={ref}\n data-copilotkit\n data-testid=\"copilot-suggestion\"\n data-slot=\"suggestion-pill\"\n className={\n className ? `cpk-suggestion-pill ${className}` : \"cpk-suggestion-pill\"\n }\n type={type ?? \"button\"}\n aria-busy={isLoading || undefined}\n disabled={isLoading || props.disabled}\n {...props}\n >\n {isLoading ? (\n <span className=\"cpk-suggestion-pill-icon\">\n <CopilotIcon\n name=\"Loader2\"\n className=\"cpk-suggestion-pill-spinner\"\n aria-hidden=\"true\"\n />\n </span>\n ) : (\n showIcon && <span className=\"cpk-suggestion-pill-icon\">{icon}</span>\n )}\n <span className=\"cpk-suggestion-pill-label\">{children}</span>\n </button>\n );\n});\n\nCopilotChatSuggestionPill.displayName = \"CopilotChatSuggestionPill\";\n\nexport default CopilotChatSuggestionPill;\n","import React from \"react\";\nimport type { Suggestion } from \"@copilotkit/core\";\nimport type { WithSlots } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport { cn } from \"../../lib/utils\";\nimport type { CopilotChatSuggestionPillProps } from \"./CopilotChatSuggestionPill\";\nimport CopilotChatSuggestionPill from \"./CopilotChatSuggestionPill\";\n\nconst DefaultContainer = React.forwardRef<\n HTMLDivElement,\n React.HTMLAttributes<HTMLDivElement>\n>(function DefaultContainer({ className, ...props }, ref) {\n return (\n <div\n ref={ref}\n data-copilotkit\n data-testid=\"copilot-suggestions\"\n className={cn(\"cpk-suggestion-view\", className)}\n {...props}\n />\n );\n});\n\nexport type CopilotChatSuggestionViewProps = WithSlots<\n {\n container: typeof DefaultContainer;\n suggestion: typeof CopilotChatSuggestionPill;\n },\n {\n suggestions: Suggestion[];\n onSelectSuggestion?: (suggestion: Suggestion, index: number) => void;\n loadingIndexes?: ReadonlyArray<number>;\n } & React.HTMLAttributes<HTMLDivElement>\n>;\n\nexport const CopilotChatSuggestionView = React.forwardRef<\n HTMLDivElement,\n CopilotChatSuggestionViewProps\n>(function CopilotChatSuggestionView(\n {\n suggestions,\n onSelectSuggestion,\n loadingIndexes,\n container,\n suggestion: suggestionSlot,\n className,\n children,\n ...restProps\n },\n ref,\n) {\n const loadingSet = React.useMemo(() => {\n if (!loadingIndexes || loadingIndexes.length === 0) {\n return new Set<number>();\n }\n return new Set(loadingIndexes);\n }, [loadingIndexes]);\n\n const ContainerElement = renderSlot(container, DefaultContainer, {\n ref,\n className,\n ...restProps,\n });\n\n const suggestionElements = suggestions.map((suggestion, index) => {\n const isLoading = loadingSet.has(index) || suggestion.isLoading === true;\n const pill = renderSlot<\n typeof CopilotChatSuggestionPill,\n CopilotChatSuggestionPillProps\n >(suggestionSlot, CopilotChatSuggestionPill, {\n children: suggestion.title,\n className: suggestion.className,\n isLoading,\n type: \"button\",\n onClick: () => onSelectSuggestion?.(suggestion, index),\n });\n\n return React.cloneElement(pill, {\n key: `${suggestion.title}-${index}`,\n });\n });\n\n const boundContainer = React.cloneElement(\n ContainerElement,\n undefined,\n suggestionElements,\n );\n\n if (typeof children === \"function\") {\n const sampleSuggestion = renderSlot<\n typeof CopilotChatSuggestionPill,\n CopilotChatSuggestionPillProps\n >(suggestionSlot, CopilotChatSuggestionPill, {\n children: suggestions[0]?.title ?? \"\",\n isLoading:\n suggestions.length > 0\n ? loadingSet.has(0) || suggestions[0]?.isLoading === true\n : false,\n type: \"button\",\n });\n\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children({\n container: boundContainer,\n suggestion: sampleSuggestion,\n suggestions,\n onSelectSuggestion,\n loadingIndexes,\n className,\n ...restProps,\n })}\n </div>\n );\n }\n\n if (children) {\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {boundContainer}\n {children}\n </div>\n );\n }\n\n return boundContainer;\n});\n\nCopilotChatSuggestionView.displayName = \"CopilotChatSuggestionView\";\n\nexport default CopilotChatSuggestionView;\n","import React from \"react\";\n\n/**\n * Provides the scroll container element to child components that need it for\n * virtualization. Set by CopilotChatView.ScrollView; consumed by\n * CopilotChatMessageView to feed useVirtualizer's getScrollElement.\n *\n * Carries the element itself (not a ref) so that context consumers re-render\n * reactively when the scroll container is first mounted.\n */\nexport const ScrollElementContext = React.createContext<HTMLElement | null>(\n null,\n);\n","import React from \"react\";\n\n/**\n * True while the pin-to-bottom behaviour is actively following the bottom of\n * the thread — i.e. `use-stick-to-bottom` will animate the scroll position to\n * the bottom the next time the content grows.\n *\n * Only CopilotChatView's pin-to-bottom branch provides this. The other scroll\n * modes leave it `false`, which is correct: nothing else writes the scroll\n * position on its own, so no one is competing with the virtualizer.\n *\n * Why this exists: the virtualizer and `use-stick-to-bottom` both write\n * `scrollTop` on the same element. The virtualizer writes it to compensate\n * when a row above the viewport turns out taller than its estimate, so that\n * what the reader is looking at does not shift. That compensation is essential\n * while the reader is scrolled up — and pointless while pinned to the bottom,\n * because the pin is about to move the scroll position anyway. Worse than\n * pointless: the compensation changes the virtual container's height, the pin\n * reads that as content growth and animates, the animation brings unmeasured\n * rows into view, they measure, and the two keep shoving each other.\n *\n * Consumed by CopilotChatMessageView to stand the virtualizer down while the\n * pin owns the scroll position.\n */\nexport const ScrollPinnedContext = React.createContext<boolean>(false);\n","import React, { useEffect, useState } from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport {\n CopilotChatDefaultLabels,\n ɵgetWorkSummaryText,\n} from \"@copilotkit/core\";\nimport type { ToolCallEntry } from \"@copilotkit/core\";\nimport { cn } from \"../../lib/utils\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\nexport interface CopilotChatWorkSummaryProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {\n /** The agent is still working on this reply. */\n isWorking: boolean;\n /** Whether the work (narration and tool calls) is showing. */\n isOpen: boolean;\n /** The tool calls the reply made. */\n calls: ToolCallEntry[];\n /**\n * How long the agent has worked on the reply, in ms, summed over its runs\n * so time spent waiting between them doesn't count. Only known for replies\n * this client watched start; without it the summary shows the tool count.\n */\n elapsedMs?: number;\n /** When the current run started (epoch ms), while the agent is working. */\n workingSince?: number;\n}\n\n/** Re-renders every second while `active`, returning the current time. */\nfunction useNow(active: boolean): number {\n const [now, setNow] = useState(() => Date.now());\n useEffect(() => {\n if (!active) return;\n setNow(Date.now());\n const timer = setInterval(() => setNow(Date.now()), 1000);\n return () => clearInterval(timer);\n }, [active]);\n return now;\n}\n\n/**\n * The line at the top of a reply in the `\"turn\"` tool-call display. While the\n * agent works it reads \"Working 4s\". Once the reply is done it reads \"Worked\n * for 9s\" and \"7 tools\", and toggles the work it folded away. The text comes\n * from the `workSummary...` and `toolCall...` chat labels.\n */\nexport function CopilotChatWorkSummary({\n isWorking,\n isOpen,\n calls,\n elapsedMs,\n workingSince,\n className,\n ...props\n}: CopilotChatWorkSummaryProps) {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const now = useNow(isWorking);\n const text = ɵgetWorkSummaryText({\n isWorking,\n calls,\n elapsedMs,\n workingSince,\n now,\n labels,\n });\n\n return (\n <button\n type=\"button\"\n data-copilotkit\n data-testid=\"copilot-work-summary\"\n data-state={isWorking ? \"working\" : \"done\"}\n aria-expanded={isOpen}\n className={cn(\"cpk-work-summary\", className)}\n {...props}\n >\n <span\n className={cn(\"cpk-work-summary-label\", isWorking && \"cpk-shimmer\")}\n >\n {text.label}\n </span>\n {text.detail !== null && (\n <span\n className={cn(\n \"cpk-work-summary-detail\",\n isWorking && \"cpk-work-summary-timer\",\n )}\n >\n {text.detail}\n </span>\n )}\n {text.failed !== null && (\n <span className=\"cpk-work-summary-failed\">{text.failed}</span>\n )}\n <CopilotIcon\n name=\"ChevronRight\"\n aria-hidden=\"true\"\n className={cn(\n \"cpk-work-summary-chevron\",\n isOpen && \"cpk-work-summary-chevron-open\",\n )}\n />\n </button>\n );\n}\n\nexport default CopilotChatWorkSummary;\n","import React from \"react\";\nimport { cn } from \"../../lib/utils\";\nimport type { Message } from \"@ag-ui/core\";\n\n/** Lifecycle state the brain hands the face. */\nexport type IntelligenceIndicatorStatus = \"in-progress\" | \"finished\";\n\nexport interface IntelligenceIndicatorViewProps extends React.HTMLAttributes<HTMLSpanElement> {\n /** The assistant message this indicator is attached to. */\n message: Message;\n /**\n * Whether the intelligence work is still running (`in-progress`) or\n * has settled (`finished`). Drives the icon morph and chrome\n * fade-out via the `data-status` attribute on the wrapper.\n */\n status: IntelligenceIndicatorStatus;\n /** The visible label, e.g. \"Using CopilotKit Intelligence\". */\n label: string;\n}\n\n/**\n * The presentational \"CopilotKit Intelligence\" face — the default\n * rendered by the {@link IntelligenceIndicator} brain and the default\n * value for the `intelligenceIndicator` slot.\n *\n * Layout: a glassmorphism pill (the `__chrome` layer) wrapping an icon\n * and a label. The icon is two overlaid SVG paths — a spinner arc and a\n * checkmark — whose geometry lives in each path's `d` ATTRIBUTE so it\n * renders in every browser (the CSS `d:` property is Chrome-only).\n *\n * Two states, driven by the `data-status` attribute (see styles/css/intelligence-indicator.css\n * for the exact timing):\n * 1. **In-progress.** The arc spins (CSS rotation) inside the pill and\n * the checkmark is hidden. Label + icon are a saturated purple.\n * 2. **Finished.** The arc fades out mid-spin while the checkmark draws\n * itself in upright (animated `stroke-dashoffset`); the pill chrome\n * fades away; and the label + icon settle from purple to a neutral\n * gray, with the label slanting slightly (a `transform: skewX`\n * faux-italic, so it interpolates with the color instead of snapping\n * and never reflows). The result reads as quiet \"history metadata\"\n * rather than an active spinner. The label text itself never changes\n * — the static check plus the color/slant shift carry the \"done\"\n * meaning, so no wording change is needed.\n *\n * All motion is gated behind `prefers-reduced-motion` (styles/css/intelligence-indicator.css):\n * when reduced motion is requested the arc does not spin and the two\n * states swap instantly, without transitions.\n *\n * Customize via the `intelligenceIndicator` slot on `CopilotChat`:\n * a className string restyles the wrapper, a props object tweaks\n * the default (`{ label }`), and a component replaces it entirely\n * with full control over visuals and timing.\n */\nexport function IntelligenceIndicatorView({\n message,\n status,\n label,\n className,\n ...rest\n}: IntelligenceIndicatorViewProps): React.ReactElement {\n return (\n <span\n className={cn(\"cpk-intelligence-indicator\", className)}\n role=\"status\"\n aria-live=\"polite\"\n data-testid={`cpk-intelligence-indicator-${message.id}`}\n data-status={status}\n title={label}\n {...rest}\n >\n {/* Chrome layer — bg, border, shadow, backdrop-blur. Sits behind\n the content via `position: absolute; inset: 0`. Fades to zero\n opacity once the icon morph completes. */}\n <span className=\"cpk-intelligence-indicator__chrome\" aria-hidden=\"true\" />\n\n {/* Content layer — icon + label. Stays put across the whole\n transition; only its color alpha drops on settle. */}\n <span className=\"cpk-intelligence-indicator__content\">\n <svg\n className=\"cpk-intelligence-indicator__icon\"\n viewBox=\"0 0 24 24\"\n width=\"14\"\n height=\"14\"\n aria-hidden=\"true\"\n >\n {/* Two overlaid paths whose geometry lives in the `d`\n ATTRIBUTE (works in every browser — the CSS `d:` property\n is Blink-only, so a stylesheet-driven `d` renders nothing\n in Safari/Firefox). Both paths set `pathLength={1}` so the\n stylesheet can express dashes as plain fractions of the\n shape. The arc is a full circle shown as a partial ring by\n its dash pattern; it spins while in-progress (CSS) and on\n the status flip fades out mid-spin while the checkmark\n draws itself in (see styles/css/intelligence-indicator.css). */}\n <path\n className=\"cpk-intelligence-indicator__icon-arc\"\n pathLength={1}\n d=\"M 12 3 C 17 3 21 7 21 12 C 21 17 17 21 12 21 C 7 21 3 17 3 12 C 3 7 7 3 12 3\"\n />\n <path\n className=\"cpk-intelligence-indicator__icon-check\"\n pathLength={1}\n d=\"M 5 12.5 L 9 16.5 L 19 6.5\"\n />\n </svg>\n <span className=\"cpk-intelligence-indicator__label\">{label}</span>\n </span>\n </span>\n );\n}\n","import React, { useEffect, useMemo, useState } from \"react\";\nimport type { Message } from \"@ag-ui/core\";\nimport { useCopilotKit } from \"../../providers/CopilotKitProvider\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport { useAgent, UseAgentUpdate } from \"../../hooks/use-agent\";\nimport { renderSlot } from \"../../lib/slots\";\nimport type { SlotValue } from \"../../lib/slots\";\nimport { IntelligenceIndicatorView } from \"./IntelligenceIndicatorView\";\n\n/**\n * Grace window before showing the spinner. A matching tool call must\n * remain unresolved (no `tool`-role result message in `agent.messages`)\n * for at least this long before the indicator transitions out of\n * `hidden`. This filters out history-replay flashes — during\n * `connectAgent` replay, tool calls and their results arrive\n * back-to-back in sub-millisecond bursts, so the timer is cancelled\n * before it fires. Live runs cross the threshold easily because the\n * tool actually has to execute.\n */\nconst PENDING_THRESHOLD_MS = 100;\n\n/**\n * Tool-name regex patterns that trigger the indicator. Matches any tool\n * name *containing* the Intelligence MCP server's canonical tool name, so\n * both the bare `copilotkit_knowledge_base_shell` and the namespaced\n * `mcp__<server>__copilotkit_knowledge_base_shell` form (emitted by\n * `@ag-ui/mcp-middleware`) light up the pill. If we add per-instance\n * customization later (e.g. a `CopilotKitProvider` prop or a runtime-info\n * field), this constant becomes the fallback.\n */\nconst DEFAULT_TOOL_PATTERNS: readonly RegExp[] = [\n /copilotkit_knowledge_base_shell/,\n];\n\n/**\n * Phase machine. Once `finished` is reached the indicator persists\n * indefinitely; placement (one indicator per turn, at the turn's first\n * bash-using message) is owned by `getIntelligenceTurnAnchors`, not by\n * this machine.\n */\nexport type Phase = \"hidden\" | \"spinner\" | \"finished\";\n\n/**\n * Phase to start in when an indicator first mounts. A turn that is already\n * complete at mount jumps straight to `finished` — no `hidden` flash, no\n * spinner blip — which is what makes scrolled-back / replayed history render\n * its indicators directly in the finished state.\n *\n * Pure and timing-free on purpose: the grace window ({@link\n * PENDING_THRESHOLD_MS}) only controls *when* the live transition is applied;\n * these functions decide *what* it resolves to, so the decision can be unit\n * tested deterministically without any timers.\n */\nexport function initialIndicatorPhase(turnComplete: boolean): Phase {\n return turnComplete ? \"finished\" : \"hidden\";\n}\n\n/**\n * Phase the grace window resolves to once it elapses:\n * - completed turn → `finished` (replay-flash suppression: a tool whose\n * result lands within the window skips the spinner entirely),\n * - a still-pending matching tool call → `spinner`,\n * - otherwise stay `hidden` (the matching tool call hasn't landed yet).\n */\nexport function resolveGracePhase(\n turnComplete: boolean,\n hasPending: boolean,\n): Phase {\n if (turnComplete) return \"finished\";\n if (hasPending) return \"spinner\";\n return \"hidden\";\n}\n\nexport interface IntelligenceIndicatorProps {\n /** The message this indicator is attached to. */\n message: Message;\n /**\n * Agent id whose run state the indicator tracks. Pass through from\n * the surrounding chat configuration; mounting from\n * `CopilotChatMessageView` resolves this automatically.\n */\n agentId: string;\n /**\n * Optional override for the visible label. Defaults to\n * \"CopilotKit Intelligence\".\n */\n label?: string;\n /**\n * Slot override for the presentational face. A className string, a\n * props object, or a full replacement component — see\n * {@link IntelligenceIndicatorView}. Forwarded from the\n * `intelligenceIndicator` slot on `CopilotChat`.\n */\n intelligenceIndicator?: SlotValue<typeof IntelligenceIndicatorView>;\n}\n\nconst isMatchingToolCallName = (name: unknown): boolean =>\n typeof name === \"string\" && DEFAULT_TOOL_PATTERNS.some((p) => p.test(name));\n\nconst messageHasMatchingToolCall = (m: Message): boolean => {\n if (m.role !== \"assistant\") return false;\n const tcs = Array.isArray(m.toolCalls) ? m.toolCalls : [];\n return tcs.some((tc) => isMatchingToolCallName(tc?.function?.name));\n};\n\n/**\n * Stable turn id for the messages that precede the first user message (a turn\n * with no opening user message of its own). Used as the React key so the\n * indicator for that turn never collides with a real user-message id.\n */\nexport const INTELLIGENCE_TURN_HEAD = \"__cpk_turn_head__\";\n\n/**\n * Map each Intelligence-using turn to its anchor message — the FIRST bash-using\n * assistant message of the turn — and a stable turn id (the id of the user\n * message that opened the turn, or {@link INTELLIGENCE_TURN_HEAD} for the\n * pre-first-user turn). Returns `Map<anchorMessageId, turnId>`.\n *\n * Anchoring to the FIRST (not last) bash-using message keeps the indicator\n * fixed in place for the whole turn: later bash steps don't reposition it, so\n * the spinner never abruptly jumps mid-turn (bug 1). `CopilotChatMessageView`\n * emits exactly one `IntelligenceIndicator` per entry, keyed by the turn id and\n * positioned at the anchor; the per-turn key also lets every past turn keep its\n * own indicator in scroll-back.\n *\n * `visibleMessages` is what actually renders, when that differs from\n * `messages` (the chat's `transformMessages`). Turns are still read from the\n * full list, so hiding a user message does not merge its turn into the one\n * before it, and anchors are only chosen among visible messages. A message the\n * transform built itself joins the turn of the visible message before it.\n */\nexport function getIntelligenceTurnAnchors(\n messages: readonly Message[],\n visibleMessages: readonly Message[] = messages,\n): Map<string, string> {\n const turnOfMessage = new Map<string, string>();\n let turnId = INTELLIGENCE_TURN_HEAD;\n for (const m of messages) {\n if (m.role === \"user\") turnId = m.id;\n turnOfMessage.set(m.id, turnId);\n }\n\n const anchors = new Map<string, string>();\n const anchoredTurns = new Set<string>();\n let currentTurn = INTELLIGENCE_TURN_HEAD;\n for (const m of visibleMessages) {\n currentTurn = turnOfMessage.get(m.id) ?? currentTurn;\n if (m.role === \"user\") continue;\n // First bash-using message of the turn wins; later ones don't move it.\n if (!anchoredTurns.has(currentTurn) && messageHasMatchingToolCall(m)) {\n anchors.set(m.id, currentTurn);\n anchoredTurns.add(currentTurn);\n }\n }\n return anchors;\n}\n\n/**\n * \"Tool-call-like\" messages do NOT count as a real follow-up: tool\n * result messages, assistant messages that carry tool calls, and\n * empty-content assistant messages (which some providers emit as a\n * standalone wrapper around a batch of tool calls). A real follow-up\n * is anything else — most importantly an assistant message with prose\n * content, or a fresh user message.\n */\nconst isToolCallLikeMessage = (m: Message): boolean => {\n if (m.role === \"tool\") return true;\n if (m.role === \"assistant\") {\n const tcs = Array.isArray(m.toolCalls) ? m.toolCalls : [];\n if (tcs.length > 0) return true;\n const content = m.content;\n return typeof content !== \"string\" || content.trim().length === 0;\n }\n return false;\n};\n\n/**\n * The \"Using CopilotKit Intelligence\" indicator brain. Auto-mounted by\n * `CopilotChatMessageView` — once per Intelligence-using turn, at that\n * turn's anchor message and keyed by the turn id (see\n * {@link getIntelligenceTurnAnchors}). Callers do not register this\n * themselves. It owns the run subscription and the phase machine and\n * renders its swappable face via the `intelligenceIndicator` slot.\n *\n * Placement (which message anchors the turn) is decided by the view, so\n * this component does not self-gate its own placement; it only derives\n * in-progress/finished for the turn it was mounted on.\n *\n * Render gates (all must hold):\n * 1. `copilotkit.intelligence !== undefined`\n * 2. The (anchor) message is an assistant message with at least one\n * tool call whose name matches {@link DEFAULT_TOOL_PATTERNS}.\n * 3. The phase machine is past `hidden`.\n *\n * Because the view keys each indicator by its turn id, the instance moves\n * with the anchor across a hand-off (no remount, no spinner restart), and\n * every prior Intelligence-using turn keeps its own persistent indicator\n * in chat history.\n *\n * Phase machine (per-instance, all timers local):\n * - Starts in `hidden`, unless the message mounts onto an\n * already-completed turn (no pending work, agent stopped or a\n * real follow-up already present), in which case the lazy\n * `useState` initializer starts directly in `finished`. This is\n * what avoids a \"hidden flash\" on history replay.\n * - `hidden → spinner` once a matching tool call has been pending\n * (no `tool`-role result with a matching `toolCallId`) for\n * {@link PENDING_THRESHOLD_MS}. Replay flashes (tool call + result\n * in the same tick) never cross this threshold.\n * - `hidden → finished` if after the grace window the turn is\n * already complete (no pending work AND\n * `sawRealFollowup || !agent.isRunning`). Handles very fast tools\n * whose result lands within the grace window.\n * - `spinner → finished` as soon as EITHER `agent.isRunning` flips\n * false OR a non-tool-call-like message appears later in\n * `agent.messages` (i.e. the agent produced a \"real\" follow-up —\n * prose answer or a new user turn).\n * - `finished` is terminal: the indicator settles into its\n * persistent tag form and stays mounted.\n */\nexport function IntelligenceIndicator(\n props: IntelligenceIndicatorProps,\n): React.ReactElement | null {\n const {\n message,\n agentId,\n label = \"CopilotKit Intelligence\",\n intelligenceIndicator,\n } = props;\n\n const { copilotkit } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const { agent } = useAgent({\n agentId,\n updates: [\n UseAgentUpdate.OnRunStatusChanged,\n UseAgentUpdate.OnMessagesChanged,\n ],\n });\n\n // IDs of matching tool calls on this message.\n const matchingToolCallIds = useMemo<readonly string[]>(() => {\n if (message.role !== \"assistant\") return [];\n const tcs = Array.isArray(message.toolCalls) ? message.toolCalls : [];\n const ids: string[] = [];\n for (const tc of tcs) {\n if (isMatchingToolCallName(tc?.function?.name) && tc?.id) {\n ids.push(tc.id);\n }\n }\n return ids;\n }, [message]);\n\n // Pending = at least one matching tool call has no corresponding\n // `tool`-role result message in `agent.messages`.\n const hasPending = useMemo(() => {\n if (matchingToolCallIds.length === 0) return false;\n const resolved = new Set<string>();\n for (const m of agent.messages) {\n if (m.role === \"tool\" && m.toolCallId) resolved.add(m.toolCallId);\n }\n return matchingToolCallIds.some((id) => !resolved.has(id));\n }, [matchingToolCallIds, agent.messages]);\n\n // True once the agent has produced a \"real\" message *after* this\n // assistant message — prose, a new user turn, etc. Tool-call-like\n // messages do not count (they're part of the same tool flow).\n const sawRealFollowup = useMemo(() => {\n const idx = agent.messages.findIndex((m) => m.id === message.id);\n if (idx < 0) return false;\n for (let i = idx + 1; i < agent.messages.length; i += 1) {\n if (!isToolCallLikeMessage(agent.messages[i]!)) return true;\n }\n return false;\n }, [agent.messages, message.id]);\n\n // Turn-completion signal — set the moment the agent stops running or\n // a \"real\" follow-up (prose / user turn) appears after this message.\n // Independent of whether the pending tool call resolved; if the run\n // finishes with a still-unresolved match (rare in production, common\n // in tests), the indicator should still settle.\n const turnComplete = sawRealFollowup || !agent.isRunning;\n\n // Lazy init: if this indicator mounts onto a message whose turn has\n // already completed (e.g. history replay finished before mount),\n // skip directly to `finished` — no `hidden` flash, no spinner blip.\n const [phase, setPhase] = useState<Phase>(() =>\n initialIndicatorPhase(turnComplete),\n );\n\n // hidden → spinner OR hidden → finished (after grace window). The grace\n // window only controls the *timing*; `resolveGracePhase` owns the decision.\n // Resolving back to `hidden` (matching tool call not landed yet) is a\n // no-op `setPhase`, preserving the \"only leave hidden once decided\" rule.\n useEffect(() => {\n if (phase !== \"hidden\") return undefined;\n const t = setTimeout(() => {\n setPhase(resolveGracePhase(turnComplete, hasPending));\n }, PENDING_THRESHOLD_MS);\n return () => clearTimeout(t);\n }, [phase, hasPending, turnComplete]);\n\n // spinner → finished\n useEffect(() => {\n if (phase !== \"spinner\") return undefined;\n if (turnComplete) {\n setPhase(\"finished\");\n }\n return undefined;\n }, [phase, turnComplete]);\n\n // ─── Render gates ────────────────────────────────────────────────────\n // Hooks above MUST run unconditionally; bail with `null` only after.\n\n if (copilotkit.intelligence === undefined) return null;\n if (!config) return null;\n if (phase === \"hidden\") return null;\n\n if (message.role !== \"assistant\") return null;\n if (!messageHasMatchingToolCall(message)) return null;\n\n // Placement (which message anchors this turn's indicator) is decided by\n // `CopilotChatMessageView` via `getIntelligenceTurnAnchors`, which mounts\n // exactly one instance per turn keyed by the turn id. The brain therefore\n // does not decide its own placement; it only owns the run-status →\n // in-progress/finished derivation for the turn it anchors.\n\n // ─── Render the (swappable) face ──────────────────────────────────────\n\n const status = phase === \"finished\" ? \"finished\" : \"in-progress\";\n\n return renderSlot(intelligenceIndicator, IntelligenceIndicatorView, {\n message,\n status,\n label,\n });\n}\n","import React, {\n useCallback,\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n defaultRangeExtractor,\n elementScroll,\n observeElementOffset,\n observeElementRect,\n useVirtualizer,\n} from \"@tanstack/react-virtual\";\nimport type { Range, VirtualItem, Virtualizer } from \"@tanstack/react-virtual\";\nimport { ScrollElementContext } from \"./scroll-element-context\";\nimport { ScrollPinnedContext } from \"./scroll-pinned-context\";\nimport type { WithSlots } from \"../../lib/slots\";\nimport { renderSlot, isReactComponentType } from \"../../lib/slots\";\nimport CopilotChatAssistantMessage from \"./CopilotChatAssistantMessage\";\nimport type {\n CopilotChatAssistantMessageProps,\n CopilotChatFeedbackMessage,\n} from \"./CopilotChatAssistantMessage\";\nimport type { CopilotChatUserMessageProps } from \"./CopilotChatUserMessage\";\nimport type { CopilotChatReasoningMessageProps } from \"./CopilotChatReasoningMessage\";\nimport CopilotChatUserMessage from \"./CopilotChatUserMessage\";\nimport CopilotChatReasoningMessage from \"./CopilotChatReasoningMessage\";\nimport {\n MessageFeedbackScopeContext,\n useLearningFeedbackEnabled,\n} from \"./message-feedback\";\nimport type { MessageFeedbackScope } from \"./message-feedback\";\nimport CopilotChatWorkSummary from \"./CopilotChatWorkSummary\";\nimport { Collapsible } from \"./CopilotChatToolCallGroup\";\nimport { ToolCallDisplayContext } from \"./tool-call-display-context\";\nimport type { ToolCallDisplayContextValue } from \"./tool-call-display-context\";\nimport {\n ɵcreateMessageViewModel,\n ɵdeduplicateMessages,\n ɵduplicateMessagesWarning,\n ɵgetMessageRunStateSnapshot,\n ɵresolveAgentId,\n} from \"@copilotkit/core\";\nimport type {\n CopilotChatToolCallDisplay,\n ToolCallEntry,\n} from \"@copilotkit/core\";\nimport { useToolCallRendererNames } from \"../../hooks/use-render-tool-call\";\nimport type {\n ActivityMessage,\n AssistantMessage,\n Message,\n ReasoningMessage,\n ToolMessage,\n UserMessage,\n} from \"@ag-ui/core\";\nimport { cn } from \"../../lib/utils\";\nimport { useRenderActivityMessage, useRenderCustomMessages } from \"../../hooks\";\nimport { useCopilotKit } from \"../../providers/CopilotKitProvider\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport {\n IntelligenceIndicator,\n getIntelligenceTurnAnchors,\n} from \"../intelligence-indicator\";\nimport type { IntelligenceIndicatorView } from \"../intelligence-indicator\";\nimport { useDefaultAgentId } from \"../../context\";\nimport {\n commitRowKeyStore,\n createRowKeyStore,\n resolveRowRenderKeysById,\n} from \"@copilotkit/shared\";\nimport type { RowKeyStore } from \"@copilotkit/shared\";\n\n/**\n * Resolves a slot value into a { Component, slotProps } pair, handling the three\n * slot forms: a component type, a className string, or a partial-props object.\n */\nfunction resolveSlotComponent<T extends React.ComponentType<any>>(\n slot: unknown,\n DefaultComponent: T,\n): { Component: T; slotProps: Partial<React.ComponentProps<T>> | undefined } {\n if (isReactComponentType(slot)) {\n return { Component: slot as T, slotProps: undefined };\n }\n if (typeof slot === \"string\") {\n return {\n Component: DefaultComponent,\n slotProps: { className: slot } as unknown as Partial<\n React.ComponentProps<T>\n >,\n };\n }\n if (slot && typeof slot === \"object\") {\n return {\n Component: DefaultComponent,\n slotProps: slot as Partial<React.ComponentProps<T>>,\n };\n }\n return { Component: DefaultComponent, slotProps: undefined };\n}\n\n/**\n * Memoized wrapper for assistant messages to prevent re-renders when other messages change.\n */\nconst MemoizedAssistantMessage = React.memo(\n function MemoizedAssistantMessage({\n message,\n messages,\n isRunning,\n isLatest,\n AssistantMessageComponent,\n slotProps,\n }: {\n message: AssistantMessage;\n messages: Message[];\n isRunning: boolean;\n isLatest: boolean;\n AssistantMessageComponent: typeof CopilotChatAssistantMessage;\n slotProps?: Partial<\n React.ComponentProps<typeof CopilotChatAssistantMessage>\n >;\n }) {\n return (\n <AssistantMessageComponent\n message={message}\n messages={messages}\n isRunning={isRunning}\n isLatest={isLatest}\n {...slotProps}\n />\n );\n },\n (prevProps, nextProps) => {\n // Only re-render if this specific message changed\n if (prevProps.message.id !== nextProps.message.id) return false;\n if (prevProps.message.content !== nextProps.message.content) return false;\n\n // Compare tool calls if present\n const prevToolCalls = prevProps.message.toolCalls;\n const nextToolCalls = nextProps.message.toolCalls;\n if (prevToolCalls?.length !== nextToolCalls?.length) return false;\n if (prevToolCalls && nextToolCalls) {\n for (let i = 0; i < prevToolCalls.length; i++) {\n const prevTc = prevToolCalls[i]!;\n const nextTc = nextToolCalls[i]!;\n if (prevTc.id !== nextTc.id) return false;\n if (prevTc.function.arguments !== nextTc.function.arguments)\n return false;\n }\n }\n\n // Check if tool results changed for this message's tool calls.\n // Tool results are separate messages with role=\"tool\" that reference tool call IDs.\n if (prevToolCalls && prevToolCalls.length > 0) {\n const toolCallIds = new Set(prevToolCalls.map((tc) => tc.id));\n\n const prevToolResults = prevProps.messages.filter(\n (m): m is ToolMessage =>\n m.role === \"tool\" && toolCallIds.has(m.toolCallId),\n );\n const nextToolResults = nextProps.messages.filter(\n (m): m is ToolMessage =>\n m.role === \"tool\" && toolCallIds.has(m.toolCallId),\n );\n\n if (prevToolResults.length !== nextToolResults.length) return false;\n\n for (let i = 0; i < prevToolResults.length; i++) {\n if (prevToolResults[i]!.content !== nextToolResults[i]!.content)\n return false;\n }\n }\n\n // A message renders as in-progress (toolbar hidden) only while it is the\n // latest one and the run is going. Re-render when that flips, including a\n // message that stops being the latest mid-run; not for every change in\n // either flag, so earlier messages stay put while a new one streams in.\n if (\n (prevProps.isRunning && prevProps.isLatest) !==\n (nextProps.isRunning && nextProps.isLatest)\n )\n return false;\n\n // Check if component reference changed\n if (\n prevProps.AssistantMessageComponent !==\n nextProps.AssistantMessageComponent\n )\n return false;\n\n // Check if slot props changed\n if (prevProps.slotProps !== nextProps.slotProps) return false;\n\n return true;\n },\n);\n\n/**\n * Memoized wrapper for user messages to prevent re-renders when other messages change.\n */\nconst MemoizedUserMessage = React.memo(\n function MemoizedUserMessage({\n message,\n UserMessageComponent,\n slotProps,\n }: {\n message: UserMessage;\n UserMessageComponent: typeof CopilotChatUserMessage;\n slotProps?: Partial<React.ComponentProps<typeof CopilotChatUserMessage>>;\n }) {\n return <UserMessageComponent message={message} {...slotProps} />;\n },\n (prevProps, nextProps) => {\n // Only re-render if this specific message changed\n if (prevProps.message.id !== nextProps.message.id) return false;\n if (prevProps.message.content !== nextProps.message.content) return false;\n if (prevProps.UserMessageComponent !== nextProps.UserMessageComponent)\n return false;\n // Check if slot props changed\n if (prevProps.slotProps !== nextProps.slotProps) return false;\n return true;\n },\n);\n\n/**\n * Memoized wrapper for activity messages to prevent re-renders when other messages change.\n */\nconst MemoizedActivityMessage = React.memo(\n function MemoizedActivityMessage({\n message,\n renderActivityMessage,\n }: {\n message: ActivityMessage;\n renderActivityMessage: (\n message: ActivityMessage,\n ) => React.ReactElement | null;\n }) {\n return renderActivityMessage(message);\n },\n (prevProps, nextProps) => {\n // Message ID changed = different message, must re-render\n if (prevProps.message.id !== nextProps.message.id) return false;\n\n // Activity type changed = must re-render\n if (prevProps.message.activityType !== nextProps.message.activityType)\n return false;\n\n // Compare content using JSON.stringify (native code, handles deep comparison)\n if (\n JSON.stringify(prevProps.message.content) !==\n JSON.stringify(nextProps.message.content)\n )\n return false;\n\n return true;\n },\n);\n\n/**\n * Memoized wrapper for reasoning messages to prevent re-renders when other messages change.\n */\nconst MemoizedReasoningMessage = React.memo(\n function MemoizedReasoningMessage({\n message,\n messages,\n isRunning,\n isLatest,\n ReasoningMessageComponent,\n slotProps,\n }: {\n message: ReasoningMessage;\n messages: Message[];\n isRunning: boolean;\n isLatest: boolean;\n ReasoningMessageComponent: typeof CopilotChatReasoningMessage;\n slotProps?: Partial<\n React.ComponentProps<typeof CopilotChatReasoningMessage>\n >;\n }) {\n return (\n <ReasoningMessageComponent\n message={message}\n messages={messages}\n isRunning={isRunning}\n isLatest={isLatest}\n {...slotProps}\n />\n );\n },\n (prevProps, nextProps) => {\n // Only re-render if this specific message changed\n if (prevProps.message.id !== nextProps.message.id) return false;\n if (prevProps.message.content !== nextProps.message.content) return false;\n\n // Re-render when \"latest\" status changes (e.g. reasoning message is no longer the last message\n // because a text message was added after it — this transitions isStreaming from true to false)\n if (prevProps.isLatest !== nextProps.isLatest) return false;\n\n // Only care about isRunning if this message is CURRENTLY the latest\n if (nextProps.isLatest && prevProps.isRunning !== nextProps.isRunning)\n return false;\n\n // Check if component reference changed\n if (\n prevProps.ReasoningMessageComponent !==\n nextProps.ReasoningMessageComponent\n )\n return false;\n\n // Check if slot props changed\n if (prevProps.slotProps !== nextProps.slotProps) return false;\n\n return true;\n },\n);\n\n/**\n * Memoized wrapper for custom messages to prevent re-renders when other messages change.\n */\nconst MemoizedCustomMessage = React.memo(\n function MemoizedCustomMessage({\n message,\n position,\n renderCustomMessage,\n }: {\n message: Message;\n position: \"before\" | \"after\";\n renderCustomMessage: (params: {\n message: Message;\n position: \"before\" | \"after\";\n }) => React.ReactElement | null;\n stateSnapshot?: unknown;\n }) {\n return renderCustomMessage({ message, position });\n },\n (prevProps, nextProps) => {\n // Only re-render if the message or position changed\n if (prevProps.message.id !== nextProps.message.id) return false;\n if (prevProps.position !== nextProps.position) return false;\n // Compare message content - for assistant messages this is a string, for others may differ\n if (prevProps.message.content !== nextProps.message.content) return false;\n if (prevProps.message.role !== nextProps.message.role) return false;\n // Compare state snapshot - custom renderers may depend on state\n if (\n JSON.stringify(prevProps.stateSnapshot) !==\n JSON.stringify(nextProps.stateSnapshot)\n )\n return false;\n // Note: We don't compare renderCustomMessage function reference because it changes\n // frequently. The message and state comparison is sufficient to determine if a re-render is needed.\n return true;\n },\n);\n\n/** What the view passes the wrapper of a message group. */\nexport interface MessageGroupWrapperProps<S = unknown> {\n /** The group's key, as returned by `groupMessages`. */\n groupKey: string;\n /** The messages in the group, in order. */\n messages: Message[];\n /** The default rendering of the group's messages. */\n children: React.ReactNode;\n /**\n * State the view keeps for this group, keyed by `groupKey`. It survives the\n * row leaving the window and the wrapper remounting, is dropped once the key\n * no longer appears, and is cleared when the thread changes. `undefined`\n * until first set.\n */\n state: S | undefined;\n setState: (next: S) => void;\n}\n\n/** Several messages rendered as one row, inside an app-provided wrapper. */\nexport interface MessageGroup<S = unknown> {\n type: \"group\";\n /**\n * Identifies the group across renders: its React key and the key its state\n * is held under. Keep it stable while the thread streams, e.g. the id of the\n * group's first message.\n */\n key: string;\n messages: Message[];\n /**\n * Define it once at module level. A component created inside\n * `groupMessages` is a new type on every call and remounts each time.\n */\n wrapper: React.ComponentType<MessageGroupWrapperProps<S>>;\n}\n\n/** One row of the message list: a single message, or a group of them. */\nexport type MessageRow = { type: \"message\"; message: Message } | MessageGroup;\n\n/** At most this many rows are rendered beyond the viewport on either side. */\nconst MAX_OVERSCAN_ROWS = 400;\n\n/** A row holding a single message, rendered as it would be ungrouped. */\nexport function messageRow(message: Message): MessageRow {\n return { type: \"message\", message };\n}\n\n/** A row holding a group of messages, rendered inside `wrapper`. */\nexport function messageGroup<S>(\n group: Omit<MessageGroup<S>, \"type\">,\n): MessageRow {\n // A group's state type is between it and its own wrapper; the row list only\n // hands back what that wrapper set. Erased once here so groups with\n // different state types can share one array.\n return { type: \"group\", ...group } as unknown as MessageGroup;\n}\n\n// Row keys are shared by React, the virtualizer and the scroll anchor. Each row\n// type has its own prefix, so a message ID can never equal a group's key.\nconst GROUP_ROW_KEY_PREFIX = \"copilotkit-group:\";\nconst MESSAGE_ROW_KEY_PREFIX = \"copilotkit-message:\";\n\nexport type CopilotChatMessageViewProps = Omit<\n WithSlots<\n {\n // Props-based, like CopilotChatView's `input` (#7158): a plain FC\n // assigns without the message components' namespace statics (Header,\n // Toolbar, MarkdownRenderer, …), which resolveSlotComponent never reads.\n assistantMessage: React.ComponentType<CopilotChatAssistantMessageProps>;\n userMessage: React.ComponentType<CopilotChatUserMessageProps>;\n reasoningMessage: React.ComponentType<CopilotChatReasoningMessageProps>;\n cursor: typeof CopilotChatMessageView.Cursor;\n intelligenceIndicator: typeof IntelligenceIndicatorView;\n /** The \"Working… / Worked for 9s\" line of the `\"turn\"` tool-call display. */\n workSummary: typeof CopilotChatWorkSummary;\n },\n {\n isRunning?: boolean;\n messages?: Message[];\n /**\n * Reshapes the message list before it renders: drop, replace or reorder\n * messages with the whole list in view. Receives the list after duplicate\n * ids are merged. Row keys, virtualization and rendering all work off\n * the returned list, so a dropped message takes no row.\n *\n * Tool-call cards still look up their results in the full list, so\n * hiding tool-result messages here does not strip results from them.\n *\n * Memoized on the input list and this function — pass a stable function\n * (e.g. `useCallback`) or it reruns on every render.\n */\n transformMessages?: (messages: Message[]) => Message[];\n /**\n * Splits the message list into rows. Return `messageRow(message)` for a\n * message that renders on its own, and `messageGroup({ key, messages,\n * wrapper })` for messages that render together inside `wrapper` — a\n * collapsible block of tool calls, say. Receives the list after\n * `transformMessages`. Each row is one virtualized row.\n *\n * Return each message in at most one row. Tool-call cards still find\n * their results in the full list.\n *\n * Memoized on its input and this function — pass a stable function.\n */\n groupMessages?: (messages: Message[]) => MessageRow[];\n /**\n * Whether reply thumbs record ratings for Automatic Learning once a\n * Trajectory has started. Defaults to `true`; set `false` to keep the\n * thumbs to your own `onThumbsUp` / `onThumbsDown` handlers and slots.\n */\n messageFeedback?: boolean;\n /**\n * How tool calls show. Defaults to `\"grouped\"`: calls made in a row\n * share one card that opens to a row per call. `\"line\"` and `\"stacked\"`\n * group them too; `\"turn\"` folds a reply's whole working phase into\n * \"Worked for 9s\" once it's done; `\"separate\"` gives every call its own\n * card. Calls with a renderer of their own always show on their own.\n */\n toolCallDisplay?: CopilotChatToolCallDisplay;\n } & React.HTMLAttributes<HTMLDivElement>\n >,\n \"children\"\n> & {\n children?: (props: {\n isRunning: boolean;\n messages: Message[];\n messageElements: React.ReactElement[];\n interruptElement: React.ReactElement | null;\n }) => React.ReactElement;\n};\n\n// Above this many messages, activate TanStack Virtual to avoid mounting the\n// full DOM tree. Below the threshold the overhead of virtualization isn't\n// worth it and the simpler flat render is faster.\nconst VIRTUALIZE_THRESHOLD = 50;\n\n/**\n * How long the scroll position must stay still, with no wheel or touch input,\n * before a correction held back during scrolling is written to `scrollTop`.\n */\nconst SCROLL_SETTLE_MS = 250;\n\n/**\n * The most a held correction moves per frame once it is written. Safari can\n * still drop a write when a new gesture starts in the same frame; a small\n * step keeps that from showing.\n */\nconst SETTLE_STEP_PX = 4;\n\nexport function CopilotChatMessageView({\n messages = [],\n assistantMessage,\n userMessage,\n reasoningMessage,\n cursor,\n intelligenceIndicator,\n workSummary,\n isRunning = false,\n transformMessages,\n groupMessages,\n messageFeedback = true,\n toolCallDisplay = \"grouped\",\n children,\n className,\n ...props\n}: CopilotChatMessageViewProps) {\n const isPinnedToBottom = useContext(ScrollPinnedContext);\n const renderCustomMessage = useRenderCustomMessages();\n const { renderActivityMessage } = useRenderActivityMessage();\n const { copilotkit, showIntelligenceIndicator = true } = useCopilotKit();\n const config = useCopilotChatConfiguration();\n const providerAgentId = useDefaultAgentId();\n const [, forceUpdate] = useReducer((x) => x + 1, 0);\n\n // Subscribe to state changes so custom message renderers re-render when state updates.\n useEffect(() => {\n if (!config?.agentId) return;\n const agent = copilotkit.getAgent(config.agentId);\n if (!agent) return;\n\n const subscription = agent.subscribe({\n onStateChanged: forceUpdate,\n });\n return () => subscription.unsubscribe();\n }, [config?.agentId, copilotkit, forceUpdate]);\n\n // Subscribe to interrupt element changes for in-chat rendering.\n const [interruptElement, setInterruptElement] =\n useState<React.ReactElement | null>(null);\n useEffect(() => {\n setInterruptElement(copilotkit.interruptElement);\n const subscription = copilotkit.subscribe({\n onInterruptElementChanged: ({ interruptElement }) => {\n setInterruptElement(interruptElement);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n // The run state a custom message renderer sees, used for memoization.\n const getStateSnapshotForMessage = (messageId: string): unknown =>\n config\n ? ɵgetMessageRunStateSnapshot(copilotkit, {\n agentId: config.agentId,\n threadId: config.threadId,\n messageId,\n })\n : undefined;\n\n const deduplicatedMessages = useMemo(\n () => ɵdeduplicateMessages(messages),\n [messages],\n );\n\n // What actually renders. Everything below — row keys, virtualization,\n // rendering — works off this list. Tool-result lookups keep using the full\n // `messages`, so a transform that hides tool results cannot break the cards\n // that display them.\n const transformedMessages = useMemo(\n () =>\n transformMessages\n ? transformMessages(deduplicatedMessages)\n : deduplicatedMessages,\n [deduplicatedMessages, transformMessages],\n );\n\n // One entry per virtualized row. Without grouping, every message is its own.\n const rows = useMemo<MessageRow[]>(\n () =>\n groupMessages\n ? groupMessages(transformedMessages)\n : transformedMessages.map(messageRow),\n [transformedMessages, groupMessages],\n );\n\n // Every message that renders, in the order it renders, whether on its own\n // row or inside a group. The message-level machinery below (row keys, the\n // latest message, Intelligence anchors) reads this, not `rows`.\n const renderedMessages = useMemo(\n () =>\n groupMessages\n ? rows.flatMap((row) =>\n row.type === \"group\" ? row.messages : [row.message],\n )\n : transformedMessages,\n [rows, groupMessages, transformedMessages],\n );\n\n // \"Latest\" means the last row on screen, not the last entry of `messages`:\n // a transform can drop, replace or reorder the tail. Streaming state and the\n // assistant toolbar key off this.\n const latestRenderedId = renderedMessages[renderedMessages.length - 1]?.id;\n\n // ---------------------------------------------------------------------------\n // Tool-call display\n // ---------------------------------------------------------------------------\n // Groups of calls can span messages (an agent often sends each call as its\n // own message), so they're laid out here for the whole list and handed to\n // each message's tool-call view through context.\n const rendererNames = useToolCallRendererNames();\n // The list's tool-call layout and turn state live in core. Calling `update`\n // during render is safe: it caches by input and records each run start or\n // end once, so repeating a render changes nothing. A user's open or close of\n // a reply's work is the only change it reports by itself.\n const [viewModel] = useState(ɵcreateMessageViewModel);\n useSyncExternalStore(\n useCallback((onChange) => viewModel.subscribe(onChange), [viewModel]),\n () => viewModel.getSnapshot(),\n () => viewModel.getSnapshot(),\n );\n const {\n layouts: toolCallLayouts,\n turnByFirstMessage,\n latestTurnKey,\n workOpen,\n workTextOpen,\n reasoningOpen,\n showCursor,\n pendingWorkSummary,\n } = viewModel.update({\n display: toolCallDisplay,\n messages,\n rendered: renderedMessages,\n isRunning,\n rendererNames,\n now: Date.now(),\n });\n\n const toolCallDisplayContext = useMemo<ToolCallDisplayContextValue>(\n () => ({\n display: toolCallDisplay,\n isRunning,\n layouts: toolCallLayouts,\n workOpen,\n workTextOpen,\n }),\n [toolCallDisplay, isRunning, toolCallLayouts, workOpen, workTextOpen],\n );\n\n const renderWorkSummary = (turnKey: string, calls: ToolCallEntry[]) => {\n const working = viewModel.isTurnWorking(turnKey);\n const open = viewModel.isTurnOpen(turnKey);\n const times = viewModel.getWorkTime(turnKey);\n return (\n <Collapsible\n key={`work-summary-${turnKey}`}\n open={working || calls.length > 0}\n >\n <div className=\"cpk-message-view-work-summary\">\n {renderSlot(workSummary, CopilotChatWorkSummary, {\n isWorking: working,\n isOpen: open,\n calls,\n elapsedMs: times?.elapsedMs,\n workingSince: times?.workingSince,\n onClick: () => viewModel.toggleTurn(turnKey),\n })}\n </div>\n </Collapsible>\n );\n };\n\n // Row keys are looked up by message id, so two rendered messages sharing an\n // id would share a React key. Deduplication already ran on the input, so a\n // repeat here can only come from the transform.\n const transformDuplicateId = useMemo(() => {\n if (\n process.env.NODE_ENV === \"production\" ||\n (!transformMessages && !groupMessages)\n ) {\n return;\n }\n const seen = new Set<string>();\n for (const message of renderedMessages) {\n if (seen.has(message.id)) return message.id;\n seen.add(message.id);\n }\n }, [renderedMessages, transformMessages, groupMessages]);\n useEffect(() => {\n if (transformDuplicateId === undefined) return;\n console.warn(\n groupMessages\n ? `[CopilotKit] CopilotChatMessageView: the message with id \"${transformDuplicateId}\" renders more than once. ` +\n \"`groupMessages` should place each message in at most one row, and `transformMessages` return each id at most once.\"\n : `[CopilotKit] CopilotChatMessageView: \\`transformMessages\\` returned more than one message with id \"${transformDuplicateId}\". ` +\n \"Return each id at most once; a message you create needs its own id, stable across renders.\",\n );\n }, [transformDuplicateId, groupMessages]);\n\n // Group keys are React keys and state keys, so two groups sharing one would\n // share both.\n const duplicateGroupKey = useMemo(() => {\n if (process.env.NODE_ENV === \"production\" || !groupMessages) return;\n const seen = new Set<string>();\n for (const row of rows) {\n if (row.type !== \"group\") continue;\n if (seen.has(row.key)) return row.key;\n seen.add(row.key);\n }\n }, [rows, groupMessages]);\n useEffect(() => {\n if (duplicateGroupKey === undefined) return;\n console.warn(\n `[CopilotKit] CopilotChatMessageView: \\`groupMessages\\` returned more than one group with key \"${duplicateGroupKey}\". ` +\n \"Give each group its own key, stable across renders.\",\n );\n }, [duplicateGroupKey]);\n\n // Stable per-row React keys. Backends can re-key a message mid-stream, and\n // keying rows by the canonical id remounts the row on that swap (the HITL\n // chat flash). See @copilotkit/shared row-render-keys for the mechanism.\n const rowKeyStoreRef = useRef<RowKeyStore | null>(null);\n rowKeyStoreRef.current ??= createRowKeyStore();\n const rowKeyStore = rowKeyStoreRef.current;\n\n const rowRenderKeys = useMemo(\n () => resolveRowRenderKeysById(rowKeyStore, renderedMessages),\n [rowKeyStore, renderedMessages],\n );\n\n // Record what this commit rendered, never what a render merely proposed: an\n // anchor from a render React goes on to abandon would re-key a committed row\n // and remount it. Layout phase, so the store is current before any later\n // render reads it.\n useLayoutEffect(() => {\n commitRowKeyStore(rowKeyStore, renderedMessages);\n }, [rowKeyStore, renderedMessages]);\n\n // A group's key, made stable the same way: a key that is a message id (the\n // documented choice is the group's first message) resolves through\n // `rowRenderKeys`, so a backend renaming that message mid-stream neither\n // remounts the group nor loses its state.\n const stableGroupKey = (key: string): string => rowRenderKeys.get(key) ?? key;\n const rowKey = (row: MessageRow): string =>\n row.type === \"group\"\n ? `${GROUP_ROW_KEY_PREFIX}${stableGroupKey(row.key)}`\n : `${MESSAGE_ROW_KEY_PREFIX}${rowRenderKeys.get(row.message.id) ?? row.message.id}`;\n\n // One stable key per row, shared by React and the virtualizer. Rows shift\n // index constantly once messages are grouped or transformed — tool calls\n // fold into one row mid-stream, a resume stand-in drops out — and a\n // virtualizer keyed by index then hands every measured height after that\n // point to the wrong row, so the total size jumps and the view moves.\n //\n // The array keeps its identity while the keys are unchanged. A new\n // `getItemKey` makes the virtualizer rebuild every row offset, re-estimating\n // the unmeasured rows above the viewport, and a parent that rebuilds its\n // `messages` array on every render would otherwise move the reader each time.\n const previousRowKeysRef = useRef<string[]>([]);\n const rowKeys = useMemo(() => {\n const next = rows.map(rowKey);\n const previous = previousRowKeysRef.current;\n return next.length === previous.length &&\n next.every((key, index) => key === previous[index])\n ? previous\n : next;\n // eslint-disable-next-line react-hooks/exhaustive-deps -- rowKey reads rowRenderKeys\n }, [rows, rowRenderKeys]);\n // react-doctor-disable-next-line react-doctor/no-ref-current-in-render -- identity cache: the stored list only decides whether an equal key list keeps its array\n previousRowKeysRef.current = rowKeys;\n\n // State each group's wrapper keeps here rather than in itself, so it\n // survives the row being windowed out and the wrapper remounting. Cleared\n // when the thread changes; pruned to the groups still on the list. One\n // setter per group, kept with its state, so a wrapper that depends on\n // `setState` in an effect or memo sees the same function every render.\n const groupStateRef = useRef<Map<string, unknown>>(new Map());\n const groupSettersRef = useRef<Map<string, (next: unknown) => void>>(\n new Map(),\n );\n const groupStateThreadRef = useRef(config?.threadId);\n if (groupStateThreadRef.current !== config?.threadId) {\n groupStateThreadRef.current = config?.threadId;\n groupStateRef.current = new Map();\n groupSettersRef.current = new Map();\n }\n const groupSetter = (key: string): ((next: unknown) => void) => {\n let setter = groupSettersRef.current.get(key);\n if (!setter) {\n setter = (next) => {\n groupStateRef.current.set(key, next);\n forceUpdate();\n };\n groupSettersRef.current.set(key, setter);\n }\n return setter;\n };\n useLayoutEffect(() => {\n const live = new Set<string>();\n for (const row of rows) {\n if (row.type === \"group\") live.add(stableGroupKey(row.key));\n }\n for (const store of [groupStateRef.current, groupSettersRef.current]) {\n for (const key of store.keys()) if (!live.has(key)) store.delete(key);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps -- stableGroupKey reads rowRenderKeys\n }, [rows, rowRenderKeys]);\n\n if (process.env.NODE_ENV === \"development\") {\n const warning = ɵduplicateMessagesWarning(\n messages.length,\n deduplicatedMessages.length,\n );\n if (warning) console.warn(warning);\n }\n\n // Resolve slot values once per prop change rather than inside renderMessageBlock.\n // resolveSlotComponent returns a new object every call when the slot is a CSS\n // class string, which would defeat MemoizedAssistantMessage's slotProps\n // reference-equality check and cause all completed messages to re-render.\n const { Component: AssistantComponent, slotProps: assistantSlotProps } =\n useMemo(\n () => resolveSlotComponent(assistantMessage, CopilotChatAssistantMessage),\n [assistantMessage],\n );\n const agentId = config?.agentId;\n const threadId = config?.threadId;\n const learningFeedbackEnabled = useLearningFeedbackEnabled(copilotkit);\n const feedbackScope = useMemo<MessageFeedbackScope | null>(\n () =>\n messageFeedback &&\n learningFeedbackEnabled &&\n agentId !== undefined &&\n threadId !== undefined\n ? { copilotkit, agentId, threadId }\n : null,\n [messageFeedback, learningFeedbackEnabled, copilotkit, agentId, threadId],\n );\n const assistantSlotPropsWithFeedback = useMemo(() => {\n const onThumbsUp = assistantSlotProps?.onThumbsUp as\n | ((message: CopilotChatFeedbackMessage) => void)\n | undefined;\n const onThumbsDown = assistantSlotProps?.onThumbsDown as\n | ((message: CopilotChatFeedbackMessage) => void)\n | undefined;\n if (!onThumbsUp && !onThumbsDown) return assistantSlotProps;\n\n const withRawEvent = (\n message: AssistantMessage,\n ): CopilotChatFeedbackMessage => {\n const rawEvent =\n agentId === undefined || threadId === undefined\n ? undefined\n : copilotkit.getRawEventForMessage(agentId, threadId, message.id);\n return rawEvent === undefined ? message : { ...message, rawEvent };\n };\n\n return {\n ...assistantSlotProps,\n ...(onThumbsUp && {\n onThumbsUp: (message: AssistantMessage) =>\n onThumbsUp(withRawEvent(message)),\n }),\n ...(onThumbsDown && {\n onThumbsDown: (message: AssistantMessage) =>\n onThumbsDown(withRawEvent(message)),\n }),\n };\n }, [assistantSlotProps, agentId, threadId, copilotkit]);\n const { Component: UserComponent, slotProps: userSlotProps } = useMemo(\n () => resolveSlotComponent(userMessage, CopilotChatUserMessage),\n [userMessage],\n );\n const { Component: ReasoningComponent, slotProps: reasoningSlotProps } =\n useMemo(\n () => resolveSlotComponent(reasoningMessage, CopilotChatReasoningMessage),\n [reasoningMessage],\n );\n\n // ---------------------------------------------------------------------------\n // Virtualization\n // ---------------------------------------------------------------------------\n // Receive the scroll container from context. ScrollView provides the element\n // as state (not a ref) so this component re-renders reactively when the\n // container first mounts. clientHeight === 0 means no real layout (jsdom) —\n // skip virtualization so tests run the flat path.\n const scrollElementFromCtx = useContext(ScrollElementContext);\n const scrollElement =\n scrollElementFromCtx && scrollElementFromCtx.clientHeight > 0\n ? scrollElementFromCtx\n : null;\n\n // Warn once in dev when a scroll element is provided but has no height —\n // this silently disables virtualization (e.g. chat inside display:none tab).\n useEffect(() => {\n if (\n process.env.NODE_ENV !== \"production\" &&\n scrollElementFromCtx &&\n scrollElementFromCtx.clientHeight === 0\n ) {\n console.warn(\n \"[CopilotKit] Chat scroll container has clientHeight=0 — virtualization disabled. \" +\n \"Ensure the chat is rendered in a visible container with a non-zero height.\",\n );\n }\n }, [scrollElementFromCtx]);\n\n // Virtualize only when we have a scroll element and enough messages. The\n // `children` render prop delegates layout to the caller, so we keep\n // messageElements flat for that case.\n const shouldVirtualize =\n !!scrollElement &&\n !children &&\n renderedMessages.length > VIRTUALIZE_THRESHOLD;\n\n // Warn once in dev when the `children` render prop is the only thing keeping\n // a long thread off the virtual path. Nothing else signals it: the chat just\n // mounts every message and gets slower as the thread grows.\n const childrenDisabledVirtualization =\n !!children &&\n !!scrollElement &&\n renderedMessages.length > VIRTUALIZE_THRESHOLD;\n const warnedChildrenRef = useRef(false);\n useEffect(() => {\n if (\n process.env.NODE_ENV === \"production\" ||\n !childrenDisabledVirtualization ||\n warnedChildrenRef.current\n ) {\n return;\n }\n warnedChildrenRef.current = true;\n console.warn(\n `[CopilotKit] CopilotChatMessageView: the \\`children\\` render prop disables virtualization, ` +\n `so all ${renderedMessages.length} messages are mounted. ` +\n (transformMessages || groupMessages\n ? \"`transformMessages` and `groupMessages` keep virtualization on by themselves; drop `children` to use them.\"\n : \"To reshape the list and keep virtualization, use `transformMessages` instead, or `groupMessages` to render several messages as one row.\"),\n );\n }, [\n childrenDisabledVirtualization,\n renderedMessages.length,\n transformMessages,\n ]);\n\n // Mean of the rows measured so far in this thread, used as the estimate for\n // rows that have not been measured yet. A flat 100 px estimate is off by\n // roughly an order of magnitude for a message carrying a code block, so the\n // total size lurches every time such a row is measured; an estimate drawn\n // from this thread's own rows keeps those corrections small.\n //\n // Sizes are kept per row rather than as a running sum because a row is\n // re-measured every time its ResizeObserver fires — a streaming message\n // reports a new height on every chunk — and treating each of those as a\n // fresh sample would drag the mean toward whatever that one row happened to\n // be mid-stream. Held in a ref because feeding it back through state would\n // re-render on every measure.\n //\n // A row keeps the estimate it was first laid out with until it is measured.\n // Each measurement rebuilds the offsets of every later row, and an\n // unmeasured row takes whatever the estimate is then; but when a row above\n // the viewport is measured, the virtualizer corrects the scroll position\n // only by that row's measured size minus its current estimate. A changed\n // estimate for rows already on the page would move everything below them,\n // the rows on screen included, by an amount nothing corrects. While the\n // reader scrolls up, the rows overscanned above the viewport are exactly\n // such rows: each one measured re-estimated the rest, and the content\n // jumped.\n const measuredRef = React.useRef({\n total: 0,\n sizes: new Map<string, number>(),\n estimates: new Map<string, number>(),\n });\n const rowKeysRef = React.useRef(rowKeys);\n rowKeysRef.current = rowKeys;\n\n const resizeAnchorRef = React.useRef<{\n index: number;\n offset: number;\n ready: boolean;\n } | null>(null);\n const restoringVisibilityRef = React.useRef(false);\n const isPinnedToBottomRef = React.useRef(isPinnedToBottom);\n\n // The instance from the previous render. A prepend reads the old layout\n // from it before this render gives the virtualizer the new rows.\n const virtualizerRef = React.useRef<Virtualizer<HTMLElement, Element> | null>(\n null,\n );\n\n // A correction is not written to `scrollTop` while the reader is scrolling:\n // the browser owns the scroll position then. Safari, on a trackpad, drops a\n // write made during the gesture or applies it a frame after the rows have\n // moved, and either way what the reader is looking at jumps. Instead the\n // correction is held here and the rows are drawn shifted by it, so nothing\n // on screen moves. Once scrolling has stopped, the shift is undone a few\n // pixels per frame, with `scrollTop` moving by the same amount each frame.\n //\n // The virtualizer works in list coordinates: list offset = `scrollTop` +\n // held offset. The rows are drawn in a wrapper shifted up by the held\n // offset, inside a spacer that is that much shorter.\n const heldOffsetRef = React.useRef(0);\n const spacerRef = React.useRef<HTMLDivElement | null>(null);\n const shiftedRowsRef = React.useRef<HTMLDivElement | null>(null);\n // Whether the row measured last started above the viewport as drawn.\n const lastMeasuredRef = React.useRef<{\n index: number;\n above: boolean;\n } | null>(null);\n const userScrollingRef = React.useRef(false);\n // The element offset the virtualizer last wrote, so its read-back is not\n // taken for the reader scrolling.\n const ownScrollWriteRef = React.useRef<number | null>(null);\n // The total size the rows were last rendered with: rows measured since then\n // have not moved yet, and the spacer must not change size ahead of them.\n const renderedTotalRef = useRef(0);\n\n // Draw the rows shifted by the held offset. Applied after every render as\n // well as by the settling below, which changes it without rendering.\n const applyHeldOffset = React.useCallback(() => {\n const held = heldOffsetRef.current;\n if (spacerRef.current)\n spacerRef.current.style.height = `${renderedTotalRef.current - held}px`;\n if (shiftedRowsRef.current)\n shiftedRowsRef.current.style.transform = held\n ? `translateY(${-held}px)`\n : \"\";\n }, []);\n\n // Rows that turn out shorter than estimated are held as a negative offset:\n // the rows are drawn that much lower. Near the top there may be less than\n // that above the viewport, and the first row would be drawn below a blank\n // band. Hold only what fits, so the first row stops at the top of the\n // viewport as it would at a scroll boundary. Returns whether it changed.\n const keepListTopInView = React.useCallback((scrollTop: number) => {\n if (heldOffsetRef.current >= 0 || scrollTop + heldOffsetRef.current >= 0)\n return false;\n heldOffsetRef.current = scrollTop > 0 ? -scrollTop : 0;\n return true;\n }, []);\n\n // Move `amount` of the held correction into `scrollTop`: the rows are drawn\n // that much less shifted and the scroll position moves with them, so\n // nothing on screen moves.\n const releaseHeldOffset = React.useCallback(\n (element: HTMLElement, amount: number) => {\n if (amount === 0) return;\n // Read before resizing the spacer, which can clamp it when shrinking.\n const scrollTop = element.scrollTop;\n heldOffsetRef.current -= amount;\n // Resize the spacer first: the new scroll position may not fit before.\n applyHeldOffset();\n const target = Math.max(0, scrollTop + amount);\n ownScrollWriteRef.current = target;\n element.scrollTop = target;\n },\n [applyHeldOffset],\n );\n\n // The thread changes when the first message changes and the new history\n // either belongs to another configured thread or shares no message with the\n // old one. Loading older history or trimming the oldest messages keeps the\n // thread (#8149), the same rule CopilotChatView uses for its bottom pin.\n // Read from the untransformed list: a transform that hides or reorders the\n // head is not a thread change.\n //\n // Done during render rather than in an effect because rows are measured\n // from ref callbacks, which run before layout effects — resetting there\n // would discard the new thread's first measurements instead of the old\n // thread's.\n const historyRef = React.useRef({\n messages: deduplicatedMessages,\n threadId,\n generation: 0,\n });\n const history = historyRef.current;\n if (history.messages !== deduplicatedMessages) {\n const previousFirstId = history.messages[0]?.id;\n if (previousFirstId !== deduplicatedMessages[0]?.id) {\n const previousIds = new Set(history.messages.map((m) => m.id));\n const sameThread =\n history.threadId === threadId &&\n deduplicatedMessages.some((m) => previousIds.has(m.id));\n if (sameThread) {\n keepReadingRowThroughHistoryChange();\n } else {\n history.generation += 1;\n resizeAnchorRef.current = null;\n // react-doctor-disable-next-line react-doctor/no-ref-current-in-render -- resets the scroll bookkeeping in the render that switches threads, like the refs beside it\n heldOffsetRef.current = 0;\n measuredRef.current = {\n total: 0,\n sizes: new Map(),\n estimates: new Map(),\n };\n }\n }\n history.messages = deduplicatedMessages;\n history.threadId = threadId;\n }\n const historyGeneration = history.generation;\n\n // Rows were added or removed above the reader. Remember the row at the top\n // of the viewport, by key, at its index in the new rows, and let the\n // resize-anchor restore below hold it there while the new rows settle.\n function keepReadingRowThroughHistoryChange() {\n const instance = virtualizerRef.current;\n const element = instance?.scrollElement;\n if (\n !instance ||\n !element ||\n instance.options.count === 0 ||\n element.clientHeight === 0 ||\n isPinnedToBottomRef.current ||\n restoringVisibilityRef.current\n )\n return;\n // In list coordinates: a correction held back while the reader scrolls\n // is not in `scrollTop` yet (see heldOffsetRef).\n const offset = element.scrollTop + heldOffsetRef.current;\n const item = instance.getVirtualItemForOffset(offset);\n const index = item ? rowKeys.indexOf(String(item.key)) : -1;\n resizeAnchorRef.current =\n item && index >= 0\n ? { index, offset: offset - item.start, ready: true }\n : null;\n }\n\n // A row that left the list (messages folded into a group, a stand-in\n // replaced) no longer says anything about this thread's row heights.\n const measuredKeysRef = React.useRef(rowKeys);\n if (measuredKeysRef.current !== rowKeys) {\n // react-doctor-disable-next-line react-doctor/no-ref-current-in-render -- prunes the cached row heights in the render that changes the rows, before the virtualizer reads them\n measuredKeysRef.current = rowKeys;\n const live = new Set(rowKeys);\n const measured = measuredRef.current;\n for (const [key, height] of measured.sizes) {\n if (!live.has(key)) {\n measured.sizes.delete(key);\n measured.total -= height;\n }\n }\n for (const key of measured.estimates.keys()) {\n if (!live.has(key)) measured.estimates.delete(key);\n }\n }\n\n // Kept per row key, like the sizes: a regroup moves rows to other indexes.\n const estimateRowSize = React.useCallback((index: number) => {\n const { total, sizes, estimates } = measuredRef.current;\n const mean =\n sizes.size > 0 ? Math.max(1, Math.round(total / sizes.size)) : 100;\n const key = rowKeysRef.current[index];\n if (key === undefined) return mean;\n let estimate = estimates.get(key);\n if (estimate === undefined) {\n estimate = mean;\n estimates.set(key, estimate);\n }\n return estimate;\n }, []);\n\n const measuredWidthRef = React.useRef<number | null>(null);\n const captureResizeAnchor = React.useCallback(\n (instance: Virtualizer<HTMLElement, Element>) => {\n const width = instance.scrollElement?.clientWidth;\n if (\n !width ||\n instance.scrollElement?.clientHeight === 0 ||\n restoringVisibilityRef.current ||\n isPinnedToBottomRef.current ||\n instance.options.count === 0 ||\n measuredWidthRef.current === null ||\n width === measuredWidthRef.current\n )\n return;\n if (resizeAnchorRef.current) {\n // A second resize can arrive before the previous anchor is released.\n // Keep its reading position, but let the old release callback expire.\n if (resizeAnchorRef.current.ready) {\n resizeAnchorRef.current = {\n ...resizeAnchorRef.current,\n ready: false,\n };\n }\n return;\n }\n const offset =\n (instance.scrollElement?.scrollTop ?? 0) + heldOffsetRef.current;\n const anchor = instance.getVirtualItemForOffset(offset);\n if (anchor) {\n resizeAnchorRef.current = {\n index: anchor.index,\n offset: offset - anchor.start,\n ready: false,\n };\n }\n },\n [],\n );\n const measureRowElement = React.useCallback(\n (\n el: Element,\n _entry: ResizeObserverEntry | undefined,\n instance: Virtualizer<HTMLElement, Element>,\n ) => {\n // Row refs and observers can run before the container observer. Capture\n // the old reading position before any row reports its resized height.\n captureResizeAnchor(instance);\n const rect = el.getBoundingClientRect();\n const measuredHeight: unknown = rect.height;\n const height = typeof measuredHeight === \"number\" ? measuredHeight : 0;\n // `data-index` is set on every virtual row below, and is what the\n // virtualizer itself uses to identify a measured element.\n const index = Number((el as HTMLElement | null)?.dataset?.index);\n // Keyed by row, not index, so a row keeps its size when history is\n // added above it or rows are regrouped.\n const key = Number.isInteger(index)\n ? rowKeysRef.current[index]\n : undefined;\n // Whether the row starts above the viewport as it is drawn now. The\n // virtualizer's own offsets for later rows lag behind within a batch of\n // measurements, while the list offset already moved with each correction\n // held before: a row well above the viewport could look inside it.\n // A measured rect without `top` (a stand-in element) says nothing about\n // where the row is, so the virtualizer's own offsets decide.\n const rowTop: unknown = rect.top;\n const viewportTop =\n typeof rowTop === \"number\"\n ? instance.scrollElement?.getBoundingClientRect().top\n : undefined;\n lastMeasuredRef.current =\n Number.isInteger(index) &&\n typeof rowTop === \"number\" &&\n typeof viewportTop === \"number\"\n ? { index, above: rowTop < viewportTop }\n : null;\n // Every row measures 0 while the chat is hidden (a display:none tab) or\n // the row is detached; those keep their last visible measurement. In a\n // visible list, 0 is a real size: a message that renders nothing, such\n // as an assistant turn holding only tool calls without a renderer, or\n // its tool results. Treating those as hidden gave each one the 100 px\n // estimate, which left long blank stretches in tool-heavy threads.\n const hidden = !el.isConnected || !instance.scrollElement?.clientHeight;\n if ((height > 0 || !hidden) && key !== undefined) {\n const { total, sizes } = measuredRef.current;\n measuredRef.current.total = total - (sizes.get(key) ?? 0) + height;\n sizes.set(key, height);\n }\n return height > 0 || !hidden\n ? height\n : ((key === undefined\n ? undefined\n : measuredRef.current.sizes.get(key)) ?? 100);\n },\n [captureResizeAnchor],\n );\n\n const shouldAdjustScrollOnResize = React.useCallback(\n (\n item: VirtualItem,\n delta: number,\n instance: Virtualizer<HTMLElement, Element>,\n ) => {\n const measured = lastMeasuredRef.current;\n lastMeasuredRef.current = null;\n // While the pin is following the bottom it owns the scroll position;\n // compensating as well is what makes the two fight (see below).\n if (\n isPinnedToBottomRef.current ||\n resizeAnchorRef.current ||\n restoringVisibilityRef.current\n )\n return false;\n // Otherwise keep the rule this property replaces rather than\n // compensating for every resize: only a row starting above the current\n // scroll offset can shift what the reader is looking at when it\n // changes size. Moving the scroll position for a row *below* the\n // viewport — an overscanned row settling, say — is the same unwanted\n // motion, just in the other direction. `scrollAdjustments` is not on\n // the public type but is part of that rule; leaving it out would drop\n // the corrections already applied.\n const scrollAdjustments =\n (instance as unknown as { scrollAdjustments?: number })\n .scrollAdjustments ?? 0;\n const above =\n measured?.index === item.index\n ? measured.above\n : item.start < (instance.scrollOffset ?? 0) + scrollAdjustments;\n if (!above) return false;\n // Also hold while an earlier correction is still settling: a write then\n // goes to list offset minus the held offset, which can lie past the\n // element's scroll range until the rows render, and is cut short.\n if (userScrollingRef.current || heldOffsetRef.current !== 0) {\n // Hold the correction instead of writing it (see heldOffsetRef). The\n // list offset moves with it, as it would after a write.\n const held = heldOffsetRef.current;\n heldOffsetRef.current += delta;\n keepListTopInView(instance.scrollElement?.scrollTop ?? 0);\n instance.scrollOffset =\n (instance.scrollOffset ?? 0) + heldOffsetRef.current - held;\n return false;\n }\n return true;\n },\n [keepListTopInView],\n );\n\n const observeListOffset = React.useCallback(\n (\n instance: Virtualizer<HTMLElement, Element>,\n notify: (offset: number, isScrolling: boolean) => void,\n ) =>\n observeElementOffset(instance, (offset, isScrolling) => {\n // Scrolling up toward the top uses up the room a negative held offset\n // has above the viewport; give up the rest of it as it does.\n if (keepListTopInView(offset)) applyHeldOffset();\n notify(offset + heldOffsetRef.current, isScrolling);\n }),\n [keepListTopInView, applyHeldOffset],\n );\n\n const scrollToListOffset = React.useCallback(\n (\n offset: number,\n options: { adjustments?: number; behavior?: ScrollBehavior },\n instance: Virtualizer<HTMLElement, Element>,\n ) => {\n const elementOffset = offset - heldOffsetRef.current;\n ownScrollWriteRef.current = elementOffset + (options.adjustments ?? 0);\n elementScroll(elementOffset, options, instance);\n },\n [],\n );\n\n const observeScrollRect = React.useCallback(\n (\n instance: Virtualizer<HTMLElement, Element>,\n notify: (rect: { width: number; height: number }) => void,\n ) => {\n let frame: number | undefined;\n let pendingRect: { width: number; height: number } | undefined;\n const disconnect = observeElementRect(instance, (rect) => {\n if (instance.scrollElement?.clientHeight === 0) {\n restoringVisibilityRef.current = true;\n resizeAnchorRef.current = null;\n if (frame !== undefined) cancelAnimationFrame(frame);\n frame = undefined;\n pendingRect = undefined;\n notify(rect);\n return;\n }\n const width = instance.scrollElement?.clientWidth ?? rect.width;\n const previousWidth = measuredWidthRef.current;\n if (width > 0 && width !== previousWidth) {\n captureResizeAnchor(instance);\n if (previousWidth !== null) {\n pendingRect = rect;\n if (frame === undefined) {\n // Resizing the spacer inside ResizeObserver can feed back into\n // the bottom pin's observer. Commit the new layout next frame.\n frame = requestAnimationFrame(() => {\n frame = undefined;\n const nextRect = pendingRect!;\n pendingRect = undefined;\n if (!instance.scrollElement?.clientHeight) return;\n measuredWidthRef.current = instance.scrollElement.clientWidth;\n if (resizeAnchorRef.current)\n resizeAnchorRef.current.ready = true;\n // Flush pending row updates before invalidating the cached prefix.\n instance.getTotalSize();\n measuredRef.current = {\n total: 0,\n sizes: new Map(),\n estimates: new Map(),\n };\n // Seed the new estimate before rebuilding offscreen offsets.\n instance.elementsCache.forEach((element) => {\n measureRowElement(element, undefined, instance);\n });\n instance.measure();\n instance.getTotalSize();\n // Already-resized rows may not emit another notification.\n instance.elementsCache.forEach((element) => {\n instance.measureElement(element);\n });\n notify(nextRect);\n });\n }\n return;\n }\n measuredWidthRef.current = width;\n }\n if (pendingRect) {\n pendingRect = rect;\n } else {\n notify(rect);\n }\n });\n return () => {\n disconnect?.();\n if (frame !== undefined) {\n cancelAnimationFrame(frame);\n }\n resizeAnchorRef.current = null;\n };\n },\n [captureResizeAnchor, measureRowElement],\n );\n\n // Cache sizes by row so that a row keeps its size when rows are added\n // above it. A new function whenever the keys change: the virtualizer only\n // rebuilds its row layout when an option it depends on changes, and a\n // regroup can keep the row count the same.\n const getItemKey = React.useCallback(\n (index: number) => rowKeys[index] ?? index,\n [rowKeys],\n );\n\n // Rows beyond the viewport are rendered by height, not only by count. A row\n // is measured when it mounts, and the virtualizer corrects the scroll\n // position for a size change only while the row is above the viewport. Rows\n // that render nothing measure 0, and a tool-heavy turn holds dozens of them\n // in a row, so five rows of overscan could reach no further than the\n // viewport's edge: the next row with content was first measured in view, and\n // its height change moved what the reader was looking at while scrolling.\n // Overscan therefore reaches at least a viewport's height in each direction.\n const rangeExtractor = React.useCallback((range: Range) => {\n const instance = virtualizerRef.current;\n const items = instance?.measurementsCache;\n const reach = instance?.scrollRect?.height ?? 0;\n if (!items || items.length !== range.count || reach <= 0)\n return defaultRangeExtractor(range);\n let start = range.startIndex;\n for (\n let above = 0;\n start > 0 &&\n range.startIndex - start < MAX_OVERSCAN_ROWS &&\n (range.startIndex - start < range.overscan || above < reach);\n ) {\n start -= 1;\n above += items[start]!.size;\n }\n let end = range.endIndex;\n for (\n let below = 0;\n end < range.count - 1 &&\n end - range.endIndex < MAX_OVERSCAN_ROWS &&\n (end - range.endIndex < range.overscan || below < reach);\n ) {\n end += 1;\n below += items[end]!.size;\n }\n const indexes: number[] = [];\n for (let index = start; index <= end; index++) indexes.push(index);\n return indexes;\n }, []);\n\n const virtualizer = useVirtualizer({\n // count=0 disables the virtualizer without changing hook call order.\n count: shouldVirtualize ? rows.length : 0,\n // Cache sizes by row so that a row keeps its size when rows are added\n // above it.\n getItemKey,\n // A disabled virtualizer must not reconnect and reset a flat list's\n // scroll offset when a hidden host becomes visible again.\n getScrollElement: () => (shouldVirtualize ? scrollElement : null),\n observeElementRect: observeScrollRect,\n observeElementOffset: observeListOffset,\n scrollToFn: scrollToListOffset,\n estimateSize: estimateRowSize,\n overscan: 5,\n rangeExtractor,\n measureElement: measureRowElement,\n // Assume a 600 px viewport before the real element is measured so that\n // the first virtual render shows ~6 items rather than 0.\n initialRect: { width: 0, height: 600 },\n });\n virtualizerRef.current = virtualizer;\n\n // react-doctor-disable-next-line react-doctor/no-ref-current-in-render -- records the total size this render lays out, which applyHeldOffset compares in the layout effect\n renderedTotalRef.current = virtualizer.getTotalSize();\n useLayoutEffect(applyHeldOffset);\n\n // Track whether the reader is scrolling (wheel, trackpad, touch, keyboard\n // or scrollbar: anything that moves the list other than our own writes) and,\n // once it has stopped, write the held correction (see heldOffsetRef).\n useEffect(() => {\n const element = shouldVirtualize ? scrollElement : null;\n if (!element) return;\n let settleTimer: ReturnType<typeof setTimeout> | undefined;\n let settleFrame: number | undefined;\n let touching = false;\n // One step per frame, after the frame's input has been handled: a gesture\n // that starts now has already marked the reader as scrolling.\n const settleStep = () => {\n settleFrame = undefined;\n const held = heldOffsetRef.current;\n if (userScrollingRef.current || touching || held === 0) return;\n releaseHeldOffset(\n element,\n Math.sign(held) * Math.min(Math.abs(held), SETTLE_STEP_PX),\n );\n if (heldOffsetRef.current !== 0)\n settleFrame = requestAnimationFrame(settleStep);\n };\n const settle = () => {\n settleTimer = undefined;\n if (touching) return;\n userScrollingRef.current = false;\n if (heldOffsetRef.current !== 0 && settleFrame === undefined)\n settleFrame = requestAnimationFrame(settleStep);\n };\n const scrolling = () => {\n userScrollingRef.current = true;\n if (settleFrame !== undefined) {\n cancelAnimationFrame(settleFrame);\n settleFrame = undefined;\n }\n if (settleTimer !== undefined) clearTimeout(settleTimer);\n settleTimer = setTimeout(settle, SCROLL_SETTLE_MS);\n };\n const onScroll = () => {\n const own = ownScrollWriteRef.current;\n if (own !== null && Math.abs(element.scrollTop - own) < 1) {\n ownScrollWriteRef.current = null;\n return;\n }\n scrolling();\n };\n const onTouchStart = () => {\n touching = true;\n scrolling();\n };\n const onTouchEnd = () => {\n touching = false;\n scrolling();\n };\n element.addEventListener(\"scroll\", onScroll, { passive: true });\n element.addEventListener(\"wheel\", scrolling, { passive: true });\n element.addEventListener(\"touchstart\", onTouchStart, { passive: true });\n element.addEventListener(\"touchend\", onTouchEnd, { passive: true });\n element.addEventListener(\"touchcancel\", onTouchEnd, { passive: true });\n return () => {\n if (settleTimer !== undefined) clearTimeout(settleTimer);\n if (settleFrame !== undefined) cancelAnimationFrame(settleFrame);\n userScrollingRef.current = false;\n element.removeEventListener(\"scroll\", onScroll);\n element.removeEventListener(\"wheel\", scrolling);\n element.removeEventListener(\"touchstart\", onTouchStart);\n element.removeEventListener(\"touchend\", onTouchEnd);\n element.removeEventListener(\"touchcancel\", onTouchEnd);\n };\n }, [shouldVirtualize, scrollElement, releaseHeldOffset]);\n\n // While the pin-to-bottom behaviour is following the bottom it is already\n // going to move the scroll position, and its ResizeObserver reads our\n // total-size changes as content growth. Compensating here as well makes the\n // two fight: each correction triggers an animation, the animation pulls\n // unmeasured rows into view, measuring them moves the total again. Stand\n // down while it is pinned; keep compensating when the reader has scrolled\n // up, which is the case the compensation is actually for.\n //\n // This is an instance property on the virtualizer rather than one of its\n // options, so it has to be assigned. Assigned during render (not in an\n // effect) because a row can be measured before effects run. The read goes\n // through a ref so the assigned function stays referentially stable.\n isPinnedToBottomRef.current = isPinnedToBottom;\n virtualizer.shouldAdjustScrollPositionOnItemSizeChange =\n shouldAdjustScrollOnResize;\n\n // Restore the reading row only after the resized spacer has committed;\n // scrolling sooner can clamp the target to its previous total height.\n useLayoutEffect(() => {\n const anchor = resizeAnchorRef.current;\n if (!anchor?.ready || restoringVisibilityRef.current) return;\n // The virtualizer keeps targets within the element's scroll range, which\n // a held correction makes differ from the list's: release it first.\n if (scrollElement) releaseHeldOffset(scrollElement, heldOffsetRef.current);\n const position = virtualizer.getOffsetForIndex(anchor.index, \"start\");\n if (position && !isPinnedToBottomRef.current) {\n const target = position[0] + anchor.offset;\n const listOffset =\n (scrollElement?.scrollTop ?? 0) + heldOffsetRef.current;\n if (Math.abs(listOffset - target) > 0.5) {\n virtualizer.scrollToOffset(target);\n }\n }\n // Keep the anchor through the row measurements caused by this render.\n // Each measurement cancels and reschedules this release until layout settles.\n const frame = requestAnimationFrame(() => {\n if (resizeAnchorRef.current === anchor) resizeAnchorRef.current = null;\n });\n return () => cancelAnimationFrame(frame);\n });\n\n // Scroll to the bottom when virtual mode first activates or the thread\n // changes (see `historyGeneration` above). For streaming new messages,\n // use-stick-to-bottom handles auto-scroll via content height growth detection\n // on the virtualizer's total-size div — same as the flat path. Adding\n // renderedMessages.length here would forcibly yank the user to the bottom\n // on every streaming chunk even if they've scrolled up to read history.\n const lastEndAlignedGenerationRef = React.useRef<number | undefined>(\n undefined,\n );\n useLayoutEffect(() => {\n if (!shouldVirtualize || !rows.length) return;\n // Resizing a hidden host can temporarily disable virtualization. Do not\n // align again when the same message list becomes measurable once more.\n if (lastEndAlignedGenerationRef.current === historyGeneration) return;\n lastEndAlignedGenerationRef.current = historyGeneration;\n virtualizer.scrollToIndex(rows.length - 1, {\n align: \"end\",\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [shouldVirtualize, historyGeneration]);\n\n // Map each Intelligence-using turn's anchor message → stable turn id. One\n // indicator is emitted per turn (keyed by the turn id) at its anchor, so it\n // moves with the anchor without remounting. `getIntelligenceTurnAnchors`\n // only yields anchors for turns that invoked the knowledge-base tool, so\n // non-Intelligence turns naturally produce an empty map (and the indicator\n // itself also hard-gates on intelligence mode).\n const intelligenceTurnAnchors = useMemo(\n () => getIntelligenceTurnAnchors(deduplicatedMessages, renderedMessages),\n [deduplicatedMessages, renderedMessages],\n );\n\n // ---------------------------------------------------------------------------\n // Per-message rendering helper (shared by flat and virtual paths)\n // ---------------------------------------------------------------------------\n const renderMessageBlock = (message: Message): React.ReactElement[] => {\n const elements: (React.ReactElement | null | undefined)[] = [];\n // Only custom message renderers consume the snapshot, and resolving it\n // deep-clones the agent's whole state (LangGraph's includes the `messages`\n // channel). Computing it unconditionally cost one clone per message per\n // render even when no renderer was registered.\n const stateSnapshot = renderCustomMessage\n ? getStateSnapshotForMessage(message.id)\n : undefined;\n // Row key only — everything keyed to message identity (state snapshots,\n // tool lookups) must keep using message.id.\n const messageKey = rowRenderKeys.get(message.id) ?? message.id;\n\n const turn = turnByFirstMessage.get(message.id);\n if (turn) elements.push(renderWorkSummary(turn.key, turn.calls));\n\n if (renderCustomMessage) {\n elements.push(\n <MemoizedCustomMessage\n key={`${messageKey}-custom-before`}\n message={message}\n position=\"before\"\n renderCustomMessage={renderCustomMessage}\n stateSnapshot={stateSnapshot}\n />,\n );\n }\n\n if (message.role === \"assistant\") {\n elements.push(\n <MemoizedAssistantMessage\n key={messageKey}\n message={message as AssistantMessage}\n messages={messages}\n isRunning={isRunning}\n isLatest={message.id === latestRenderedId}\n AssistantMessageComponent={AssistantComponent}\n slotProps={assistantSlotPropsWithFeedback}\n />,\n );\n } else if (message.role === \"user\") {\n elements.push(\n <MemoizedUserMessage\n key={messageKey}\n message={message as UserMessage}\n UserMessageComponent={UserComponent}\n slotProps={userSlotProps}\n />,\n );\n } else if (message.role === \"activity\") {\n elements.push(\n <MemoizedActivityMessage\n key={messageKey}\n message={message as ActivityMessage}\n renderActivityMessage={renderActivityMessage}\n />,\n );\n } else if (message.role === \"reasoning\") {\n const reasoning = (\n <MemoizedReasoningMessage\n key={messageKey}\n message={message as ReasoningMessage}\n messages={messages}\n isRunning={isRunning}\n isLatest={message.id === latestRenderedId}\n ReasoningMessageComponent={ReasoningComponent}\n slotProps={reasoningSlotProps}\n />\n );\n // Reasoning during a reply's working phase folds away with the work,\n // and a thought the agent has already moved on from folds away while it\n // works. Always wrapped in this display, so reasoning that turns into\n // work keeps its node (and its \"Thought for\" timer) instead of\n // remounting.\n elements.push(\n toolCallDisplay === \"turn\" ? (\n <Collapsible\n key={messageKey}\n open={reasoningOpen.get(message.id) ?? true}\n >\n {reasoning}\n </Collapsible>\n ) : (\n reasoning\n ),\n );\n }\n\n if (renderCustomMessage) {\n elements.push(\n <MemoizedCustomMessage\n key={`${messageKey}-custom-after`}\n message={message}\n position=\"after\"\n renderCustomMessage={renderCustomMessage}\n stateSnapshot={stateSnapshot}\n />,\n );\n }\n\n // Auto-mount the IntelligenceIndicator once per Intelligence-using turn,\n // at that turn's anchor message (its first bash-using assistant), keyed by\n // the stable turn id. Keying by turn (not message) means the indicator\n // moves with the anchor across a hand-off without remounting, and past\n // turns keep their own indicator.\n const intelligenceTurnId = showIntelligenceIndicator\n ? intelligenceTurnAnchors.get(message.id)\n : undefined;\n if (intelligenceTurnId !== undefined) {\n elements.push(\n <IntelligenceIndicator\n key={`intelligence-${intelligenceTurnId}`}\n message={message}\n agentId={ɵresolveAgentId({\n chatAgentId: config?.agentId,\n providerAgentId,\n })}\n intelligenceIndicator={intelligenceIndicator}\n />,\n );\n }\n\n return elements.filter(Boolean) as React.ReactElement[];\n };\n\n const renderRow = (row: MessageRow): React.ReactElement[] => {\n if (row.type === \"message\") return renderMessageBlock(row.message);\n const Wrapper = row.wrapper;\n const stateKey = stableGroupKey(row.key);\n return [\n <Wrapper\n key={rowKey(row)}\n groupKey={row.key}\n messages={row.messages}\n state={groupStateRef.current.get(stateKey)}\n setState={groupSetter(stateKey)}\n >\n {row.messages.flatMap(renderMessageBlock)}\n </Wrapper>,\n ];\n };\n\n const virtualModeRef = useRef(shouldVirtualize);\n virtualModeRef.current = shouldVirtualize;\n\n // Re-entering virtual mode can re-estimate rows above the viewport. A pixel\n // scrollTop then identifies different content, so retain the first visible\n // row and its offset within the viewport instead.\n useEffect(() => {\n const element = scrollElementFromCtx;\n if (!element) return;\n let anchor: { key: string; offset: number } | null = null;\n let suspended = false;\n let frame = 0;\n\n const visibleRows = () =>\n Array.from(element.querySelectorAll<HTMLElement>(\"[data-scroll-anchor]\"));\n const remember = () => {\n if (suspended || element.clientHeight === 0 || !virtualModeRef.current)\n return;\n if (isPinnedToBottomRef.current) {\n anchor = null;\n return;\n }\n const viewport = element.getBoundingClientRect();\n const row = visibleRows().find((row) => {\n const bounds = row.getBoundingClientRect();\n return bounds.bottom > viewport.top && bounds.top < viewport.bottom;\n });\n if (row) {\n anchor = {\n key: row.dataset.scrollAnchor!,\n offset: row.getBoundingClientRect().top - viewport.top,\n };\n }\n };\n const observer = new ResizeObserver(() => {\n if (element.clientHeight === 0) {\n suspended = true;\n // Hide/show owns restoration until its saved row has settled. Width\n // changes may invalidate measurements, but must not also move it.\n restoringVisibilityRef.current = true;\n resizeAnchorRef.current = null;\n cancelAnimationFrame(frame);\n return;\n }\n if (!suspended || !anchor) {\n suspended = false;\n restoringVisibilityRef.current = false;\n remember();\n return;\n }\n cancelAnimationFrame(frame);\n let attempts = 0;\n let stableFrames = 0;\n const restore = () => {\n if (!anchor || element.clientHeight === 0) return;\n if (isPinnedToBottomRef.current) {\n anchor = null;\n suspended = false;\n restoringVisibilityRef.current = false;\n return;\n }\n const index = rowKeysRef.current.indexOf(anchor.key);\n if (index < 0) {\n anchor = null;\n suspended = false;\n restoringVisibilityRef.current = false;\n return;\n }\n const row = visibleRows().find(\n (row) => row.dataset.scrollAnchor === anchor!.key,\n );\n if (row) {\n const delta =\n row.getBoundingClientRect().top -\n element.getBoundingClientRect().top -\n anchor.offset;\n element.scrollTop += delta;\n stableFrames = Math.abs(delta) < 1 ? stableFrames + 1 : 0;\n } else {\n // Bring an unmounted anchor into range, then refine its measured\n // position on the next frame rather than using an estimated height.\n const offset = virtualizer.getOffsetForIndex(index, \"start\")?.[0];\n if (offset !== undefined)\n virtualizer.scrollToOffset(offset - anchor.offset);\n stableFrames = 0;\n }\n if (++attempts < 60 && stableFrames < 3) {\n frame = requestAnimationFrame(restore);\n } else {\n suspended = false;\n restoringVisibilityRef.current = false;\n remember();\n }\n };\n frame = requestAnimationFrame(restore);\n });\n const interrupt = () => {\n cancelAnimationFrame(frame);\n anchor = null;\n suspended = false;\n restoringVisibilityRef.current = false;\n resizeAnchorRef.current = null;\n };\n element.addEventListener(\"scroll\", remember, { passive: true });\n element.addEventListener(\"wheel\", interrupt, { passive: true });\n element.addEventListener(\"touchstart\", interrupt, { passive: true });\n element.addEventListener(\"keydown\", interrupt);\n observer.observe(element);\n remember();\n return () => {\n cancelAnimationFrame(frame);\n observer.disconnect();\n restoringVisibilityRef.current = false;\n element.removeEventListener(\"scroll\", remember);\n element.removeEventListener(\"wheel\", interrupt);\n element.removeEventListener(\"touchstart\", interrupt);\n element.removeEventListener(\"keydown\", interrupt);\n };\n }, [scrollElementFromCtx, virtualizer, historyGeneration]);\n\n // Build the flat element list only when we're not virtualizing (avoids\n // creating 500 React elements that we'd immediately discard).\n const messageElements: React.ReactElement[] = shouldVirtualize\n ? []\n : rows.flatMap(renderRow);\n\n // ---------------------------------------------------------------------------\n // children render prop (custom layout, always non-virtual)\n // ---------------------------------------------------------------------------\n if (children) {\n return (\n <MessageFeedbackScopeContext.Provider value={feedbackScope}>\n <ToolCallDisplayContext.Provider value={toolCallDisplayContext}>\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children({\n messageElements,\n messages,\n isRunning,\n interruptElement,\n })}\n </div>\n </ToolCallDisplayContext.Provider>\n </MessageFeedbackScopeContext.Provider>\n );\n }\n\n // ---------------------------------------------------------------------------\n // Render — shared wrapper, conditional inner content (virtual vs flat)\n // ---------------------------------------------------------------------------\n return (\n <MessageFeedbackScopeContext.Provider value={feedbackScope}>\n <ToolCallDisplayContext.Provider value={toolCallDisplayContext}>\n <div\n data-copilotkit\n data-testid=\"copilot-message-list\"\n className={cn(\"copilotKitMessages cpk-message-view\", className)}\n {...props}\n >\n {shouldVirtualize ? (\n // Virtual path: only visible items are in the DOM; outer div maintains\n // total scroll height so the scrollbar reflects the full list size.\n <div\n ref={spacerRef}\n style={{\n height: renderedTotalRef.current - heldOffsetRef.current,\n position: \"relative\",\n overflowAnchor: \"none\",\n }}\n >\n <div\n ref={shiftedRowsRef}\n style={{\n position: \"absolute\",\n top: 0,\n left: 0,\n width: \"100%\",\n transform: heldOffsetRef.current\n ? `translateY(${-heldOffsetRef.current}px)`\n : undefined,\n }}\n >\n {virtualizer.getVirtualItems().map((virtualItem) => {\n const row = rows[virtualItem.index]!;\n return (\n <div\n key={rowKey(row)}\n data-index={virtualItem.index}\n data-scroll-anchor={rowKey(row)}\n ref={virtualizer.measureElement}\n style={{\n position: \"absolute\",\n top: 0,\n left: 0,\n width: \"100%\",\n transform: `translateY(${virtualItem.start}px)`,\n }}\n >\n {renderRow(row)}\n </div>\n );\n })}\n </div>\n </div>\n ) : (\n messageElements\n )}\n {interruptElement}\n {pendingWorkSummary && renderWorkSummary(latestTurnKey, [])}\n {showCursor && (\n <div className=\"cpk-message-view-cursor-container\">\n {renderSlot(cursor, CopilotChatMessageView.Cursor, {})}\n </div>\n )}\n </div>\n </ToolCallDisplayContext.Provider>\n </MessageFeedbackScopeContext.Provider>\n );\n}\n\nCopilotChatMessageView.Cursor = function Cursor({\n className,\n ...props\n}: React.HTMLAttributes<HTMLDivElement>) {\n return (\n <div\n data-testid=\"copilot-loading-cursor\"\n className={cn(\"cpk-message-view-cursor\", className)}\n {...props}\n />\n );\n};\n\nexport default CopilotChatMessageView;\n","import React, { useEffect, useState } from \"react\";\nimport type { Attachment } from \"@copilotkit/shared\";\nimport {\n formatFileSize,\n getSourceUrl,\n getDocumentIcon,\n} from \"@copilotkit/shared\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport { cn } from \"../../lib/utils\";\nimport { Lightbox, useLightbox } from \"./Lightbox\";\nimport {\n CopilotChatDefaultLabels,\n ɵcanPreviewDocument,\n ɵcreateObjectUrlFromSource,\n ɵdecodeTextSource,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\ninterface CopilotChatAttachmentQueueProps {\n attachments: Attachment[];\n onRemoveAttachment: (id: string) => void;\n className?: string;\n}\n\n/**\n * The attachments queued in the composer, each with a preview and a remove\n * button named by `labels.attachmentRemoveButtonLabel`.\n */\nexport const CopilotChatAttachmentQueue: React.FC<\n CopilotChatAttachmentQueueProps\n> = ({ attachments, onRemoveAttachment, className }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n if (attachments.length === 0) return null;\n\n return (\n <div\n data-testid=\"copilot-attachment-queue\"\n className={cn(\"cpk-attachment-queue\", className)}\n >\n {attachments.map((attachment) => {\n const isMedia =\n attachment.type === \"image\" || attachment.type === \"video\";\n return (\n <div\n key={attachment.id}\n className={cn(\n \"cpk-attachment-queue-item\",\n isMedia\n ? \"cpk-attachment-queue-item-media\"\n : attachment.type === \"audio\"\n ? \"cpk-attachment-queue-item-audio\"\n : \"cpk-attachment-queue-item-document\",\n )}\n >\n {attachment.status === \"uploading\" && <UploadingOverlay />}\n <AttachmentPreview attachment={attachment} />\n <button\n onClick={() => onRemoveAttachment(attachment.id)}\n className=\"cpk-attachment-queue-remove-button\"\n aria-label={labels.attachmentRemoveButtonLabel}\n >\n ✕\n </button>\n </div>\n );\n })}\n </div>\n );\n};\n\n// ---------------------------------------------------------------------------\n// Shared\n// ---------------------------------------------------------------------------\n\nfunction UploadingOverlay() {\n return (\n <div className=\"cpk-attachment-queue-uploading-overlay\">\n <div className=\"cpk-attachment-queue-uploading-spinner\" />\n </div>\n );\n}\n\nfunction AttachmentPreview({ attachment }: { attachment: Attachment }) {\n if (attachment.status === \"uploading\") {\n return <div className=\"cpk-attachment-queue-placeholder\" />;\n }\n\n switch (attachment.type) {\n case \"image\":\n return <ImagePreview attachment={attachment} />;\n case \"audio\":\n return <AudioPreview attachment={attachment} />;\n case \"video\":\n return <VideoPreview attachment={attachment} />;\n case \"document\":\n return <DocumentPreview attachment={attachment} />;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Image\n// ---------------------------------------------------------------------------\n\nfunction ImagePreview({ attachment }: { attachment: Attachment }) {\n const src = getSourceUrl(attachment.source);\n const { thumbnailRef, vtName, open, openLightbox, closeLightbox } =\n useLightbox();\n\n return (\n <>\n <img\n ref={thumbnailRef as React.Ref<HTMLImageElement>}\n src={src}\n alt={attachment.filename || \"Image attachment\"}\n className=\"cpk-attachment-queue-image\"\n onClick={openLightbox}\n />\n {open && (\n <Lightbox\n onClose={closeLightbox}\n label={attachment.filename || \"Image attachment\"}\n >\n <img\n style={{ viewTransitionName: vtName }}\n src={src}\n alt={attachment.filename || \"Image attachment\"}\n className=\"cpk-attachment-queue-lightbox-image\"\n />\n </Lightbox>\n )}\n </>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Audio\n// ---------------------------------------------------------------------------\n\nfunction AudioPreview({ attachment }: { attachment: Attachment }) {\n const src = getSourceUrl(attachment.source);\n return (\n <div className=\"cpk-attachment-queue-audio\">\n <audio\n src={src}\n controls\n preload=\"metadata\"\n className=\"cpk-attachment-queue-audio-player\"\n />\n {attachment.filename && (\n <span className=\"cpk-attachment-queue-audio-filename\">\n {attachment.filename}\n </span>\n )}\n </div>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Video – thumbnail with play button; click opens lightbox with full controls\n// ---------------------------------------------------------------------------\n\n/**\n * A video thumbnail with a play button, named by\n * `labels.attachmentPlayVideoButtonLabel`, that opens the full player in a\n * lightbox.\n */\nfunction VideoPreview({ attachment }: { attachment: Attachment }) {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const src = getSourceUrl(attachment.source);\n const { thumbnailRef, vtName, open, openLightbox, closeLightbox } =\n useLightbox();\n\n return (\n <>\n <div\n ref={thumbnailRef as React.Ref<HTMLDivElement>}\n className=\"cpk-attachment-queue-video\"\n >\n {attachment.thumbnail ? (\n <img\n src={attachment.thumbnail}\n alt={attachment.filename || \"Video thumbnail\"}\n className=\"cpk-attachment-queue-video-thumbnail\"\n />\n ) : (\n <video\n src={src}\n preload=\"metadata\"\n muted\n className=\"cpk-attachment-queue-video-thumbnail\"\n />\n )}\n </div>\n <button\n onClick={openLightbox}\n className=\"cpk-attachment-queue-video-play-button\"\n aria-label={labels.attachmentPlayVideoButtonLabel}\n >\n <div className=\"cpk-attachment-queue-video-play-badge\">\n <CopilotIcon\n name=\"Play\"\n className=\"cpk-attachment-queue-video-play-icon\"\n />\n </div>\n </button>\n {open && (\n <Lightbox\n onClose={closeLightbox}\n label={attachment.filename || \"Video attachment\"}\n >\n <video\n style={{ viewTransitionName: vtName }}\n src={src}\n controls\n autoPlay\n className=\"cpk-attachment-queue-lightbox-video\"\n />\n </Lightbox>\n )}\n </>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Document – click opens lightbox with PDF/text preview or info card\n// ---------------------------------------------------------------------------\n\n/**\n * A URL a frame can show for the attachment. Base64 data becomes a blob:\n * URL (browsers block data: URLs for PDFs), revoked on unmount.\n */\nfunction useBlobUrl(attachment: Attachment): string | null {\n const [url, setUrl] = useState<string | null>(null);\n\n useEffect(() => {\n if (attachment.source.type !== \"data\") return;\n const objectUrl = ɵcreateObjectUrlFromSource(attachment.source);\n setUrl(objectUrl?.url ?? null);\n return objectUrl?.revoke;\n }, [\n attachment.source.type,\n attachment.source.value,\n attachment.source.mimeType,\n ]);\n\n if (attachment.source.type === \"url\") return attachment.source.value;\n return url;\n}\n\nfunction DocumentLightboxContent({\n attachment,\n vtName,\n}: {\n attachment: Attachment;\n vtName: string;\n}) {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const mimeType = attachment.source.mimeType;\n const blobUrl = useBlobUrl(attachment);\n const preview = ɵcanPreviewDocument(mimeType);\n\n if (preview === \"pdf\") {\n if (!blobUrl) return null;\n return (\n <iframe\n style={{ viewTransitionName: vtName }}\n src={blobUrl}\n title={attachment.filename || \"PDF preview\"}\n className=\"cpk-attachment-queue-pdf-preview\"\n />\n );\n }\n\n if (preview === \"text\") {\n const textContent = ɵdecodeTextSource(attachment.source);\n return (\n <div\n style={{ viewTransitionName: vtName }}\n className=\"cpk-attachment-queue-text-preview\"\n >\n {attachment.filename && (\n <div className=\"cpk-attachment-queue-text-preview-filename\">\n {attachment.filename}\n </div>\n )}\n {textContent ? (\n <pre className=\"cpk-attachment-queue-text-preview-content\">\n {textContent}\n </pre>\n ) : blobUrl ? (\n <iframe\n src={blobUrl}\n title={attachment.filename || \"Text preview\"}\n className=\"cpk-attachment-queue-text-preview-frame\"\n />\n ) : null}\n </div>\n );\n }\n\n // Fallback: info card for non-previewable documents\n return (\n <div\n style={{ viewTransitionName: vtName }}\n className=\"cpk-attachment-queue-document-card\"\n >\n <div className=\"cpk-attachment-queue-document-card-icon\">\n {getDocumentIcon(mimeType ?? \"\")}\n </div>\n <div className=\"cpk-attachment-queue-document-card-details\">\n <div className=\"cpk-attachment-queue-document-card-name\">\n {attachment.filename || labels.attachmentDocumentLabel}\n </div>\n <div className=\"cpk-attachment-queue-document-card-meta\">\n {mimeType || labels.attachmentUnknownTypeText}\n {attachment.size != null && ` · ${formatFileSize(attachment.size)}`}\n </div>\n </div>\n <div className=\"cpk-attachment-queue-document-card-note\">\n {labels.attachmentNoPreviewText}\n </div>\n </div>\n );\n}\n\nfunction DocumentPreview({ attachment }: { attachment: Attachment }) {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n const { thumbnailRef, vtName, open, openLightbox, closeLightbox } =\n useLightbox();\n\n const mimeType = attachment.source.mimeType;\n const previewable = ɵcanPreviewDocument(mimeType) !== null;\n\n return (\n <>\n <div\n ref={thumbnailRef as React.Ref<HTMLDivElement>}\n className={cn(\n \"cpk-attachment-queue-document\",\n previewable && \"cpk-attachment-queue-document-previewable\",\n )}\n onClick={previewable ? openLightbox : undefined}\n >\n <div className=\"cpk-attachment-queue-document-icon\">\n {getDocumentIcon(mimeType ?? \"\")}\n </div>\n <div className=\"cpk-attachment-queue-document-info\">\n <span className=\"cpk-attachment-queue-document-name\">\n {attachment.filename || labels.attachmentDocumentLabel}\n </span>\n {attachment.size != null && (\n <span className=\"cpk-attachment-queue-document-size\">\n {formatFileSize(attachment.size)}\n </span>\n )}\n </div>\n </div>\n {open && (\n <Lightbox\n onClose={closeLightbox}\n label={attachment.filename || labels.attachmentDocumentLabel}\n >\n <DocumentLightboxContent attachment={attachment} vtName={vtName} />\n </Lightbox>\n )}\n </>\n );\n}\n","import { useState, useEffect } from \"react\";\nimport { ɵinitialKeyboardState, ɵwatchKeyboardState } from \"@copilotkit/core\";\nimport type { ɵKeyboardState } from \"@copilotkit/core\";\n\nexport type KeyboardState = ɵKeyboardState;\n\n/**\n * Hook to detect mobile keyboard appearance and calculate available viewport height.\n * Uses the Visual Viewport API to track keyboard state on mobile devices.\n *\n * @returns KeyboardState object with keyboard information\n */\nexport function useKeyboardHeight(): KeyboardState {\n const [keyboardState, setKeyboardState] = useState(ɵinitialKeyboardState);\n useEffect(() => ɵwatchKeyboardState(setKeyboardState), []);\n return keyboardState;\n}\n","import React from \"react\";\n\n/**\n * Context used by `CopilotChatView` to announce the latest user message\n * to descendants (notably `usePinToSend`), so scroll logic can anchor\n * the viewport to the most recent user turn in \"pin-to-send\" mode.\n *\n * `sendNonce` increments on each new send so repeated IDs (e.g., message\n * edits that preserve the ID) still trigger dependent effects.\n */\nexport type LastUserMessageState = {\n id: string | null;\n sendNonce: number;\n};\n\nexport const LastUserMessageContext = React.createContext<LastUserMessageState>(\n {\n id: null,\n sendNonce: 0,\n },\n);\n","import { useContext, useEffect, useRef } from \"react\";\nimport { ɵpinMessageToTop } from \"@copilotkit/core\";\nimport { LastUserMessageContext } from \"../components/chat/last-user-message-context\";\n\nexport type UsePinToSendOptions = {\n scrollRef: React.RefObject<HTMLElement | null>;\n contentRef: React.RefObject<HTMLElement | null>;\n spacerRef: React.RefObject<HTMLElement | null>;\n topOffset?: number;\n};\n\n/**\n * Pins the latest sent user message near the top of the chat while the reply\n * streams below it. Core's `ɵpinMessageToTop` does the measuring and\n * scrolling; this hook runs it once per send.\n */\nexport function usePinToSend({\n scrollRef,\n contentRef,\n spacerRef,\n topOffset = 16,\n}: UsePinToSendOptions): void {\n const { id, sendNonce } = useContext(LastUserMessageContext);\n const lastNonceRef = useRef<number>(-1);\n\n useEffect(() => {\n if (sendNonce === lastNonceRef.current) return;\n const previousNonce = lastNonceRef.current;\n lastNonceRef.current = sendNonce;\n\n if (!id) return;\n const scrollEl = scrollRef.current;\n const contentEl = contentRef.current;\n const spacerEl = spacerRef.current;\n if (!scrollEl || !contentEl || !spacerEl) return;\n\n const unpin = ɵpinMessageToTop({\n scrollEl,\n contentEl,\n spacerEl,\n messageId: id,\n topOffset,\n });\n return () => {\n // Torn down before the scroll ran, as React's StrictMode does right\n // after mount (the first send mounts the message list): let the next\n // run pin this send again. Skipping it would leave the spacer at its\n // full height for good, with nothing to shrink it as the reply grows.\n if (!unpin()) lastNonceRef.current = previousNonce;\n };\n }, [id, sendNonce, scrollRef, contentRef, spacerRef, topOffset]);\n}\n","import React, {\n useCallback,\n useRef,\n useState,\n useEffect,\n useLayoutEffect,\n} from \"react\";\nimport { ScrollElementContext } from \"./scroll-element-context\";\nimport type { WithSlots, SlotValue } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport CopilotChatMessageView from \"./CopilotChatMessageView\";\nimport type { CopilotChatMessageViewProps } from \"./CopilotChatMessageView\";\nimport type { IntelligenceIndicatorView } from \"../intelligence-indicator\";\nimport type {\n CopilotChatInputProps,\n CopilotChatInputMode,\n} from \"./CopilotChatInput\";\nimport CopilotChatInput from \"./CopilotChatInput\";\nimport CopilotChatSuggestionView from \"./CopilotChatSuggestionView\";\nimport {\n ɵgetChatViewState,\n ɵisContentScrolledToBottom,\n ɵisScrolledToBottom,\n ɵwatchElementHeight,\n} from \"@copilotkit/core\";\nimport type { Suggestion } from \"@copilotkit/core\";\nimport type { Message } from \"@ag-ui/core\";\nimport type { Attachment } from \"@copilotkit/shared\";\nimport { CopilotChatAttachmentQueue } from \"./CopilotChatAttachmentQueue\";\nimport { StickToBottom, useStickToBottomContext } from \"use-stick-to-bottom\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\nimport { Button } from \"../../components/ui/button\";\nimport { cn } from \"../../lib/utils\";\nimport { CopilotChatDefaultLabels } from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport { useKeyboardHeight } from \"../../hooks/use-keyboard-height\";\nimport { ScrollPinnedContext } from \"./scroll-pinned-context\";\nimport { ɵnormalizeAutoScroll as normalizeAutoScroll } from \"@copilotkit/core\";\nimport type { ɵAutoScrollMode as AutoScrollMode } from \"@copilotkit/core\";\nimport { usePinToSend } from \"../../hooks/use-pin-to-send\";\n\n// Vertical gap between the scroll-to-bottom button and the input container.\nconst SCROLL_BUTTON_OFFSET = 16;\n\n// Forward declaration for WelcomeScreen component type\nexport type WelcomeScreenProps = WithSlots<\n {\n welcomeMessage: React.FC<React.HTMLAttributes<HTMLDivElement>>;\n },\n {\n input: React.ReactElement;\n suggestionView: React.ReactElement;\n } & React.HTMLAttributes<HTMLDivElement>\n>;\n\nexport type CopilotChatViewProps = WithSlots<\n {\n // Props-based for the same reason as `input` below: renderSlot only\n // renders the slot, so CopilotChatMessageView's statics (Cursor) are not\n // required of a replacement.\n messageView: React.ComponentType<CopilotChatMessageViewProps>;\n scrollView: typeof CopilotChatView.ScrollView;\n // Widened to the props-based form so a plain FC / call signature assigns\n // without the CopilotChatInput namespace statics — see #7158, same shape as\n // CopilotChat's `chatView` after #7156.\n input: React.ComponentType<CopilotChatInputProps>;\n suggestionView: typeof CopilotChatSuggestionView;\n },\n {\n messages?: Message[];\n autoScroll?: AutoScrollMode | boolean;\n isRunning?: boolean;\n suggestions?: Suggestion[];\n suggestionLoadingIndexes?: ReadonlyArray<number>;\n onSelectSuggestion?: (suggestion: Suggestion, index: number) => void;\n welcomeScreen?: SlotValue<React.FC<WelcomeScreenProps>> | boolean;\n // Input behavior props\n onSubmitMessage?: (value: string) => void;\n onStop?: () => void;\n inputMode?: CopilotChatInputMode;\n inputValue?: string;\n onInputChange?: (value: string) => void;\n onStartTranscribe?: () => void;\n onCancelTranscribe?: () => void;\n onFinishTranscribe?: () => void;\n onFinishTranscribeWithAudio?: (audioBlob: Blob) => Promise<void>;\n // Attachment props\n attachments?: Attachment[];\n onRemoveAttachment?: (id: string) => void;\n onAddFile?: () => void;\n dragOver?: boolean;\n onDragOver?: (e: React.DragEvent) => void;\n onDragLeave?: (e: React.DragEvent) => void;\n onDrop?: (e: React.DragEvent) => void;\n /**\n * When `true`, suppresses the welcome screen while a thread's initial\n * connect is in flight. Prevents the \"How can I help you today?\" flash\n * that would otherwise appear between mounting an empty agent instance\n * and the bootstrap messages arriving from /connect.\n */\n isConnecting?: boolean;\n /**\n * Indicator shown while `isConnecting` is `true` and no messages have\n * arrived yet, so restoring a thread's history doesn't render as an\n * empty panel. Pass `false` to disable it, or a component, className, or\n * props object to customize it.\n */\n connectingIndicator?:\n | SlotValue<React.FC<React.HTMLAttributes<HTMLDivElement>>>\n | boolean;\n /**\n * When `true`, the caller has explicitly picked a thread (via `threadId`\n * prop or `CopilotChatConfigurationProvider`). Suppresses the welcome\n * screen unconditionally — a caller-managed thread targets a specific\n * conversation and should render its messages (or an empty panel during\n * connect) rather than a generic \"start a new chat\" greeting.\n */\n hasExplicitThreadId?: boolean;\n /**\n * Slot for the \"Using CopilotKit Intelligence\" indicator. Pass-through\n * to `CopilotChatMessageView`'s `intelligenceIndicator` slot — accepts a\n * className string, a props object, or a replacement component.\n */\n intelligenceIndicator?: SlotValue<typeof IntelligenceIndicatorView>;\n } & Omit<React.HTMLAttributes<HTMLDivElement>, \"inputMode\">\n>;\n\nfunction DropOverlay() {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <div className=\"cpk-chat-view-drop-overlay\">\n <div className=\"cpk-chat-view-drop-overlay-content\">\n <CopilotIcon\n name=\"Upload\"\n className=\"cpk-chat-view-drop-overlay-icon\"\n />\n <span className=\"cpk-chat-view-drop-overlay-label\">\n {labels.chatDropFilesLabel}\n </span>\n </div>\n </div>\n );\n}\n\nexport function CopilotChatView({\n messageView,\n input,\n scrollView,\n suggestionView,\n welcomeScreen,\n messages = [],\n autoScroll = true,\n isRunning = false,\n suggestions,\n suggestionLoadingIndexes,\n onSelectSuggestion,\n // Input behavior props\n onSubmitMessage,\n onStop,\n inputMode,\n inputValue,\n onInputChange,\n onStartTranscribe,\n onCancelTranscribe,\n onFinishTranscribe,\n onFinishTranscribeWithAudio,\n // Attachment props\n attachments,\n onRemoveAttachment,\n onAddFile,\n dragOver,\n onDragOver,\n onDragLeave,\n onDrop,\n isConnecting = false,\n connectingIndicator,\n hasExplicitThreadId = false,\n // Pass-through to CopilotChatMessageView's intelligenceIndicator slot\n intelligenceIndicator,\n children,\n className,\n ...props\n}: CopilotChatViewProps) {\n // Element-as-state via callback ref. The overlay wrapper only renders on the\n // chat-view branch (the welcome-screen branch omits it), so a plain\n // useRef + `[]` useEffect would observe `null` on mount whenever the chat\n // starts on the welcome screen and never re-attach after the user sends\n // their first message — leaving inputContainerHeight at 0 and the scroll\n // content's reserved bottom padding at 32px instead of ~input height. The\n // result is the last messages scrolling underneath the absolute-positioned\n // input pill. Subscribing to element state lets the observer attach (and\n // detach) reactively as the overlay mounts/unmounts.\n // Use the provider's thread identity when available. A standalone view\n // changes identity only when its new history has no messages in common with\n // the previous nonempty list. Prepending or trimming history is not a switch.\n const configuredThreadId = useCopilotChatConfiguration()?.threadId;\n const [fallbackThreadId, setFallbackThreadId] = useState(messages[0]?.id);\n const previousMessageIds = useRef(new Set<string>());\n useEffect(() => {\n const firstMessage = messages[0];\n if (firstMessage === undefined) return;\n const overlaps = messages.some((message) =>\n previousMessageIds.current.has(message.id),\n );\n previousMessageIds.current = new Set(messages.map((message) => message.id));\n if (!overlaps) setFallbackThreadId(firstMessage.id);\n }, [messages]);\n const scrollThreadId = configuredThreadId ?? fallbackThreadId;\n const [inputContainerEl, setInputContainerEl] =\n useState<HTMLDivElement | null>(null);\n const [inputContainerHeight, setInputContainerHeight] = useState(0);\n const [isResizing, setIsResizing] = useState(false);\n\n // Track keyboard state for mobile\n const { isKeyboardOpen, keyboardHeight } = useKeyboardHeight();\n\n // Track input container height changes. While the height settles, the\n // scroll-to-bottom button hides (see ɵwatchElementHeight).\n useEffect(() => {\n const element = inputContainerEl;\n if (!element) {\n // Reset measured height so the scroll content's paddingBottom doesn't\n // hold a stale value if the overlay unmounts (e.g. messages cleared\n // and the welcome screen returns).\n setInputContainerHeight(0);\n setIsResizing(false);\n return;\n }\n return ɵwatchElementHeight(element, (state) => {\n setInputContainerHeight(state.height);\n setIsResizing(state.isResizing);\n });\n }, [inputContainerEl]);\n\n const BoundMessageView = renderSlot(messageView, CopilotChatMessageView, {\n messages,\n isRunning,\n intelligenceIndicator,\n });\n\n const BoundInput = renderSlot(input, CopilotChatInput, {\n onSubmitMessage,\n onStop,\n mode: inputMode,\n value: inputValue,\n onChange: onInputChange,\n isRunning,\n onStartTranscribe,\n onCancelTranscribe,\n onFinishTranscribe,\n onFinishTranscribeWithAudio,\n onAddFile,\n positioning: \"static\",\n keyboardHeight: isKeyboardOpen ? keyboardHeight : 0,\n showDisclaimer: true,\n // The parent overlay wrapper handles absolute bottom-0 positioning.\n // `bottomAnchored` still triggers the license-banner offset padding\n // inside CopilotChatInput. The welcome-screen input (below) intentionally\n // omits this flag.\n bottomAnchored: true,\n } as CopilotChatInputProps);\n\n // Suggestions, the welcome screen and the bottom padding follow core's\n // rules (ɵgetChatViewState): no suggestions while connecting or running, no\n // generic welcome for a connecting or caller-picked thread.\n const {\n hasSuggestions,\n showWelcomeScreen,\n showConnectingIndicator,\n paddingBottom,\n } = ɵgetChatViewState({\n messageCount: messages.length,\n suggestionCount: Array.isArray(suggestions) ? suggestions.length : 0,\n isRunning,\n isConnecting,\n hasExplicitThreadId,\n // Type assertion needed because TypeScript doesn't fully propagate `| boolean` through WithSlots\n welcomeScreenEnabled: (welcomeScreen as unknown) !== false,\n inputContainerHeight,\n connectingIndicatorEnabled: connectingIndicator !== false,\n });\n const BoundSuggestionView = hasSuggestions\n ? renderSlot(suggestionView, CopilotChatSuggestionView, {\n suggestions,\n loadingIndexes: suggestionLoadingIndexes,\n onSelectSuggestion,\n className: \"cpk-chat-view-suggestion-view\",\n })\n : null;\n\n // Show a loading indicator while a thread's initial connect is in flight\n // and nothing has been restored yet. Once the first message arrives the\n // message view takes over, even if the bootstrap stream is still replaying.\n const BoundConnectingIndicator = showConnectingIndicator\n ? renderSlot(\n typeof connectingIndicator === \"boolean\"\n ? undefined\n : connectingIndicator,\n CopilotChatView.ConnectingIndicator,\n {},\n )\n : null;\n\n const BoundScrollView = renderSlot(scrollView, CopilotChatView.ScrollView, {\n autoScroll,\n scrollThreadId,\n inputContainerHeight,\n isResizing,\n children: (\n <div\n data-testid=\"copilot-scroll-content\"\n style={{\n paddingBottom: `${paddingBottom}px`,\n }}\n >\n <div className=\"cpk-chat-view-feed\">\n {BoundConnectingIndicator}\n {BoundMessageView}\n {hasSuggestions ? (\n <div className=\"cpk-chat-view-suggestions\">\n {BoundSuggestionView}\n </div>\n ) : null}\n </div>\n </div>\n ),\n });\n\n if (showWelcomeScreen) {\n // Create a separate input for welcome screen with static positioning and disclaimer visible\n const BoundInputForWelcome = renderSlot(input, CopilotChatInput, {\n onSubmitMessage,\n onStop,\n mode: inputMode,\n value: inputValue,\n onChange: onInputChange,\n isRunning,\n onStartTranscribe,\n onCancelTranscribe,\n onFinishTranscribe,\n onFinishTranscribeWithAudio,\n onAddFile,\n positioning: \"static\",\n showDisclaimer: true,\n } as CopilotChatInputProps);\n\n // Convert boolean `true` to undefined (use default), and exclude `false` since we've checked for it\n const welcomeScreenSlot = (\n welcomeScreen === true ? undefined : welcomeScreen\n ) as SlotValue<React.FC<WelcomeScreenProps>> | undefined;\n // Wrap the input with attachment queue above it\n const inputWithAttachments = (\n <div className=\"cpk-chat-view-welcome-input-group\">\n {attachments && attachments.length > 0 && (\n <CopilotChatAttachmentQueue\n attachments={attachments}\n onRemoveAttachment={(id) => onRemoveAttachment?.(id)}\n className=\"cpk-chat-view-welcome-attachment-queue\"\n />\n )}\n {BoundInputForWelcome}\n </div>\n );\n\n const BoundWelcomeScreen = renderSlot(\n welcomeScreenSlot,\n CopilotChatView.WelcomeScreen,\n {\n input: inputWithAttachments,\n suggestionView: BoundSuggestionView ?? <></>,\n },\n );\n\n return (\n <div\n data-copilotkit\n data-testid=\"copilot-chat\"\n data-copilot-running={isRunning ? \"true\" : \"false\"}\n data-copilot-connecting={isConnecting ? \"true\" : \"false\"}\n onDragOver={onDragOver}\n onDragLeave={onDragLeave}\n onDrop={onDrop}\n className={cn(\"copilotKitChat cpk-chat-view\", className)}\n {...props}\n >\n {dragOver && <DropOverlay />}\n {BoundWelcomeScreen}\n </div>\n );\n }\n\n if (children) {\n return (\n <div\n data-copilotkit\n data-copilot-connecting={isConnecting ? \"true\" : \"false\"}\n style={{ display: \"contents\" }}\n >\n {children({\n messageView: BoundMessageView,\n input: BoundInput,\n scrollView: BoundScrollView,\n suggestionView: BoundSuggestionView ?? <></>,\n })}\n </div>\n );\n }\n\n return (\n <div\n data-copilotkit\n data-testid=\"copilot-chat\"\n data-copilot-running={isRunning ? \"true\" : \"false\"}\n data-copilot-connecting={isConnecting ? \"true\" : \"false\"}\n onDragOver={onDragOver}\n onDragLeave={onDragLeave}\n onDrop={onDrop}\n className={cn(\"copilotKitChat cpk-chat-view\", className)}\n {...props}\n >\n {dragOver && <DropOverlay />}\n {BoundScrollView}\n\n <div\n ref={setInputContainerEl}\n data-testid=\"copilot-input-overlay\"\n className=\"cpk-chat-view-input-overlay\"\n >\n {attachments && attachments.length > 0 && (\n <div className=\"cpk-chat-view-attachments\">\n <CopilotChatAttachmentQueue\n attachments={attachments}\n onRemoveAttachment={(id) => onRemoveAttachment?.(id)}\n className=\"cpk-chat-view-attachment-queue\"\n />\n </div>\n )}\n {BoundInput}\n </div>\n </div>\n );\n}\n\nexport namespace CopilotChatView {\n // Inner component that has access to StickToBottom context\n const ScrollContent: React.FC<{\n children: React.ReactNode;\n scrollToBottomButton?: SlotValue<\n React.FC<React.ButtonHTMLAttributes<HTMLButtonElement>>\n >;\n feather?: SlotValue<React.FC<React.HTMLAttributes<HTMLDivElement>>>;\n inputContainerHeight: number;\n isResizing: boolean;\n scrollThreadId?: string;\n }> = ({\n children,\n scrollToBottomButton,\n feather,\n inputContainerHeight,\n isResizing,\n scrollThreadId,\n }) => {\n const { isAtBottom, scrollToBottom, stopScroll, scrollRef, state } =\n useStickToBottomContext();\n\n // Capture the scroll element in state so the context value is reactive —\n // consumers re-render when the element is first set rather than reading a\n // ref that silently stays null until after their own layout effects fire.\n const [scrollEl, setScrollEl] = useState<HTMLElement | null>(null);\n const readingOffsetRef = useRef<number | null>(null);\n const pinIntentRef = useRef(false);\n const stateRef = useRef(state);\n stateRef.current = state;\n useLayoutEffect(() => {\n setScrollEl(scrollRef.current ?? null);\n // scrollRef is a stable object; omitting from deps is intentional.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // A hidden chat has no viewport. The stick-to-bottom observer can mistake\n // that collapse for reaching the end and re-enable its scroll lock. Keep\n // the reader's last visible offset until the viewport is measurable again.\n useEffect(() => {\n if (!scrollEl) return;\n\n let hidden = false;\n let resumeBottom = false;\n let pendingFrame = 0;\n let resumeFrame = 0;\n let settleFrame = 0;\n readingOffsetRef.current = null;\n const rememberScroll = () => {\n if (hidden || scrollEl.clientHeight === 0) return;\n if (resumeBottom) {\n // Ignore scroll events from the collapsed layout until the pending\n // bottom pin has been restarted against the restored viewport.\n readingOffsetRef.current = null;\n return;\n }\n if (pinIntentRef.current) {\n // Keyboard, touch, and scrollbar input can escape the pin without a\n // wheel event. The library reports that escape after its scroll\n // callback, so the scheduled frame below sees the updated state.\n if (stateRef.current.escapedFromLock) {\n pinIntentRef.current = false;\n } else {\n readingOffsetRef.current = null;\n if (!stateRef.current.isNearBottom) return;\n pinIntentRef.current = false;\n }\n }\n // Geometry alone is misleading during an active smooth pin: it may\n // still be far from the end while intentionally moving there.\n readingOffsetRef.current =\n !stateRef.current.isAtBottom &&\n (stateRef.current.escapedFromLock || !stateRef.current.isNearBottom)\n ? scrollEl.scrollTop\n : null;\n };\n const onScroll = () => {\n rememberScroll();\n // The library updates escape state after its scroll event callback.\n // Re-read it on the next frame for programmatic scrolls too.\n cancelAnimationFrame(pendingFrame);\n pendingFrame = requestAnimationFrame(rememberScroll);\n };\n const onWheel = (event: WheelEvent) => {\n if (event.deltaY < 0) {\n pinIntentRef.current = false;\n resumeBottom = false;\n }\n };\n const resizeObserver = new ResizeObserver(() => {\n if (scrollEl.clientHeight === 0) {\n hidden = true;\n resumeBottom =\n pinIntentRef.current || readingOffsetRef.current === null;\n if (!resumeBottom) stopScroll();\n } else if (hidden) {\n hidden = false;\n if (resumeBottom) {\n // Cancel the old animation before starting a new one against the\n // restored viewport; otherwise its queued frame can override us.\n stopScroll();\n // The library's animation may have stopped at zero height. Wait\n // for the restored layout before calculating its new bottom.\n resumeFrame = requestAnimationFrame(() => {\n // Let the library's scroll event from the zero-height collapse\n // finish before starting a fresh pin animation.\n settleFrame = requestAnimationFrame(() => {\n if (scrollEl.clientHeight > 0 && resumeBottom) {\n resumeBottom = false;\n pinIntentRef.current = true;\n void scrollToBottom({ animation: \"instant\" });\n }\n });\n });\n } else if (readingOffsetRef.current !== null) {\n stopScroll();\n scrollEl.scrollTop = readingOffsetRef.current;\n }\n }\n });\n\n rememberScroll();\n scrollEl.addEventListener(\"scroll\", onScroll);\n scrollEl.addEventListener(\"wheel\", onWheel, { passive: true });\n resizeObserver.observe(scrollEl);\n return () => {\n scrollEl.removeEventListener(\"scroll\", onScroll);\n scrollEl.removeEventListener(\"wheel\", onWheel);\n cancelAnimationFrame(pendingFrame);\n cancelAnimationFrame(resumeFrame);\n cancelAnimationFrame(settleFrame);\n resizeObserver.disconnect();\n };\n }, [scrollEl, scrollToBottom, stopScroll, scrollThreadId]);\n\n const startBottomPin = useCallback(\n (instant = false) => {\n readingOffsetRef.current = null;\n pinIntentRef.current = true;\n void scrollToBottom(instant ? { animation: \"instant\" } : undefined);\n },\n [scrollToBottom],\n );\n\n const previousScrollThreadId = useRef(scrollThreadId);\n useEffect(() => {\n if (previousScrollThreadId.current === scrollThreadId) return;\n previousScrollThreadId.current = scrollThreadId;\n // A new conversation should start at its end even if the old one had\n // escaped the pin while its host was hidden.\n startBottomPin(true);\n }, [scrollThreadId, startBottomPin]);\n\n const BoundFeather = renderSlot(feather, CopilotChatView.Feather, {});\n\n return (\n // Provide the scroll element so CopilotChatMessageView can feed it to\n // useVirtualizer's getScrollElement. Using state (not the raw ref) means\n // the context value updates reactively when the element mounts.\n <ScrollElementContext.Provider value={scrollEl}>\n {/* While the pin is following the bottom it is the sole owner of the\n scroll position; the virtualizer stands down (see\n ScrollPinnedContext).\n\n `state.isAtBottom`, not the context's `isAtBottom`: the latter is\n `isAtBottom || isNearBottom`. Scrolling up a little — still inside\n the near-bottom band — clears `state.isAtBottom`, which is what the\n pin's animation loop checks before it moves anything, while the\n combined flag stays true. Using the combined flag would stand the\n virtualizer down in a window where nothing owns the scroll\n position.\n\n `state` is a stable object, so this is only read again when\n something re-renders us. Every transition *out* of the pin sets\n `escapedFromLock` in the same breath, and that is one of the deps\n of the memo behind this context, so the re-render is there for the\n case that matters. The way back in can lag a render, which leaves\n the virtualizer compensating slightly longer than it needs to —\n the harmless direction, and what it does by default anyway.\n\n The scroll-to-bottom button keeps the combined flag: it should\n stay hidden anywhere in the near-bottom band. */}\n <ScrollPinnedContext.Provider value={state.isAtBottom}>\n <>\n <StickToBottom.Content\n className=\"cpk-chat-view-scroll-viewport\"\n style={{ flex: \"1 1 0%\", minHeight: 0 }}\n >\n <div className=\"cpk-chat-view-scroll-content\">{children}</div>\n </StickToBottom.Content>\n\n {BoundFeather}\n\n {/* Scroll to bottom button - hidden during resize */}\n {!isAtBottom && !isResizing && (\n <div\n className=\"cpk-chat-view-scroll-to-bottom\"\n style={{\n bottom: `${inputContainerHeight + SCROLL_BUTTON_OFFSET}px`,\n }}\n >\n {renderSlot(\n scrollToBottomButton,\n CopilotChatView.ScrollToBottomButton,\n {\n onClick: () => startBottomPin(),\n },\n )}\n </div>\n )}\n </>\n </ScrollPinnedContext.Provider>\n </ScrollElementContext.Provider>\n );\n };\n\n // Internal component for pin-to-send scroll behavior — not exported on CopilotChatView.\n const PinToSendScrollContainer: React.FC<\n React.HTMLAttributes<HTMLDivElement> & {\n scrollRef: React.MutableRefObject<HTMLElement | null>;\n contentRef: React.MutableRefObject<HTMLDivElement | null>;\n scrollToBottom: () => void;\n scrollToBottomButton?: SlotValue<\n React.FC<React.ButtonHTMLAttributes<HTMLButtonElement>>\n >;\n feather?: SlotValue<React.FC<React.HTMLAttributes<HTMLDivElement>>>;\n inputContainerHeight: number;\n isResizing: boolean;\n nonAutoScrollEl: HTMLElement | null;\n nonAutoScrollRefCallback: (el: HTMLElement | null) => void;\n showScrollButton: boolean;\n }\n > = ({\n children,\n scrollRef,\n contentRef,\n scrollToBottom,\n scrollToBottomButton,\n feather,\n inputContainerHeight,\n isResizing,\n nonAutoScrollEl,\n nonAutoScrollRefCallback,\n showScrollButton,\n className,\n ...props\n }) => {\n const spacerRef = useRef<HTMLDivElement>(null);\n\n usePinToSend({\n scrollRef,\n contentRef,\n spacerRef,\n topOffset: 16,\n });\n\n // The feather and scroll-to-bottom button live OUTSIDE the scroll\n // container. `position: absolute` children of an `overflow: auto` element\n // are positioned relative to the scroll *content*, which means they\n // scroll away with it. Placing them as siblings of the scroll container\n // (inside a `relative` wrapper) keeps them pinned to the viewport bottom.\n const BoundFeather = renderSlot(feather, CopilotChatView.Feather, {});\n\n return (\n <ScrollElementContext.Provider value={nonAutoScrollEl}>\n <div className={cn(\"cpk-chat-view-scroll-area\", className)}>\n <div\n ref={nonAutoScrollRefCallback}\n className=\"cpk-chat-view-scroll-viewport\"\n {...props}\n >\n <div ref={contentRef} className=\"cpk-chat-view-scroll-content\">\n {children}\n </div>\n <div\n ref={spacerRef}\n data-pin-to-send-spacer\n aria-hidden=\"true\"\n style={{ height: 0, flex: \"0 0 auto\" }}\n />\n </div>\n {BoundFeather}\n {/* Scroll to bottom button */}\n {showScrollButton && !isResizing && (\n <div\n className=\"cpk-chat-view-scroll-to-bottom\"\n style={{\n bottom: `${inputContainerHeight + SCROLL_BUTTON_OFFSET}px`,\n }}\n >\n {renderSlot(\n scrollToBottomButton,\n CopilotChatView.ScrollToBottomButton,\n {\n onClick: () => scrollToBottom(),\n },\n )}\n </div>\n )}\n </div>\n </ScrollElementContext.Provider>\n );\n };\n\n export const ScrollView: React.FC<\n React.HTMLAttributes<HTMLDivElement> & {\n autoScroll?: AutoScrollMode | boolean;\n scrollThreadId?: string;\n scrollToBottomButton?: SlotValue<\n React.FC<React.ButtonHTMLAttributes<HTMLButtonElement>>\n >;\n feather?: SlotValue<React.FC<React.HTMLAttributes<HTMLDivElement>>>;\n inputContainerHeight?: number;\n isResizing?: boolean;\n }\n > = ({\n children,\n autoScroll = \"pin-to-bottom\",\n scrollThreadId,\n scrollToBottomButton,\n feather,\n inputContainerHeight = 0,\n isResizing = false,\n className,\n ...props\n }) => {\n const mode = normalizeAutoScroll(autoScroll);\n const [hasMounted, setHasMounted] = useState(false);\n // Plain refs for the \"none\" and \"pin-to-send\" paths. Do NOT use\n // useStickToBottom() here — its internal effects would attach scroll-following\n // behavior to these refs and fight pin-to-send. The \"pin-to-bottom\" path\n // gets its refs via <StickToBottom> below, scoped to that branch only.\n const scrollRef = useRef<HTMLElement | null>(null);\n const contentRef = useRef<HTMLDivElement | null>(null);\n const scrollToBottom = useCallback(() => {\n const el = scrollRef.current;\n if (el) el.scrollTo({ top: el.scrollHeight, behavior: \"smooth\" });\n }, []);\n const [showScrollButton, setShowScrollButton] = useState(false);\n // Tracks the scroll container element for the non-autoScroll path so the\n // context value is reactive (element state, not a ref).\n const [nonAutoScrollEl, setNonAutoScrollEl] = useState<HTMLElement | null>(\n null,\n );\n\n // Callback ref that keeps scrollRef in sync with the DOM element while also\n // updating context state — eliminates the need for a useLayoutEffect.\n const nonAutoScrollRefCallback = useCallback(\n (el: HTMLElement | null) => {\n scrollRef.current = el;\n setNonAutoScrollEl(el);\n },\n // scrollRef is a stable ref object; safe to omit.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [],\n );\n\n useEffect(() => {\n setHasMounted(true);\n }, []);\n\n // Monitor scroll position for non-autoscroll mode\n useEffect(() => {\n if (mode === \"pin-to-bottom\") return; // Skip for autoscroll mode\n\n const scrollElement = nonAutoScrollEl;\n if (!scrollElement) return;\n const contentElement = contentRef.current;\n\n // The button shows while messages sit below the viewport. That is the\n // end of the messages, not the scroll height: in \"pin-to-send\" mode an\n // empty spacer under them lets a sent message reach the top, and\n // scrolling into it would only clear the screen.\n const checkScroll = () => {\n const isAtBottom = contentElement\n ? ɵisContentScrolledToBottom(scrollElement, contentElement)\n : ɵisScrolledToBottom(scrollElement);\n setShowScrollButton(!isAtBottom);\n };\n\n checkScroll();\n scrollElement.addEventListener(\"scroll\", checkScroll);\n\n // Also check when the viewport or the messages resize: a reply that\n // streams past the bottom needs the button before anyone scrolls.\n const resizeObserver = new ResizeObserver(checkScroll);\n resizeObserver.observe(scrollElement);\n if (contentElement) resizeObserver.observe(contentElement);\n\n return () => {\n scrollElement.removeEventListener(\"scroll\", checkScroll);\n resizeObserver.disconnect();\n };\n }, [nonAutoScrollEl, mode]);\n\n if (!hasMounted) {\n return (\n <div className=\"cpk-chat-view-scroll-area cpk-chat-view-scroll-viewport\">\n <div className=\"cpk-chat-view-scroll-content\">{children}</div>\n </div>\n );\n }\n\n if (mode === \"none\") {\n const BoundFeather = renderSlot(feather, CopilotChatView.Feather, {});\n\n return (\n // Provide the scroll element so CopilotChatMessageView can use it for\n // useVirtualizer. Element state (not a ref) keeps the context reactive.\n <ScrollElementContext.Provider value={nonAutoScrollEl}>\n <div\n ref={nonAutoScrollRefCallback}\n className={cn(\n \"cpk-chat-view-scroll-area cpk-chat-view-scroll-viewport\",\n className,\n )}\n {...props}\n >\n <div ref={contentRef} className=\"cpk-chat-view-scroll-content\">\n {children}\n </div>\n\n {BoundFeather}\n\n {/* Scroll to bottom button for manual mode */}\n {showScrollButton && !isResizing && (\n <div\n className=\"cpk-chat-view-scroll-to-bottom\"\n style={{\n bottom: `${inputContainerHeight + SCROLL_BUTTON_OFFSET}px`,\n }}\n >\n {renderSlot(\n scrollToBottomButton,\n CopilotChatView.ScrollToBottomButton,\n {\n onClick: () => scrollToBottom(),\n },\n )}\n </div>\n )}\n </div>\n </ScrollElementContext.Provider>\n );\n }\n\n if (mode === \"pin-to-send\") {\n return (\n <PinToSendScrollContainer\n scrollRef={scrollRef}\n contentRef={contentRef}\n scrollToBottom={scrollToBottom}\n scrollToBottomButton={scrollToBottomButton}\n feather={feather}\n inputContainerHeight={inputContainerHeight}\n isResizing={isResizing}\n nonAutoScrollEl={nonAutoScrollEl}\n nonAutoScrollRefCallback={nonAutoScrollRefCallback}\n showScrollButton={showScrollButton}\n className={className}\n {...props}\n >\n {children}\n </PinToSendScrollContainer>\n );\n }\n\n // mode === \"pin-to-bottom\" (default)\n return (\n <StickToBottom\n className={cn(\"cpk-chat-view-scroll-view\", className)}\n resize=\"smooth\"\n initial=\"smooth\"\n {...props}\n >\n <ScrollContent\n scrollThreadId={scrollThreadId}\n scrollToBottomButton={scrollToBottomButton}\n feather={feather}\n inputContainerHeight={inputContainerHeight}\n isResizing={isResizing}\n >\n {children}\n </ScrollContent>\n </StickToBottom>\n );\n };\n\n /**\n * Scrolls the message list to the latest message. Shown while the user is\n * scrolled up; its accessible name is `labels.chatScrollToBottomLabel`.\n */\n export const ScrollToBottomButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ className, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <Button\n data-testid=\"copilot-scroll-to-bottom\"\n variant=\"outline\"\n size=\"sm\"\n className={cn(\"cpk-chat-view-scroll-to-bottom-button\", className)}\n aria-label={labels.chatScrollToBottomLabel}\n {...props}\n >\n <CopilotIcon\n name=\"ChevronDown\"\n className=\"cpk-chat-view-scroll-to-bottom-icon\"\n />\n </Button>\n );\n };\n\n // Default renders an empty div — no visual, but the element is still in the\n // tree so a slot override of the form `scrollView={{ feather: \"my-class\" }}`\n // can apply classes (and any consumer with a full component override gets\n // the className/style forwarding they expect).\n export const Feather: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({\n className,\n ...props\n }) => <div className={className} {...props} />;\n\n /**\n * Default indicator shown while a thread's history is being restored.\n * Renders a spinner plus visually hidden `labels.chatConnectingLabel` text\n * inside a `role=\"status\"` region. Replace it via the `connectingIndicator`\n * slot.\n */\n export const ConnectingIndicator: React.FC<\n React.HTMLAttributes<HTMLDivElement>\n > = ({ className, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n\n return (\n <div\n data-testid=\"copilot-connecting-indicator\"\n role=\"status\"\n className={cn(\"cpk-chat-view-connecting-indicator\", className)}\n {...props}\n >\n <CopilotIcon\n name=\"Loader2\"\n className=\"cpk-chat-view-connecting-spinner\"\n />\n {/* Screen readers announce a status region's text content, not its\n aria-label, so the label is visually hidden text. */}\n <span className=\"cpk-chat-view-connecting-label\">\n {labels.chatConnectingLabel}\n </span>\n </div>\n );\n };\n\n export const WelcomeMessage: React.FC<\n React.HTMLAttributes<HTMLDivElement>\n > = ({ className, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n\n return (\n <h1 className={cn(\"cpk-chat-view-welcome-message\", className)} {...props}>\n {labels.welcomeMessageText}\n </h1>\n );\n };\n\n export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({\n welcomeMessage,\n input,\n suggestionView,\n className,\n children,\n ...props\n }) => {\n // Render the welcomeMessage slot internally\n const BoundWelcomeMessage = renderSlot(\n welcomeMessage,\n CopilotChatView.WelcomeMessage,\n {},\n );\n\n if (children) {\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children({\n welcomeMessage: BoundWelcomeMessage,\n input,\n suggestionView,\n className,\n ...props,\n })}\n </div>\n );\n }\n\n return (\n <div\n data-testid=\"copilot-welcome-screen\"\n className={cn(\"cpk-chat-view-welcome-screen\", className)}\n {...props}\n >\n <div className=\"cpk-chat-view-welcome-screen-content\">\n {/* Welcome message */}\n <div className=\"cpk-chat-view-welcome-screen-message\">\n {BoundWelcomeMessage}\n </div>\n\n {/* Input */}\n <div className=\"cpk-chat-view-welcome-screen-input\">{input}</div>\n\n {/* Suggestions */}\n <div className=\"cpk-chat-view-welcome-screen-suggestions\">\n {suggestionView}\n </div>\n </div>\n </div>\n );\n };\n}\n\nexport default CopilotChatView;\n","import { useEffect, useState, useSyncExternalStore } from \"react\";\nimport { ɵInspectorThreadOverride } from \"@copilotkit/core\";\n\n/**\n * Apply the Inspector's \"view this thread\" requests to a chat. Core's\n * `ɵInspectorThreadOverride` owns the state machine; this hook binds it to\n * the component's lifetime and React's render cycle.\n */\nexport function useInspectorThreadOverride(args: {\n agentId: string;\n baseThreadId: string;\n}): {\n inspectorThreadId: string | null;\n inspectorRequestId: string | null;\n failInspectorOverride: (requestId: string) => void;\n} {\n const [controller] = useState(() => new ɵInspectorThreadOverride(args));\n const override = useSyncExternalStore(\n controller.subscribe,\n controller.getSnapshot,\n controller.getSnapshot,\n );\n\n const { agentId, baseThreadId } = args;\n useEffect(() => {\n controller.update({ agentId, baseThreadId });\n }, [controller, agentId, baseThreadId]);\n\n return {\n inspectorThreadId: override?.threadId ?? null,\n inspectorRequestId: override?.requestId ?? null,\n failInspectorOverride: controller.fail,\n };\n}\n","import { useAgent } from \"../../hooks/use-agent\";\nimport { useAttachments } from \"../../hooks/use-attachments\";\nimport { useSuggestions } from \"../../hooks/use-suggestions\";\nimport type { CopilotChatViewProps } from \"./CopilotChatView\";\nimport { CopilotChatView } from \"./CopilotChatView\";\nimport type { CopilotChatInputMode } from \"./CopilotChatInput\";\nimport {\n CopilotChatConfigurationProvider,\n useCopilotChatConfiguration,\n} from \"../../providers/CopilotChatConfigurationProvider\";\nimport { randomUUID } from \"@copilotkit/shared\";\nimport type { AttachmentsConfig } from \"@copilotkit/shared\";\nimport {\n CopilotChatDefaultLabels,\n CopilotKitCoreErrorCode,\n CopilotKitCoreRuntimeConnectionStatus,\n ɵChatConnection,\n ɵcreateChatSubmitter,\n ɵcreateLastUserMessageTracker,\n ɵcreateThreadStore,\n ɵFreshThreadId,\n ɵmessagesFingerprint,\n ɵresolveAgentId,\n ɵresolveChatNotice,\n ɵsubscribeToAgentErrors,\n} from \"@copilotkit/core\";\nimport type {\n CopilotChatLabels,\n Suggestion,\n ɵChatRunScope,\n ɵThreadRuntimeContext,\n ɵThreadStore,\n} from \"@copilotkit/core\";\nimport React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport {\n useCopilotKit,\n useDefaultAgentId,\n useLicenseContext,\n} from \"../../context\";\nimport { InlineFeatureWarning } from \"../../components/license-warning-banner\";\nimport type { SlotValue } from \"../../lib/slots\";\nimport { renderSlot, useShallowStableRef } from \"../../lib/slots\";\nimport { LastUserMessageContext } from \"./last-user-message-context\";\nimport type { LastUserMessageState } from \"./last-user-message-context\";\nimport { useInspectorThreadOverride } from \"../../providers/use-inspector-thread-override\";\nimport { GenerativeUIChatSlotContext } from \"../../generative-ui/chat\";\nimport type { GenerativeUIChatSurfaceProps } from \"../../generative-ui/chat\";\nimport {\n CopilotKitInspectorContextProvider,\n useCopilotKitInspector,\n} from \"../CopilotKitInspectorContext\";\nimport { CopilotKitStyles } from \"../../styles/copilot-kit-styles\";\n\nexport type CopilotChatProps = Omit<\n CopilotChatViewProps,\n | \"messages\"\n | \"isRunning\"\n | \"suggestions\"\n | \"suggestionLoadingIndexes\"\n | \"onSelectSuggestion\"\n // Attachment state props — managed internally based on `attachments` config\n | \"attachments\"\n | \"onRemoveAttachment\"\n | \"onAddFile\"\n | \"dragOver\"\n | \"onDragOver\"\n | \"onDragLeave\"\n | \"onDrop\"\n // CopilotChat defines its own agent-error `onError` below and never passes\n // it to the view's <div>, so the DOM `onError` attribute is left out.\n | \"onError\"\n // Redeclared below, deprecated: the chat sets it from its own state\n | \"inputMode\"\n> & {\n /**\n * @deprecated Has no effect. `CopilotChat` sets the input mode from its own\n * transcription state. To set it yourself, render `CopilotChatView` and pass\n * `inputMode` there.\n */\n inputMode?: CopilotChatViewProps[\"inputMode\"];\n agentId?: string;\n threadId?: string;\n labels?: Partial<CopilotChatLabels>;\n /**\n * Enable Inspector message shortcuts for this chat (enabled by default).\n * An explicit CopilotKit provider enableInspector value takes priority.\n * Shortcuts only appear in local development while Inspector is visible.\n */\n inspectorTools?: boolean;\n /** Accepts a className, partial props, or any component with CopilotChatView props — static namespace members are not required. */\n chatView?: SlotValue<React.ComponentType<CopilotChatViewProps>>;\n isModalDefaultOpen?: boolean;\n /** Enable multimodal file attachments (images, audio, video, documents). */\n attachments?: AttachmentsConfig;\n /**\n * Error handler scoped to this chat's agent. Fires in addition to the\n * provider-level onError (does not suppress it). Receives only errors\n * whose context.agentId matches this chat's agent.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n /**\n * Throttle interval (in milliseconds) for re-renders triggered by message\n * change notifications. Overrides the provider-level `defaultThrottleMs`\n * for this chat instance. Forwarded to the internal `useAgent()` hook,\n * which resolves the effective throttle value.\n *\n * @default undefined — inherits from provider `defaultThrottleMs`;\n * if that is also unset, re-renders are unthrottled. Note: passing\n * `throttleMs={0}` explicitly disables throttling for this instance\n * even when the provider specifies a non-zero `defaultThrottleMs`.\n */\n throttleMs?: number;\n /**\n * Experimental. Wrapper for generative UI surfaces rendered in this chat.\n * Receives `{ surfaceId, isStreaming, error, children }`.\n */\n generativeUISurface?: React.ComponentType<GenerativeUIChatSurfaceProps>;\n};\nexport function CopilotChat({\n agentId,\n threadId,\n labels,\n inspectorTools,\n chatView,\n isModalDefaultOpen,\n attachments: attachmentsConfig,\n onError,\n throttleMs,\n generativeUISurface,\n ...props\n}: CopilotChatProps) {\n // Check for existing configuration provider\n const existingConfig = useCopilotChatConfiguration();\n const inspector = useCopilotKitInspector();\n const inspectorContextValue = useMemo(\n () => ({\n ...inspector,\n isInspectorEnabled:\n inspector.isInspectorEnabled &&\n (inspector.providerEnableInspector ?? inspectorTools ?? true),\n }),\n [inspector, inspectorTools],\n );\n\n // Apply priority: props > existing config > defaults\n const providerAgentId = useDefaultAgentId();\n const resolvedAgentId = ɵresolveAgentId({\n agentId,\n chatAgentId: existingConfig?.agentId,\n providerAgentId,\n });\n const providedThreadId = threadId ?? existingConfig?.threadId;\n const [freshThreadId] = useState(() => new ɵFreshThreadId());\n const baseThreadId = useMemo(\n () => freshThreadId.resolve(providedThreadId),\n [freshThreadId, providedThreadId],\n );\n // \"Explicit\" means a caller actually picked this thread — via the\n // `threadId` prop on CopilotChat or a wrapping provider that marked its\n // threadId as caller-chosen. An auto-minted UUID leaking down through a\n // CopilotChatConfigurationProvider (e.g. from the v1 CopilotKit →\n // ThreadsProvider chain) does NOT count; treating it as explicit is\n // what made /connect fire against 404s and the welcome screen stay\n // hidden for fresh empty chats.\n const baseHasExplicitThreadId =\n !!threadId || !!existingConfig?.hasExplicitThreadId;\n const { inspectorThreadId, inspectorRequestId, failInspectorOverride } =\n useInspectorThreadOverride({\n agentId: resolvedAgentId,\n baseThreadId,\n });\n const resolvedThreadId = inspectorThreadId ?? baseThreadId;\n const hasExplicitThreadId =\n inspectorThreadId !== null || baseHasExplicitThreadId;\n\n const { agent, isReady } = useAgent({\n agentId: resolvedAgentId,\n throttleMs,\n });\n const { copilotkit } = useCopilotKit();\n const { suggestions: autoSuggestions } = useSuggestions({\n agentId: resolvedAgentId,\n });\n\n const { checkFeature } = useLicenseContext();\n const isChatLicensed = checkFeature(\"chat\");\n\n useEffect(() => {\n if (!isChatLicensed) {\n console.warn(\n '[CopilotKit] Warning: \"chat\" feature is not licensed. Visit copilotkit.ai/pricing',\n );\n }\n }, [isChatLicensed]);\n\n // onError subscription — forward core errors scoped to this chat's agent\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n if (!onErrorRef.current) return;\n return ɵsubscribeToAgentErrors(copilotkit, resolvedAgentId, (event) =>\n onErrorRef.current?.(event),\n );\n }, [copilotkit, resolvedAgentId]);\n\n // Loads the thread this chat shows. Owns the connect's abort, detach and\n // \"connecting\" state, and ends a failed Inspector override.\n const failInspectorOverrideRef = useRef(failInspectorOverride);\n failInspectorOverrideRef.current = failInspectorOverride;\n const [connection] = useState(\n () =>\n new ɵChatConnection({\n core: copilotkit,\n onInspectorOverrideFailed: (requestId) =>\n failInspectorOverrideRef.current(requestId),\n }),\n );\n const { threads } = connection;\n useSyncExternalStore(\n useCallback((onChange) => connection.subscribe(onChange), [connection]),\n () => connection.getSnapshot(),\n () => connection.getSnapshot(),\n );\n\n // Transcription state\n const [transcribeMode, setTranscribeMode] =\n useState<CopilotChatInputMode>(\"input\");\n const [inputValue, setInputValue] = useState(\"\");\n // The submitter reads and writes the input between renders (a transcript\n // appended after an await, a blocked send restored), so it goes through a\n // ref that is always the latest value.\n const inputValueRef = useRef(inputValue);\n inputValueRef.current = inputValue;\n\n // Attachments\n const {\n attachments: selectedAttachments,\n enabled: attachmentsEnabled,\n dragOver,\n fileInputRef,\n containerRef: chatContainerRef,\n handleFileUpload,\n handleDragOver,\n handleDragLeave,\n handleDrop,\n removeAttachment,\n consumeAttachments,\n } = useAttachments({ config: attachmentsConfig });\n\n // A send waits for the run in flight, so the submitter re-checks the\n // \"uploading\" guard after the wait against FRESH state, not this render's.\n const selectedAttachmentsRef = useRef(selectedAttachments);\n useEffect(() => {\n selectedAttachmentsRef.current = selectedAttachments;\n }, [selectedAttachments]);\n\n // Check if transcription is enabled\n const isTranscriptionEnabled = copilotkit.audioFileTranscriptionEnabled;\n\n // Check if browser supports MediaRecorder\n const isMediaRecorderSupported =\n typeof window !== \"undefined\" && typeof MediaRecorder !== \"undefined\";\n\n const {\n messageView: providedMessageView,\n suggestionView: providedSuggestionView,\n onStop: providedStopHandler,\n ...restProps\n } = props;\n\n // When the caller picked a thread, the welcome screen stays hidden until\n // its connect settles, so switching threads does not flash it while the\n // thread's messages load.\n const isConnecting = connection.isConnecting({\n threadId: resolvedThreadId,\n explicit: hasExplicitThreadId,\n });\n const activeConnectCountRef = useRef(0);\n const trackConnection = useCallback(\n (connect: () => Promise<void>) => {\n void connection.track(connect);\n },\n [connection],\n );\n const pendingRunActivityReconnectRef = useRef(false);\n const runActivityReconnectGenerationRef = useRef(0);\n const activeLocalRunIdsRef = useRef<Set<string>>(new Set());\n // In-flight runs this client started on the agent by any path (the input,\n // `copilotkit.runAgent`, a frontend-tool follow-up). Kept apart from\n // `activeLocalRunIdsRef`, whose pinned ids span a whole follow-up chain.\n const observedLocalRunIdsRef = useRef<Set<string>>(new Set());\n const recentlyLocalRunIdsRef = useRef<\n Map<string, ReturnType<typeof setTimeout>>\n >(new Map());\n const activeWakeRunIdsRef = useRef<Set<string>>(new Set());\n const recentlyWakeRunIdsRef = useRef<\n Map<string, ReturnType<typeof setTimeout>>\n >(new Map());\n const pendingWakeRunIdRef = useRef<string | undefined>(undefined);\n const startRunActivityReconnectRef = useRef<\n ((generation: number) => void) | null\n >(null);\n const runtimeStatus =\n copilotkit.runtimeConnectionStatus ===\n CopilotKitCoreRuntimeConnectionStatus.Connected\n ? \"Connected\"\n : copilotkit.runtimeConnectionStatus;\n const hasNativeIntelligenceRunActivity =\n hasExplicitThreadId &&\n runtimeStatus === \"Connected\" &&\n !!copilotkit.intelligence?.wsUrl &&\n copilotkit.threadEndpoints?.realtimeMetadata === true;\n const [standaloneRunActivityStore] = useState<ɵThreadStore>(() =>\n ɵcreateThreadStore({\n fetch: copilotkit.ɵruntimeFetch,\n }),\n );\n\n const rememberRecentlyLocalRunId = useCallback((runId: string) => {\n const existingTimeout = recentlyLocalRunIdsRef.current.get(runId);\n if (existingTimeout) {\n clearTimeout(existingTimeout);\n }\n\n const timeout = setTimeout(() => {\n recentlyLocalRunIdsRef.current.delete(runId);\n }, 30_000);\n recentlyLocalRunIdsRef.current.set(runId, timeout);\n }, []);\n\n const rememberRecentlyWakeRunId = useCallback((runId: string) => {\n const existingTimeout = recentlyWakeRunIdsRef.current.get(runId);\n if (existingTimeout) {\n clearTimeout(existingTimeout);\n }\n\n const timeout = setTimeout(() => {\n recentlyWakeRunIdsRef.current.delete(runId);\n }, 30_000);\n recentlyWakeRunIdsRef.current.set(runId, timeout);\n }, []);\n\n const isLocalActiveRunActivity = useCallback(\n (notification: { agentId?: string; runId?: string; eventType: string }) => {\n if (notification.agentId && notification.agentId !== resolvedAgentId) {\n return false;\n }\n if (\n !notification.runId ||\n (!activeLocalRunIdsRef.current.has(notification.runId) &&\n !observedLocalRunIdsRef.current.has(notification.runId) &&\n !recentlyLocalRunIdsRef.current.has(notification.runId))\n ) {\n return false;\n }\n\n const eventType = notification.eventType.toUpperCase();\n return (\n eventType === \"RUN_STARTED\" ||\n eventType === \"RUN_FINISHED\" ||\n eventType === \"RUN_ERROR\"\n );\n },\n [resolvedAgentId],\n );\n\n useEffect(() => {\n const recentlyLocalRunIds = recentlyLocalRunIdsRef.current;\n const recentlyWakeRunIds = recentlyWakeRunIdsRef.current;\n return () => {\n recentlyLocalRunIds.forEach((timeout) => {\n clearTimeout(timeout);\n });\n recentlyLocalRunIds.clear();\n recentlyWakeRunIds.forEach((timeout) => {\n clearTimeout(timeout);\n });\n recentlyWakeRunIds.clear();\n };\n }, []);\n\n useEffect(() => {\n // Pins the thread on the agent and connects a thread the caller picked.\n // A switch to a fresh thread (startNewThread, the drawer's \"+ New\")\n // empties the agent so the welcome screen shows; moving in or out of an\n // Inspector override stops the run. Release aborts a connect still\n // loading, which keeps StrictMode's remount from sending a second\n // /connect.\n const handle = connection.open(\n {\n agent,\n threadId: resolvedThreadId,\n explicit: hasExplicitThreadId,\n inspectorRequestId,\n },\n {\n onStart: () => {\n activeConnectCountRef.current += 1;\n },\n onSettled: (current) => {\n activeConnectCountRef.current = Math.max(\n 0,\n activeConnectCountRef.current - 1,\n );\n if (!current || activeConnectCountRef.current !== 0) return;\n const startReconnect = startRunActivityReconnectRef.current;\n if (pendingRunActivityReconnectRef.current && startReconnect) {\n pendingRunActivityReconnectRef.current = false;\n startReconnect(runActivityReconnectGenerationRef.current);\n }\n },\n },\n );\n return () => handle.release();\n }, [\n connection,\n resolvedThreadId,\n agent,\n resolvedAgentId,\n hasExplicitThreadId,\n inspectorRequestId,\n ]);\n\n useEffect(() => {\n if (!hasNativeIntelligenceRunActivity) return;\n\n const registeredThreadStore = copilotkit.getThreadStore(resolvedAgentId);\n const threadStore = registeredThreadStore ?? standaloneRunActivityStore;\n if (!threadStore?.subscribeToRunActivity) return;\n const ownsStandaloneStore = registeredThreadStore === undefined;\n if (ownsStandaloneStore) {\n threadStore.start();\n const context: ɵThreadRuntimeContext | null = copilotkit.runtimeUrl\n ? {\n runtimeUrl: copilotkit.runtimeUrl,\n wsUrl: copilotkit.intelligence?.wsUrl,\n agentId: resolvedAgentId,\n }\n : null;\n threadStore.setContext(context);\n }\n\n const generation = runActivityReconnectGenerationRef.current + 1;\n runActivityReconnectGenerationRef.current = generation;\n let detached = false;\n let wakeReconnectActive = false;\n let pendingAgentIdleDrain: ReturnType<typeof setTimeout> | null = null;\n const hasActiveAgentRun = () =>\n activeLocalRunIdsRef.current.size > 0 || agent.isRunning;\n const scheduleAgentIdleDrain = () => {\n if (pendingAgentIdleDrain !== null) return;\n pendingAgentIdleDrain = setTimeout(() => {\n pendingAgentIdleDrain = null;\n if (\n detached ||\n runActivityReconnectGenerationRef.current !== generation ||\n !pendingRunActivityReconnectRef.current\n ) {\n return;\n }\n if (hasActiveAgentRun()) {\n scheduleAgentIdleDrain();\n return;\n }\n startRunActivityReconnectRef.current?.(generation);\n }, 10);\n };\n\n const connect = async () => {\n activeConnectCountRef.current += 1;\n wakeReconnectActive = true;\n const wakeRunId = pendingWakeRunIdRef.current;\n pendingWakeRunIdRef.current = undefined;\n if (wakeRunId) {\n activeWakeRunIdsRef.current.add(wakeRunId);\n }\n let didConnect = false;\n try {\n await copilotkit.connectAgent({ agent });\n didConnect = true;\n } catch (error) {\n if (!detached) throw error;\n } finally {\n if (wakeRunId) {\n activeWakeRunIdsRef.current.delete(wakeRunId);\n if (didConnect) {\n rememberRecentlyWakeRunId(wakeRunId);\n }\n }\n activeConnectCountRef.current = Math.max(\n 0,\n activeConnectCountRef.current - 1,\n );\n wakeReconnectActive = false;\n const canDrainPendingReconnect =\n !detached &&\n runActivityReconnectGenerationRef.current === generation &&\n activeConnectCountRef.current === 0;\n\n if (\n canDrainPendingReconnect &&\n pendingRunActivityReconnectRef.current\n ) {\n pendingRunActivityReconnectRef.current = false;\n trackConnection(connect);\n }\n }\n };\n\n startRunActivityReconnectRef.current = (requestedGeneration) => {\n if (\n detached ||\n requestedGeneration !== generation ||\n runActivityReconnectGenerationRef.current !== generation\n ) {\n return;\n }\n if (hasActiveAgentRun()) {\n pendingRunActivityReconnectRef.current = true;\n scheduleAgentIdleDrain();\n return;\n }\n if (activeConnectCountRef.current > 0) {\n if (!wakeReconnectActive) {\n pendingRunActivityReconnectRef.current = true;\n }\n return;\n }\n pendingRunActivityReconnectRef.current = false;\n trackConnection(connect);\n };\n\n const subscription = threadStore.subscribeToRunActivity((notification) => {\n if (notification.threadId !== resolvedThreadId) return;\n if (notification.agentId && notification.agentId !== resolvedAgentId) {\n return;\n }\n if (isLocalActiveRunActivity(notification)) return;\n if (\n notification.runId &&\n (activeWakeRunIdsRef.current.has(notification.runId) ||\n recentlyWakeRunIdsRef.current.has(notification.runId))\n ) {\n return;\n }\n pendingWakeRunIdRef.current = notification.runId;\n startRunActivityReconnectRef.current?.(generation);\n });\n\n const observedLocalRunIds = observedLocalRunIdsRef.current;\n const localRunSubscription = agent.subscribe({\n onRunInitialized: ({ input }) => {\n observedLocalRunIds.add(input.runId);\n },\n onRunFinalized: ({ input }) => {\n observedLocalRunIds.delete(input.runId);\n rememberRecentlyLocalRunId(input.runId);\n },\n });\n\n return () => {\n detached = true;\n pendingRunActivityReconnectRef.current = false;\n pendingWakeRunIdRef.current = undefined;\n if (pendingAgentIdleDrain !== null) {\n clearTimeout(pendingAgentIdleDrain);\n pendingAgentIdleDrain = null;\n }\n if (startRunActivityReconnectRef.current) {\n startRunActivityReconnectRef.current = null;\n }\n if (wakeReconnectActive) {\n agent.detachActiveRun().catch(() => {});\n }\n activeWakeRunIdsRef.current.clear();\n subscription.unsubscribe();\n localRunSubscription.unsubscribe();\n if (ownsStandaloneStore) {\n threadStore.setContext(null);\n threadStore.stop();\n }\n };\n // copilotkit is intentionally excluded — it is a stable ref that never changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n agent,\n resolvedAgentId,\n resolvedThreadId,\n hasExplicitThreadId,\n hasNativeIntelligenceRunActivity,\n copilotkit.runtimeConnectionStatus,\n copilotkit.runtimeUrl,\n copilotkit.ɵheadersGeneration,\n copilotkit.intelligence?.wsUrl,\n copilotkit.threadEndpoints?.realtimeMetadata,\n standaloneRunActivityStore,\n isLocalActiveRunActivity,\n rememberRecentlyLocalRunId,\n rememberRecentlyWakeRunId,\n trackConnection,\n ]);\n\n // Each send gets a fresh Intelligence run id, so the run-activity stream can\n // tell this client's own runs from runs started elsewhere.\n const prepareRun = (): ɵChatRunScope => {\n const localRunId = hasNativeIntelligenceRunActivity\n ? randomUUID()\n : undefined;\n if (localRunId) activeLocalRunIdsRef.current.add(localRunId);\n return {\n runId: localRunId,\n settle: () => {\n if (localRunId) {\n activeLocalRunIdsRef.current.delete(localRunId);\n rememberRecentlyLocalRunId(localRunId);\n }\n const startReconnect = startRunActivityReconnectRef.current;\n const canReconnect =\n pendingRunActivityReconnectRef.current &&\n activeLocalRunIdsRef.current.size === 0 &&\n activeConnectCountRef.current === 0 &&\n startReconnect !== null;\n if (canReconnect) {\n pendingRunActivityReconnectRef.current = false;\n startReconnect(runActivityReconnectGenerationRef.current);\n }\n },\n };\n };\n const prepareRunRef = useRef(prepareRun);\n prepareRunRef.current = prepareRun;\n const agentRef = useRef(agent);\n agentRef.current = agent;\n\n // The send side — queueing behind the run in flight and the thread's\n // connection, the upload guard, stop, and transcription — lives in core.\n const [submitter] = useState(() =>\n ɵcreateChatSubmitter({\n core: copilotkit,\n getAgent: () => agentRef.current,\n input: {\n get: () => inputValueRef.current,\n set: (value) => {\n inputValueRef.current = value;\n setInputValue(value);\n },\n },\n attachments: {\n isUploading: () =>\n selectedAttachmentsRef.current.some((a) => a.status === \"uploading\"),\n consumeReady: consumeAttachments,\n },\n threads,\n prepareRun: () => prepareRunRef.current(),\n }),\n );\n const { notice, isTranscribing } = useSyncExternalStore(\n useCallback((onChange) => submitter.subscribe(onChange), [submitter]),\n () => submitter.getSnapshot(),\n () => submitter.getSnapshot(),\n );\n // Clears the notice timer on unmount. Not `dispose()`: StrictMode remounts\n // the same component instance, which keeps its submitter.\n useEffect(() => () => submitter.showNotice(null), [submitter]);\n\n // The view and DOM props expect void callbacks, so these handlers keep\n // the submitter's and the attachment handlers' promises fire-and-forget.\n const onSubmitInput = useCallback(\n (value: string) => {\n void submitter.submit(value);\n },\n [submitter],\n );\n\n const handleSelectSuggestion = useCallback(\n (suggestion: Suggestion) => {\n void submitter.selectSuggestion(suggestion);\n },\n [submitter],\n );\n\n const dropFiles = useCallback(\n (e: React.DragEvent) => {\n void handleDrop(e);\n },\n [handleDrop],\n );\n const uploadFiles = useCallback(\n (e: React.ChangeEvent<HTMLInputElement>) => {\n void handleFileUpload(e);\n },\n [handleFileUpload],\n );\n\n const stopCurrentRun = useCallback(() => submitter.stop(), [submitter]);\n\n // Transcription handlers\n const handleStartTranscribe = useCallback(() => {\n submitter.showNotice(null);\n setTranscribeMode(\"transcribe\");\n }, [submitter]);\n\n const handleCancelTranscribe = useCallback(() => {\n submitter.showNotice(null);\n setTranscribeMode(\"input\");\n }, [submitter]);\n\n const handleFinishTranscribe = useCallback(() => {\n setTranscribeMode(\"input\");\n }, []);\n\n // Transcribe the audio blob from CopilotChatInput into the input\n const handleFinishTranscribeWithAudio = useCallback(\n (audioBlob: Blob) => submitter.transcribe(audioBlob),\n [submitter],\n );\n\n // Stabilize slot object references so inline props (new object reference on\n // every parent render) don't defeat MemoizedSlotWrapper's shallow equality\n // check and cause unnecessary re-renders of the message list on each keystroke.\n const stableMessageView = useShallowStableRef(\n typeof providedMessageView === \"string\"\n ? { className: providedMessageView }\n : providedMessageView,\n );\n const stableSuggestionView = useShallowStableRef(providedSuggestionView);\n\n // Stabilize the `onAddFile` handler. Without useCallback, a new arrow\n // function is created inline on every render, causing CopilotChatView to\n // re-render on every keystroke even when nothing else changed.\n const handleAddFile = useCallback(() => {\n // Delay to let Radix dropdown menu close before triggering file input\n setTimeout(() => {\n fileInputRef.current?.click();\n }, 100);\n }, []);\n\n // Use shallow spread instead of ts-deepmerge. ts-deepmerge deep-clones plain\n // objects even from a single source, which would defeat the reference\n // stability we just established for stableMessageView and other slot values.\n const mergedProps: Partial<CopilotChatViewProps> = {\n isRunning: agent.isRunning,\n // HIDE suggestion pills until the runtime is ready, mirroring the\n // `onSubmitMessage` gate below. Static `available:\"always\"` pills render\n // during the provisional window (before `/info` swaps the real agent in),\n // so a click before `isReady` would commit `suggestion.message` to the\n // doomed provisional agent and run against it — the same empty-assistant\n // loss the typed-message gate prevents. Withholding `onSelectSuggestion`\n // alone leaves the pill VISUALLY ENABLED but inert (a click silently drops\n // the user's intent), so instead we do not surface the pills at all until\n // the real agent is bound: passing an empty list keeps `hasSuggestions`\n // false in the view (the same mechanism that hides pills while connecting /\n // running). Once `isReady` flips true the real suggestions appear and the\n // handler goes live. The `onSelectSuggestion` gate is retained as\n // defense-in-depth for any custom chatView slot that renders its own pills.\n suggestions: isReady ? autoSuggestions : [],\n onSelectSuggestion: isReady ? handleSelectSuggestion : undefined,\n suggestionView: stableSuggestionView,\n ...restProps,\n };\n if (stableMessageView !== undefined)\n mergedProps.messageView = stableMessageView;\n\n const hasMessages = agent.messages.length > 0;\n const shouldAllowStop = agent.isRunning && hasMessages;\n const effectiveStopHandler = shouldAllowStop\n ? (providedStopHandler ?? stopCurrentRun)\n : providedStopHandler;\n\n // Determine if transcription feature should be available\n const showTranscription = isTranscriptionEnabled && isMediaRecorderSupported;\n\n // Determine mode: transcribing takes priority, then transcribe mode, then default to input\n const effectiveMode: CopilotChatInputMode = isTranscribing\n ? \"processing\"\n : transcribeMode;\n\n // Memoize messages array — only create a new reference when content changes.\n // The fingerprint is cheaper than a deep compare: it keeps base64 uploads out\n // of the key, and still changes for streamed text, streamed tool arguments,\n // added parts, and replaced activity content.\n const messagesMemoKey = ɵmessagesFingerprint(agent.messages);\n const messages = useMemo(\n () => [...agent.messages],\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [messagesMemoKey],\n );\n\n // The latest user message and a send counter, for pin-to-send scrolling.\n // Messages the chat starts with (a restored thread) do not count as a send.\n // `update` keeps the same object until the last user message changes, so\n // calling it during render is safe.\n const [lastUserMessageTracker] = useState(() =>\n ɵcreateLastUserMessageTracker(messages),\n );\n const lastUserMessageState: LastUserMessageState =\n lastUserMessageTracker.update(messages);\n\n const finalProps: CopilotChatViewProps = {\n ...mergedProps,\n messages,\n // Input behavior props\n // Gate submission on runtime readiness. While `isReady` is false the\n // `agent` returned by useAgent is a provisional stand-in that `/info` will\n // swap out; a message committed to it (and the composer cleared) is lost\n // on that swap, surfacing as an empty assistant response. Withholding\n // `onSubmitMessage` disables the send control (canSend keys off it) and\n // makes Enter a no-op that preserves the composer text until the real\n // agent is bound.\n onSubmitMessage: isReady ? onSubmitInput : undefined,\n onStop: effectiveStopHandler,\n inputMode: effectiveMode,\n inputValue,\n onInputChange: setInputValue,\n // Only provide transcription handlers if feature is available\n onStartTranscribe: showTranscription ? handleStartTranscribe : undefined,\n onCancelTranscribe: showTranscription ? handleCancelTranscribe : undefined,\n onFinishTranscribe: showTranscription ? handleFinishTranscribe : undefined,\n onFinishTranscribeWithAudio: showTranscription\n ? handleFinishTranscribeWithAudio\n : undefined,\n // Attachment props\n attachments: selectedAttachments,\n onRemoveAttachment: removeAttachment,\n onAddFile: attachmentsEnabled ? handleAddFile : undefined,\n dragOver,\n onDragOver: handleDragOver,\n onDragLeave: handleDragLeave,\n onDrop: dropFiles,\n isConnecting,\n hasExplicitThreadId,\n };\n\n // Always create a provider with merged values\n // This ensures priority: props > existing config > defaults\n const RenderedChatView = renderSlot(chatView, CopilotChatView, finalProps);\n\n return (\n <CopilotChatConfigurationProvider\n agentId={resolvedAgentId}\n threadId={resolvedThreadId}\n hasExplicitThreadId={hasExplicitThreadId}\n labels={labels}\n isModalDefaultOpen={isModalDefaultOpen}\n >\n <div ref={chatContainerRef} style={{ display: \"contents\" }}>\n <CopilotKitStyles />\n {attachmentsEnabled && (\n <input\n type=\"file\"\n multiple\n ref={fileInputRef}\n onChange={uploadFiles}\n accept={attachmentsConfig?.accept ?? \"*/*\"}\n style={{ display: \"none\" }}\n />\n )}\n {!isChatLicensed && <InlineFeatureWarning featureName=\"Chat\" />}\n {notice && (\n <div\n style={{\n position: \"absolute\",\n bottom: \"100px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n backgroundColor: \"#ef4444\",\n color: \"white\",\n padding: \"8px 16px\",\n borderRadius: \"8px\",\n fontSize: \"14px\",\n zIndex: 50,\n }}\n >\n {ɵresolveChatNotice(notice, {\n ...CopilotChatDefaultLabels,\n ...existingConfig?.labels,\n ...labels,\n })}\n </div>\n )}\n <LastUserMessageContext.Provider value={lastUserMessageState}>\n <CopilotKitInspectorContextProvider value={inspectorContextValue}>\n <GenerativeUIChatSlotContext.Provider value={generativeUISurface}>\n {RenderedChatView}\n </GenerativeUIChatSlotContext.Provider>\n </CopilotKitInspectorContextProvider>\n </LastUserMessageContext.Provider>\n </div>\n </CopilotChatConfigurationProvider>\n );\n}\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace CopilotChat {\n export const View = CopilotChatView;\n}\n","import type { MouseEvent } from \"react\";\nimport React, { useState } from \"react\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\n\nimport type { SlotValue } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport { cn } from \"../../lib/utils\";\nimport { CopilotChatDefaultLabels } from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\nconst ICON_CLASS = \"cpk-chat-toggle-button-icon\";\n\n// The button passes ICON_CLASS through `className`; standalone use falls back\n// to it so the icon keeps its size.\nconst DefaultOpenIcon: React.FC<React.SVGProps<SVGSVGElement>> = ({\n className,\n ...props\n}) => (\n <CopilotIcon\n className={className ?? ICON_CLASS}\n strokeWidth={1.75}\n fill=\"currentColor\"\n {...props}\n name=\"MessageCircle\"\n />\n);\n\nconst DefaultCloseIcon: React.FC<React.SVGProps<SVGSVGElement>> = ({\n className,\n ...props\n}) => (\n <CopilotIcon\n className={className ?? ICON_CLASS}\n strokeWidth={1.75}\n {...props}\n name=\"X\"\n />\n);\n\nDefaultOpenIcon.displayName = \"CopilotChatToggleButton.OpenIcon\";\nDefaultCloseIcon.displayName = \"CopilotChatToggleButton.CloseIcon\";\n\nexport interface CopilotChatToggleButtonProps extends Omit<\n React.ButtonHTMLAttributes<HTMLButtonElement>,\n \"children\"\n> {\n /** Optional slot override for the chat (closed) icon. */\n openIcon?: SlotValue<typeof DefaultOpenIcon>;\n /** Optional slot override for the close icon. */\n closeIcon?: SlotValue<typeof DefaultCloseIcon>;\n}\n\nconst ICON_TRANSITION_STYLE: React.CSSProperties = Object.freeze({\n transition:\n \"opacity 120ms ease-out, transform 260ms cubic-bezier(0.22, 1, 0.36, 1)\",\n});\n\nconst ICON_WRAPPER_CLASS = \"cpk-chat-toggle-button-icon-wrapper\";\n\nexport const CopilotChatToggleButton = React.forwardRef<\n HTMLButtonElement,\n CopilotChatToggleButtonProps\n>(function CopilotChatToggleButton(\n { openIcon, closeIcon, className, ...buttonProps },\n ref,\n) {\n const { onClick, type, disabled, ...restProps } = buttonProps;\n\n const configuration = useCopilotChatConfiguration();\n const labels = configuration?.labels ?? CopilotChatDefaultLabels;\n\n const [fallbackOpen, setFallbackOpen] = useState(false);\n\n const isOpen = configuration?.isModalOpen ?? fallbackOpen;\n const setModalOpen = configuration?.setModalOpen ?? setFallbackOpen;\n\n const handleClick = (event: MouseEvent<HTMLButtonElement>) => {\n if (disabled) {\n return;\n }\n\n if (onClick) {\n onClick(event);\n }\n\n if (event.defaultPrevented) {\n return;\n }\n\n const nextOpen = !isOpen;\n setModalOpen(nextOpen);\n };\n\n const renderedOpenIcon = renderSlot(openIcon, DefaultOpenIcon, {\n className: ICON_CLASS,\n \"aria-hidden\": true,\n focusable: false,\n });\n\n const renderedCloseIcon = renderSlot(closeIcon, DefaultCloseIcon, {\n className: ICON_CLASS,\n \"aria-hidden\": true,\n focusable: false,\n });\n\n const openIconElement = (\n <span\n aria-hidden=\"true\"\n data-slot=\"chat-toggle-button-open-icon\"\n className={ICON_WRAPPER_CLASS}\n style={{\n ...ICON_TRANSITION_STYLE,\n opacity: isOpen ? 0 : 1,\n transform: `scale(${isOpen ? 0.75 : 1}) rotate(${isOpen ? 90 : 0}deg)`,\n }}\n >\n {renderedOpenIcon}\n </span>\n );\n\n const closeIconElement = (\n <span\n aria-hidden=\"true\"\n data-slot=\"chat-toggle-button-close-icon\"\n className={ICON_WRAPPER_CLASS}\n style={{\n ...ICON_TRANSITION_STYLE,\n opacity: isOpen ? 1 : 0,\n transform: `scale(${isOpen ? 1 : 0.75}) rotate(${isOpen ? 0 : -90}deg)`,\n }}\n >\n {renderedCloseIcon}\n </span>\n );\n\n return (\n <button\n ref={ref}\n type={type ?? \"button\"}\n data-copilotkit\n data-testid=\"copilot-chat-toggle\"\n data-slot=\"chat-toggle-button\"\n data-state={isOpen ? \"open\" : \"closed\"}\n className={cn(\"copilotKitButton cpk-chat-toggle-button\", className)}\n aria-label={\n isOpen ? labels.chatToggleCloseLabel : labels.chatToggleOpenLabel\n }\n aria-pressed={isOpen}\n disabled={disabled}\n onClick={handleClick}\n {...restProps}\n >\n {openIconElement}\n {closeIconElement}\n </button>\n );\n});\nCopilotChatToggleButton.displayName = \"CopilotChatToggleButton\";\nexport default CopilotChatToggleButton;\n\nexport {\n DefaultOpenIcon as CopilotChatToggleButtonOpenIcon,\n DefaultCloseIcon as CopilotChatToggleButtonCloseIcon,\n};\n","import React, { createContext, useContext, useMemo } from \"react\";\n\n/**\n * The host-supplied controlled open state for a prebuilt modal surface\n * (`<CopilotSidebar>`, `<CopilotPopup>`).\n */\nexport interface ModalOpenControl {\n /** Controlled open state. `undefined` leaves the surface uncontrolled. */\n open?: boolean;\n /** Called with the requested state when the surface asks to open or close. */\n onOpenChange?: (open: boolean) => void;\n}\n\nconst ModalOpenControlContext = createContext<ModalOpenControl>({});\n\nexport interface ModalOpenControlProviderProps extends ModalOpenControl {\n children: React.ReactNode;\n}\n\n/**\n * Carries `open` / `onOpenChange` from a prebuilt surface down to the view that\n * owns the modal state.\n *\n * A context is required rather than plain props because `<CopilotSidebar>`\n * hands its view to `<CopilotChat>` as a `chatView` **component**. Threading a\n * value that changes (like `open`) through that component's identity would mint\n * a new element type on every toggle, and React unmounts and remounts the whole\n * chat subtree when the element type changes. That is the remount class of bug\n * already fixed for `<CopilotPopup>` on resize. Context keeps the override\n * identity stable while still re-rendering the view when `open` changes.\n */\nexport function ModalOpenControlProvider({\n open,\n onOpenChange,\n children,\n}: ModalOpenControlProviderProps) {\n const value = useMemo<ModalOpenControl>(\n () => ({ open, onOpenChange }),\n [open, onOpenChange],\n );\n\n return (\n <ModalOpenControlContext.Provider value={value}>\n {children}\n </ModalOpenControlContext.Provider>\n );\n}\n\n/**\n * Reads the controlled open state supplied by the surrounding prebuilt\n * surface. Returns an empty control (uncontrolled) when there is none.\n *\n * @returns The host's `open` / `onOpenChange` pair.\n */\nexport function useModalOpenControl(): ModalOpenControl {\n return useContext(ModalOpenControlContext);\n}\n","import React, { useCallback, useEffect, useState } from \"react\";\n\nimport { cn } from \"../../lib/utils\";\nimport {\n CopilotChatDefaultLabels,\n ɵwatchMobileViewport,\n} from \"@copilotkit/core\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\nimport type { WithSlots } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport { CopilotIcon } from \"../icons/CopilotIcon\";\n\ntype HeaderSlots = {\n titleContent: typeof CopilotModalHeader.Title;\n closeButton: typeof CopilotModalHeader.CloseButton;\n drawerLauncher: typeof CopilotModalHeader.DrawerLauncher;\n};\n\ntype HeaderRestProps = {\n title?: string;\n} & Omit<React.HTMLAttributes<HTMLDivElement>, \"children\">;\n\n/**\n * Payload handed to the optional `children` render function. `drawerLauncher`\n * is nullable because the launcher is rendered only when a drawer has\n * registered — when none is present, custom layouts receive `null` and can omit\n * the launcher slot entirely.\n */\ntype HeaderChildrenPayload = {\n titleContent: React.ReactElement;\n closeButton: React.ReactElement;\n drawerLauncher: React.ReactElement | null;\n title?: string;\n} & Omit<HeaderRestProps, \"title\">;\n\nexport type CopilotModalHeaderProps = Omit<\n WithSlots<HeaderSlots, HeaderRestProps>,\n \"children\"\n> & {\n children?: (props: HeaderChildrenPayload) => React.ReactNode;\n};\n\n/**\n * Reactively tracks whether the viewport is in the mobile range (≤767px) — the\n * same breakpoint the drawer + chat coordination use. SSR-safe: starts `false`\n * (desktop) so the server render and first client render agree, then syncs on\n * mount and on resize.\n */\nfunction useIsMobileViewport() {\n const [isMobile, setIsMobile] = useState(false);\n useEffect(() => ɵwatchMobileViewport(setIsMobile), []);\n return isMobile;\n}\n\nexport function CopilotModalHeader({\n title,\n titleContent,\n closeButton,\n drawerLauncher,\n children,\n className,\n ...rest\n}: CopilotModalHeaderProps) {\n const configuration = useCopilotChatConfiguration();\n\n const fallbackTitle =\n configuration?.labels.modalHeaderTitle ??\n CopilotChatDefaultLabels.modalHeaderTitle;\n const resolvedTitle = title ?? fallbackTitle;\n\n // The thread-list launcher renders ONLY when a <CopilotThreadsDrawer> wrapper has\n // registered with the chat configuration AND the viewport is mobile. On\n // desktop the drawer is an in-flow, persistent panel (it ignores `open`), so\n // an \"open the drawer\" launcher there is a dead no-op — it only does anything\n // for the mobile off-canvas drawer. Chats with no drawer get no launcher and\n // no behavior change.\n const isMobile = useIsMobileViewport();\n const drawerRegistered =\n (configuration?.drawerRegistered ?? false) && isMobile;\n\n const handleClose = useCallback(() => {\n configuration?.setModalOpen?.(false);\n }, [configuration]);\n\n const handleToggleDrawer = useCallback(() => {\n configuration?.setDrawerOpen?.(!configuration.drawerOpen);\n }, [configuration]);\n\n const BoundTitle = renderSlot(titleContent, CopilotModalHeader.Title, {\n children: resolvedTitle,\n });\n\n const BoundCloseButton = renderSlot(\n closeButton,\n CopilotModalHeader.CloseButton,\n {\n onClick: handleClose,\n },\n );\n\n // Only bind the launcher slot when a drawer is registered. When no drawer is\n // present, `BoundDrawerLauncher` is null and nothing is rendered.\n const BoundDrawerLauncher = drawerRegistered\n ? renderSlot(drawerLauncher, CopilotModalHeader.DrawerLauncher, {\n onClick: handleToggleDrawer,\n \"aria-expanded\": configuration?.drawerOpen ?? false,\n })\n : null;\n\n if (children) {\n return children({\n titleContent: BoundTitle,\n closeButton: BoundCloseButton,\n drawerLauncher: BoundDrawerLauncher,\n title: resolvedTitle,\n ...rest,\n });\n }\n\n return (\n <header\n data-testid=\"copilot-modal-header\"\n data-slot=\"copilot-modal-header\"\n className={cn(\"copilotKitHeader cpk-modal-header\", className)}\n {...rest}\n >\n <div className=\"cpk-modal-header-content\">\n <div className=\"cpk-modal-header-start\">\n {BoundDrawerLauncher ?? <span aria-hidden=\"true\" />}\n </div>\n <div className=\"cpk-modal-header-center\">{BoundTitle}</div>\n <div className=\"cpk-modal-header-end\">{BoundCloseButton}</div>\n </div>\n </header>\n );\n}\n\nCopilotModalHeader.displayName = \"CopilotModalHeader\";\n\nexport namespace CopilotModalHeader {\n export const Title: React.FC<React.HTMLAttributes<HTMLDivElement>> = ({\n children,\n className,\n ...props\n }) => (\n <div\n data-testid=\"copilot-header-title\"\n className={cn(\"cpk-modal-header-title\", className)}\n {...props}\n >\n {children}\n </div>\n );\n\n /**\n * Closes the popup or sidebar. Its accessible name is\n * `labels.modalHeaderCloseButtonLabel`.\n */\n export const CloseButton: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ className, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <button\n type=\"button\"\n data-testid=\"copilot-close-button\"\n className={cn(\"cpk-modal-header-close-button\", className)}\n aria-label={labels.modalHeaderCloseButtonLabel}\n {...props}\n >\n <CopilotIcon\n name=\"X\"\n className=\"cpk-modal-header-close-icon\"\n aria-hidden=\"true\"\n />\n </button>\n );\n };\n\n /**\n * The thread-list launcher button. Rendered in the header ONLY when a\n * `<CopilotThreadsDrawer>` wrapper has registered with the chat configuration; it\n * toggles the drawer open state. The stable `data-testid` is the focus-return\n * target for the drawer wrapper on cancel/back/backdrop/Escape.\n */\n export const DrawerLauncher: React.FC<\n React.ButtonHTMLAttributes<HTMLButtonElement>\n > = ({ className, ...props }) => {\n const config = useCopilotChatConfiguration();\n const labels = config?.labels ?? CopilotChatDefaultLabels;\n return (\n <button\n type=\"button\"\n data-testid=\"copilot-threads-drawer-launcher\"\n className={cn(\"cpk-modal-header-drawer-launcher\", className)}\n aria-label={labels.modalHeaderThreadsButtonLabel}\n {...props}\n >\n <CopilotIcon\n name=\"PanelLeftOpen\"\n className=\"cpk-modal-header-drawer-launcher-icon\"\n aria-hidden=\"true\"\n />\n </button>\n );\n };\n}\n\nCopilotModalHeader.Title.displayName = \"CopilotModalHeader.Title\";\nCopilotModalHeader.CloseButton.displayName = \"CopilotModalHeader.CloseButton\";\nCopilotModalHeader.DrawerLauncher.displayName =\n \"CopilotModalHeader.DrawerLauncher\";\n\nexport default CopilotModalHeader;\n","import React, { useEffect, useLayoutEffect, useRef, useState } from \"react\";\n\nimport type {\n CopilotChatViewProps,\n WelcomeScreenProps,\n} from \"./CopilotChatView\";\nimport CopilotChatView from \"./CopilotChatView\";\nimport {\n CopilotChatDefaultLabels,\n ɵSIDEBAR_DEFAULT_WIDTH,\n ɵSIDEBAR_TRANSITION_MS,\n ɵcreateDockedSidebar,\n ɵdimensionToCss,\n ɵwatchElementWidth,\n} from \"@copilotkit/core\";\nimport type { ɵDockedSidebar } from \"@copilotkit/core\";\nimport {\n ControlledModalOpenScope,\n CopilotChatConfigurationProvider,\n useCopilotChatConfiguration,\n} from \"../../providers/CopilotChatConfigurationProvider\";\nimport { useModalOpenControl } from \"./modal-open-control\";\nimport CopilotChatToggleButton from \"./CopilotChatToggleButton\";\nimport { cn } from \"../../lib/utils\";\nimport { CopilotModalHeader } from \"./CopilotModalHeader\";\nimport type { CopilotModalHeaderProps } from \"./CopilotModalHeader\";\nimport type { SlotValue } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\n\nexport type CopilotSidebarViewProps = CopilotChatViewProps & {\n /** Accepts a className, partial props, or any component with CopilotModalHeader props — static namespace members are not required. */\n header?: SlotValue<React.ComponentType<CopilotModalHeaderProps>>;\n toggleButton?: SlotValue<typeof CopilotChatToggleButton>;\n width?: number | string;\n defaultOpen?: boolean;\n position?: \"left\" | \"right\";\n};\n\n/**\n * The chat in a side panel: a `complementary` region named by\n * `labels.sidebarLabel`, with a header, the chat view and a toggle button.\n */\nexport function CopilotSidebarView({\n header,\n toggleButton,\n width,\n defaultOpen = true,\n position = \"right\",\n ...props\n}: CopilotSidebarViewProps) {\n // Controlled open state supplied by `<CopilotSidebar open onOpenChange>`.\n const { open, onOpenChange } = useModalOpenControl();\n // The scope is needed for either half: `open` pins the state, and\n // `onOpenChange` reports requests even while the sidebar manages itself.\n const hasOpenControl = open !== undefined || onOpenChange !== undefined;\n\n const internal = (\n <CopilotSidebarViewInternal\n header={header}\n toggleButton={toggleButton}\n width={width}\n position={position}\n {...props}\n />\n );\n\n return (\n // Seed the underlying uncontrolled state from `open` so it starts aligned\n // with the host. The scope below is what the surface actually renders, so\n // this only matters if the host later drops `open` and hands control back:\n // the sidebar then stays where it was instead of jumping to `defaultOpen`.\n <CopilotChatConfigurationProvider isModalDefaultOpen={open ?? defaultOpen}>\n {hasOpenControl ? (\n <ControlledModalOpenScope open={open} onOpenChange={onOpenChange}>\n {internal}\n </ControlledModalOpenScope>\n ) : (\n internal\n )}\n </CopilotChatConfigurationProvider>\n );\n}\n\nfunction CopilotSidebarViewInternal({\n header,\n toggleButton,\n width,\n position = \"right\",\n ...props\n}: Omit<CopilotSidebarViewProps, \"defaultOpen\">) {\n const configuration = useCopilotChatConfiguration();\n\n const isSidebarOpen = configuration?.isModalOpen ?? false;\n\n const sidebarRef = useRef<HTMLDivElement | null>(null);\n const [measuredWidth, setMeasuredWidth] = useState<number | string>(\n width ?? ɵSIDEBAR_DEFAULT_WIDTH,\n );\n // The `width` prop wins over the measured width, also when it changes\n // after mount.\n const sidebarWidth = width ?? measuredWidth;\n\n useEffect(() => {\n // If width is explicitly provided, don't measure\n if (width !== undefined) {\n return;\n }\n const element = sidebarRef.current;\n if (!element) {\n return;\n }\n return ɵwatchElementWidth(element, setMeasuredWidth);\n }, [width]);\n\n const widthCss = ɵdimensionToCss(sidebarWidth, ɵSIDEBAR_DEFAULT_WIDTH);\n\n // The page makes room on the docked edge (desktop only). Layout effects run\n // before paint, so defaultOpen={true} never shows a layout shift: the\n // margin is already there on the first frame.\n const dockRef = useRef<ɵDockedSidebar | null>(null);\n useLayoutEffect(() => {\n const dock = ɵcreateDockedSidebar(document, {\n transitionMs: ɵSIDEBAR_TRANSITION_MS,\n });\n dockRef.current = dock;\n return () => {\n dock.dispose();\n dockRef.current = null;\n };\n }, []);\n\n useLayoutEffect(() => {\n dockRef.current?.set({\n open: isSidebarOpen,\n position,\n width: widthCss,\n });\n }, [isSidebarOpen, position, widthCss]);\n\n const headerElement = renderSlot(header, CopilotModalHeader, {});\n const toggleButtonElement = renderSlot(\n toggleButton,\n CopilotChatToggleButton,\n position === \"left\"\n ? { className: \"cpk-sidebar-view-toggle-button-left\" }\n : {},\n );\n\n return (\n <>\n {toggleButtonElement}\n <aside\n ref={sidebarRef}\n data-copilotkit\n data-testid=\"copilot-sidebar\"\n data-copilot-sidebar\n data-position={position}\n className={cn(\n \"copilotKitSidebar copilotKitWindow cpk-sidebar-view\",\n // Slides off its edge (data-position) when closed.\n !isSidebarOpen && \"cpk-sidebar-view-closed\",\n )}\n style={\n {\n // Use CSS custom property for responsive width\n \"--sidebar-width\": widthCss,\n // Safe area insets for iOS\n paddingTop: \"env(safe-area-inset-top)\",\n paddingBottom: \"env(safe-area-inset-bottom)\",\n } as React.CSSProperties\n }\n aria-hidden={!isSidebarOpen}\n aria-label={\n configuration?.labels.sidebarLabel ??\n CopilotChatDefaultLabels.sidebarLabel\n }\n role=\"complementary\"\n >\n <div className=\"cpk-sidebar-view-panel\">\n {headerElement}\n <div className=\"cpk-sidebar-view-chat\" data-sidebar-chat>\n <CopilotChatView {...props} />\n </div>\n </div>\n </aside>\n </>\n );\n}\n\nCopilotSidebarView.displayName = \"CopilotSidebarView\";\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace CopilotSidebarView {\n /**\n * Sidebar-specific welcome screen layout:\n * - Suggestions at the top\n * - Welcome message in the middle\n * - Input fixed at the bottom (like normal chat)\n */\n export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({\n welcomeMessage,\n input,\n suggestionView,\n className,\n children,\n ...props\n }) => {\n // Render the welcomeMessage slot internally\n const BoundWelcomeMessage = renderSlot(\n welcomeMessage,\n CopilotChatView.WelcomeMessage,\n {},\n );\n\n if (children) {\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children({\n welcomeMessage: BoundWelcomeMessage,\n input,\n suggestionView,\n className,\n ...props,\n })}\n </div>\n );\n }\n\n return (\n <div\n className={cn(\"cpk-sidebar-view-welcome-screen\", className)}\n {...props}\n >\n {/* Welcome message - centered vertically */}\n <div className=\"cpk-sidebar-view-welcome-screen-message\">\n {BoundWelcomeMessage}\n </div>\n\n {/* Suggestions and input at bottom */}\n <div className=\"cpk-sidebar-view-welcome-screen-footer\">\n <div className=\"cpk-sidebar-view-welcome-screen-content\">\n {/* Suggestions above input */}\n <div className=\"cpk-sidebar-view-welcome-screen-suggestions\">\n {suggestionView}\n </div>\n {input}\n </div>\n </div>\n </div>\n );\n };\n}\n\nexport default CopilotSidebarView;\n","import React, {\n useEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from \"react\";\nimport type {\n CopilotChatViewProps,\n WelcomeScreenProps,\n} from \"./CopilotChatView\";\nimport CopilotChatView from \"./CopilotChatView\";\nimport CopilotChatToggleButton from \"./CopilotChatToggleButton\";\nimport { CopilotModalHeader } from \"./CopilotModalHeader\";\nimport type { CopilotModalHeaderProps } from \"./CopilotModalHeader\";\nimport { cn } from \"../../lib/utils\";\nimport type { SlotValue } from \"../../lib/slots\";\nimport { renderSlot } from \"../../lib/slots\";\nimport {\n CopilotChatDefaultLabels,\n ɵPOPUP_DEFAULT_HEIGHT,\n ɵPOPUP_DEFAULT_WIDTH,\n ɵbindPopupDismiss,\n ɵcreateExitPresence,\n ɵdimensionToCss,\n} from \"@copilotkit/core\";\nimport {\n ControlledModalOpenScope,\n CopilotChatConfigurationProvider,\n useCopilotChatConfiguration,\n} from \"../../providers/CopilotChatConfigurationProvider\";\nimport { useModalOpenControl } from \"./modal-open-control\";\n\nexport type CopilotPopupViewProps = CopilotChatViewProps & {\n /** Accepts a className, partial props, or any component with CopilotModalHeader props — static namespace members are not required. */\n header?: SlotValue<React.ComponentType<CopilotModalHeaderProps>>;\n toggleButton?: SlotValue<typeof CopilotChatToggleButton>;\n width?: number | string;\n height?: number | string;\n clickOutsideToClose?: boolean;\n defaultOpen?: boolean;\n};\n\nexport function CopilotPopupView({\n header,\n toggleButton,\n width,\n height,\n clickOutsideToClose,\n defaultOpen = true,\n className,\n ...restProps\n}: CopilotPopupViewProps) {\n // Controlled open state supplied by `<CopilotPopup open onOpenChange>`.\n const { open, onOpenChange } = useModalOpenControl();\n // The scope is needed for either half: `open` pins the state, and\n // `onOpenChange` reports requests even while the popup manages itself.\n const hasOpenControl = open !== undefined || onOpenChange !== undefined;\n\n const internal = (\n <CopilotPopupViewInternal\n header={header}\n toggleButton={toggleButton}\n width={width}\n height={height}\n clickOutsideToClose={clickOutsideToClose}\n className={className}\n {...restProps}\n />\n );\n\n return (\n // Seed the underlying uncontrolled state from `open` so it starts aligned\n // with the host. The scope below is what the surface actually renders, so\n // this only matters if the host later drops `open` and hands control back:\n // the popup then stays where it was instead of jumping to `defaultOpen`.\n <CopilotChatConfigurationProvider isModalDefaultOpen={open ?? defaultOpen}>\n {hasOpenControl ? (\n <ControlledModalOpenScope open={open} onOpenChange={onOpenChange}>\n {internal}\n </ControlledModalOpenScope>\n ) : (\n internal\n )}\n </CopilotChatConfigurationProvider>\n );\n}\n\nfunction CopilotPopupViewInternal({\n header,\n toggleButton,\n width,\n height,\n clickOutsideToClose,\n className,\n ...restProps\n}: Omit<CopilotPopupViewProps, \"defaultOpen\">) {\n const configuration = useCopilotChatConfiguration();\n const isPopupOpen = configuration?.isModalOpen ?? false;\n const setModalOpen = configuration?.setModalOpen;\n const labels = configuration?.labels ?? CopilotChatDefaultLabels;\n\n const containerRef = useRef<HTMLDivElement>(null);\n // Core keeps the closed popup rendered while its exit animation plays.\n const [presence] = useState(() => ɵcreateExitPresence(isPopupOpen));\n const { isRendered, isClosing: isAnimatingOut } = useSyncExternalStore(\n presence.subscribe,\n presence.getState,\n presence.getState,\n );\n useEffect(() => {\n presence.setOpen(isPopupOpen);\n }, [presence, isPopupOpen]);\n useEffect(() => () => presence.dispose(), [presence]);\n\n // Escape, a click outside (when enabled), and focus once the popup opens.\n useEffect(() => {\n if (!isPopupOpen) {\n return;\n }\n return ɵbindPopupDismiss({\n getContainer: () => containerRef.current,\n onDismiss: () => setModalOpen?.(false),\n clickOutsideToClose: clickOutsideToClose === true,\n });\n }, [isPopupOpen, clickOutsideToClose, setModalOpen]);\n\n const headerElement = useMemo(\n () => renderSlot(header, CopilotModalHeader, {}),\n [header],\n );\n const toggleButtonElement = useMemo(\n () => renderSlot(toggleButton, CopilotChatToggleButton, {}),\n [toggleButton],\n );\n\n const resolvedWidth = ɵdimensionToCss(width, ɵPOPUP_DEFAULT_WIDTH);\n const resolvedHeight = ɵdimensionToCss(height, ɵPOPUP_DEFAULT_HEIGHT);\n\n const popupStyle = useMemo(\n () =>\n ({\n \"--copilot-popup-width\": resolvedWidth,\n \"--copilot-popup-height\": resolvedHeight,\n \"--copilot-popup-max-width\": \"calc(100vw - 3rem)\",\n \"--copilot-popup-max-height\": \"calc(100dvh - 7.5rem)\",\n paddingTop: \"env(safe-area-inset-top)\",\n paddingBottom: \"env(safe-area-inset-bottom)\",\n paddingLeft: \"env(safe-area-inset-left)\",\n paddingRight: \"env(safe-area-inset-right)\",\n }) as React.CSSProperties,\n [resolvedHeight, resolvedWidth],\n );\n\n const popupContent = isRendered ? (\n <div data-copilotkit className=\"cpk-popup-view\">\n <div\n ref={containerRef}\n tabIndex={-1}\n role=\"dialog\"\n aria-label={labels.modalHeaderTitle}\n data-testid=\"copilot-popup\"\n data-copilot-popup\n className={cn(\n \"copilotKitPopup copilotKitWindow cpk-popup-view-window\",\n isPopupOpen && !isAnimatingOut && \"cpk-popup-view-window-open\",\n )}\n style={popupStyle}\n >\n {headerElement}\n <div className=\"cpk-popup-view-chat\" data-popup-chat>\n <CopilotChatView\n {...restProps}\n className={cn(\"cpk-popup-view-chat-view\", className)}\n />\n </div>\n </div>\n </div>\n ) : null;\n\n return (\n <>\n {toggleButtonElement}\n {popupContent}\n </>\n );\n}\n\nCopilotPopupView.displayName = \"CopilotPopupView\";\n\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace CopilotPopupView {\n /**\n * Popup-specific welcome screen layout:\n * - Welcome message centered vertically\n * - Suggestions just above input\n * - Input fixed at the bottom\n */\n export const WelcomeScreen: React.FC<WelcomeScreenProps> = ({\n welcomeMessage,\n input,\n suggestionView,\n className,\n children,\n ...props\n }) => {\n // Render the welcomeMessage slot internally\n const BoundWelcomeMessage = renderSlot(\n welcomeMessage,\n CopilotChatView.WelcomeMessage,\n {},\n );\n\n if (children) {\n return (\n <div data-copilotkit style={{ display: \"contents\" }}>\n {children({\n welcomeMessage: BoundWelcomeMessage,\n input,\n suggestionView,\n className,\n ...props,\n })}\n </div>\n );\n }\n\n return (\n <div\n className={cn(\"cpk-popup-view-welcome-screen\", className)}\n {...props}\n >\n {/* Welcome message - centered vertically */}\n <div className=\"cpk-popup-view-welcome-screen-message\">\n {BoundWelcomeMessage}\n </div>\n\n {/* Suggestions and input at bottom */}\n <div>\n {/* Suggestions above input */}\n <div className=\"cpk-popup-view-welcome-screen-suggestions\">\n {suggestionView}\n </div>\n {input}\n </div>\n </div>\n );\n };\n}\n\nexport default CopilotPopupView;\n","import React, { useEffect, useMemo } from \"react\";\nimport { useLicenseContext } from \"../../providers/CopilotKitProvider\";\nimport { InlineFeatureWarning } from \"../license-warning-banner\";\n\nimport type { CopilotChatProps } from \"./CopilotChat\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatViewProps } from \"./CopilotChatView\";\nimport CopilotChatView from \"./CopilotChatView\";\nimport type { CopilotSidebarViewProps } from \"./CopilotSidebarView\";\nimport { CopilotSidebarView } from \"./CopilotSidebarView\";\nimport { ModalOpenControlProvider } from \"./modal-open-control\";\n\nexport type CopilotSidebarProps = Omit<CopilotChatProps, \"chatView\"> & {\n header?: CopilotSidebarViewProps[\"header\"];\n toggleButton?: CopilotSidebarViewProps[\"toggleButton\"];\n defaultOpen?: boolean;\n /**\n * Controlled open state. When supplied, the host owns whether the sidebar is\n * open: the sidebar renders this value and never changes it on its own.\n * Pair it with `onOpenChange` to react to the toggle button. Omit it (and use\n * `defaultOpen`) to let the sidebar manage its own state.\n */\n open?: boolean;\n /**\n * Called with the requested state whenever the sidebar asks to open or close\n * (the toggle button, or the thread drawer on mobile). In controlled mode\n * nothing moves until the host updates `open`.\n */\n onOpenChange?: (open: boolean) => void;\n width?: number | string;\n position?: CopilotSidebarViewProps[\"position\"];\n};\n\nexport function CopilotSidebar({\n header,\n toggleButton,\n defaultOpen,\n open,\n onOpenChange,\n width,\n position,\n ...chatProps\n}: CopilotSidebarProps) {\n const { checkFeature } = useLicenseContext();\n const isSidebarLicensed = checkFeature(\"sidebar\");\n\n useEffect(() => {\n if (!isSidebarLicensed) {\n console.warn(\n '[CopilotKit] Warning: \"sidebar\" feature is not licensed. Visit copilotkit.ai/pricing',\n );\n }\n }, [isSidebarLicensed]);\n\n const SidebarViewOverride = useMemo(() => {\n const Component: React.FC<CopilotChatViewProps> = (viewProps) => {\n const {\n header: viewHeader,\n toggleButton: viewToggleButton,\n width: viewWidth,\n defaultOpen: viewDefaultOpen,\n position: viewPosition,\n ...restProps\n } = viewProps as CopilotSidebarViewProps;\n\n return (\n <CopilotSidebarView\n {...(restProps as CopilotSidebarViewProps)}\n header={header ?? viewHeader}\n toggleButton={toggleButton ?? viewToggleButton}\n width={width ?? viewWidth}\n defaultOpen={defaultOpen ?? viewDefaultOpen}\n position={position ?? viewPosition}\n />\n );\n };\n\n return Object.assign(Component, CopilotChatView);\n }, [header, toggleButton, width, defaultOpen, position]);\n\n return (\n <>\n {!isSidebarLicensed && <InlineFeatureWarning featureName=\"Sidebar\" />}\n {/*\n `open` / `onOpenChange` travel by context, not through\n SidebarViewOverride. The override is memoized on its own props, so a\n changing `open` would mint a new component identity on every toggle and\n remount the whole chat subtree.\n */}\n <ModalOpenControlProvider open={open} onOpenChange={onOpenChange}>\n <CopilotChat\n welcomeScreen={CopilotSidebarView.WelcomeScreen}\n {...chatProps}\n isModalDefaultOpen={defaultOpen}\n chatView={SidebarViewOverride}\n />\n </ModalOpenControlProvider>\n </>\n );\n}\n\nCopilotSidebar.displayName = \"CopilotSidebar\";\n\nexport default CopilotSidebar;\n","import React, { useContext, useEffect, useMemo } from \"react\";\nimport { useLicenseContext } from \"../../providers/CopilotKitProvider\";\nimport { InlineFeatureWarning } from \"../license-warning-banner\";\n\nimport type { CopilotChatProps } from \"./CopilotChat\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatViewProps } from \"./CopilotChatView\";\nimport CopilotChatView from \"./CopilotChatView\";\nimport type { CopilotPopupViewProps } from \"./CopilotPopupView\";\nimport CopilotPopupView from \"./CopilotPopupView\";\nimport { ModalOpenControlProvider } from \"./modal-open-control\";\n\n/**\n * Carries the popup shell props (header, toggle, width, height, …) to the\n * chatView override without baking them into the override's component\n * identity. Width/height change on every resize; if they were `useMemo`\n * dependencies of the override component, each change would mint a new\n * component function, and rendering a new element *type* makes React unmount\n * and remount the entire chat subtree — resetting scrollTop to 0 and firing\n * `initial=\"smooth\"`, which visibly scrolls the message list from top to\n * bottom on every resize. Routing them through context keeps the override\n * identity stable (no remount) while still re-rendering CopilotPopupView with\n * the new dimensions on change.\n */\ntype PopupShellProps = {\n header?: CopilotPopupViewProps[\"header\"];\n toggleButton?: CopilotPopupViewProps[\"toggleButton\"];\n width?: CopilotPopupViewProps[\"width\"];\n height?: CopilotPopupViewProps[\"height\"];\n clickOutsideToClose?: CopilotPopupViewProps[\"clickOutsideToClose\"];\n defaultOpen?: boolean;\n};\n\nconst PopupShellPropsContext = React.createContext<PopupShellProps>({});\n\n// Stable override component. Its identity never changes, so the chat subtree\n// is never remounted on resize. Popup props flow in via context, so changing\n// width/height re-renders CopilotPopupView (a style update) instead.\nconst PopupViewOverride: React.FC<CopilotChatViewProps> = (viewProps) => {\n const {\n header: viewHeader,\n toggleButton: viewToggleButton,\n width: viewWidth,\n height: viewHeight,\n clickOutsideToClose: viewClickOutsideToClose,\n defaultOpen: viewDefaultOpen,\n ...restProps\n } = viewProps as CopilotPopupViewProps;\n\n const shell = useContext(PopupShellPropsContext);\n\n return (\n <CopilotPopupView\n {...(restProps as CopilotPopupViewProps)}\n header={shell.header ?? viewHeader}\n toggleButton={shell.toggleButton ?? viewToggleButton}\n width={shell.width ?? viewWidth}\n height={shell.height ?? viewHeight}\n clickOutsideToClose={shell.clickOutsideToClose ?? viewClickOutsideToClose}\n defaultOpen={shell.defaultOpen ?? viewDefaultOpen}\n />\n );\n};\n\n// Preserve the static slot members (WelcomeScreen, etc.) that callers reach\n// through the CopilotChatView namespace. The cast restores those statics on\n// the type after Object.assign, matching the shape CopilotChat's `chatView`\n// slot expects (typeof CopilotChatView).\nconst PopupViewOverrideWithStatics = Object.assign(\n PopupViewOverride,\n CopilotChatView,\n) as typeof CopilotChatView;\n\nexport type CopilotPopupProps = Omit<CopilotChatProps, \"chatView\"> & {\n header?: CopilotPopupViewProps[\"header\"];\n toggleButton?: CopilotPopupViewProps[\"toggleButton\"];\n defaultOpen?: boolean;\n /**\n * Controlled open state. When supplied, the host owns whether the popup is\n * open: the popup renders this value and never changes it on its own. Pair it\n * with `onOpenChange` to react to the toggle button and to click-outside.\n * Omit it (and use `defaultOpen`) to let the popup manage its own state.\n */\n open?: boolean;\n /**\n * Called with the requested state whenever the popup asks to open or close\n * (the toggle button, click-outside, or the thread drawer on mobile). In\n * controlled mode nothing moves until the host updates `open`.\n */\n onOpenChange?: (open: boolean) => void;\n width?: CopilotPopupViewProps[\"width\"];\n height?: CopilotPopupViewProps[\"height\"];\n clickOutsideToClose?: CopilotPopupViewProps[\"clickOutsideToClose\"];\n};\n\nexport function CopilotPopup({\n header,\n toggleButton,\n defaultOpen,\n open,\n onOpenChange,\n width,\n height,\n clickOutsideToClose,\n ...chatProps\n}: CopilotPopupProps) {\n const { checkFeature } = useLicenseContext();\n const isPopupLicensed = checkFeature(\"popup\");\n\n useEffect(() => {\n if (!isPopupLicensed) {\n console.warn(\n '[CopilotKit] Warning: \"popup\" feature is not licensed. Visit copilotkit.ai/pricing',\n );\n }\n }, [isPopupLicensed]);\n\n const shellProps = useMemo<PopupShellProps>(\n () => ({\n header,\n toggleButton,\n width,\n height,\n clickOutsideToClose,\n defaultOpen,\n }),\n [clickOutsideToClose, header, toggleButton, height, width, defaultOpen],\n );\n\n return (\n <>\n {!isPopupLicensed && <InlineFeatureWarning featureName=\"Popup\" />}\n <PopupShellPropsContext.Provider value={shellProps}>\n <ModalOpenControlProvider open={open} onOpenChange={onOpenChange}>\n <CopilotChat\n welcomeScreen={CopilotPopupView.WelcomeScreen}\n {...chatProps}\n isModalDefaultOpen={defaultOpen}\n chatView={PopupViewOverrideWithStatics}\n />\n </ModalOpenControlProvider>\n </PopupShellPropsContext.Provider>\n </>\n );\n}\n\nCopilotPopup.displayName = \"CopilotPopup\";\n\nexport default CopilotPopup;\n","\"use client\";\n\nimport React, {\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport {\n defineCopilotKitThreadsDrawer,\n COPILOTKIT_THREADS_DRAWER_TAG,\n} from \"@copilotkit/web-components/threads-drawer\";\nimport type {\n CopilotKitThreadsDrawer as CopilotKitThreadsDrawerElement,\n ThreadSelectedDetail,\n ArchiveDetail,\n UnarchiveDetail,\n DeleteDetail,\n OpenChangeDetail,\n RetryDetail,\n} from \"@copilotkit/web-components/threads-drawer\";\n// TODO(ENT-1051): import `CollapseChangeDetail` from\n// \"@copilotkit/web-components/threads-drawer\" once the parallel element PR that\n// adds the collapse feature (property `collapsible` + event `collapse-change`)\n// lands and is published; declared locally here because the built element types\n// in this worktree predate it.\ntype CollapseChangeDetail = { collapsed: boolean };\nimport {\n ɵcreateThreadsDrawerActions,\n ɵgetThreadsDrawerElementProps,\n ɵresolveAgentId,\n ɵresolveThreadsLicense,\n ɵtoDrawerThread,\n} from \"@copilotkit/core\";\nimport { useThreads } from \"../../hooks/use-threads\";\nimport type { Thread } from \"../../hooks/use-threads\";\nimport { useLicenseContext } from \"../../providers/CopilotKitProvider\";\nimport { CopilotKitContext, useDefaultAgentId } from \"../../context\";\nimport { useCopilotChatConfiguration } from \"../../providers/CopilotChatConfigurationProvider\";\n\n/**\n * Per-row content render function. Receives a thread and returns the React\n * node to project into the element's `slot=\"row:{id}\"`. Returning `null`\n * (or omitting the prop) falls back to the element's built-in row name.\n */\nexport type CopilotThreadsDrawerRowRenderer = (\n thread: Thread,\n) => React.ReactNode;\n\n/**\n * Props for {@link CopilotThreadsDrawer}.\n *\n * The drawer is a thin controller around the framework-agnostic\n * `<copilotkit-threads-drawer>` custom element. It feeds the element domain data\n * (threads/loading/error from {@link useThreads}, the active thread from the\n * chat configuration) and routes the element's outbound DOM events back into\n * core thread operations and chat-configuration changes.\n */\nexport interface CopilotThreadsDrawerProps {\n /**\n * The agent whose threads to list and manage. Defaults to the agent of the\n * surrounding chat configuration, or the platform default when none is set.\n */\n agentId?: string;\n /**\n * Optional escape-hatch called when the user picks a thread row. The wrapper\n * additionally focuses the chat input. When omitted, the wrapper drives the\n * surrounding chat configuration directly (`setActiveThreadId`), so a bare\n * `<CopilotThreadsDrawer>` switches the rendered thread with no host wiring. Provide\n * this only to take control of the active thread yourself (e.g. a v1\n * `setThreadId`); when provided it is preferred over the provider.\n */\n onThreadSelect?: (threadId: string) => void;\n /**\n * Optional escape-hatch called when the user starts a new thread (the\n * element's \"+ New\" button). The wrapper always resets the core thread store\n * to a fresh, non-explicit client-side thread (`startNewThread`). When this\n * is omitted, the wrapper also resets the surrounding chat configuration to a\n * fresh non-explicit thread (`startNewThread`) so the welcome screen shows\n * with no host wiring. Provide this only to clear your own active thread;\n * when provided it is preferred over the provider.\n */\n onNewThread?: () => void;\n /** Called when the Upgrade CTA is clicked. */\n onLicensed?: () => void;\n /**\n * Destination the locked view's Upgrade CTA opens in a new tab. Defaults to\n * the element's built-in CopilotKit Intelligence docs URL when omitted. Set\n * to an empty string to suppress the default navigation and handle the click\n * yourself via `onLicensed`.\n */\n licenseUrl?: string;\n /**\n * Optional per-row content. Rendered as light-DOM children with\n * `slot=\"row:{id}\"` so the element projects them in place of the default\n * row name. Return `null` for a given row to keep the element's default.\n */\n renderRow?: CopilotThreadsDrawerRowRenderer;\n /**\n * Accessible + default-header label for the drawer region. Sets the custom\n * element's `aria-label` and the default header text (shown when no\n * `slot=\"header\"` content is projected). Defaults to the element's built-in\n * `\"Threads\"` when omitted.\n */\n label?: string;\n /**\n * Heading for the \"Recent Conversations\" section above the thread list. Sets\n * the custom element's `recent-label` attribute. Defaults to the element's\n * built-in `\"Recent Conversations\"` when omitted.\n */\n recentLabel?: string;\n /**\n * Whether the drawer offers a collapse toggle. Sets the custom element's\n * `collapsible` PROPERTY. When `false`, the drawer has no collapse toggle and\n * is always expanded. Defaults to the element's built-in `true` when omitted.\n */\n collapsible?: boolean;\n /**\n * Called when the drawer's collapsed state changes (via the element's collapse\n * toggle), with the new collapsed state. Mirrors the element's\n * `collapse-change` event.\n */\n onCollapseChange?: (collapsed: boolean) => void;\n /**\n * Page size for thread pagination. When set, threads are fetched in pages of\n * this size and the drawer shows a \"Load more\" control while more remain.\n * When omitted, the full list loads at once and no pagination control shows.\n */\n limit?: number;\n /**\n * `data-testid` set on the underlying custom element (handy in tests and for\n * targeting from a host page). Defaults to `\"copilot-threads-drawer\"`.\n */\n \"data-testid\"?: string;\n}\n\n/**\n * React wrapper for the shadow-DOM `<copilotkit-threads-drawer>` threads drawer.\n *\n * Responsibilities:\n * - Registers the custom element on the client (SSR-safe; nothing renders\n * during prerender to avoid hydration mismatch).\n * - Feeds the element domain data: `threads`, `loading`, `error`,\n * `activeThreadId`, `licensed`, fetch-more state.\n * - Routes the element's outbound events to core thread operations\n * ({@link useThreads}) and chat-configuration changes.\n * - Registers with the surrounding chat configuration so the header\n * thread-list launcher appears, and binds the element `open` state to the\n * configuration's `drawerOpen`.\n *\n * Intelligence gating is two-pronged: the locked view shows when the runtime\n * reports no active entitlement OR the `threads` feature is unavailable. While\n * unavailable, the thread fetch is skipped entirely so the drawer issues no\n * network requests.\n *\n * Thread switching needs no host wiring: when `onThreadSelect`/`onNewThread`\n * are omitted, the wrapper drives the surrounding chat configuration directly\n * ({@link CopilotChatConfigurationValue.setActiveThreadId} /\n * {@link CopilotChatConfigurationValue.startNewThread}), so a bare drawer\n * connects to the picked thread and shows the welcome screen on \"+ New\". Pass\n * the callbacks only to take control yourself.\n *\n * @example\n * ```tsx\n * // Callback-free: the drawer drives the chat configuration itself.\n * <CopilotKitProvider runtimeUrl=\"/api/copilotkit\">\n * <CopilotChat />\n * <CopilotThreadsDrawer />\n * </CopilotKitProvider>\n * ```\n */\nexport function CopilotThreadsDrawer({\n agentId,\n onThreadSelect,\n onNewThread,\n onLicensed,\n licenseUrl,\n renderRow,\n label,\n recentLabel,\n collapsible,\n onCollapseChange,\n limit,\n \"data-testid\": dataTestId = \"copilot-threads-drawer\",\n}: CopilotThreadsDrawerProps): React.ReactElement | null {\n const configuration = useCopilotChatConfiguration();\n // `unknown` (an entitlement lookup that did not recover) is not a settled\n // negative, so core treats it as licensed and lets the threads endpoint\n // decide; `null` (not reported yet) is pending, never the locked view.\n // A runtime that connects without reporting a license (no Intelligence)\n // ends the pending. `useThreads` below re-renders this component on every\n // connection change, so this read stays current.\n const copilotkit = useContext(CopilotKitContext)?.copilotkit;\n const { licensed, licensePending } = ɵresolveThreadsLicense(\n useLicenseContext(),\n copilotkit?.ɵruntimeInfo,\n );\n\n const providerAgentId = useDefaultAgentId();\n const resolvedAgentId = ɵresolveAgentId({\n agentId,\n chatAgentId: configuration?.agentId,\n providerAgentId,\n });\n const activeThreadId = configuration?.threadId ?? null;\n\n // While unlicensed, skip the thread fetch entirely: the element shows only\n // its locked view and no `/threads` request is issued.\n const {\n threads,\n isLoading,\n listError,\n fetchMoreError,\n hasMoreThreads,\n isFetchingMoreThreads,\n archiveThread,\n unarchiveThread,\n deleteThread,\n fetchMoreThreads,\n refetchThreads,\n startNewThread,\n } = useThreads({\n agentId: resolvedAgentId,\n includeArchived: true,\n enabled: licensed,\n ...(limit !== undefined ? { limit } : {}),\n });\n\n const drawerThreads = useMemo(() => threads.map(ɵtoDrawerThread), [threads]);\n\n const elementRef = useRef<CopilotKitThreadsDrawerElement | null>(null);\n\n // Register the custom element on the client only. `customElements` is absent\n // during SSR/prerender; gating the render below on `mounted` keeps the server\n // output empty so there is no hydration mismatch or layout shift.\n const [mounted, setMounted] = useState(false);\n useEffect(() => {\n defineCopilotKitThreadsDrawer();\n setMounted(true);\n }, []);\n\n // Announce presence to the surrounding chat configuration so the header\n // launcher renders; de-register on unmount. Depend on the stable\n // `registerDrawer` callback, NOT the whole `configuration` object — the\n // object's identity changes on every drawer/modal/label update, which would\n // otherwise churn register/de-register each render and momentarily drop\n // `drawerRegistered` (flickering the header launcher).\n const registerDrawer = configuration?.registerDrawer;\n useEffect(() => {\n if (!registerDrawer) return;\n return registerDrawer();\n }, [registerDrawer]);\n\n // Drive the chat configuration's drawerOpen from the element's open-change\n // event, and reflect drawerOpen back onto the element below.\n //\n // Provider-less fallback: without a surrounding chat configuration there is no\n // shared open-state to bind to, so the wrapper keeps its own local open-state.\n // It starts CLOSED — matching the provider's own `ownDrawerOpen` default of\n // `false` — so a bare `<CopilotThreadsDrawer>` does not render stuck-open and the\n // element's open-change events still toggle it.\n const [localDrawerOpen, setLocalDrawerOpen] = useState(false);\n const drawerOpen = configuration ? configuration.drawerOpen : localDrawerOpen;\n const setDrawerOpen = configuration\n ? configuration.setDrawerOpen\n : setLocalDrawerOpen;\n\n // --- Event handlers (stable via refs to the latest closures) -------------\n // The element is imperatively wired with addEventListener once; we keep the\n // latest handler implementations in a ref so listeners need not be re-bound\n // every render (which would churn on each thread/loading change).\n\n // Prefer the host callbacks when provided; otherwise drive the surrounding\n // chat configuration directly so a bare `<CopilotThreadsDrawer>` works callback-free.\n // Core owns the drawer actions. They read the latest values through refs,\n // so they are created once.\n const latestRef = useRef({\n threads: {\n startNewThread,\n archiveThread,\n unarchiveThread,\n deleteThread,\n fetchMoreThreads,\n refetchThreads,\n },\n configuration,\n callbacks: { onThreadSelect, onNewThread },\n });\n latestRef.current = {\n threads: {\n startNewThread,\n archiveThread,\n unarchiveThread,\n deleteThread,\n fetchMoreThreads,\n refetchThreads,\n },\n configuration,\n callbacks: { onThreadSelect, onNewThread },\n };\n const [actions] = useState(() =>\n ɵcreateThreadsDrawerActions({\n getThreads: () => latestRef.current.threads,\n getConfig: () => latestRef.current.configuration,\n getCallbacks: () => latestRef.current.callbacks,\n getElement: () => elementRef.current,\n }),\n );\n const handleThreadSelected = actions.selectThread;\n const handleNewThread = actions.newThread;\n const handleArchive = actions.archive;\n const handleUnarchive = actions.unarchive;\n const handleDelete = actions.remove;\n const handleFilterChange = actions.refetch;\n const handleRetry = actions.retry;\n\n const handleOpenChange = useCallback(\n (open: boolean) => {\n setDrawerOpen(open);\n },\n [setDrawerOpen],\n );\n\n const handleLicensed = useCallback(() => {\n onLicensed?.();\n }, [onLicensed]);\n\n const handleLoadMore = actions.loadMore;\n\n const handleCollapseChange = useCallback(\n (collapsed: boolean) => {\n onCollapseChange?.(collapsed);\n },\n [onCollapseChange],\n );\n\n // Keep a ref to the live handlers so the addEventListener effect can stay\n // stable (bind once) while still calling the freshest closures.\n const handlersRef = useRef({\n handleThreadSelected,\n handleNewThread,\n handleArchive,\n handleUnarchive,\n handleDelete,\n handleFilterChange,\n handleRetry,\n handleOpenChange,\n handleLicensed,\n handleLoadMore,\n handleCollapseChange,\n });\n handlersRef.current = {\n handleThreadSelected,\n handleNewThread,\n handleArchive,\n handleUnarchive,\n handleDelete,\n handleFilterChange,\n handleRetry,\n handleOpenChange,\n handleLicensed,\n handleLoadMore,\n handleCollapseChange,\n };\n\n // Bind the outbound DOM events once the element exists. Listeners are\n // bound a single time and cleaned up on unmount; they dispatch through the\n // handlers ref so they always invoke the latest closures.\n useEffect(() => {\n const el = elementRef.current;\n if (!el) return;\n\n const onThreadSelected = (event: Event) => {\n const detail = (event as CustomEvent<ThreadSelectedDetail>).detail;\n handlersRef.current.handleThreadSelected(detail.threadId);\n };\n const onNewThreadEvent = () => handlersRef.current.handleNewThread();\n const onArchive = (event: Event) => {\n const detail = (event as CustomEvent<ArchiveDetail>).detail;\n handlersRef.current.handleArchive(detail.threadId);\n };\n const onUnarchive = (event: Event) => {\n const detail = (event as CustomEvent<UnarchiveDetail>).detail;\n handlersRef.current.handleUnarchive(detail.threadId);\n };\n const onDelete = (event: Event) => {\n const detail = (event as CustomEvent<DeleteDetail>).detail;\n handlersRef.current.handleDelete(detail.threadId);\n };\n const onFilterChange = (_event: Event) => {\n handlersRef.current.handleFilterChange();\n };\n const onOpenChangeEvent = (event: Event) => {\n const detail = (event as CustomEvent<OpenChangeDetail>).detail;\n handlersRef.current.handleOpenChange(detail.open);\n };\n const onRetry = (event: Event) => {\n const detail = (event as CustomEvent<RetryDetail>).detail;\n handlersRef.current.handleRetry(detail.scope);\n };\n const onLicensedEvent = () => handlersRef.current.handleLicensed();\n const onLoadMore = () => handlersRef.current.handleLoadMore();\n const onCollapseChangeEvent = (event: Event) => {\n const detail = (event as CustomEvent<CollapseChangeDetail>).detail;\n handlersRef.current.handleCollapseChange(detail.collapsed);\n };\n\n el.addEventListener(\"thread-selected\", onThreadSelected);\n el.addEventListener(\"new-thread\", onNewThreadEvent);\n el.addEventListener(\"archive\", onArchive);\n el.addEventListener(\"unarchive\", onUnarchive);\n el.addEventListener(\"delete\", onDelete);\n el.addEventListener(\"filter-change\", onFilterChange);\n el.addEventListener(\"open-change\", onOpenChangeEvent);\n el.addEventListener(\"retry\", onRetry);\n el.addEventListener(\"licensed\", onLicensedEvent);\n el.addEventListener(\"load-more\", onLoadMore);\n el.addEventListener(\"collapse-change\", onCollapseChangeEvent);\n\n return () => {\n el.removeEventListener(\"thread-selected\", onThreadSelected);\n el.removeEventListener(\"new-thread\", onNewThreadEvent);\n el.removeEventListener(\"archive\", onArchive);\n el.removeEventListener(\"unarchive\", onUnarchive);\n el.removeEventListener(\"delete\", onDelete);\n el.removeEventListener(\"filter-change\", onFilterChange);\n el.removeEventListener(\"open-change\", onOpenChangeEvent);\n el.removeEventListener(\"retry\", onRetry);\n el.removeEventListener(\"licensed\", onLicensedEvent);\n el.removeEventListener(\"load-more\", onLoadMore);\n el.removeEventListener(\"collapse-change\", onCollapseChangeEvent);\n };\n // Re-bind only after the first client mount (deps: [mounted]); the element\n // ref is stable thereafter.\n }, [mounted]);\n\n // Assign object/array/boolean PROPERTIES imperatively. React would otherwise\n // set these as string attributes, which a custom element cannot accept for\n // arrays/objects. Setting them as instance properties is the correct interop.\n useEffect(() => {\n const el = elementRef.current;\n if (!el) return;\n el.threads = drawerThreads;\n }, [drawerThreads, mounted]);\n\n useEffect(() => {\n const el = elementRef.current;\n if (!el) return;\n // While the license is still resolving, the element shows its loading\n // state and stays \"licensed\", so the locked view never flashes.\n const elementProps = ɵgetThreadsDrawerElementProps({\n loading: isLoading,\n licensed,\n licensePending,\n });\n el.loading = elementProps.loading;\n // Only genuine list-load/mutation errors reach the end user. Developer/\n // config errors (missing runtime URL, runtime without thread endpoints) are\n // excluded via `listError` so they never leak into the drawer's error UI.\n el.error = listError ? listError.message : null;\n el.activeThreadId = activeThreadId;\n el.licensed = elementProps.licensed;\n el.hasMore = hasMoreThreads;\n el.fetchingMore = isFetchingMoreThreads;\n // Dedicated fetch-more error channel: drives the element's inline\n // \"couldn't load more — retry\" panel without disturbing the loaded list or\n // the initial-list `error`. The `retry{scope:\"fetch-more\"}` handler\n // becomes reachable once this panel renders.\n el.fetchMoreError = fetchMoreError ? fetchMoreError.message : null;\n }, [\n isLoading,\n listError,\n fetchMoreError,\n activeThreadId,\n licensed,\n licensePending,\n hasMoreThreads,\n isFetchingMoreThreads,\n mounted,\n ]);\n\n // Bind the element's controlled `open` to the chat configuration's\n // drawerOpen, so the header launcher and the element stay in sync.\n useEffect(() => {\n const el = elementRef.current;\n if (!el) return;\n el.open = drawerOpen;\n }, [drawerOpen, mounted]);\n\n // Mirror the optional `label` onto the element (its accessible + default\n // header text). Leave the element's built-in default (\"Threads\") in place\n // when the prop is omitted, rather than clobbering it with undefined.\n useEffect(() => {\n const el = elementRef.current;\n if (!el) return;\n if (label !== undefined) el.label = label;\n }, [label, mounted]);\n\n // Mirror the optional `licenseUrl` onto the element (the locked view's\n // Upgrade CTA destination). Leave the element's built-in default in place\n // when the prop is omitted, rather than clobbering it with undefined.\n useEffect(() => {\n const el = elementRef.current;\n if (!el) return;\n if (licenseUrl !== undefined) el.licenseUrl = licenseUrl;\n }, [licenseUrl, mounted]);\n\n // Mirror the optional `collapsible` onto the element as a PROPERTY (a\n // default-true boolean, exactly like `licensed` — a string attribute cannot\n // represent it since any non-empty value is truthy). Leave the element's\n // built-in default (`true`) in place when the prop is omitted, rather than\n // clobbering it with undefined.\n useEffect(() => {\n const el = elementRef.current;\n if (!el) return;\n if (collapsible !== undefined) {\n // TODO(ENT-1051): drop the intersection cast once the published element\n // type declares `collapsible` (see the local CollapseChangeDetail note).\n (\n el as CopilotKitThreadsDrawerElement & { collapsible: boolean }\n ).collapsible = collapsible;\n }\n }, [collapsible, mounted]);\n\n // Per-row light-DOM children projected via `slot=\"row:{id}\"`.\n const rowChildren = useMemo(() => {\n if (!renderRow) return null;\n return drawerThreads.map((drawerThread) => {\n const fullThread = threads.find((t) => t.id === drawerThread.id);\n if (!fullThread) return null;\n const content = renderRow(fullThread);\n if (content === null || content === undefined) return null;\n return (\n <div key={drawerThread.id} slot={`row:${drawerThread.id}`}>\n {content}\n </div>\n );\n });\n }, [renderRow, drawerThreads, threads]);\n\n // SSR / pre-mount: render nothing so the server output matches the initial\n // client render (the element is not yet registered), avoiding hydration\n // mismatch and layout shift.\n if (!mounted) return null;\n\n return React.createElement(\n COPILOTKIT_THREADS_DRAWER_TAG,\n {\n ref: elementRef,\n \"data-testid\": dataTestId,\n // Pass the section heading label as an attribute; omit it entirely when\n // unset so the element keeps its built-in default rather than receiving\n // an `undefined` that would clobber it.\n ...(recentLabel !== undefined ? { \"recent-label\": recentLabel } : {}),\n },\n rowChildren,\n );\n}\n\nCopilotThreadsDrawer.displayName = \"CopilotThreadsDrawer\";\n\nexport default CopilotThreadsDrawer;\n","import { defineToolCallRenderer } from \"../types/defineToolCallRenderer\";\nimport {\n DefaultToolCallRenderer,\n adaptRendererProps,\n} from \"../hooks/use-default-render-tool\";\n\n/**\n * Catch-all (`\"*\"`) tool-call renderer that shows CopilotKit's default\n * tool-call card for any tool without a dedicated renderer.\n */\nexport const WildcardToolCallRender = defineToolCallRenderer({\n name: \"*\",\n group: true,\n render: (props) => <DefaultToolCallRenderer {...adaptRendererProps(props)} />,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAM,iBAAiB;CACrB,SAAS;CACT,aAAa;CACb,SAAS;CACT,WAAW;CACX,OAAO;CACP,MAAM;CACN,+BAA+B;CAC/B,yBAAyB;CACzB,2BAA2B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