@copilotkit/react-native 2.0.0-rc.5 → 2.0.0-rc.50

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 (113) hide show
  1. package/README.md +334 -2
  2. package/USAGE.md +382 -21
  3. package/dist/CopilotKitProvider-CBVQLdzn.d.cts +77 -0
  4. package/dist/{CopilotKitProvider-CE4bc6CP.mjs → CopilotKitProvider-CCBBonxr.mjs} +63 -43
  5. package/dist/CopilotKitProvider-CCBBonxr.mjs.map +1 -0
  6. package/dist/CopilotKitProvider-CtQg_0S-.d.mts +77 -0
  7. package/dist/{CopilotKitProvider-Byw3cqe2.cjs → CopilotKitProvider-QdcQrrSA.cjs} +69 -42
  8. package/dist/CopilotKitProvider-QdcQrrSA.cjs.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 +3 -2
  33. package/dist/headless.d.cts +3 -3
  34. package/dist/headless.d.mts +3 -3
  35. package/dist/headless.mjs +2 -2
  36. package/dist/index.cjs +132 -162
  37. package/dist/index.cjs.map +1 -1
  38. package/dist/index.d.cts +37 -19
  39. package/dist/index.d.mts +37 -19
  40. package/dist/index.mjs +131 -162
  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 +101 -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-alias-exports.test.ts +16 -0
  71. package/src/__tests__/copilotkit-provider.test.tsx +68 -73
  72. package/src/__tests__/generative-ui-harness.tsx +243 -0
  73. package/src/__tests__/generative-ui-provider-props.test-d.tsx +106 -0
  74. package/src/__tests__/generative-ui-rn-mock.tsx +54 -0
  75. package/src/__tests__/generative-ui-wiring.test.tsx +720 -0
  76. package/src/__tests__/generative-ui.test.tsx +1000 -0
  77. package/src/__tests__/headless-entry-surface.test.ts +979 -61
  78. package/src/__tests__/headless-integration.test.tsx +11 -1
  79. package/src/__tests__/use-attachments.test.ts +27 -2
  80. package/src/components/CopilotChat.tsx +106 -233
  81. package/src/components/CopilotModal.tsx +1 -1
  82. package/src/components/Markdown.tsx +4 -4
  83. package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +5 -1
  84. package/src/components/__tests__/CopilotChat.test.tsx +12 -4
  85. package/src/components/__tests__/CopilotChatInterrupt.test.tsx +208 -0
  86. package/src/components/__tests__/Markdown.code-alias.test.tsx +1 -1
  87. package/src/components/index.ts +6 -0
  88. package/src/components/messages/AssistantMessage.tsx +3 -3
  89. package/src/components/messages/TypingIndicator.tsx +4 -4
  90. package/src/generative-ui/GenerativeUIActivity.tsx +235 -0
  91. package/src/generative-ui/GenerativeUIProvider.tsx +171 -0
  92. package/src/generative-ui/GenerativeUISurface.tsx +303 -0
  93. package/src/generative-ui/host.tsx +138 -0
  94. package/src/generative-ui/index.ts +93 -0
  95. package/src/generative-ui/internal.ts +55 -0
  96. package/src/headless.ts +4 -0
  97. package/src/hooks/use-attachments.ts +95 -139
  98. package/src/index.ts +10 -4
  99. package/src/polyfills/__tests__/encoding-utf8.test.ts +112 -0
  100. package/src/polyfills/encoding.ts +160 -4
  101. package/src/types.d.ts +0 -13
  102. package/tsdown.config.ts +1 -0
  103. package/dist/CopilotKitProvider-BWjzCdHN.d.mts +0 -121
  104. package/dist/CopilotKitProvider-Btm10msB.d.cts +0 -121
  105. package/dist/CopilotKitProvider-Byw3cqe2.cjs.map +0 -1
  106. package/dist/CopilotKitProvider-CE4bc6CP.mjs.map +0 -1
  107. package/dist/Markdown-C6AsLHmd.mjs.map +0 -1
  108. package/dist/Markdown-C_9Re36O.cjs.map +0 -1
  109. package/dist/MarkdownRendererContext-BRNe808d.cjs +0 -72
  110. package/dist/streaming-fetch-Bm91EsRc.cjs +0 -225
  111. package/dist/streaming-fetch-Bm91EsRc.cjs.map +0 -1
  112. package/dist/streaming-fetch-Dm1oN4f2.mjs +0 -219
  113. package/dist/streaming-fetch-Dm1oN4f2.mjs.map +0 -1
@@ -17,11 +17,17 @@
17
17
  // natively, so asserting they are merely "defined" afterwards would pass on
18
18
  // an empty barrel; clearing them first is what makes the check honest. It
19
19
  // runs in a child process so the probe cannot poison this one.
20
- // - ESM is checked structurally. It cannot be executed here: the encoding
21
- // polyfill takes a named import from `text-encoding`, which is CommonJS.
22
- // Metro rewrites that to a require() and it works in React Native; bare
23
- // Node ESM refuses it. Asserting the five imports survive the bundler is
24
- // the part this file exists to protect.
20
+ // - ESM is checked structurally: the CJS run already proves that each
21
+ // polyfill installs its globals. Asserting the five imports survive the
22
+ // bundler is the part this file exists to protect.
23
+ //
24
+ // Then a third check, over every published code entry in package.json
25
+ // `exports` (all but the polyfill subpaths): the built import and require
26
+ // files must load the polyfill barrel before anything else. An app can import
27
+ // any entry first, and @copilotkit/core and @ag-ui/client fail at load time on
28
+ // Hermes without the polyfills. It reads dist/ because the bundler decides the
29
+ // emitted order: it hoisted a shared provider chunk above the root entry's
30
+ // `export * from "./headless"`, so the source order alone proved nothing.
25
31
  //
26
32
  // Invoked from package.json `build`, so a barrel that installs nothing fails
27
33
  // the build rather than reaching npm.
@@ -73,7 +79,7 @@ export function assertBuilt(distDir) {
73
79
 
74
80
  /**
75
81
  * Which polyfill modules the ESM barrel no longer imports. Pure; the ESM barrel
76
- * is read as text rather than executed (see the header note on text-encoding).
82
+ * is read as text rather than executed (see the header note).
77
83
  */
78
84
  export function missingEsmImports(esmSource) {
79
85
  return GROUPS.filter(
@@ -138,7 +144,111 @@ export function verifyBarrel(distDir) {
138
144
  return { ok, cjs, esmMissing };
139
145
  }
140
146
 
141
- export function formatReport({ cjs, esmMissing }) {
147
+ /**
148
+ * Export subpaths that are the polyfills themselves, or carry no code. Every
149
+ * other published entry loads @copilotkit/core or @ag-ui/client, which fail at
150
+ * load time on Hermes without the polyfills, so each must install them first:
151
+ * an app can import any entry before the root one.
152
+ */
153
+ const isPolyfillOrManifestExport = (key) =>
154
+ key === "./package.json" ||
155
+ key === "./polyfills" ||
156
+ key.startsWith("./polyfills/");
157
+
158
+ /** The first module an ESM file imports or re-exports, in order. */
159
+ export function firstEsmSpecifier(source) {
160
+ const m =
161
+ /^\s*(?:import\s*(?:[^;"'`]*?\bfrom\s*)?|export\s[^;"'`]*?\bfrom\s*)["'`]([^"'`]+)["'`]/m.exec(
162
+ source.replace(/\/\*[\s\S]*?\*\/|^\s*\/\/[^\n]*$/gm, ""),
163
+ );
164
+ return m ? m[1] : null;
165
+ }
166
+
167
+ /**
168
+ * The first module a CJS file requires, in order, skipping the bundler's own
169
+ * runtime helper chunk (rolldown's `chunk-*.cjs`: `__toESM` and friends, which
170
+ * requires nothing and touches no global).
171
+ */
172
+ export function firstCjsSpecifier(source) {
173
+ for (const m of source.matchAll(/\brequire\s*\(\s*(["'])([^"']+)\1\s*\)/g)) {
174
+ if (/(?:^|\/)chunk-[\w-]+\.cjs$/.test(m[2])) continue;
175
+ return m[2];
176
+ }
177
+ return null;
178
+ }
179
+
180
+ /**
181
+ * For every published code entry (from package.json `exports`), whether its
182
+ * BUILT import and require targets load the polyfill barrel before anything
183
+ * else. Checked in dist/, because the bundler decides the emitted order: a
184
+ * shared chunk can be hoisted above a re-export that installs the polyfills.
185
+ */
186
+ export function checkEntryOrder(packageDir) {
187
+ const manifestPath = path.join(packageDir, "package.json");
188
+ if (!existsSync(manifestPath)) {
189
+ throw new Error(`No package.json at ${manifestPath}.`);
190
+ }
191
+ const { exports: exportsMap } = JSON.parse(
192
+ readFileSync(manifestPath, "utf8"),
193
+ );
194
+ const results = [];
195
+ for (const [key, value] of Object.entries(exportsMap ?? {})) {
196
+ if (isPolyfillOrManifestExport(key)) continue;
197
+ const targets =
198
+ typeof value === "string" ? { import: value } : (value ?? {});
199
+ for (const [condition, target] of Object.entries(targets)) {
200
+ if (condition !== "import" && condition !== "require") continue;
201
+ const file = path.join(packageDir, target);
202
+ const cjs = file.endsWith(".cjs");
203
+ let expected = path
204
+ .relative(
205
+ path.dirname(file),
206
+ path.join(
207
+ packageDir,
208
+ "dist",
209
+ cjs ? "polyfills.cjs" : "polyfills.mjs",
210
+ ),
211
+ )
212
+ .split(path.sep)
213
+ .join("/");
214
+ if (!expected.startsWith(".")) expected = `./${expected}`;
215
+ if (!existsSync(file)) {
216
+ results.push({
217
+ entry: key,
218
+ file: target,
219
+ expected,
220
+ first: null,
221
+ ok: false,
222
+ error: "not built",
223
+ });
224
+ continue;
225
+ }
226
+ const source = readFileSync(file, "utf8");
227
+ const first = cjs ? firstCjsSpecifier(source) : firstEsmSpecifier(source);
228
+ results.push({
229
+ entry: key,
230
+ file: target,
231
+ expected,
232
+ first,
233
+ ok: first === expected,
234
+ });
235
+ }
236
+ }
237
+ return results;
238
+ }
239
+
240
+ /** The barrel check plus the entry-order check, for a built package. */
241
+ export function verifyPackage(packageDir) {
242
+ const barrel = verifyBarrel(path.join(packageDir, "dist"));
243
+ const entries = checkEntryOrder(packageDir);
244
+ return {
245
+ ...barrel,
246
+ entries,
247
+ ok: barrel.ok && entries.every((entry) => entry.ok),
248
+ };
249
+ }
250
+
251
+ export function formatReport({ cjs, esmMissing, entries = [] }) {
142
252
  const lines = cjs.map(
143
253
  (entry) =>
144
254
  `${entry.missing.length === 0 ? "PASS" : "FAIL"} cjs ${entry.group.padEnd(9)} ` +
@@ -150,10 +260,41 @@ export function formatReport({ cjs, esmMissing }) {
150
260
  `import "./polyfills/${group.name}.mjs"`,
151
261
  );
152
262
  }
263
+ for (const entry of entries) {
264
+ lines.push(
265
+ `${entry.ok ? "PASS" : "FAIL"} ${entry.file.padEnd(32)} ` +
266
+ `first loads ${entry.first ?? `(${entry.error ?? "nothing"})`}`,
267
+ );
268
+ }
153
269
  return lines.join("\n");
154
270
  }
155
271
 
156
- export function failureMessage({ cjs, esmMissing }) {
272
+ export function failureMessage({ cjs, esmMissing, entries = [] }) {
273
+ const misordered = entries.filter((entry) => !entry.ok);
274
+ if (
275
+ misordered.length &&
276
+ cjs.every((entry) => entry.missing.length === 0) &&
277
+ esmMissing.length === 0
278
+ ) {
279
+ return (
280
+ `A published entry does not install the polyfills before anything else.\n` +
281
+ misordered
282
+ .map(
283
+ (entry) =>
284
+ ` ${entry.file} (${entry.entry}) first loads ` +
285
+ `${entry.first ?? `(${entry.error ?? "nothing"})`}, expected ${entry.expected}`,
286
+ )
287
+ .join("\n") +
288
+ `\n\nAn app can import any entry before the root one, and on Hermes\n` +
289
+ `@copilotkit/core and @ag-ui/client fail at load time without the polyfills.\n` +
290
+ `Make \`import "./polyfills"\` (relative) the entry's first import, and list\n` +
291
+ `the entry's src and dist paths in package.json "sideEffects".`
292
+ );
293
+ }
294
+ return failureMessageForBarrel({ cjs, esmMissing }, misordered);
295
+ }
296
+
297
+ function failureMessageForBarrel({ cjs, esmMissing }, misordered) {
157
298
  const dropped = [
158
299
  ...cjs.flatMap((entry) => entry.missing),
159
300
  ...esmMissing.map((name) => `import "./polyfills/${name}.mjs"`),
@@ -163,7 +304,10 @@ export function failureMessage({ cjs, esmMissing }) {
163
304
  `Missing: ${dropped.join(", ")}\n\n` +
164
305
  `The side-effect imports in src/polyfills.ts were tree-shaken away. Check that\n` +
165
306
  `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.`
307
+ `globs that only match ./dist/** tell the bundler the src files are pure.` +
308
+ (misordered.length
309
+ ? `\n\nAlso misordered: ${misordered.map((entry) => entry.file).join(", ")}`
310
+ : "")
167
311
  );
168
312
  }
169
313
 
@@ -196,7 +340,7 @@ if (isEntrypoint(import.meta.url, process.argv[1])) {
196
340
  const jsonMode = process.argv.includes("--json");
197
341
  let report;
198
342
  try {
199
- report = verifyBarrel(path.join(packageRoot, "dist"));
343
+ report = verifyPackage(packageRoot);
200
344
  } catch (error) {
201
345
  if (jsonMode) {
202
346
  process.stdout.write(
@@ -214,7 +358,10 @@ if (isEntrypoint(import.meta.url, process.argv[1])) {
214
358
  process.stdout.write(formatReport(report) + "\n");
215
359
  if (!report.ok) process.stderr.write(`\n${failureMessage(report)}\n`);
216
360
  else
217
- process.stdout.write(`\nAll ${GROUPS.length} polyfill groups install.\n`);
361
+ process.stdout.write(
362
+ `\nAll ${GROUPS.length} polyfill groups install, and all ` +
363
+ `${report.entries.length} published entry files load them first.\n`,
364
+ );
218
365
  }
219
366
  process.exit(report.ok ? 0 : 1);
220
367
  }
@@ -3,14 +3,26 @@ import React, {
3
3
  useCallback,
4
4
  useContext,
5
5
  useEffect,
6
+ useLayoutEffect,
7
+ useMemo,
6
8
  useRef,
9
+ useState,
7
10
  } from "react";
8
11
  import type { ReactNode } from "react";
9
- import { useAgent } from "@copilotkit/react-core/headless";
12
+ import {
13
+ CopilotChatConfigurationProvider,
14
+ useAgent,
15
+ useCopilotChatConfiguration,
16
+ } from "@copilotkit/react-core/headless";
10
17
  import { useCopilotKit } from "@copilotkit/react-core/context";
11
- import { DEFAULT_AGENT_ID, randomUUID } from "@copilotkit/shared";
12
- import type { InputContent } from "@copilotkit/shared";
18
+ import { DEFAULT_AGENT_ID } from "@copilotkit/shared";
13
19
  import type { CopilotKitCoreErrorCode } from "@copilotkit/core";
20
+ import {
21
+ ɵChatConnection,
22
+ ɵFreshThreadId,
23
+ ɵcreateChatSubmitter,
24
+ ɵsubscribeToAgentErrors,
25
+ } from "@copilotkit/core";
14
26
  import { useAttachments } from "./hooks/use-attachments";
15
27
  import type { NativeAttachmentsConfig } from "./hooks/use-attachments";
16
28
  import type { Attachment } from "@copilotkit/shared";
@@ -35,9 +47,10 @@ export interface CopilotChatContextValue {
35
47
  /** Remove an attachment by ID. */
36
48
  removeAttachment: (id: string) => void;
37
49
  /**
38
- * Submit a message with optional attachments.
39
- * Handles consuming ready attachments, building InputContent[],
40
- * calling agent.addMessage, and running the agent.
50
+ * Submit a message with the ready attachments and run the agent. Waits
51
+ * for the thread's connection and for the run in flight. Blank text, and a
52
+ * send while an attachment uploads, are ignored. Resolves once the run has
53
+ * settled.
41
54
  */
42
55
  submitMessage: (text: string) => Promise<void>;
43
56
  }
@@ -67,7 +80,8 @@ export interface CopilotChatBaseProps {
67
80
  * The agent ID to use for this chat session.
68
81
  * Matches the web SDK's CopilotChat `agentId` prop.
69
82
  *
70
- * Resolution order: `agentId` > `agentName` > `"default"`
83
+ * Resolution order: `agentId` > `agentName` > the agent of the chat (or
84
+ * `CopilotChatConfigurationProvider`) around this one > `"default"`
71
85
  */
72
86
  agentId?: string;
73
87
 
@@ -78,15 +92,17 @@ export interface CopilotChatBaseProps {
78
92
  agentName?: string;
79
93
 
80
94
  /**
81
- * Thread ID for this chat session. When provided, the chat will resume
82
- * the specified thread. Matches the web SDK's CopilotChat `threadId` prop.
95
+ * Thread ID for this chat session. When provided, the chat restores the
96
+ * thread from the backend and reconnects to a run in progress. Without it,
97
+ * the chat uses the thread of the chat around it, or a new thread. Matches
98
+ * the web SDK's CopilotChat `threadId` prop.
83
99
  */
84
100
  threadId?: string;
85
101
 
86
102
  /**
87
103
  * Error handler scoped to this chat's agent. Fires in addition to the
88
- * provider-level onError (does not suppress it). Receives only errors
89
- * whose context.agentId matches this chat's agent.
104
+ * provider-level onError (does not suppress it). Receives errors whose
105
+ * context.agentId matches this chat's agent, and errors with no agentId.
90
106
  */
91
107
  onError?: (event: {
92
108
  error: Error;
@@ -130,6 +146,16 @@ export interface CopilotChatProps extends CopilotChatBaseProps {
130
146
  *
131
147
  * Children can access chat state via `useCopilotChatContext()`.
132
148
  *
149
+ * Hooks inside the chat, such as `useAgent` and `useInterrupt`, use this
150
+ * chat's agent when they do not pass an `agentId`. When the chat has a
151
+ * `threadId`, `useAgent` inside the chat sets that thread on each agent it
152
+ * returns, also on an agent that the hook names with its own `agentId`. Only
153
+ * `useAgent({ agentId, runtimeAgentId, threadId })` keeps a different thread.
154
+ *
155
+ * A chat inside another chat uses the outer chat's agent when it has no
156
+ * `agentId`. When the outer chat has a `threadId` and the inner chat does not,
157
+ * the inner chat uses the outer thread. The web `CopilotChat` does the same.
158
+ *
133
159
  * ```tsx
134
160
  * import { CopilotChat, useCopilotChatContext } from "@copilotkit/react-native";
135
161
  *
@@ -153,7 +179,11 @@ export function CopilotChat({
153
179
  children,
154
180
  ..._rest
155
181
  }: CopilotChatProps) {
156
- const resolvedAgentId = agentId ?? agentName ?? DEFAULT_AGENT_ID;
182
+ // Same precedence as the web CopilotChat: a chat that names no agent takes
183
+ // the agent of the chat configuration around it before "default".
184
+ const chatConfig = useCopilotChatConfiguration();
185
+ const resolvedAgentId =
186
+ agentId ?? agentName ?? chatConfig?.agentId ?? DEFAULT_AGENT_ID;
157
187
 
158
188
  // Deprecation warning (dev only, fires once per mount)
159
189
  const warnedRef = useRef(false);
@@ -172,17 +202,37 @@ export function CopilotChat({
172
202
  }
173
203
  }, [agentName, agentId]);
174
204
 
205
+ // Same thread rules as the web CopilotChat: the `threadId` prop, else the
206
+ // thread of the chat around this one, else a UUID minted for this chat.
207
+ // Only a thread a caller picked is "explicit" and restored from the backend.
208
+ const providedThreadId = threadId ?? chatConfig?.threadId;
209
+ const [freshThreadId] = useState(() => new ɵFreshThreadId());
210
+ const resolvedThreadId = useMemo(
211
+ () => freshThreadId.resolve(providedThreadId),
212
+ [freshThreadId, providedThreadId],
213
+ );
214
+ const hasExplicitThreadId = !!threadId || !!chatConfig?.hasExplicitThreadId;
215
+
175
216
  const { agent } = useAgent({ agentId: resolvedAgentId, throttleMs });
217
+ const { copilotkit } = useCopilotKit();
176
218
 
177
- // Set threadId on the agent when provided
219
+ // Keeps the agent on the thread this chat shows, restores a picked thread
220
+ // with a connect, and empties the agent on a switch to a fresh thread. Core
221
+ // owns the connect's abort and detach, as in the web chats.
222
+ const [connection] = useState(
223
+ () => new ɵChatConnection({ core: copilotkit }),
224
+ );
225
+ const { threads } = connection;
178
226
  useEffect(() => {
179
- if (threadId) {
180
- agent.threadId = threadId;
181
- }
182
- }, [agent, threadId]);
227
+ const handle = connection.open({
228
+ agent,
229
+ threadId: resolvedThreadId,
230
+ explicit: hasExplicitThreadId,
231
+ });
232
+ return () => handle.release();
233
+ }, [connection, agent, resolvedThreadId, hasExplicitThreadId]);
183
234
 
184
235
  // onError subscription -- forward core errors scoped to this chat's agent
185
- const { copilotkit } = useCopilotKit();
186
236
  const onErrorRef = useRef(onError);
187
237
  useEffect(() => {
188
238
  onErrorRef.current = onError;
@@ -190,26 +240,9 @@ export function CopilotChat({
190
240
 
191
241
  useEffect(() => {
192
242
  if (!onErrorRef.current) return;
193
-
194
- const subscription = copilotkit.subscribe({
195
- onError: (event) => {
196
- // Only forward errors that match this chat's agent
197
- if (
198
- event.context?.agentId === resolvedAgentId ||
199
- !event.context?.agentId
200
- ) {
201
- onErrorRef.current?.({
202
- error: event.error,
203
- code: event.code,
204
- context: event.context,
205
- });
206
- }
207
- },
208
- });
209
-
210
- return () => {
211
- subscription.unsubscribe();
212
- };
243
+ return ɵsubscribeToAgentErrors(copilotkit, resolvedAgentId, (event) =>
244
+ onErrorRef.current?.(event),
245
+ );
213
246
  }, [copilotkit, resolvedAgentId]);
214
247
 
215
248
  // Attachments
@@ -220,60 +253,39 @@ export function CopilotChat({
220
253
  removeAttachment,
221
254
  consumeAttachments,
222
255
  } = useAttachments({ config: attachmentsConfig });
256
+ // A send waits for the run in flight, so the submitter re-checks the
257
+ // upload guard against the latest attachments, not this render's.
258
+ const attachmentsRef = useRef(selectedAttachments);
259
+ useLayoutEffect(() => {
260
+ attachmentsRef.current = selectedAttachments;
261
+ });
223
262
 
224
- // Submit handler -- mirrors web CopilotChat.tsx lines 234-288
263
+ // The send side lives in core: the upload guard, the message content, and
264
+ // waiting for the thread's connection and the run in flight.
265
+ const agentRef = useRef(agent);
266
+ useLayoutEffect(() => {
267
+ agentRef.current = agent;
268
+ });
269
+ const [submitter] = useState(() =>
270
+ ɵcreateChatSubmitter({
271
+ core: copilotkit,
272
+ getAgent: () => agentRef.current,
273
+ // This chat renders no input box, so there is no text to clear or put
274
+ // back.
275
+ input: { get: () => "", set: () => {} },
276
+ attachments: {
277
+ isUploading: () =>
278
+ attachmentsRef.current.some((a) => a.status === "uploading"),
279
+ consumeReady: () => consumeAttachments(),
280
+ },
281
+ threads,
282
+ }),
283
+ );
284
+ // Clears the notice timer of a blocked send on unmount.
285
+ useEffect(() => () => submitter.showNotice(null), [submitter]);
225
286
  const submitMessage = useCallback(
226
- async (value: string) => {
227
- // Block if uploads in progress
228
- const hasUploading = selectedAttachments.some(
229
- (a) => a.status === "uploading",
230
- );
231
- if (hasUploading) {
232
- console.error(
233
- "[CopilotKit] Cannot send while attachments are uploading",
234
- );
235
- return;
236
- }
237
-
238
- const readyAttachments = consumeAttachments();
239
-
240
- if (readyAttachments.length > 0) {
241
- const contentParts: InputContent[] = [];
242
- if (value.trim()) {
243
- contentParts.push({ type: "text", text: value });
244
- }
245
- for (const att of readyAttachments) {
246
- contentParts.push({
247
- type: att.type,
248
- source: att.source,
249
- metadata: {
250
- ...(att.filename ? { filename: att.filename } : {}),
251
- ...att.metadata,
252
- },
253
- } as InputContent);
254
- }
255
- agent.addMessage({
256
- id: randomUUID(),
257
- role: "user",
258
- content: contentParts,
259
- });
260
- } else {
261
- agent.addMessage({
262
- id: randomUUID(),
263
- role: "user",
264
- content: value,
265
- });
266
- }
267
-
268
- try {
269
- await copilotkit.runAgent({ agent });
270
- } catch (error) {
271
- console.error("CopilotChat: runAgent failed", error);
272
- }
273
- },
274
- // copilotkit is intentionally excluded -- it is a stable ref that never changes.
275
- // eslint-disable-next-line react-hooks/exhaustive-deps
276
- [agent, selectedAttachments, consumeAttachments],
287
+ (value: string) => submitter.submit(value),
288
+ [submitter],
277
289
  );
278
290
 
279
291
  const contextValue: CopilotChatContextValue = {
@@ -287,9 +299,18 @@ export function CopilotChat({
287
299
  submitMessage,
288
300
  };
289
301
 
302
+ // Publish this chat's agent and thread to the subtree, as the web
303
+ // CopilotChat does. Hooks inside it that name no agent use this chat's
304
+ // agent, which is the outer chat's agent when this chat names none.
290
305
  return (
291
- <CopilotChatCtx.Provider value={contextValue}>
292
- {children}
293
- </CopilotChatCtx.Provider>
306
+ <CopilotChatConfigurationProvider
307
+ agentId={resolvedAgentId}
308
+ threadId={resolvedThreadId}
309
+ hasExplicitThreadId={hasExplicitThreadId}
310
+ >
311
+ <CopilotChatCtx.Provider value={contextValue}>
312
+ {children}
313
+ </CopilotChatCtx.Provider>
314
+ </CopilotChatConfigurationProvider>
294
315
  );
295
316
  }