@copilotkit/react-native 1.57.4 → 1.58.0-canary.thread-id-propagation

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.
Files changed (48) hide show
  1. package/USAGE.md +116 -0
  2. package/dist/RenderToolContext-CBNKcJqz.cjs +126 -0
  3. package/dist/RenderToolContext-CBNKcJqz.cjs.map +1 -0
  4. package/dist/RenderToolContext-CszHyes6.mjs +75 -0
  5. package/dist/RenderToolContext-CszHyes6.mjs.map +1 -0
  6. package/dist/components/index.cjs +722 -0
  7. package/dist/components/index.cjs.map +1 -0
  8. package/dist/components/index.d.cts +203 -0
  9. package/dist/components/index.d.mts +203 -0
  10. package/dist/components/index.mjs +714 -0
  11. package/dist/components/index.mjs.map +1 -0
  12. package/dist/index.cjs +53 -38
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +102 -6
  15. package/dist/index.d.mts +100 -4
  16. package/dist/index.mjs +49 -3
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/polyfills/encoding.cjs +1 -1
  19. package/dist/polyfills/streams.cjs +1 -1
  20. package/package.json +24 -4
  21. package/src/CopilotKitProvider.tsx +2 -1
  22. package/src/__mocks__/react-native-streamdown.ts +16 -0
  23. package/src/__mocks__/react-native.ts +52 -0
  24. package/src/__tests__/headless-integration.test.tsx +16 -0
  25. package/src/components/CopilotChat.tsx +465 -0
  26. package/src/components/CopilotModal.tsx +210 -0
  27. package/src/components/Markdown.tsx +124 -0
  28. package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +418 -0
  29. package/src/components/__tests__/CopilotChat.test.tsx +390 -0
  30. package/src/components/__tests__/CopilotModal.test.tsx +257 -0
  31. package/src/components/__tests__/Markdown.test.tsx +106 -0
  32. package/src/components/index.ts +18 -0
  33. package/src/components/messages/AssistantMessage.tsx +73 -0
  34. package/src/components/messages/TypingIndicator.tsx +103 -0
  35. package/src/components/messages/UserMessage.tsx +68 -0
  36. package/src/components/messages/__tests__/messages-edge-cases.test.tsx +179 -0
  37. package/src/components/messages/__tests__/messages.test.tsx +189 -0
  38. package/src/components/messages/__tests__/utils.test.ts +39 -0
  39. package/src/components/messages/index.ts +8 -0
  40. package/src/components/messages/utils.ts +11 -0
  41. package/src/hooks/RenderToolContext.tsx +150 -0
  42. package/src/hooks/__tests__/RenderToolContext.test.tsx +264 -0
  43. package/src/hooks/__tests__/useRenderTool.test.tsx +334 -0
  44. package/src/hooks/index.ts +9 -0
  45. package/src/hooks/useRenderTool.ts +96 -0
  46. package/src/index.ts +10 -3
  47. package/tsdown.config.ts +9 -0
  48. package/vitest.config.mjs +10 -0
@@ -0,0 +1,418 @@
1
+ import React from "react";
2
+ import { render, fireEvent, act } from "@testing-library/react";
3
+ import { describe, it, expect, beforeEach, vi } from "vitest";
4
+
5
+ // ─── Hoisted state ─────────────────────────────────────────────────────────────
6
+
7
+ const hoisted = vi.hoisted(() => {
8
+ return {
9
+ mockAgent: {
10
+ messages: [] as any[],
11
+ isRunning: false,
12
+ addMessage: vi.fn(),
13
+ },
14
+ mockRunAgent: vi.fn().mockResolvedValue(undefined),
15
+ mockToolRegistry: vi.fn(() => new Map()),
16
+ mockExecutingToolCallIds: new Set<string>(),
17
+ };
18
+ });
19
+
20
+ // ─── Mocks ────────────────────────────────────────────────────────────────────
21
+
22
+ vi.mock("@copilotkit/react-core/v2/headless", () => ({
23
+ useAgent: vi.fn(() => ({ agent: hoisted.mockAgent })),
24
+ }));
25
+
26
+ vi.mock("@copilotkit/react-core/v2/context", () => ({
27
+ useCopilotKit: vi.fn(() => ({
28
+ copilotkit: { runAgent: hoisted.mockRunAgent },
29
+ executingToolCallIds: hoisted.mockExecutingToolCallIds,
30
+ })),
31
+ }));
32
+
33
+ vi.mock("../messages/AssistantMessage", () => ({
34
+ AssistantMessage: ({ content, isLoading }: any) => {
35
+ const React = require("react");
36
+ return React.createElement(
37
+ "div",
38
+ { "data-testid": "assistant-message" },
39
+ isLoading ? "Loading..." : content,
40
+ );
41
+ },
42
+ }));
43
+
44
+ vi.mock("../messages/UserMessage", () => ({
45
+ UserMessage: ({ content }: any) => {
46
+ const React = require("react");
47
+ return React.createElement(
48
+ "div",
49
+ { "data-testid": "user-message" },
50
+ content,
51
+ );
52
+ },
53
+ }));
54
+
55
+ vi.mock("../../hooks/RenderToolContext", () => ({
56
+ useRenderToolRegistry: (...args: any[]) => hoisted.mockToolRegistry(...args),
57
+ }));
58
+
59
+ // Mock react-native components with testable DOM elements
60
+ vi.mock("react-native", () => {
61
+ const React = require("react");
62
+ return {
63
+ FlatList: ({ data, renderItem, ListEmptyComponent, keyExtractor }: any) => {
64
+ if (!data || data.length === 0) {
65
+ return React.createElement(
66
+ "div",
67
+ { "data-testid": "flatlist" },
68
+ ListEmptyComponent,
69
+ );
70
+ }
71
+ return React.createElement(
72
+ "div",
73
+ { "data-testid": "flatlist" },
74
+ data.map((item: any, index: number) =>
75
+ React.createElement(
76
+ "div",
77
+ { key: keyExtractor?.(item, index) ?? index },
78
+ renderItem({ item, index }),
79
+ ),
80
+ ),
81
+ );
82
+ },
83
+ KeyboardAvoidingView: ({ children }: any) =>
84
+ React.createElement("div", { "data-testid": "keyboard-view" }, children),
85
+ Platform: { OS: "ios" },
86
+ Pressable: ({ children, onPress, ...props }: any) =>
87
+ React.createElement(
88
+ "button",
89
+ { onClick: onPress, "data-testid": "pressable", ...props },
90
+ children,
91
+ ),
92
+ StyleSheet: {
93
+ create: (styles: any) => styles,
94
+ hairlineWidth: 1,
95
+ },
96
+ Text: ({ children, ...props }: any) =>
97
+ React.createElement("span", props, children),
98
+ TextInput: ({ value, onChangeText, onSubmitEditing, ...props }: any) =>
99
+ React.createElement("input", {
100
+ value,
101
+ onChange: (e: any) => onChangeText?.(e.target.value),
102
+ onKeyDown: (e: any) => {
103
+ if (e.key === "Enter") onSubmitEditing?.();
104
+ },
105
+ "data-testid": "text-input",
106
+ ...props,
107
+ }),
108
+ TouchableOpacity: ({
109
+ children,
110
+ onPress,
111
+ disabled,
112
+ testID,
113
+ ...props
114
+ }: any) =>
115
+ React.createElement(
116
+ "button",
117
+ {
118
+ onClick: onPress,
119
+ disabled,
120
+ ...(testID ? { "data-testid": testID } : {}),
121
+ ...props,
122
+ },
123
+ children,
124
+ ),
125
+ View: ({ children, ...props }: any) =>
126
+ React.createElement("div", props, children),
127
+ };
128
+ });
129
+
130
+ import { CopilotChat } from "../CopilotChat";
131
+
132
+ // ─── Tests ────────────────────────────────────────────────────────────────────
133
+
134
+ describe("CopilotChat edge cases", () => {
135
+ beforeEach(() => {
136
+ vi.clearAllMocks();
137
+ hoisted.mockAgent.messages = [];
138
+ hoisted.mockAgent.isRunning = false;
139
+ hoisted.mockAgent.addMessage = vi.fn();
140
+ hoisted.mockRunAgent.mockResolvedValue(undefined);
141
+ hoisted.mockToolRegistry.mockReturnValue(new Map());
142
+ hoisted.mockExecutingToolCallIds.clear();
143
+ });
144
+
145
+ describe("disableKeyboardAvoiding", () => {
146
+ it("wraps content in KeyboardAvoidingView by default", () => {
147
+ const { getByTestId } = render(<CopilotChat />);
148
+ expect(getByTestId("keyboard-view")).toBeTruthy();
149
+ });
150
+
151
+ it("skips KeyboardAvoidingView when disableKeyboardAvoiding is true", () => {
152
+ const { queryByTestId } = render(<CopilotChat disableKeyboardAvoiding />);
153
+ expect(queryByTestId("keyboard-view")).toBeNull();
154
+ });
155
+ });
156
+
157
+ describe("FlatListComponent", () => {
158
+ it("uses custom FlatListComponent when provided", () => {
159
+ const CustomFlatList = ({
160
+ data,
161
+ renderItem,
162
+ ListEmptyComponent,
163
+ keyExtractor,
164
+ }: any) => {
165
+ return React.createElement(
166
+ "div",
167
+ { "data-testid": "custom-flatlist" },
168
+ ListEmptyComponent,
169
+ );
170
+ };
171
+
172
+ const { getByTestId, queryByTestId } = render(
173
+ <CopilotChat FlatListComponent={CustomFlatList} />,
174
+ );
175
+
176
+ expect(getByTestId("custom-flatlist")).toBeTruthy();
177
+ // The default FlatList should not be rendered
178
+ expect(queryByTestId("flatlist")).toBeNull();
179
+ });
180
+ });
181
+
182
+ describe("malformed tool call arguments", () => {
183
+ it("handles invalid JSON in tool arguments gracefully", () => {
184
+ const mockRenderer = (props: any) => {
185
+ return React.createElement(
186
+ "div",
187
+ { "data-testid": "tool-render" },
188
+ `args: ${JSON.stringify(props.args)}`,
189
+ );
190
+ };
191
+
192
+ const toolMap = new Map([["brokenTool", mockRenderer]]);
193
+ hoisted.mockToolRegistry.mockReturnValue(toolMap);
194
+
195
+ hoisted.mockAgent.messages = [
196
+ {
197
+ id: "1",
198
+ role: "assistant",
199
+ content: "",
200
+ toolCalls: [
201
+ {
202
+ id: "tc-1",
203
+ type: "function" as const,
204
+ function: {
205
+ name: "brokenTool",
206
+ arguments: "this is not valid JSON{{{",
207
+ },
208
+ },
209
+ ],
210
+ },
211
+ ];
212
+
213
+ // Suppress the expected console.warn
214
+ const spy = vi.spyOn(console, "warn").mockImplementation(() => {});
215
+
216
+ const { getByTestId } = render(<CopilotChat />);
217
+
218
+ // Should render with empty args instead of crashing
219
+ expect(getByTestId("tool-render")).toBeTruthy();
220
+ expect(getByTestId("tool-render").textContent).toBe("args: {}");
221
+
222
+ spy.mockRestore();
223
+ });
224
+
225
+ it("handles empty string arguments in tool calls", () => {
226
+ const mockRenderer = (props: any) => {
227
+ return React.createElement(
228
+ "div",
229
+ { "data-testid": "tool-render" },
230
+ `args: ${JSON.stringify(props.args)}`,
231
+ );
232
+ };
233
+
234
+ const toolMap = new Map([["emptyArgsTool", mockRenderer]]);
235
+ hoisted.mockToolRegistry.mockReturnValue(toolMap);
236
+
237
+ hoisted.mockAgent.messages = [
238
+ {
239
+ id: "1",
240
+ role: "assistant",
241
+ content: "",
242
+ toolCalls: [
243
+ {
244
+ id: "tc-1",
245
+ type: "function" as const,
246
+ function: {
247
+ name: "emptyArgsTool",
248
+ arguments: "",
249
+ },
250
+ },
251
+ ],
252
+ },
253
+ ];
254
+
255
+ const { getByTestId } = render(<CopilotChat />);
256
+
257
+ expect(getByTestId("tool-render")).toBeTruthy();
258
+ expect(getByTestId("tool-render").textContent).toBe("args: {}");
259
+ });
260
+ });
261
+
262
+ describe("tool call status", () => {
263
+ it("passes 'executing' status when tool call is in executingToolCallIds", () => {
264
+ const receivedProps: any[] = [];
265
+ const mockRenderer = (props: any) => {
266
+ receivedProps.push(props);
267
+ return React.createElement(
268
+ "div",
269
+ { "data-testid": "tool-render" },
270
+ `status: ${props.status}`,
271
+ );
272
+ };
273
+
274
+ const toolMap = new Map([["myTool", mockRenderer]]);
275
+ hoisted.mockToolRegistry.mockReturnValue(toolMap);
276
+
277
+ // Add executing tool call ID to the shared set
278
+ hoisted.mockExecutingToolCallIds.add("tc-1");
279
+
280
+ hoisted.mockAgent.messages = [
281
+ {
282
+ id: "1",
283
+ role: "assistant",
284
+ content: "",
285
+ toolCalls: [
286
+ {
287
+ id: "tc-1",
288
+ type: "function" as const,
289
+ function: { name: "myTool", arguments: '{"key":"val"}' },
290
+ },
291
+ ],
292
+ },
293
+ ];
294
+
295
+ const { getByTestId } = render(<CopilotChat />);
296
+
297
+ expect(getByTestId("tool-render").textContent).toBe("status: executing");
298
+ expect(receivedProps[0].status).toBe("executing");
299
+ });
300
+ });
301
+
302
+ describe("message list building", () => {
303
+ it("handles assistant messages with empty content and tool calls", () => {
304
+ hoisted.mockAgent.messages = [
305
+ {
306
+ id: "1",
307
+ role: "assistant",
308
+ content: "",
309
+ toolCalls: [
310
+ {
311
+ id: "tc-1",
312
+ type: "function" as const,
313
+ function: { name: "unknownTool", arguments: "{}" },
314
+ },
315
+ ],
316
+ },
317
+ ];
318
+
319
+ const { getByText, queryAllByTestId } = render(<CopilotChat />);
320
+
321
+ // Should show tool call indicator, not an empty assistant message
322
+ expect(getByText("Called: unknownTool")).toBeTruthy();
323
+ expect(queryAllByTestId("assistant-message")).toHaveLength(0);
324
+ });
325
+
326
+ it("handles assistant messages with both content and tool calls", () => {
327
+ hoisted.mockAgent.messages = [
328
+ {
329
+ id: "1",
330
+ role: "assistant",
331
+ content: "Let me check that for you",
332
+ toolCalls: [
333
+ {
334
+ id: "tc-1",
335
+ type: "function" as const,
336
+ function: { name: "searchTool", arguments: "{}" },
337
+ },
338
+ ],
339
+ },
340
+ ];
341
+
342
+ const { getByText, getByTestId } = render(<CopilotChat />);
343
+
344
+ // Should show both content and tool call indicator
345
+ expect(getByTestId("assistant-message").textContent).toBe(
346
+ "Let me check that for you",
347
+ );
348
+ expect(getByText("Called: searchTool")).toBeTruthy();
349
+ });
350
+
351
+ it("shows loading indicator when agent is running and last message is from user", () => {
352
+ hoisted.mockAgent.messages = [
353
+ { id: "1", role: "user", content: "Hello" },
354
+ ];
355
+ hoisted.mockAgent.isRunning = true;
356
+
357
+ const { getAllByTestId } = render(<CopilotChat />);
358
+
359
+ // Should have user message + loading assistant message
360
+ const userMessages = getAllByTestId("user-message");
361
+ const assistantMessages = getAllByTestId("assistant-message");
362
+ expect(userMessages).toHaveLength(1);
363
+ expect(assistantMessages).toHaveLength(1);
364
+ expect(assistantMessages[0].textContent).toBe("Loading...");
365
+ });
366
+
367
+ it("does not add extra loading indicator when last item is already an assistant message", () => {
368
+ hoisted.mockAgent.messages = [
369
+ { id: "1", role: "user", content: "Hello" },
370
+ { id: "2", role: "assistant", content: "I'm thinking..." },
371
+ ];
372
+ hoisted.mockAgent.isRunning = true;
373
+
374
+ const { getAllByTestId } = render(<CopilotChat />);
375
+
376
+ // Should NOT add an extra loading indicator since last message is assistant
377
+ const assistantMessages = getAllByTestId("assistant-message");
378
+ expect(assistantMessages).toHaveLength(1);
379
+ });
380
+ });
381
+
382
+ describe("empty message handling", () => {
383
+ it("does not send a whitespace-only message", async () => {
384
+ const { getByTestId } = render(<CopilotChat />);
385
+
386
+ const input = getByTestId("text-input");
387
+ const sendBtn = getByTestId("send-button");
388
+
389
+ await act(async () => {
390
+ fireEvent.change(input, { target: { value: " " } });
391
+ });
392
+
393
+ // Button should still be disabled for whitespace-only input
394
+ expect(sendBtn).toHaveProperty("disabled", true);
395
+ });
396
+ });
397
+
398
+ describe("suggestion pill interaction", () => {
399
+ it("sends a message when a suggestion pill is pressed", async () => {
400
+ const suggestions = ["Tell me a joke"];
401
+ const { getByText } = render(
402
+ <CopilotChat initialMessages={suggestions} />,
403
+ );
404
+
405
+ await act(async () => {
406
+ fireEvent.click(getByText("Tell me a joke"));
407
+ });
408
+
409
+ expect(hoisted.mockAgent.addMessage).toHaveBeenCalledWith(
410
+ expect.objectContaining({
411
+ role: "user",
412
+ content: "Tell me a joke",
413
+ }),
414
+ );
415
+ expect(hoisted.mockRunAgent).toHaveBeenCalled();
416
+ });
417
+ });
418
+ });