@copilotkit/react-native 1.85.0 → 1.87.0

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 (55) hide show
  1. package/README.md +341 -2
  2. package/USAGE.md +388 -21
  3. package/dist/{CopilotKitProvider-DBq4AhRP.d.cts → CopilotKitProvider-CQ-DpvY1.d.cts} +2 -2
  4. package/dist/{CopilotKitProvider-D8sn7G_C.mjs → CopilotKitProvider-CXQGv39c.mjs} +1 -1
  5. package/dist/{CopilotKitProvider-D8sn7G_C.mjs.map → CopilotKitProvider-CXQGv39c.mjs.map} +1 -1
  6. package/dist/{CopilotKitProvider-fW21Gb7T.d.mts → CopilotKitProvider-Dc1Vbv7K.d.mts} +1 -1
  7. package/dist/{CopilotKitProvider-CjoPnabW.cjs → CopilotKitProvider-zSfbWwIg.cjs} +1 -1
  8. package/dist/{CopilotKitProvider-CjoPnabW.cjs.map → CopilotKitProvider-zSfbWwIg.cjs.map} +1 -1
  9. package/dist/components/index.cjs +1 -0
  10. package/dist/components/index.cjs.map +1 -1
  11. package/dist/components/index.mjs +1 -0
  12. package/dist/components/index.mjs.map +1 -1
  13. package/dist/generative-ui/index.cjs +612 -0
  14. package/dist/generative-ui/index.cjs.map +1 -0
  15. package/dist/generative-ui/index.d.cts +341 -0
  16. package/dist/generative-ui/index.d.mts +341 -0
  17. package/dist/generative-ui/index.mjs +549 -0
  18. package/dist/generative-ui/index.mjs.map +1 -0
  19. package/dist/headless.cjs +1 -1
  20. package/dist/headless.d.cts +1 -1
  21. package/dist/headless.d.mts +1 -1
  22. package/dist/headless.mjs +1 -1
  23. package/dist/index.cjs +2 -1
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +2 -2
  26. package/dist/index.d.mts +1 -1
  27. package/dist/index.mjs +2 -1
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/polyfills.cjs +218 -2
  30. package/dist/polyfills.cjs.map +1 -1
  31. package/dist/polyfills.mjs +217 -1
  32. package/dist/polyfills.mjs.map +1 -1
  33. package/package.json +12 -4
  34. package/project.json +6 -1
  35. package/scripts/__tests__/verify-polyfill-barrel.test.mjs +150 -0
  36. package/scripts/verify-polyfill-barrel.mjs +154 -5
  37. package/src/__tests__/generative-ui-harness.tsx +243 -0
  38. package/src/__tests__/generative-ui-provider-props.test-d.tsx +106 -0
  39. package/src/__tests__/generative-ui-rn-mock.tsx +54 -0
  40. package/src/__tests__/generative-ui-wiring.test.tsx +720 -0
  41. package/src/__tests__/generative-ui.test.tsx +1000 -0
  42. package/src/__tests__/headless-entry-surface.test.ts +964 -34
  43. package/src/components/index.ts +6 -0
  44. package/src/generative-ui/GenerativeUIActivity.tsx +235 -0
  45. package/src/generative-ui/GenerativeUIProvider.tsx +171 -0
  46. package/src/generative-ui/GenerativeUISurface.tsx +303 -0
  47. package/src/generative-ui/host.tsx +138 -0
  48. package/src/generative-ui/index.ts +99 -0
  49. package/src/generative-ui/internal.ts +55 -0
  50. package/src/index.ts +8 -3
  51. package/tsdown.config.ts +1 -0
  52. package/dist/streaming-fetch-Bm91EsRc.cjs +0 -225
  53. package/dist/streaming-fetch-Bm91EsRc.cjs.map +0 -1
  54. package/dist/streaming-fetch-Dm1oN4f2.mjs +0 -219
  55. package/dist/streaming-fetch-Dm1oN4f2.mjs.map +0 -1
@@ -20,6 +20,9 @@ import path from "node:path";
20
20
  import {
21
21
  assertBuilt,
22
22
  BUILD_COMMAND,
23
+ checkEntryOrder,
24
+ firstCjsSpecifier,
25
+ firstEsmSpecifier,
23
26
  GROUPS,
24
27
  isEntrypoint,
25
28
  missingEsmImports,
@@ -32,6 +35,61 @@ const emptyBarrel = path.join(fixtureDir, "dist-empty-barrel");
32
35
  const completeBarrel = path.join(fixtureDir, "dist-complete-barrel");
33
36
  const scriptPath = path.join(here, "..", "verify-polyfill-barrel.mjs");
34
37
 
38
+ // The CLI reads package.json next to dist/. Only the polyfill subpath, so the
39
+ // barrel fixtures are checked on their own.
40
+ const BARREL_ONLY_MANIFEST = JSON.stringify({
41
+ exports: {
42
+ "./polyfills": {
43
+ import: "./dist/polyfills.mjs",
44
+ require: "./dist/polyfills.cjs",
45
+ },
46
+ },
47
+ });
48
+
49
+ /**
50
+ * A package root with one `./generative-ui` code entry built as `esm` / `cjs`,
51
+ * beside the complete barrel.
52
+ */
53
+ function packageWithEntry({ esm, cjs }) {
54
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "rn-entry-order-"));
55
+ fs.cpSync(completeBarrel, path.join(root, "dist"), { recursive: true });
56
+ fs.mkdirSync(path.join(root, "dist", "generative-ui"));
57
+ fs.writeFileSync(path.join(root, "dist", "generative-ui", "index.mjs"), esm);
58
+ fs.writeFileSync(path.join(root, "dist", "generative-ui", "index.cjs"), cjs);
59
+ fs.writeFileSync(
60
+ path.join(root, "package.json"),
61
+ JSON.stringify({
62
+ exports: {
63
+ "./generative-ui": {
64
+ import: "./dist/generative-ui/index.mjs",
65
+ require: "./dist/generative-ui/index.cjs",
66
+ },
67
+ "./polyfills": {
68
+ import: "./dist/polyfills.mjs",
69
+ require: "./dist/polyfills.cjs",
70
+ },
71
+ "./package.json": "./package.json",
72
+ },
73
+ }),
74
+ );
75
+ return root;
76
+ }
77
+
78
+ // What tsdown emitted for the generative UI entry before it imported the
79
+ // polyfills: core-loading modules first, no polyfill barrel at all.
80
+ const UNPOLYFILLED_ESM =
81
+ 'import React from "react";\n' +
82
+ 'import { useCopilotKit } from "@copilotkit/react-core/v2/context";\n';
83
+ const UNPOLYFILLED_CJS =
84
+ "Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n" +
85
+ "const require_chunk = require('../chunk-C0xms8kb.cjs');\n" +
86
+ 'let react = require("react");\n';
87
+ const POLYFILLED_ESM = 'import "../polyfills.mjs";\n' + UNPOLYFILLED_ESM;
88
+ const POLYFILLED_CJS = UNPOLYFILLED_CJS.replace(
89
+ 'let react = require("react");',
90
+ "require('../polyfills.cjs');\nlet react = require(\"react\");",
91
+ );
92
+
35
93
  describe("verifyBarrel", () => {
36
94
  it("rejects the tree-shaken barrel that shipped in 1.69.2", () => {
37
95
  const report = verifyBarrel(emptyBarrel);
@@ -96,6 +154,73 @@ describe("verifyBarrel", () => {
96
154
  });
97
155
  });
98
156
 
157
+ describe("checkEntryOrder", () => {
158
+ it("rejects a published entry that loads CopilotKit before the polyfills", () => {
159
+ const root = packageWithEntry({
160
+ esm: UNPOLYFILLED_ESM,
161
+ cjs: UNPOLYFILLED_CJS,
162
+ });
163
+ const results = checkEntryOrder(root);
164
+ // Both formats, and nothing for the polyfill subpath or the manifest.
165
+ assert.deepEqual(
166
+ results.map(({ file, first, ok }) => ({ file, first, ok })),
167
+ [
168
+ { file: "./dist/generative-ui/index.mjs", first: "react", ok: false },
169
+ { file: "./dist/generative-ui/index.cjs", first: "react", ok: false },
170
+ ],
171
+ );
172
+ fs.rmSync(root, { recursive: true, force: true });
173
+ });
174
+
175
+ it("accepts an entry whose first load is the polyfill barrel", () => {
176
+ const root = packageWithEntry({
177
+ esm: POLYFILLED_ESM,
178
+ cjs: POLYFILLED_CJS,
179
+ });
180
+ const results = checkEntryOrder(root);
181
+ assert.equal(results.length, 2);
182
+ for (const result of results) assert.equal(result.ok, true, result.file);
183
+ fs.rmSync(root, { recursive: true, force: true });
184
+ });
185
+
186
+ it("rejects an entry whose polyfill import is present but not first", () => {
187
+ // The root entry's real regression: the bundler hoisted a shared chunk
188
+ // that loads @copilotkit/react-core above the import of the polyfills.
189
+ const root = packageWithEntry({
190
+ esm: UNPOLYFILLED_ESM + 'import "../polyfills.mjs";\n',
191
+ cjs: UNPOLYFILLED_CJS + "require('../polyfills.cjs');\n",
192
+ });
193
+ for (const result of checkEntryOrder(root)) {
194
+ assert.equal(result.ok, false, result.file);
195
+ }
196
+ fs.rmSync(root, { recursive: true, force: true });
197
+ });
198
+
199
+ it("reports an entry that was not built instead of skipping it", () => {
200
+ const root = packageWithEntry({ esm: POLYFILLED_ESM, cjs: POLYFILLED_CJS });
201
+ fs.rmSync(path.join(root, "dist", "generative-ui", "index.cjs"));
202
+ const missing = checkEntryOrder(root).find((r) => r.file.endsWith(".cjs"));
203
+ assert.equal(missing.ok, false);
204
+ assert.equal(missing.error, "not built");
205
+ fs.rmSync(root, { recursive: true, force: true });
206
+ });
207
+ });
208
+
209
+ describe("firstEsmSpecifier / firstCjsSpecifier", () => {
210
+ it("reads the first module, past comments and rolldown's runtime chunk", () => {
211
+ assert.equal(
212
+ firstEsmSpecifier(
213
+ '//#region x\nimport "./polyfills.mjs";\nimport a from "a";',
214
+ ),
215
+ "./polyfills.mjs",
216
+ );
217
+ assert.equal(firstEsmSpecifier('export * from "./x.mjs";'), "./x.mjs");
218
+ assert.equal(firstEsmSpecifier("const a = 1;"), null);
219
+ assert.equal(firstCjsSpecifier(POLYFILLED_CJS), "../polyfills.cjs");
220
+ assert.equal(firstCjsSpecifier(UNPOLYFILLED_CJS), "react");
221
+ });
222
+ });
223
+
99
224
  describe("missingEsmImports", () => {
100
225
  it("names every group the ESM barrel no longer imports", () => {
101
226
  assert.deepEqual(
@@ -157,6 +282,7 @@ describe("cli", () => {
157
282
  fs.mkdirSync(path.join(fakeRoot, "scripts"));
158
283
  fs.cpSync(scriptPath, path.join(fakeRoot, "scripts", "verify.mjs"));
159
284
  fs.cpSync(emptyBarrel, path.join(fakeRoot, "dist"), { recursive: true });
285
+ fs.writeFileSync(path.join(fakeRoot, "package.json"), BARREL_ONLY_MANIFEST);
160
286
 
161
287
  const result = spawnSync(
162
288
  process.execPath,
@@ -174,6 +300,7 @@ describe("cli", () => {
174
300
  fs.mkdirSync(path.join(fakeRoot, "scripts"));
175
301
  fs.cpSync(scriptPath, path.join(fakeRoot, "scripts", "verify.mjs"));
176
302
  fs.cpSync(completeBarrel, path.join(fakeRoot, "dist"), { recursive: true });
303
+ fs.writeFileSync(path.join(fakeRoot, "package.json"), BARREL_ONLY_MANIFEST);
177
304
 
178
305
  const result = spawnSync(
179
306
  process.execPath,
@@ -184,4 +311,27 @@ describe("cli", () => {
184
311
  assert.equal(JSON.parse(result.stdout).ok, true);
185
312
  fs.rmSync(fakeRoot, { recursive: true, force: true });
186
313
  });
314
+
315
+ it("fails the build when a published entry loads CopilotKit before the polyfills", () => {
316
+ const fakeRoot = packageWithEntry({
317
+ esm: UNPOLYFILLED_ESM,
318
+ cjs: UNPOLYFILLED_CJS,
319
+ });
320
+ fs.mkdirSync(path.join(fakeRoot, "scripts"));
321
+ fs.cpSync(scriptPath, path.join(fakeRoot, "scripts", "verify.mjs"));
322
+
323
+ const result = spawnSync(
324
+ process.execPath,
325
+ [path.join(fakeRoot, "scripts", "verify.mjs")],
326
+ { encoding: "utf8" },
327
+ );
328
+ assert.equal(result.status, 1);
329
+ assert.match(
330
+ result.stdout,
331
+ /FAIL {2}\.\/dist\/generative-ui\/index\.mjs +first loads react/,
332
+ );
333
+ assert.match(result.stderr, /expected \.\.\/polyfills\.cjs/);
334
+ assert.match(result.stderr, /sideEffects/);
335
+ fs.rmSync(fakeRoot, { recursive: true, force: true });
336
+ });
187
337
  });
@@ -23,6 +23,14 @@
23
23
  // Node ESM refuses it. Asserting the five imports survive the bundler is
24
24
  // the part this file exists to protect.
25
25
  //
26
+ // Then a third check, over every published code entry in package.json
27
+ // `exports` (all but the polyfill subpaths): the built import and require
28
+ // files must load the polyfill barrel before anything else. An app can import
29
+ // any entry first, and @copilotkit/core and @ag-ui/client fail at load time on
30
+ // Hermes without the polyfills. It reads dist/ because the bundler decides the
31
+ // emitted order: it hoisted a shared provider chunk above the root entry's
32
+ // `export * from "./headless"`, so the source order alone proved nothing.
33
+ //
26
34
  // Invoked from package.json `build`, so a barrel that installs nothing fails
27
35
  // the build rather than reaching npm.
28
36
  //
@@ -138,7 +146,111 @@ export function verifyBarrel(distDir) {
138
146
  return { ok, cjs, esmMissing };
139
147
  }
140
148
 
141
- export function formatReport({ cjs, esmMissing }) {
149
+ /**
150
+ * Export subpaths that are the polyfills themselves, or carry no code. Every
151
+ * other published entry loads @copilotkit/core or @ag-ui/client, which fail at
152
+ * load time on Hermes without the polyfills, so each must install them first:
153
+ * an app can import any entry before the root one.
154
+ */
155
+ const isPolyfillOrManifestExport = (key) =>
156
+ key === "./package.json" ||
157
+ key === "./polyfills" ||
158
+ key.startsWith("./polyfills/");
159
+
160
+ /** The first module an ESM file imports or re-exports, in order. */
161
+ export function firstEsmSpecifier(source) {
162
+ const m =
163
+ /^\s*(?:import\s*(?:[^;"'`]*?\bfrom\s*)?|export\s[^;"'`]*?\bfrom\s*)["'`]([^"'`]+)["'`]/m.exec(
164
+ source.replace(/\/\*[\s\S]*?\*\/|^\s*\/\/[^\n]*$/gm, ""),
165
+ );
166
+ return m ? m[1] : null;
167
+ }
168
+
169
+ /**
170
+ * The first module a CJS file requires, in order, skipping the bundler's own
171
+ * runtime helper chunk (rolldown's `chunk-*.cjs`: `__toESM` and friends, which
172
+ * requires nothing and touches no global).
173
+ */
174
+ export function firstCjsSpecifier(source) {
175
+ for (const m of source.matchAll(/\brequire\s*\(\s*(["'])([^"']+)\1\s*\)/g)) {
176
+ if (/(?:^|\/)chunk-[\w-]+\.cjs$/.test(m[2])) continue;
177
+ return m[2];
178
+ }
179
+ return null;
180
+ }
181
+
182
+ /**
183
+ * For every published code entry (from package.json `exports`), whether its
184
+ * BUILT import and require targets load the polyfill barrel before anything
185
+ * else. Checked in dist/, because the bundler decides the emitted order: a
186
+ * shared chunk can be hoisted above a re-export that installs the polyfills.
187
+ */
188
+ export function checkEntryOrder(packageDir) {
189
+ const manifestPath = path.join(packageDir, "package.json");
190
+ if (!existsSync(manifestPath)) {
191
+ throw new Error(`No package.json at ${manifestPath}.`);
192
+ }
193
+ const { exports: exportsMap } = JSON.parse(
194
+ readFileSync(manifestPath, "utf8"),
195
+ );
196
+ const results = [];
197
+ for (const [key, value] of Object.entries(exportsMap ?? {})) {
198
+ if (isPolyfillOrManifestExport(key)) continue;
199
+ const targets =
200
+ typeof value === "string" ? { import: value } : (value ?? {});
201
+ for (const [condition, target] of Object.entries(targets)) {
202
+ if (condition !== "import" && condition !== "require") continue;
203
+ const file = path.join(packageDir, target);
204
+ const cjs = file.endsWith(".cjs");
205
+ let expected = path
206
+ .relative(
207
+ path.dirname(file),
208
+ path.join(
209
+ packageDir,
210
+ "dist",
211
+ cjs ? "polyfills.cjs" : "polyfills.mjs",
212
+ ),
213
+ )
214
+ .split(path.sep)
215
+ .join("/");
216
+ if (!expected.startsWith(".")) expected = `./${expected}`;
217
+ if (!existsSync(file)) {
218
+ results.push({
219
+ entry: key,
220
+ file: target,
221
+ expected,
222
+ first: null,
223
+ ok: false,
224
+ error: "not built",
225
+ });
226
+ continue;
227
+ }
228
+ const source = readFileSync(file, "utf8");
229
+ const first = cjs ? firstCjsSpecifier(source) : firstEsmSpecifier(source);
230
+ results.push({
231
+ entry: key,
232
+ file: target,
233
+ expected,
234
+ first,
235
+ ok: first === expected,
236
+ });
237
+ }
238
+ }
239
+ return results;
240
+ }
241
+
242
+ /** The barrel check plus the entry-order check, for a built package. */
243
+ export function verifyPackage(packageDir) {
244
+ const barrel = verifyBarrel(path.join(packageDir, "dist"));
245
+ const entries = checkEntryOrder(packageDir);
246
+ return {
247
+ ...barrel,
248
+ entries,
249
+ ok: barrel.ok && entries.every((entry) => entry.ok),
250
+ };
251
+ }
252
+
253
+ export function formatReport({ cjs, esmMissing, entries = [] }) {
142
254
  const lines = cjs.map(
143
255
  (entry) =>
144
256
  `${entry.missing.length === 0 ? "PASS" : "FAIL"} cjs ${entry.group.padEnd(9)} ` +
@@ -150,10 +262,41 @@ export function formatReport({ cjs, esmMissing }) {
150
262
  `import "./polyfills/${group.name}.mjs"`,
151
263
  );
152
264
  }
265
+ for (const entry of entries) {
266
+ lines.push(
267
+ `${entry.ok ? "PASS" : "FAIL"} ${entry.file.padEnd(32)} ` +
268
+ `first loads ${entry.first ?? `(${entry.error ?? "nothing"})`}`,
269
+ );
270
+ }
153
271
  return lines.join("\n");
154
272
  }
155
273
 
156
- export function failureMessage({ cjs, esmMissing }) {
274
+ export function failureMessage({ cjs, esmMissing, entries = [] }) {
275
+ const misordered = entries.filter((entry) => !entry.ok);
276
+ if (
277
+ misordered.length &&
278
+ cjs.every((entry) => entry.missing.length === 0) &&
279
+ esmMissing.length === 0
280
+ ) {
281
+ return (
282
+ `A published entry does not install the polyfills before anything else.\n` +
283
+ misordered
284
+ .map(
285
+ (entry) =>
286
+ ` ${entry.file} (${entry.entry}) first loads ` +
287
+ `${entry.first ?? `(${entry.error ?? "nothing"})`}, expected ${entry.expected}`,
288
+ )
289
+ .join("\n") +
290
+ `\n\nAn app can import any entry before the root one, and on Hermes\n` +
291
+ `@copilotkit/core and @ag-ui/client fail at load time without the polyfills.\n` +
292
+ `Make \`import "./polyfills"\` (relative) the entry's first import, and list\n` +
293
+ `the entry's src and dist paths in package.json "sideEffects".`
294
+ );
295
+ }
296
+ return failureMessageForBarrel({ cjs, esmMissing }, misordered);
297
+ }
298
+
299
+ function failureMessageForBarrel({ cjs, esmMissing }, misordered) {
157
300
  const dropped = [
158
301
  ...cjs.flatMap((entry) => entry.missing),
159
302
  ...esmMissing.map((name) => `import "./polyfills/${name}.mjs"`),
@@ -163,7 +306,10 @@ export function failureMessage({ cjs, esmMissing }) {
163
306
  `Missing: ${dropped.join(", ")}\n\n` +
164
307
  `The side-effect imports in src/polyfills.ts were tree-shaken away. Check that\n` +
165
308
  `the "sideEffects" globs in package.json match this package's SOURCE paths —\n` +
166
- `globs that only match ./dist/** tell the bundler the src files are pure.`
309
+ `globs that only match ./dist/** tell the bundler the src files are pure.` +
310
+ (misordered.length
311
+ ? `\n\nAlso misordered: ${misordered.map((entry) => entry.file).join(", ")}`
312
+ : "")
167
313
  );
168
314
  }
169
315
 
@@ -196,7 +342,7 @@ if (isEntrypoint(import.meta.url, process.argv[1])) {
196
342
  const jsonMode = process.argv.includes("--json");
197
343
  let report;
198
344
  try {
199
- report = verifyBarrel(path.join(packageRoot, "dist"));
345
+ report = verifyPackage(packageRoot);
200
346
  } catch (error) {
201
347
  if (jsonMode) {
202
348
  process.stdout.write(
@@ -214,7 +360,10 @@ if (isEntrypoint(import.meta.url, process.argv[1])) {
214
360
  process.stdout.write(formatReport(report) + "\n");
215
361
  if (!report.ok) process.stderr.write(`\n${failureMessage(report)}\n`);
216
362
  else
217
- process.stdout.write(`\nAll ${GROUPS.length} polyfill groups install.\n`);
363
+ process.stdout.write(
364
+ `\nAll ${GROUPS.length} polyfill groups install, and all ` +
365
+ `${report.entries.length} published entry files load them first.\n`,
366
+ );
218
367
  }
219
368
  process.exit(report.ok ? 0 : 1);
220
369
  }
@@ -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/v2/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
+ }