@copilotkit/react-native 1.67.1 → 1.68.1

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 (56) hide show
  1. package/dist/chunk-C0xms8kb.cjs +34 -0
  2. package/dist/components/index.cjs +146 -33
  3. package/dist/components/index.cjs.map +1 -1
  4. package/dist/components/index.mjs +144 -32
  5. package/dist/components/index.mjs.map +1 -1
  6. package/dist/headless.cjs +40 -4
  7. package/dist/headless.d.cts +3 -3
  8. package/dist/headless.d.mts +3 -3
  9. package/dist/headless.mjs +5 -4
  10. package/dist/index.cjs +43 -7
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +3 -3
  13. package/dist/index.d.mts +4 -4
  14. package/dist/index.mjs +3 -4
  15. package/dist/index.mjs.map +1 -1
  16. package/dist/polyfills/encoding.cjs +1 -1
  17. package/dist/polyfills/streams.cjs +1 -1
  18. package/dist/useRenderTool-BBxnOOeJ.d.mts +161 -0
  19. package/dist/useRenderTool-BWo11PCL.d.cts +161 -0
  20. package/dist/{useRenderTool-DLavcsVB.cjs → useRenderTool-CKEPq7MQ.cjs} +20 -34
  21. package/dist/useRenderTool-CKEPq7MQ.cjs.map +1 -0
  22. package/dist/{useRenderTool-DUqpS97B.mjs → useRenderTool-l7M-I8rT.mjs} +18 -33
  23. package/dist/useRenderTool-l7M-I8rT.mjs.map +1 -0
  24. package/package.json +9 -6
  25. package/scripts/__tests__/fixtures/stray-react-dom-headless.js +16 -0
  26. package/scripts/__tests__/fixtures/tiny-headless.js +10 -0
  27. package/scripts/__tests__/fixtures/warning-headless.js +13 -0
  28. package/scripts/__tests__/measure-headless.test.mjs +275 -0
  29. package/scripts/measure-headless.mjs +310 -0
  30. package/src/CopilotKitProvider.tsx +1 -2
  31. package/src/__mocks__/test-copilotkit.tsx +116 -0
  32. package/src/__mocks__/tool-fixtures.ts +50 -0
  33. package/src/__tests__/headless-entry-surface.test.ts +464 -46
  34. package/src/__tests__/headless-integration.test.tsx +12 -1
  35. package/src/__tests__/headless-value-exports.test.ts +369 -0
  36. package/src/components/CopilotChat.tsx +218 -32
  37. package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +5 -126
  38. package/src/components/__tests__/CopilotChat.test.tsx +5 -49
  39. package/src/components/__tests__/CopilotChatToolCalls.test.tsx +468 -0
  40. package/src/headless.ts +36 -14
  41. package/src/hooks/__tests__/render-tool-call.integration.test.tsx +181 -0
  42. package/src/hooks/__tests__/useRenderTool.test.tsx +232 -267
  43. package/src/hooks/index.ts +1 -7
  44. package/src/hooks/render-tool-types.ts +55 -0
  45. package/src/hooks/useRenderTool.ts +29 -57
  46. package/src/index.ts +13 -5
  47. package/dist/RenderToolContext-CBNKcJqz.cjs +0 -126
  48. package/dist/RenderToolContext-CBNKcJqz.cjs.map +0 -1
  49. package/dist/RenderToolContext-D8M-JhD1.mjs +0 -75
  50. package/dist/RenderToolContext-D8M-JhD1.mjs.map +0 -1
  51. package/dist/useRenderTool-9YDIfZ0D.d.mts +0 -164
  52. package/dist/useRenderTool-BugVTDoM.d.cts +0 -164
  53. package/dist/useRenderTool-DLavcsVB.cjs.map +0 -1
  54. package/dist/useRenderTool-DUqpS97B.mjs.map +0 -1
  55. package/src/hooks/RenderToolContext.tsx +0 -150
  56. package/src/hooks/__tests__/RenderToolContext.test.tsx +0 -264
@@ -1,6 +1,10 @@
1
- import { describe, it, expect } from "vitest";
1
+ import { describe, it, expect, beforeAll } from "vitest";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
+ // Type-only, so it is erased and does NOT statically pull the entry this file
5
+ // deliberately loads at runtime (and is not part of the walked graph either —
6
+ // the walk starts at src/headless.ts / src/index.ts, not at this test).
7
+ import type * as HeadlessEntry from "../headless";
4
8
 
5
9
  /**
6
10
  * Guards the `@copilotkit/react-native/headless` entry (src/headless.ts).
@@ -16,6 +20,45 @@ import path from "node:path";
16
20
  *
17
21
  * Mirrors the export-surface guard added for @copilotkit/react-core/v2/headless
18
22
  * (PR #5883).
23
+ *
24
+ * ─── Why the walker looks the way it does ──────────────────────────────────
25
+ * A guard that under-reports is worse than no guard, because it is trusted. The
26
+ * first version of this file had four blind spots, each of which let a REAL
27
+ * violation through (or flagged a non-violation), so the walker below is written
28
+ * to close them and each is covered by a test:
29
+ *
30
+ * 1. It only saw `import … from "x"`. A lazy optional-peer
31
+ * `require("@copilotkit/react-core/v2")` or `await import(…)` — which Metro
32
+ * follows and bundles just the same — was invisible. Now static, bare
33
+ * side-effect, dynamic `import()` and `require()` are all extracted, and a
34
+ * loader whose argument is NOT a literal is reported as unanalyzable rather
35
+ * than ignored.
36
+ * 2. It matched raw text, so doc comments counted as imports. That was not
37
+ * hypothetical: it was harvesting EIGHT specifiers (`@copilotkit/react-native`,
38
+ * `…/headless`, `…/polyfills` and its five subpaths) that NO source file
39
+ * imports (half the reported bare-specifier set), purely from JSDoc
40
+ * examples. In the other direction, a "don't do this: import from
41
+ * @copilotkit/react-core/v2" counter-example written in a doc comment failed
42
+ * the build. Comments are stripped before matching now.
43
+ * 3. `resolveLocal` returned null for an edge it could not resolve and the
44
+ * caller dropped it, so an unresolvable specifier read as "clean" while
45
+ * hiding a whole subgraph behind it (e.g. an ESM-style `"./foo.js"` pointing
46
+ * at `foo.ts`). Unresolvable edges are now resolved where possible and FAIL
47
+ * LOUDLY where not, and the walk has a non-vacuity floor so a truncated
48
+ * graph cannot make the deny-lists below pass for the wrong reason.
49
+ * 4. The graph was walked in the `describe` body, so a missing entry file threw
50
+ * at COLLECTION time and every test in the file — including the one
51
+ * asserting the entry exists — silently never ran. The walk is lazy and
52
+ * memoized per entry now, and happens inside test bodies.
53
+ * 5. Four separate tests each did `await import("../headless")`, so four tests
54
+ * raced the SAME one-time module-graph cost against the default 5s per-test
55
+ * budget — and when the first one lost that race the other three inherited
56
+ * its in-flight import and timed out with it (the observed signature was 3
57
+ * failures at once, not 1). Measured at up to 4568ms, i.e. 91% of the budget
58
+ * (see IMPORT_BUDGET_MS), so the file timed out nondeterministically — a
59
+ * flaky hard gate, which is a gate people learn to ignore. The runtime-export
60
+ * checks now share ONE explicitly-budgeted `beforeAll`, so the cost lives in
61
+ * exactly one place instead of being raced four times.
19
62
  */
20
63
 
21
64
  const srcDir = path.resolve(__dirname, "..");
@@ -38,18 +81,185 @@ const FORBIDDEN_LOCAL = [
38
81
  "use-attachments",
39
82
  ];
40
83
 
41
- const importRe =
42
- /(?:import|export)\s+(?:type\s+)?[^"']*?from\s+["']([^"']+)["']|import\s+["']([^"']+)["']/g;
84
+ // ─── #4893 bundle guard ──────────────────────────────────────────────────────
85
+ // @copilotkit/react-core/v2 (the "fat" entry) re-exports from a monolithic chunk
86
+ // that pulls the chat-message rendering stack: streamdown -> shiki (~5.5 MB of
87
+ // grammars + themes), plus mermaid, cytoscape and katex. Metro does not
88
+ // tree-shake, so ONE import of that specifier from anywhere in this package puts
89
+ // all of it in every consumer's app bundle (issue #4893). PR #5883 moved the lean
90
+ // hooks into /v2/headless precisely so this package never needs the fat entry.
91
+ const ALLOWED_REACT_CORE_ENTRIES = [
92
+ "@copilotkit/react-core/v2/headless",
93
+ "@copilotkit/react-core/v2/context",
94
+ ];
95
+
96
+ // Heavy modules that must never appear as a direct import from this package.
97
+ // (Transitive leakage through react-core's own entry is covered separately by
98
+ // packages/react-core/scripts/assert-headless-purity.mjs — this walker cannot
99
+ // follow into node_modules.)
100
+ const FORBIDDEN_HEAVY = [
101
+ "shiki",
102
+ "mermaid",
103
+ "cytoscape",
104
+ "katex",
105
+ "streamdown",
106
+ "@copilotkit/a2ui-renderer",
107
+ "@copilotkit/web-inspector",
108
+ "@copilotkit/runtime-client-gql",
109
+ ];
110
+
111
+ const indexEntry = path.join(srcDir, "index.ts");
112
+ const pkgJsonPath = path.resolve(srcDir, "..", "package.json");
113
+
114
+ /**
115
+ * Modules the headless graph MUST reach. Purely a non-vacuity floor: every other
116
+ * graph assertion in this file is a deny-list, and a deny-list over an EMPTY set
117
+ * passes. If the walker ever silently stops walking (a resolver regression, a
118
+ * renamed entry), this is the test that says so instead of the whole file going
119
+ * green while checking nothing.
120
+ */
121
+ const REQUIRED_HEADLESS_MODULES = [
122
+ "headless.ts",
123
+ "CopilotKitProvider.tsx",
124
+ "polyfills.ts",
125
+ ];
126
+ const REQUIRED_HEADLESS_BARE = ["@copilotkit/react-core/v2/headless"];
127
+
128
+ interface PkgManifest {
129
+ dependencies?: Record<string, string>;
130
+ peerDependencies?: Record<string, string>;
131
+ peerDependenciesMeta?: Record<string, { optional?: boolean }>;
132
+ }
133
+
134
+ /**
135
+ * The packages a headless consumer is GUARANTEED to be able to resolve: this
136
+ * package's own `dependencies` plus its NON-optional `peerDependencies`.
137
+ *
138
+ * That set is exactly the promise the headless entry sells — "install this and
139
+ * bundle, without stubbing anything in metro.config.js" — so it is the right
140
+ * allow-list, and it is READ from package.json rather than hand-copied so it
141
+ * cannot drift from the manifest it is meant to describe. Anything else in the
142
+ * graph is a package the consumer may not have: every optional peer
143
+ * (`@gorhom/bottom-sheet`, `expo-*`, `react-native-streamdown`, `zod`), any
144
+ * brand-new third-party edge, and any Node builtin (which RN has no business
145
+ * reaching). This package's OWN name is deliberately absent, which is what keeps
146
+ * this test doubling as the comment-stripping regression: the eight phantom
147
+ * `@copilotkit/react-native…` specifiers that JSDoc examples used to harvest are
148
+ * all self-references, so if `stripComments` regresses they fail here.
149
+ *
150
+ * What this set does NOT police is WHICH ENTRY of an allowed package is imported:
151
+ * `@copilotkit/react-core` is a legitimate dependency, so the fat
152
+ * `@copilotkit/react-core/v2` passes here and is caught by the dedicated
153
+ * ALLOWED_REACT_CORE_ENTRIES test (which is package-wide, i.e. stricter). Keep
154
+ * both — this one is the catch-all for UNENUMERATED packages, that one is the
155
+ * #4893 entry ban.
156
+ */
157
+ function guaranteedPackages(): Set<string> {
158
+ const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, "utf8")) as PkgManifest;
159
+ const optional = pkg.peerDependenciesMeta ?? {};
160
+ const guaranteed = new Set([
161
+ ...Object.keys(pkg.dependencies ?? {}),
162
+ ...Object.keys(pkg.peerDependencies ?? {}).filter(
163
+ (name) => !optional[name]?.optional,
164
+ ),
165
+ ]);
166
+ // Fail loud rather than allow-list nothing (which would make the assertion
167
+ // below scream about every legitimate import) or everything.
168
+ expect(
169
+ guaranteed.size,
170
+ `read no dependencies from ${pkgJsonPath} — the allow-list would be meaningless`,
171
+ ).toBeGreaterThan(0);
172
+ return guaranteed;
173
+ }
174
+
175
+ /** `@scope/pkg/sub/path` -> `@scope/pkg`; `pkg/sub` -> `pkg`. */
176
+ function packageNameOf(spec: string): string {
177
+ const parts = spec.split("/");
178
+ return spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]!;
179
+ }
180
+
181
+ /**
182
+ * Comment / string / template alternation, scanned left-to-right in ONE pass.
183
+ *
184
+ * Matching strings with the SAME alternation is what makes comment stripping
185
+ * correct: a `//` inside a string literal is consumed as part of the string
186
+ * before the comment branch can see it, and a quote inside a comment is consumed
187
+ * as part of the comment. `'` and `"` deliberately do not cross a newline, so an
188
+ * unbalanced apostrophe in prose ("doesn't") cannot swallow the rest of a file.
189
+ */
190
+ const COMMENT_OR_LITERAL =
191
+ /"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`|\/\/[^\n]*|\/\*[\s\S]*?\*\//g;
192
+
193
+ /**
194
+ * Blanks out comments, preserving newlines (and therefore line numbers) and
195
+ * leaving real string/template literals untouched.
196
+ */
197
+ function stripComments(code: string): string {
198
+ return code.replace(COMMENT_OR_LITERAL, (match) =>
199
+ match.startsWith("//") || match.startsWith("/*")
200
+ ? match.replace(/[^\n]/g, " ")
201
+ : match,
202
+ );
203
+ }
204
+
205
+ // Every way this package could reach another module. `import`/`export … from`
206
+ // and bare side-effect `import "x"` are the static forms; `import()` and
207
+ // `require()` are the lazy forms Metro follows all the same — omitting them let
208
+ // a lazily-required fat entry defeat the whole guard.
209
+ const SPEC_PATTERNS: RegExp[] = [
210
+ // import … from "x" / export … from "x" / export * as ns from "x"
211
+ /\b(?:import|export)\b[^;"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,
212
+ // import "x" (side effect)
213
+ /\bimport\s*["'`]([^"'`]+)["'`]/g,
214
+ // import("x") / await import("x")
215
+ /\bimport\s*\(\s*["'`]([^"'`]+)["'`]/g,
216
+ // require("x") / require.resolve("x")
217
+ /\brequire(?:\.resolve)?\s*\(\s*["'`]([^"'`]+)["'`]/g,
218
+ ];
219
+
220
+ // A loader whose argument is not a string literal — `require(name)`,
221
+ // `import(`@scope/${pkg}`)`. Statically unanalyzable, so it must be reported
222
+ // rather than skipped: silence here is exactly how a fat-entry import hides.
223
+ const OPAQUE_LOADER =
224
+ /\b(?:import|require(?:\.resolve)?)\s*\(\s*(?!["'`]\s*[^"'`$]*["'`]\s*\))([^)]*)\)/g;
225
+
226
+ function extractSpecs(code: string): { specs: string[]; opaque: string[] } {
227
+ const specs = new Set<string>();
228
+ const opaque = new Set<string>();
229
+
230
+ for (const re of SPEC_PATTERNS) {
231
+ for (const m of code.matchAll(re)) {
232
+ const spec = m[1];
233
+ if (!spec) continue;
234
+ // A template with an interpolation is not a resolvable specifier.
235
+ if (spec.includes("${")) opaque.add(spec);
236
+ else specs.add(spec);
237
+ }
238
+ }
239
+ for (const m of code.matchAll(OPAQUE_LOADER)) {
240
+ const arg = m[1]?.trim();
241
+ if (arg) opaque.add(arg);
242
+ }
243
+ return { specs: [...specs], opaque: [...opaque] };
244
+ }
43
245
 
44
246
  function resolveLocal(fromFile: string, spec: string): string | null {
45
247
  if (!spec.startsWith(".")) return null;
46
248
  const base = path.resolve(path.dirname(fromFile), spec);
249
+ // TS source is allowed to spell a relative import with the EMITTED extension
250
+ // (`./foo.js` for `foo.ts`). Without these rewrites such an edge resolves to
251
+ // nothing, and the old walker then dropped the entire subgraph behind it.
252
+ const rewritten = base.replace(/\.(?:js|jsx|mjs|cjs)$/, "");
47
253
  const candidates = [
48
254
  base,
49
- `${base}.ts`,
50
- `${base}.tsx`,
51
- path.join(base, "index.ts"),
52
- path.join(base, "index.tsx"),
255
+ ...[base, rewritten].flatMap((b) => [
256
+ `${b}.ts`,
257
+ `${b}.tsx`,
258
+ `${b}.mts`,
259
+ `${b}.cts`,
260
+ path.join(b, "index.ts"),
261
+ path.join(b, "index.tsx"),
262
+ ]),
53
263
  ];
54
264
  for (const c of candidates) {
55
265
  if (fs.existsSync(c) && fs.statSync(c).isFile()) return c;
@@ -57,10 +267,22 @@ function resolveLocal(fromFile: string, spec: string): string | null {
57
267
  return null;
58
268
  }
59
269
 
60
- function walkGraph(entry: string) {
270
+ interface Graph {
271
+ /** Every source file reachable from the entry, including the entry. */
272
+ seen: Set<string>;
273
+ /** Every bare (non-relative) specifier reached from those files. */
274
+ bareSpecs: Set<string>;
275
+ /** Relative edges that resolved to no file — asserted empty, never dropped. */
276
+ unresolved: string[];
277
+ /** Loader calls with a non-literal argument — asserted empty. */
278
+ opaque: string[];
279
+ }
280
+
281
+ function walkGraph(entry: string): Graph {
61
282
  const seen = new Set<string>();
62
283
  const bareSpecs = new Set<string>();
63
- const localFiles = new Set<string>();
284
+ const unresolved: string[] = [];
285
+ const opaque: string[] = [];
64
286
  const stack = [entry];
65
287
 
66
288
  while (stack.length) {
@@ -68,32 +290,133 @@ function walkGraph(entry: string) {
68
290
  if (seen.has(file)) continue;
69
291
  seen.add(file);
70
292
 
71
- const code = fs.readFileSync(file, "utf8");
72
- for (const m of code.matchAll(importRe)) {
73
- const spec = m[1] ?? m[2];
74
- if (!spec) continue;
293
+ const code = stripComments(fs.readFileSync(file, "utf8"));
294
+ const here = path.relative(srcDir, file);
295
+ const { specs, opaque: opaqueHere } = extractSpecs(code);
296
+
297
+ for (const arg of opaqueHere) opaque.push(`${here}: ${arg}`);
298
+
299
+ for (const spec of specs) {
75
300
  if (spec.startsWith(".")) {
76
301
  const resolved = resolveLocal(file, spec);
77
302
  if (resolved) {
78
- localFiles.add(resolved);
79
303
  stack.push(resolved);
304
+ } else {
305
+ unresolved.push(`${here} -> ${spec}`);
80
306
  }
81
307
  } else {
82
308
  bareSpecs.add(spec);
83
309
  }
84
310
  }
85
311
  }
86
- return { seen, bareSpecs, localFiles };
312
+ return { seen, bareSpecs, unresolved, opaque };
87
313
  }
88
314
 
315
+ // Memoized so each test body can ask for a graph without the walk running in the
316
+ // `describe` body — where a throw would kill COLLECTION and silently take every
317
+ // test in this file with it (including the one asserting the entry exists).
318
+ const graphCache = new Map<string, Graph>();
319
+ function graphFor(entry: string): Graph {
320
+ let graph = graphCache.get(entry);
321
+ if (!graph) {
322
+ graph = walkGraph(entry);
323
+ graphCache.set(entry, graph);
324
+ }
325
+ return graph;
326
+ }
327
+
328
+ const rel = (files: Iterable<string>) =>
329
+ [...files].map((f) => path.relative(srcDir, f)).sort();
330
+
331
+ const ENTRIES: [label: string, entry: string][] = [
332
+ ["headless", headlessEntry],
333
+ ["default barrel", indexEntry],
334
+ ];
335
+
89
336
  describe("@copilotkit/react-native/headless entry", () => {
90
- it("has a headless entry file", () => {
91
- expect(fs.existsSync(headlessEntry)).toBe(true);
337
+ // Runs for real now: nothing walks the graph before collection finishes, so a
338
+ // missing entry file reports HERE instead of erroring the whole suite out.
339
+ it.each(ENTRIES)("has a %s entry file", (_label, entry) => {
340
+ expect(fs.existsSync(entry), `missing entry file: ${entry}`).toBe(true);
341
+ });
342
+
343
+ // Fail-loud, both entries: an edge the walker cannot follow means every check
344
+ // below is reasoning about an incomplete graph, so it must never pass quietly.
345
+ it.each(ENTRIES)(
346
+ "%s entry graph resolves every relative import",
347
+ (_label, entry) => {
348
+ const { unresolved } = graphFor(entry);
349
+ expect(
350
+ unresolved,
351
+ `unresolvable relative imports — the walker cannot see past these, so a ` +
352
+ `forbidden import hidden behind one would read as clean: ${unresolved.join(", ")}`,
353
+ ).toEqual([]);
354
+ },
355
+ );
356
+
357
+ it.each(ENTRIES)(
358
+ "%s entry graph contains no statically unanalyzable import()/require()",
359
+ (_label, entry) => {
360
+ const { opaque } = graphFor(entry);
361
+ expect(
362
+ opaque,
363
+ `import()/require() with a non-literal specifier cannot be checked for ` +
364
+ `#4893 violations. Make it a literal, or extend this guard: ${opaque.join(", ")}`,
365
+ ).toEqual([]);
366
+ },
367
+ );
368
+
369
+ // The non-vacuity floor for every deny-list in this file (see
370
+ // REQUIRED_HEADLESS_MODULES). A subset check, so adding a module is free.
371
+ it("headless graph walk reaches the modules it must reach", () => {
372
+ const { seen, bareSpecs } = graphFor(headlessEntry);
373
+ const modules = rel(seen);
374
+ const missing = REQUIRED_HEADLESS_MODULES.filter(
375
+ (m) => !modules.includes(m),
376
+ );
377
+ expect(
378
+ missing,
379
+ `the walk did not reach ${missing.join(", ")} — every deny-list below is ` +
380
+ `then reasoning about a truncated graph and passes for the wrong reason. ` +
381
+ `Reached: ${modules.join(", ")}`,
382
+ ).toEqual([]);
383
+ const missingBare = REQUIRED_HEADLESS_BARE.filter((s) => !bareSpecs.has(s));
384
+ expect(
385
+ missingBare,
386
+ `no edge to ${missingBare.join(", ")} was harvested — the specifier ` +
387
+ `extractor is not seeing imports it must see`,
388
+ ).toEqual([]);
92
389
  });
93
390
 
94
- const { seen, bareSpecs } = walkGraph(headlessEntry);
391
+ // Replaces an EXACT pin of the resolved graph (module list + bare-specifier
392
+ // list, both `toEqual`). The pin's intent was a catch-all: any new edge,
393
+ // including a heavy dependency nobody has enumerated yet, had to be looked at
394
+ // deliberately. Its cost was that it also failed on innocent growth — a new
395
+ // first-party `src/` module, or a second import of an already-sanctioned
396
+ // package — putting a red check on unrelated PRs. A guard that fails on
397
+ // innocent changes gets deleted by the third person who hits it, and then it
398
+ // guards nothing, so the catch-all is expressed here as an allow-list over
399
+ // PACKAGES instead of a snapshot of MODULES: adding first-party modules is
400
+ // free, adding a third-party edge is not.
401
+ it("headless graph draws only on packages a consumer is guaranteed to have", () => {
402
+ const { seen, bareSpecs } = graphFor(headlessEntry);
403
+ const guaranteed = guaranteedPackages();
404
+ const unsanctioned = [...bareSpecs]
405
+ .filter((spec) => !guaranteed.has(packageNameOf(spec)))
406
+ .sort();
407
+ expect(
408
+ unsanctioned,
409
+ `the headless graph reaches package(s) a consumer is not guaranteed to ` +
410
+ `have installed: ${unsanctioned.join(", ")}. The headless entry's whole ` +
411
+ `promise is that it bundles with nothing stubbed, so an edge here must ` +
412
+ `be a dependency or a non-optional peer in package.json — add it there ` +
413
+ `deliberately (and mind #4893: heavy is still forbidden below), or drop ` +
414
+ `the import. Graph: ${rel(seen).join(", ")}`,
415
+ ).toEqual([]);
416
+ });
95
417
 
96
418
  it("does not pull chat/attachment native peer deps into its import graph", () => {
419
+ const { bareSpecs } = graphFor(headlessEntry);
97
420
  const leaked = FORBIDDEN_BARE.filter((dep) =>
98
421
  [...bareSpecs].some((s) => s === dep || s.startsWith(`${dep}/`)),
99
422
  );
@@ -104,6 +427,7 @@ describe("@copilotkit/react-native/headless entry", () => {
104
427
  });
105
428
 
106
429
  it("does not reach the chat UI / useAttachments modules", () => {
430
+ const { seen } = graphFor(headlessEntry);
107
431
  const reached = [...seen].filter((f) =>
108
432
  FORBIDDEN_LOCAL.some((name) =>
109
433
  path
@@ -114,38 +438,132 @@ describe("@copilotkit/react-native/headless entry", () => {
114
438
  );
115
439
  expect(
116
440
  reached,
117
- `headless graph must not reach: ${reached
118
- .map((f) => path.relative(srcDir, f))
119
- .join(", ")}`,
441
+ `headless graph must not reach: ${rel(reached).join(", ")}`,
120
442
  ).toEqual([]);
121
443
  });
122
444
 
123
- it("does export the provider + core headless hooks", async () => {
124
- const mod = await import("../headless");
125
- for (const name of [
126
- "CopilotKitProvider",
127
- "useCopilotKit",
128
- "useAgent",
129
- "useFrontendTool",
130
- "useRenderTool",
131
- "RenderToolProvider",
132
- ]) {
133
- expect(mod, `missing export: ${name}`).toHaveProperty(name);
134
- }
445
+ /**
446
+ * The four checks below need the entry EVALUATED, not just read: they assert
447
+ * that the named exports exist as runtime values (a re-export of a name that
448
+ * no longer exists is a runtime hole a static read cannot see). So the import
449
+ * stays — but it is paid exactly once, in a hook, rather than being raced by
450
+ * four tests against the default per-test budget.
451
+ *
452
+ * Why the budget below is what it is. Nothing here is hung or polling — the
453
+ * cost is a ONE-TIME module-graph load (resolve + transform + evaluate), paid
454
+ * per worker with no persistent transform cache, and it is the VARIANCE rather
455
+ * than the mean that broke the 5s default:
456
+ *
457
+ * - vitest.config.mjs sets `server.deps.inline: [/@copilotkit/]`, so the
458
+ * workspace dists this entry pulls are transformed rather than loaded
459
+ * natively: ~283 KB (core ~218 KB, react-core v2/headless ~55 KB, plus
460
+ * v2/context and shared), on top of the 11 RN source modules.
461
+ * - Measured on one dev machine: ~0.9–1.8s inside the full 22-file suite
462
+ * (n=8), ~0.7–1.1s for this file alone (n=8) — but 4568ms on the run
463
+ * straight after a cold `nx build`, i.e. 91% of the 5s budget, and the
464
+ * 4 independent agents who hit this hit it as an outright timeout. Bare
465
+ * Node `import()` of the equivalent prebuilt dist is 461ms, so the spread
466
+ * is resolve/transform and page-cache-cold I/O, both load-sensitive.
467
+ *
468
+ * So the budget is a CEILING for a cold, loaded or slower (CI) machine, NOT an
469
+ * expected duration: the happy path stays ~1s and every test below reports
470
+ * ~0ms. A genuinely hung import still fails, just not spuriously. Lowering it
471
+ * re-introduces the flake; lowering the COST would mean not inlining
472
+ * `@copilotkit/core` for this suite, which is a shared-config change affecting
473
+ * all 22 test files rather than something this file can do.
474
+ */
475
+ const IMPORT_BUDGET_MS = 60_000;
476
+
477
+ // Nested so the hook's failure domain covers ONLY the tests that need the
478
+ // module. Hoisting it to the top-level `describe` would let an import failure
479
+ // take down the fs-only graph tests above — the same collection-time
480
+ // blast-radius problem as blind spot #4, just moved into a hook.
481
+ describe("runtime export surface", () => {
482
+ let mod: typeof HeadlessEntry;
483
+
484
+ beforeAll(async () => {
485
+ mod = await import("../headless");
486
+ }, IMPORT_BUDGET_MS);
487
+
488
+ it("does export the provider + core headless hooks", () => {
489
+ for (const name of [
490
+ "CopilotKitProvider",
491
+ "useCopilotKit",
492
+ "useAgent",
493
+ "useFrontendTool",
494
+ "useRenderTool",
495
+ ]) {
496
+ expect(mod, `missing export: ${name}`).toHaveProperty(name);
497
+ }
498
+ });
499
+
500
+ it("exports the render-tool consumption hooks from the headless entry", () => {
501
+ // useRenderToolCall: renders a registered component on ANY surface, not
502
+ // just the chat (an in-car stage, a kiosk, a dashboard). useComponent: the
503
+ // controlled generative-UI primitive. Both come from react-core now.
504
+ for (const name of [
505
+ "useRenderToolCall",
506
+ "useComponent",
507
+ "useRenderTool",
508
+ ]) {
509
+ expect(mod, `missing export: ${name}`).toHaveProperty(name);
510
+ }
511
+ });
512
+
513
+ it("no longer exports the removed registry hook or its provider", () => {
514
+ // Both removed (BREAKING). Asserted so neither creeps back as a shim:
515
+ // useRenderToolRegistry cannot be honoured (core's renderers need
516
+ // name/toolCallId, so a derived Map would silently change the call
517
+ // signature), and RenderToolProvider has nothing left to provide now that
518
+ // registration goes to CopilotKitCoreReact.renderToolCalls.
519
+ for (const name of ["useRenderToolRegistry", "RenderToolProvider"]) {
520
+ expect(mod, `must not export: ${name}`).not.toHaveProperty(name);
521
+ }
522
+ });
523
+
524
+ it("does NOT re-export chat components or useAttachments from the headless entry", () => {
525
+ for (const name of [
526
+ "CopilotChat",
527
+ "CopilotModal",
528
+ "CopilotSidebar",
529
+ "CopilotPopup",
530
+ "useAttachments",
531
+ ]) {
532
+ expect(
533
+ mod,
534
+ `headless entry must not export: ${name}`,
535
+ ).not.toHaveProperty(name);
536
+ }
537
+ });
135
538
  });
136
539
 
137
- it("does NOT re-export chat components or useAttachments from the headless entry", async () => {
138
- const mod = await import("../headless");
139
- for (const name of [
140
- "CopilotChat",
141
- "CopilotModal",
142
- "CopilotSidebar",
143
- "CopilotPopup",
144
- "useAttachments",
145
- ]) {
146
- expect(mod, `headless entry must not export: ${name}`).not.toHaveProperty(
147
- name,
540
+ // Applies to BOTH entries: the fat-entry ban is package-wide, unlike the
541
+ // native-peer-dep ban above which only constrains the headless entry.
542
+ it.each(ENTRIES)(
543
+ "%s entry imports no react-core entry other than /v2/headless and /v2/context",
544
+ (_label, entry) => {
545
+ const { bareSpecs } = graphFor(entry);
546
+ const offenders = [...bareSpecs].filter(
547
+ (s) =>
548
+ s.startsWith("@copilotkit/react-core") &&
549
+ !ALLOWED_REACT_CORE_ENTRIES.includes(s),
148
550
  );
149
- }
150
- });
551
+ expect(
552
+ offenders,
553
+ `must import only ${ALLOWED_REACT_CORE_ENTRIES.join(" or ")} — found: ${offenders.join(", ")}. ` +
554
+ `Importing @copilotkit/react-core/v2 drags the shiki/mermaid/katex render stack into every RN bundle (#4893).`,
555
+ ).toEqual([]);
556
+ },
557
+ );
558
+
559
+ it.each(ENTRIES)(
560
+ "%s entry imports none of the heavy render stack directly",
561
+ (_label, entry) => {
562
+ const { bareSpecs } = graphFor(entry);
563
+ const leaked = FORBIDDEN_HEAVY.filter((dep) =>
564
+ [...bareSpecs].some((s) => s === dep || s.startsWith(`${dep}/`)),
565
+ );
566
+ expect(leaked, `must not import: ${leaked.join(", ")}`).toEqual([]);
567
+ },
568
+ );
151
569
  });
@@ -1,6 +1,9 @@
1
1
  import React from "react";
2
2
  import { render } from "@testing-library/react";
3
3
  import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
4
+ // Type-only (erased at runtime, so it does not defeat the vi.mock hoisting
5
+ // below): shapes the importOriginal() spread in the @copilotkit/shared mock.
6
+ import type * as CopilotKitShared from "@copilotkit/shared";
4
7
 
5
8
  // ─── Mocks ────────────────────────────────────────────────────────────────────
6
9
 
@@ -226,7 +229,15 @@ vi.mock("@gorhom/bottom-sheet", () => {
226
229
  };
227
230
  });
228
231
 
229
- vi.mock("@copilotkit/shared", () => ({
232
+ // Spread the real module rather than replacing it: `../headless` re-exports
233
+ // @copilotkit/core's runtime enums (ToolCallStatus / CopilotKitCoreErrorCode /
234
+ // CopilotKitCoreRuntimeConnectionStatus) as VALUES, so importing `../index`
235
+ // evaluates real @copilotkit/core, which named-imports RUNTIME_MODE_SSE and
236
+ // friends from @copilotkit/shared. A replace-everything factory has to restate
237
+ // every one of those or the import throws; only createLicenseContextValue needs
238
+ // stubbing here.
239
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
240
+ ...(await importOriginal<typeof CopilotKitShared>()),
230
241
  createLicenseContextValue: () => ({
231
242
  status: null,
232
243
  license: null,