@copilotkit/react-native 2.0.0-rc.4 → 2.0.0-rc.40

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 (111) hide show
  1. package/README.md +334 -2
  2. package/USAGE.md +382 -21
  3. package/dist/CopilotKitProvider-Cbfrm_7u.d.mts +65 -0
  4. package/dist/{CopilotKitProvider-Byw3cqe2.cjs → CopilotKitProvider-CvJYytjn.cjs} +56 -42
  5. package/dist/CopilotKitProvider-CvJYytjn.cjs.map +1 -0
  6. package/dist/CopilotKitProvider-Dv3ISMKf.d.cts +65 -0
  7. package/dist/{CopilotKitProvider-CE4bc6CP.mjs → CopilotKitProvider-oTdmylSY.mjs} +55 -42
  8. package/dist/CopilotKitProvider-oTdmylSY.mjs.map +1 -0
  9. package/dist/{Markdown-C_9Re36O.cjs → Markdown-DLopAh5W.cjs} +10 -10
  10. package/dist/Markdown-DLopAh5W.cjs.map +1 -0
  11. package/dist/{Markdown-JsYh7oSA.d.mts → Markdown-Du-b_Qpr.d.mts} +3 -3
  12. package/dist/{Markdown-1ips7myr.d.cts → Markdown-UXZdDjzs.d.cts} +3 -3
  13. package/dist/{Markdown-C6AsLHmd.mjs → Markdown-VxtPJ_yh.mjs} +4 -4
  14. package/dist/Markdown-VxtPJ_yh.mjs.map +1 -0
  15. package/dist/{MarkdownRendererContext-CAnuohIS.mjs → MarkdownRendererContext-EobUsERg.mjs} +1 -1
  16. package/dist/{MarkdownRendererContext-CAnuohIS.mjs.map → MarkdownRendererContext-EobUsERg.mjs.map} +1 -1
  17. package/dist/MarkdownRendererContext-cDEHvbw9.cjs +40 -0
  18. package/dist/{MarkdownRendererContext-BRNe808d.cjs.map → MarkdownRendererContext-cDEHvbw9.cjs.map} +1 -1
  19. package/dist/chunk-C0xms8kb.cjs +34 -0
  20. package/dist/components/index.cjs +78 -175
  21. package/dist/components/index.cjs.map +1 -1
  22. package/dist/components/index.d.cts +2 -2
  23. package/dist/components/index.d.mts +2 -2
  24. package/dist/components/index.mjs +76 -174
  25. package/dist/components/index.mjs.map +1 -1
  26. package/dist/generative-ui/index.cjs +612 -0
  27. package/dist/generative-ui/index.cjs.map +1 -0
  28. package/dist/generative-ui/index.d.cts +341 -0
  29. package/dist/generative-ui/index.d.mts +341 -0
  30. package/dist/generative-ui/index.mjs +549 -0
  31. package/dist/generative-ui/index.mjs.map +1 -0
  32. package/dist/headless.cjs +2 -2
  33. package/dist/headless.d.cts +2 -2
  34. package/dist/headless.d.mts +2 -2
  35. package/dist/headless.mjs +1 -1
  36. package/dist/index.cjs +131 -162
  37. package/dist/index.cjs.map +1 -1
  38. package/dist/index.d.cts +36 -18
  39. package/dist/index.d.mts +36 -18
  40. package/dist/index.mjs +130 -161
  41. package/dist/index.mjs.map +1 -1
  42. package/dist/polyfills/encoding.cjs +115 -5
  43. package/dist/polyfills/encoding.cjs.map +1 -1
  44. package/dist/polyfills/encoding.d.cts +31 -1
  45. package/dist/polyfills/encoding.d.mts +31 -1
  46. package/dist/polyfills/encoding.mjs +113 -6
  47. package/dist/polyfills/encoding.mjs.map +1 -1
  48. package/dist/polyfills/streams.cjs +1 -1
  49. package/dist/polyfills.cjs +218 -2
  50. package/dist/polyfills.cjs.map +1 -1
  51. package/dist/polyfills.mjs +217 -1
  52. package/dist/polyfills.mjs.map +1 -1
  53. package/package.json +51 -21
  54. package/project.json +6 -1
  55. package/scripts/__tests__/verify-polyfill-barrel.test.mjs +150 -0
  56. package/scripts/verify-polyfill-barrel.mjs +158 -11
  57. package/src/CopilotChat.tsx +114 -93
  58. package/src/CopilotKitProvider.tsx +87 -130
  59. package/src/CopilotPopup.tsx +2 -2
  60. package/src/CopilotSidebar.tsx +7 -5
  61. package/src/__mocks__/react-native.ts +31 -0
  62. package/src/__mocks__/test-copilotkit.tsx +9 -3
  63. package/src/__tests__/attachments-integration.test.tsx +15 -2
  64. package/src/__tests__/copilot-chat-agentid.test.tsx +15 -2
  65. package/src/__tests__/copilot-chat-attachments.test.tsx +15 -2
  66. package/src/__tests__/copilot-chat-configuration.test.tsx +82 -0
  67. package/src/__tests__/copilot-chat-threads.test.tsx +232 -0
  68. package/src/__tests__/copilot-popup.test.tsx +15 -2
  69. package/src/__tests__/copilot-sidebar.test.tsx +15 -2
  70. package/src/__tests__/copilotkit-provider.test.tsx +68 -73
  71. package/src/__tests__/generative-ui-harness.tsx +243 -0
  72. package/src/__tests__/generative-ui-provider-props.test-d.tsx +106 -0
  73. package/src/__tests__/generative-ui-rn-mock.tsx +54 -0
  74. package/src/__tests__/generative-ui-wiring.test.tsx +720 -0
  75. package/src/__tests__/generative-ui.test.tsx +1000 -0
  76. package/src/__tests__/headless-entry-surface.test.ts +979 -60
  77. package/src/__tests__/headless-integration.test.tsx +11 -1
  78. package/src/__tests__/use-attachments.test.ts +27 -2
  79. package/src/components/CopilotChat.tsx +106 -233
  80. package/src/components/CopilotModal.tsx +1 -1
  81. package/src/components/Markdown.tsx +4 -4
  82. package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +5 -1
  83. package/src/components/__tests__/CopilotChat.test.tsx +12 -4
  84. package/src/components/__tests__/CopilotChatInterrupt.test.tsx +208 -0
  85. package/src/components/__tests__/Markdown.code-alias.test.tsx +1 -1
  86. package/src/components/index.ts +6 -0
  87. package/src/components/messages/AssistantMessage.tsx +3 -3
  88. package/src/components/messages/TypingIndicator.tsx +4 -4
  89. package/src/generative-ui/GenerativeUIActivity.tsx +235 -0
  90. package/src/generative-ui/GenerativeUIProvider.tsx +171 -0
  91. package/src/generative-ui/GenerativeUISurface.tsx +303 -0
  92. package/src/generative-ui/host.tsx +138 -0
  93. package/src/generative-ui/index.ts +93 -0
  94. package/src/generative-ui/internal.ts +55 -0
  95. package/src/hooks/use-attachments.ts +95 -139
  96. package/src/index.ts +8 -3
  97. package/src/polyfills/__tests__/encoding-utf8.test.ts +112 -0
  98. package/src/polyfills/encoding.ts +160 -4
  99. package/src/types.d.ts +0 -13
  100. package/tsdown.config.ts +1 -0
  101. package/dist/CopilotKitProvider-BWjzCdHN.d.mts +0 -121
  102. package/dist/CopilotKitProvider-Btm10msB.d.cts +0 -121
  103. package/dist/CopilotKitProvider-Byw3cqe2.cjs.map +0 -1
  104. package/dist/CopilotKitProvider-CE4bc6CP.mjs.map +0 -1
  105. package/dist/Markdown-C6AsLHmd.mjs.map +0 -1
  106. package/dist/Markdown-C_9Re36O.cjs.map +0 -1
  107. package/dist/MarkdownRendererContext-BRNe808d.cjs +0 -72
  108. package/dist/streaming-fetch-Bm91EsRc.cjs +0 -225
  109. package/dist/streaming-fetch-Bm91EsRc.cjs.map +0 -1
  110. package/dist/streaming-fetch-Dm1oN4f2.mjs +0 -219
  111. package/dist/streaming-fetch-Dm1oN4f2.mjs.map +0 -1
@@ -23,17 +23,20 @@ function createMockCore() {
23
23
  capturedSubscriber = subscriber;
24
24
  return { unsubscribe: unsubscribeMock };
25
25
  }),
26
- setRuntimeUrl: vi.fn(),
27
- setRuntimeTransport: vi.fn(),
28
- setHeaders: vi.fn(),
29
- setCredentials: vi.fn(),
30
- setProperties: vi.fn(),
31
- setMessageFilter: vi.fn(),
32
- setDebug: vi.fn(),
33
- setDefaultThrottleMs: vi.fn(),
26
+ ɵupdateConfig: vi.fn(),
27
+ ɵruntimeInfo: { status: "disconnected" },
28
+ ɵsubscribeToRuntimeInfo: vi.fn(() => () => {}),
29
+ setErrorHandler: vi.fn(),
30
+ connect: vi.fn(),
31
+ dispose: vi.fn(),
34
32
  };
35
33
  }
36
34
 
35
+ /** The last config patch the provider pushed to the core. */
36
+ function lastPatch() {
37
+ return mockCoreInstance.ɵupdateConfig.mock.calls.at(-1)?.[0];
38
+ }
39
+
37
40
  let mockCoreInstance: ReturnType<typeof createMockCore>;
38
41
 
39
42
  /** Keeps the final turn only — the shape #1482 asks for. */
@@ -41,14 +44,16 @@ const keepLastTurn = (messages: any[]) => messages.slice(-1);
41
44
  /** A second, distinguishable filter, for asserting a swap took effect. */
42
45
  const keepLastTwo = (messages: any[]) => messages.slice(-2);
43
46
 
44
- vi.mock("@copilotkit/react-core/headless", () => {
47
+ vi.mock("@copilotkit/react-core/headless", async (importOriginal) => {
48
+ const actual =
49
+ await importOriginal<typeof import("@copilotkit/react-core/headless")>();
45
50
  // Regular function (not arrow) so it's new-able
46
51
  function CopilotKitCoreReact(this: any, ...args: any[]) {
47
52
  hoisted.MockCoreConstructor(...args);
48
53
  const instance = hoisted.MockCoreConstructor.mock.results.at(-1)?.value;
49
54
  if (instance) Object.assign(this, instance);
50
55
  }
51
- return { CopilotKitCoreReact };
56
+ return { ...actual, CopilotKitCoreReact };
52
57
  });
53
58
 
54
59
  vi.mock("@copilotkit/react-core/context", () => {
@@ -70,7 +75,8 @@ vi.mock("@copilotkit/react-core/context", () => {
70
75
  };
71
76
  });
72
77
 
73
- vi.mock("@copilotkit/shared", () => ({
78
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
79
+ ...(await importOriginal<typeof import("@copilotkit/shared")>()),
74
80
  createLicenseContextValue: () => ({
75
81
  status: null,
76
82
  license: null,
@@ -197,9 +203,7 @@ describe("CopilotKitProvider (React Native)", () => {
197
203
  </CopilotKitProvider>,
198
204
  );
199
205
 
200
- expect(mockCoreInstance.setRuntimeUrl).toHaveBeenCalledWith(
201
- "https://api.test/v2",
202
- );
206
+ expect(lastPatch()?.runtimeUrl).toBe("https://api.test/v2");
203
207
  });
204
208
 
205
209
  it("calls setHeaders when headers content changes", () => {
@@ -209,7 +213,7 @@ describe("CopilotKitProvider (React Native)", () => {
209
213
  </CopilotKitProvider>,
210
214
  );
211
215
 
212
- mockCoreInstance.setHeaders.mockClear();
216
+ mockCoreInstance.ɵupdateConfig.mockClear();
213
217
 
214
218
  rerender(
215
219
  <CopilotKitProvider runtimeUrl="https://api.test" headers={{ b: "2" }}>
@@ -217,7 +221,7 @@ describe("CopilotKitProvider (React Native)", () => {
217
221
  </CopilotKitProvider>,
218
222
  );
219
223
 
220
- expect(mockCoreInstance.setHeaders).toHaveBeenCalledWith({ b: "2" });
224
+ expect(lastPatch()?.headers).toEqual({ b: "2" });
221
225
  });
222
226
 
223
227
  it("does not re-fire setHeaders when content is identical (JSON-stabilized)", () => {
@@ -227,7 +231,7 @@ describe("CopilotKitProvider (React Native)", () => {
227
231
  </CopilotKitProvider>,
228
232
  );
229
233
 
230
- mockCoreInstance.setHeaders.mockClear();
234
+ mockCoreInstance.ɵupdateConfig.mockClear();
231
235
 
232
236
  // New object reference but same content
233
237
  rerender(
@@ -236,7 +240,7 @@ describe("CopilotKitProvider (React Native)", () => {
236
240
  </CopilotKitProvider>,
237
241
  );
238
242
 
239
- expect(mockCoreInstance.setHeaders).not.toHaveBeenCalled();
243
+ expect(mockCoreInstance.ɵupdateConfig).not.toHaveBeenCalled();
240
244
  });
241
245
 
242
246
  // #1482: parity with the React, Vue and Angular providers. The filter's own
@@ -267,7 +271,7 @@ describe("CopilotKitProvider (React Native)", () => {
267
271
  </CopilotKitProvider>,
268
272
  );
269
273
 
270
- mockCoreInstance.setMessageFilter.mockClear();
274
+ mockCoreInstance.ɵupdateConfig.mockClear();
271
275
 
272
276
  rerender(
273
277
  <CopilotKitProvider
@@ -278,9 +282,7 @@ describe("CopilotKitProvider (React Native)", () => {
278
282
  </CopilotKitProvider>,
279
283
  );
280
284
 
281
- expect(mockCoreInstance.setMessageFilter).toHaveBeenCalledWith(
282
- keepLastTwo,
283
- );
285
+ expect(lastPatch()?.messageFilter).toBe(keepLastTwo);
284
286
  });
285
287
 
286
288
  it("clears the filter when the prop goes away", () => {
@@ -293,7 +295,7 @@ describe("CopilotKitProvider (React Native)", () => {
293
295
  </CopilotKitProvider>,
294
296
  );
295
297
 
296
- mockCoreInstance.setMessageFilter.mockClear();
298
+ mockCoreInstance.ɵupdateConfig.mockClear();
297
299
 
298
300
  rerender(
299
301
  <CopilotKitProvider runtimeUrl="https://api.test">
@@ -301,7 +303,9 @@ describe("CopilotKitProvider (React Native)", () => {
301
303
  </CopilotKitProvider>,
302
304
  );
303
305
 
304
- expect(mockCoreInstance.setMessageFilter).toHaveBeenCalledWith(undefined);
306
+ const patch = lastPatch();
307
+ expect(patch && "messageFilter" in patch).toBe(true);
308
+ expect(patch?.messageFilter).toBeUndefined();
305
309
  });
306
310
  });
307
311
 
@@ -403,7 +407,9 @@ describe("CopilotKitProvider (React Native)", () => {
403
407
  // ── Error handling ────────────────────────────────────────────────────
404
408
 
405
409
  describe("error handling", () => {
406
- it("forwards errors to onError prop when provided", () => {
410
+ // Core calls the handler, and logs when there is none (core tests cover
411
+ // that). The provider's job is handing the handler over.
412
+ it("passes onError to the core at construction", () => {
407
413
  const onError = vi.fn();
408
414
  render(
409
415
  <CopilotKitProvider runtimeUrl="https://api.test" onError={onError}>
@@ -411,47 +417,12 @@ describe("CopilotKitProvider (React Native)", () => {
411
417
  </CopilotKitProvider>,
412
418
  );
413
419
 
414
- const testError = new Error("test error");
415
- act(() => {
416
- capturedSubscriber.onError({
417
- error: testError,
418
- code: "RUNTIME_ERROR",
419
- context: { detail: "info" },
420
- });
421
- });
422
-
423
- expect(onError).toHaveBeenCalledWith({
424
- error: testError,
425
- code: "RUNTIME_ERROR",
426
- context: { detail: "info" },
427
- });
428
- });
429
-
430
- it("logs to console.error when onError is not provided", () => {
431
- const spy = vi.spyOn(console, "error").mockImplementation(() => {});
432
- render(
433
- <CopilotKitProvider runtimeUrl="https://api.test">
434
- <div />
435
- </CopilotKitProvider>,
436
- );
437
-
438
- act(() => {
439
- capturedSubscriber.onError({
440
- error: new Error("fail"),
441
- code: "AGENT_ERROR",
442
- context: {},
443
- });
444
- });
445
-
446
- expect(spy).toHaveBeenCalledWith(
447
- expect.stringContaining("AGENT_ERROR"),
448
- expect.any(Error),
449
- expect.any(Object),
420
+ expect(hoisted.MockCoreConstructor).toHaveBeenCalledWith(
421
+ expect.objectContaining({ onError }),
450
422
  );
451
- spy.mockRestore();
452
423
  });
453
424
 
454
- it("picks up new onError callback without resubscribing (ref pattern)", () => {
425
+ it("hands a new onError to the core", () => {
455
426
  const onError1 = vi.fn();
456
427
  const onError2 = vi.fn();
457
428
 
@@ -467,16 +438,9 @@ describe("CopilotKitProvider (React Native)", () => {
467
438
  </CopilotKitProvider>,
468
439
  );
469
440
 
470
- act(() => {
471
- capturedSubscriber.onError({
472
- error: new Error("test"),
473
- code: "RUNTIME_ERROR",
474
- context: {},
475
- });
476
- });
477
-
478
- expect(onError1).not.toHaveBeenCalled();
479
- expect(onError2).toHaveBeenCalled();
441
+ expect(mockCoreInstance.setErrorHandler).toHaveBeenLastCalledWith(
442
+ onError2,
443
+ );
480
444
  });
481
445
  });
482
446
 
@@ -494,5 +458,36 @@ describe("CopilotKitProvider (React Native)", () => {
494
458
 
495
459
  expect(unsubscribeMock).toHaveBeenCalled();
496
460
  });
461
+
462
+ it("disposes the core after unmount", async () => {
463
+ const { unmount } = render(
464
+ <CopilotKitProvider runtimeUrl="https://api.test">
465
+ <div />
466
+ </CopilotKitProvider>,
467
+ );
468
+
469
+ unmount();
470
+
471
+ await vi.waitFor(() =>
472
+ expect(mockCoreInstance.dispose).toHaveBeenCalledTimes(1),
473
+ );
474
+ });
475
+ });
476
+
477
+ // ── Runtime connection ──────────────────────────────────────────────
478
+
479
+ describe("runtime connection", () => {
480
+ it("defers /info to an effect", () => {
481
+ render(
482
+ <CopilotKitProvider runtimeUrl="https://api.test">
483
+ <div />
484
+ </CopilotKitProvider>,
485
+ );
486
+
487
+ expect(hoisted.MockCoreConstructor).toHaveBeenCalledWith(
488
+ expect.objectContaining({ deferInitialConnection: true }),
489
+ );
490
+ expect(mockCoreInstance.connect).toHaveBeenCalled();
491
+ });
497
492
  });
498
493
  });
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Shared fixtures of the generative UI tests: the catalog, activity message
3
+ * builders, and a harness that mounts a real CopilotKit core with the React
4
+ * Native provider.
5
+ *
6
+ * A test file that imports this must mock react-native first:
7
+ *
8
+ * ```ts
9
+ * vi.mock("react-native", async () =>
10
+ * (await import("./generative-ui-rn-mock")).createReactNativeMock(),
11
+ * );
12
+ * ```
13
+ *
14
+ * The harness covers the three wiring paths a happy-path mount leaves out:
15
+ * - `messages` seeds the agent's messages before mount, so the provider's
16
+ * own ingest of `agent.messages` runs on `startRun` (the path a real app
17
+ * takes), malformed content included;
18
+ * - `strict` mounts under `<React.StrictMode>`, which runs every effect,
19
+ * its cleanup and the effect again;
20
+ * - `inProduction` runs a callback with `NODE_ENV=production`.
21
+ */
22
+ import React, { StrictMode, useState } from "react";
23
+ import type { ReactNode } from "react";
24
+ import { act } from "@testing-library/react";
25
+ import { vi } from "vitest";
26
+ import { z } from "zod";
27
+ import type { AbstractAgent, RunAgentParameters } from "@ag-ui/client";
28
+ import { GENERATIVE_UI_ACTIVITY_TYPE } from "@copilotkit/shared";
29
+ import type {
30
+ A2UIComponentNode,
31
+ A2UIOperation,
32
+ GenerativeUIRejectedOperation,
33
+ GenerativeUISurfaceContent,
34
+ } from "@copilotkit/shared";
35
+ import { useCopilotKit } from "@copilotkit/react-core/context";
36
+ import { SeededAgent, TestCopilotKit } from "../__mocks__/test-copilotkit";
37
+ import {
38
+ GenerativeUIProvider,
39
+ createGenerativeUI,
40
+ useGenerativeUIAccessibility,
41
+ } from "../generative-ui";
42
+ import type {
43
+ GenerativeUIComponentProps,
44
+ GenerativeUIProviderProps,
45
+ } from "../generative-ui";
46
+
47
+ export function Column({ children }: { children?: ReactNode }) {
48
+ return <div data-testid="column">{children}</div>;
49
+ }
50
+ export function Balance({
51
+ label,
52
+ amount,
53
+ }: GenerativeUIComponentProps<typeof ui, "Balance">) {
54
+ return (
55
+ <div data-testid={`balance-${label}`}>
56
+ {label}: {amount}
57
+ </div>
58
+ );
59
+ }
60
+ function Boom(): ReactNode {
61
+ throw new Error("kaboom");
62
+ }
63
+ /** Throws until `flaky.ok` is set, so a Retry can recover it. */
64
+ export const flaky = { ok: false };
65
+ function Flaky(): ReactNode {
66
+ if (!flaky.ok) throw new Error("not yet");
67
+ return <div data-testid="flaky-ok">recovered</div>;
68
+ }
69
+ /** Applies the accessibility envelope to its own root view. */
70
+ function SelfPanel(): ReactNode {
71
+ const aria = useGenerativeUIAccessibility();
72
+ return (
73
+ <div data-testid="self-panel" data-aria={JSON.stringify(aria)}>
74
+ panel
75
+ </div>
76
+ );
77
+ }
78
+
79
+ export const ui = createGenerativeUI({
80
+ id: "bank",
81
+ components: {
82
+ Column: {
83
+ description: "Stacks children vertically",
84
+ component: Column,
85
+ slots: { children: "multiple" },
86
+ },
87
+ Balance: {
88
+ description: "An account balance",
89
+ component: Balance,
90
+ props: z.object({ label: z.string(), amount: z.number() }),
91
+ },
92
+ Boom: { description: "Always throws", component: Boom },
93
+ Flaky: { description: "Throws until it is fixed", component: Flaky },
94
+ SelfPanel: {
95
+ description: "Applies its own accessibility",
96
+ component: SelfPanel,
97
+ accessibility: "self",
98
+ },
99
+ },
100
+ });
101
+
102
+ export const S = "home-surface";
103
+ export const create: A2UIOperation = {
104
+ version: "1.0",
105
+ createSurface: { surfaceId: S, catalogId: "bank" },
106
+ };
107
+ export const nodes = (...components: A2UIComponentNode[]): A2UIOperation => ({
108
+ version: "1.0",
109
+ updateComponents: { surfaceId: S, components },
110
+ });
111
+ export const activity = (
112
+ operations: A2UIOperation[],
113
+ status: GenerativeUISurfaceContent["status"] = "streaming",
114
+ target = "chat",
115
+ ) => ({
116
+ id: `activity-${operations.length}-${status}`,
117
+ role: "activity",
118
+ activityType: GENERATIVE_UI_ACTIVITY_TYPE,
119
+ content: {
120
+ surfaceId: S,
121
+ target,
122
+ catalogId: "bank",
123
+ operations,
124
+ status,
125
+ rejected: [] as GenerativeUIRejectedOperation[],
126
+ } satisfies GenerativeUISurfaceContent,
127
+ });
128
+
129
+ /** A list with a hole at every index that `entries` does not set. */
130
+ export function sparse(...entries: [number, unknown][]): unknown[] {
131
+ const list: unknown[] = [];
132
+ for (const [index, value] of entries) list[index] = value;
133
+ return list;
134
+ }
135
+
136
+ /**
137
+ * An agent that core can run: `runAgent` records its input and resolves at
138
+ * once, so `copilotkit.runAgent` fires the run-start notification that the
139
+ * provider ingests the agent's messages on.
140
+ */
141
+ export class RunnableAgent extends SeededAgent {
142
+ inputs: RunAgentParameters[] = [];
143
+ async runAgent(parameters?: RunAgentParameters) {
144
+ this.inputs.push(parameters ?? {});
145
+ return { result: undefined, newMessages: [] };
146
+ }
147
+ }
148
+
149
+ export type CopilotKitCore = ReturnType<typeof useCopilotKit>["copilotkit"];
150
+
151
+ /** Publishes the CopilotKit core to the test. */
152
+ function CoreProbe({
153
+ coreRef,
154
+ }: {
155
+ coreRef?: React.MutableRefObject<CopilotKitCore | null>;
156
+ }) {
157
+ const { copilotkit } = useCopilotKit();
158
+ if (coreRef) coreRef.current = copilotkit;
159
+ return null;
160
+ }
161
+
162
+ export interface HarnessProps {
163
+ children: (agent: AbstractAgent) => ReactNode;
164
+ agentRef: React.MutableRefObject<AbstractAgent | null>;
165
+ providerProps?: Partial<GenerativeUIProviderProps>;
166
+ /**
167
+ * The agent's messages before mount. The provider ingests them itself at
168
+ * the next run start (`startRun`), and on every change after that.
169
+ */
170
+ messages?: Array<Record<string, unknown>>;
171
+ /** Mounts the tree under `<React.StrictMode>`. */
172
+ strict?: boolean;
173
+ /** Receives the CopilotKit core. */
174
+ coreRef?: React.MutableRefObject<CopilotKitCore | null>;
175
+ }
176
+
177
+ /** Renders `children` inside a real CopilotKit core and the RN provider. */
178
+ export function Harness({
179
+ children,
180
+ agentRef,
181
+ providerProps,
182
+ messages = [],
183
+ strict = false,
184
+ coreRef,
185
+ }: HarnessProps) {
186
+ const [agent] = useState(() => new RunnableAgent());
187
+ const tree = (
188
+ <TestCopilotKit messages={messages} agentRef={agentRef} agent={agent}>
189
+ <CoreProbe coreRef={coreRef} />
190
+ <GenerativeUIProvider ui={ui} {...providerProps}>
191
+ <AgentChildren agentRef={agentRef}>{children}</AgentChildren>
192
+ </GenerativeUIProvider>
193
+ </TestCopilotKit>
194
+ );
195
+ return strict ? <StrictMode>{tree}</StrictMode> : tree;
196
+ }
197
+ function AgentChildren({
198
+ agentRef,
199
+ children,
200
+ }: {
201
+ agentRef: React.MutableRefObject<AbstractAgent | null>;
202
+ children: (agent: AbstractAgent) => ReactNode;
203
+ }) {
204
+ return <>{children(agentRef.current!)}</>;
205
+ }
206
+
207
+ /** A fresh agent ref for the harness. */
208
+ export function newAgentRef() {
209
+ return { current: null } as React.MutableRefObject<AbstractAgent | null>;
210
+ }
211
+
212
+ /**
213
+ * Starts a run of `agent` on `copilotkit` and waits for it. The provider
214
+ * ingests the agent's messages at the start of the run.
215
+ */
216
+ export async function startRun(
217
+ copilotkit: CopilotKitCore,
218
+ agent: AbstractAgent,
219
+ ) {
220
+ await act(async () => {
221
+ await copilotkit.runAgent({ agent });
222
+ });
223
+ }
224
+
225
+ /** Runs `fn` with `NODE_ENV=production`. */
226
+ export async function inProduction<T>(fn: () => T | Promise<T>): Promise<T> {
227
+ vi.stubEnv("NODE_ENV", "production");
228
+ try {
229
+ return await fn();
230
+ } finally {
231
+ vi.unstubAllEnvs();
232
+ }
233
+ }
234
+
235
+ /** The console calls whose first argument contains `needle`. */
236
+ export function warningsWith(
237
+ warn: { mock: { calls: unknown[][] } },
238
+ needle: string,
239
+ ): string[] {
240
+ return warn.mock.calls
241
+ .map((c) => String(c[0]))
242
+ .filter((message) => message.includes(needle));
243
+ }
@@ -0,0 +1,106 @@
1
+ import type React from "react";
2
+ import { expectTypeOf } from "vitest";
3
+ import type { Message } from "@ag-ui/client";
4
+ import {
5
+ createGenerativeUI,
6
+ GenerativeUIProvider,
7
+ GenerativeUISurface,
8
+ isGenerativeUIActivity,
9
+ } from "../generative-ui";
10
+ import type {
11
+ GenerativeUIAccessibilityWrapperProps,
12
+ GenerativeUIActivityWrapperProps,
13
+ GenerativeUIHost,
14
+ GenerativeUINodeFallbackProps,
15
+ GenerativeUIProviderProps,
16
+ GenerativeUIRejectedOperation,
17
+ GenerativeUIRuntime,
18
+ GenerativeUISurfaceProps,
19
+ GenerativeUISurfaceRootProps,
20
+ GenerativeUIToolConfig,
21
+ } from "../generative-ui";
22
+
23
+ /**
24
+ * Type-level guard for the `@copilotkit/react-native/generative-ui` entry.
25
+ *
26
+ * A `.test-d.tsx` file, like `frontend-tool-render.test-d.tsx`: `tsc --noEmit`
27
+ * (`nx run @copilotkit/react-native:check-types`) compiles it, so every
28
+ * `@ts-expect-error` below is load-bearing, and the `.test-d.` infix keeps it
29
+ * out of vitest's suite glob.
30
+ */
31
+
32
+ const ui = createGenerativeUI({ id: "props-test", components: {} });
33
+
34
+ // ─── `theme` is not a React Native prop ──────────────────────────────────────
35
+ // The web `theme` sets `--a2ui-*` CSS variables. React Native has no CSS
36
+ // variables, so the RN host never applies it; accepting it would drop the
37
+ // value silently.
38
+
39
+ expectTypeOf<GenerativeUIProviderProps>().not.toHaveProperty("theme");
40
+ // The config type this entry exports is the React Native one, without theme.
41
+ expectTypeOf<GenerativeUIToolConfig>().not.toHaveProperty("theme");
42
+ expectTypeOf<GenerativeUIToolConfig>().toHaveProperty("agentIds");
43
+
44
+ export const withTheme = (
45
+ // @ts-expect-error `theme` is not accepted on React Native.
46
+ <GenerativeUIProvider ui={ui} theme={{}}>
47
+ {null}
48
+ </GenerativeUIProvider>
49
+ );
50
+
51
+ export const withoutTheme = (
52
+ <GenerativeUIProvider ui={ui} agentIds={["agent"]}>
53
+ {null}
54
+ </GenerativeUIProvider>
55
+ );
56
+
57
+ // ─── The types a custom `host` and a custom Wrapper need are exported ────────
58
+
59
+ expectTypeOf<GenerativeUIActivityWrapperProps["rejected"]>().toEqualTypeOf<
60
+ GenerativeUIRejectedOperation[]
61
+ >();
62
+ expectTypeOf<
63
+ React.ComponentProps<GenerativeUIHost["SurfaceRoot"]>
64
+ >().toEqualTypeOf<GenerativeUISurfaceRootProps>();
65
+ expectTypeOf<
66
+ React.ComponentProps<GenerativeUIHost["AccessibilityWrapper"]>
67
+ >().toEqualTypeOf<GenerativeUIAccessibilityWrapperProps>();
68
+ expectTypeOf<
69
+ React.ComponentProps<GenerativeUIHost["NodeFallback"]>
70
+ >().toEqualTypeOf<GenerativeUINodeFallbackProps>();
71
+ expectTypeOf<GenerativeUIRuntime>().toBeObject();
72
+
73
+ // ─── isGenerativeUIActivity is a type guard ──────────────────────────────────
74
+
75
+ declare const messages: Message[];
76
+ const activities = messages.filter(isGenerativeUIActivity);
77
+ expectTypeOf(activities[0]!.role).toEqualTypeOf<"activity">();
78
+ expectTypeOf(
79
+ activities[0]!.activityType,
80
+ ).toEqualTypeOf<"generative-ui-surface">();
81
+
82
+ // ─── GenerativeUISurface: `components` is typed by `ui` ──────────────────────
83
+
84
+ const shopUI = createGenerativeUI({
85
+ id: "surface-props-test",
86
+ components: { Card: { component: () => null } },
87
+ });
88
+
89
+ export const typedComponents = (
90
+ <GenerativeUISurface id="a" ui={shopUI} components={["Card"]} />
91
+ );
92
+
93
+ export const unknownComponent = (
94
+ // @ts-expect-error "Nope" is not a component of shopUI.
95
+ <GenerativeUISurface id="a" ui={shopUI} components={["Nope"]} />
96
+ );
97
+
98
+ export const componentsWithoutUI = (
99
+ // @ts-expect-error `components` needs `ui`, which types its names.
100
+ <GenerativeUISurface id="a" components={["Card"]} />
101
+ );
102
+
103
+ // The Wrapper of a named-target surface takes the Activity's Wrapper props.
104
+ expectTypeOf<NonNullable<GenerativeUISurfaceProps["Wrapper"]>>().toEqualTypeOf<
105
+ React.ComponentType<GenerativeUIActivityWrapperProps>
106
+ >();
@@ -0,0 +1,54 @@
1
+ /**
2
+ * React Native host components as DOM elements, so the generative UI tests
3
+ * can query them. The layout and accessibility props a native view would
4
+ * receive are written out as data attributes, so the tests can see what
5
+ * reaches the platform.
6
+ *
7
+ * Use it as the factory of `vi.mock("react-native", ...)`. It imports
8
+ * nothing that imports react-native, so the factory cannot recurse.
9
+ */
10
+ import React from "react";
11
+
12
+ const host =
13
+ (tag: string) =>
14
+ ({
15
+ children,
16
+ testID,
17
+ style,
18
+ onPress,
19
+ accessibilityRole,
20
+ collapsable,
21
+ accessibilityElementsHidden,
22
+ importantForAccessibility,
23
+ accessibilityLiveRegion,
24
+ "aria-hidden": ariaHidden,
25
+ "aria-live": ariaLive,
26
+ }: any) =>
27
+ React.createElement(
28
+ tag,
29
+ {
30
+ "data-testid": testID,
31
+ "data-style": JSON.stringify(style ?? null),
32
+ "data-collapsable": JSON.stringify(collapsable),
33
+ "data-accessibility-elements-hidden": JSON.stringify(
34
+ accessibilityElementsHidden,
35
+ ),
36
+ "data-important-for-accessibility": importantForAccessibility,
37
+ "data-accessibility-live-region": accessibilityLiveRegion,
38
+ "data-aria-hidden": JSON.stringify(ariaHidden),
39
+ "data-aria-live": ariaLive,
40
+ role: accessibilityRole,
41
+ onClick: onPress,
42
+ },
43
+ children,
44
+ );
45
+
46
+ export function createReactNativeMock() {
47
+ return {
48
+ View: host("div"),
49
+ Text: host("span"),
50
+ Pressable: host("button"),
51
+ StyleSheet: { create: (s: unknown) => s, hairlineWidth: 1 },
52
+ Platform: { OS: "ios", select: (o: any) => o.ios ?? o.default },
53
+ };
54
+ }