@copilotkit/react-native 2.0.0-rc.25 → 2.0.0-rc.27

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.
@@ -3,7 +3,10 @@ import React, {
3
3
  useCallback,
4
4
  useContext,
5
5
  useEffect,
6
+ useLayoutEffect,
7
+ useMemo,
6
8
  useRef,
9
+ useState,
7
10
  } from "react";
8
11
  import type { ReactNode } from "react";
9
12
  import {
@@ -12,9 +15,14 @@ import {
12
15
  useCopilotChatConfiguration,
13
16
  } from "@copilotkit/react-core/headless";
14
17
  import { useCopilotKit } from "@copilotkit/react-core/context";
15
- import { DEFAULT_AGENT_ID, randomUUID } from "@copilotkit/shared";
16
- import type { InputContent } from "@copilotkit/shared";
18
+ import { DEFAULT_AGENT_ID } from "@copilotkit/shared";
17
19
  import type { CopilotKitCoreErrorCode } from "@copilotkit/core";
20
+ import {
21
+ ɵChatConnection,
22
+ ɵFreshThreadId,
23
+ ɵcreateChatSubmitter,
24
+ ɵsubscribeToAgentErrors,
25
+ } from "@copilotkit/core";
18
26
  import { useAttachments } from "./hooks/use-attachments";
19
27
  import type { NativeAttachmentsConfig } from "./hooks/use-attachments";
20
28
  import type { Attachment } from "@copilotkit/shared";
@@ -39,9 +47,10 @@ export interface CopilotChatContextValue {
39
47
  /** Remove an attachment by ID. */
40
48
  removeAttachment: (id: string) => void;
41
49
  /**
42
- * Submit a message with optional attachments.
43
- * Handles consuming ready attachments, building InputContent[],
44
- * calling agent.addMessage, and running the agent.
50
+ * Submit a message with the ready attachments and run the agent. Waits
51
+ * for the thread's connection and for the run in flight. Blank text, and a
52
+ * send while an attachment uploads, are ignored. Resolves once the run has
53
+ * settled.
45
54
  */
46
55
  submitMessage: (text: string) => Promise<void>;
47
56
  }
@@ -83,8 +92,10 @@ export interface CopilotChatBaseProps {
83
92
  agentName?: string;
84
93
 
85
94
  /**
86
- * Thread ID for this chat session. When provided, the chat will resume
87
- * the specified thread. Matches the web SDK's CopilotChat `threadId` prop.
95
+ * Thread ID for this chat session. When provided, the chat restores the
96
+ * thread from the backend and reconnects to a run in progress. Without it,
97
+ * the chat uses the thread of the chat around it, or a new thread. Matches
98
+ * the web SDK's CopilotChat `threadId` prop.
88
99
  */
89
100
  threadId?: string;
90
101
 
@@ -191,17 +202,37 @@ export function CopilotChat({
191
202
  }
192
203
  }, [agentName, agentId]);
193
204
 
205
+ // Same thread rules as the web CopilotChat: the `threadId` prop, else the
206
+ // thread of the chat around this one, else a UUID minted for this chat.
207
+ // Only a thread a caller picked is "explicit" and restored from the backend.
208
+ const providedThreadId = threadId ?? chatConfig?.threadId;
209
+ const [freshThreadId] = useState(() => new ɵFreshThreadId());
210
+ const resolvedThreadId = useMemo(
211
+ () => freshThreadId.resolve(providedThreadId),
212
+ [freshThreadId, providedThreadId],
213
+ );
214
+ const hasExplicitThreadId = !!threadId || !!chatConfig?.hasExplicitThreadId;
215
+
194
216
  const { agent } = useAgent({ agentId: resolvedAgentId, throttleMs });
217
+ const { copilotkit } = useCopilotKit();
195
218
 
196
- // Set threadId on the agent when provided
219
+ // Keeps the agent on the thread this chat shows, restores a picked thread
220
+ // with a connect, and empties the agent on a switch to a fresh thread. Core
221
+ // owns the connect's abort and detach, as in the web chats.
222
+ const [connection] = useState(
223
+ () => new ɵChatConnection({ core: copilotkit }),
224
+ );
225
+ const { threads } = connection;
197
226
  useEffect(() => {
198
- if (threadId) {
199
- agent.threadId = threadId;
200
- }
201
- }, [agent, threadId]);
227
+ const handle = connection.open({
228
+ agent,
229
+ threadId: resolvedThreadId,
230
+ explicit: hasExplicitThreadId,
231
+ });
232
+ return () => handle.release();
233
+ }, [connection, agent, resolvedThreadId, hasExplicitThreadId]);
202
234
 
203
235
  // onError subscription -- forward core errors scoped to this chat's agent
204
- const { copilotkit } = useCopilotKit();
205
236
  const onErrorRef = useRef(onError);
206
237
  useEffect(() => {
207
238
  onErrorRef.current = onError;
@@ -209,26 +240,9 @@ export function CopilotChat({
209
240
 
210
241
  useEffect(() => {
211
242
  if (!onErrorRef.current) return;
212
-
213
- const subscription = copilotkit.subscribe({
214
- onError: (event) => {
215
- // Only forward errors that match this chat's agent
216
- if (
217
- event.context?.agentId === resolvedAgentId ||
218
- !event.context?.agentId
219
- ) {
220
- void onErrorRef.current?.({
221
- error: event.error,
222
- code: event.code,
223
- context: event.context,
224
- });
225
- }
226
- },
227
- });
228
-
229
- return () => {
230
- subscription.unsubscribe();
231
- };
243
+ return ɵsubscribeToAgentErrors(copilotkit, resolvedAgentId, (event) =>
244
+ onErrorRef.current?.(event),
245
+ );
232
246
  }, [copilotkit, resolvedAgentId]);
233
247
 
234
248
  // Attachments
@@ -239,60 +253,39 @@ export function CopilotChat({
239
253
  removeAttachment,
240
254
  consumeAttachments,
241
255
  } = useAttachments({ config: attachmentsConfig });
256
+ // A send waits for the run in flight, so the submitter re-checks the
257
+ // upload guard against the latest attachments, not this render's.
258
+ const attachmentsRef = useRef(selectedAttachments);
259
+ useLayoutEffect(() => {
260
+ attachmentsRef.current = selectedAttachments;
261
+ });
242
262
 
243
- // Submit handler -- mirrors web CopilotChat.tsx lines 234-288
263
+ // The send side lives in core: the upload guard, the message content, and
264
+ // waiting for the thread's connection and the run in flight.
265
+ const agentRef = useRef(agent);
266
+ useLayoutEffect(() => {
267
+ agentRef.current = agent;
268
+ });
269
+ const [submitter] = useState(() =>
270
+ ɵcreateChatSubmitter({
271
+ core: copilotkit,
272
+ getAgent: () => agentRef.current,
273
+ // This chat renders no input box, so there is no text to clear or put
274
+ // back.
275
+ input: { get: () => "", set: () => {} },
276
+ attachments: {
277
+ isUploading: () =>
278
+ attachmentsRef.current.some((a) => a.status === "uploading"),
279
+ consumeReady: () => consumeAttachments(),
280
+ },
281
+ threads,
282
+ }),
283
+ );
284
+ // Clears the notice timer of a blocked send on unmount.
285
+ useEffect(() => () => submitter.showNotice(null), [submitter]);
244
286
  const submitMessage = useCallback(
245
- async (value: string) => {
246
- // Block if uploads in progress
247
- const hasUploading = selectedAttachments.some(
248
- (a) => a.status === "uploading",
249
- );
250
- if (hasUploading) {
251
- console.error(
252
- "[CopilotKit] Cannot send while attachments are uploading",
253
- );
254
- return;
255
- }
256
-
257
- const readyAttachments = consumeAttachments();
258
-
259
- if (readyAttachments.length > 0) {
260
- const contentParts: InputContent[] = [];
261
- if (value.trim()) {
262
- contentParts.push({ type: "text", text: value });
263
- }
264
- for (const att of readyAttachments) {
265
- contentParts.push({
266
- type: att.type,
267
- source: att.source,
268
- metadata: {
269
- ...(att.filename ? { filename: att.filename } : {}),
270
- ...att.metadata,
271
- },
272
- } as InputContent);
273
- }
274
- agent.addMessage({
275
- id: randomUUID(),
276
- role: "user",
277
- content: contentParts,
278
- });
279
- } else {
280
- agent.addMessage({
281
- id: randomUUID(),
282
- role: "user",
283
- content: value,
284
- });
285
- }
286
-
287
- try {
288
- await copilotkit.runAgent({ agent });
289
- } catch (error) {
290
- console.error("CopilotChat: runAgent failed", error);
291
- }
292
- },
293
- // copilotkit is intentionally excluded -- it is a stable ref that never changes.
294
- // eslint-disable-next-line react-hooks/exhaustive-deps
295
- [agent, selectedAttachments, consumeAttachments],
287
+ (value: string) => submitter.submit(value),
288
+ [submitter],
296
289
  );
297
290
 
298
291
  const contextValue: CopilotChatContextValue = {
@@ -312,7 +305,8 @@ export function CopilotChat({
312
305
  return (
313
306
  <CopilotChatConfigurationProvider
314
307
  agentId={resolvedAgentId}
315
- threadId={threadId}
308
+ threadId={resolvedThreadId}
309
+ hasExplicitThreadId={hasExplicitThreadId}
316
310
  >
317
311
  <CopilotChatCtx.Provider value={contextValue}>
318
312
  {children}
@@ -135,9 +135,9 @@ export const CopilotSidebar = forwardRef<
135
135
 
136
136
  // Animation & open state -------------------------------------------------
137
137
  const [isOpen, setIsOpen] = useState(defaultOpen);
138
- const slideAnim = useRef(
139
- new Animated.Value(defaultOpen ? 0 : drawerWidth),
140
- ).current;
138
+ const [slideAnim] = useState(
139
+ () => new Animated.Value(defaultOpen ? 0 : drawerWidth),
140
+ );
141
141
 
142
142
  // Keep the animated value in sync when drawerWidth changes while closed
143
143
  useEffect(() => {
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Thread restore and thread switching in the headless `<CopilotChat>`. Runs on
3
+ * a REAL `CopilotKitCoreReact` (via `TestCopilotKit`), so the connect, the
4
+ * reset on a switch to a fresh thread, and the send queue are core's
5
+ * `ɵThreadSwitchCoordinator` and `ɵChatSubmitter`, as in the web chats.
6
+ */
7
+ import React from "react";
8
+ import { act, render, screen, waitFor } from "@testing-library/react";
9
+ import { describe, expect, it, vi } from "vitest";
10
+ import type { Message, RunAgentResult } from "@ag-ui/client";
11
+ import { CopilotChat, useCopilotChatContext } from "../CopilotChat";
12
+ import { SeededAgent, TestCopilotKit } from "../__mocks__/test-copilotkit";
13
+ import type { CopilotChatContextValue } from "../CopilotChat";
14
+
15
+ const EMPTY_RESULT: RunAgentResult = { result: undefined, newMessages: [] };
16
+
17
+ const text = (id: string, content: string): Message => ({
18
+ id,
19
+ role: "assistant",
20
+ content,
21
+ });
22
+
23
+ /**
24
+ * An agent with stored threads. `connectAgent` restores the history of the
25
+ * thread the agent is on, as the runtime's `/connect` does. A test can hold
26
+ * the connect open with `holdConnect`.
27
+ */
28
+ class ThreadedAgent extends SeededAgent {
29
+ readonly connectedThreadIds: string[] = [];
30
+ readonly runs: { threadId: string; messages: string[] }[] = [];
31
+ private heldConnect: Promise<void> | undefined;
32
+ private heldRun: Promise<void> | undefined;
33
+
34
+ constructor(private readonly histories: Record<string, Message[]>) {
35
+ super();
36
+ }
37
+
38
+ holdConnect() {
39
+ let release!: () => void;
40
+ this.heldConnect = new Promise<void>((resolve) => {
41
+ release = resolve;
42
+ });
43
+ return release;
44
+ }
45
+
46
+ override async connectAgent(): Promise<RunAgentResult> {
47
+ const threadId = this.threadId;
48
+ this.connectedThreadIds.push(threadId);
49
+ await this.heldConnect;
50
+ this.setMessages(this.histories[threadId] ?? []);
51
+ return EMPTY_RESULT;
52
+ }
53
+
54
+ /** Holds the next run open; the returned function finishes it with a reply. */
55
+ holdRun() {
56
+ let release!: () => void;
57
+ this.heldRun = new Promise<void>((resolve) => {
58
+ release = resolve;
59
+ });
60
+ return release;
61
+ }
62
+
63
+ override async runAgent(): Promise<RunAgentResult> {
64
+ this.runs.push({
65
+ threadId: this.threadId,
66
+ messages: this.messages.map((m) => String(m.content)),
67
+ });
68
+ const held = this.heldRun;
69
+ if (held) {
70
+ this.heldRun = undefined;
71
+ await held;
72
+ this.addMessage(text("reply", "reply"));
73
+ }
74
+ return EMPTY_RESULT;
75
+ }
76
+ }
77
+
78
+ let chat: CopilotChatContextValue | null = null;
79
+
80
+ function Transcript() {
81
+ chat = useCopilotChatContext();
82
+ return (
83
+ <ul data-testid="transcript">
84
+ {chat.messages.map((m: Message) => (
85
+ <li key={m.id}>{String(m.content)}</li>
86
+ ))}
87
+ </ul>
88
+ );
89
+ }
90
+
91
+ function renderChat(agent: ThreadedAgent, threadId?: string) {
92
+ const agents = { x: agent };
93
+ const view = (id?: string) => (
94
+ <TestCopilotKit messages={[]} agents={agents}>
95
+ <CopilotChat agentId="x" threadId={id}>
96
+ <Transcript />
97
+ </CopilotChat>
98
+ </TestCopilotKit>
99
+ );
100
+ const result = render(view(threadId));
101
+ return {
102
+ switchTo: (id?: string) => result.rerender(view(id)),
103
+ unmount: result.unmount,
104
+ };
105
+ }
106
+
107
+ const transcript = () =>
108
+ Array.from(screen.getByTestId("transcript").children).map(
109
+ (li) => li.textContent,
110
+ );
111
+
112
+ describe("headless CopilotChat threads", () => {
113
+ it("restores the thread named by threadId", async () => {
114
+ const agent = new ThreadedAgent({ t1: [text("a", "from t1")] });
115
+
116
+ renderChat(agent, "t1");
117
+
118
+ await waitFor(() => expect(transcript()).toEqual(["from t1"]));
119
+ expect(agent.connectedThreadIds).toEqual(["t1"]);
120
+ expect(agent.threadId).toBe("t1");
121
+ });
122
+
123
+ it("restores the new thread when threadId changes", async () => {
124
+ const agent = new ThreadedAgent({
125
+ t1: [text("a", "from t1")],
126
+ t2: [text("b", "from t2")],
127
+ });
128
+ const { switchTo } = renderChat(agent, "t1");
129
+ await waitFor(() => expect(transcript()).toEqual(["from t1"]));
130
+
131
+ switchTo("t2");
132
+
133
+ await waitFor(() => expect(transcript()).toEqual(["from t2"]));
134
+ expect(agent.connectedThreadIds).toEqual(["t1", "t2"]);
135
+ expect(agent.threadId).toBe("t2");
136
+ });
137
+
138
+ it("does not connect a chat without threadId, and gives the agent a new thread", () => {
139
+ const agent = new ThreadedAgent({});
140
+ const before = agent.threadId;
141
+
142
+ renderChat(agent);
143
+
144
+ expect(agent.connectedThreadIds).toEqual([]);
145
+ expect(agent.threadId).toEqual(expect.any(String));
146
+ expect(agent.threadId).not.toBe(before);
147
+ });
148
+
149
+ it("empties the chat when threadId is removed", async () => {
150
+ const agent = new ThreadedAgent({ t1: [text("a", "from t1")] });
151
+ const { switchTo } = renderChat(agent, "t1");
152
+ await waitFor(() => expect(transcript()).toEqual(["from t1"]));
153
+
154
+ switchTo(undefined);
155
+
156
+ await waitFor(() => expect(transcript()).toEqual([]));
157
+ expect(agent.threadId).not.toBe("t1");
158
+ expect(agent.connectedThreadIds).toEqual(["t1"]);
159
+ });
160
+
161
+ it("sends a message only after the thread has been restored", async () => {
162
+ const agent = new ThreadedAgent({ t1: [text("a", "from t1")] });
163
+ const release = agent.holdConnect();
164
+ renderChat(agent, "t1");
165
+ await waitFor(() => expect(agent.connectedThreadIds).toEqual(["t1"]));
166
+
167
+ let sent: Promise<void> | undefined;
168
+ act(() => {
169
+ sent = chat!.submitMessage("hello");
170
+ });
171
+ // The connect is still loading, so the send waits for it.
172
+ await Promise.resolve();
173
+ expect(agent.runs).toEqual([]);
174
+
175
+ await act(async () => {
176
+ release();
177
+ await sent;
178
+ });
179
+
180
+ expect(agent.runs).toEqual([
181
+ { threadId: "t1", messages: ["from t1", "hello"] },
182
+ ]);
183
+ });
184
+ it("leaves the agent's run running when the chat unmounts after the thread loaded", async () => {
185
+ const agent = new ThreadedAgent({ t1: [text("a", "from t1")] });
186
+ const { unmount } = renderChat(agent, "t1");
187
+ await waitFor(() => expect(transcript()).toEqual(["from t1"]));
188
+ const finishRun = agent.holdRun();
189
+ let sent: Promise<void> | undefined;
190
+ act(() => {
191
+ sent = chat!.submitMessage("hello");
192
+ });
193
+ await waitFor(() => expect(agent.runs).toHaveLength(1));
194
+ // Core detaches the previous run itself before a connect or a run; count
195
+ // only what the chat's cleanup does.
196
+ const detach = vi.spyOn(agent, "detachActiveRun");
197
+
198
+ unmount();
199
+ await act(async () => {});
200
+
201
+ // The connect had settled, so the run in flight is not the connect's
202
+ // own: the reply the user asked for keeps streaming.
203
+ expect(detach).not.toHaveBeenCalled();
204
+ finishRun();
205
+ await sent;
206
+ expect(agent.messages.map((m) => String(m.content))).toEqual([
207
+ "from t1",
208
+ "hello",
209
+ "reply",
210
+ ]);
211
+ });
212
+
213
+ it("keeps the messages of an agent that cannot connect, and sends on its thread", async () => {
214
+ // An agent without connect: a connect would only empty it.
215
+ const agent = new (class extends SeededAgent {
216
+ readonly runs: string[] = [];
217
+ override async runAgent(): Promise<RunAgentResult> {
218
+ this.runs.push(this.threadId);
219
+ return EMPTY_RESULT;
220
+ }
221
+ })();
222
+ agent.setMessages([text("a", "kept")]);
223
+ renderChat(agent as unknown as ThreadedAgent, "t1");
224
+
225
+ await act(async () => {
226
+ await chat!.submitMessage("hello");
227
+ });
228
+
229
+ expect(transcript()).toEqual(["kept", "hello"]);
230
+ expect(agent.runs).toEqual(["t1"]);
231
+ });
232
+ });
@@ -17,8 +17,10 @@ vi.mock("expo-file-system", () => ({
17
17
  EncodingType: { Base64: "base64" },
18
18
  }));
19
19
 
20
- // Mock @copilotkit/shared -- only the utils we use
21
- vi.mock("@copilotkit/shared", () => ({
20
+ // Mock @copilotkit/shared over the real module: core's attachment queue
21
+ // needs its other exports.
22
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
23
+ ...(await importOriginal<typeof import("@copilotkit/shared")>()),
22
24
  getModalityFromMimeType: (mimeType: string) => {
23
25
  if (mimeType.startsWith("image/")) return "image";
24
26
  if (mimeType.startsWith("audio/")) return "audio";
@@ -157,6 +159,7 @@ describe("useAttachments (React Native)", () => {
157
159
  expect(onUploadFailed).toHaveBeenCalledWith(
158
160
  expect.objectContaining({
159
161
  reason: "file-too-large",
162
+ file,
160
163
  }),
161
164
  );
162
165
  });
@@ -189,6 +192,7 @@ describe("useAttachments (React Native)", () => {
189
192
  expect(onUploadFailed).toHaveBeenCalledWith(
190
193
  expect.objectContaining({
191
194
  reason: "invalid-type",
195
+ file,
192
196
  }),
193
197
  );
194
198
  });
@@ -219,10 +223,31 @@ describe("useAttachments (React Native)", () => {
219
223
  expect(onUploadFailed).toHaveBeenCalledWith(
220
224
  expect.objectContaining({
221
225
  reason: "upload-failed",
226
+ file,
222
227
  }),
223
228
  );
224
229
  });
225
230
 
231
+ it("ignores files while attachments are disabled", async () => {
232
+ const { result } = renderHook(() =>
233
+ useAttachments({ config: { enabled: false } }),
234
+ );
235
+
236
+ await act(async () => {
237
+ await result.current.processFiles([
238
+ {
239
+ uri: "file:///tmp/photo.jpg",
240
+ name: "photo.jpg",
241
+ size: 1024,
242
+ mimeType: "image/jpeg",
243
+ },
244
+ ]);
245
+ });
246
+
247
+ expect(result.current.attachments).toEqual([]);
248
+ expect(mockReadAsStringAsync).not.toHaveBeenCalled();
249
+ });
250
+
226
251
  it("calls custom onUpload instead of reading file directly", async () => {
227
252
  const customUpload = vi.fn().mockResolvedValue({
228
253
  type: "url",