@copilotkit/react-native 2.0.0-rc.24 → 2.0.0-rc.26
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/components/index.cjs +3 -3
- package/dist/components/index.cjs.map +1 -1
- package/dist/components/index.mjs +3 -3
- package/dist/components/index.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
- package/src/CopilotSidebar.tsx +3 -4
- package/src/components/CopilotModal.tsx +1 -1
- package/src/components/messages/AssistantMessage.tsx +0 -1
- package/src/components/messages/TypingIndicator.tsx +4 -4
|
@@ -22,9 +22,9 @@ const ANIMATION_DURATION = 400;
|
|
|
22
22
|
* Uses React Native's built-in `Animated` API (no Reanimated dependency).
|
|
23
23
|
*/
|
|
24
24
|
function TypingIndicator({ style }) {
|
|
25
|
-
const dot1 = (0, react.
|
|
26
|
-
const dot2 = (0, react.
|
|
27
|
-
const dot3 = (0, react.
|
|
25
|
+
const [dot1] = (0, react.useState)(() => new react_native.Animated.Value(0));
|
|
26
|
+
const [dot2] = (0, react.useState)(() => new react_native.Animated.Value(0));
|
|
27
|
+
const [dot3] = (0, react.useState)(() => new react_native.Animated.Value(0));
|
|
28
28
|
(0, react.useEffect)(() => {
|
|
29
29
|
const createPulse = (dot, delay) => react_native.Animated.sequence([react_native.Animated.delay(delay), react_native.Animated.loop(react_native.Animated.sequence([react_native.Animated.timing(dot, {
|
|
30
30
|
toValue: 1,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["Animated","styles","View","StyleSheet","TIMESTAMP_COLOR","useMarkdownRenderer","View","styles","isNativeComponentRenderer","React","CopilotMarkdown","Text","StyleSheet","View","styles","Text","StyleSheet","FlatList","View","styles","Text","Pressable","TextInput","TouchableOpacity","KeyboardAvoidingView","Platform","StyleSheet","BottomSheetBackdrop","BottomSheet","BottomSheetView","BottomSheetFlatList","StyleSheet"],"sources":["../../src/components/messages/TypingIndicator.tsx","../../src/components/messages/utils.ts","../../src/components/messages/AssistantMessage.tsx","../../src/components/messages/UserMessage.tsx","../../src/components/CopilotChat.tsx","../../src/components/CopilotModal.tsx"],"sourcesContent":["import React, { useEffect, useRef } from \"react\";\nimport { View, Animated, StyleSheet } from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\n\n/**\n * Props for the TypingIndicator component.\n */\nexport interface TypingIndicatorProps {\n /** Optional style override for the container */\n style?: ViewStyle;\n}\n\nconst DOT_SIZE = 6;\nconst DOT_SPACING = 4;\nconst ANIMATION_DURATION = 400;\n\n/**\n * Three animated dots that pulse in sequence, suitable for embedding\n * inside an AssistantMessage to indicate the AI is still generating.\n *\n * Uses React Native's built-in `Animated` API (no Reanimated dependency).\n */\nexport function TypingIndicator({ style }: TypingIndicatorProps) {\n const dot1 = useRef(new Animated.Value(0)).current;\n const dot2 = useRef(new Animated.Value(0)).current;\n const dot3 = useRef(new Animated.Value(0)).current;\n\n useEffect(() => {\n const createPulse = (dot: Animated.Value, delay: number) =>\n Animated.sequence([\n Animated.delay(delay),\n Animated.loop(\n Animated.sequence([\n Animated.timing(dot, {\n toValue: 1,\n duration: ANIMATION_DURATION,\n useNativeDriver: true,\n }),\n Animated.timing(dot, {\n toValue: 0,\n duration: ANIMATION_DURATION,\n useNativeDriver: true,\n }),\n ]),\n ),\n ]);\n\n const animation = Animated.parallel([\n createPulse(dot1, 0),\n createPulse(dot2, ANIMATION_DURATION * 0.33),\n createPulse(dot3, ANIMATION_DURATION * 0.66),\n ]);\n\n animation.start();\n\n return () => {\n animation.stop();\n };\n }, [dot1, dot2, dot3]);\n\n const dotStyle = (animatedValue: Animated.Value) => ({\n ...styles.dot,\n opacity: animatedValue.interpolate({\n inputRange: [0, 1],\n outputRange: [0.3, 1],\n }),\n transform: [\n {\n scale: animatedValue.interpolate({\n inputRange: [0, 1],\n outputRange: [0.8, 1.2],\n }),\n },\n ],\n });\n\n return (\n <View\n testID=\"copilot-loading-cursor\"\n style={[styles.container, style]}\n accessibilityLabel=\"Typing indicator\"\n accessibilityRole=\"text\"\n >\n <Animated.View style={dotStyle(dot1)} />\n <Animated.View style={dotStyle(dot2)} />\n <Animated.View style={dotStyle(dot3)} />\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flexDirection: \"row\",\n alignItems: \"center\",\n paddingVertical: 4,\n paddingHorizontal: 2,\n },\n dot: {\n width: DOT_SIZE,\n height: DOT_SIZE,\n borderRadius: DOT_SIZE / 2,\n backgroundColor: \"#999999\",\n marginHorizontal: DOT_SPACING / 2,\n },\n});\n","/**\n * Format a Date as a 12-hour time string (e.g. \"2:05 PM\").\n */\nexport function formatTimestamp(date: Date): string {\n const hours = date.getHours();\n const minutes = date.getMinutes();\n const ampm = hours >= 12 ? \"PM\" : \"AM\";\n const displayHours = hours % 12 || 12;\n const displayMinutes = minutes.toString().padStart(2, \"0\");\n return `${displayHours}:${displayMinutes} ${ampm}`;\n}\n","import React from \"react\";\nimport { View, Text, StyleSheet } from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotMarkdown } from \"../Markdown\";\nimport {\n useMarkdownRenderer,\n isNativeComponentRenderer,\n} from \"../MarkdownRendererContext\";\nimport { TypingIndicator } from \"./TypingIndicator\";\nimport { formatTimestamp } from \"./utils\";\n\n// ─── Colors ──────────────────────────────────────────────────────────────────\nconst ASSISTANT_BUBBLE_BG = \"#F0F0F0\";\nconst ASSISTANT_TEXT_COLOR = \"#1A1A1A\";\nconst TIMESTAMP_COLOR = \"#999999\";\n\n/**\n * Props for the AssistantMessage component.\n */\nexport interface AssistantMessageProps {\n /** Markdown content to render inside the bubble */\n content: string;\n /** When true, shows a typing indicator below any content */\n isLoading?: boolean;\n /** Optional timestamp displayed below the bubble */\n timestamp?: Date;\n /** Optional style override for the outer container */\n style?: ViewStyle;\n}\n\n/**\n * Left-aligned chat bubble for AI assistant responses.\n *\n * Renders markdown content via `CopilotMarkdown` and shows an animated\n * typing indicator when `isLoading` is true.\n */\nexport function AssistantMessage({\n content,\n isLoading = false,\n timestamp,\n style,\n}: AssistantMessageProps) {\n // Honor a provider-level markdown renderer (CopilotKitProvider's\n // `markdownRenderer` prop), falling back to the built-in CopilotMarkdown.\n // This is the React Native arm of the slot -> provider -> built-in\n // resolution order documented in the migration guide.\n const provided = useMarkdownRenderer();\n return (\n <View style={[styles.container, style]}>\n <View style={styles.bubble}>\n {content ? (\n isNativeComponentRenderer(provided) ? (\n React.createElement(provided, { content, isStreaming: isLoading })\n ) : provided ? (\n <CopilotMarkdown\n content={content}\n style={provided.style}\n streamingAnimation={provided.animate}\n />\n ) : (\n <CopilotMarkdown content={content} />\n )\n ) : null}\n {isLoading ? <TypingIndicator /> : null}\n </View>\n {timestamp && (\n <Text style={styles.timestamp}>{formatTimestamp(timestamp)}</Text>\n )}\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n alignItems: \"flex-start\",\n marginVertical: 4,\n paddingHorizontal: 12,\n },\n bubble: {\n backgroundColor: ASSISTANT_BUBBLE_BG,\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n borderBottomRightRadius: 16,\n borderBottomLeftRadius: 4,\n paddingHorizontal: 12,\n paddingVertical: 8,\n maxWidth: \"80%\",\n },\n timestamp: {\n color: TIMESTAMP_COLOR,\n fontSize: 11,\n marginTop: 2,\n marginLeft: 4,\n },\n});\n","import React from \"react\";\nimport { View, Text, StyleSheet, type ViewStyle } from \"react-native\";\nimport { formatTimestamp } from \"./utils\";\n\n// ─── Colors ──────────────────────────────────────────────────────────────────\nconst USER_BUBBLE_BG = \"#0066CC\";\nconst USER_TEXT_COLOR = \"#FFFFFF\";\nconst TIMESTAMP_COLOR = \"#999999\";\n\n/**\n * Props for the UserMessage component.\n */\nexport interface UserMessageProps {\n /** Plain text content to display */\n content: string;\n /** Optional timestamp displayed below the bubble */\n timestamp?: Date;\n /** Optional style override for the outer container */\n style?: ViewStyle;\n}\n\n/**\n * Right-aligned chat bubble for user messages.\n *\n * Renders plain text (no markdown) with a primary-color background\n * and white text. Optionally displays a subtle timestamp below.\n */\nexport function UserMessage({ content, timestamp, style }: UserMessageProps) {\n return (\n <View style={[styles.container, style]}>\n <View style={styles.bubble}>\n <Text style={styles.text}>{content}</Text>\n </View>\n {timestamp && (\n <Text style={styles.timestamp}>{formatTimestamp(timestamp)}</Text>\n )}\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n alignItems: \"flex-end\",\n marginVertical: 4,\n paddingHorizontal: 12,\n },\n bubble: {\n backgroundColor: USER_BUBBLE_BG,\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n borderBottomLeftRadius: 16,\n borderBottomRightRadius: 4,\n paddingHorizontal: 12,\n paddingVertical: 8,\n maxWidth: \"80%\",\n },\n text: {\n color: USER_TEXT_COLOR,\n fontSize: 16,\n lineHeight: 22,\n },\n timestamp: {\n color: TIMESTAMP_COLOR,\n fontSize: 11,\n marginTop: 2,\n marginRight: 4,\n },\n});\n","import React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport {\n FlatList,\n KeyboardAvoidingView,\n Platform,\n Pressable,\n StyleSheet,\n Text,\n TextInput,\n TouchableOpacity,\n View,\n} from \"react-native\";\nimport type { ListRenderItemInfo, ViewStyle } from \"react-native\";\nimport { useAgent, useRenderToolCall } from \"@copilotkit/react-core/headless\";\nimport { useCopilotKit } from \"@copilotkit/react-core/context\";\nimport { AssistantMessage } from \"./messages/AssistantMessage\";\nimport { UserMessage } from \"./messages/UserMessage\";\nimport type { Message } from \"@copilotkit/shared\";\nimport type { ToolMessage } from \"@ag-ui/client\";\nimport { contentToText } from \"@ag-ui/client\";\n\n/** Shape of an assistant message with optional tool calls. */\ninterface AssistantMessageShape {\n id: string;\n role: \"assistant\";\n content?: string;\n toolCalls?: Array<{\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n }>;\n}\n\nexport interface CopilotChatProps {\n /** Agent ID to connect to. Defaults to 'default'. */\n agentName?: string;\n /** Placeholder text for the input field. */\n placeholder?: string;\n /** Suggestion pills shown in the empty state. */\n initialMessages?: string[];\n /** Title shown when there are no messages. */\n emptyStateTitle?: string;\n /** Subtitle shown when there are no messages. */\n emptyStateSubtitle?: string;\n /** Title for the optional header bar. */\n headerTitle?: string;\n /** Whether to show the header bar. Defaults to true. */\n showHeader?: boolean;\n /** Style override for the outermost container. */\n style?: ViewStyle;\n /** Style override for the message list container. */\n messageContainerStyle?: ViewStyle;\n /** Style override for the input bar container. */\n inputContainerStyle?: ViewStyle;\n /** Callback fired when the user sends a message. */\n onSendMessage?: (text: string) => void;\n /** Custom FlatList component (e.g. BottomSheetFlatList for use inside a bottom sheet). */\n FlatListComponent?: React.ComponentType<any>;\n /** When true, skip the KeyboardAvoidingView wrapper (useful when a parent already handles keyboard). */\n disableKeyboardAvoiding?: boolean;\n}\n\ninterface ChatListItem {\n id: string;\n type: \"user\" | \"assistant\" | \"tool-call\" | \"loading\";\n content?: string;\n toolCalls?: Array<{\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n }>;\n}\n\n/**\n * Lightweight content fingerprint for an agent's message list.\n *\n * The identity of `agent.messages` is NOT a reliable change signal, and it fails\n * in BOTH directions:\n *\n * - It changes on paths that have nothing to do with what is read below.\n * `@ag-ui/client`'s apply pipeline REASSIGNS the array\n * (`AbstractAgent.processApplyEvents` does `this.messages = applied.messages`),\n * so a streaming run hands down a fresh array — and fresh message, `toolCall`\n * and `function` objects — on every applied delta.\n * - It does NOT change on the paths these memos exist to serve. Core inserts\n * tool results by mutating in place —\n * `agent.messages.splice(insertAt, 0, toolMessage)`\n * (packages/core/src/core/run-handler.ts:931, :1080) —\n * `AbstractAgent.addMessage` is a `this.messages.push(...)`, and `useAgent`\n * re-renders with a bare `forceUpdate()` rather than a new array.\n *\n * (Grepping `packages/core/src` for a `.messages` assignment finds test files\n * only, but that proves nothing about identity: the reassignment lives in\n * `@ag-ui/client`, outside that tree.)\n *\n * So anything derived from messages must depend on their CONTENT, not on the\n * array reference.\n *\n * Captures exactly what the derivations below read — id, role, content size,\n * `toolCallId` (so an inserted tool result is visible), and each tool call's id\n * plus argument length (so streaming args advance).\n *\n * String and array content contribute their LENGTH rather than their value, so\n * large text and base64 attachment payloads are never re-serialized on every\n * render. Object content is the deliberate exception and IS serialized: a\n * length-based key is a constant 0 for every object, so an in-place content\n * replacement that keeps the same message id would otherwise be invisible to\n * every memo below.\n *\n * That object branch is convergence, not a fix for a reachable stale render: the\n * producer of same-id object content is an ACTIVITY_SNAPSHOT replace, and\n * `role: \"activity\"` never reaches `listItems`, which builds rows for `user` and\n * `assistant` only. It follows the SHAPE of react-core's `messagesMemoKey`\n * (react-core #6325). The two are independent implementations of the same idea —\n * a change to that key does not propagate here on its own, so treat this as a\n * documented parallel rather than a mirror.\n */\nfunction messagesFingerprint(messages: readonly unknown[]): string {\n return messages\n .map((msg) => {\n const m = msg as {\n id?: string;\n role?: string;\n content?: unknown;\n toolCallId?: string;\n toolCalls?: Array<{ id: string; function?: { arguments?: string } }>;\n };\n const content = m.content;\n const contentKey =\n typeof content === \"string\" || Array.isArray(content)\n ? content.length\n : content && typeof content === \"object\"\n ? objectContentKey(content)\n : 0;\n const toolCallsKey = Array.isArray(m.toolCalls)\n ? m.toolCalls\n .map((tc) => `${tc.id}:${tc.function?.arguments?.length ?? 0}`)\n .join(\";\")\n : \"\";\n return `${m.id}:${m.role}:${contentKey}:${m.toolCallId ?? \"\"}:${toolCallsKey}`;\n })\n .join(\",\");\n}\n\n/**\n * Serializes object content for the fingerprint above.\n *\n * Guarded because `JSON.stringify` THROWS on a circular structure and\n * `messagesFingerprint` runs on EVERY render, so a bare call would take the whole\n * chat down on content this component is explicitly required to tolerate —\n * `toolResultContent` below documents why non-string content reaches RN at all,\n * and \"does not throw on tool content that cannot be JSON-serialised\" pins that a\n * circular tool result must still render.\n *\n * The fallback is a constant, which means a circular object is invisible to the\n * memo exactly as every object used to be. That is the correct trade: it confines\n * the old always-equal behaviour to the pathological case instead of letting it\n * decide the common one. NOTE: this guard is a deliberate divergence from\n * react-core's `messagesMemoKey`, which stringifies unguarded.\n */\nfunction objectContentKey(content: object): string {\n try {\n return JSON.stringify(content) ?? \"\";\n } catch {\n return \"[unserializable]\";\n }\n}\n\n/**\n * Coerces a tool message's `content` to the `string` the renderer contract\n * requires (`ReactToolCallRenderer`'s Complete branch declares `result: string`)\n * WITHOUT inventing an empty result.\n *\n * AG-UI 1.0 models tool content as `string | ContentPart[]`: a plain string, or\n * an ordered list of typed parts (text, image, audio, video, document). A\n * string passes through; a list of parts is rendered as its text parts\n * concatenated — the flattening the spec permits for a string-only consumer —\n * and the media parts stay on the message for anything that can show them.\n * Neither is malformed, so neither warns.\n *\n * Anything else is only reachable from a producer that skipped validation —\n * restored thread history, a non-SSE transport, or app code casting on\n * `addMessage`. Core hedges against that case too (it accepts `unknown` content\n * and handles arrays of text parts), so this must not answer it with `\"\"`: an\n * empty string is a LEGITIMATE tool result, which makes a dropped result\n * indistinguishable from an empty one. Serialise faithfully — the same\n * representation core uses for non-string results — and warn in dev.\n */\nconst MEDIA_PART_TYPES = new Set([\"image\", \"audio\", \"video\", \"document\"]);\n\n/**\n * Whether a value is one of the protocol's content parts: a text part with a\n * string `text`, or a media part with a `source` that names its kind and\n * value. Anything else — an array of typed records from restored history,\n * say — is not parts and keeps the serialise-and-warn path.\n */\nfunction isContentPart(part: unknown): boolean {\n if (typeof part !== \"object\" || part === null) return false;\n const record = part as { type?: unknown; text?: unknown; source?: unknown };\n if (record.type === \"text\") return typeof record.text === \"string\";\n if (typeof record.type !== \"string\" || !MEDIA_PART_TYPES.has(record.type))\n return false;\n const source = record.source as\n | { type?: unknown; value?: unknown; mimeType?: unknown }\n | undefined;\n if (typeof source !== \"object\" || source === null) return false;\n if (typeof source.value !== \"string\") return false;\n // Inline bytes need their type; a URL or a provider file handle (AG-UI 1.0\n // `file` source) may leave it out.\n if (source.type === \"data\") return typeof source.mimeType === \"string\";\n return (\n (source.type === \"url\" || source.type === \"file\") &&\n (source.mimeType === undefined || typeof source.mimeType === \"string\")\n );\n}\n\nfunction toolResultContent(content: unknown, toolCallId: string): string {\n if (typeof content === \"string\") return content;\n\n if (Array.isArray(content) && content.every(isContentPart)) {\n return contentToText(content as ToolMessage[\"content\"]);\n }\n\n // null/undefined carry no payload, so \"\" loses nothing — but the message is\n // still malformed, so it warns below rather than passing silently.\n let serialized = \"\";\n if (content !== null && content !== undefined) {\n try {\n serialized =\n JSON.stringify(content) ?? Object.prototype.toString.call(content);\n } catch {\n // Circular or otherwise non-serialisable: keep SOMETHING over dropping\n // the result, and never throw from a render path.\n serialized = Object.prototype.toString.call(content);\n }\n }\n\n if (typeof __DEV__ === \"undefined\" || __DEV__) {\n console.warn(\n `[CopilotChat] Tool message for tool call \"${toolCallId}\" had non-string ` +\n `content (${content === null ? \"null\" : typeof content}), but renderers ` +\n `receive \\`result: string\\`. Rendering a serialized form instead of ` +\n `dropping it: ${serialized === \"\" ? \"<empty>\" : serialized}`,\n );\n }\n\n return serialized;\n}\n\n/**\n * Full-screen chat UI component for React Native.\n *\n * Connects to a CopilotKit agent via `useAgent` and renders messages\n * using platform-appropriate AssistantMessage / UserMessage components.\n *\n * Usage:\n * ```tsx\n * <CopilotChat agentName=\"my-agent\" headerTitle=\"Assistant\" />\n * ```\n */\nexport function CopilotChat({\n agentName = \"default\",\n placeholder = \"Type a message...\",\n initialMessages = [],\n emptyStateTitle = \"How can I help?\",\n emptyStateSubtitle = \"Ask me anything or try a suggestion below.\",\n headerTitle = \"Chat\",\n showHeader = true,\n style,\n messageContainerStyle,\n inputContainerStyle,\n onSendMessage,\n FlatListComponent = FlatList,\n disableKeyboardAvoiding = false,\n}: CopilotChatProps) {\n const [inputText, setInputText] = useState(\"\");\n const [error, setError] = useState<string | null>(null);\n const flatListRef = useRef<FlatList>(null);\n const messageIdCounter = useRef(0);\n\n const { copilotkit } = useCopilotKit();\n const { agent } = useAgent({ agentId: agentName });\n\n const messages = agent.messages ?? [];\n const isRunning = agent.isRunning;\n\n const renderToolCall = useRenderToolCall();\n\n // useInterrupt publishes its element to core unless renderInChat is false.\n // Draw it after the last message, as the web message view does.\n const [interruptElement, setInterruptElement] =\n useState<React.ReactElement | null>(null);\n useEffect(() => {\n setInterruptElement(copilotkit.interruptElement);\n const subscription = copilotkit.subscribe({\n onInterruptElementChanged: ({ interruptElement: element }) => {\n setInterruptElement(element);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n // Recomputed every render — cheap, and the only honest dependency for the\n // message-derived memos below. See `messagesFingerprint` for why the array\n // reference cannot be trusted as one.\n const messagesKey = messagesFingerprint(messages);\n\n // toolCallId -> tool result message. react-core's renderer reports\n // status \"complete\" with `result` when a tool message exists; RN's chat\n // previously never correlated these, so `result` was always undefined.\n const toolMessages = useMemo(() => {\n const byId = new Map<string, ToolMessage>();\n for (const msg of messages) {\n const m = msg as {\n role?: string;\n id?: string;\n toolCallId?: string;\n content?: unknown;\n };\n if (m.role === \"tool\" && m.toolCallId) {\n byId.set(m.toolCallId, {\n id: m.id ?? m.toolCallId,\n role: \"tool\",\n toolCallId: m.toolCallId,\n content: toolResultContent(m.content, m.toolCallId),\n });\n }\n }\n return byId;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [messagesKey]);\n\n // Build flat list items from messages\n const listItems: ChatListItem[] = useMemo(() => {\n const items: ChatListItem[] = [];\n\n for (const msg of messages) {\n if (msg.role === \"user\") {\n items.push({\n id: msg.id,\n type: \"user\",\n content: typeof msg.content === \"string\" ? msg.content : \"\",\n });\n } else if (msg.role === \"assistant\") {\n const assistantMsg = msg as AssistantMessageShape;\n // Add text content if present\n if (assistantMsg.content) {\n items.push({\n id: msg.id,\n type: \"assistant\",\n content: assistantMsg.content,\n });\n }\n // Add tool calls if present\n if (assistantMsg.toolCalls && assistantMsg.toolCalls.length > 0) {\n for (const tc of assistantMsg.toolCalls) {\n items.push({\n id: `${msg.id}-tc-${tc.id}`,\n type: \"tool-call\",\n toolCalls: [tc],\n });\n }\n }\n }\n }\n\n // Show loading indicator when agent is running and the last message\n // is not already the assistant streaming\n if (isRunning) {\n const lastItem = items[items.length - 1];\n if (!lastItem || lastItem.type !== \"assistant\") {\n items.push({ id: \"__loading__\", type: \"loading\" });\n }\n }\n\n return items;\n // Same reasoning as `toolMessages`: keyed on message CONTENT, because the\n // array reference does not track content in either direction — core's\n // in-place `splice` and `addMessage`'s push leave it untouched, while the\n // AG-UI apply pipeline replaces it on every delta. Without this, an\n // assistant message or tool call appended mid-run never reaches the list.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [messagesKey, isRunning]);\n\n // Id of the trailing row. renderItem needs \"is this the last row?\" to place\n // the streaming indicator; deriving it here keeps that a named scalar instead\n // of renderItem closing over `listItems` and index-reading its tail.\n const lastItemId = useMemo(\n () => listItems[listItems.length - 1]?.id,\n [listItems],\n );\n\n // extraData defeats FlatList's PureComponent shallow-compare for the values\n // renderItem CLOSES OVER, as opposed to the ones it receives per row. Those\n // are exactly the four below, and they mirror renderItem's dependency array —\n // keep the two in sync. `listItems` is deliberately absent: renderItem's only\n // read of it is the tail id, now passed as `lastItemId`, and the array itself\n // is already the `data` prop, which invalidates cells on its own (every\n // rebuild allocates fresh item objects, so each cell's `item` prop differs).\n const extraData = useMemo(\n () => ({ isRunning, lastItemId, renderToolCall, toolMessages }),\n [isRunning, lastItemId, renderToolCall, toolMessages],\n );\n\n // Shared logic for sending a message to the agent\n const sendMessage = useCallback(\n async (text: string) => {\n if (!text || isRunning || !agent) return;\n\n setError(null);\n onSendMessage?.(text);\n\n const id = `user-${++messageIdCounter.current}`;\n agent.addMessage({\n id,\n role: \"user\",\n content: text,\n } as Message);\n\n try {\n await copilotkit.runAgent({ agent });\n } catch (err) {\n const message =\n err instanceof Error ? err.message : \"An unexpected error occurred\";\n console.error(\"[CopilotChat] runAgent failed:\", err);\n setError(message);\n }\n },\n [isRunning, agent, copilotkit, onSendMessage],\n );\n\n // Send from the input field\n const handleSend = useCallback(() => {\n const text = inputText.trim();\n if (!text) return;\n setInputText(\"\");\n void sendMessage(text);\n }, [inputText, sendMessage]);\n\n // Handle suggestion pill press\n const handleSuggestion = useCallback(\n (text: string) => {\n void sendMessage(text);\n },\n [sendMessage],\n );\n\n // Auto-scroll when content changes\n const handleContentSizeChange = useCallback(() => {\n flatListRef.current?.scrollToEnd({ animated: true });\n }, []);\n\n // Render a single list item\n const renderItem = useCallback(\n ({ item }: ListRenderItemInfo<ChatListItem>) => {\n if (item.type === \"user\") {\n return <UserMessage content={item.content ?? \"\"} />;\n }\n\n if (item.type === \"assistant\") {\n return (\n <AssistantMessage\n content={item.content ?? \"\"}\n isLoading={isRunning && item.id === lastItemId}\n />\n );\n }\n\n if (item.type === \"tool-call\" && item.toolCalls) {\n const tc = item.toolCalls[0];\n // Partial-parses streaming args, resolves the renderer (exact name ->\n // agent-scoped -> wildcard \"*\") and derives status — all in react-core,\n // shared with web. Returns ReactElement | null, which is what\n // renderItem requires.\n const rendered = renderToolCall({\n toolCall: tc,\n toolMessage: toolMessages.get(tc.id),\n });\n if (rendered) return <>{rendered}</>;\n\n // Subtle indicator for unregistered tool calls\n return (\n <View style={styles.toolCallIndicator}>\n <Text style={styles.toolCallText}>Called: {tc.function.name}</Text>\n </View>\n );\n }\n\n if (item.type === \"loading\") {\n return <AssistantMessage content=\"\" isLoading />;\n }\n\n return null;\n },\n [isRunning, lastItemId, renderToolCall, toolMessages],\n );\n\n const keyExtractor = useCallback((item: ChatListItem) => item.id, []);\n\n // Empty state component\n const emptyComponent = useMemo(\n () => (\n <View style={styles.emptyState}>\n <Text style={styles.emptyTitle}>{emptyStateTitle}</Text>\n <Text style={styles.emptySubtitle}>{emptyStateSubtitle}</Text>\n {initialMessages.map((suggestion, i) => (\n <Pressable\n key={`suggestion-${i}`}\n style={styles.suggestionPill}\n onPress={() => handleSuggestion(suggestion)}\n >\n <Text style={styles.suggestionText}>{suggestion}</Text>\n </Pressable>\n ))}\n </View>\n ),\n [emptyStateTitle, emptyStateSubtitle, initialMessages, handleSuggestion],\n );\n\n const sendDisabled = !inputText.trim() || isRunning;\n\n const content = (\n <>\n {showHeader && (\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n </View>\n )}\n\n <FlatListComponent\n ref={flatListRef}\n data={listItems}\n renderItem={renderItem}\n keyExtractor={keyExtractor}\n extraData={extraData}\n contentContainerStyle={[styles.messageList, messageContainerStyle]}\n onContentSizeChange={handleContentSizeChange}\n ListEmptyComponent={emptyComponent}\n ListFooterComponent={interruptElement}\n />\n\n {error && (\n <View style={styles.errorContainer} testID=\"error-message\">\n <Text style={styles.errorText}>{error}</Text>\n </View>\n )}\n\n <View style={[styles.inputContainer, inputContainerStyle]}>\n <TextInput\n style={styles.input}\n value={inputText}\n onChangeText={setInputText}\n placeholder={placeholder}\n placeholderTextColor=\"#999\"\n multiline\n numberOfLines={4}\n returnKeyType=\"send\"\n onSubmitEditing={handleSend}\n />\n <TouchableOpacity\n style={[styles.sendButton, sendDisabled && styles.sendButtonDisabled]}\n onPress={handleSend}\n disabled={sendDisabled}\n testID=\"send-button\"\n >\n <Text style={styles.sendButtonIcon}>{\"↑\"}</Text>\n </TouchableOpacity>\n </View>\n </>\n );\n\n if (disableKeyboardAvoiding) {\n return <View style={[styles.container, style]}>{content}</View>;\n }\n\n return (\n <KeyboardAvoidingView\n style={[styles.container, style]}\n behavior={Platform.OS === \"ios\" ? \"padding\" : \"height\"}\n keyboardVerticalOffset={0}\n >\n {content}\n </KeyboardAvoidingView>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n backgroundColor: \"#FFFFFF\",\n },\n header: {\n height: 56,\n justifyContent: \"center\",\n alignItems: \"center\",\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#E0E0E0\",\n backgroundColor: \"#FFFFFF\",\n },\n headerTitle: {\n fontSize: 17,\n fontWeight: \"600\",\n color: \"#1A1A1A\",\n },\n messageList: {\n paddingHorizontal: 16,\n flexGrow: 1,\n },\n inputContainer: {\n flexDirection: \"row\",\n alignItems: \"flex-end\",\n paddingHorizontal: 8,\n paddingVertical: 8,\n borderTopWidth: StyleSheet.hairlineWidth,\n borderTopColor: \"#E0E0E0\",\n backgroundColor: \"#FFFFFF\",\n },\n input: {\n flex: 1,\n backgroundColor: \"#F5F5F5\",\n borderRadius: 20,\n paddingHorizontal: 12,\n paddingVertical: 8,\n fontSize: 15,\n maxHeight: 100,\n color: \"#1A1A1A\",\n },\n sendButton: {\n width: 36,\n height: 36,\n borderRadius: 18,\n backgroundColor: \"#0066CC\",\n justifyContent: \"center\",\n alignItems: \"center\",\n marginLeft: 8,\n },\n sendButtonDisabled: {\n opacity: 0.4,\n },\n sendButtonIcon: {\n color: \"#FFFFFF\",\n fontSize: 18,\n fontWeight: \"700\",\n },\n emptyState: {\n flex: 1,\n justifyContent: \"center\",\n alignItems: \"center\",\n paddingTop: 100,\n gap: 12,\n },\n emptyTitle: {\n fontSize: 22,\n fontWeight: \"700\",\n color: \"#1A1A1A\",\n marginBottom: 4,\n },\n emptySubtitle: {\n fontSize: 15,\n color: \"#666666\",\n marginBottom: 16,\n },\n suggestionPill: {\n backgroundColor: \"#E8F0FE\",\n borderRadius: 20,\n paddingHorizontal: 16,\n paddingVertical: 10,\n },\n suggestionText: {\n color: \"#0066CC\",\n fontWeight: \"600\",\n fontSize: 14,\n },\n toolCallIndicator: {\n alignSelf: \"flex-start\",\n backgroundColor: \"#F0F0F0\",\n borderRadius: 12,\n paddingHorizontal: 12,\n paddingVertical: 6,\n marginBottom: 8,\n },\n toolCallText: {\n fontSize: 12,\n color: \"#999999\",\n fontStyle: \"italic\",\n },\n errorContainer: {\n backgroundColor: \"#FEE2E2\",\n paddingHorizontal: 12,\n paddingVertical: 8,\n marginHorizontal: 8,\n borderRadius: 8,\n },\n errorText: {\n color: \"#DC2626\",\n fontSize: 13,\n },\n});\n","/**\n * CopilotModal — a bottom-sheet chat overlay for React Native.\n *\n * Mobile equivalent of CopilotPopup on web. Wraps CopilotChat inside\n * @gorhom/bottom-sheet so the chat can slide up over any screen.\n */\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n} from \"react\";\nimport { StyleSheet, View } from \"react-native\";\nimport BottomSheet, {\n BottomSheetBackdrop,\n BottomSheetFlatList,\n BottomSheetView,\n} from \"@gorhom/bottom-sheet\";\nimport type { BottomSheetBackdropProps } from \"@gorhom/bottom-sheet\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatProps } from \"./CopilotChat\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CopilotModalProps {\n /** Controlled visibility — when true the sheet opens, when false it closes. */\n visible?: boolean;\n\n /** Called when the sheet is dismissed (via backdrop tap, swipe-down, or close()). */\n onDismiss?: () => void;\n\n /**\n * Bottom-sheet snap points.\n * @default ['50%', '90%']\n */\n snapPoints?: (string | number)[];\n\n /**\n * Which snap-point index to open at.\n * @default 0\n */\n initialSnapIndex?: number;\n\n /**\n * Whether closing the sheet fires onDismiss.\n * @default true\n */\n enableDismissOnClose?: boolean;\n\n /**\n * Backdrop opacity when the sheet is open.\n * @default 0.5\n */\n backdropOpacity?: number;\n\n // -- Pass-through to CopilotChat ------------------------------------------\n\n /** Which agent to connect to. */\n agentName?: string;\n\n /** Input placeholder text. */\n placeholder?: string;\n\n /** Seed messages shown on first render. */\n initialMessages?: string[];\n\n /** Title shown in the CopilotChat header area. */\n headerTitle?: string;\n}\n\n/** Imperative handle exposed via ref. */\nexport interface CopilotModalRef {\n /** Programmatically open the bottom sheet. */\n open: () => void;\n /** Programmatically close the bottom sheet. */\n close: () => void;\n}\n\n// ---------------------------------------------------------------------------\n// Component\n// ---------------------------------------------------------------------------\n\nexport const CopilotModal = forwardRef<CopilotModalRef, CopilotModalProps>(\n function CopilotModal(\n {\n visible,\n onDismiss,\n snapPoints: snapPointsProp,\n initialSnapIndex = 0,\n enableDismissOnClose = true,\n backdropOpacity = 0.5,\n agentName,\n placeholder,\n initialMessages,\n headerTitle,\n },\n ref,\n ) {\n const bottomSheetRef = useRef<BottomSheet>(null);\n\n // Stable snap-points array\n const snapPoints = useMemo(\n () => snapPointsProp ?? [\"50%\", \"90%\"],\n [snapPointsProp],\n );\n\n // ── Imperative API ────────────────────────────────────────────────────\n useImperativeHandle(\n ref,\n () => ({\n open() {\n bottomSheetRef.current?.snapToIndex(initialSnapIndex);\n },\n close() {\n bottomSheetRef.current?.close();\n },\n }),\n [initialSnapIndex],\n );\n\n // ── Controlled visibility ─────────────────────────────────────────────\n useEffect(() => {\n if (visible === undefined) return;\n if (visible) {\n bottomSheetRef.current?.snapToIndex(initialSnapIndex);\n } else {\n bottomSheetRef.current?.close();\n }\n }, [visible, initialSnapIndex]);\n\n // ── Backdrop renderer ─────────────────────────────────────────────────\n const renderBackdrop = useCallback(\n (props: BottomSheetBackdropProps) => (\n <BottomSheetBackdrop\n {...props}\n disappearsOnIndex={-1}\n appearsOnIndex={0}\n opacity={backdropOpacity}\n pressBehavior=\"close\"\n />\n ),\n [backdropOpacity],\n );\n\n // ── Sheet close handler ───────────────────────────────────────────────\n const handleClose = useCallback(() => {\n if (enableDismissOnClose) {\n onDismiss?.();\n }\n }, [enableDismissOnClose, onDismiss]);\n\n // ── Build CopilotChat props ───────────────────────────────────────────\n const chatProps = useMemo(() => {\n const props: Partial<CopilotChatProps> = {};\n if (agentName !== undefined) props.agentName = agentName;\n if (placeholder !== undefined) props.placeholder = placeholder;\n if (initialMessages !== undefined)\n props.initialMessages = initialMessages;\n if (headerTitle !== undefined) props.headerTitle = headerTitle;\n return props;\n }, [agentName, placeholder, initialMessages, headerTitle]);\n\n return (\n <BottomSheet\n ref={bottomSheetRef}\n index={-1}\n snapPoints={snapPoints}\n enablePanDownToClose\n backdropComponent={renderBackdrop}\n onClose={handleClose}\n keyboardBehavior=\"interactive\"\n keyboardBlurBehavior=\"restore\"\n backgroundStyle={styles.sheetBackground}\n handleIndicatorStyle={styles.handleIndicator}\n >\n <BottomSheetView style={styles.contentContainer}>\n <CopilotChat\n {...chatProps}\n FlatListComponent={BottomSheetFlatList}\n disableKeyboardAvoiding\n />\n </BottomSheetView>\n </BottomSheet>\n );\n },\n);\n\n// ---------------------------------------------------------------------------\n// Styles\n// ---------------------------------------------------------------------------\n\nconst styles = StyleSheet.create({\n sheetBackground: {\n backgroundColor: \"#FFFFFF\",\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n },\n handleIndicator: {\n width: 40,\n height: 4,\n backgroundColor: \"#DDDDDD\",\n },\n contentContainer: {\n flex: 1,\n },\n});\n"],"mappings":";;;;;;;;;;;;;;AAYA,MAAM,WAAW;AACjB,MAAM,cAAc;AACpB,MAAM,qBAAqB;;;;;;;AAQ3B,SAAgB,gBAAgB,EAAE,SAA+B;CAC/D,MAAM,yBAAc,IAAIA,sBAAS,MAAM,EAAE,CAAC,CAAC;CAC3C,MAAM,yBAAc,IAAIA,sBAAS,MAAM,EAAE,CAAC,CAAC;CAC3C,MAAM,yBAAc,IAAIA,sBAAS,MAAM,EAAE,CAAC,CAAC;AAE3C,4BAAgB;EACd,MAAM,eAAe,KAAqB,UACxCA,sBAAS,SAAS,CAChBA,sBAAS,MAAM,MAAM,EACrBA,sBAAS,KACPA,sBAAS,SAAS,CAChBA,sBAAS,OAAO,KAAK;GACnB,SAAS;GACT,UAAU;GACV,iBAAiB;GAClB,CAAC,EACFA,sBAAS,OAAO,KAAK;GACnB,SAAS;GACT,UAAU;GACV,iBAAiB;GAClB,CAAC,CACH,CAAC,CACH,CACF,CAAC;EAEJ,MAAM,YAAYA,sBAAS,SAAS;GAClC,YAAY,MAAM,EAAE;GACpB,YAAY,MAAM,qBAAqB,IAAK;GAC5C,YAAY,MAAM,qBAAqB,IAAK;GAC7C,CAAC;AAEF,YAAU,OAAO;AAEjB,eAAa;AACX,aAAU,MAA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E1D,QACE,2CAACC;EACC,KAAK;EACL,OAAO;EACK;EACZ;EACA,mBAAmB;EACnB,SAAS;EACT,kBAAiB;EACjB,sBAAqB;EACrB,iBAAiB,OAAO;EACxB,sBAAsB,OAAO;YAE7B,2CAACC;GAAgB,OAAO,OAAO;aAC7B,2CAAC;IACC,GAAI;IACJ,mBAAmBC;IACnB;KACA;IACc;GACN;EAGnB;AAMD,MAAM,SAASC,wBAAW,OAAO;CAC/B,iBAAiB;EACf,iBAAiB;EACjB,qBAAqB;EACrB,sBAAsB;EACvB;CACD,iBAAiB;EACf,OAAO;EACP,QAAQ;EACR,iBAAiB;EAClB;CACD,kBAAkB,EAChB,MAAM,GACP;CACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["Animated","styles","View","StyleSheet","TIMESTAMP_COLOR","useMarkdownRenderer","View","styles","isNativeComponentRenderer","React","CopilotMarkdown","Text","StyleSheet","View","styles","Text","StyleSheet","FlatList","View","styles","Text","Pressable","TextInput","TouchableOpacity","KeyboardAvoidingView","Platform","StyleSheet","BottomSheetBackdrop","BottomSheet","BottomSheetView","BottomSheetFlatList","StyleSheet"],"sources":["../../src/components/messages/TypingIndicator.tsx","../../src/components/messages/utils.ts","../../src/components/messages/AssistantMessage.tsx","../../src/components/messages/UserMessage.tsx","../../src/components/CopilotChat.tsx","../../src/components/CopilotModal.tsx"],"sourcesContent":["import React, { useEffect, useState } from \"react\";\nimport { View, Animated, StyleSheet } from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\n\n/**\n * Props for the TypingIndicator component.\n */\nexport interface TypingIndicatorProps {\n /** Optional style override for the container */\n style?: ViewStyle;\n}\n\nconst DOT_SIZE = 6;\nconst DOT_SPACING = 4;\nconst ANIMATION_DURATION = 400;\n\n/**\n * Three animated dots that pulse in sequence, suitable for embedding\n * inside an AssistantMessage to indicate the AI is still generating.\n *\n * Uses React Native's built-in `Animated` API (no Reanimated dependency).\n */\nexport function TypingIndicator({ style }: TypingIndicatorProps) {\n const [dot1] = useState(() => new Animated.Value(0));\n const [dot2] = useState(() => new Animated.Value(0));\n const [dot3] = useState(() => new Animated.Value(0));\n\n useEffect(() => {\n const createPulse = (dot: Animated.Value, delay: number) =>\n Animated.sequence([\n Animated.delay(delay),\n Animated.loop(\n Animated.sequence([\n Animated.timing(dot, {\n toValue: 1,\n duration: ANIMATION_DURATION,\n useNativeDriver: true,\n }),\n Animated.timing(dot, {\n toValue: 0,\n duration: ANIMATION_DURATION,\n useNativeDriver: true,\n }),\n ]),\n ),\n ]);\n\n const animation = Animated.parallel([\n createPulse(dot1, 0),\n createPulse(dot2, ANIMATION_DURATION * 0.33),\n createPulse(dot3, ANIMATION_DURATION * 0.66),\n ]);\n\n animation.start();\n\n return () => {\n animation.stop();\n };\n }, [dot1, dot2, dot3]);\n\n const dotStyle = (animatedValue: Animated.Value) => ({\n ...styles.dot,\n opacity: animatedValue.interpolate({\n inputRange: [0, 1],\n outputRange: [0.3, 1],\n }),\n transform: [\n {\n scale: animatedValue.interpolate({\n inputRange: [0, 1],\n outputRange: [0.8, 1.2],\n }),\n },\n ],\n });\n\n return (\n <View\n testID=\"copilot-loading-cursor\"\n style={[styles.container, style]}\n accessibilityLabel=\"Typing indicator\"\n accessibilityRole=\"text\"\n >\n <Animated.View style={dotStyle(dot1)} />\n <Animated.View style={dotStyle(dot2)} />\n <Animated.View style={dotStyle(dot3)} />\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flexDirection: \"row\",\n alignItems: \"center\",\n paddingVertical: 4,\n paddingHorizontal: 2,\n },\n dot: {\n width: DOT_SIZE,\n height: DOT_SIZE,\n borderRadius: DOT_SIZE / 2,\n backgroundColor: \"#999999\",\n marginHorizontal: DOT_SPACING / 2,\n },\n});\n","/**\n * Format a Date as a 12-hour time string (e.g. \"2:05 PM\").\n */\nexport function formatTimestamp(date: Date): string {\n const hours = date.getHours();\n const minutes = date.getMinutes();\n const ampm = hours >= 12 ? \"PM\" : \"AM\";\n const displayHours = hours % 12 || 12;\n const displayMinutes = minutes.toString().padStart(2, \"0\");\n return `${displayHours}:${displayMinutes} ${ampm}`;\n}\n","import React from \"react\";\nimport { View, Text, StyleSheet } from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotMarkdown } from \"../Markdown\";\nimport {\n useMarkdownRenderer,\n isNativeComponentRenderer,\n} from \"../MarkdownRendererContext\";\nimport { TypingIndicator } from \"./TypingIndicator\";\nimport { formatTimestamp } from \"./utils\";\n\n// ─── Colors ──────────────────────────────────────────────────────────────────\nconst ASSISTANT_BUBBLE_BG = \"#F0F0F0\";\nconst TIMESTAMP_COLOR = \"#999999\";\n\n/**\n * Props for the AssistantMessage component.\n */\nexport interface AssistantMessageProps {\n /** Markdown content to render inside the bubble */\n content: string;\n /** When true, shows a typing indicator below any content */\n isLoading?: boolean;\n /** Optional timestamp displayed below the bubble */\n timestamp?: Date;\n /** Optional style override for the outer container */\n style?: ViewStyle;\n}\n\n/**\n * Left-aligned chat bubble for AI assistant responses.\n *\n * Renders markdown content via `CopilotMarkdown` and shows an animated\n * typing indicator when `isLoading` is true.\n */\nexport function AssistantMessage({\n content,\n isLoading = false,\n timestamp,\n style,\n}: AssistantMessageProps) {\n // Honor a provider-level markdown renderer (CopilotKitProvider's\n // `markdownRenderer` prop), falling back to the built-in CopilotMarkdown.\n // This is the React Native arm of the slot -> provider -> built-in\n // resolution order documented in the migration guide.\n const provided = useMarkdownRenderer();\n return (\n <View style={[styles.container, style]}>\n <View style={styles.bubble}>\n {content ? (\n isNativeComponentRenderer(provided) ? (\n React.createElement(provided, { content, isStreaming: isLoading })\n ) : provided ? (\n <CopilotMarkdown\n content={content}\n style={provided.style}\n streamingAnimation={provided.animate}\n />\n ) : (\n <CopilotMarkdown content={content} />\n )\n ) : null}\n {isLoading ? <TypingIndicator /> : null}\n </View>\n {timestamp && (\n <Text style={styles.timestamp}>{formatTimestamp(timestamp)}</Text>\n )}\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n alignItems: \"flex-start\",\n marginVertical: 4,\n paddingHorizontal: 12,\n },\n bubble: {\n backgroundColor: ASSISTANT_BUBBLE_BG,\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n borderBottomRightRadius: 16,\n borderBottomLeftRadius: 4,\n paddingHorizontal: 12,\n paddingVertical: 8,\n maxWidth: \"80%\",\n },\n timestamp: {\n color: TIMESTAMP_COLOR,\n fontSize: 11,\n marginTop: 2,\n marginLeft: 4,\n },\n});\n","import React from \"react\";\nimport { View, Text, StyleSheet, type ViewStyle } from \"react-native\";\nimport { formatTimestamp } from \"./utils\";\n\n// ─── Colors ──────────────────────────────────────────────────────────────────\nconst USER_BUBBLE_BG = \"#0066CC\";\nconst USER_TEXT_COLOR = \"#FFFFFF\";\nconst TIMESTAMP_COLOR = \"#999999\";\n\n/**\n * Props for the UserMessage component.\n */\nexport interface UserMessageProps {\n /** Plain text content to display */\n content: string;\n /** Optional timestamp displayed below the bubble */\n timestamp?: Date;\n /** Optional style override for the outer container */\n style?: ViewStyle;\n}\n\n/**\n * Right-aligned chat bubble for user messages.\n *\n * Renders plain text (no markdown) with a primary-color background\n * and white text. Optionally displays a subtle timestamp below.\n */\nexport function UserMessage({ content, timestamp, style }: UserMessageProps) {\n return (\n <View style={[styles.container, style]}>\n <View style={styles.bubble}>\n <Text style={styles.text}>{content}</Text>\n </View>\n {timestamp && (\n <Text style={styles.timestamp}>{formatTimestamp(timestamp)}</Text>\n )}\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n alignItems: \"flex-end\",\n marginVertical: 4,\n paddingHorizontal: 12,\n },\n bubble: {\n backgroundColor: USER_BUBBLE_BG,\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n borderBottomLeftRadius: 16,\n borderBottomRightRadius: 4,\n paddingHorizontal: 12,\n paddingVertical: 8,\n maxWidth: \"80%\",\n },\n text: {\n color: USER_TEXT_COLOR,\n fontSize: 16,\n lineHeight: 22,\n },\n timestamp: {\n color: TIMESTAMP_COLOR,\n fontSize: 11,\n marginTop: 2,\n marginRight: 4,\n },\n});\n","import React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport {\n FlatList,\n KeyboardAvoidingView,\n Platform,\n Pressable,\n StyleSheet,\n Text,\n TextInput,\n TouchableOpacity,\n View,\n} from \"react-native\";\nimport type { ListRenderItemInfo, ViewStyle } from \"react-native\";\nimport { useAgent, useRenderToolCall } from \"@copilotkit/react-core/headless\";\nimport { useCopilotKit } from \"@copilotkit/react-core/context\";\nimport { AssistantMessage } from \"./messages/AssistantMessage\";\nimport { UserMessage } from \"./messages/UserMessage\";\nimport type { Message } from \"@copilotkit/shared\";\nimport type { ToolMessage } from \"@ag-ui/client\";\nimport { contentToText } from \"@ag-ui/client\";\n\n/** Shape of an assistant message with optional tool calls. */\ninterface AssistantMessageShape {\n id: string;\n role: \"assistant\";\n content?: string;\n toolCalls?: Array<{\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n }>;\n}\n\nexport interface CopilotChatProps {\n /** Agent ID to connect to. Defaults to 'default'. */\n agentName?: string;\n /** Placeholder text for the input field. */\n placeholder?: string;\n /** Suggestion pills shown in the empty state. */\n initialMessages?: string[];\n /** Title shown when there are no messages. */\n emptyStateTitle?: string;\n /** Subtitle shown when there are no messages. */\n emptyStateSubtitle?: string;\n /** Title for the optional header bar. */\n headerTitle?: string;\n /** Whether to show the header bar. Defaults to true. */\n showHeader?: boolean;\n /** Style override for the outermost container. */\n style?: ViewStyle;\n /** Style override for the message list container. */\n messageContainerStyle?: ViewStyle;\n /** Style override for the input bar container. */\n inputContainerStyle?: ViewStyle;\n /** Callback fired when the user sends a message. */\n onSendMessage?: (text: string) => void;\n /** Custom FlatList component (e.g. BottomSheetFlatList for use inside a bottom sheet). */\n FlatListComponent?: React.ComponentType<any>;\n /** When true, skip the KeyboardAvoidingView wrapper (useful when a parent already handles keyboard). */\n disableKeyboardAvoiding?: boolean;\n}\n\ninterface ChatListItem {\n id: string;\n type: \"user\" | \"assistant\" | \"tool-call\" | \"loading\";\n content?: string;\n toolCalls?: Array<{\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n }>;\n}\n\n/**\n * Lightweight content fingerprint for an agent's message list.\n *\n * The identity of `agent.messages` is NOT a reliable change signal, and it fails\n * in BOTH directions:\n *\n * - It changes on paths that have nothing to do with what is read below.\n * `@ag-ui/client`'s apply pipeline REASSIGNS the array\n * (`AbstractAgent.processApplyEvents` does `this.messages = applied.messages`),\n * so a streaming run hands down a fresh array — and fresh message, `toolCall`\n * and `function` objects — on every applied delta.\n * - It does NOT change on the paths these memos exist to serve. Core inserts\n * tool results by mutating in place —\n * `agent.messages.splice(insertAt, 0, toolMessage)`\n * (packages/core/src/core/run-handler.ts:931, :1080) —\n * `AbstractAgent.addMessage` is a `this.messages.push(...)`, and `useAgent`\n * re-renders with a bare `forceUpdate()` rather than a new array.\n *\n * (Grepping `packages/core/src` for a `.messages` assignment finds test files\n * only, but that proves nothing about identity: the reassignment lives in\n * `@ag-ui/client`, outside that tree.)\n *\n * So anything derived from messages must depend on their CONTENT, not on the\n * array reference.\n *\n * Captures exactly what the derivations below read — id, role, content size,\n * `toolCallId` (so an inserted tool result is visible), and each tool call's id\n * plus argument length (so streaming args advance).\n *\n * String and array content contribute their LENGTH rather than their value, so\n * large text and base64 attachment payloads are never re-serialized on every\n * render. Object content is the deliberate exception and IS serialized: a\n * length-based key is a constant 0 for every object, so an in-place content\n * replacement that keeps the same message id would otherwise be invisible to\n * every memo below.\n *\n * That object branch is convergence, not a fix for a reachable stale render: the\n * producer of same-id object content is an ACTIVITY_SNAPSHOT replace, and\n * `role: \"activity\"` never reaches `listItems`, which builds rows for `user` and\n * `assistant` only. It follows the SHAPE of react-core's `messagesMemoKey`\n * (react-core #6325). The two are independent implementations of the same idea —\n * a change to that key does not propagate here on its own, so treat this as a\n * documented parallel rather than a mirror.\n */\nfunction messagesFingerprint(messages: readonly unknown[]): string {\n return messages\n .map((msg) => {\n const m = msg as {\n id?: string;\n role?: string;\n content?: unknown;\n toolCallId?: string;\n toolCalls?: Array<{ id: string; function?: { arguments?: string } }>;\n };\n const content = m.content;\n const contentKey =\n typeof content === \"string\" || Array.isArray(content)\n ? content.length\n : content && typeof content === \"object\"\n ? objectContentKey(content)\n : 0;\n const toolCallsKey = Array.isArray(m.toolCalls)\n ? m.toolCalls\n .map((tc) => `${tc.id}:${tc.function?.arguments?.length ?? 0}`)\n .join(\";\")\n : \"\";\n return `${m.id}:${m.role}:${contentKey}:${m.toolCallId ?? \"\"}:${toolCallsKey}`;\n })\n .join(\",\");\n}\n\n/**\n * Serializes object content for the fingerprint above.\n *\n * Guarded because `JSON.stringify` THROWS on a circular structure and\n * `messagesFingerprint` runs on EVERY render, so a bare call would take the whole\n * chat down on content this component is explicitly required to tolerate —\n * `toolResultContent` below documents why non-string content reaches RN at all,\n * and \"does not throw on tool content that cannot be JSON-serialised\" pins that a\n * circular tool result must still render.\n *\n * The fallback is a constant, which means a circular object is invisible to the\n * memo exactly as every object used to be. That is the correct trade: it confines\n * the old always-equal behaviour to the pathological case instead of letting it\n * decide the common one. NOTE: this guard is a deliberate divergence from\n * react-core's `messagesMemoKey`, which stringifies unguarded.\n */\nfunction objectContentKey(content: object): string {\n try {\n return JSON.stringify(content) ?? \"\";\n } catch {\n return \"[unserializable]\";\n }\n}\n\n/**\n * Coerces a tool message's `content` to the `string` the renderer contract\n * requires (`ReactToolCallRenderer`'s Complete branch declares `result: string`)\n * WITHOUT inventing an empty result.\n *\n * AG-UI 1.0 models tool content as `string | ContentPart[]`: a plain string, or\n * an ordered list of typed parts (text, image, audio, video, document). A\n * string passes through; a list of parts is rendered as its text parts\n * concatenated — the flattening the spec permits for a string-only consumer —\n * and the media parts stay on the message for anything that can show them.\n * Neither is malformed, so neither warns.\n *\n * Anything else is only reachable from a producer that skipped validation —\n * restored thread history, a non-SSE transport, or app code casting on\n * `addMessage`. Core hedges against that case too (it accepts `unknown` content\n * and handles arrays of text parts), so this must not answer it with `\"\"`: an\n * empty string is a LEGITIMATE tool result, which makes a dropped result\n * indistinguishable from an empty one. Serialise faithfully — the same\n * representation core uses for non-string results — and warn in dev.\n */\nconst MEDIA_PART_TYPES = new Set([\"image\", \"audio\", \"video\", \"document\"]);\n\n/**\n * Whether a value is one of the protocol's content parts: a text part with a\n * string `text`, or a media part with a `source` that names its kind and\n * value. Anything else — an array of typed records from restored history,\n * say — is not parts and keeps the serialise-and-warn path.\n */\nfunction isContentPart(part: unknown): boolean {\n if (typeof part !== \"object\" || part === null) return false;\n const record = part as { type?: unknown; text?: unknown; source?: unknown };\n if (record.type === \"text\") return typeof record.text === \"string\";\n if (typeof record.type !== \"string\" || !MEDIA_PART_TYPES.has(record.type))\n return false;\n const source = record.source as\n | { type?: unknown; value?: unknown; mimeType?: unknown }\n | undefined;\n if (typeof source !== \"object\" || source === null) return false;\n if (typeof source.value !== \"string\") return false;\n // Inline bytes need their type; a URL or a provider file handle (AG-UI 1.0\n // `file` source) may leave it out.\n if (source.type === \"data\") return typeof source.mimeType === \"string\";\n return (\n (source.type === \"url\" || source.type === \"file\") &&\n (source.mimeType === undefined || typeof source.mimeType === \"string\")\n );\n}\n\nfunction toolResultContent(content: unknown, toolCallId: string): string {\n if (typeof content === \"string\") return content;\n\n if (Array.isArray(content) && content.every(isContentPart)) {\n return contentToText(content as ToolMessage[\"content\"]);\n }\n\n // null/undefined carry no payload, so \"\" loses nothing — but the message is\n // still malformed, so it warns below rather than passing silently.\n let serialized = \"\";\n if (content !== null && content !== undefined) {\n try {\n serialized =\n JSON.stringify(content) ?? Object.prototype.toString.call(content);\n } catch {\n // Circular or otherwise non-serialisable: keep SOMETHING over dropping\n // the result, and never throw from a render path.\n serialized = Object.prototype.toString.call(content);\n }\n }\n\n if (typeof __DEV__ === \"undefined\" || __DEV__) {\n console.warn(\n `[CopilotChat] Tool message for tool call \"${toolCallId}\" had non-string ` +\n `content (${content === null ? \"null\" : typeof content}), but renderers ` +\n `receive \\`result: string\\`. Rendering a serialized form instead of ` +\n `dropping it: ${serialized === \"\" ? \"<empty>\" : serialized}`,\n );\n }\n\n return serialized;\n}\n\n/**\n * Full-screen chat UI component for React Native.\n *\n * Connects to a CopilotKit agent via `useAgent` and renders messages\n * using platform-appropriate AssistantMessage / UserMessage components.\n *\n * Usage:\n * ```tsx\n * <CopilotChat agentName=\"my-agent\" headerTitle=\"Assistant\" />\n * ```\n */\nexport function CopilotChat({\n agentName = \"default\",\n placeholder = \"Type a message...\",\n initialMessages = [],\n emptyStateTitle = \"How can I help?\",\n emptyStateSubtitle = \"Ask me anything or try a suggestion below.\",\n headerTitle = \"Chat\",\n showHeader = true,\n style,\n messageContainerStyle,\n inputContainerStyle,\n onSendMessage,\n FlatListComponent = FlatList,\n disableKeyboardAvoiding = false,\n}: CopilotChatProps) {\n const [inputText, setInputText] = useState(\"\");\n const [error, setError] = useState<string | null>(null);\n const flatListRef = useRef<FlatList>(null);\n const messageIdCounter = useRef(0);\n\n const { copilotkit } = useCopilotKit();\n const { agent } = useAgent({ agentId: agentName });\n\n const messages = agent.messages ?? [];\n const isRunning = agent.isRunning;\n\n const renderToolCall = useRenderToolCall();\n\n // useInterrupt publishes its element to core unless renderInChat is false.\n // Draw it after the last message, as the web message view does.\n const [interruptElement, setInterruptElement] =\n useState<React.ReactElement | null>(null);\n useEffect(() => {\n setInterruptElement(copilotkit.interruptElement);\n const subscription = copilotkit.subscribe({\n onInterruptElementChanged: ({ interruptElement: element }) => {\n setInterruptElement(element);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n // Recomputed every render — cheap, and the only honest dependency for the\n // message-derived memos below. See `messagesFingerprint` for why the array\n // reference cannot be trusted as one.\n const messagesKey = messagesFingerprint(messages);\n\n // toolCallId -> tool result message. react-core's renderer reports\n // status \"complete\" with `result` when a tool message exists; RN's chat\n // previously never correlated these, so `result` was always undefined.\n const toolMessages = useMemo(() => {\n const byId = new Map<string, ToolMessage>();\n for (const msg of messages) {\n const m = msg as {\n role?: string;\n id?: string;\n toolCallId?: string;\n content?: unknown;\n };\n if (m.role === \"tool\" && m.toolCallId) {\n byId.set(m.toolCallId, {\n id: m.id ?? m.toolCallId,\n role: \"tool\",\n toolCallId: m.toolCallId,\n content: toolResultContent(m.content, m.toolCallId),\n });\n }\n }\n return byId;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [messagesKey]);\n\n // Build flat list items from messages\n const listItems: ChatListItem[] = useMemo(() => {\n const items: ChatListItem[] = [];\n\n for (const msg of messages) {\n if (msg.role === \"user\") {\n items.push({\n id: msg.id,\n type: \"user\",\n content: typeof msg.content === \"string\" ? msg.content : \"\",\n });\n } else if (msg.role === \"assistant\") {\n const assistantMsg = msg as AssistantMessageShape;\n // Add text content if present\n if (assistantMsg.content) {\n items.push({\n id: msg.id,\n type: \"assistant\",\n content: assistantMsg.content,\n });\n }\n // Add tool calls if present\n if (assistantMsg.toolCalls && assistantMsg.toolCalls.length > 0) {\n for (const tc of assistantMsg.toolCalls) {\n items.push({\n id: `${msg.id}-tc-${tc.id}`,\n type: \"tool-call\",\n toolCalls: [tc],\n });\n }\n }\n }\n }\n\n // Show loading indicator when agent is running and the last message\n // is not already the assistant streaming\n if (isRunning) {\n const lastItem = items[items.length - 1];\n if (!lastItem || lastItem.type !== \"assistant\") {\n items.push({ id: \"__loading__\", type: \"loading\" });\n }\n }\n\n return items;\n // Same reasoning as `toolMessages`: keyed on message CONTENT, because the\n // array reference does not track content in either direction — core's\n // in-place `splice` and `addMessage`'s push leave it untouched, while the\n // AG-UI apply pipeline replaces it on every delta. Without this, an\n // assistant message or tool call appended mid-run never reaches the list.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [messagesKey, isRunning]);\n\n // Id of the trailing row. renderItem needs \"is this the last row?\" to place\n // the streaming indicator; deriving it here keeps that a named scalar instead\n // of renderItem closing over `listItems` and index-reading its tail.\n const lastItemId = useMemo(\n () => listItems[listItems.length - 1]?.id,\n [listItems],\n );\n\n // extraData defeats FlatList's PureComponent shallow-compare for the values\n // renderItem CLOSES OVER, as opposed to the ones it receives per row. Those\n // are exactly the four below, and they mirror renderItem's dependency array —\n // keep the two in sync. `listItems` is deliberately absent: renderItem's only\n // read of it is the tail id, now passed as `lastItemId`, and the array itself\n // is already the `data` prop, which invalidates cells on its own (every\n // rebuild allocates fresh item objects, so each cell's `item` prop differs).\n const extraData = useMemo(\n () => ({ isRunning, lastItemId, renderToolCall, toolMessages }),\n [isRunning, lastItemId, renderToolCall, toolMessages],\n );\n\n // Shared logic for sending a message to the agent\n const sendMessage = useCallback(\n async (text: string) => {\n if (!text || isRunning || !agent) return;\n\n setError(null);\n onSendMessage?.(text);\n\n const id = `user-${++messageIdCounter.current}`;\n agent.addMessage({\n id,\n role: \"user\",\n content: text,\n } as Message);\n\n try {\n await copilotkit.runAgent({ agent });\n } catch (err) {\n const message =\n err instanceof Error ? err.message : \"An unexpected error occurred\";\n console.error(\"[CopilotChat] runAgent failed:\", err);\n setError(message);\n }\n },\n [isRunning, agent, copilotkit, onSendMessage],\n );\n\n // Send from the input field\n const handleSend = useCallback(() => {\n const text = inputText.trim();\n if (!text) return;\n setInputText(\"\");\n void sendMessage(text);\n }, [inputText, sendMessage]);\n\n // Handle suggestion pill press\n const handleSuggestion = useCallback(\n (text: string) => {\n void sendMessage(text);\n },\n [sendMessage],\n );\n\n // Auto-scroll when content changes\n const handleContentSizeChange = useCallback(() => {\n flatListRef.current?.scrollToEnd({ animated: true });\n }, []);\n\n // Render a single list item\n const renderItem = useCallback(\n ({ item }: ListRenderItemInfo<ChatListItem>) => {\n if (item.type === \"user\") {\n return <UserMessage content={item.content ?? \"\"} />;\n }\n\n if (item.type === \"assistant\") {\n return (\n <AssistantMessage\n content={item.content ?? \"\"}\n isLoading={isRunning && item.id === lastItemId}\n />\n );\n }\n\n if (item.type === \"tool-call\" && item.toolCalls) {\n const tc = item.toolCalls[0];\n // Partial-parses streaming args, resolves the renderer (exact name ->\n // agent-scoped -> wildcard \"*\") and derives status — all in react-core,\n // shared with web. Returns ReactElement | null, which is what\n // renderItem requires.\n const rendered = renderToolCall({\n toolCall: tc,\n toolMessage: toolMessages.get(tc.id),\n });\n if (rendered) return <>{rendered}</>;\n\n // Subtle indicator for unregistered tool calls\n return (\n <View style={styles.toolCallIndicator}>\n <Text style={styles.toolCallText}>Called: {tc.function.name}</Text>\n </View>\n );\n }\n\n if (item.type === \"loading\") {\n return <AssistantMessage content=\"\" isLoading />;\n }\n\n return null;\n },\n [isRunning, lastItemId, renderToolCall, toolMessages],\n );\n\n const keyExtractor = useCallback((item: ChatListItem) => item.id, []);\n\n // Empty state component\n const emptyComponent = useMemo(\n () => (\n <View style={styles.emptyState}>\n <Text style={styles.emptyTitle}>{emptyStateTitle}</Text>\n <Text style={styles.emptySubtitle}>{emptyStateSubtitle}</Text>\n {initialMessages.map((suggestion, i) => (\n <Pressable\n key={`suggestion-${i}`}\n style={styles.suggestionPill}\n onPress={() => handleSuggestion(suggestion)}\n >\n <Text style={styles.suggestionText}>{suggestion}</Text>\n </Pressable>\n ))}\n </View>\n ),\n [emptyStateTitle, emptyStateSubtitle, initialMessages, handleSuggestion],\n );\n\n const sendDisabled = !inputText.trim() || isRunning;\n\n const content = (\n <>\n {showHeader && (\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n </View>\n )}\n\n <FlatListComponent\n ref={flatListRef}\n data={listItems}\n renderItem={renderItem}\n keyExtractor={keyExtractor}\n extraData={extraData}\n contentContainerStyle={[styles.messageList, messageContainerStyle]}\n onContentSizeChange={handleContentSizeChange}\n ListEmptyComponent={emptyComponent}\n ListFooterComponent={interruptElement}\n />\n\n {error && (\n <View style={styles.errorContainer} testID=\"error-message\">\n <Text style={styles.errorText}>{error}</Text>\n </View>\n )}\n\n <View style={[styles.inputContainer, inputContainerStyle]}>\n <TextInput\n style={styles.input}\n value={inputText}\n onChangeText={setInputText}\n placeholder={placeholder}\n placeholderTextColor=\"#999\"\n multiline\n numberOfLines={4}\n returnKeyType=\"send\"\n onSubmitEditing={handleSend}\n />\n <TouchableOpacity\n style={[styles.sendButton, sendDisabled && styles.sendButtonDisabled]}\n onPress={handleSend}\n disabled={sendDisabled}\n testID=\"send-button\"\n >\n <Text style={styles.sendButtonIcon}>{\"↑\"}</Text>\n </TouchableOpacity>\n </View>\n </>\n );\n\n if (disableKeyboardAvoiding) {\n return <View style={[styles.container, style]}>{content}</View>;\n }\n\n return (\n <KeyboardAvoidingView\n style={[styles.container, style]}\n behavior={Platform.OS === \"ios\" ? \"padding\" : \"height\"}\n keyboardVerticalOffset={0}\n >\n {content}\n </KeyboardAvoidingView>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n backgroundColor: \"#FFFFFF\",\n },\n header: {\n height: 56,\n justifyContent: \"center\",\n alignItems: \"center\",\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#E0E0E0\",\n backgroundColor: \"#FFFFFF\",\n },\n headerTitle: {\n fontSize: 17,\n fontWeight: \"600\",\n color: \"#1A1A1A\",\n },\n messageList: {\n paddingHorizontal: 16,\n flexGrow: 1,\n },\n inputContainer: {\n flexDirection: \"row\",\n alignItems: \"flex-end\",\n paddingHorizontal: 8,\n paddingVertical: 8,\n borderTopWidth: StyleSheet.hairlineWidth,\n borderTopColor: \"#E0E0E0\",\n backgroundColor: \"#FFFFFF\",\n },\n input: {\n flex: 1,\n backgroundColor: \"#F5F5F5\",\n borderRadius: 20,\n paddingHorizontal: 12,\n paddingVertical: 8,\n fontSize: 15,\n maxHeight: 100,\n color: \"#1A1A1A\",\n },\n sendButton: {\n width: 36,\n height: 36,\n borderRadius: 18,\n backgroundColor: \"#0066CC\",\n justifyContent: \"center\",\n alignItems: \"center\",\n marginLeft: 8,\n },\n sendButtonDisabled: {\n opacity: 0.4,\n },\n sendButtonIcon: {\n color: \"#FFFFFF\",\n fontSize: 18,\n fontWeight: \"700\",\n },\n emptyState: {\n flex: 1,\n justifyContent: \"center\",\n alignItems: \"center\",\n paddingTop: 100,\n gap: 12,\n },\n emptyTitle: {\n fontSize: 22,\n fontWeight: \"700\",\n color: \"#1A1A1A\",\n marginBottom: 4,\n },\n emptySubtitle: {\n fontSize: 15,\n color: \"#666666\",\n marginBottom: 16,\n },\n suggestionPill: {\n backgroundColor: \"#E8F0FE\",\n borderRadius: 20,\n paddingHorizontal: 16,\n paddingVertical: 10,\n },\n suggestionText: {\n color: \"#0066CC\",\n fontWeight: \"600\",\n fontSize: 14,\n },\n toolCallIndicator: {\n alignSelf: \"flex-start\",\n backgroundColor: \"#F0F0F0\",\n borderRadius: 12,\n paddingHorizontal: 12,\n paddingVertical: 6,\n marginBottom: 8,\n },\n toolCallText: {\n fontSize: 12,\n color: \"#999999\",\n fontStyle: \"italic\",\n },\n errorContainer: {\n backgroundColor: \"#FEE2E2\",\n paddingHorizontal: 12,\n paddingVertical: 8,\n marginHorizontal: 8,\n borderRadius: 8,\n },\n errorText: {\n color: \"#DC2626\",\n fontSize: 13,\n },\n});\n","/**\n * CopilotModal — a bottom-sheet chat overlay for React Native.\n *\n * Mobile equivalent of CopilotPopup on web. Wraps CopilotChat inside\n * @gorhom/bottom-sheet so the chat can slide up over any screen.\n */\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n} from \"react\";\nimport { StyleSheet } from \"react-native\";\nimport BottomSheet, {\n BottomSheetBackdrop,\n BottomSheetFlatList,\n BottomSheetView,\n} from \"@gorhom/bottom-sheet\";\nimport type { BottomSheetBackdropProps } from \"@gorhom/bottom-sheet\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatProps } from \"./CopilotChat\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CopilotModalProps {\n /** Controlled visibility — when true the sheet opens, when false it closes. */\n visible?: boolean;\n\n /** Called when the sheet is dismissed (via backdrop tap, swipe-down, or close()). */\n onDismiss?: () => void;\n\n /**\n * Bottom-sheet snap points.\n * @default ['50%', '90%']\n */\n snapPoints?: (string | number)[];\n\n /**\n * Which snap-point index to open at.\n * @default 0\n */\n initialSnapIndex?: number;\n\n /**\n * Whether closing the sheet fires onDismiss.\n * @default true\n */\n enableDismissOnClose?: boolean;\n\n /**\n * Backdrop opacity when the sheet is open.\n * @default 0.5\n */\n backdropOpacity?: number;\n\n // -- Pass-through to CopilotChat ------------------------------------------\n\n /** Which agent to connect to. */\n agentName?: string;\n\n /** Input placeholder text. */\n placeholder?: string;\n\n /** Seed messages shown on first render. */\n initialMessages?: string[];\n\n /** Title shown in the CopilotChat header area. */\n headerTitle?: string;\n}\n\n/** Imperative handle exposed via ref. */\nexport interface CopilotModalRef {\n /** Programmatically open the bottom sheet. */\n open: () => void;\n /** Programmatically close the bottom sheet. */\n close: () => void;\n}\n\n// ---------------------------------------------------------------------------\n// Component\n// ---------------------------------------------------------------------------\n\nexport const CopilotModal = forwardRef<CopilotModalRef, CopilotModalProps>(\n function CopilotModal(\n {\n visible,\n onDismiss,\n snapPoints: snapPointsProp,\n initialSnapIndex = 0,\n enableDismissOnClose = true,\n backdropOpacity = 0.5,\n agentName,\n placeholder,\n initialMessages,\n headerTitle,\n },\n ref,\n ) {\n const bottomSheetRef = useRef<BottomSheet>(null);\n\n // Stable snap-points array\n const snapPoints = useMemo(\n () => snapPointsProp ?? [\"50%\", \"90%\"],\n [snapPointsProp],\n );\n\n // ── Imperative API ────────────────────────────────────────────────────\n useImperativeHandle(\n ref,\n () => ({\n open() {\n bottomSheetRef.current?.snapToIndex(initialSnapIndex);\n },\n close() {\n bottomSheetRef.current?.close();\n },\n }),\n [initialSnapIndex],\n );\n\n // ── Controlled visibility ─────────────────────────────────────────────\n useEffect(() => {\n if (visible === undefined) return;\n if (visible) {\n bottomSheetRef.current?.snapToIndex(initialSnapIndex);\n } else {\n bottomSheetRef.current?.close();\n }\n }, [visible, initialSnapIndex]);\n\n // ── Backdrop renderer ─────────────────────────────────────────────────\n const renderBackdrop = useCallback(\n (props: BottomSheetBackdropProps) => (\n <BottomSheetBackdrop\n {...props}\n disappearsOnIndex={-1}\n appearsOnIndex={0}\n opacity={backdropOpacity}\n pressBehavior=\"close\"\n />\n ),\n [backdropOpacity],\n );\n\n // ── Sheet close handler ───────────────────────────────────────────────\n const handleClose = useCallback(() => {\n if (enableDismissOnClose) {\n onDismiss?.();\n }\n }, [enableDismissOnClose, onDismiss]);\n\n // ── Build CopilotChat props ───────────────────────────────────────────\n const chatProps = useMemo(() => {\n const props: Partial<CopilotChatProps> = {};\n if (agentName !== undefined) props.agentName = agentName;\n if (placeholder !== undefined) props.placeholder = placeholder;\n if (initialMessages !== undefined)\n props.initialMessages = initialMessages;\n if (headerTitle !== undefined) props.headerTitle = headerTitle;\n return props;\n }, [agentName, placeholder, initialMessages, headerTitle]);\n\n return (\n <BottomSheet\n ref={bottomSheetRef}\n index={-1}\n snapPoints={snapPoints}\n enablePanDownToClose\n backdropComponent={renderBackdrop}\n onClose={handleClose}\n keyboardBehavior=\"interactive\"\n keyboardBlurBehavior=\"restore\"\n backgroundStyle={styles.sheetBackground}\n handleIndicatorStyle={styles.handleIndicator}\n >\n <BottomSheetView style={styles.contentContainer}>\n <CopilotChat\n {...chatProps}\n FlatListComponent={BottomSheetFlatList}\n disableKeyboardAvoiding\n />\n </BottomSheetView>\n </BottomSheet>\n );\n },\n);\n\n// ---------------------------------------------------------------------------\n// Styles\n// ---------------------------------------------------------------------------\n\nconst styles = StyleSheet.create({\n sheetBackground: {\n backgroundColor: \"#FFFFFF\",\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n },\n handleIndicator: {\n width: 40,\n height: 4,\n backgroundColor: \"#DDDDDD\",\n },\n contentContainer: {\n flex: 1,\n },\n});\n"],"mappings":";;;;;;;;;;;;;;AAYA,MAAM,WAAW;AACjB,MAAM,cAAc;AACpB,MAAM,qBAAqB;;;;;;;AAQ3B,SAAgB,gBAAgB,EAAE,SAA+B;CAC/D,MAAM,CAAC,kCAAu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D,CAAC,iBAAiB,CACnB;AAGD,4BAAgB;AACd,MAAI,YAAY,OAAW;AAC3B,MAAI,QACF,gBAAe,SAAS,YAAY,iBAAiB;MAErD,gBAAe,SAAS,OAAO;IAEhC,CAAC,SAAS,iBAAiB,CAAC;CAG/B,MAAM,yCACH,UACC,2CAACC;EACC,GAAI;EACJ,mBAAmB;EACnB,gBAAgB;EAChB,SAAS;EACT,eAAc;GACd,EAEJ,CAAC,gBAAgB,CAClB;CAGD,MAAM,2CAAgC;AACpC,MAAI,qBACF,cAAa;IAEd,CAAC,sBAAsB,UAAU,CAAC;CAGrC,MAAM,qCAA0B;EAC9B,MAAM,QAAmC,EAAE;AAC3C,MAAI,cAAc,OAAW,OAAM,YAAY;AAC/C,MAAI,gBAAgB,OAAW,OAAM,cAAc;AACnD,MAAI,oBAAoB,OACtB,OAAM,kBAAkB;AAC1B,MAAI,gBAAgB,OAAW,OAAM,cAAc;AACnD,SAAO;IACN;EAAC;EAAW;EAAa;EAAiB;EAAY,CAAC;AAE1D,QACE,2CAACC;EACC,KAAK;EACL,OAAO;EACK;EACZ;EACA,mBAAmB;EACnB,SAAS;EACT,kBAAiB;EACjB,sBAAqB;EACrB,iBAAiB,OAAO;EACxB,sBAAsB,OAAO;YAE7B,2CAACC;GAAgB,OAAO,OAAO;aAC7B,2CAAC;IACC,GAAI;IACJ,mBAAmBC;IACnB;KACA;IACc;GACN;EAGnB;AAMD,MAAM,SAASC,wBAAW,OAAO;CAC/B,iBAAiB;EACf,iBAAiB;EACjB,qBAAqB;EACrB,sBAAsB;EACvB;CACD,iBAAiB;EACf,OAAO;EACP,QAAQ;EACR,iBAAiB;EAClB;CACD,kBAAkB,EAChB,MAAM,GACP;CACF,CAAC"}
|
|
@@ -19,9 +19,9 @@ const ANIMATION_DURATION = 400;
|
|
|
19
19
|
* Uses React Native's built-in `Animated` API (no Reanimated dependency).
|
|
20
20
|
*/
|
|
21
21
|
function TypingIndicator({ style }) {
|
|
22
|
-
const dot1 =
|
|
23
|
-
const dot2 =
|
|
24
|
-
const dot3 =
|
|
22
|
+
const [dot1] = useState(() => new Animated.Value(0));
|
|
23
|
+
const [dot2] = useState(() => new Animated.Value(0));
|
|
24
|
+
const [dot3] = useState(() => new Animated.Value(0));
|
|
25
25
|
useEffect(() => {
|
|
26
26
|
const createPulse = (dot, delay) => Animated.sequence([Animated.delay(delay), Animated.loop(Animated.sequence([Animated.timing(dot, {
|
|
27
27
|
toValue: 1,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["styles","TIMESTAMP_COLOR","styles","styles","styles"],"sources":["../../src/components/messages/TypingIndicator.tsx","../../src/components/messages/utils.ts","../../src/components/messages/AssistantMessage.tsx","../../src/components/messages/UserMessage.tsx","../../src/components/CopilotChat.tsx","../../src/components/CopilotModal.tsx"],"sourcesContent":["import React, { useEffect, useRef } from \"react\";\nimport { View, Animated, StyleSheet } from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\n\n/**\n * Props for the TypingIndicator component.\n */\nexport interface TypingIndicatorProps {\n /** Optional style override for the container */\n style?: ViewStyle;\n}\n\nconst DOT_SIZE = 6;\nconst DOT_SPACING = 4;\nconst ANIMATION_DURATION = 400;\n\n/**\n * Three animated dots that pulse in sequence, suitable for embedding\n * inside an AssistantMessage to indicate the AI is still generating.\n *\n * Uses React Native's built-in `Animated` API (no Reanimated dependency).\n */\nexport function TypingIndicator({ style }: TypingIndicatorProps) {\n const dot1 = useRef(new Animated.Value(0)).current;\n const dot2 = useRef(new Animated.Value(0)).current;\n const dot3 = useRef(new Animated.Value(0)).current;\n\n useEffect(() => {\n const createPulse = (dot: Animated.Value, delay: number) =>\n Animated.sequence([\n Animated.delay(delay),\n Animated.loop(\n Animated.sequence([\n Animated.timing(dot, {\n toValue: 1,\n duration: ANIMATION_DURATION,\n useNativeDriver: true,\n }),\n Animated.timing(dot, {\n toValue: 0,\n duration: ANIMATION_DURATION,\n useNativeDriver: true,\n }),\n ]),\n ),\n ]);\n\n const animation = Animated.parallel([\n createPulse(dot1, 0),\n createPulse(dot2, ANIMATION_DURATION * 0.33),\n createPulse(dot3, ANIMATION_DURATION * 0.66),\n ]);\n\n animation.start();\n\n return () => {\n animation.stop();\n };\n }, [dot1, dot2, dot3]);\n\n const dotStyle = (animatedValue: Animated.Value) => ({\n ...styles.dot,\n opacity: animatedValue.interpolate({\n inputRange: [0, 1],\n outputRange: [0.3, 1],\n }),\n transform: [\n {\n scale: animatedValue.interpolate({\n inputRange: [0, 1],\n outputRange: [0.8, 1.2],\n }),\n },\n ],\n });\n\n return (\n <View\n testID=\"copilot-loading-cursor\"\n style={[styles.container, style]}\n accessibilityLabel=\"Typing indicator\"\n accessibilityRole=\"text\"\n >\n <Animated.View style={dotStyle(dot1)} />\n <Animated.View style={dotStyle(dot2)} />\n <Animated.View style={dotStyle(dot3)} />\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flexDirection: \"row\",\n alignItems: \"center\",\n paddingVertical: 4,\n paddingHorizontal: 2,\n },\n dot: {\n width: DOT_SIZE,\n height: DOT_SIZE,\n borderRadius: DOT_SIZE / 2,\n backgroundColor: \"#999999\",\n marginHorizontal: DOT_SPACING / 2,\n },\n});\n","/**\n * Format a Date as a 12-hour time string (e.g. \"2:05 PM\").\n */\nexport function formatTimestamp(date: Date): string {\n const hours = date.getHours();\n const minutes = date.getMinutes();\n const ampm = hours >= 12 ? \"PM\" : \"AM\";\n const displayHours = hours % 12 || 12;\n const displayMinutes = minutes.toString().padStart(2, \"0\");\n return `${displayHours}:${displayMinutes} ${ampm}`;\n}\n","import React from \"react\";\nimport { View, Text, StyleSheet } from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotMarkdown } from \"../Markdown\";\nimport {\n useMarkdownRenderer,\n isNativeComponentRenderer,\n} from \"../MarkdownRendererContext\";\nimport { TypingIndicator } from \"./TypingIndicator\";\nimport { formatTimestamp } from \"./utils\";\n\n// ─── Colors ──────────────────────────────────────────────────────────────────\nconst ASSISTANT_BUBBLE_BG = \"#F0F0F0\";\nconst ASSISTANT_TEXT_COLOR = \"#1A1A1A\";\nconst TIMESTAMP_COLOR = \"#999999\";\n\n/**\n * Props for the AssistantMessage component.\n */\nexport interface AssistantMessageProps {\n /** Markdown content to render inside the bubble */\n content: string;\n /** When true, shows a typing indicator below any content */\n isLoading?: boolean;\n /** Optional timestamp displayed below the bubble */\n timestamp?: Date;\n /** Optional style override for the outer container */\n style?: ViewStyle;\n}\n\n/**\n * Left-aligned chat bubble for AI assistant responses.\n *\n * Renders markdown content via `CopilotMarkdown` and shows an animated\n * typing indicator when `isLoading` is true.\n */\nexport function AssistantMessage({\n content,\n isLoading = false,\n timestamp,\n style,\n}: AssistantMessageProps) {\n // Honor a provider-level markdown renderer (CopilotKitProvider's\n // `markdownRenderer` prop), falling back to the built-in CopilotMarkdown.\n // This is the React Native arm of the slot -> provider -> built-in\n // resolution order documented in the migration guide.\n const provided = useMarkdownRenderer();\n return (\n <View style={[styles.container, style]}>\n <View style={styles.bubble}>\n {content ? (\n isNativeComponentRenderer(provided) ? (\n React.createElement(provided, { content, isStreaming: isLoading })\n ) : provided ? (\n <CopilotMarkdown\n content={content}\n style={provided.style}\n streamingAnimation={provided.animate}\n />\n ) : (\n <CopilotMarkdown content={content} />\n )\n ) : null}\n {isLoading ? <TypingIndicator /> : null}\n </View>\n {timestamp && (\n <Text style={styles.timestamp}>{formatTimestamp(timestamp)}</Text>\n )}\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n alignItems: \"flex-start\",\n marginVertical: 4,\n paddingHorizontal: 12,\n },\n bubble: {\n backgroundColor: ASSISTANT_BUBBLE_BG,\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n borderBottomRightRadius: 16,\n borderBottomLeftRadius: 4,\n paddingHorizontal: 12,\n paddingVertical: 8,\n maxWidth: \"80%\",\n },\n timestamp: {\n color: TIMESTAMP_COLOR,\n fontSize: 11,\n marginTop: 2,\n marginLeft: 4,\n },\n});\n","import React from \"react\";\nimport { View, Text, StyleSheet, type ViewStyle } from \"react-native\";\nimport { formatTimestamp } from \"./utils\";\n\n// ─── Colors ──────────────────────────────────────────────────────────────────\nconst USER_BUBBLE_BG = \"#0066CC\";\nconst USER_TEXT_COLOR = \"#FFFFFF\";\nconst TIMESTAMP_COLOR = \"#999999\";\n\n/**\n * Props for the UserMessage component.\n */\nexport interface UserMessageProps {\n /** Plain text content to display */\n content: string;\n /** Optional timestamp displayed below the bubble */\n timestamp?: Date;\n /** Optional style override for the outer container */\n style?: ViewStyle;\n}\n\n/**\n * Right-aligned chat bubble for user messages.\n *\n * Renders plain text (no markdown) with a primary-color background\n * and white text. Optionally displays a subtle timestamp below.\n */\nexport function UserMessage({ content, timestamp, style }: UserMessageProps) {\n return (\n <View style={[styles.container, style]}>\n <View style={styles.bubble}>\n <Text style={styles.text}>{content}</Text>\n </View>\n {timestamp && (\n <Text style={styles.timestamp}>{formatTimestamp(timestamp)}</Text>\n )}\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n alignItems: \"flex-end\",\n marginVertical: 4,\n paddingHorizontal: 12,\n },\n bubble: {\n backgroundColor: USER_BUBBLE_BG,\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n borderBottomLeftRadius: 16,\n borderBottomRightRadius: 4,\n paddingHorizontal: 12,\n paddingVertical: 8,\n maxWidth: \"80%\",\n },\n text: {\n color: USER_TEXT_COLOR,\n fontSize: 16,\n lineHeight: 22,\n },\n timestamp: {\n color: TIMESTAMP_COLOR,\n fontSize: 11,\n marginTop: 2,\n marginRight: 4,\n },\n});\n","import React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport {\n FlatList,\n KeyboardAvoidingView,\n Platform,\n Pressable,\n StyleSheet,\n Text,\n TextInput,\n TouchableOpacity,\n View,\n} from \"react-native\";\nimport type { ListRenderItemInfo, ViewStyle } from \"react-native\";\nimport { useAgent, useRenderToolCall } from \"@copilotkit/react-core/headless\";\nimport { useCopilotKit } from \"@copilotkit/react-core/context\";\nimport { AssistantMessage } from \"./messages/AssistantMessage\";\nimport { UserMessage } from \"./messages/UserMessage\";\nimport type { Message } from \"@copilotkit/shared\";\nimport type { ToolMessage } from \"@ag-ui/client\";\nimport { contentToText } from \"@ag-ui/client\";\n\n/** Shape of an assistant message with optional tool calls. */\ninterface AssistantMessageShape {\n id: string;\n role: \"assistant\";\n content?: string;\n toolCalls?: Array<{\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n }>;\n}\n\nexport interface CopilotChatProps {\n /** Agent ID to connect to. Defaults to 'default'. */\n agentName?: string;\n /** Placeholder text for the input field. */\n placeholder?: string;\n /** Suggestion pills shown in the empty state. */\n initialMessages?: string[];\n /** Title shown when there are no messages. */\n emptyStateTitle?: string;\n /** Subtitle shown when there are no messages. */\n emptyStateSubtitle?: string;\n /** Title for the optional header bar. */\n headerTitle?: string;\n /** Whether to show the header bar. Defaults to true. */\n showHeader?: boolean;\n /** Style override for the outermost container. */\n style?: ViewStyle;\n /** Style override for the message list container. */\n messageContainerStyle?: ViewStyle;\n /** Style override for the input bar container. */\n inputContainerStyle?: ViewStyle;\n /** Callback fired when the user sends a message. */\n onSendMessage?: (text: string) => void;\n /** Custom FlatList component (e.g. BottomSheetFlatList for use inside a bottom sheet). */\n FlatListComponent?: React.ComponentType<any>;\n /** When true, skip the KeyboardAvoidingView wrapper (useful when a parent already handles keyboard). */\n disableKeyboardAvoiding?: boolean;\n}\n\ninterface ChatListItem {\n id: string;\n type: \"user\" | \"assistant\" | \"tool-call\" | \"loading\";\n content?: string;\n toolCalls?: Array<{\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n }>;\n}\n\n/**\n * Lightweight content fingerprint for an agent's message list.\n *\n * The identity of `agent.messages` is NOT a reliable change signal, and it fails\n * in BOTH directions:\n *\n * - It changes on paths that have nothing to do with what is read below.\n * `@ag-ui/client`'s apply pipeline REASSIGNS the array\n * (`AbstractAgent.processApplyEvents` does `this.messages = applied.messages`),\n * so a streaming run hands down a fresh array — and fresh message, `toolCall`\n * and `function` objects — on every applied delta.\n * - It does NOT change on the paths these memos exist to serve. Core inserts\n * tool results by mutating in place —\n * `agent.messages.splice(insertAt, 0, toolMessage)`\n * (packages/core/src/core/run-handler.ts:931, :1080) —\n * `AbstractAgent.addMessage` is a `this.messages.push(...)`, and `useAgent`\n * re-renders with a bare `forceUpdate()` rather than a new array.\n *\n * (Grepping `packages/core/src` for a `.messages` assignment finds test files\n * only, but that proves nothing about identity: the reassignment lives in\n * `@ag-ui/client`, outside that tree.)\n *\n * So anything derived from messages must depend on their CONTENT, not on the\n * array reference.\n *\n * Captures exactly what the derivations below read — id, role, content size,\n * `toolCallId` (so an inserted tool result is visible), and each tool call's id\n * plus argument length (so streaming args advance).\n *\n * String and array content contribute their LENGTH rather than their value, so\n * large text and base64 attachment payloads are never re-serialized on every\n * render. Object content is the deliberate exception and IS serialized: a\n * length-based key is a constant 0 for every object, so an in-place content\n * replacement that keeps the same message id would otherwise be invisible to\n * every memo below.\n *\n * That object branch is convergence, not a fix for a reachable stale render: the\n * producer of same-id object content is an ACTIVITY_SNAPSHOT replace, and\n * `role: \"activity\"` never reaches `listItems`, which builds rows for `user` and\n * `assistant` only. It follows the SHAPE of react-core's `messagesMemoKey`\n * (react-core #6325). The two are independent implementations of the same idea —\n * a change to that key does not propagate here on its own, so treat this as a\n * documented parallel rather than a mirror.\n */\nfunction messagesFingerprint(messages: readonly unknown[]): string {\n return messages\n .map((msg) => {\n const m = msg as {\n id?: string;\n role?: string;\n content?: unknown;\n toolCallId?: string;\n toolCalls?: Array<{ id: string; function?: { arguments?: string } }>;\n };\n const content = m.content;\n const contentKey =\n typeof content === \"string\" || Array.isArray(content)\n ? content.length\n : content && typeof content === \"object\"\n ? objectContentKey(content)\n : 0;\n const toolCallsKey = Array.isArray(m.toolCalls)\n ? m.toolCalls\n .map((tc) => `${tc.id}:${tc.function?.arguments?.length ?? 0}`)\n .join(\";\")\n : \"\";\n return `${m.id}:${m.role}:${contentKey}:${m.toolCallId ?? \"\"}:${toolCallsKey}`;\n })\n .join(\",\");\n}\n\n/**\n * Serializes object content for the fingerprint above.\n *\n * Guarded because `JSON.stringify` THROWS on a circular structure and\n * `messagesFingerprint` runs on EVERY render, so a bare call would take the whole\n * chat down on content this component is explicitly required to tolerate —\n * `toolResultContent` below documents why non-string content reaches RN at all,\n * and \"does not throw on tool content that cannot be JSON-serialised\" pins that a\n * circular tool result must still render.\n *\n * The fallback is a constant, which means a circular object is invisible to the\n * memo exactly as every object used to be. That is the correct trade: it confines\n * the old always-equal behaviour to the pathological case instead of letting it\n * decide the common one. NOTE: this guard is a deliberate divergence from\n * react-core's `messagesMemoKey`, which stringifies unguarded.\n */\nfunction objectContentKey(content: object): string {\n try {\n return JSON.stringify(content) ?? \"\";\n } catch {\n return \"[unserializable]\";\n }\n}\n\n/**\n * Coerces a tool message's `content` to the `string` the renderer contract\n * requires (`ReactToolCallRenderer`'s Complete branch declares `result: string`)\n * WITHOUT inventing an empty result.\n *\n * AG-UI 1.0 models tool content as `string | ContentPart[]`: a plain string, or\n * an ordered list of typed parts (text, image, audio, video, document). A\n * string passes through; a list of parts is rendered as its text parts\n * concatenated — the flattening the spec permits for a string-only consumer —\n * and the media parts stay on the message for anything that can show them.\n * Neither is malformed, so neither warns.\n *\n * Anything else is only reachable from a producer that skipped validation —\n * restored thread history, a non-SSE transport, or app code casting on\n * `addMessage`. Core hedges against that case too (it accepts `unknown` content\n * and handles arrays of text parts), so this must not answer it with `\"\"`: an\n * empty string is a LEGITIMATE tool result, which makes a dropped result\n * indistinguishable from an empty one. Serialise faithfully — the same\n * representation core uses for non-string results — and warn in dev.\n */\nconst MEDIA_PART_TYPES = new Set([\"image\", \"audio\", \"video\", \"document\"]);\n\n/**\n * Whether a value is one of the protocol's content parts: a text part with a\n * string `text`, or a media part with a `source` that names its kind and\n * value. Anything else — an array of typed records from restored history,\n * say — is not parts and keeps the serialise-and-warn path.\n */\nfunction isContentPart(part: unknown): boolean {\n if (typeof part !== \"object\" || part === null) return false;\n const record = part as { type?: unknown; text?: unknown; source?: unknown };\n if (record.type === \"text\") return typeof record.text === \"string\";\n if (typeof record.type !== \"string\" || !MEDIA_PART_TYPES.has(record.type))\n return false;\n const source = record.source as\n | { type?: unknown; value?: unknown; mimeType?: unknown }\n | undefined;\n if (typeof source !== \"object\" || source === null) return false;\n if (typeof source.value !== \"string\") return false;\n // Inline bytes need their type; a URL or a provider file handle (AG-UI 1.0\n // `file` source) may leave it out.\n if (source.type === \"data\") return typeof source.mimeType === \"string\";\n return (\n (source.type === \"url\" || source.type === \"file\") &&\n (source.mimeType === undefined || typeof source.mimeType === \"string\")\n );\n}\n\nfunction toolResultContent(content: unknown, toolCallId: string): string {\n if (typeof content === \"string\") return content;\n\n if (Array.isArray(content) && content.every(isContentPart)) {\n return contentToText(content as ToolMessage[\"content\"]);\n }\n\n // null/undefined carry no payload, so \"\" loses nothing — but the message is\n // still malformed, so it warns below rather than passing silently.\n let serialized = \"\";\n if (content !== null && content !== undefined) {\n try {\n serialized =\n JSON.stringify(content) ?? Object.prototype.toString.call(content);\n } catch {\n // Circular or otherwise non-serialisable: keep SOMETHING over dropping\n // the result, and never throw from a render path.\n serialized = Object.prototype.toString.call(content);\n }\n }\n\n if (typeof __DEV__ === \"undefined\" || __DEV__) {\n console.warn(\n `[CopilotChat] Tool message for tool call \"${toolCallId}\" had non-string ` +\n `content (${content === null ? \"null\" : typeof content}), but renderers ` +\n `receive \\`result: string\\`. Rendering a serialized form instead of ` +\n `dropping it: ${serialized === \"\" ? \"<empty>\" : serialized}`,\n );\n }\n\n return serialized;\n}\n\n/**\n * Full-screen chat UI component for React Native.\n *\n * Connects to a CopilotKit agent via `useAgent` and renders messages\n * using platform-appropriate AssistantMessage / UserMessage components.\n *\n * Usage:\n * ```tsx\n * <CopilotChat agentName=\"my-agent\" headerTitle=\"Assistant\" />\n * ```\n */\nexport function CopilotChat({\n agentName = \"default\",\n placeholder = \"Type a message...\",\n initialMessages = [],\n emptyStateTitle = \"How can I help?\",\n emptyStateSubtitle = \"Ask me anything or try a suggestion below.\",\n headerTitle = \"Chat\",\n showHeader = true,\n style,\n messageContainerStyle,\n inputContainerStyle,\n onSendMessage,\n FlatListComponent = FlatList,\n disableKeyboardAvoiding = false,\n}: CopilotChatProps) {\n const [inputText, setInputText] = useState(\"\");\n const [error, setError] = useState<string | null>(null);\n const flatListRef = useRef<FlatList>(null);\n const messageIdCounter = useRef(0);\n\n const { copilotkit } = useCopilotKit();\n const { agent } = useAgent({ agentId: agentName });\n\n const messages = agent.messages ?? [];\n const isRunning = agent.isRunning;\n\n const renderToolCall = useRenderToolCall();\n\n // useInterrupt publishes its element to core unless renderInChat is false.\n // Draw it after the last message, as the web message view does.\n const [interruptElement, setInterruptElement] =\n useState<React.ReactElement | null>(null);\n useEffect(() => {\n setInterruptElement(copilotkit.interruptElement);\n const subscription = copilotkit.subscribe({\n onInterruptElementChanged: ({ interruptElement: element }) => {\n setInterruptElement(element);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n // Recomputed every render — cheap, and the only honest dependency for the\n // message-derived memos below. See `messagesFingerprint` for why the array\n // reference cannot be trusted as one.\n const messagesKey = messagesFingerprint(messages);\n\n // toolCallId -> tool result message. react-core's renderer reports\n // status \"complete\" with `result` when a tool message exists; RN's chat\n // previously never correlated these, so `result` was always undefined.\n const toolMessages = useMemo(() => {\n const byId = new Map<string, ToolMessage>();\n for (const msg of messages) {\n const m = msg as {\n role?: string;\n id?: string;\n toolCallId?: string;\n content?: unknown;\n };\n if (m.role === \"tool\" && m.toolCallId) {\n byId.set(m.toolCallId, {\n id: m.id ?? m.toolCallId,\n role: \"tool\",\n toolCallId: m.toolCallId,\n content: toolResultContent(m.content, m.toolCallId),\n });\n }\n }\n return byId;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [messagesKey]);\n\n // Build flat list items from messages\n const listItems: ChatListItem[] = useMemo(() => {\n const items: ChatListItem[] = [];\n\n for (const msg of messages) {\n if (msg.role === \"user\") {\n items.push({\n id: msg.id,\n type: \"user\",\n content: typeof msg.content === \"string\" ? msg.content : \"\",\n });\n } else if (msg.role === \"assistant\") {\n const assistantMsg = msg as AssistantMessageShape;\n // Add text content if present\n if (assistantMsg.content) {\n items.push({\n id: msg.id,\n type: \"assistant\",\n content: assistantMsg.content,\n });\n }\n // Add tool calls if present\n if (assistantMsg.toolCalls && assistantMsg.toolCalls.length > 0) {\n for (const tc of assistantMsg.toolCalls) {\n items.push({\n id: `${msg.id}-tc-${tc.id}`,\n type: \"tool-call\",\n toolCalls: [tc],\n });\n }\n }\n }\n }\n\n // Show loading indicator when agent is running and the last message\n // is not already the assistant streaming\n if (isRunning) {\n const lastItem = items[items.length - 1];\n if (!lastItem || lastItem.type !== \"assistant\") {\n items.push({ id: \"__loading__\", type: \"loading\" });\n }\n }\n\n return items;\n // Same reasoning as `toolMessages`: keyed on message CONTENT, because the\n // array reference does not track content in either direction — core's\n // in-place `splice` and `addMessage`'s push leave it untouched, while the\n // AG-UI apply pipeline replaces it on every delta. Without this, an\n // assistant message or tool call appended mid-run never reaches the list.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [messagesKey, isRunning]);\n\n // Id of the trailing row. renderItem needs \"is this the last row?\" to place\n // the streaming indicator; deriving it here keeps that a named scalar instead\n // of renderItem closing over `listItems` and index-reading its tail.\n const lastItemId = useMemo(\n () => listItems[listItems.length - 1]?.id,\n [listItems],\n );\n\n // extraData defeats FlatList's PureComponent shallow-compare for the values\n // renderItem CLOSES OVER, as opposed to the ones it receives per row. Those\n // are exactly the four below, and they mirror renderItem's dependency array —\n // keep the two in sync. `listItems` is deliberately absent: renderItem's only\n // read of it is the tail id, now passed as `lastItemId`, and the array itself\n // is already the `data` prop, which invalidates cells on its own (every\n // rebuild allocates fresh item objects, so each cell's `item` prop differs).\n const extraData = useMemo(\n () => ({ isRunning, lastItemId, renderToolCall, toolMessages }),\n [isRunning, lastItemId, renderToolCall, toolMessages],\n );\n\n // Shared logic for sending a message to the agent\n const sendMessage = useCallback(\n async (text: string) => {\n if (!text || isRunning || !agent) return;\n\n setError(null);\n onSendMessage?.(text);\n\n const id = `user-${++messageIdCounter.current}`;\n agent.addMessage({\n id,\n role: \"user\",\n content: text,\n } as Message);\n\n try {\n await copilotkit.runAgent({ agent });\n } catch (err) {\n const message =\n err instanceof Error ? err.message : \"An unexpected error occurred\";\n console.error(\"[CopilotChat] runAgent failed:\", err);\n setError(message);\n }\n },\n [isRunning, agent, copilotkit, onSendMessage],\n );\n\n // Send from the input field\n const handleSend = useCallback(() => {\n const text = inputText.trim();\n if (!text) return;\n setInputText(\"\");\n void sendMessage(text);\n }, [inputText, sendMessage]);\n\n // Handle suggestion pill press\n const handleSuggestion = useCallback(\n (text: string) => {\n void sendMessage(text);\n },\n [sendMessage],\n );\n\n // Auto-scroll when content changes\n const handleContentSizeChange = useCallback(() => {\n flatListRef.current?.scrollToEnd({ animated: true });\n }, []);\n\n // Render a single list item\n const renderItem = useCallback(\n ({ item }: ListRenderItemInfo<ChatListItem>) => {\n if (item.type === \"user\") {\n return <UserMessage content={item.content ?? \"\"} />;\n }\n\n if (item.type === \"assistant\") {\n return (\n <AssistantMessage\n content={item.content ?? \"\"}\n isLoading={isRunning && item.id === lastItemId}\n />\n );\n }\n\n if (item.type === \"tool-call\" && item.toolCalls) {\n const tc = item.toolCalls[0];\n // Partial-parses streaming args, resolves the renderer (exact name ->\n // agent-scoped -> wildcard \"*\") and derives status — all in react-core,\n // shared with web. Returns ReactElement | null, which is what\n // renderItem requires.\n const rendered = renderToolCall({\n toolCall: tc,\n toolMessage: toolMessages.get(tc.id),\n });\n if (rendered) return <>{rendered}</>;\n\n // Subtle indicator for unregistered tool calls\n return (\n <View style={styles.toolCallIndicator}>\n <Text style={styles.toolCallText}>Called: {tc.function.name}</Text>\n </View>\n );\n }\n\n if (item.type === \"loading\") {\n return <AssistantMessage content=\"\" isLoading />;\n }\n\n return null;\n },\n [isRunning, lastItemId, renderToolCall, toolMessages],\n );\n\n const keyExtractor = useCallback((item: ChatListItem) => item.id, []);\n\n // Empty state component\n const emptyComponent = useMemo(\n () => (\n <View style={styles.emptyState}>\n <Text style={styles.emptyTitle}>{emptyStateTitle}</Text>\n <Text style={styles.emptySubtitle}>{emptyStateSubtitle}</Text>\n {initialMessages.map((suggestion, i) => (\n <Pressable\n key={`suggestion-${i}`}\n style={styles.suggestionPill}\n onPress={() => handleSuggestion(suggestion)}\n >\n <Text style={styles.suggestionText}>{suggestion}</Text>\n </Pressable>\n ))}\n </View>\n ),\n [emptyStateTitle, emptyStateSubtitle, initialMessages, handleSuggestion],\n );\n\n const sendDisabled = !inputText.trim() || isRunning;\n\n const content = (\n <>\n {showHeader && (\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n </View>\n )}\n\n <FlatListComponent\n ref={flatListRef}\n data={listItems}\n renderItem={renderItem}\n keyExtractor={keyExtractor}\n extraData={extraData}\n contentContainerStyle={[styles.messageList, messageContainerStyle]}\n onContentSizeChange={handleContentSizeChange}\n ListEmptyComponent={emptyComponent}\n ListFooterComponent={interruptElement}\n />\n\n {error && (\n <View style={styles.errorContainer} testID=\"error-message\">\n <Text style={styles.errorText}>{error}</Text>\n </View>\n )}\n\n <View style={[styles.inputContainer, inputContainerStyle]}>\n <TextInput\n style={styles.input}\n value={inputText}\n onChangeText={setInputText}\n placeholder={placeholder}\n placeholderTextColor=\"#999\"\n multiline\n numberOfLines={4}\n returnKeyType=\"send\"\n onSubmitEditing={handleSend}\n />\n <TouchableOpacity\n style={[styles.sendButton, sendDisabled && styles.sendButtonDisabled]}\n onPress={handleSend}\n disabled={sendDisabled}\n testID=\"send-button\"\n >\n <Text style={styles.sendButtonIcon}>{\"↑\"}</Text>\n </TouchableOpacity>\n </View>\n </>\n );\n\n if (disableKeyboardAvoiding) {\n return <View style={[styles.container, style]}>{content}</View>;\n }\n\n return (\n <KeyboardAvoidingView\n style={[styles.container, style]}\n behavior={Platform.OS === \"ios\" ? \"padding\" : \"height\"}\n keyboardVerticalOffset={0}\n >\n {content}\n </KeyboardAvoidingView>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n backgroundColor: \"#FFFFFF\",\n },\n header: {\n height: 56,\n justifyContent: \"center\",\n alignItems: \"center\",\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#E0E0E0\",\n backgroundColor: \"#FFFFFF\",\n },\n headerTitle: {\n fontSize: 17,\n fontWeight: \"600\",\n color: \"#1A1A1A\",\n },\n messageList: {\n paddingHorizontal: 16,\n flexGrow: 1,\n },\n inputContainer: {\n flexDirection: \"row\",\n alignItems: \"flex-end\",\n paddingHorizontal: 8,\n paddingVertical: 8,\n borderTopWidth: StyleSheet.hairlineWidth,\n borderTopColor: \"#E0E0E0\",\n backgroundColor: \"#FFFFFF\",\n },\n input: {\n flex: 1,\n backgroundColor: \"#F5F5F5\",\n borderRadius: 20,\n paddingHorizontal: 12,\n paddingVertical: 8,\n fontSize: 15,\n maxHeight: 100,\n color: \"#1A1A1A\",\n },\n sendButton: {\n width: 36,\n height: 36,\n borderRadius: 18,\n backgroundColor: \"#0066CC\",\n justifyContent: \"center\",\n alignItems: \"center\",\n marginLeft: 8,\n },\n sendButtonDisabled: {\n opacity: 0.4,\n },\n sendButtonIcon: {\n color: \"#FFFFFF\",\n fontSize: 18,\n fontWeight: \"700\",\n },\n emptyState: {\n flex: 1,\n justifyContent: \"center\",\n alignItems: \"center\",\n paddingTop: 100,\n gap: 12,\n },\n emptyTitle: {\n fontSize: 22,\n fontWeight: \"700\",\n color: \"#1A1A1A\",\n marginBottom: 4,\n },\n emptySubtitle: {\n fontSize: 15,\n color: \"#666666\",\n marginBottom: 16,\n },\n suggestionPill: {\n backgroundColor: \"#E8F0FE\",\n borderRadius: 20,\n paddingHorizontal: 16,\n paddingVertical: 10,\n },\n suggestionText: {\n color: \"#0066CC\",\n fontWeight: \"600\",\n fontSize: 14,\n },\n toolCallIndicator: {\n alignSelf: \"flex-start\",\n backgroundColor: \"#F0F0F0\",\n borderRadius: 12,\n paddingHorizontal: 12,\n paddingVertical: 6,\n marginBottom: 8,\n },\n toolCallText: {\n fontSize: 12,\n color: \"#999999\",\n fontStyle: \"italic\",\n },\n errorContainer: {\n backgroundColor: \"#FEE2E2\",\n paddingHorizontal: 12,\n paddingVertical: 8,\n marginHorizontal: 8,\n borderRadius: 8,\n },\n errorText: {\n color: \"#DC2626\",\n fontSize: 13,\n },\n});\n","/**\n * CopilotModal — a bottom-sheet chat overlay for React Native.\n *\n * Mobile equivalent of CopilotPopup on web. Wraps CopilotChat inside\n * @gorhom/bottom-sheet so the chat can slide up over any screen.\n */\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n} from \"react\";\nimport { StyleSheet, View } from \"react-native\";\nimport BottomSheet, {\n BottomSheetBackdrop,\n BottomSheetFlatList,\n BottomSheetView,\n} from \"@gorhom/bottom-sheet\";\nimport type { BottomSheetBackdropProps } from \"@gorhom/bottom-sheet\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatProps } from \"./CopilotChat\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CopilotModalProps {\n /** Controlled visibility — when true the sheet opens, when false it closes. */\n visible?: boolean;\n\n /** Called when the sheet is dismissed (via backdrop tap, swipe-down, or close()). */\n onDismiss?: () => void;\n\n /**\n * Bottom-sheet snap points.\n * @default ['50%', '90%']\n */\n snapPoints?: (string | number)[];\n\n /**\n * Which snap-point index to open at.\n * @default 0\n */\n initialSnapIndex?: number;\n\n /**\n * Whether closing the sheet fires onDismiss.\n * @default true\n */\n enableDismissOnClose?: boolean;\n\n /**\n * Backdrop opacity when the sheet is open.\n * @default 0.5\n */\n backdropOpacity?: number;\n\n // -- Pass-through to CopilotChat ------------------------------------------\n\n /** Which agent to connect to. */\n agentName?: string;\n\n /** Input placeholder text. */\n placeholder?: string;\n\n /** Seed messages shown on first render. */\n initialMessages?: string[];\n\n /** Title shown in the CopilotChat header area. */\n headerTitle?: string;\n}\n\n/** Imperative handle exposed via ref. */\nexport interface CopilotModalRef {\n /** Programmatically open the bottom sheet. */\n open: () => void;\n /** Programmatically close the bottom sheet. */\n close: () => void;\n}\n\n// ---------------------------------------------------------------------------\n// Component\n// ---------------------------------------------------------------------------\n\nexport const CopilotModal = forwardRef<CopilotModalRef, CopilotModalProps>(\n function CopilotModal(\n {\n visible,\n onDismiss,\n snapPoints: snapPointsProp,\n initialSnapIndex = 0,\n enableDismissOnClose = true,\n backdropOpacity = 0.5,\n agentName,\n placeholder,\n initialMessages,\n headerTitle,\n },\n ref,\n ) {\n const bottomSheetRef = useRef<BottomSheet>(null);\n\n // Stable snap-points array\n const snapPoints = useMemo(\n () => snapPointsProp ?? [\"50%\", \"90%\"],\n [snapPointsProp],\n );\n\n // ── Imperative API ────────────────────────────────────────────────────\n useImperativeHandle(\n ref,\n () => ({\n open() {\n bottomSheetRef.current?.snapToIndex(initialSnapIndex);\n },\n close() {\n bottomSheetRef.current?.close();\n },\n }),\n [initialSnapIndex],\n );\n\n // ── Controlled visibility ─────────────────────────────────────────────\n useEffect(() => {\n if (visible === undefined) return;\n if (visible) {\n bottomSheetRef.current?.snapToIndex(initialSnapIndex);\n } else {\n bottomSheetRef.current?.close();\n }\n }, [visible, initialSnapIndex]);\n\n // ── Backdrop renderer ─────────────────────────────────────────────────\n const renderBackdrop = useCallback(\n (props: BottomSheetBackdropProps) => (\n <BottomSheetBackdrop\n {...props}\n disappearsOnIndex={-1}\n appearsOnIndex={0}\n opacity={backdropOpacity}\n pressBehavior=\"close\"\n />\n ),\n [backdropOpacity],\n );\n\n // ── Sheet close handler ───────────────────────────────────────────────\n const handleClose = useCallback(() => {\n if (enableDismissOnClose) {\n onDismiss?.();\n }\n }, [enableDismissOnClose, onDismiss]);\n\n // ── Build CopilotChat props ───────────────────────────────────────────\n const chatProps = useMemo(() => {\n const props: Partial<CopilotChatProps> = {};\n if (agentName !== undefined) props.agentName = agentName;\n if (placeholder !== undefined) props.placeholder = placeholder;\n if (initialMessages !== undefined)\n props.initialMessages = initialMessages;\n if (headerTitle !== undefined) props.headerTitle = headerTitle;\n return props;\n }, [agentName, placeholder, initialMessages, headerTitle]);\n\n return (\n <BottomSheet\n ref={bottomSheetRef}\n index={-1}\n snapPoints={snapPoints}\n enablePanDownToClose\n backdropComponent={renderBackdrop}\n onClose={handleClose}\n keyboardBehavior=\"interactive\"\n keyboardBlurBehavior=\"restore\"\n backgroundStyle={styles.sheetBackground}\n handleIndicatorStyle={styles.handleIndicator}\n >\n <BottomSheetView style={styles.contentContainer}>\n <CopilotChat\n {...chatProps}\n FlatListComponent={BottomSheetFlatList}\n disableKeyboardAvoiding\n />\n </BottomSheetView>\n </BottomSheet>\n );\n },\n);\n\n// ---------------------------------------------------------------------------\n// Styles\n// ---------------------------------------------------------------------------\n\nconst styles = StyleSheet.create({\n sheetBackground: {\n backgroundColor: \"#FFFFFF\",\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n },\n handleIndicator: {\n width: 40,\n height: 4,\n backgroundColor: \"#DDDDDD\",\n },\n contentContainer: {\n flex: 1,\n },\n});\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,WAAW;AACjB,MAAM,cAAc;AACpB,MAAM,qBAAqB;;;;;;;AAQ3B,SAAgB,gBAAgB,EAAE,SAA+B;CAC/D,MAAM,OAAO,OAAO,IAAI,SAAS,MAAM,EAAE,CAAC,CAAC;CAC3C,MAAM,OAAO,OAAO,IAAI,SAAS,MAAM,EAAE,CAAC,CAAC;CAC3C,MAAM,OAAO,OAAO,IAAI,SAAS,MAAM,EAAE,CAAC,CAAC;AAE3C,iBAAgB;EACd,MAAM,eAAe,KAAqB,UACxC,SAAS,SAAS,CAChB,SAAS,MAAM,MAAM,EACrB,SAAS,KACP,SAAS,SAAS,CAChB,SAAS,OAAO,KAAK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C,oBAAC;EACC,GAAI;EACJ,mBAAmB;EACnB,gBAAgB;EAChB,SAAS;EACT,eAAc;GACd,EAEJ,CAAC,gBAAgB,CAClB;CAGD,MAAM,cAAc,kBAAkB;AACpC,MAAI,qBACF,cAAa;IAEd,CAAC,sBAAsB,UAAU,CAAC;CAGrC,MAAM,YAAY,cAAc;EAC9B,MAAM,QAAmC,EAAE;AAC3C,MAAI,cAAc,OAAW,OAAM,YAAY;AAC/C,MAAI,gBAAgB,OAAW,OAAM,cAAc;AACnD,MAAI,oBAAoB,OACtB,OAAM,kBAAkB;AAC1B,MAAI,gBAAgB,OAAW,OAAM,cAAc;AACnD,SAAO;IACN;EAAC;EAAW;EAAa;EAAiB;EAAY,CAAC;AAE1D,QACE,oBAAC;EACC,KAAK;EACL,OAAO;EACK;EACZ;EACA,mBAAmB;EACnB,SAAS;EACT,kBAAiB;EACjB,sBAAqB;EACrB,iBAAiB,OAAO;EACxB,sBAAsB,OAAO;YAE7B,oBAAC;GAAgB,OAAO,OAAO;aAC7B,oBAAC;IACC,GAAI;IACJ,mBAAmB;IACnB;KACA;IACc;GACN;EAGnB;AAMD,MAAM,SAAS,WAAW,OAAO;CAC/B,iBAAiB;EACf,iBAAiB;EACjB,qBAAqB;EACrB,sBAAsB;EACvB;CACD,iBAAiB;EACf,OAAO;EACP,QAAQ;EACR,iBAAiB;EAClB;CACD,kBAAkB,EAChB,MAAM,GACP;CACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["styles","TIMESTAMP_COLOR","styles","styles","styles"],"sources":["../../src/components/messages/TypingIndicator.tsx","../../src/components/messages/utils.ts","../../src/components/messages/AssistantMessage.tsx","../../src/components/messages/UserMessage.tsx","../../src/components/CopilotChat.tsx","../../src/components/CopilotModal.tsx"],"sourcesContent":["import React, { useEffect, useState } from \"react\";\nimport { View, Animated, StyleSheet } from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\n\n/**\n * Props for the TypingIndicator component.\n */\nexport interface TypingIndicatorProps {\n /** Optional style override for the container */\n style?: ViewStyle;\n}\n\nconst DOT_SIZE = 6;\nconst DOT_SPACING = 4;\nconst ANIMATION_DURATION = 400;\n\n/**\n * Three animated dots that pulse in sequence, suitable for embedding\n * inside an AssistantMessage to indicate the AI is still generating.\n *\n * Uses React Native's built-in `Animated` API (no Reanimated dependency).\n */\nexport function TypingIndicator({ style }: TypingIndicatorProps) {\n const [dot1] = useState(() => new Animated.Value(0));\n const [dot2] = useState(() => new Animated.Value(0));\n const [dot3] = useState(() => new Animated.Value(0));\n\n useEffect(() => {\n const createPulse = (dot: Animated.Value, delay: number) =>\n Animated.sequence([\n Animated.delay(delay),\n Animated.loop(\n Animated.sequence([\n Animated.timing(dot, {\n toValue: 1,\n duration: ANIMATION_DURATION,\n useNativeDriver: true,\n }),\n Animated.timing(dot, {\n toValue: 0,\n duration: ANIMATION_DURATION,\n useNativeDriver: true,\n }),\n ]),\n ),\n ]);\n\n const animation = Animated.parallel([\n createPulse(dot1, 0),\n createPulse(dot2, ANIMATION_DURATION * 0.33),\n createPulse(dot3, ANIMATION_DURATION * 0.66),\n ]);\n\n animation.start();\n\n return () => {\n animation.stop();\n };\n }, [dot1, dot2, dot3]);\n\n const dotStyle = (animatedValue: Animated.Value) => ({\n ...styles.dot,\n opacity: animatedValue.interpolate({\n inputRange: [0, 1],\n outputRange: [0.3, 1],\n }),\n transform: [\n {\n scale: animatedValue.interpolate({\n inputRange: [0, 1],\n outputRange: [0.8, 1.2],\n }),\n },\n ],\n });\n\n return (\n <View\n testID=\"copilot-loading-cursor\"\n style={[styles.container, style]}\n accessibilityLabel=\"Typing indicator\"\n accessibilityRole=\"text\"\n >\n <Animated.View style={dotStyle(dot1)} />\n <Animated.View style={dotStyle(dot2)} />\n <Animated.View style={dotStyle(dot3)} />\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flexDirection: \"row\",\n alignItems: \"center\",\n paddingVertical: 4,\n paddingHorizontal: 2,\n },\n dot: {\n width: DOT_SIZE,\n height: DOT_SIZE,\n borderRadius: DOT_SIZE / 2,\n backgroundColor: \"#999999\",\n marginHorizontal: DOT_SPACING / 2,\n },\n});\n","/**\n * Format a Date as a 12-hour time string (e.g. \"2:05 PM\").\n */\nexport function formatTimestamp(date: Date): string {\n const hours = date.getHours();\n const minutes = date.getMinutes();\n const ampm = hours >= 12 ? \"PM\" : \"AM\";\n const displayHours = hours % 12 || 12;\n const displayMinutes = minutes.toString().padStart(2, \"0\");\n return `${displayHours}:${displayMinutes} ${ampm}`;\n}\n","import React from \"react\";\nimport { View, Text, StyleSheet } from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotMarkdown } from \"../Markdown\";\nimport {\n useMarkdownRenderer,\n isNativeComponentRenderer,\n} from \"../MarkdownRendererContext\";\nimport { TypingIndicator } from \"./TypingIndicator\";\nimport { formatTimestamp } from \"./utils\";\n\n// ─── Colors ──────────────────────────────────────────────────────────────────\nconst ASSISTANT_BUBBLE_BG = \"#F0F0F0\";\nconst TIMESTAMP_COLOR = \"#999999\";\n\n/**\n * Props for the AssistantMessage component.\n */\nexport interface AssistantMessageProps {\n /** Markdown content to render inside the bubble */\n content: string;\n /** When true, shows a typing indicator below any content */\n isLoading?: boolean;\n /** Optional timestamp displayed below the bubble */\n timestamp?: Date;\n /** Optional style override for the outer container */\n style?: ViewStyle;\n}\n\n/**\n * Left-aligned chat bubble for AI assistant responses.\n *\n * Renders markdown content via `CopilotMarkdown` and shows an animated\n * typing indicator when `isLoading` is true.\n */\nexport function AssistantMessage({\n content,\n isLoading = false,\n timestamp,\n style,\n}: AssistantMessageProps) {\n // Honor a provider-level markdown renderer (CopilotKitProvider's\n // `markdownRenderer` prop), falling back to the built-in CopilotMarkdown.\n // This is the React Native arm of the slot -> provider -> built-in\n // resolution order documented in the migration guide.\n const provided = useMarkdownRenderer();\n return (\n <View style={[styles.container, style]}>\n <View style={styles.bubble}>\n {content ? (\n isNativeComponentRenderer(provided) ? (\n React.createElement(provided, { content, isStreaming: isLoading })\n ) : provided ? (\n <CopilotMarkdown\n content={content}\n style={provided.style}\n streamingAnimation={provided.animate}\n />\n ) : (\n <CopilotMarkdown content={content} />\n )\n ) : null}\n {isLoading ? <TypingIndicator /> : null}\n </View>\n {timestamp && (\n <Text style={styles.timestamp}>{formatTimestamp(timestamp)}</Text>\n )}\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n alignItems: \"flex-start\",\n marginVertical: 4,\n paddingHorizontal: 12,\n },\n bubble: {\n backgroundColor: ASSISTANT_BUBBLE_BG,\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n borderBottomRightRadius: 16,\n borderBottomLeftRadius: 4,\n paddingHorizontal: 12,\n paddingVertical: 8,\n maxWidth: \"80%\",\n },\n timestamp: {\n color: TIMESTAMP_COLOR,\n fontSize: 11,\n marginTop: 2,\n marginLeft: 4,\n },\n});\n","import React from \"react\";\nimport { View, Text, StyleSheet, type ViewStyle } from \"react-native\";\nimport { formatTimestamp } from \"./utils\";\n\n// ─── Colors ──────────────────────────────────────────────────────────────────\nconst USER_BUBBLE_BG = \"#0066CC\";\nconst USER_TEXT_COLOR = \"#FFFFFF\";\nconst TIMESTAMP_COLOR = \"#999999\";\n\n/**\n * Props for the UserMessage component.\n */\nexport interface UserMessageProps {\n /** Plain text content to display */\n content: string;\n /** Optional timestamp displayed below the bubble */\n timestamp?: Date;\n /** Optional style override for the outer container */\n style?: ViewStyle;\n}\n\n/**\n * Right-aligned chat bubble for user messages.\n *\n * Renders plain text (no markdown) with a primary-color background\n * and white text. Optionally displays a subtle timestamp below.\n */\nexport function UserMessage({ content, timestamp, style }: UserMessageProps) {\n return (\n <View style={[styles.container, style]}>\n <View style={styles.bubble}>\n <Text style={styles.text}>{content}</Text>\n </View>\n {timestamp && (\n <Text style={styles.timestamp}>{formatTimestamp(timestamp)}</Text>\n )}\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n alignItems: \"flex-end\",\n marginVertical: 4,\n paddingHorizontal: 12,\n },\n bubble: {\n backgroundColor: USER_BUBBLE_BG,\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n borderBottomLeftRadius: 16,\n borderBottomRightRadius: 4,\n paddingHorizontal: 12,\n paddingVertical: 8,\n maxWidth: \"80%\",\n },\n text: {\n color: USER_TEXT_COLOR,\n fontSize: 16,\n lineHeight: 22,\n },\n timestamp: {\n color: TIMESTAMP_COLOR,\n fontSize: 11,\n marginTop: 2,\n marginRight: 4,\n },\n});\n","import React, {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport {\n FlatList,\n KeyboardAvoidingView,\n Platform,\n Pressable,\n StyleSheet,\n Text,\n TextInput,\n TouchableOpacity,\n View,\n} from \"react-native\";\nimport type { ListRenderItemInfo, ViewStyle } from \"react-native\";\nimport { useAgent, useRenderToolCall } from \"@copilotkit/react-core/headless\";\nimport { useCopilotKit } from \"@copilotkit/react-core/context\";\nimport { AssistantMessage } from \"./messages/AssistantMessage\";\nimport { UserMessage } from \"./messages/UserMessage\";\nimport type { Message } from \"@copilotkit/shared\";\nimport type { ToolMessage } from \"@ag-ui/client\";\nimport { contentToText } from \"@ag-ui/client\";\n\n/** Shape of an assistant message with optional tool calls. */\ninterface AssistantMessageShape {\n id: string;\n role: \"assistant\";\n content?: string;\n toolCalls?: Array<{\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n }>;\n}\n\nexport interface CopilotChatProps {\n /** Agent ID to connect to. Defaults to 'default'. */\n agentName?: string;\n /** Placeholder text for the input field. */\n placeholder?: string;\n /** Suggestion pills shown in the empty state. */\n initialMessages?: string[];\n /** Title shown when there are no messages. */\n emptyStateTitle?: string;\n /** Subtitle shown when there are no messages. */\n emptyStateSubtitle?: string;\n /** Title for the optional header bar. */\n headerTitle?: string;\n /** Whether to show the header bar. Defaults to true. */\n showHeader?: boolean;\n /** Style override for the outermost container. */\n style?: ViewStyle;\n /** Style override for the message list container. */\n messageContainerStyle?: ViewStyle;\n /** Style override for the input bar container. */\n inputContainerStyle?: ViewStyle;\n /** Callback fired when the user sends a message. */\n onSendMessage?: (text: string) => void;\n /** Custom FlatList component (e.g. BottomSheetFlatList for use inside a bottom sheet). */\n FlatListComponent?: React.ComponentType<any>;\n /** When true, skip the KeyboardAvoidingView wrapper (useful when a parent already handles keyboard). */\n disableKeyboardAvoiding?: boolean;\n}\n\ninterface ChatListItem {\n id: string;\n type: \"user\" | \"assistant\" | \"tool-call\" | \"loading\";\n content?: string;\n toolCalls?: Array<{\n id: string;\n type: \"function\";\n function: { name: string; arguments: string };\n }>;\n}\n\n/**\n * Lightweight content fingerprint for an agent's message list.\n *\n * The identity of `agent.messages` is NOT a reliable change signal, and it fails\n * in BOTH directions:\n *\n * - It changes on paths that have nothing to do with what is read below.\n * `@ag-ui/client`'s apply pipeline REASSIGNS the array\n * (`AbstractAgent.processApplyEvents` does `this.messages = applied.messages`),\n * so a streaming run hands down a fresh array — and fresh message, `toolCall`\n * and `function` objects — on every applied delta.\n * - It does NOT change on the paths these memos exist to serve. Core inserts\n * tool results by mutating in place —\n * `agent.messages.splice(insertAt, 0, toolMessage)`\n * (packages/core/src/core/run-handler.ts:931, :1080) —\n * `AbstractAgent.addMessage` is a `this.messages.push(...)`, and `useAgent`\n * re-renders with a bare `forceUpdate()` rather than a new array.\n *\n * (Grepping `packages/core/src` for a `.messages` assignment finds test files\n * only, but that proves nothing about identity: the reassignment lives in\n * `@ag-ui/client`, outside that tree.)\n *\n * So anything derived from messages must depend on their CONTENT, not on the\n * array reference.\n *\n * Captures exactly what the derivations below read — id, role, content size,\n * `toolCallId` (so an inserted tool result is visible), and each tool call's id\n * plus argument length (so streaming args advance).\n *\n * String and array content contribute their LENGTH rather than their value, so\n * large text and base64 attachment payloads are never re-serialized on every\n * render. Object content is the deliberate exception and IS serialized: a\n * length-based key is a constant 0 for every object, so an in-place content\n * replacement that keeps the same message id would otherwise be invisible to\n * every memo below.\n *\n * That object branch is convergence, not a fix for a reachable stale render: the\n * producer of same-id object content is an ACTIVITY_SNAPSHOT replace, and\n * `role: \"activity\"` never reaches `listItems`, which builds rows for `user` and\n * `assistant` only. It follows the SHAPE of react-core's `messagesMemoKey`\n * (react-core #6325). The two are independent implementations of the same idea —\n * a change to that key does not propagate here on its own, so treat this as a\n * documented parallel rather than a mirror.\n */\nfunction messagesFingerprint(messages: readonly unknown[]): string {\n return messages\n .map((msg) => {\n const m = msg as {\n id?: string;\n role?: string;\n content?: unknown;\n toolCallId?: string;\n toolCalls?: Array<{ id: string; function?: { arguments?: string } }>;\n };\n const content = m.content;\n const contentKey =\n typeof content === \"string\" || Array.isArray(content)\n ? content.length\n : content && typeof content === \"object\"\n ? objectContentKey(content)\n : 0;\n const toolCallsKey = Array.isArray(m.toolCalls)\n ? m.toolCalls\n .map((tc) => `${tc.id}:${tc.function?.arguments?.length ?? 0}`)\n .join(\";\")\n : \"\";\n return `${m.id}:${m.role}:${contentKey}:${m.toolCallId ?? \"\"}:${toolCallsKey}`;\n })\n .join(\",\");\n}\n\n/**\n * Serializes object content for the fingerprint above.\n *\n * Guarded because `JSON.stringify` THROWS on a circular structure and\n * `messagesFingerprint` runs on EVERY render, so a bare call would take the whole\n * chat down on content this component is explicitly required to tolerate —\n * `toolResultContent` below documents why non-string content reaches RN at all,\n * and \"does not throw on tool content that cannot be JSON-serialised\" pins that a\n * circular tool result must still render.\n *\n * The fallback is a constant, which means a circular object is invisible to the\n * memo exactly as every object used to be. That is the correct trade: it confines\n * the old always-equal behaviour to the pathological case instead of letting it\n * decide the common one. NOTE: this guard is a deliberate divergence from\n * react-core's `messagesMemoKey`, which stringifies unguarded.\n */\nfunction objectContentKey(content: object): string {\n try {\n return JSON.stringify(content) ?? \"\";\n } catch {\n return \"[unserializable]\";\n }\n}\n\n/**\n * Coerces a tool message's `content` to the `string` the renderer contract\n * requires (`ReactToolCallRenderer`'s Complete branch declares `result: string`)\n * WITHOUT inventing an empty result.\n *\n * AG-UI 1.0 models tool content as `string | ContentPart[]`: a plain string, or\n * an ordered list of typed parts (text, image, audio, video, document). A\n * string passes through; a list of parts is rendered as its text parts\n * concatenated — the flattening the spec permits for a string-only consumer —\n * and the media parts stay on the message for anything that can show them.\n * Neither is malformed, so neither warns.\n *\n * Anything else is only reachable from a producer that skipped validation —\n * restored thread history, a non-SSE transport, or app code casting on\n * `addMessage`. Core hedges against that case too (it accepts `unknown` content\n * and handles arrays of text parts), so this must not answer it with `\"\"`: an\n * empty string is a LEGITIMATE tool result, which makes a dropped result\n * indistinguishable from an empty one. Serialise faithfully — the same\n * representation core uses for non-string results — and warn in dev.\n */\nconst MEDIA_PART_TYPES = new Set([\"image\", \"audio\", \"video\", \"document\"]);\n\n/**\n * Whether a value is one of the protocol's content parts: a text part with a\n * string `text`, or a media part with a `source` that names its kind and\n * value. Anything else — an array of typed records from restored history,\n * say — is not parts and keeps the serialise-and-warn path.\n */\nfunction isContentPart(part: unknown): boolean {\n if (typeof part !== \"object\" || part === null) return false;\n const record = part as { type?: unknown; text?: unknown; source?: unknown };\n if (record.type === \"text\") return typeof record.text === \"string\";\n if (typeof record.type !== \"string\" || !MEDIA_PART_TYPES.has(record.type))\n return false;\n const source = record.source as\n | { type?: unknown; value?: unknown; mimeType?: unknown }\n | undefined;\n if (typeof source !== \"object\" || source === null) return false;\n if (typeof source.value !== \"string\") return false;\n // Inline bytes need their type; a URL or a provider file handle (AG-UI 1.0\n // `file` source) may leave it out.\n if (source.type === \"data\") return typeof source.mimeType === \"string\";\n return (\n (source.type === \"url\" || source.type === \"file\") &&\n (source.mimeType === undefined || typeof source.mimeType === \"string\")\n );\n}\n\nfunction toolResultContent(content: unknown, toolCallId: string): string {\n if (typeof content === \"string\") return content;\n\n if (Array.isArray(content) && content.every(isContentPart)) {\n return contentToText(content as ToolMessage[\"content\"]);\n }\n\n // null/undefined carry no payload, so \"\" loses nothing — but the message is\n // still malformed, so it warns below rather than passing silently.\n let serialized = \"\";\n if (content !== null && content !== undefined) {\n try {\n serialized =\n JSON.stringify(content) ?? Object.prototype.toString.call(content);\n } catch {\n // Circular or otherwise non-serialisable: keep SOMETHING over dropping\n // the result, and never throw from a render path.\n serialized = Object.prototype.toString.call(content);\n }\n }\n\n if (typeof __DEV__ === \"undefined\" || __DEV__) {\n console.warn(\n `[CopilotChat] Tool message for tool call \"${toolCallId}\" had non-string ` +\n `content (${content === null ? \"null\" : typeof content}), but renderers ` +\n `receive \\`result: string\\`. Rendering a serialized form instead of ` +\n `dropping it: ${serialized === \"\" ? \"<empty>\" : serialized}`,\n );\n }\n\n return serialized;\n}\n\n/**\n * Full-screen chat UI component for React Native.\n *\n * Connects to a CopilotKit agent via `useAgent` and renders messages\n * using platform-appropriate AssistantMessage / UserMessage components.\n *\n * Usage:\n * ```tsx\n * <CopilotChat agentName=\"my-agent\" headerTitle=\"Assistant\" />\n * ```\n */\nexport function CopilotChat({\n agentName = \"default\",\n placeholder = \"Type a message...\",\n initialMessages = [],\n emptyStateTitle = \"How can I help?\",\n emptyStateSubtitle = \"Ask me anything or try a suggestion below.\",\n headerTitle = \"Chat\",\n showHeader = true,\n style,\n messageContainerStyle,\n inputContainerStyle,\n onSendMessage,\n FlatListComponent = FlatList,\n disableKeyboardAvoiding = false,\n}: CopilotChatProps) {\n const [inputText, setInputText] = useState(\"\");\n const [error, setError] = useState<string | null>(null);\n const flatListRef = useRef<FlatList>(null);\n const messageIdCounter = useRef(0);\n\n const { copilotkit } = useCopilotKit();\n const { agent } = useAgent({ agentId: agentName });\n\n const messages = agent.messages ?? [];\n const isRunning = agent.isRunning;\n\n const renderToolCall = useRenderToolCall();\n\n // useInterrupt publishes its element to core unless renderInChat is false.\n // Draw it after the last message, as the web message view does.\n const [interruptElement, setInterruptElement] =\n useState<React.ReactElement | null>(null);\n useEffect(() => {\n setInterruptElement(copilotkit.interruptElement);\n const subscription = copilotkit.subscribe({\n onInterruptElementChanged: ({ interruptElement: element }) => {\n setInterruptElement(element);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n // Recomputed every render — cheap, and the only honest dependency for the\n // message-derived memos below. See `messagesFingerprint` for why the array\n // reference cannot be trusted as one.\n const messagesKey = messagesFingerprint(messages);\n\n // toolCallId -> tool result message. react-core's renderer reports\n // status \"complete\" with `result` when a tool message exists; RN's chat\n // previously never correlated these, so `result` was always undefined.\n const toolMessages = useMemo(() => {\n const byId = new Map<string, ToolMessage>();\n for (const msg of messages) {\n const m = msg as {\n role?: string;\n id?: string;\n toolCallId?: string;\n content?: unknown;\n };\n if (m.role === \"tool\" && m.toolCallId) {\n byId.set(m.toolCallId, {\n id: m.id ?? m.toolCallId,\n role: \"tool\",\n toolCallId: m.toolCallId,\n content: toolResultContent(m.content, m.toolCallId),\n });\n }\n }\n return byId;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [messagesKey]);\n\n // Build flat list items from messages\n const listItems: ChatListItem[] = useMemo(() => {\n const items: ChatListItem[] = [];\n\n for (const msg of messages) {\n if (msg.role === \"user\") {\n items.push({\n id: msg.id,\n type: \"user\",\n content: typeof msg.content === \"string\" ? msg.content : \"\",\n });\n } else if (msg.role === \"assistant\") {\n const assistantMsg = msg as AssistantMessageShape;\n // Add text content if present\n if (assistantMsg.content) {\n items.push({\n id: msg.id,\n type: \"assistant\",\n content: assistantMsg.content,\n });\n }\n // Add tool calls if present\n if (assistantMsg.toolCalls && assistantMsg.toolCalls.length > 0) {\n for (const tc of assistantMsg.toolCalls) {\n items.push({\n id: `${msg.id}-tc-${tc.id}`,\n type: \"tool-call\",\n toolCalls: [tc],\n });\n }\n }\n }\n }\n\n // Show loading indicator when agent is running and the last message\n // is not already the assistant streaming\n if (isRunning) {\n const lastItem = items[items.length - 1];\n if (!lastItem || lastItem.type !== \"assistant\") {\n items.push({ id: \"__loading__\", type: \"loading\" });\n }\n }\n\n return items;\n // Same reasoning as `toolMessages`: keyed on message CONTENT, because the\n // array reference does not track content in either direction — core's\n // in-place `splice` and `addMessage`'s push leave it untouched, while the\n // AG-UI apply pipeline replaces it on every delta. Without this, an\n // assistant message or tool call appended mid-run never reaches the list.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [messagesKey, isRunning]);\n\n // Id of the trailing row. renderItem needs \"is this the last row?\" to place\n // the streaming indicator; deriving it here keeps that a named scalar instead\n // of renderItem closing over `listItems` and index-reading its tail.\n const lastItemId = useMemo(\n () => listItems[listItems.length - 1]?.id,\n [listItems],\n );\n\n // extraData defeats FlatList's PureComponent shallow-compare for the values\n // renderItem CLOSES OVER, as opposed to the ones it receives per row. Those\n // are exactly the four below, and they mirror renderItem's dependency array —\n // keep the two in sync. `listItems` is deliberately absent: renderItem's only\n // read of it is the tail id, now passed as `lastItemId`, and the array itself\n // is already the `data` prop, which invalidates cells on its own (every\n // rebuild allocates fresh item objects, so each cell's `item` prop differs).\n const extraData = useMemo(\n () => ({ isRunning, lastItemId, renderToolCall, toolMessages }),\n [isRunning, lastItemId, renderToolCall, toolMessages],\n );\n\n // Shared logic for sending a message to the agent\n const sendMessage = useCallback(\n async (text: string) => {\n if (!text || isRunning || !agent) return;\n\n setError(null);\n onSendMessage?.(text);\n\n const id = `user-${++messageIdCounter.current}`;\n agent.addMessage({\n id,\n role: \"user\",\n content: text,\n } as Message);\n\n try {\n await copilotkit.runAgent({ agent });\n } catch (err) {\n const message =\n err instanceof Error ? err.message : \"An unexpected error occurred\";\n console.error(\"[CopilotChat] runAgent failed:\", err);\n setError(message);\n }\n },\n [isRunning, agent, copilotkit, onSendMessage],\n );\n\n // Send from the input field\n const handleSend = useCallback(() => {\n const text = inputText.trim();\n if (!text) return;\n setInputText(\"\");\n void sendMessage(text);\n }, [inputText, sendMessage]);\n\n // Handle suggestion pill press\n const handleSuggestion = useCallback(\n (text: string) => {\n void sendMessage(text);\n },\n [sendMessage],\n );\n\n // Auto-scroll when content changes\n const handleContentSizeChange = useCallback(() => {\n flatListRef.current?.scrollToEnd({ animated: true });\n }, []);\n\n // Render a single list item\n const renderItem = useCallback(\n ({ item }: ListRenderItemInfo<ChatListItem>) => {\n if (item.type === \"user\") {\n return <UserMessage content={item.content ?? \"\"} />;\n }\n\n if (item.type === \"assistant\") {\n return (\n <AssistantMessage\n content={item.content ?? \"\"}\n isLoading={isRunning && item.id === lastItemId}\n />\n );\n }\n\n if (item.type === \"tool-call\" && item.toolCalls) {\n const tc = item.toolCalls[0];\n // Partial-parses streaming args, resolves the renderer (exact name ->\n // agent-scoped -> wildcard \"*\") and derives status — all in react-core,\n // shared with web. Returns ReactElement | null, which is what\n // renderItem requires.\n const rendered = renderToolCall({\n toolCall: tc,\n toolMessage: toolMessages.get(tc.id),\n });\n if (rendered) return <>{rendered}</>;\n\n // Subtle indicator for unregistered tool calls\n return (\n <View style={styles.toolCallIndicator}>\n <Text style={styles.toolCallText}>Called: {tc.function.name}</Text>\n </View>\n );\n }\n\n if (item.type === \"loading\") {\n return <AssistantMessage content=\"\" isLoading />;\n }\n\n return null;\n },\n [isRunning, lastItemId, renderToolCall, toolMessages],\n );\n\n const keyExtractor = useCallback((item: ChatListItem) => item.id, []);\n\n // Empty state component\n const emptyComponent = useMemo(\n () => (\n <View style={styles.emptyState}>\n <Text style={styles.emptyTitle}>{emptyStateTitle}</Text>\n <Text style={styles.emptySubtitle}>{emptyStateSubtitle}</Text>\n {initialMessages.map((suggestion, i) => (\n <Pressable\n key={`suggestion-${i}`}\n style={styles.suggestionPill}\n onPress={() => handleSuggestion(suggestion)}\n >\n <Text style={styles.suggestionText}>{suggestion}</Text>\n </Pressable>\n ))}\n </View>\n ),\n [emptyStateTitle, emptyStateSubtitle, initialMessages, handleSuggestion],\n );\n\n const sendDisabled = !inputText.trim() || isRunning;\n\n const content = (\n <>\n {showHeader && (\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n </View>\n )}\n\n <FlatListComponent\n ref={flatListRef}\n data={listItems}\n renderItem={renderItem}\n keyExtractor={keyExtractor}\n extraData={extraData}\n contentContainerStyle={[styles.messageList, messageContainerStyle]}\n onContentSizeChange={handleContentSizeChange}\n ListEmptyComponent={emptyComponent}\n ListFooterComponent={interruptElement}\n />\n\n {error && (\n <View style={styles.errorContainer} testID=\"error-message\">\n <Text style={styles.errorText}>{error}</Text>\n </View>\n )}\n\n <View style={[styles.inputContainer, inputContainerStyle]}>\n <TextInput\n style={styles.input}\n value={inputText}\n onChangeText={setInputText}\n placeholder={placeholder}\n placeholderTextColor=\"#999\"\n multiline\n numberOfLines={4}\n returnKeyType=\"send\"\n onSubmitEditing={handleSend}\n />\n <TouchableOpacity\n style={[styles.sendButton, sendDisabled && styles.sendButtonDisabled]}\n onPress={handleSend}\n disabled={sendDisabled}\n testID=\"send-button\"\n >\n <Text style={styles.sendButtonIcon}>{\"↑\"}</Text>\n </TouchableOpacity>\n </View>\n </>\n );\n\n if (disableKeyboardAvoiding) {\n return <View style={[styles.container, style]}>{content}</View>;\n }\n\n return (\n <KeyboardAvoidingView\n style={[styles.container, style]}\n behavior={Platform.OS === \"ios\" ? \"padding\" : \"height\"}\n keyboardVerticalOffset={0}\n >\n {content}\n </KeyboardAvoidingView>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n backgroundColor: \"#FFFFFF\",\n },\n header: {\n height: 56,\n justifyContent: \"center\",\n alignItems: \"center\",\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#E0E0E0\",\n backgroundColor: \"#FFFFFF\",\n },\n headerTitle: {\n fontSize: 17,\n fontWeight: \"600\",\n color: \"#1A1A1A\",\n },\n messageList: {\n paddingHorizontal: 16,\n flexGrow: 1,\n },\n inputContainer: {\n flexDirection: \"row\",\n alignItems: \"flex-end\",\n paddingHorizontal: 8,\n paddingVertical: 8,\n borderTopWidth: StyleSheet.hairlineWidth,\n borderTopColor: \"#E0E0E0\",\n backgroundColor: \"#FFFFFF\",\n },\n input: {\n flex: 1,\n backgroundColor: \"#F5F5F5\",\n borderRadius: 20,\n paddingHorizontal: 12,\n paddingVertical: 8,\n fontSize: 15,\n maxHeight: 100,\n color: \"#1A1A1A\",\n },\n sendButton: {\n width: 36,\n height: 36,\n borderRadius: 18,\n backgroundColor: \"#0066CC\",\n justifyContent: \"center\",\n alignItems: \"center\",\n marginLeft: 8,\n },\n sendButtonDisabled: {\n opacity: 0.4,\n },\n sendButtonIcon: {\n color: \"#FFFFFF\",\n fontSize: 18,\n fontWeight: \"700\",\n },\n emptyState: {\n flex: 1,\n justifyContent: \"center\",\n alignItems: \"center\",\n paddingTop: 100,\n gap: 12,\n },\n emptyTitle: {\n fontSize: 22,\n fontWeight: \"700\",\n color: \"#1A1A1A\",\n marginBottom: 4,\n },\n emptySubtitle: {\n fontSize: 15,\n color: \"#666666\",\n marginBottom: 16,\n },\n suggestionPill: {\n backgroundColor: \"#E8F0FE\",\n borderRadius: 20,\n paddingHorizontal: 16,\n paddingVertical: 10,\n },\n suggestionText: {\n color: \"#0066CC\",\n fontWeight: \"600\",\n fontSize: 14,\n },\n toolCallIndicator: {\n alignSelf: \"flex-start\",\n backgroundColor: \"#F0F0F0\",\n borderRadius: 12,\n paddingHorizontal: 12,\n paddingVertical: 6,\n marginBottom: 8,\n },\n toolCallText: {\n fontSize: 12,\n color: \"#999999\",\n fontStyle: \"italic\",\n },\n errorContainer: {\n backgroundColor: \"#FEE2E2\",\n paddingHorizontal: 12,\n paddingVertical: 8,\n marginHorizontal: 8,\n borderRadius: 8,\n },\n errorText: {\n color: \"#DC2626\",\n fontSize: 13,\n },\n});\n","/**\n * CopilotModal — a bottom-sheet chat overlay for React Native.\n *\n * Mobile equivalent of CopilotPopup on web. Wraps CopilotChat inside\n * @gorhom/bottom-sheet so the chat can slide up over any screen.\n */\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n} from \"react\";\nimport { StyleSheet } from \"react-native\";\nimport BottomSheet, {\n BottomSheetBackdrop,\n BottomSheetFlatList,\n BottomSheetView,\n} from \"@gorhom/bottom-sheet\";\nimport type { BottomSheetBackdropProps } from \"@gorhom/bottom-sheet\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatProps } from \"./CopilotChat\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CopilotModalProps {\n /** Controlled visibility — when true the sheet opens, when false it closes. */\n visible?: boolean;\n\n /** Called when the sheet is dismissed (via backdrop tap, swipe-down, or close()). */\n onDismiss?: () => void;\n\n /**\n * Bottom-sheet snap points.\n * @default ['50%', '90%']\n */\n snapPoints?: (string | number)[];\n\n /**\n * Which snap-point index to open at.\n * @default 0\n */\n initialSnapIndex?: number;\n\n /**\n * Whether closing the sheet fires onDismiss.\n * @default true\n */\n enableDismissOnClose?: boolean;\n\n /**\n * Backdrop opacity when the sheet is open.\n * @default 0.5\n */\n backdropOpacity?: number;\n\n // -- Pass-through to CopilotChat ------------------------------------------\n\n /** Which agent to connect to. */\n agentName?: string;\n\n /** Input placeholder text. */\n placeholder?: string;\n\n /** Seed messages shown on first render. */\n initialMessages?: string[];\n\n /** Title shown in the CopilotChat header area. */\n headerTitle?: string;\n}\n\n/** Imperative handle exposed via ref. */\nexport interface CopilotModalRef {\n /** Programmatically open the bottom sheet. */\n open: () => void;\n /** Programmatically close the bottom sheet. */\n close: () => void;\n}\n\n// ---------------------------------------------------------------------------\n// Component\n// ---------------------------------------------------------------------------\n\nexport const CopilotModal = forwardRef<CopilotModalRef, CopilotModalProps>(\n function CopilotModal(\n {\n visible,\n onDismiss,\n snapPoints: snapPointsProp,\n initialSnapIndex = 0,\n enableDismissOnClose = true,\n backdropOpacity = 0.5,\n agentName,\n placeholder,\n initialMessages,\n headerTitle,\n },\n ref,\n ) {\n const bottomSheetRef = useRef<BottomSheet>(null);\n\n // Stable snap-points array\n const snapPoints = useMemo(\n () => snapPointsProp ?? [\"50%\", \"90%\"],\n [snapPointsProp],\n );\n\n // ── Imperative API ────────────────────────────────────────────────────\n useImperativeHandle(\n ref,\n () => ({\n open() {\n bottomSheetRef.current?.snapToIndex(initialSnapIndex);\n },\n close() {\n bottomSheetRef.current?.close();\n },\n }),\n [initialSnapIndex],\n );\n\n // ── Controlled visibility ─────────────────────────────────────────────\n useEffect(() => {\n if (visible === undefined) return;\n if (visible) {\n bottomSheetRef.current?.snapToIndex(initialSnapIndex);\n } else {\n bottomSheetRef.current?.close();\n }\n }, [visible, initialSnapIndex]);\n\n // ── Backdrop renderer ─────────────────────────────────────────────────\n const renderBackdrop = useCallback(\n (props: BottomSheetBackdropProps) => (\n <BottomSheetBackdrop\n {...props}\n disappearsOnIndex={-1}\n appearsOnIndex={0}\n opacity={backdropOpacity}\n pressBehavior=\"close\"\n />\n ),\n [backdropOpacity],\n );\n\n // ── Sheet close handler ───────────────────────────────────────────────\n const handleClose = useCallback(() => {\n if (enableDismissOnClose) {\n onDismiss?.();\n }\n }, [enableDismissOnClose, onDismiss]);\n\n // ── Build CopilotChat props ───────────────────────────────────────────\n const chatProps = useMemo(() => {\n const props: Partial<CopilotChatProps> = {};\n if (agentName !== undefined) props.agentName = agentName;\n if (placeholder !== undefined) props.placeholder = placeholder;\n if (initialMessages !== undefined)\n props.initialMessages = initialMessages;\n if (headerTitle !== undefined) props.headerTitle = headerTitle;\n return props;\n }, [agentName, placeholder, initialMessages, headerTitle]);\n\n return (\n <BottomSheet\n ref={bottomSheetRef}\n index={-1}\n snapPoints={snapPoints}\n enablePanDownToClose\n backdropComponent={renderBackdrop}\n onClose={handleClose}\n keyboardBehavior=\"interactive\"\n keyboardBlurBehavior=\"restore\"\n backgroundStyle={styles.sheetBackground}\n handleIndicatorStyle={styles.handleIndicator}\n >\n <BottomSheetView style={styles.contentContainer}>\n <CopilotChat\n {...chatProps}\n FlatListComponent={BottomSheetFlatList}\n disableKeyboardAvoiding\n />\n </BottomSheetView>\n </BottomSheet>\n );\n },\n);\n\n// ---------------------------------------------------------------------------\n// Styles\n// ---------------------------------------------------------------------------\n\nconst styles = StyleSheet.create({\n sheetBackground: {\n backgroundColor: \"#FFFFFF\",\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n },\n handleIndicator: {\n width: 40,\n height: 4,\n backgroundColor: \"#DDDDDD\",\n },\n contentContainer: {\n flex: 1,\n },\n});\n"],"mappings":";;;;;;;;;;;AAYA,MAAM,WAAW;AACjB,MAAM,cAAc;AACpB,MAAM,qBAAqB;;;;;;;AAQ3B,SAAgB,gBAAgB,EAAE,SAA+B;CAC/D,MAAM,CAAC,QAAQ,eAAe,IAAI,SAAS,MAAM,EAAE,CAAC;CACpD,MAAM,CAAC,QAAQ,eAAe,IAAI,SAAS,MAAM,EAAE,CAAC;CACpD,MAAM,CAAC,QAAQ,eAAe,IAAI,SAAS,MAAM,EAAE,CAAC;AAEpD,iBAAgB;EACd,MAAM,eAAe,KAAqB,UACxC,SAAS,SAAS,CAChB,SAAS,MAAM,MAAM,EACrB,SAAS,KACP,SAAS,SAAS,CAChB,SAAS,OAAO,KAAK;GACnB,SAAS;GACT,UAAU;GACV,iBAAiB;GAClB,CAAC,EACF,SAAS,OAAO,KAAK;GACnB,SAAS;GACT,UAAU;GACV,iBAAiB;GAClB,CAAC,CACH,CAAC,CACH,CACF,CAAC;EAEJ,MAAM,YAAY,SAAS,SAAS;GAClC,YAAY,MAAM,EAAE;GACpB,YAAY,MAAM,qBAAqB,IAAK;GAC5C,YAAY,MAAM,qBAAqB,IAAK;GAC7C,CAAC;AAEF,YAAU,OAAO;AAEjB,eAAa;AACX,aAAU,MAAM;;IAEjB;EAAC;EAAM;EAAM;EAAK,CAAC;CAEtB,MAAM,YAAY,mBAAmC;EACnD,GAAGA,SAAO;EACV,SAAS,cAAc,YAAY;GACjC,YAAY,CAAC,GAAG,EAAE;GAClB,aAAa,CAAC,IAAK,EAAE;GACtB,CAAC;EACF,WAAW,CACT,EACE,OAAO,cAAc,YAAY;GAC/B,YAAY,CAAC,GAAG,EAAE;GAClB,aAAa,CAAC,IAAK,IAAI;GACxB,CAAC,EACH,CACF;EACF;AAED,QACE,qBAAC;EACC,QAAO;EACP,OAAO,CAACA,SAAO,WAAW,M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nB;AAMD,MAAM,SAAS,WAAW,OAAO;CAC/B,iBAAiB;EACf,iBAAiB;EACjB,qBAAqB;EACrB,sBAAsB;EACvB;CACD,iBAAiB;EACf,OAAO;EACP,QAAQ;EACR,iBAAiB;EAClB;CACD,kBAAkB,EAChB,MAAM,GACP;CACF,CAAC"}
|
package/dist/index.cjs
CHANGED
|
@@ -345,7 +345,7 @@ const CopilotSidebar = (0, react.forwardRef)(function CopilotSidebar({ agentId,
|
|
|
345
345
|
const { width: screenWidth } = (0, react_native.useWindowDimensions)();
|
|
346
346
|
const drawerWidth = resolveWidth(widthProp, screenWidth);
|
|
347
347
|
const [isOpen, setIsOpen] = (0, react.useState)(defaultOpen);
|
|
348
|
-
const slideAnim = (0, react.
|
|
348
|
+
const [slideAnim] = (0, react.useState)(() => new react_native.Animated.Value(defaultOpen ? 0 : drawerWidth));
|
|
349
349
|
(0, react.useEffect)(() => {
|
|
350
350
|
if (!isOpen) slideAnim.setValue(drawerWidth);
|
|
351
351
|
}, [
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["FileSystem","DocumentPicker","DEFAULT_AGENT_ID","CopilotChatConfigurationProvider","Animated","Pressable","styles","View","Text","StyleSheet","TouchableOpacity","Text","Modal","Pressable","View","StyleSheet"],"sources":["../src/hooks/use-attachments.ts","../src/CopilotChat.tsx","../src/CopilotModal.tsx","../src/CopilotSidebar.tsx","../src/CopilotPopup.tsx"],"sourcesContent":["// packages/react-native/src/hooks/use-attachments.ts\nimport { useCallback, useRef, useState } from \"react\";\nimport {\n randomUUID,\n getModalityFromMimeType,\n formatFileSize,\n} from \"@copilotkit/shared\";\nimport type {\n Attachment,\n AttachmentUploadResult,\n AttachmentUploadErrorReason,\n} from \"@copilotkit/shared\";\nimport * as DocumentPicker from \"expo-document-picker\";\nimport * as FileSystem from \"expo-file-system\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Platform-neutral file descriptor for React Native.\n * Replaces the web `File` object in all attachment APIs.\n */\nexport interface NativeFileInput {\n /** Local file URI (e.g. `file:///path/to/file`). */\n uri: string;\n /** Filename with extension. */\n name: string;\n /** File size in bytes. */\n size: number;\n /** MIME type (e.g. `\"image/jpeg\"`). */\n mimeType: string;\n}\n\n/**\n * React Native variant of AttachmentsConfig.\n * Identical to the shared AttachmentsConfig except `onUpload` receives\n * a `NativeFileInput` instead of a web `File`.\n */\nexport interface NativeAttachmentsConfig {\n /** Enable file attachments in the chat input. */\n enabled: boolean;\n /** MIME type filter for the file picker, default all files. */\n accept?: string;\n /** Maximum file size in bytes, default 20MB (20 * 1024 * 1024). */\n maxSize?: number;\n /** Custom upload handler. Receives the native file descriptor. */\n onUpload?: (\n file: NativeFileInput,\n ) => AttachmentUploadResult | Promise<AttachmentUploadResult>;\n /** Called when an attachment fails validation or upload. */\n onUploadFailed?: (error: {\n reason: AttachmentUploadErrorReason;\n file: NativeFileInput;\n message: string;\n }) => void;\n}\n\nexport interface UseNativeAttachmentsProps {\n config?: NativeAttachmentsConfig;\n}\n\nexport interface UseNativeAttachmentsReturn {\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n enabled: boolean;\n /** Open the native document picker. */\n openPicker: () => Promise<void>;\n /** Process an array of NativeFileInput objects (validate, read, add to state). */\n processFiles: (files: NativeFileInput[]) => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /** Consume ready attachments and clear the queue. Returns the consumed attachments. */\n consumeAttachments: () => Attachment[];\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20 MB\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * React Native hook that manages file attachment state -- picking, uploading,\n * and lifecycle. All returned callbacks are referentially stable via useCallback.\n *\n * This is the RN counterpart of the web `useAttachments` hook from\n * `@copilotkit/react-core`. It replaces web APIs (FileReader, DragEvent,\n * HTMLInputElement) with Expo modules (expo-document-picker, expo-file-system).\n */\nexport function useAttachments({\n config,\n}: UseNativeAttachmentsProps): UseNativeAttachmentsReturn {\n const enabled = config?.enabled ?? false;\n\n const [attachments, setAttachments] = useState<Attachment[]>([]);\n\n // Refs for stable callbacks to read latest values\n const configRef = useRef(config);\n configRef.current = config;\n const attachmentsRef = useRef<Attachment[]>([]);\n attachmentsRef.current = attachments;\n\n /**\n * Simple MIME accept filter for NativeFileInput.\n * Handles wildcards like \"image/*\" and exact types like \"application/pdf\".\n * Comma-separated lists are supported.\n */\n const matchesAccept = useCallback(\n (file: NativeFileInput, accept: string): boolean => {\n if (!accept || accept === \"*/*\") return true;\n const filters = accept.split(\",\").map((f) => f.trim());\n return filters.some((filter) => {\n if (filter.startsWith(\".\")) {\n return file.name.toLowerCase().endsWith(filter.toLowerCase());\n }\n if (filter.endsWith(\"/*\")) {\n const prefix = filter.slice(0, -2);\n return file.mimeType.startsWith(prefix + \"/\");\n }\n return file.mimeType === filter;\n });\n },\n [],\n );\n\n const processFiles = useCallback(\n async (files: NativeFileInput[]) => {\n const cfg = configRef.current;\n const accept = cfg?.accept ?? \"*/*\";\n const maxSize = cfg?.maxSize ?? DEFAULT_MAX_SIZE;\n\n // Filter by accept type\n const rejectedFiles = files.filter((f) => !matchesAccept(f, accept));\n for (const file of rejectedFiles) {\n cfg?.onUploadFailed?.({\n reason: \"invalid-type\",\n file,\n message: `File \"${file.name}\" is not accepted. Supported types: ${accept}`,\n });\n }\n\n const validFiles = files.filter((f) => matchesAccept(f, accept));\n\n for (const file of validFiles) {\n // Size check\n if (file.size > maxSize) {\n cfg?.onUploadFailed?.({\n reason: \"file-too-large\",\n file,\n message: `File \"${file.name}\" exceeds the maximum size of ${formatFileSize(maxSize)}`,\n });\n continue;\n }\n\n const modality = getModalityFromMimeType(file.mimeType);\n const placeholderId = randomUUID();\n const placeholder: Attachment = {\n id: placeholderId,\n type: modality,\n source: { type: \"data\", value: \"\", mimeType: file.mimeType },\n filename: file.name,\n size: file.size,\n status: \"uploading\",\n };\n\n setAttachments((prev) => [...prev, placeholder]);\n\n try {\n let source: Attachment[\"source\"];\n let uploadMetadata: Record<string, unknown> | undefined;\n\n if (cfg?.onUpload) {\n const { metadata: meta, ...uploadSource } =\n await cfg.onUpload(file);\n source = uploadSource;\n uploadMetadata = meta;\n } else {\n // Default: read file as base64 via expo-file-system\n const base64 = await FileSystem.readAsStringAsync(file.uri, {\n encoding: FileSystem.EncodingType.Base64,\n });\n source = { type: \"data\", value: base64, mimeType: file.mimeType };\n }\n\n setAttachments((prev) =>\n prev.map((att) =>\n att.id === placeholderId\n ? {\n ...att,\n source,\n status: \"ready\" as const,\n metadata: uploadMetadata,\n }\n : att,\n ),\n );\n } catch (error) {\n // Remove placeholder on failure\n setAttachments((prev) =>\n prev.filter((att) => att.id !== placeholderId),\n );\n console.error(`[CopilotKit] Failed to upload \"${file.name}\":`, error);\n cfg?.onUploadFailed?.({\n reason: \"upload-failed\",\n file,\n message:\n error instanceof Error\n ? error.message\n : `Failed to upload \"${file.name}\"`,\n });\n }\n }\n },\n [matchesAccept],\n );\n\n const openPicker = useCallback(async () => {\n const cfg = configRef.current;\n const accept = cfg?.accept ?? \"*/*\";\n\n // Convert accept string to array for DocumentPicker\n const typeArray = accept\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean);\n\n try {\n const result = await DocumentPicker.getDocumentAsync({\n type: typeArray.length > 0 ? typeArray : [\"*/*\"],\n copyToCacheDirectory: true,\n multiple: true,\n });\n\n if (result.canceled || !result.assets?.length) return;\n\n const nativeFiles: NativeFileInput[] = result.assets.map((asset) => ({\n uri: asset.uri,\n name: asset.name ?? \"unknown\",\n size: asset.size ?? 0,\n mimeType: asset.mimeType ?? \"application/octet-stream\",\n }));\n\n await processFiles(nativeFiles);\n } catch (error) {\n console.error(\"[CopilotKit] Document picker error:\", error);\n }\n }, [processFiles]);\n\n const removeAttachment = useCallback((id: string) => {\n setAttachments((prev) => prev.filter((a) => a.id !== id));\n }, []);\n\n const consumeAttachments = useCallback(() => {\n const ready = attachmentsRef.current.filter((a) => a.status === \"ready\");\n if (ready.length === 0) return ready;\n setAttachments((prev) => prev.filter((a) => a.status !== \"ready\"));\n return ready;\n }, []);\n\n return {\n attachments,\n enabled,\n openPicker,\n processFiles,\n removeAttachment,\n consumeAttachments,\n };\n}\n","import React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useRef,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotChatConfigurationProvider,\n useAgent,\n useCopilotChatConfiguration,\n} from \"@copilotkit/react-core/headless\";\nimport { useCopilotKit } from \"@copilotkit/react-core/context\";\nimport { DEFAULT_AGENT_ID, randomUUID } from \"@copilotkit/shared\";\nimport type { InputContent } from \"@copilotkit/shared\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport { useAttachments } from \"./hooks/use-attachments\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { Attachment } from \"@copilotkit/shared\";\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatContextValue {\n /** The resolved agent instance. */\n agent: any;\n /** Whether the agent is currently running. */\n isRunning: boolean;\n /** Current messages in the conversation. */\n messages: any[];\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n attachmentsEnabled: boolean;\n /** Open the native document picker to add files. */\n openPicker: () => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /**\n * Submit a message with optional attachments.\n * Handles consuming ready attachments, building InputContent[],\n * calling agent.addMessage, and running the agent.\n */\n submitMessage: (text: string) => Promise<void>;\n}\n\nconst CopilotChatCtx = createContext<CopilotChatContextValue | null>(null);\n\n/**\n * Hook to access the CopilotChat context from child components.\n * Must be called inside a `<CopilotChat>` component tree.\n */\nexport function useCopilotChatContext(): CopilotChatContextValue {\n const ctx = useContext(CopilotChatCtx);\n if (!ctx) {\n throw new Error(\n \"useCopilotChatContext must be used within a <CopilotChat> component\",\n );\n }\n return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Props\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatBaseProps {\n /**\n * The agent ID to use for this chat session.\n * Matches the web SDK's CopilotChat `agentId` prop.\n *\n * Resolution order: `agentId` > `agentName` > the agent of the chat (or\n * `CopilotChatConfigurationProvider`) around this one > `\"default\"`\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead. `agentName` is kept for backwards\n * compatibility and will be removed in a future release.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session. When provided, the chat will resume\n * the specified thread. Matches the web SDK's CopilotChat `threadId` prop.\n */\n threadId?: string;\n\n /**\n * Error handler scoped to this chat's agent. Fires in addition to the\n * provider-level onError (does not suppress it). Receives errors whose\n * context.agentId matches this chat's agent, and errors with no agentId.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n\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 *\n * @default undefined -- inherits from provider `defaultThrottleMs`;\n * if that is also unset, re-renders are unthrottled.\n */\n throttleMs?: number;\n\n /**\n * Enable multimodal file attachments (images, audio, video, documents).\n * Pass a NativeAttachmentsConfig object to configure file picking behavior.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Optional children rendered inside the chat context.\n */\n children?: ReactNode;\n}\n\nexport interface CopilotChatProps extends CopilotChatBaseProps {\n /** Passthrough props are forwarded to consumers via the agent context. */\n [key: string]: unknown;\n}\n\n/**\n * Headless CopilotChat component for React Native.\n *\n * Wires up the `useAgent` hook with `agentId` resolution and renders children.\n * Unlike the web SDK's CopilotChat, this component does not render any UI\n * elements -- consumers provide their own React Native views.\n *\n * Children can access chat state via `useCopilotChatContext()`.\n *\n * Hooks inside the chat, such as `useAgent` and `useInterrupt`, use this\n * chat's agent when they do not pass an `agentId`. When the chat has a\n * `threadId`, `useAgent` inside the chat sets that thread on each agent it\n * returns, also on an agent that the hook names with its own `agentId`. Only\n * `useAgent({ agentId, runtimeAgentId, threadId })` keeps a different thread.\n *\n * A chat inside another chat uses the outer chat's agent when it has no\n * `agentId`. When the outer chat has a `threadId` and the inner chat does not,\n * the inner chat uses the outer thread. The web `CopilotChat` does the same.\n *\n * ```tsx\n * import { CopilotChat, useCopilotChatContext } from \"@copilotkit/react-native\";\n *\n * function MyChatUI() {\n * const { messages, submitMessage, attachments, openPicker } = useCopilotChatContext();\n * // ... render your UI\n * }\n *\n * <CopilotChat agentId=\"my-agent\" attachments={{ enabled: true }}>\n * <MyChatUI />\n * </CopilotChat>\n * ```\n */\nexport function CopilotChat({\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n attachments: attachmentsConfig,\n children,\n ..._rest\n}: CopilotChatProps) {\n // Same precedence as the web CopilotChat: a chat that names no agent takes\n // the agent of the chat configuration around it before \"default\".\n const chatConfig = useCopilotChatConfiguration();\n const resolvedAgentId =\n agentId ?? agentName ?? chatConfig?.agentId ?? DEFAULT_AGENT_ID;\n\n // Deprecation warning (dev only, fires once per mount)\n const warnedRef = useRef(false);\n useEffect(() => {\n if (\n agentName !== undefined &&\n agentId === undefined &&\n !warnedRef.current\n ) {\n warnedRef.current = true;\n if (typeof __DEV__ === \"undefined\" || __DEV__) {\n console.warn(\n \"[CopilotKit] agentName is deprecated, use agentId instead\",\n );\n }\n }\n }, [agentName, agentId]);\n\n const { agent } = useAgent({ agentId: resolvedAgentId, throttleMs });\n\n // Set threadId on the agent when provided\n useEffect(() => {\n if (threadId) {\n agent.threadId = threadId;\n }\n }, [agent, threadId]);\n\n // onError subscription -- forward core errors scoped to this chat's agent\n const { copilotkit } = useCopilotKit();\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n if (!onErrorRef.current) return;\n\n const subscription = copilotkit.subscribe({\n onError: (event) => {\n // Only forward errors that match this chat's agent\n if (\n event.context?.agentId === resolvedAgentId ||\n !event.context?.agentId\n ) {\n void onErrorRef.current?.({\n error: event.error,\n code: event.code,\n context: event.context,\n });\n }\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit, resolvedAgentId]);\n\n // Attachments\n const {\n attachments: selectedAttachments,\n enabled: attachmentsEnabled,\n openPicker,\n removeAttachment,\n consumeAttachments,\n } = useAttachments({ config: attachmentsConfig });\n\n // Submit handler -- mirrors web CopilotChat.tsx lines 234-288\n const submitMessage = useCallback(\n async (value: string) => {\n // Block if uploads in progress\n const hasUploading = selectedAttachments.some(\n (a) => a.status === \"uploading\",\n );\n if (hasUploading) {\n console.error(\n \"[CopilotKit] Cannot send while attachments are uploading\",\n );\n return;\n }\n\n const readyAttachments = consumeAttachments();\n\n if (readyAttachments.length > 0) {\n const contentParts: InputContent[] = [];\n if (value.trim()) {\n contentParts.push({ type: \"text\", text: value });\n }\n for (const att of readyAttachments) {\n contentParts.push({\n type: att.type,\n source: att.source,\n metadata: {\n ...(att.filename ? { filename: att.filename } : {}),\n ...att.metadata,\n },\n } as InputContent);\n }\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: contentParts,\n });\n } else {\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: value,\n });\n }\n\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed\", error);\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 [agent, selectedAttachments, consumeAttachments],\n );\n\n const contextValue: CopilotChatContextValue = {\n agent,\n isRunning: agent.isRunning,\n messages: agent.messages,\n attachments: selectedAttachments,\n attachmentsEnabled,\n openPicker,\n removeAttachment,\n submitMessage,\n };\n\n // Publish this chat's agent and thread to the subtree, as the web\n // CopilotChat does. Hooks inside it that name no agent use this chat's\n // agent, which is the outer chat's agent when this chat names none.\n return (\n <CopilotChatConfigurationProvider\n agentId={resolvedAgentId}\n threadId={threadId}\n >\n <CopilotChatCtx.Provider value={contextValue}>\n {children}\n </CopilotChatCtx.Provider>\n </CopilotChatConfigurationProvider>\n );\n}\n","import React, { type ReactNode } from \"react\";\nimport { CopilotChat, type CopilotChatProps } from \"./CopilotChat\";\n\nexport interface CopilotModalProps extends CopilotChatProps {\n /**\n * Optional children rendered inside the modal context.\n */\n children?: ReactNode;\n}\n\n/**\n * Headless CopilotModal component for React Native.\n *\n * A thin wrapper around CopilotChat that mirrors the web SDK's CopilotModal\n * API surface. On React Native, modal presentation is handled by the consumer\n * (e.g. React Native's `Modal` component) -- this component only provides\n * the agent wiring and prop resolution.\n *\n * ```tsx\n * import { CopilotModal } from \"@copilotkit/react-native\";\n * import { Modal } from \"react-native\";\n *\n * <Modal visible={isOpen}>\n * <CopilotModal agentId=\"my-agent\">\n * <MyChatUI />\n * </CopilotModal>\n * </Modal>\n * ```\n */\nexport function CopilotModal({ children, ...props }: CopilotModalProps) {\n return <CopilotChat {...props}>{children}</CopilotChat>;\n}\n","import React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Animated,\n Dimensions,\n Pressable,\n StyleSheet,\n Text,\n useWindowDimensions,\n View,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatBaseProps } from \"./CopilotChat\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CopilotSidebarHandle {\n /** Slide the drawer open. */\n open(): void;\n /** Slide the drawer closed. */\n close(): void;\n /** Toggle the drawer open/closed. */\n toggle(): void;\n}\n\nexport interface CopilotSidebarProps extends Omit<\n CopilotChatBaseProps,\n \"children\"\n> {\n /**\n * Start the drawer in the open position.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Width of the drawer panel. Accepts a number (points) or a percentage\n * string (e.g. `\"85%\"`). Defaults to 85% of the screen width.\n */\n width?: number | string;\n\n /**\n * Title displayed in the drawer header bar.\n * @default \"Copilot\"\n */\n headerTitle?: string;\n\n /**\n * Show a floating action button to toggle the drawer.\n * @default true\n */\n showToggleButton?: boolean;\n\n /** Called after the drawer finishes opening. */\n onOpen?: () => void;\n\n /** Called after the drawer finishes closing. */\n onClose?: () => void;\n\n /** Custom style applied to the drawer container. */\n style?: ViewStyle;\n\n /**\n * Your chat UI, rendered inside the drawer below the header. The inner\n * CopilotChat is headless and draws no messages or input of its own.\n */\n children?: ReactNode;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst ANIMATION_DURATION_MS = 300;\nconst DEFAULT_HEADER_TITLE = \"Copilot\";\nconst BACKDROP_OPACITY = 0.4;\nconst FAB_SIZE = 56;\n\n// ---------------------------------------------------------------------------\n// Component\n// ---------------------------------------------------------------------------\n\n/**\n * CopilotSidebar -- a slide-in drawer from the right edge of the screen\n * that wraps CopilotChat for React Native.\n *\n * ```tsx\n * import { CopilotSidebar } from \"@copilotkit/react-native\";\n *\n * const ref = useRef<CopilotSidebarHandle>(null);\n *\n * <CopilotSidebar\n * ref={ref}\n * agentId=\"my-agent\"\n * headerTitle=\"Assistant\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotSidebar = forwardRef<\n CopilotSidebarHandle,\n CopilotSidebarProps\n>(function CopilotSidebar(\n {\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n defaultOpen = false,\n width: widthProp,\n headerTitle = DEFAULT_HEADER_TITLE,\n showToggleButton = true,\n onOpen,\n onClose,\n style,\n children,\n ...rest\n },\n ref,\n) {\n const { width: screenWidth } = useWindowDimensions();\n\n // Resolve drawer width ---------------------------------------------------\n const drawerWidth = resolveWidth(widthProp, screenWidth);\n\n // Animation & open state -------------------------------------------------\n const [isOpen, setIsOpen] = useState(defaultOpen);\n const slideAnim = useRef(\n new Animated.Value(defaultOpen ? 0 : drawerWidth),\n ).current;\n\n // Keep the animated value in sync when drawerWidth changes while closed\n useEffect(() => {\n if (!isOpen) {\n slideAnim.setValue(drawerWidth);\n }\n }, [drawerWidth, isOpen, slideAnim]);\n\n const animateTo = useCallback(\n (toValue: number, cb?: () => void) => {\n Animated.timing(slideAnim, {\n toValue,\n duration: ANIMATION_DURATION_MS,\n useNativeDriver: true,\n }).start(({ finished }) => {\n if (finished) cb?.();\n });\n },\n [slideAnim],\n );\n\n const open = useCallback(() => {\n setIsOpen(true);\n animateTo(0, onOpen);\n }, [animateTo, onOpen]);\n\n const close = useCallback(() => {\n animateTo(drawerWidth, () => {\n setIsOpen(false);\n onClose?.();\n });\n }, [animateTo, drawerWidth, onClose]);\n\n const toggle = useCallback(() => {\n if (isOpen) {\n close();\n } else {\n open();\n }\n }, [isOpen, open, close]);\n\n useImperativeHandle(ref, () => ({ open, close, toggle }), [\n open,\n close,\n toggle,\n ]);\n\n // Callbacks stored in refs for stable animation closures -----------------\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n // -----------------------------------------------------------------------\n // Render\n // -----------------------------------------------------------------------\n return (\n <>\n {/* Backdrop */}\n {isOpen && (\n <Pressable\n style={styles.backdrop}\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close sidebar\"\n testID=\"copilot-sidebar-backdrop\"\n />\n )}\n\n {/* Drawer */}\n {isOpen && (\n <Animated.View\n style={[\n styles.drawer,\n { width: drawerWidth, transform: [{ translateX: slideAnim }] },\n style,\n ]}\n testID=\"copilot-sidebar-drawer\"\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <Pressable\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close\"\n hitSlop={8}\n testID=\"copilot-sidebar-close\"\n >\n <Text style={styles.closeButton}>{\"✕\"}</Text>\n </Pressable>\n </View>\n\n {/* Chat area */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n onError={onError}\n throttleMs={throttleMs}\n {...rest}\n >\n {children}\n </CopilotChat>\n </View>\n </Animated.View>\n )}\n\n {/* Floating action button */}\n {showToggleButton && !isOpen && (\n <Pressable\n style={styles.fab}\n onPress={open}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Open sidebar\"\n testID=\"copilot-sidebar-fab\"\n >\n <Text style={styles.fabIcon}>{\"💬\"}</Text>\n </Pressable>\n )}\n </>\n );\n});\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveWidth(\n widthProp: number | string | undefined,\n screenWidth: number,\n): number {\n if (widthProp === undefined) {\n return Math.round(screenWidth * 0.85);\n }\n if (typeof widthProp === \"number\") {\n return widthProp;\n }\n // Percentage string, e.g. \"85%\"\n const pctMatch = String(widthProp).match(/^(\\d+(?:\\.\\d+)?)%$/);\n if (pctMatch) {\n return Math.round(screenWidth * (parseFloat(pctMatch[1]) / 100));\n }\n // Fallback: try parsing as number\n const parsed = parseFloat(widthProp);\n return isNaN(parsed) ? Math.round(screenWidth * 0.85) : parsed;\n}\n\n// ---------------------------------------------------------------------------\n// Styles\n// ---------------------------------------------------------------------------\n\nconst styles = StyleSheet.create({\n backdrop: {\n ...StyleSheet.absoluteFill,\n backgroundColor: `rgba(0, 0, 0, ${BACKDROP_OPACITY})`,\n zIndex: 999,\n },\n drawer: {\n position: \"absolute\",\n top: 0,\n right: 0,\n bottom: 0,\n backgroundColor: \"#ffffff\",\n zIndex: 1000,\n shadowColor: \"#000\",\n shadowOffset: { width: -2, height: 0 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n elevation: 16,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e0e0e0\",\n },\n headerTitle: {\n fontSize: 18,\n fontWeight: \"600\",\n color: \"#1a1a1a\",\n },\n closeButton: {\n fontSize: 20,\n color: \"#666\",\n padding: 4,\n },\n chatContainer: {\n flex: 1,\n },\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: FAB_SIZE,\n height: FAB_SIZE,\n borderRadius: FAB_SIZE / 2,\n backgroundColor: \"#007AFF\",\n alignItems: \"center\",\n justifyContent: \"center\",\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 2 },\n shadowOpacity: 0.3,\n shadowRadius: 4,\n elevation: 8,\n zIndex: 998,\n },\n fabIcon: {\n fontSize: 24,\n },\n});\n","// NOTE: This component needs to be exported from index.ts\n// e.g. export { CopilotPopup } from \"./CopilotPopup\";\n// export type { CopilotPopupProps, CopilotPopupHandle } from \"./CopilotPopup\";\n\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Modal,\n Pressable,\n StyleSheet,\n Text,\n TouchableOpacity,\n View,\n useWindowDimensions,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\n\nexport interface CopilotPopupProps {\n /**\n * The agent ID to use for this chat session.\n * Passed through to CopilotChat.\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session.\n */\n threadId?: string;\n\n /**\n * Throttle interval (ms) for re-renders.\n */\n throttleMs?: number;\n\n /**\n * Whether the popup starts in the open state.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Height of the popup card. Accepts a number (points) or a percentage\n * string (e.g. \"60%\") relative to the screen height.\n * @default \"60%\"\n */\n height?: number | string;\n\n /**\n * Error handler scoped to this popup's chat agent.\n */\n onError?: (error: Error) => void;\n\n /**\n * Title displayed in the popup header bar.\n * @default \"CopilotKit\"\n */\n headerTitle?: string;\n\n /**\n * Enable multimodal file attachments. Forwarded to the internal CopilotChat.\n * Children access attachment state via `useCopilotChatContext()`.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Your chat UI, rendered inside the popup card below the header. The inner\n * CopilotChat is headless and draws no messages or input of its own.\n */\n children?: ReactNode;\n\n /**\n * Callback fired when the popup opens.\n */\n onOpen?: () => void;\n\n /**\n * Callback fired when the popup closes.\n */\n onClose?: () => void;\n\n /**\n * Whether tapping the semi-transparent backdrop dismisses the popup.\n * Equivalent to web SDK's `clickOutsideToClose`.\n * @default true\n */\n dismissOnBackdropPress?: boolean;\n\n /**\n * Whether to show the floating action button (FAB) that toggles the popup.\n * @default true\n */\n showToggleButton?: boolean;\n\n /**\n * Custom styles applied to the popup card container.\n */\n style?: ViewStyle;\n}\n\n/**\n * Imperative handle exposed via ref for controlling the popup programmatically.\n */\nexport interface CopilotPopupHandle {\n open: () => void;\n close: () => void;\n toggle: () => void;\n}\n\n/**\n * CopilotPopup for React Native.\n *\n * A floating action button (FAB) that opens a modal chat overlay.\n * The popup appears as a card floating above content with rounded corners,\n * a shadow, and a semi-transparent backdrop.\n *\n * ```tsx\n * import { CopilotPopup } from \"@copilotkit/react-native\";\n *\n * const popupRef = useRef<CopilotPopupHandle>(null);\n *\n * <CopilotPopup\n * ref={popupRef}\n * agentId=\"my-agent\"\n * headerTitle=\"Chat\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotPopup = forwardRef<CopilotPopupHandle, CopilotPopupProps>(\n function CopilotPopup(\n {\n agentId,\n agentName,\n threadId,\n throttleMs,\n defaultOpen = false,\n height = \"60%\",\n onError,\n headerTitle = \"CopilotKit\",\n attachments: attachmentsConfig,\n children,\n onOpen,\n onClose,\n dismissOnBackdropPress = true,\n showToggleButton = true,\n style,\n }: CopilotPopupProps,\n ref: React.Ref<CopilotPopupHandle>,\n ) {\n const [visible, setVisible] = useState(defaultOpen);\n const { height: screenHeight } = useWindowDimensions();\n\n // Stable refs for callbacks to avoid effect churn\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n const handleOpen = useCallback(() => {\n setVisible(true);\n onOpenRef.current?.();\n }, []);\n\n const handleClose = useCallback(() => {\n setVisible(false);\n onCloseRef.current?.();\n }, []);\n\n const handleToggle = useCallback(() => {\n setVisible((prev) => {\n const next = !prev;\n if (next) {\n onOpenRef.current?.();\n } else {\n onCloseRef.current?.();\n }\n return next;\n });\n }, []);\n\n // Expose imperative methods\n useImperativeHandle(\n ref,\n () => ({\n open: handleOpen,\n close: handleClose,\n toggle: handleToggle,\n }),\n [handleOpen, handleClose, handleToggle],\n );\n\n // Resolve popup height\n const resolvedHeight =\n typeof height === \"string\" && height.endsWith(\"%\")\n ? (parseFloat(height) / 100) * screenHeight\n : typeof height === \"number\"\n ? height\n : 0.6 * screenHeight;\n\n // Wrap onError to match CopilotChat's expected signature\n const chatOnError = onError\n ? (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => onError(event.error)\n : undefined;\n\n return (\n <>\n {/* Floating Action Button */}\n {showToggleButton && !visible && (\n <TouchableOpacity\n testID=\"copilot-popup-fab\"\n style={styles.fab}\n onPress={handleToggle}\n activeOpacity={0.8}\n accessibilityLabel=\"Open chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.fabIcon}>💬</Text>\n </TouchableOpacity>\n )}\n\n {/* Modal Overlay */}\n <Modal\n testID=\"copilot-popup-modal\"\n visible={visible}\n transparent\n animationType=\"slide\"\n onRequestClose={handleClose}\n >\n {/* Backdrop */}\n <Pressable\n testID=\"copilot-popup-backdrop\"\n style={styles.backdrop}\n onPress={dismissOnBackdropPress ? handleClose : undefined}\n >\n {/* Card — stop propagation so tapping the card doesn't dismiss */}\n <Pressable\n testID=\"copilot-popup-card\"\n style={[styles.card, { height: resolvedHeight }, style]}\n onPress={() => {\n // Prevent backdrop press from firing\n }}\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <TouchableOpacity\n testID=\"copilot-popup-close\"\n onPress={handleClose}\n hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}\n accessibilityLabel=\"Close chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.closeButton}>✕</Text>\n </TouchableOpacity>\n </View>\n\n {/* Chat Content */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n throttleMs={throttleMs}\n onError={chatOnError}\n attachments={attachmentsConfig}\n >\n {children}\n </CopilotChat>\n </View>\n </Pressable>\n </Pressable>\n </Modal>\n </>\n );\n },\n);\n\nconst styles = StyleSheet.create({\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: 56,\n height: 56,\n borderRadius: 28,\n backgroundColor: \"#6366f1\",\n alignItems: \"center\",\n justifyContent: \"center\",\n elevation: 6,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 3 },\n shadowOpacity: 0.27,\n shadowRadius: 4.65,\n },\n fabIcon: {\n fontSize: 24,\n },\n backdrop: {\n flex: 1,\n backgroundColor: \"rgba(0, 0, 0, 0.4)\",\n justifyContent: \"flex-end\",\n },\n card: {\n backgroundColor: \"#ffffff\",\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n overflow: \"hidden\",\n elevation: 10,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: -3 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e5e7eb\",\n },\n headerTitle: {\n fontSize: 17,\n fontWeight: \"600\",\n color: \"#111827\",\n },\n closeButton: {\n fontSize: 18,\n color: \"#6b7280\",\n fontWeight: \"500\",\n },\n chatContainer: {\n flex: 1,\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiFA,MAAM,mBAAmB,KAAK,OAAO;;;;;;;;;AAcrC,SAAgB,eAAe,EAC7B,UACwD;CACxD,MAAM,UAAU,QAAQ,WAAW;CAEnC,MAAM,CAAC,aAAa,sCAAyC,EAAE,CAAC;CAGhE,MAAM,8BAAmB,OAAO;AAChC,WAAU,UAAU;CACpB,MAAM,mCAAsC,EAAE,CAAC;AAC/C,gBAAe,UAAU;;;;;;CAOzB,MAAM,wCACH,MAAuB,WAA4B;AAClD,MAAI,CAAC,UAAU,WAAW,MAAO,QAAO;AAExC,SADgB,OAAO,MAAM,IAAI,CAAC,KAAK,MAAM,EAAE,MAAM,CAAC,CACvC,MAAM,WAAW;AAC9B,OAAI,OAAO,WAAW,IAAI,CACxB,QAAO,KAAK,KAAK,aAAa,CAAC,SAAS,OAAO,aAAa,CAAC;AAE/D,OAAI,OAAO,SAAS,KAAK,EAAE;IACzB,MAAM,SAAS,OAAO,MAAM,GAAG,GAAG;AAClC,WAAO,KAAK,SAAS,WAAW,SAAS,IAAI;;AAE/C,UAAO,KAAK,aAAa;IACzB;IAEJ,EAAE,CACH;CAED,MAAM,sCACJ,OAAO,UAA6B;EAClC,MAAM,MAAM,UAAU;EACtB,MAAM,SAAS,KAAK,UAAU;EAC9B,MAAM,UAAU,KAAK,WAAW;EAGhC,MAAM,gBAAgB,MAAM,QAAQ,MAAM,CAAC,cAAc,GAAG,OAAO,CAAC;AACpE,OAAK,MAAM,QAAQ,cACjB,MAAK,iBAAiB;GACpB,QAAQ;GACR;GACA,SAAS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Aa;EACX,UAAU;EACV,OAAO;EACP,YAAY;EACb;CACD,eAAe,EACb,MAAM,GACP;CACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["FileSystem","DocumentPicker","DEFAULT_AGENT_ID","CopilotChatConfigurationProvider","Animated","Pressable","styles","View","Text","StyleSheet","TouchableOpacity","Text","Modal","Pressable","View","StyleSheet"],"sources":["../src/hooks/use-attachments.ts","../src/CopilotChat.tsx","../src/CopilotModal.tsx","../src/CopilotSidebar.tsx","../src/CopilotPopup.tsx"],"sourcesContent":["// packages/react-native/src/hooks/use-attachments.ts\nimport { useCallback, useRef, useState } from \"react\";\nimport {\n randomUUID,\n getModalityFromMimeType,\n formatFileSize,\n} from \"@copilotkit/shared\";\nimport type {\n Attachment,\n AttachmentUploadResult,\n AttachmentUploadErrorReason,\n} from \"@copilotkit/shared\";\nimport * as DocumentPicker from \"expo-document-picker\";\nimport * as FileSystem from \"expo-file-system\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Platform-neutral file descriptor for React Native.\n * Replaces the web `File` object in all attachment APIs.\n */\nexport interface NativeFileInput {\n /** Local file URI (e.g. `file:///path/to/file`). */\n uri: string;\n /** Filename with extension. */\n name: string;\n /** File size in bytes. */\n size: number;\n /** MIME type (e.g. `\"image/jpeg\"`). */\n mimeType: string;\n}\n\n/**\n * React Native variant of AttachmentsConfig.\n * Identical to the shared AttachmentsConfig except `onUpload` receives\n * a `NativeFileInput` instead of a web `File`.\n */\nexport interface NativeAttachmentsConfig {\n /** Enable file attachments in the chat input. */\n enabled: boolean;\n /** MIME type filter for the file picker, default all files. */\n accept?: string;\n /** Maximum file size in bytes, default 20MB (20 * 1024 * 1024). */\n maxSize?: number;\n /** Custom upload handler. Receives the native file descriptor. */\n onUpload?: (\n file: NativeFileInput,\n ) => AttachmentUploadResult | Promise<AttachmentUploadResult>;\n /** Called when an attachment fails validation or upload. */\n onUploadFailed?: (error: {\n reason: AttachmentUploadErrorReason;\n file: NativeFileInput;\n message: string;\n }) => void;\n}\n\nexport interface UseNativeAttachmentsProps {\n config?: NativeAttachmentsConfig;\n}\n\nexport interface UseNativeAttachmentsReturn {\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n enabled: boolean;\n /** Open the native document picker. */\n openPicker: () => Promise<void>;\n /** Process an array of NativeFileInput objects (validate, read, add to state). */\n processFiles: (files: NativeFileInput[]) => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /** Consume ready attachments and clear the queue. Returns the consumed attachments. */\n consumeAttachments: () => Attachment[];\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20 MB\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * React Native hook that manages file attachment state -- picking, uploading,\n * and lifecycle. All returned callbacks are referentially stable via useCallback.\n *\n * This is the RN counterpart of the web `useAttachments` hook from\n * `@copilotkit/react-core`. It replaces web APIs (FileReader, DragEvent,\n * HTMLInputElement) with Expo modules (expo-document-picker, expo-file-system).\n */\nexport function useAttachments({\n config,\n}: UseNativeAttachmentsProps): UseNativeAttachmentsReturn {\n const enabled = config?.enabled ?? false;\n\n const [attachments, setAttachments] = useState<Attachment[]>([]);\n\n // Refs for stable callbacks to read latest values\n const configRef = useRef(config);\n configRef.current = config;\n const attachmentsRef = useRef<Attachment[]>([]);\n attachmentsRef.current = attachments;\n\n /**\n * Simple MIME accept filter for NativeFileInput.\n * Handles wildcards like \"image/*\" and exact types like \"application/pdf\".\n * Comma-separated lists are supported.\n */\n const matchesAccept = useCallback(\n (file: NativeFileInput, accept: string): boolean => {\n if (!accept || accept === \"*/*\") return true;\n const filters = accept.split(\",\").map((f) => f.trim());\n return filters.some((filter) => {\n if (filter.startsWith(\".\")) {\n return file.name.toLowerCase().endsWith(filter.toLowerCase());\n }\n if (filter.endsWith(\"/*\")) {\n const prefix = filter.slice(0, -2);\n return file.mimeType.startsWith(prefix + \"/\");\n }\n return file.mimeType === filter;\n });\n },\n [],\n );\n\n const processFiles = useCallback(\n async (files: NativeFileInput[]) => {\n const cfg = configRef.current;\n const accept = cfg?.accept ?? \"*/*\";\n const maxSize = cfg?.maxSize ?? DEFAULT_MAX_SIZE;\n\n // Filter by accept type\n const rejectedFiles = files.filter((f) => !matchesAccept(f, accept));\n for (const file of rejectedFiles) {\n cfg?.onUploadFailed?.({\n reason: \"invalid-type\",\n file,\n message: `File \"${file.name}\" is not accepted. Supported types: ${accept}`,\n });\n }\n\n const validFiles = files.filter((f) => matchesAccept(f, accept));\n\n for (const file of validFiles) {\n // Size check\n if (file.size > maxSize) {\n cfg?.onUploadFailed?.({\n reason: \"file-too-large\",\n file,\n message: `File \"${file.name}\" exceeds the maximum size of ${formatFileSize(maxSize)}`,\n });\n continue;\n }\n\n const modality = getModalityFromMimeType(file.mimeType);\n const placeholderId = randomUUID();\n const placeholder: Attachment = {\n id: placeholderId,\n type: modality,\n source: { type: \"data\", value: \"\", mimeType: file.mimeType },\n filename: file.name,\n size: file.size,\n status: \"uploading\",\n };\n\n setAttachments((prev) => [...prev, placeholder]);\n\n try {\n let source: Attachment[\"source\"];\n let uploadMetadata: Record<string, unknown> | undefined;\n\n if (cfg?.onUpload) {\n const { metadata: meta, ...uploadSource } =\n await cfg.onUpload(file);\n source = uploadSource;\n uploadMetadata = meta;\n } else {\n // Default: read file as base64 via expo-file-system\n const base64 = await FileSystem.readAsStringAsync(file.uri, {\n encoding: FileSystem.EncodingType.Base64,\n });\n source = { type: \"data\", value: base64, mimeType: file.mimeType };\n }\n\n setAttachments((prev) =>\n prev.map((att) =>\n att.id === placeholderId\n ? {\n ...att,\n source,\n status: \"ready\" as const,\n metadata: uploadMetadata,\n }\n : att,\n ),\n );\n } catch (error) {\n // Remove placeholder on failure\n setAttachments((prev) =>\n prev.filter((att) => att.id !== placeholderId),\n );\n console.error(`[CopilotKit] Failed to upload \"${file.name}\":`, error);\n cfg?.onUploadFailed?.({\n reason: \"upload-failed\",\n file,\n message:\n error instanceof Error\n ? error.message\n : `Failed to upload \"${file.name}\"`,\n });\n }\n }\n },\n [matchesAccept],\n );\n\n const openPicker = useCallback(async () => {\n const cfg = configRef.current;\n const accept = cfg?.accept ?? \"*/*\";\n\n // Convert accept string to array for DocumentPicker\n const typeArray = accept\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean);\n\n try {\n const result = await DocumentPicker.getDocumentAsync({\n type: typeArray.length > 0 ? typeArray : [\"*/*\"],\n copyToCacheDirectory: true,\n multiple: true,\n });\n\n if (result.canceled || !result.assets?.length) return;\n\n const nativeFiles: NativeFileInput[] = result.assets.map((asset) => ({\n uri: asset.uri,\n name: asset.name ?? \"unknown\",\n size: asset.size ?? 0,\n mimeType: asset.mimeType ?? \"application/octet-stream\",\n }));\n\n await processFiles(nativeFiles);\n } catch (error) {\n console.error(\"[CopilotKit] Document picker error:\", error);\n }\n }, [processFiles]);\n\n const removeAttachment = useCallback((id: string) => {\n setAttachments((prev) => prev.filter((a) => a.id !== id));\n }, []);\n\n const consumeAttachments = useCallback(() => {\n const ready = attachmentsRef.current.filter((a) => a.status === \"ready\");\n if (ready.length === 0) return ready;\n setAttachments((prev) => prev.filter((a) => a.status !== \"ready\"));\n return ready;\n }, []);\n\n return {\n attachments,\n enabled,\n openPicker,\n processFiles,\n removeAttachment,\n consumeAttachments,\n };\n}\n","import React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useRef,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotChatConfigurationProvider,\n useAgent,\n useCopilotChatConfiguration,\n} from \"@copilotkit/react-core/headless\";\nimport { useCopilotKit } from \"@copilotkit/react-core/context\";\nimport { DEFAULT_AGENT_ID, randomUUID } from \"@copilotkit/shared\";\nimport type { InputContent } from \"@copilotkit/shared\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport { useAttachments } from \"./hooks/use-attachments\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { Attachment } from \"@copilotkit/shared\";\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatContextValue {\n /** The resolved agent instance. */\n agent: any;\n /** Whether the agent is currently running. */\n isRunning: boolean;\n /** Current messages in the conversation. */\n messages: any[];\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n attachmentsEnabled: boolean;\n /** Open the native document picker to add files. */\n openPicker: () => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /**\n * Submit a message with optional attachments.\n * Handles consuming ready attachments, building InputContent[],\n * calling agent.addMessage, and running the agent.\n */\n submitMessage: (text: string) => Promise<void>;\n}\n\nconst CopilotChatCtx = createContext<CopilotChatContextValue | null>(null);\n\n/**\n * Hook to access the CopilotChat context from child components.\n * Must be called inside a `<CopilotChat>` component tree.\n */\nexport function useCopilotChatContext(): CopilotChatContextValue {\n const ctx = useContext(CopilotChatCtx);\n if (!ctx) {\n throw new Error(\n \"useCopilotChatContext must be used within a <CopilotChat> component\",\n );\n }\n return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Props\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatBaseProps {\n /**\n * The agent ID to use for this chat session.\n * Matches the web SDK's CopilotChat `agentId` prop.\n *\n * Resolution order: `agentId` > `agentName` > the agent of the chat (or\n * `CopilotChatConfigurationProvider`) around this one > `\"default\"`\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead. `agentName` is kept for backwards\n * compatibility and will be removed in a future release.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session. When provided, the chat will resume\n * the specified thread. Matches the web SDK's CopilotChat `threadId` prop.\n */\n threadId?: string;\n\n /**\n * Error handler scoped to this chat's agent. Fires in addition to the\n * provider-level onError (does not suppress it). Receives errors whose\n * context.agentId matches this chat's agent, and errors with no agentId.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n\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 *\n * @default undefined -- inherits from provider `defaultThrottleMs`;\n * if that is also unset, re-renders are unthrottled.\n */\n throttleMs?: number;\n\n /**\n * Enable multimodal file attachments (images, audio, video, documents).\n * Pass a NativeAttachmentsConfig object to configure file picking behavior.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Optional children rendered inside the chat context.\n */\n children?: ReactNode;\n}\n\nexport interface CopilotChatProps extends CopilotChatBaseProps {\n /** Passthrough props are forwarded to consumers via the agent context. */\n [key: string]: unknown;\n}\n\n/**\n * Headless CopilotChat component for React Native.\n *\n * Wires up the `useAgent` hook with `agentId` resolution and renders children.\n * Unlike the web SDK's CopilotChat, this component does not render any UI\n * elements -- consumers provide their own React Native views.\n *\n * Children can access chat state via `useCopilotChatContext()`.\n *\n * Hooks inside the chat, such as `useAgent` and `useInterrupt`, use this\n * chat's agent when they do not pass an `agentId`. When the chat has a\n * `threadId`, `useAgent` inside the chat sets that thread on each agent it\n * returns, also on an agent that the hook names with its own `agentId`. Only\n * `useAgent({ agentId, runtimeAgentId, threadId })` keeps a different thread.\n *\n * A chat inside another chat uses the outer chat's agent when it has no\n * `agentId`. When the outer chat has a `threadId` and the inner chat does not,\n * the inner chat uses the outer thread. The web `CopilotChat` does the same.\n *\n * ```tsx\n * import { CopilotChat, useCopilotChatContext } from \"@copilotkit/react-native\";\n *\n * function MyChatUI() {\n * const { messages, submitMessage, attachments, openPicker } = useCopilotChatContext();\n * // ... render your UI\n * }\n *\n * <CopilotChat agentId=\"my-agent\" attachments={{ enabled: true }}>\n * <MyChatUI />\n * </CopilotChat>\n * ```\n */\nexport function CopilotChat({\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n attachments: attachmentsConfig,\n children,\n ..._rest\n}: CopilotChatProps) {\n // Same precedence as the web CopilotChat: a chat that names no agent takes\n // the agent of the chat configuration around it before \"default\".\n const chatConfig = useCopilotChatConfiguration();\n const resolvedAgentId =\n agentId ?? agentName ?? chatConfig?.agentId ?? DEFAULT_AGENT_ID;\n\n // Deprecation warning (dev only, fires once per mount)\n const warnedRef = useRef(false);\n useEffect(() => {\n if (\n agentName !== undefined &&\n agentId === undefined &&\n !warnedRef.current\n ) {\n warnedRef.current = true;\n if (typeof __DEV__ === \"undefined\" || __DEV__) {\n console.warn(\n \"[CopilotKit] agentName is deprecated, use agentId instead\",\n );\n }\n }\n }, [agentName, agentId]);\n\n const { agent } = useAgent({ agentId: resolvedAgentId, throttleMs });\n\n // Set threadId on the agent when provided\n useEffect(() => {\n if (threadId) {\n agent.threadId = threadId;\n }\n }, [agent, threadId]);\n\n // onError subscription -- forward core errors scoped to this chat's agent\n const { copilotkit } = useCopilotKit();\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n if (!onErrorRef.current) return;\n\n const subscription = copilotkit.subscribe({\n onError: (event) => {\n // Only forward errors that match this chat's agent\n if (\n event.context?.agentId === resolvedAgentId ||\n !event.context?.agentId\n ) {\n void onErrorRef.current?.({\n error: event.error,\n code: event.code,\n context: event.context,\n });\n }\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit, resolvedAgentId]);\n\n // Attachments\n const {\n attachments: selectedAttachments,\n enabled: attachmentsEnabled,\n openPicker,\n removeAttachment,\n consumeAttachments,\n } = useAttachments({ config: attachmentsConfig });\n\n // Submit handler -- mirrors web CopilotChat.tsx lines 234-288\n const submitMessage = useCallback(\n async (value: string) => {\n // Block if uploads in progress\n const hasUploading = selectedAttachments.some(\n (a) => a.status === \"uploading\",\n );\n if (hasUploading) {\n console.error(\n \"[CopilotKit] Cannot send while attachments are uploading\",\n );\n return;\n }\n\n const readyAttachments = consumeAttachments();\n\n if (readyAttachments.length > 0) {\n const contentParts: InputContent[] = [];\n if (value.trim()) {\n contentParts.push({ type: \"text\", text: value });\n }\n for (const att of readyAttachments) {\n contentParts.push({\n type: att.type,\n source: att.source,\n metadata: {\n ...(att.filename ? { filename: att.filename } : {}),\n ...att.metadata,\n },\n } as InputContent);\n }\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: contentParts,\n });\n } else {\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: value,\n });\n }\n\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed\", error);\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 [agent, selectedAttachments, consumeAttachments],\n );\n\n const contextValue: CopilotChatContextValue = {\n agent,\n isRunning: agent.isRunning,\n messages: agent.messages,\n attachments: selectedAttachments,\n attachmentsEnabled,\n openPicker,\n removeAttachment,\n submitMessage,\n };\n\n // Publish this chat's agent and thread to the subtree, as the web\n // CopilotChat does. Hooks inside it that name no agent use this chat's\n // agent, which is the outer chat's agent when this chat names none.\n return (\n <CopilotChatConfigurationProvider\n agentId={resolvedAgentId}\n threadId={threadId}\n >\n <CopilotChatCtx.Provider value={contextValue}>\n {children}\n </CopilotChatCtx.Provider>\n </CopilotChatConfigurationProvider>\n );\n}\n","import React, { type ReactNode } from \"react\";\nimport { CopilotChat, type CopilotChatProps } from \"./CopilotChat\";\n\nexport interface CopilotModalProps extends CopilotChatProps {\n /**\n * Optional children rendered inside the modal context.\n */\n children?: ReactNode;\n}\n\n/**\n * Headless CopilotModal component for React Native.\n *\n * A thin wrapper around CopilotChat that mirrors the web SDK's CopilotModal\n * API surface. On React Native, modal presentation is handled by the consumer\n * (e.g. React Native's `Modal` component) -- this component only provides\n * the agent wiring and prop resolution.\n *\n * ```tsx\n * import { CopilotModal } from \"@copilotkit/react-native\";\n * import { Modal } from \"react-native\";\n *\n * <Modal visible={isOpen}>\n * <CopilotModal agentId=\"my-agent\">\n * <MyChatUI />\n * </CopilotModal>\n * </Modal>\n * ```\n */\nexport function CopilotModal({ children, ...props }: CopilotModalProps) {\n return <CopilotChat {...props}>{children}</CopilotChat>;\n}\n","import React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Animated,\n Pressable,\n StyleSheet,\n Text,\n useWindowDimensions,\n View,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatBaseProps } from \"./CopilotChat\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CopilotSidebarHandle {\n /** Slide the drawer open. */\n open(): void;\n /** Slide the drawer closed. */\n close(): void;\n /** Toggle the drawer open/closed. */\n toggle(): void;\n}\n\nexport interface CopilotSidebarProps extends Omit<\n CopilotChatBaseProps,\n \"children\"\n> {\n /**\n * Start the drawer in the open position.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Width of the drawer panel. Accepts a number (points) or a percentage\n * string (e.g. `\"85%\"`). Defaults to 85% of the screen width.\n */\n width?: number | string;\n\n /**\n * Title displayed in the drawer header bar.\n * @default \"Copilot\"\n */\n headerTitle?: string;\n\n /**\n * Show a floating action button to toggle the drawer.\n * @default true\n */\n showToggleButton?: boolean;\n\n /** Called after the drawer finishes opening. */\n onOpen?: () => void;\n\n /** Called after the drawer finishes closing. */\n onClose?: () => void;\n\n /** Custom style applied to the drawer container. */\n style?: ViewStyle;\n\n /**\n * Your chat UI, rendered inside the drawer below the header. The inner\n * CopilotChat is headless and draws no messages or input of its own.\n */\n children?: ReactNode;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst ANIMATION_DURATION_MS = 300;\nconst DEFAULT_HEADER_TITLE = \"Copilot\";\nconst BACKDROP_OPACITY = 0.4;\nconst FAB_SIZE = 56;\n\n// ---------------------------------------------------------------------------\n// Component\n// ---------------------------------------------------------------------------\n\n/**\n * CopilotSidebar -- a slide-in drawer from the right edge of the screen\n * that wraps CopilotChat for React Native.\n *\n * ```tsx\n * import { CopilotSidebar } from \"@copilotkit/react-native\";\n *\n * const ref = useRef<CopilotSidebarHandle>(null);\n *\n * <CopilotSidebar\n * ref={ref}\n * agentId=\"my-agent\"\n * headerTitle=\"Assistant\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotSidebar = forwardRef<\n CopilotSidebarHandle,\n CopilotSidebarProps\n>(function CopilotSidebar(\n {\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n defaultOpen = false,\n width: widthProp,\n headerTitle = DEFAULT_HEADER_TITLE,\n showToggleButton = true,\n onOpen,\n onClose,\n style,\n children,\n ...rest\n },\n ref,\n) {\n const { width: screenWidth } = useWindowDimensions();\n\n // Resolve drawer width ---------------------------------------------------\n const drawerWidth = resolveWidth(widthProp, screenWidth);\n\n // Animation & open state -------------------------------------------------\n const [isOpen, setIsOpen] = useState(defaultOpen);\n const [slideAnim] = useState(\n () => new Animated.Value(defaultOpen ? 0 : drawerWidth),\n );\n\n // Keep the animated value in sync when drawerWidth changes while closed\n useEffect(() => {\n if (!isOpen) {\n slideAnim.setValue(drawerWidth);\n }\n }, [drawerWidth, isOpen, slideAnim]);\n\n const animateTo = useCallback(\n (toValue: number, cb?: () => void) => {\n Animated.timing(slideAnim, {\n toValue,\n duration: ANIMATION_DURATION_MS,\n useNativeDriver: true,\n }).start(({ finished }) => {\n if (finished) cb?.();\n });\n },\n [slideAnim],\n );\n\n const open = useCallback(() => {\n setIsOpen(true);\n animateTo(0, onOpen);\n }, [animateTo, onOpen]);\n\n const close = useCallback(() => {\n animateTo(drawerWidth, () => {\n setIsOpen(false);\n onClose?.();\n });\n }, [animateTo, drawerWidth, onClose]);\n\n const toggle = useCallback(() => {\n if (isOpen) {\n close();\n } else {\n open();\n }\n }, [isOpen, open, close]);\n\n useImperativeHandle(ref, () => ({ open, close, toggle }), [\n open,\n close,\n toggle,\n ]);\n\n // Callbacks stored in refs for stable animation closures -----------------\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n // -----------------------------------------------------------------------\n // Render\n // -----------------------------------------------------------------------\n return (\n <>\n {/* Backdrop */}\n {isOpen && (\n <Pressable\n style={styles.backdrop}\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close sidebar\"\n testID=\"copilot-sidebar-backdrop\"\n />\n )}\n\n {/* Drawer */}\n {isOpen && (\n <Animated.View\n style={[\n styles.drawer,\n { width: drawerWidth, transform: [{ translateX: slideAnim }] },\n style,\n ]}\n testID=\"copilot-sidebar-drawer\"\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <Pressable\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close\"\n hitSlop={8}\n testID=\"copilot-sidebar-close\"\n >\n <Text style={styles.closeButton}>{\"✕\"}</Text>\n </Pressable>\n </View>\n\n {/* Chat area */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n onError={onError}\n throttleMs={throttleMs}\n {...rest}\n >\n {children}\n </CopilotChat>\n </View>\n </Animated.View>\n )}\n\n {/* Floating action button */}\n {showToggleButton && !isOpen && (\n <Pressable\n style={styles.fab}\n onPress={open}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Open sidebar\"\n testID=\"copilot-sidebar-fab\"\n >\n <Text style={styles.fabIcon}>{\"💬\"}</Text>\n </Pressable>\n )}\n </>\n );\n});\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveWidth(\n widthProp: number | string | undefined,\n screenWidth: number,\n): number {\n if (widthProp === undefined) {\n return Math.round(screenWidth * 0.85);\n }\n if (typeof widthProp === \"number\") {\n return widthProp;\n }\n // Percentage string, e.g. \"85%\"\n const pctMatch = String(widthProp).match(/^(\\d+(?:\\.\\d+)?)%$/);\n if (pctMatch) {\n return Math.round(screenWidth * (parseFloat(pctMatch[1]) / 100));\n }\n // Fallback: try parsing as number\n const parsed = parseFloat(widthProp);\n return isNaN(parsed) ? Math.round(screenWidth * 0.85) : parsed;\n}\n\n// ---------------------------------------------------------------------------\n// Styles\n// ---------------------------------------------------------------------------\n\nconst styles = StyleSheet.create({\n backdrop: {\n ...StyleSheet.absoluteFill,\n backgroundColor: `rgba(0, 0, 0, ${BACKDROP_OPACITY})`,\n zIndex: 999,\n },\n drawer: {\n position: \"absolute\",\n top: 0,\n right: 0,\n bottom: 0,\n backgroundColor: \"#ffffff\",\n zIndex: 1000,\n shadowColor: \"#000\",\n shadowOffset: { width: -2, height: 0 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n elevation: 16,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e0e0e0\",\n },\n headerTitle: {\n fontSize: 18,\n fontWeight: \"600\",\n color: \"#1a1a1a\",\n },\n closeButton: {\n fontSize: 20,\n color: \"#666\",\n padding: 4,\n },\n chatContainer: {\n flex: 1,\n },\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: FAB_SIZE,\n height: FAB_SIZE,\n borderRadius: FAB_SIZE / 2,\n backgroundColor: \"#007AFF\",\n alignItems: \"center\",\n justifyContent: \"center\",\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 2 },\n shadowOpacity: 0.3,\n shadowRadius: 4,\n elevation: 8,\n zIndex: 998,\n },\n fabIcon: {\n fontSize: 24,\n },\n});\n","// NOTE: This component needs to be exported from index.ts\n// e.g. export { CopilotPopup } from \"./CopilotPopup\";\n// export type { CopilotPopupProps, CopilotPopupHandle } from \"./CopilotPopup\";\n\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Modal,\n Pressable,\n StyleSheet,\n Text,\n TouchableOpacity,\n View,\n useWindowDimensions,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\n\nexport interface CopilotPopupProps {\n /**\n * The agent ID to use for this chat session.\n * Passed through to CopilotChat.\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session.\n */\n threadId?: string;\n\n /**\n * Throttle interval (ms) for re-renders.\n */\n throttleMs?: number;\n\n /**\n * Whether the popup starts in the open state.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Height of the popup card. Accepts a number (points) or a percentage\n * string (e.g. \"60%\") relative to the screen height.\n * @default \"60%\"\n */\n height?: number | string;\n\n /**\n * Error handler scoped to this popup's chat agent.\n */\n onError?: (error: Error) => void;\n\n /**\n * Title displayed in the popup header bar.\n * @default \"CopilotKit\"\n */\n headerTitle?: string;\n\n /**\n * Enable multimodal file attachments. Forwarded to the internal CopilotChat.\n * Children access attachment state via `useCopilotChatContext()`.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Your chat UI, rendered inside the popup card below the header. The inner\n * CopilotChat is headless and draws no messages or input of its own.\n */\n children?: ReactNode;\n\n /**\n * Callback fired when the popup opens.\n */\n onOpen?: () => void;\n\n /**\n * Callback fired when the popup closes.\n */\n onClose?: () => void;\n\n /**\n * Whether tapping the semi-transparent backdrop dismisses the popup.\n * Equivalent to web SDK's `clickOutsideToClose`.\n * @default true\n */\n dismissOnBackdropPress?: boolean;\n\n /**\n * Whether to show the floating action button (FAB) that toggles the popup.\n * @default true\n */\n showToggleButton?: boolean;\n\n /**\n * Custom styles applied to the popup card container.\n */\n style?: ViewStyle;\n}\n\n/**\n * Imperative handle exposed via ref for controlling the popup programmatically.\n */\nexport interface CopilotPopupHandle {\n open: () => void;\n close: () => void;\n toggle: () => void;\n}\n\n/**\n * CopilotPopup for React Native.\n *\n * A floating action button (FAB) that opens a modal chat overlay.\n * The popup appears as a card floating above content with rounded corners,\n * a shadow, and a semi-transparent backdrop.\n *\n * ```tsx\n * import { CopilotPopup } from \"@copilotkit/react-native\";\n *\n * const popupRef = useRef<CopilotPopupHandle>(null);\n *\n * <CopilotPopup\n * ref={popupRef}\n * agentId=\"my-agent\"\n * headerTitle=\"Chat\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotPopup = forwardRef<CopilotPopupHandle, CopilotPopupProps>(\n function CopilotPopup(\n {\n agentId,\n agentName,\n threadId,\n throttleMs,\n defaultOpen = false,\n height = \"60%\",\n onError,\n headerTitle = \"CopilotKit\",\n attachments: attachmentsConfig,\n children,\n onOpen,\n onClose,\n dismissOnBackdropPress = true,\n showToggleButton = true,\n style,\n }: CopilotPopupProps,\n ref: React.Ref<CopilotPopupHandle>,\n ) {\n const [visible, setVisible] = useState(defaultOpen);\n const { height: screenHeight } = useWindowDimensions();\n\n // Stable refs for callbacks to avoid effect churn\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n const handleOpen = useCallback(() => {\n setVisible(true);\n onOpenRef.current?.();\n }, []);\n\n const handleClose = useCallback(() => {\n setVisible(false);\n onCloseRef.current?.();\n }, []);\n\n const handleToggle = useCallback(() => {\n setVisible((prev) => {\n const next = !prev;\n if (next) {\n onOpenRef.current?.();\n } else {\n onCloseRef.current?.();\n }\n return next;\n });\n }, []);\n\n // Expose imperative methods\n useImperativeHandle(\n ref,\n () => ({\n open: handleOpen,\n close: handleClose,\n toggle: handleToggle,\n }),\n [handleOpen, handleClose, handleToggle],\n );\n\n // Resolve popup height\n const resolvedHeight =\n typeof height === \"string\" && height.endsWith(\"%\")\n ? (parseFloat(height) / 100) * screenHeight\n : typeof height === \"number\"\n ? height\n : 0.6 * screenHeight;\n\n // Wrap onError to match CopilotChat's expected signature\n const chatOnError = onError\n ? (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => onError(event.error)\n : undefined;\n\n return (\n <>\n {/* Floating Action Button */}\n {showToggleButton && !visible && (\n <TouchableOpacity\n testID=\"copilot-popup-fab\"\n style={styles.fab}\n onPress={handleToggle}\n activeOpacity={0.8}\n accessibilityLabel=\"Open chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.fabIcon}>💬</Text>\n </TouchableOpacity>\n )}\n\n {/* Modal Overlay */}\n <Modal\n testID=\"copilot-popup-modal\"\n visible={visible}\n transparent\n animationType=\"slide\"\n onRequestClose={handleClose}\n >\n {/* Backdrop */}\n <Pressable\n testID=\"copilot-popup-backdrop\"\n style={styles.backdrop}\n onPress={dismissOnBackdropPress ? handleClose : undefined}\n >\n {/* Card — stop propagation so tapping the card doesn't dismiss */}\n <Pressable\n testID=\"copilot-popup-card\"\n style={[styles.card, { height: resolvedHeight }, style]}\n onPress={() => {\n // Prevent backdrop press from firing\n }}\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <TouchableOpacity\n testID=\"copilot-popup-close\"\n onPress={handleClose}\n hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}\n accessibilityLabel=\"Close chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.closeButton}>✕</Text>\n </TouchableOpacity>\n </View>\n\n {/* Chat Content */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n throttleMs={throttleMs}\n onError={chatOnError}\n attachments={attachmentsConfig}\n >\n {children}\n </CopilotChat>\n </View>\n </Pressable>\n </Pressable>\n </Modal>\n </>\n );\n },\n);\n\nconst styles = StyleSheet.create({\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: 56,\n height: 56,\n borderRadius: 28,\n backgroundColor: \"#6366f1\",\n alignItems: \"center\",\n justifyContent: \"center\",\n elevation: 6,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 3 },\n shadowOpacity: 0.27,\n shadowRadius: 4.65,\n },\n fabIcon: {\n fontSize: 24,\n },\n backdrop: {\n flex: 1,\n backgroundColor: \"rgba(0, 0, 0, 0.4)\",\n justifyContent: \"flex-end\",\n },\n card: {\n backgroundColor: \"#ffffff\",\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n overflow: \"hidden\",\n elevation: 10,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: -3 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e5e7eb\",\n },\n headerTitle: {\n fontSize: 17,\n fontWeight: \"600\",\n color: \"#111827\",\n },\n closeButton: {\n fontSize: 18,\n color: \"#6b7280\",\n fontWeight: \"500\",\n },\n chatContainer: {\n flex: 1,\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiFA,MAAM,mBAAmB,KAAK,OAAO;;;;;;;;;AAcrC,SAAgB,eAAe,EAC7B,UACwD;CACxD,MAAM,UAAU,QAAQ,WAAW;CAEnC,MAAM,CAAC,aAAa,sCAAyC,EAAE,CAAC;CAGhE,MAAM,8BAAmB,OAAO;AAChC,WAAU,UAAU;CACpB,MAAM,mCAAsC,EAAE,CAAC;AAC/C,gBAAe,UAAU;;;;;;CAOzB,MAAM,wCACH,MAAuB,WAA4B;AAClD,MAAI,CAA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AO;CAC/B,KAAK;EACH,UAAU;EACV,QAAQ;EACR,OAAO;EACP,OAAO;EACP,QAAQ;EACR,cAAc;EACd,iBAAiB;EACjB,YAAY;EACZ,gBAAgB;EAChB,WAAW;EACX,aAAa;EACb,cAAc;GAAE,OAAO;GAAG,QAAQ;GAAG;EACrC,eAAe;EACf,cAAc;EACf;CACD,SAAS,EACP,UAAU,IACX;CACD,UAAU;EACR,MAAM;EACN,iBAAiB;EACjB,gBAAgB;EACjB;CACD,MAAM;EACJ,iBAAiB;EACjB,qBAAqB;EACrB,sBAAsB;EACtB,UAAU;EACV,WAAW;EACX,aAAa;EACb,cAAc;GAAE,OAAO;GAAG,QAAQ;GAAI;EACtC,eAAe;EACf,cAAc;EACf;CACD,QAAQ;EACN,eAAe;EACf,YAAY;EACZ,gBAAgB;EAChB,mBAAmB;EACnB,iBAAiB;EACjB,mBAAmBA,wBAAW;EAC9B,mBAAmB;EACpB;CACD,aAAa;EACX,UAAU;EACV,YAAY;EACZ,OAAO;EACR;CACD,aAAa;EACX,UAAU;EACV,OAAO;EACP,YAAY;EACb;CACD,eAAe,EACb,MAAM,GACP;CACF,CAAC"}
|
package/dist/index.mjs
CHANGED
|
@@ -339,7 +339,7 @@ const CopilotSidebar = forwardRef(function CopilotSidebar({ agentId, agentName,
|
|
|
339
339
|
const { width: screenWidth } = useWindowDimensions();
|
|
340
340
|
const drawerWidth = resolveWidth(widthProp, screenWidth);
|
|
341
341
|
const [isOpen, setIsOpen] = useState(defaultOpen);
|
|
342
|
-
const slideAnim =
|
|
342
|
+
const [slideAnim] = useState(() => new Animated.Value(defaultOpen ? 0 : drawerWidth));
|
|
343
343
|
useEffect(() => {
|
|
344
344
|
if (!isOpen) slideAnim.setValue(drawerWidth);
|
|
345
345
|
}, [
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["useAgent","useCopilotKit","styles"],"sources":["../src/hooks/use-attachments.ts","../src/CopilotChat.tsx","../src/CopilotModal.tsx","../src/CopilotSidebar.tsx","../src/CopilotPopup.tsx"],"sourcesContent":["// packages/react-native/src/hooks/use-attachments.ts\nimport { useCallback, useRef, useState } from \"react\";\nimport {\n randomUUID,\n getModalityFromMimeType,\n formatFileSize,\n} from \"@copilotkit/shared\";\nimport type {\n Attachment,\n AttachmentUploadResult,\n AttachmentUploadErrorReason,\n} from \"@copilotkit/shared\";\nimport * as DocumentPicker from \"expo-document-picker\";\nimport * as FileSystem from \"expo-file-system\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Platform-neutral file descriptor for React Native.\n * Replaces the web `File` object in all attachment APIs.\n */\nexport interface NativeFileInput {\n /** Local file URI (e.g. `file:///path/to/file`). */\n uri: string;\n /** Filename with extension. */\n name: string;\n /** File size in bytes. */\n size: number;\n /** MIME type (e.g. `\"image/jpeg\"`). */\n mimeType: string;\n}\n\n/**\n * React Native variant of AttachmentsConfig.\n * Identical to the shared AttachmentsConfig except `onUpload` receives\n * a `NativeFileInput` instead of a web `File`.\n */\nexport interface NativeAttachmentsConfig {\n /** Enable file attachments in the chat input. */\n enabled: boolean;\n /** MIME type filter for the file picker, default all files. */\n accept?: string;\n /** Maximum file size in bytes, default 20MB (20 * 1024 * 1024). */\n maxSize?: number;\n /** Custom upload handler. Receives the native file descriptor. */\n onUpload?: (\n file: NativeFileInput,\n ) => AttachmentUploadResult | Promise<AttachmentUploadResult>;\n /** Called when an attachment fails validation or upload. */\n onUploadFailed?: (error: {\n reason: AttachmentUploadErrorReason;\n file: NativeFileInput;\n message: string;\n }) => void;\n}\n\nexport interface UseNativeAttachmentsProps {\n config?: NativeAttachmentsConfig;\n}\n\nexport interface UseNativeAttachmentsReturn {\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n enabled: boolean;\n /** Open the native document picker. */\n openPicker: () => Promise<void>;\n /** Process an array of NativeFileInput objects (validate, read, add to state). */\n processFiles: (files: NativeFileInput[]) => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /** Consume ready attachments and clear the queue. Returns the consumed attachments. */\n consumeAttachments: () => Attachment[];\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20 MB\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * React Native hook that manages file attachment state -- picking, uploading,\n * and lifecycle. All returned callbacks are referentially stable via useCallback.\n *\n * This is the RN counterpart of the web `useAttachments` hook from\n * `@copilotkit/react-core`. It replaces web APIs (FileReader, DragEvent,\n * HTMLInputElement) with Expo modules (expo-document-picker, expo-file-system).\n */\nexport function useAttachments({\n config,\n}: UseNativeAttachmentsProps): UseNativeAttachmentsReturn {\n const enabled = config?.enabled ?? false;\n\n const [attachments, setAttachments] = useState<Attachment[]>([]);\n\n // Refs for stable callbacks to read latest values\n const configRef = useRef(config);\n configRef.current = config;\n const attachmentsRef = useRef<Attachment[]>([]);\n attachmentsRef.current = attachments;\n\n /**\n * Simple MIME accept filter for NativeFileInput.\n * Handles wildcards like \"image/*\" and exact types like \"application/pdf\".\n * Comma-separated lists are supported.\n */\n const matchesAccept = useCallback(\n (file: NativeFileInput, accept: string): boolean => {\n if (!accept || accept === \"*/*\") return true;\n const filters = accept.split(\",\").map((f) => f.trim());\n return filters.some((filter) => {\n if (filter.startsWith(\".\")) {\n return file.name.toLowerCase().endsWith(filter.toLowerCase());\n }\n if (filter.endsWith(\"/*\")) {\n const prefix = filter.slice(0, -2);\n return file.mimeType.startsWith(prefix + \"/\");\n }\n return file.mimeType === filter;\n });\n },\n [],\n );\n\n const processFiles = useCallback(\n async (files: NativeFileInput[]) => {\n const cfg = configRef.current;\n const accept = cfg?.accept ?? \"*/*\";\n const maxSize = cfg?.maxSize ?? DEFAULT_MAX_SIZE;\n\n // Filter by accept type\n const rejectedFiles = files.filter((f) => !matchesAccept(f, accept));\n for (const file of rejectedFiles) {\n cfg?.onUploadFailed?.({\n reason: \"invalid-type\",\n file,\n message: `File \"${file.name}\" is not accepted. Supported types: ${accept}`,\n });\n }\n\n const validFiles = files.filter((f) => matchesAccept(f, accept));\n\n for (const file of validFiles) {\n // Size check\n if (file.size > maxSize) {\n cfg?.onUploadFailed?.({\n reason: \"file-too-large\",\n file,\n message: `File \"${file.name}\" exceeds the maximum size of ${formatFileSize(maxSize)}`,\n });\n continue;\n }\n\n const modality = getModalityFromMimeType(file.mimeType);\n const placeholderId = randomUUID();\n const placeholder: Attachment = {\n id: placeholderId,\n type: modality,\n source: { type: \"data\", value: \"\", mimeType: file.mimeType },\n filename: file.name,\n size: file.size,\n status: \"uploading\",\n };\n\n setAttachments((prev) => [...prev, placeholder]);\n\n try {\n let source: Attachment[\"source\"];\n let uploadMetadata: Record<string, unknown> | undefined;\n\n if (cfg?.onUpload) {\n const { metadata: meta, ...uploadSource } =\n await cfg.onUpload(file);\n source = uploadSource;\n uploadMetadata = meta;\n } else {\n // Default: read file as base64 via expo-file-system\n const base64 = await FileSystem.readAsStringAsync(file.uri, {\n encoding: FileSystem.EncodingType.Base64,\n });\n source = { type: \"data\", value: base64, mimeType: file.mimeType };\n }\n\n setAttachments((prev) =>\n prev.map((att) =>\n att.id === placeholderId\n ? {\n ...att,\n source,\n status: \"ready\" as const,\n metadata: uploadMetadata,\n }\n : att,\n ),\n );\n } catch (error) {\n // Remove placeholder on failure\n setAttachments((prev) =>\n prev.filter((att) => att.id !== placeholderId),\n );\n console.error(`[CopilotKit] Failed to upload \"${file.name}\":`, error);\n cfg?.onUploadFailed?.({\n reason: \"upload-failed\",\n file,\n message:\n error instanceof Error\n ? error.message\n : `Failed to upload \"${file.name}\"`,\n });\n }\n }\n },\n [matchesAccept],\n );\n\n const openPicker = useCallback(async () => {\n const cfg = configRef.current;\n const accept = cfg?.accept ?? \"*/*\";\n\n // Convert accept string to array for DocumentPicker\n const typeArray = accept\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean);\n\n try {\n const result = await DocumentPicker.getDocumentAsync({\n type: typeArray.length > 0 ? typeArray : [\"*/*\"],\n copyToCacheDirectory: true,\n multiple: true,\n });\n\n if (result.canceled || !result.assets?.length) return;\n\n const nativeFiles: NativeFileInput[] = result.assets.map((asset) => ({\n uri: asset.uri,\n name: asset.name ?? \"unknown\",\n size: asset.size ?? 0,\n mimeType: asset.mimeType ?? \"application/octet-stream\",\n }));\n\n await processFiles(nativeFiles);\n } catch (error) {\n console.error(\"[CopilotKit] Document picker error:\", error);\n }\n }, [processFiles]);\n\n const removeAttachment = useCallback((id: string) => {\n setAttachments((prev) => prev.filter((a) => a.id !== id));\n }, []);\n\n const consumeAttachments = useCallback(() => {\n const ready = attachmentsRef.current.filter((a) => a.status === \"ready\");\n if (ready.length === 0) return ready;\n setAttachments((prev) => prev.filter((a) => a.status !== \"ready\"));\n return ready;\n }, []);\n\n return {\n attachments,\n enabled,\n openPicker,\n processFiles,\n removeAttachment,\n consumeAttachments,\n };\n}\n","import React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useRef,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotChatConfigurationProvider,\n useAgent,\n useCopilotChatConfiguration,\n} from \"@copilotkit/react-core/headless\";\nimport { useCopilotKit } from \"@copilotkit/react-core/context\";\nimport { DEFAULT_AGENT_ID, randomUUID } from \"@copilotkit/shared\";\nimport type { InputContent } from \"@copilotkit/shared\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport { useAttachments } from \"./hooks/use-attachments\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { Attachment } from \"@copilotkit/shared\";\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatContextValue {\n /** The resolved agent instance. */\n agent: any;\n /** Whether the agent is currently running. */\n isRunning: boolean;\n /** Current messages in the conversation. */\n messages: any[];\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n attachmentsEnabled: boolean;\n /** Open the native document picker to add files. */\n openPicker: () => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /**\n * Submit a message with optional attachments.\n * Handles consuming ready attachments, building InputContent[],\n * calling agent.addMessage, and running the agent.\n */\n submitMessage: (text: string) => Promise<void>;\n}\n\nconst CopilotChatCtx = createContext<CopilotChatContextValue | null>(null);\n\n/**\n * Hook to access the CopilotChat context from child components.\n * Must be called inside a `<CopilotChat>` component tree.\n */\nexport function useCopilotChatContext(): CopilotChatContextValue {\n const ctx = useContext(CopilotChatCtx);\n if (!ctx) {\n throw new Error(\n \"useCopilotChatContext must be used within a <CopilotChat> component\",\n );\n }\n return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Props\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatBaseProps {\n /**\n * The agent ID to use for this chat session.\n * Matches the web SDK's CopilotChat `agentId` prop.\n *\n * Resolution order: `agentId` > `agentName` > the agent of the chat (or\n * `CopilotChatConfigurationProvider`) around this one > `\"default\"`\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead. `agentName` is kept for backwards\n * compatibility and will be removed in a future release.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session. When provided, the chat will resume\n * the specified thread. Matches the web SDK's CopilotChat `threadId` prop.\n */\n threadId?: string;\n\n /**\n * Error handler scoped to this chat's agent. Fires in addition to the\n * provider-level onError (does not suppress it). Receives errors whose\n * context.agentId matches this chat's agent, and errors with no agentId.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n\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 *\n * @default undefined -- inherits from provider `defaultThrottleMs`;\n * if that is also unset, re-renders are unthrottled.\n */\n throttleMs?: number;\n\n /**\n * Enable multimodal file attachments (images, audio, video, documents).\n * Pass a NativeAttachmentsConfig object to configure file picking behavior.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Optional children rendered inside the chat context.\n */\n children?: ReactNode;\n}\n\nexport interface CopilotChatProps extends CopilotChatBaseProps {\n /** Passthrough props are forwarded to consumers via the agent context. */\n [key: string]: unknown;\n}\n\n/**\n * Headless CopilotChat component for React Native.\n *\n * Wires up the `useAgent` hook with `agentId` resolution and renders children.\n * Unlike the web SDK's CopilotChat, this component does not render any UI\n * elements -- consumers provide their own React Native views.\n *\n * Children can access chat state via `useCopilotChatContext()`.\n *\n * Hooks inside the chat, such as `useAgent` and `useInterrupt`, use this\n * chat's agent when they do not pass an `agentId`. When the chat has a\n * `threadId`, `useAgent` inside the chat sets that thread on each agent it\n * returns, also on an agent that the hook names with its own `agentId`. Only\n * `useAgent({ agentId, runtimeAgentId, threadId })` keeps a different thread.\n *\n * A chat inside another chat uses the outer chat's agent when it has no\n * `agentId`. When the outer chat has a `threadId` and the inner chat does not,\n * the inner chat uses the outer thread. The web `CopilotChat` does the same.\n *\n * ```tsx\n * import { CopilotChat, useCopilotChatContext } from \"@copilotkit/react-native\";\n *\n * function MyChatUI() {\n * const { messages, submitMessage, attachments, openPicker } = useCopilotChatContext();\n * // ... render your UI\n * }\n *\n * <CopilotChat agentId=\"my-agent\" attachments={{ enabled: true }}>\n * <MyChatUI />\n * </CopilotChat>\n * ```\n */\nexport function CopilotChat({\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n attachments: attachmentsConfig,\n children,\n ..._rest\n}: CopilotChatProps) {\n // Same precedence as the web CopilotChat: a chat that names no agent takes\n // the agent of the chat configuration around it before \"default\".\n const chatConfig = useCopilotChatConfiguration();\n const resolvedAgentId =\n agentId ?? agentName ?? chatConfig?.agentId ?? DEFAULT_AGENT_ID;\n\n // Deprecation warning (dev only, fires once per mount)\n const warnedRef = useRef(false);\n useEffect(() => {\n if (\n agentName !== undefined &&\n agentId === undefined &&\n !warnedRef.current\n ) {\n warnedRef.current = true;\n if (typeof __DEV__ === \"undefined\" || __DEV__) {\n console.warn(\n \"[CopilotKit] agentName is deprecated, use agentId instead\",\n );\n }\n }\n }, [agentName, agentId]);\n\n const { agent } = useAgent({ agentId: resolvedAgentId, throttleMs });\n\n // Set threadId on the agent when provided\n useEffect(() => {\n if (threadId) {\n agent.threadId = threadId;\n }\n }, [agent, threadId]);\n\n // onError subscription -- forward core errors scoped to this chat's agent\n const { copilotkit } = useCopilotKit();\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n if (!onErrorRef.current) return;\n\n const subscription = copilotkit.subscribe({\n onError: (event) => {\n // Only forward errors that match this chat's agent\n if (\n event.context?.agentId === resolvedAgentId ||\n !event.context?.agentId\n ) {\n void onErrorRef.current?.({\n error: event.error,\n code: event.code,\n context: event.context,\n });\n }\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit, resolvedAgentId]);\n\n // Attachments\n const {\n attachments: selectedAttachments,\n enabled: attachmentsEnabled,\n openPicker,\n removeAttachment,\n consumeAttachments,\n } = useAttachments({ config: attachmentsConfig });\n\n // Submit handler -- mirrors web CopilotChat.tsx lines 234-288\n const submitMessage = useCallback(\n async (value: string) => {\n // Block if uploads in progress\n const hasUploading = selectedAttachments.some(\n (a) => a.status === \"uploading\",\n );\n if (hasUploading) {\n console.error(\n \"[CopilotKit] Cannot send while attachments are uploading\",\n );\n return;\n }\n\n const readyAttachments = consumeAttachments();\n\n if (readyAttachments.length > 0) {\n const contentParts: InputContent[] = [];\n if (value.trim()) {\n contentParts.push({ type: \"text\", text: value });\n }\n for (const att of readyAttachments) {\n contentParts.push({\n type: att.type,\n source: att.source,\n metadata: {\n ...(att.filename ? { filename: att.filename } : {}),\n ...att.metadata,\n },\n } as InputContent);\n }\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: contentParts,\n });\n } else {\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: value,\n });\n }\n\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed\", error);\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 [agent, selectedAttachments, consumeAttachments],\n );\n\n const contextValue: CopilotChatContextValue = {\n agent,\n isRunning: agent.isRunning,\n messages: agent.messages,\n attachments: selectedAttachments,\n attachmentsEnabled,\n openPicker,\n removeAttachment,\n submitMessage,\n };\n\n // Publish this chat's agent and thread to the subtree, as the web\n // CopilotChat does. Hooks inside it that name no agent use this chat's\n // agent, which is the outer chat's agent when this chat names none.\n return (\n <CopilotChatConfigurationProvider\n agentId={resolvedAgentId}\n threadId={threadId}\n >\n <CopilotChatCtx.Provider value={contextValue}>\n {children}\n </CopilotChatCtx.Provider>\n </CopilotChatConfigurationProvider>\n );\n}\n","import React, { type ReactNode } from \"react\";\nimport { CopilotChat, type CopilotChatProps } from \"./CopilotChat\";\n\nexport interface CopilotModalProps extends CopilotChatProps {\n /**\n * Optional children rendered inside the modal context.\n */\n children?: ReactNode;\n}\n\n/**\n * Headless CopilotModal component for React Native.\n *\n * A thin wrapper around CopilotChat that mirrors the web SDK's CopilotModal\n * API surface. On React Native, modal presentation is handled by the consumer\n * (e.g. React Native's `Modal` component) -- this component only provides\n * the agent wiring and prop resolution.\n *\n * ```tsx\n * import { CopilotModal } from \"@copilotkit/react-native\";\n * import { Modal } from \"react-native\";\n *\n * <Modal visible={isOpen}>\n * <CopilotModal agentId=\"my-agent\">\n * <MyChatUI />\n * </CopilotModal>\n * </Modal>\n * ```\n */\nexport function CopilotModal({ children, ...props }: CopilotModalProps) {\n return <CopilotChat {...props}>{children}</CopilotChat>;\n}\n","import React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Animated,\n Dimensions,\n Pressable,\n StyleSheet,\n Text,\n useWindowDimensions,\n View,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatBaseProps } from \"./CopilotChat\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CopilotSidebarHandle {\n /** Slide the drawer open. */\n open(): void;\n /** Slide the drawer closed. */\n close(): void;\n /** Toggle the drawer open/closed. */\n toggle(): void;\n}\n\nexport interface CopilotSidebarProps extends Omit<\n CopilotChatBaseProps,\n \"children\"\n> {\n /**\n * Start the drawer in the open position.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Width of the drawer panel. Accepts a number (points) or a percentage\n * string (e.g. `\"85%\"`). Defaults to 85% of the screen width.\n */\n width?: number | string;\n\n /**\n * Title displayed in the drawer header bar.\n * @default \"Copilot\"\n */\n headerTitle?: string;\n\n /**\n * Show a floating action button to toggle the drawer.\n * @default true\n */\n showToggleButton?: boolean;\n\n /** Called after the drawer finishes opening. */\n onOpen?: () => void;\n\n /** Called after the drawer finishes closing. */\n onClose?: () => void;\n\n /** Custom style applied to the drawer container. */\n style?: ViewStyle;\n\n /**\n * Your chat UI, rendered inside the drawer below the header. The inner\n * CopilotChat is headless and draws no messages or input of its own.\n */\n children?: ReactNode;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst ANIMATION_DURATION_MS = 300;\nconst DEFAULT_HEADER_TITLE = \"Copilot\";\nconst BACKDROP_OPACITY = 0.4;\nconst FAB_SIZE = 56;\n\n// ---------------------------------------------------------------------------\n// Component\n// ---------------------------------------------------------------------------\n\n/**\n * CopilotSidebar -- a slide-in drawer from the right edge of the screen\n * that wraps CopilotChat for React Native.\n *\n * ```tsx\n * import { CopilotSidebar } from \"@copilotkit/react-native\";\n *\n * const ref = useRef<CopilotSidebarHandle>(null);\n *\n * <CopilotSidebar\n * ref={ref}\n * agentId=\"my-agent\"\n * headerTitle=\"Assistant\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotSidebar = forwardRef<\n CopilotSidebarHandle,\n CopilotSidebarProps\n>(function CopilotSidebar(\n {\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n defaultOpen = false,\n width: widthProp,\n headerTitle = DEFAULT_HEADER_TITLE,\n showToggleButton = true,\n onOpen,\n onClose,\n style,\n children,\n ...rest\n },\n ref,\n) {\n const { width: screenWidth } = useWindowDimensions();\n\n // Resolve drawer width ---------------------------------------------------\n const drawerWidth = resolveWidth(widthProp, screenWidth);\n\n // Animation & open state -------------------------------------------------\n const [isOpen, setIsOpen] = useState(defaultOpen);\n const slideAnim = useRef(\n new Animated.Value(defaultOpen ? 0 : drawerWidth),\n ).current;\n\n // Keep the animated value in sync when drawerWidth changes while closed\n useEffect(() => {\n if (!isOpen) {\n slideAnim.setValue(drawerWidth);\n }\n }, [drawerWidth, isOpen, slideAnim]);\n\n const animateTo = useCallback(\n (toValue: number, cb?: () => void) => {\n Animated.timing(slideAnim, {\n toValue,\n duration: ANIMATION_DURATION_MS,\n useNativeDriver: true,\n }).start(({ finished }) => {\n if (finished) cb?.();\n });\n },\n [slideAnim],\n );\n\n const open = useCallback(() => {\n setIsOpen(true);\n animateTo(0, onOpen);\n }, [animateTo, onOpen]);\n\n const close = useCallback(() => {\n animateTo(drawerWidth, () => {\n setIsOpen(false);\n onClose?.();\n });\n }, [animateTo, drawerWidth, onClose]);\n\n const toggle = useCallback(() => {\n if (isOpen) {\n close();\n } else {\n open();\n }\n }, [isOpen, open, close]);\n\n useImperativeHandle(ref, () => ({ open, close, toggle }), [\n open,\n close,\n toggle,\n ]);\n\n // Callbacks stored in refs for stable animation closures -----------------\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n // -----------------------------------------------------------------------\n // Render\n // -----------------------------------------------------------------------\n return (\n <>\n {/* Backdrop */}\n {isOpen && (\n <Pressable\n style={styles.backdrop}\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close sidebar\"\n testID=\"copilot-sidebar-backdrop\"\n />\n )}\n\n {/* Drawer */}\n {isOpen && (\n <Animated.View\n style={[\n styles.drawer,\n { width: drawerWidth, transform: [{ translateX: slideAnim }] },\n style,\n ]}\n testID=\"copilot-sidebar-drawer\"\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <Pressable\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close\"\n hitSlop={8}\n testID=\"copilot-sidebar-close\"\n >\n <Text style={styles.closeButton}>{\"✕\"}</Text>\n </Pressable>\n </View>\n\n {/* Chat area */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n onError={onError}\n throttleMs={throttleMs}\n {...rest}\n >\n {children}\n </CopilotChat>\n </View>\n </Animated.View>\n )}\n\n {/* Floating action button */}\n {showToggleButton && !isOpen && (\n <Pressable\n style={styles.fab}\n onPress={open}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Open sidebar\"\n testID=\"copilot-sidebar-fab\"\n >\n <Text style={styles.fabIcon}>{\"💬\"}</Text>\n </Pressable>\n )}\n </>\n );\n});\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveWidth(\n widthProp: number | string | undefined,\n screenWidth: number,\n): number {\n if (widthProp === undefined) {\n return Math.round(screenWidth * 0.85);\n }\n if (typeof widthProp === \"number\") {\n return widthProp;\n }\n // Percentage string, e.g. \"85%\"\n const pctMatch = String(widthProp).match(/^(\\d+(?:\\.\\d+)?)%$/);\n if (pctMatch) {\n return Math.round(screenWidth * (parseFloat(pctMatch[1]) / 100));\n }\n // Fallback: try parsing as number\n const parsed = parseFloat(widthProp);\n return isNaN(parsed) ? Math.round(screenWidth * 0.85) : parsed;\n}\n\n// ---------------------------------------------------------------------------\n// Styles\n// ---------------------------------------------------------------------------\n\nconst styles = StyleSheet.create({\n backdrop: {\n ...StyleSheet.absoluteFill,\n backgroundColor: `rgba(0, 0, 0, ${BACKDROP_OPACITY})`,\n zIndex: 999,\n },\n drawer: {\n position: \"absolute\",\n top: 0,\n right: 0,\n bottom: 0,\n backgroundColor: \"#ffffff\",\n zIndex: 1000,\n shadowColor: \"#000\",\n shadowOffset: { width: -2, height: 0 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n elevation: 16,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e0e0e0\",\n },\n headerTitle: {\n fontSize: 18,\n fontWeight: \"600\",\n color: \"#1a1a1a\",\n },\n closeButton: {\n fontSize: 20,\n color: \"#666\",\n padding: 4,\n },\n chatContainer: {\n flex: 1,\n },\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: FAB_SIZE,\n height: FAB_SIZE,\n borderRadius: FAB_SIZE / 2,\n backgroundColor: \"#007AFF\",\n alignItems: \"center\",\n justifyContent: \"center\",\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 2 },\n shadowOpacity: 0.3,\n shadowRadius: 4,\n elevation: 8,\n zIndex: 998,\n },\n fabIcon: {\n fontSize: 24,\n },\n});\n","// NOTE: This component needs to be exported from index.ts\n// e.g. export { CopilotPopup } from \"./CopilotPopup\";\n// export type { CopilotPopupProps, CopilotPopupHandle } from \"./CopilotPopup\";\n\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Modal,\n Pressable,\n StyleSheet,\n Text,\n TouchableOpacity,\n View,\n useWindowDimensions,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\n\nexport interface CopilotPopupProps {\n /**\n * The agent ID to use for this chat session.\n * Passed through to CopilotChat.\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session.\n */\n threadId?: string;\n\n /**\n * Throttle interval (ms) for re-renders.\n */\n throttleMs?: number;\n\n /**\n * Whether the popup starts in the open state.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Height of the popup card. Accepts a number (points) or a percentage\n * string (e.g. \"60%\") relative to the screen height.\n * @default \"60%\"\n */\n height?: number | string;\n\n /**\n * Error handler scoped to this popup's chat agent.\n */\n onError?: (error: Error) => void;\n\n /**\n * Title displayed in the popup header bar.\n * @default \"CopilotKit\"\n */\n headerTitle?: string;\n\n /**\n * Enable multimodal file attachments. Forwarded to the internal CopilotChat.\n * Children access attachment state via `useCopilotChatContext()`.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Your chat UI, rendered inside the popup card below the header. The inner\n * CopilotChat is headless and draws no messages or input of its own.\n */\n children?: ReactNode;\n\n /**\n * Callback fired when the popup opens.\n */\n onOpen?: () => void;\n\n /**\n * Callback fired when the popup closes.\n */\n onClose?: () => void;\n\n /**\n * Whether tapping the semi-transparent backdrop dismisses the popup.\n * Equivalent to web SDK's `clickOutsideToClose`.\n * @default true\n */\n dismissOnBackdropPress?: boolean;\n\n /**\n * Whether to show the floating action button (FAB) that toggles the popup.\n * @default true\n */\n showToggleButton?: boolean;\n\n /**\n * Custom styles applied to the popup card container.\n */\n style?: ViewStyle;\n}\n\n/**\n * Imperative handle exposed via ref for controlling the popup programmatically.\n */\nexport interface CopilotPopupHandle {\n open: () => void;\n close: () => void;\n toggle: () => void;\n}\n\n/**\n * CopilotPopup for React Native.\n *\n * A floating action button (FAB) that opens a modal chat overlay.\n * The popup appears as a card floating above content with rounded corners,\n * a shadow, and a semi-transparent backdrop.\n *\n * ```tsx\n * import { CopilotPopup } from \"@copilotkit/react-native\";\n *\n * const popupRef = useRef<CopilotPopupHandle>(null);\n *\n * <CopilotPopup\n * ref={popupRef}\n * agentId=\"my-agent\"\n * headerTitle=\"Chat\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotPopup = forwardRef<CopilotPopupHandle, CopilotPopupProps>(\n function CopilotPopup(\n {\n agentId,\n agentName,\n threadId,\n throttleMs,\n defaultOpen = false,\n height = \"60%\",\n onError,\n headerTitle = \"CopilotKit\",\n attachments: attachmentsConfig,\n children,\n onOpen,\n onClose,\n dismissOnBackdropPress = true,\n showToggleButton = true,\n style,\n }: CopilotPopupProps,\n ref: React.Ref<CopilotPopupHandle>,\n ) {\n const [visible, setVisible] = useState(defaultOpen);\n const { height: screenHeight } = useWindowDimensions();\n\n // Stable refs for callbacks to avoid effect churn\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n const handleOpen = useCallback(() => {\n setVisible(true);\n onOpenRef.current?.();\n }, []);\n\n const handleClose = useCallback(() => {\n setVisible(false);\n onCloseRef.current?.();\n }, []);\n\n const handleToggle = useCallback(() => {\n setVisible((prev) => {\n const next = !prev;\n if (next) {\n onOpenRef.current?.();\n } else {\n onCloseRef.current?.();\n }\n return next;\n });\n }, []);\n\n // Expose imperative methods\n useImperativeHandle(\n ref,\n () => ({\n open: handleOpen,\n close: handleClose,\n toggle: handleToggle,\n }),\n [handleOpen, handleClose, handleToggle],\n );\n\n // Resolve popup height\n const resolvedHeight =\n typeof height === \"string\" && height.endsWith(\"%\")\n ? (parseFloat(height) / 100) * screenHeight\n : typeof height === \"number\"\n ? height\n : 0.6 * screenHeight;\n\n // Wrap onError to match CopilotChat's expected signature\n const chatOnError = onError\n ? (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => onError(event.error)\n : undefined;\n\n return (\n <>\n {/* Floating Action Button */}\n {showToggleButton && !visible && (\n <TouchableOpacity\n testID=\"copilot-popup-fab\"\n style={styles.fab}\n onPress={handleToggle}\n activeOpacity={0.8}\n accessibilityLabel=\"Open chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.fabIcon}>💬</Text>\n </TouchableOpacity>\n )}\n\n {/* Modal Overlay */}\n <Modal\n testID=\"copilot-popup-modal\"\n visible={visible}\n transparent\n animationType=\"slide\"\n onRequestClose={handleClose}\n >\n {/* Backdrop */}\n <Pressable\n testID=\"copilot-popup-backdrop\"\n style={styles.backdrop}\n onPress={dismissOnBackdropPress ? handleClose : undefined}\n >\n {/* Card — stop propagation so tapping the card doesn't dismiss */}\n <Pressable\n testID=\"copilot-popup-card\"\n style={[styles.card, { height: resolvedHeight }, style]}\n onPress={() => {\n // Prevent backdrop press from firing\n }}\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <TouchableOpacity\n testID=\"copilot-popup-close\"\n onPress={handleClose}\n hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}\n accessibilityLabel=\"Close chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.closeButton}>✕</Text>\n </TouchableOpacity>\n </View>\n\n {/* Chat Content */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n throttleMs={throttleMs}\n onError={chatOnError}\n attachments={attachmentsConfig}\n >\n {children}\n </CopilotChat>\n </View>\n </Pressable>\n </Pressable>\n </Modal>\n </>\n );\n },\n);\n\nconst styles = StyleSheet.create({\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: 56,\n height: 56,\n borderRadius: 28,\n backgroundColor: \"#6366f1\",\n alignItems: \"center\",\n justifyContent: \"center\",\n elevation: 6,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 3 },\n shadowOpacity: 0.27,\n shadowRadius: 4.65,\n },\n fabIcon: {\n fontSize: 24,\n },\n backdrop: {\n flex: 1,\n backgroundColor: \"rgba(0, 0, 0, 0.4)\",\n justifyContent: \"flex-end\",\n },\n card: {\n backgroundColor: \"#ffffff\",\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n overflow: \"hidden\",\n elevation: 10,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: -3 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e5e7eb\",\n },\n headerTitle: {\n fontSize: 17,\n fontWeight: \"600\",\n color: \"#111827\",\n },\n closeButton: {\n fontSize: 18,\n color: \"#6b7280\",\n fontWeight: \"500\",\n },\n chatContainer: {\n flex: 1,\n },\n});\n"],"mappings":";;;;;;;;;;;;;;;AAiFA,MAAM,mBAAmB,KAAK,OAAO;;;;;;;;;AAcrC,SAAgB,eAAe,EAC7B,UACwD;CACxD,MAAM,UAAU,QAAQ,WAAW;CAEnC,MAAM,CAAC,aAAa,kBAAkB,SAAuB,EAAE,CAAC;CAGhE,MAAM,YAAY,OAAO,OAAO;AAChC,WAAU,UAAU;CACpB,MAAM,iBAAiB,OAAqB,EAAE,CAAC;AAC/C,gBAAe,UAAU;;;;;;CAOzB,MAAM,gBAAgB,aACnB,MAAuB,WAA4B;AAClD,MAAI,CAAC,UAAU,WAAW,MAAO,QAAO;AAExC,SADgB,OAAO,MAAM,IAAI,CAAC,KAAK,MAAM,EAAE,MAAM,CAAC,CACvC,MAAM,WAAW;AAC9B,OAAI,OAAO,WAAW,IAAI,CACxB,QAAO,KAAK,KAAK,aAAa,CAAC,SAAS,OAAO,aAAa,CAAC;AAE/D,OAAI,OAAO,SAAS,KAAK,EAAE;I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AAQ;EACR,cAAc;EACd,iBAAiB;EACjB,YAAY;EACZ,gBAAgB;EAChB,WAAW;EACX,aAAa;EACb,cAAc;GAAE,OAAO;GAAG,QAAQ;GAAG;EACrC,eAAe;EACf,cAAc;EACf;CACD,SAAS,EACP,UAAU,IACX;CACD,UAAU;EACR,MAAM;EACN,iBAAiB;EACjB,gBAAgB;EACjB;CACD,MAAM;EACJ,iBAAiB;EACjB,qBAAqB;EACrB,sBAAsB;EACtB,UAAU;EACV,WAAW;EACX,aAAa;EACb,cAAc;GAAE,OAAO;GAAG,QAAQ;GAAI;EACtC,eAAe;EACf,cAAc;EACf;CACD,QAAQ;EACN,eAAe;EACf,YAAY;EACZ,gBAAgB;EAChB,mBAAmB;EACnB,iBAAiB;EACjB,mBAAmB,WAAW;EAC9B,mBAAmB;EACpB;CACD,aAAa;EACX,UAAU;EACV,YAAY;EACZ,OAAO;EACR;CACD,aAAa;EACX,UAAU;EACV,OAAO;EACP,YAAY;EACb;CACD,eAAe,EACb,MAAM,GACP;CACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["useAgent","useCopilotKit","styles"],"sources":["../src/hooks/use-attachments.ts","../src/CopilotChat.tsx","../src/CopilotModal.tsx","../src/CopilotSidebar.tsx","../src/CopilotPopup.tsx"],"sourcesContent":["// packages/react-native/src/hooks/use-attachments.ts\nimport { useCallback, useRef, useState } from \"react\";\nimport {\n randomUUID,\n getModalityFromMimeType,\n formatFileSize,\n} from \"@copilotkit/shared\";\nimport type {\n Attachment,\n AttachmentUploadResult,\n AttachmentUploadErrorReason,\n} from \"@copilotkit/shared\";\nimport * as DocumentPicker from \"expo-document-picker\";\nimport * as FileSystem from \"expo-file-system\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Platform-neutral file descriptor for React Native.\n * Replaces the web `File` object in all attachment APIs.\n */\nexport interface NativeFileInput {\n /** Local file URI (e.g. `file:///path/to/file`). */\n uri: string;\n /** Filename with extension. */\n name: string;\n /** File size in bytes. */\n size: number;\n /** MIME type (e.g. `\"image/jpeg\"`). */\n mimeType: string;\n}\n\n/**\n * React Native variant of AttachmentsConfig.\n * Identical to the shared AttachmentsConfig except `onUpload` receives\n * a `NativeFileInput` instead of a web `File`.\n */\nexport interface NativeAttachmentsConfig {\n /** Enable file attachments in the chat input. */\n enabled: boolean;\n /** MIME type filter for the file picker, default all files. */\n accept?: string;\n /** Maximum file size in bytes, default 20MB (20 * 1024 * 1024). */\n maxSize?: number;\n /** Custom upload handler. Receives the native file descriptor. */\n onUpload?: (\n file: NativeFileInput,\n ) => AttachmentUploadResult | Promise<AttachmentUploadResult>;\n /** Called when an attachment fails validation or upload. */\n onUploadFailed?: (error: {\n reason: AttachmentUploadErrorReason;\n file: NativeFileInput;\n message: string;\n }) => void;\n}\n\nexport interface UseNativeAttachmentsProps {\n config?: NativeAttachmentsConfig;\n}\n\nexport interface UseNativeAttachmentsReturn {\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n enabled: boolean;\n /** Open the native document picker. */\n openPicker: () => Promise<void>;\n /** Process an array of NativeFileInput objects (validate, read, add to state). */\n processFiles: (files: NativeFileInput[]) => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /** Consume ready attachments and clear the queue. Returns the consumed attachments. */\n consumeAttachments: () => Attachment[];\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20 MB\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * React Native hook that manages file attachment state -- picking, uploading,\n * and lifecycle. All returned callbacks are referentially stable via useCallback.\n *\n * This is the RN counterpart of the web `useAttachments` hook from\n * `@copilotkit/react-core`. It replaces web APIs (FileReader, DragEvent,\n * HTMLInputElement) with Expo modules (expo-document-picker, expo-file-system).\n */\nexport function useAttachments({\n config,\n}: UseNativeAttachmentsProps): UseNativeAttachmentsReturn {\n const enabled = config?.enabled ?? false;\n\n const [attachments, setAttachments] = useState<Attachment[]>([]);\n\n // Refs for stable callbacks to read latest values\n const configRef = useRef(config);\n configRef.current = config;\n const attachmentsRef = useRef<Attachment[]>([]);\n attachmentsRef.current = attachments;\n\n /**\n * Simple MIME accept filter for NativeFileInput.\n * Handles wildcards like \"image/*\" and exact types like \"application/pdf\".\n * Comma-separated lists are supported.\n */\n const matchesAccept = useCallback(\n (file: NativeFileInput, accept: string): boolean => {\n if (!accept || accept === \"*/*\") return true;\n const filters = accept.split(\",\").map((f) => f.trim());\n return filters.some((filter) => {\n if (filter.startsWith(\".\")) {\n return file.name.toLowerCase().endsWith(filter.toLowerCase());\n }\n if (filter.endsWith(\"/*\")) {\n const prefix = filter.slice(0, -2);\n return file.mimeType.startsWith(prefix + \"/\");\n }\n return file.mimeType === filter;\n });\n },\n [],\n );\n\n const processFiles = useCallback(\n async (files: NativeFileInput[]) => {\n const cfg = configRef.current;\n const accept = cfg?.accept ?? \"*/*\";\n const maxSize = cfg?.maxSize ?? DEFAULT_MAX_SIZE;\n\n // Filter by accept type\n const rejectedFiles = files.filter((f) => !matchesAccept(f, accept));\n for (const file of rejectedFiles) {\n cfg?.onUploadFailed?.({\n reason: \"invalid-type\",\n file,\n message: `File \"${file.name}\" is not accepted. Supported types: ${accept}`,\n });\n }\n\n const validFiles = files.filter((f) => matchesAccept(f, accept));\n\n for (const file of validFiles) {\n // Size check\n if (file.size > maxSize) {\n cfg?.onUploadFailed?.({\n reason: \"file-too-large\",\n file,\n message: `File \"${file.name}\" exceeds the maximum size of ${formatFileSize(maxSize)}`,\n });\n continue;\n }\n\n const modality = getModalityFromMimeType(file.mimeType);\n const placeholderId = randomUUID();\n const placeholder: Attachment = {\n id: placeholderId,\n type: modality,\n source: { type: \"data\", value: \"\", mimeType: file.mimeType },\n filename: file.name,\n size: file.size,\n status: \"uploading\",\n };\n\n setAttachments((prev) => [...prev, placeholder]);\n\n try {\n let source: Attachment[\"source\"];\n let uploadMetadata: Record<string, unknown> | undefined;\n\n if (cfg?.onUpload) {\n const { metadata: meta, ...uploadSource } =\n await cfg.onUpload(file);\n source = uploadSource;\n uploadMetadata = meta;\n } else {\n // Default: read file as base64 via expo-file-system\n const base64 = await FileSystem.readAsStringAsync(file.uri, {\n encoding: FileSystem.EncodingType.Base64,\n });\n source = { type: \"data\", value: base64, mimeType: file.mimeType };\n }\n\n setAttachments((prev) =>\n prev.map((att) =>\n att.id === placeholderId\n ? {\n ...att,\n source,\n status: \"ready\" as const,\n metadata: uploadMetadata,\n }\n : att,\n ),\n );\n } catch (error) {\n // Remove placeholder on failure\n setAttachments((prev) =>\n prev.filter((att) => att.id !== placeholderId),\n );\n console.error(`[CopilotKit] Failed to upload \"${file.name}\":`, error);\n cfg?.onUploadFailed?.({\n reason: \"upload-failed\",\n file,\n message:\n error instanceof Error\n ? error.message\n : `Failed to upload \"${file.name}\"`,\n });\n }\n }\n },\n [matchesAccept],\n );\n\n const openPicker = useCallback(async () => {\n const cfg = configRef.current;\n const accept = cfg?.accept ?? \"*/*\";\n\n // Convert accept string to array for DocumentPicker\n const typeArray = accept\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean);\n\n try {\n const result = await DocumentPicker.getDocumentAsync({\n type: typeArray.length > 0 ? typeArray : [\"*/*\"],\n copyToCacheDirectory: true,\n multiple: true,\n });\n\n if (result.canceled || !result.assets?.length) return;\n\n const nativeFiles: NativeFileInput[] = result.assets.map((asset) => ({\n uri: asset.uri,\n name: asset.name ?? \"unknown\",\n size: asset.size ?? 0,\n mimeType: asset.mimeType ?? \"application/octet-stream\",\n }));\n\n await processFiles(nativeFiles);\n } catch (error) {\n console.error(\"[CopilotKit] Document picker error:\", error);\n }\n }, [processFiles]);\n\n const removeAttachment = useCallback((id: string) => {\n setAttachments((prev) => prev.filter((a) => a.id !== id));\n }, []);\n\n const consumeAttachments = useCallback(() => {\n const ready = attachmentsRef.current.filter((a) => a.status === \"ready\");\n if (ready.length === 0) return ready;\n setAttachments((prev) => prev.filter((a) => a.status !== \"ready\"));\n return ready;\n }, []);\n\n return {\n attachments,\n enabled,\n openPicker,\n processFiles,\n removeAttachment,\n consumeAttachments,\n };\n}\n","import React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useRef,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotChatConfigurationProvider,\n useAgent,\n useCopilotChatConfiguration,\n} from \"@copilotkit/react-core/headless\";\nimport { useCopilotKit } from \"@copilotkit/react-core/context\";\nimport { DEFAULT_AGENT_ID, randomUUID } from \"@copilotkit/shared\";\nimport type { InputContent } from \"@copilotkit/shared\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport { useAttachments } from \"./hooks/use-attachments\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { Attachment } from \"@copilotkit/shared\";\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatContextValue {\n /** The resolved agent instance. */\n agent: any;\n /** Whether the agent is currently running. */\n isRunning: boolean;\n /** Current messages in the conversation. */\n messages: any[];\n /** Currently selected attachments (uploading + ready). */\n attachments: Attachment[];\n /** Whether attachments are enabled. */\n attachmentsEnabled: boolean;\n /** Open the native document picker to add files. */\n openPicker: () => Promise<void>;\n /** Remove an attachment by ID. */\n removeAttachment: (id: string) => void;\n /**\n * Submit a message with optional attachments.\n * Handles consuming ready attachments, building InputContent[],\n * calling agent.addMessage, and running the agent.\n */\n submitMessage: (text: string) => Promise<void>;\n}\n\nconst CopilotChatCtx = createContext<CopilotChatContextValue | null>(null);\n\n/**\n * Hook to access the CopilotChat context from child components.\n * Must be called inside a `<CopilotChat>` component tree.\n */\nexport function useCopilotChatContext(): CopilotChatContextValue {\n const ctx = useContext(CopilotChatCtx);\n if (!ctx) {\n throw new Error(\n \"useCopilotChatContext must be used within a <CopilotChat> component\",\n );\n }\n return ctx;\n}\n\n// ---------------------------------------------------------------------------\n// Props\n// ---------------------------------------------------------------------------\n\nexport interface CopilotChatBaseProps {\n /**\n * The agent ID to use for this chat session.\n * Matches the web SDK's CopilotChat `agentId` prop.\n *\n * Resolution order: `agentId` > `agentName` > the agent of the chat (or\n * `CopilotChatConfigurationProvider`) around this one > `\"default\"`\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead. `agentName` is kept for backwards\n * compatibility and will be removed in a future release.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session. When provided, the chat will resume\n * the specified thread. Matches the web SDK's CopilotChat `threadId` prop.\n */\n threadId?: string;\n\n /**\n * Error handler scoped to this chat's agent. Fires in addition to the\n * provider-level onError (does not suppress it). Receives errors whose\n * context.agentId matches this chat's agent, and errors with no agentId.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n\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 *\n * @default undefined -- inherits from provider `defaultThrottleMs`;\n * if that is also unset, re-renders are unthrottled.\n */\n throttleMs?: number;\n\n /**\n * Enable multimodal file attachments (images, audio, video, documents).\n * Pass a NativeAttachmentsConfig object to configure file picking behavior.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Optional children rendered inside the chat context.\n */\n children?: ReactNode;\n}\n\nexport interface CopilotChatProps extends CopilotChatBaseProps {\n /** Passthrough props are forwarded to consumers via the agent context. */\n [key: string]: unknown;\n}\n\n/**\n * Headless CopilotChat component for React Native.\n *\n * Wires up the `useAgent` hook with `agentId` resolution and renders children.\n * Unlike the web SDK's CopilotChat, this component does not render any UI\n * elements -- consumers provide their own React Native views.\n *\n * Children can access chat state via `useCopilotChatContext()`.\n *\n * Hooks inside the chat, such as `useAgent` and `useInterrupt`, use this\n * chat's agent when they do not pass an `agentId`. When the chat has a\n * `threadId`, `useAgent` inside the chat sets that thread on each agent it\n * returns, also on an agent that the hook names with its own `agentId`. Only\n * `useAgent({ agentId, runtimeAgentId, threadId })` keeps a different thread.\n *\n * A chat inside another chat uses the outer chat's agent when it has no\n * `agentId`. When the outer chat has a `threadId` and the inner chat does not,\n * the inner chat uses the outer thread. The web `CopilotChat` does the same.\n *\n * ```tsx\n * import { CopilotChat, useCopilotChatContext } from \"@copilotkit/react-native\";\n *\n * function MyChatUI() {\n * const { messages, submitMessage, attachments, openPicker } = useCopilotChatContext();\n * // ... render your UI\n * }\n *\n * <CopilotChat agentId=\"my-agent\" attachments={{ enabled: true }}>\n * <MyChatUI />\n * </CopilotChat>\n * ```\n */\nexport function CopilotChat({\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n attachments: attachmentsConfig,\n children,\n ..._rest\n}: CopilotChatProps) {\n // Same precedence as the web CopilotChat: a chat that names no agent takes\n // the agent of the chat configuration around it before \"default\".\n const chatConfig = useCopilotChatConfiguration();\n const resolvedAgentId =\n agentId ?? agentName ?? chatConfig?.agentId ?? DEFAULT_AGENT_ID;\n\n // Deprecation warning (dev only, fires once per mount)\n const warnedRef = useRef(false);\n useEffect(() => {\n if (\n agentName !== undefined &&\n agentId === undefined &&\n !warnedRef.current\n ) {\n warnedRef.current = true;\n if (typeof __DEV__ === \"undefined\" || __DEV__) {\n console.warn(\n \"[CopilotKit] agentName is deprecated, use agentId instead\",\n );\n }\n }\n }, [agentName, agentId]);\n\n const { agent } = useAgent({ agentId: resolvedAgentId, throttleMs });\n\n // Set threadId on the agent when provided\n useEffect(() => {\n if (threadId) {\n agent.threadId = threadId;\n }\n }, [agent, threadId]);\n\n // onError subscription -- forward core errors scoped to this chat's agent\n const { copilotkit } = useCopilotKit();\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n useEffect(() => {\n if (!onErrorRef.current) return;\n\n const subscription = copilotkit.subscribe({\n onError: (event) => {\n // Only forward errors that match this chat's agent\n if (\n event.context?.agentId === resolvedAgentId ||\n !event.context?.agentId\n ) {\n void onErrorRef.current?.({\n error: event.error,\n code: event.code,\n context: event.context,\n });\n }\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [copilotkit, resolvedAgentId]);\n\n // Attachments\n const {\n attachments: selectedAttachments,\n enabled: attachmentsEnabled,\n openPicker,\n removeAttachment,\n consumeAttachments,\n } = useAttachments({ config: attachmentsConfig });\n\n // Submit handler -- mirrors web CopilotChat.tsx lines 234-288\n const submitMessage = useCallback(\n async (value: string) => {\n // Block if uploads in progress\n const hasUploading = selectedAttachments.some(\n (a) => a.status === \"uploading\",\n );\n if (hasUploading) {\n console.error(\n \"[CopilotKit] Cannot send while attachments are uploading\",\n );\n return;\n }\n\n const readyAttachments = consumeAttachments();\n\n if (readyAttachments.length > 0) {\n const contentParts: InputContent[] = [];\n if (value.trim()) {\n contentParts.push({ type: \"text\", text: value });\n }\n for (const att of readyAttachments) {\n contentParts.push({\n type: att.type,\n source: att.source,\n metadata: {\n ...(att.filename ? { filename: att.filename } : {}),\n ...att.metadata,\n },\n } as InputContent);\n }\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: contentParts,\n });\n } else {\n agent.addMessage({\n id: randomUUID(),\n role: \"user\",\n content: value,\n });\n }\n\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed\", error);\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 [agent, selectedAttachments, consumeAttachments],\n );\n\n const contextValue: CopilotChatContextValue = {\n agent,\n isRunning: agent.isRunning,\n messages: agent.messages,\n attachments: selectedAttachments,\n attachmentsEnabled,\n openPicker,\n removeAttachment,\n submitMessage,\n };\n\n // Publish this chat's agent and thread to the subtree, as the web\n // CopilotChat does. Hooks inside it that name no agent use this chat's\n // agent, which is the outer chat's agent when this chat names none.\n return (\n <CopilotChatConfigurationProvider\n agentId={resolvedAgentId}\n threadId={threadId}\n >\n <CopilotChatCtx.Provider value={contextValue}>\n {children}\n </CopilotChatCtx.Provider>\n </CopilotChatConfigurationProvider>\n );\n}\n","import React, { type ReactNode } from \"react\";\nimport { CopilotChat, type CopilotChatProps } from \"./CopilotChat\";\n\nexport interface CopilotModalProps extends CopilotChatProps {\n /**\n * Optional children rendered inside the modal context.\n */\n children?: ReactNode;\n}\n\n/**\n * Headless CopilotModal component for React Native.\n *\n * A thin wrapper around CopilotChat that mirrors the web SDK's CopilotModal\n * API surface. On React Native, modal presentation is handled by the consumer\n * (e.g. React Native's `Modal` component) -- this component only provides\n * the agent wiring and prop resolution.\n *\n * ```tsx\n * import { CopilotModal } from \"@copilotkit/react-native\";\n * import { Modal } from \"react-native\";\n *\n * <Modal visible={isOpen}>\n * <CopilotModal agentId=\"my-agent\">\n * <MyChatUI />\n * </CopilotModal>\n * </Modal>\n * ```\n */\nexport function CopilotModal({ children, ...props }: CopilotModalProps) {\n return <CopilotChat {...props}>{children}</CopilotChat>;\n}\n","import React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Animated,\n Pressable,\n StyleSheet,\n Text,\n useWindowDimensions,\n View,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { CopilotChatBaseProps } from \"./CopilotChat\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface CopilotSidebarHandle {\n /** Slide the drawer open. */\n open(): void;\n /** Slide the drawer closed. */\n close(): void;\n /** Toggle the drawer open/closed. */\n toggle(): void;\n}\n\nexport interface CopilotSidebarProps extends Omit<\n CopilotChatBaseProps,\n \"children\"\n> {\n /**\n * Start the drawer in the open position.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Width of the drawer panel. Accepts a number (points) or a percentage\n * string (e.g. `\"85%\"`). Defaults to 85% of the screen width.\n */\n width?: number | string;\n\n /**\n * Title displayed in the drawer header bar.\n * @default \"Copilot\"\n */\n headerTitle?: string;\n\n /**\n * Show a floating action button to toggle the drawer.\n * @default true\n */\n showToggleButton?: boolean;\n\n /** Called after the drawer finishes opening. */\n onOpen?: () => void;\n\n /** Called after the drawer finishes closing. */\n onClose?: () => void;\n\n /** Custom style applied to the drawer container. */\n style?: ViewStyle;\n\n /**\n * Your chat UI, rendered inside the drawer below the header. The inner\n * CopilotChat is headless and draws no messages or input of its own.\n */\n children?: ReactNode;\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst ANIMATION_DURATION_MS = 300;\nconst DEFAULT_HEADER_TITLE = \"Copilot\";\nconst BACKDROP_OPACITY = 0.4;\nconst FAB_SIZE = 56;\n\n// ---------------------------------------------------------------------------\n// Component\n// ---------------------------------------------------------------------------\n\n/**\n * CopilotSidebar -- a slide-in drawer from the right edge of the screen\n * that wraps CopilotChat for React Native.\n *\n * ```tsx\n * import { CopilotSidebar } from \"@copilotkit/react-native\";\n *\n * const ref = useRef<CopilotSidebarHandle>(null);\n *\n * <CopilotSidebar\n * ref={ref}\n * agentId=\"my-agent\"\n * headerTitle=\"Assistant\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotSidebar = forwardRef<\n CopilotSidebarHandle,\n CopilotSidebarProps\n>(function CopilotSidebar(\n {\n agentId,\n agentName,\n threadId,\n onError,\n throttleMs,\n defaultOpen = false,\n width: widthProp,\n headerTitle = DEFAULT_HEADER_TITLE,\n showToggleButton = true,\n onOpen,\n onClose,\n style,\n children,\n ...rest\n },\n ref,\n) {\n const { width: screenWidth } = useWindowDimensions();\n\n // Resolve drawer width ---------------------------------------------------\n const drawerWidth = resolveWidth(widthProp, screenWidth);\n\n // Animation & open state -------------------------------------------------\n const [isOpen, setIsOpen] = useState(defaultOpen);\n const [slideAnim] = useState(\n () => new Animated.Value(defaultOpen ? 0 : drawerWidth),\n );\n\n // Keep the animated value in sync when drawerWidth changes while closed\n useEffect(() => {\n if (!isOpen) {\n slideAnim.setValue(drawerWidth);\n }\n }, [drawerWidth, isOpen, slideAnim]);\n\n const animateTo = useCallback(\n (toValue: number, cb?: () => void) => {\n Animated.timing(slideAnim, {\n toValue,\n duration: ANIMATION_DURATION_MS,\n useNativeDriver: true,\n }).start(({ finished }) => {\n if (finished) cb?.();\n });\n },\n [slideAnim],\n );\n\n const open = useCallback(() => {\n setIsOpen(true);\n animateTo(0, onOpen);\n }, [animateTo, onOpen]);\n\n const close = useCallback(() => {\n animateTo(drawerWidth, () => {\n setIsOpen(false);\n onClose?.();\n });\n }, [animateTo, drawerWidth, onClose]);\n\n const toggle = useCallback(() => {\n if (isOpen) {\n close();\n } else {\n open();\n }\n }, [isOpen, open, close]);\n\n useImperativeHandle(ref, () => ({ open, close, toggle }), [\n open,\n close,\n toggle,\n ]);\n\n // Callbacks stored in refs for stable animation closures -----------------\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n // -----------------------------------------------------------------------\n // Render\n // -----------------------------------------------------------------------\n return (\n <>\n {/* Backdrop */}\n {isOpen && (\n <Pressable\n style={styles.backdrop}\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close sidebar\"\n testID=\"copilot-sidebar-backdrop\"\n />\n )}\n\n {/* Drawer */}\n {isOpen && (\n <Animated.View\n style={[\n styles.drawer,\n { width: drawerWidth, transform: [{ translateX: slideAnim }] },\n style,\n ]}\n testID=\"copilot-sidebar-drawer\"\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <Pressable\n onPress={close}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Close\"\n hitSlop={8}\n testID=\"copilot-sidebar-close\"\n >\n <Text style={styles.closeButton}>{\"✕\"}</Text>\n </Pressable>\n </View>\n\n {/* Chat area */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n onError={onError}\n throttleMs={throttleMs}\n {...rest}\n >\n {children}\n </CopilotChat>\n </View>\n </Animated.View>\n )}\n\n {/* Floating action button */}\n {showToggleButton && !isOpen && (\n <Pressable\n style={styles.fab}\n onPress={open}\n accessibilityRole=\"button\"\n accessibilityLabel=\"Open sidebar\"\n testID=\"copilot-sidebar-fab\"\n >\n <Text style={styles.fabIcon}>{\"💬\"}</Text>\n </Pressable>\n )}\n </>\n );\n});\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction resolveWidth(\n widthProp: number | string | undefined,\n screenWidth: number,\n): number {\n if (widthProp === undefined) {\n return Math.round(screenWidth * 0.85);\n }\n if (typeof widthProp === \"number\") {\n return widthProp;\n }\n // Percentage string, e.g. \"85%\"\n const pctMatch = String(widthProp).match(/^(\\d+(?:\\.\\d+)?)%$/);\n if (pctMatch) {\n return Math.round(screenWidth * (parseFloat(pctMatch[1]) / 100));\n }\n // Fallback: try parsing as number\n const parsed = parseFloat(widthProp);\n return isNaN(parsed) ? Math.round(screenWidth * 0.85) : parsed;\n}\n\n// ---------------------------------------------------------------------------\n// Styles\n// ---------------------------------------------------------------------------\n\nconst styles = StyleSheet.create({\n backdrop: {\n ...StyleSheet.absoluteFill,\n backgroundColor: `rgba(0, 0, 0, ${BACKDROP_OPACITY})`,\n zIndex: 999,\n },\n drawer: {\n position: \"absolute\",\n top: 0,\n right: 0,\n bottom: 0,\n backgroundColor: \"#ffffff\",\n zIndex: 1000,\n shadowColor: \"#000\",\n shadowOffset: { width: -2, height: 0 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n elevation: 16,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e0e0e0\",\n },\n headerTitle: {\n fontSize: 18,\n fontWeight: \"600\",\n color: \"#1a1a1a\",\n },\n closeButton: {\n fontSize: 20,\n color: \"#666\",\n padding: 4,\n },\n chatContainer: {\n flex: 1,\n },\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: FAB_SIZE,\n height: FAB_SIZE,\n borderRadius: FAB_SIZE / 2,\n backgroundColor: \"#007AFF\",\n alignItems: \"center\",\n justifyContent: \"center\",\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 2 },\n shadowOpacity: 0.3,\n shadowRadius: 4,\n elevation: 8,\n zIndex: 998,\n },\n fabIcon: {\n fontSize: 24,\n },\n});\n","// NOTE: This component needs to be exported from index.ts\n// e.g. export { CopilotPopup } from \"./CopilotPopup\";\n// export type { CopilotPopupProps, CopilotPopupHandle } from \"./CopilotPopup\";\n\nimport React, {\n forwardRef,\n useCallback,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n Modal,\n Pressable,\n StyleSheet,\n Text,\n TouchableOpacity,\n View,\n useWindowDimensions,\n} from \"react-native\";\nimport type { ViewStyle } from \"react-native\";\nimport { CopilotChat } from \"./CopilotChat\";\nimport type { NativeAttachmentsConfig } from \"./hooks/use-attachments\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\n\nexport interface CopilotPopupProps {\n /**\n * The agent ID to use for this chat session.\n * Passed through to CopilotChat.\n */\n agentId?: string;\n\n /**\n * @deprecated Use `agentId` instead.\n */\n agentName?: string;\n\n /**\n * Thread ID for this chat session.\n */\n threadId?: string;\n\n /**\n * Throttle interval (ms) for re-renders.\n */\n throttleMs?: number;\n\n /**\n * Whether the popup starts in the open state.\n * @default false\n */\n defaultOpen?: boolean;\n\n /**\n * Height of the popup card. Accepts a number (points) or a percentage\n * string (e.g. \"60%\") relative to the screen height.\n * @default \"60%\"\n */\n height?: number | string;\n\n /**\n * Error handler scoped to this popup's chat agent.\n */\n onError?: (error: Error) => void;\n\n /**\n * Title displayed in the popup header bar.\n * @default \"CopilotKit\"\n */\n headerTitle?: string;\n\n /**\n * Enable multimodal file attachments. Forwarded to the internal CopilotChat.\n * Children access attachment state via `useCopilotChatContext()`.\n */\n attachments?: NativeAttachmentsConfig;\n\n /**\n * Your chat UI, rendered inside the popup card below the header. The inner\n * CopilotChat is headless and draws no messages or input of its own.\n */\n children?: ReactNode;\n\n /**\n * Callback fired when the popup opens.\n */\n onOpen?: () => void;\n\n /**\n * Callback fired when the popup closes.\n */\n onClose?: () => void;\n\n /**\n * Whether tapping the semi-transparent backdrop dismisses the popup.\n * Equivalent to web SDK's `clickOutsideToClose`.\n * @default true\n */\n dismissOnBackdropPress?: boolean;\n\n /**\n * Whether to show the floating action button (FAB) that toggles the popup.\n * @default true\n */\n showToggleButton?: boolean;\n\n /**\n * Custom styles applied to the popup card container.\n */\n style?: ViewStyle;\n}\n\n/**\n * Imperative handle exposed via ref for controlling the popup programmatically.\n */\nexport interface CopilotPopupHandle {\n open: () => void;\n close: () => void;\n toggle: () => void;\n}\n\n/**\n * CopilotPopup for React Native.\n *\n * A floating action button (FAB) that opens a modal chat overlay.\n * The popup appears as a card floating above content with rounded corners,\n * a shadow, and a semi-transparent backdrop.\n *\n * ```tsx\n * import { CopilotPopup } from \"@copilotkit/react-native\";\n *\n * const popupRef = useRef<CopilotPopupHandle>(null);\n *\n * <CopilotPopup\n * ref={popupRef}\n * agentId=\"my-agent\"\n * headerTitle=\"Chat\"\n * defaultOpen={false}\n * />\n * ```\n */\nexport const CopilotPopup = forwardRef<CopilotPopupHandle, CopilotPopupProps>(\n function CopilotPopup(\n {\n agentId,\n agentName,\n threadId,\n throttleMs,\n defaultOpen = false,\n height = \"60%\",\n onError,\n headerTitle = \"CopilotKit\",\n attachments: attachmentsConfig,\n children,\n onOpen,\n onClose,\n dismissOnBackdropPress = true,\n showToggleButton = true,\n style,\n }: CopilotPopupProps,\n ref: React.Ref<CopilotPopupHandle>,\n ) {\n const [visible, setVisible] = useState(defaultOpen);\n const { height: screenHeight } = useWindowDimensions();\n\n // Stable refs for callbacks to avoid effect churn\n const onOpenRef = useRef(onOpen);\n const onCloseRef = useRef(onClose);\n useEffect(() => {\n onOpenRef.current = onOpen;\n }, [onOpen]);\n useEffect(() => {\n onCloseRef.current = onClose;\n }, [onClose]);\n\n const handleOpen = useCallback(() => {\n setVisible(true);\n onOpenRef.current?.();\n }, []);\n\n const handleClose = useCallback(() => {\n setVisible(false);\n onCloseRef.current?.();\n }, []);\n\n const handleToggle = useCallback(() => {\n setVisible((prev) => {\n const next = !prev;\n if (next) {\n onOpenRef.current?.();\n } else {\n onCloseRef.current?.();\n }\n return next;\n });\n }, []);\n\n // Expose imperative methods\n useImperativeHandle(\n ref,\n () => ({\n open: handleOpen,\n close: handleClose,\n toggle: handleToggle,\n }),\n [handleOpen, handleClose, handleToggle],\n );\n\n // Resolve popup height\n const resolvedHeight =\n typeof height === \"string\" && height.endsWith(\"%\")\n ? (parseFloat(height) / 100) * screenHeight\n : typeof height === \"number\"\n ? height\n : 0.6 * screenHeight;\n\n // Wrap onError to match CopilotChat's expected signature\n const chatOnError = onError\n ? (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => onError(event.error)\n : undefined;\n\n return (\n <>\n {/* Floating Action Button */}\n {showToggleButton && !visible && (\n <TouchableOpacity\n testID=\"copilot-popup-fab\"\n style={styles.fab}\n onPress={handleToggle}\n activeOpacity={0.8}\n accessibilityLabel=\"Open chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.fabIcon}>💬</Text>\n </TouchableOpacity>\n )}\n\n {/* Modal Overlay */}\n <Modal\n testID=\"copilot-popup-modal\"\n visible={visible}\n transparent\n animationType=\"slide\"\n onRequestClose={handleClose}\n >\n {/* Backdrop */}\n <Pressable\n testID=\"copilot-popup-backdrop\"\n style={styles.backdrop}\n onPress={dismissOnBackdropPress ? handleClose : undefined}\n >\n {/* Card — stop propagation so tapping the card doesn't dismiss */}\n <Pressable\n testID=\"copilot-popup-card\"\n style={[styles.card, { height: resolvedHeight }, style]}\n onPress={() => {\n // Prevent backdrop press from firing\n }}\n >\n {/* Header */}\n <View style={styles.header}>\n <Text style={styles.headerTitle}>{headerTitle}</Text>\n <TouchableOpacity\n testID=\"copilot-popup-close\"\n onPress={handleClose}\n hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}\n accessibilityLabel=\"Close chat\"\n accessibilityRole=\"button\"\n >\n <Text style={styles.closeButton}>✕</Text>\n </TouchableOpacity>\n </View>\n\n {/* Chat Content */}\n <View style={styles.chatContainer}>\n <CopilotChat\n agentId={agentId}\n agentName={agentName}\n threadId={threadId}\n throttleMs={throttleMs}\n onError={chatOnError}\n attachments={attachmentsConfig}\n >\n {children}\n </CopilotChat>\n </View>\n </Pressable>\n </Pressable>\n </Modal>\n </>\n );\n },\n);\n\nconst styles = StyleSheet.create({\n fab: {\n position: \"absolute\",\n bottom: 24,\n right: 24,\n width: 56,\n height: 56,\n borderRadius: 28,\n backgroundColor: \"#6366f1\",\n alignItems: \"center\",\n justifyContent: \"center\",\n elevation: 6,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: 3 },\n shadowOpacity: 0.27,\n shadowRadius: 4.65,\n },\n fabIcon: {\n fontSize: 24,\n },\n backdrop: {\n flex: 1,\n backgroundColor: \"rgba(0, 0, 0, 0.4)\",\n justifyContent: \"flex-end\",\n },\n card: {\n backgroundColor: \"#ffffff\",\n borderTopLeftRadius: 16,\n borderTopRightRadius: 16,\n overflow: \"hidden\",\n elevation: 10,\n shadowColor: \"#000\",\n shadowOffset: { width: 0, height: -3 },\n shadowOpacity: 0.25,\n shadowRadius: 8,\n },\n header: {\n flexDirection: \"row\",\n alignItems: \"center\",\n justifyContent: \"space-between\",\n paddingHorizontal: 16,\n paddingVertical: 12,\n borderBottomWidth: StyleSheet.hairlineWidth,\n borderBottomColor: \"#e5e7eb\",\n },\n headerTitle: {\n fontSize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;CACD,aAAa;EACX,UAAU;EACV,YAAY;EACZ,OAAO;EACR;CACD,aAAa;EACX,UAAU;EACV,OAAO;EACP,YAAY;EACb;CACD,eAAe,EACb,MAAM,GACP;CACF,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@copilotkit/react-native",
|
|
3
|
-
"version": "2.0.0-rc.
|
|
3
|
+
"version": "2.0.0-rc.26",
|
|
4
4
|
"private": false,
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -77,10 +77,10 @@
|
|
|
77
77
|
},
|
|
78
78
|
"dependencies": {
|
|
79
79
|
"@ag-ui/client": "1.0.2",
|
|
80
|
-
"@copilotkit/core": "2.0.0-rc.
|
|
81
|
-
"@copilotkit/markdown": "2.0.0-rc.
|
|
82
|
-
"@copilotkit/react-core": "2.0.0-rc.
|
|
83
|
-
"@copilotkit/shared": "2.0.0-rc.
|
|
80
|
+
"@copilotkit/core": "2.0.0-rc.26",
|
|
81
|
+
"@copilotkit/markdown": "2.0.0-rc.26",
|
|
82
|
+
"@copilotkit/react-core": "2.0.0-rc.26",
|
|
83
|
+
"@copilotkit/shared": "2.0.0-rc.26",
|
|
84
84
|
"web-streams-polyfill": "^4.2.0"
|
|
85
85
|
},
|
|
86
86
|
"devDependencies": {
|
package/src/CopilotSidebar.tsx
CHANGED
|
@@ -9,7 +9,6 @@ import React, {
|
|
|
9
9
|
import type { ReactNode } from "react";
|
|
10
10
|
import {
|
|
11
11
|
Animated,
|
|
12
|
-
Dimensions,
|
|
13
12
|
Pressable,
|
|
14
13
|
StyleSheet,
|
|
15
14
|
Text,
|
|
@@ -136,9 +135,9 @@ export const CopilotSidebar = forwardRef<
|
|
|
136
135
|
|
|
137
136
|
// Animation & open state -------------------------------------------------
|
|
138
137
|
const [isOpen, setIsOpen] = useState(defaultOpen);
|
|
139
|
-
const slideAnim =
|
|
140
|
-
new Animated.Value(defaultOpen ? 0 : drawerWidth),
|
|
141
|
-
)
|
|
138
|
+
const [slideAnim] = useState(
|
|
139
|
+
() => new Animated.Value(defaultOpen ? 0 : drawerWidth),
|
|
140
|
+
);
|
|
142
141
|
|
|
143
142
|
// Keep the animated value in sync when drawerWidth changes while closed
|
|
144
143
|
useEffect(() => {
|
|
@@ -11,7 +11,6 @@ import { formatTimestamp } from "./utils";
|
|
|
11
11
|
|
|
12
12
|
// ─── Colors ──────────────────────────────────────────────────────────────────
|
|
13
13
|
const ASSISTANT_BUBBLE_BG = "#F0F0F0";
|
|
14
|
-
const ASSISTANT_TEXT_COLOR = "#1A1A1A";
|
|
15
14
|
const TIMESTAMP_COLOR = "#999999";
|
|
16
15
|
|
|
17
16
|
/**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import React, { useEffect,
|
|
1
|
+
import React, { useEffect, useState } from "react";
|
|
2
2
|
import { View, Animated, StyleSheet } from "react-native";
|
|
3
3
|
import type { ViewStyle } from "react-native";
|
|
4
4
|
|
|
@@ -21,9 +21,9 @@ const ANIMATION_DURATION = 400;
|
|
|
21
21
|
* Uses React Native's built-in `Animated` API (no Reanimated dependency).
|
|
22
22
|
*/
|
|
23
23
|
export function TypingIndicator({ style }: TypingIndicatorProps) {
|
|
24
|
-
const dot1 =
|
|
25
|
-
const dot2 =
|
|
26
|
-
const dot3 =
|
|
24
|
+
const [dot1] = useState(() => new Animated.Value(0));
|
|
25
|
+
const [dot2] = useState(() => new Animated.Value(0));
|
|
26
|
+
const [dot3] = useState(() => new Animated.Value(0));
|
|
27
27
|
|
|
28
28
|
useEffect(() => {
|
|
29
29
|
const createPulse = (dot: Animated.Value, delay: number) =>
|