@copilotkit/react-native 1.67.1 → 1.68.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.
- package/dist/chunk-C0xms8kb.cjs +34 -0
- package/dist/components/index.cjs +146 -33
- package/dist/components/index.cjs.map +1 -1
- package/dist/components/index.mjs +144 -32
- package/dist/components/index.mjs.map +1 -1
- package/dist/headless.cjs +40 -4
- package/dist/headless.d.cts +3 -3
- package/dist/headless.d.mts +3 -3
- package/dist/headless.mjs +5 -4
- package/dist/index.cjs +43 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +3 -4
- package/dist/index.mjs.map +1 -1
- package/dist/polyfills/encoding.cjs +1 -1
- package/dist/polyfills/streams.cjs +1 -1
- package/dist/useRenderTool-BBxnOOeJ.d.mts +161 -0
- package/dist/useRenderTool-BWo11PCL.d.cts +161 -0
- package/dist/{useRenderTool-DLavcsVB.cjs → useRenderTool-CKEPq7MQ.cjs} +20 -34
- package/dist/useRenderTool-CKEPq7MQ.cjs.map +1 -0
- package/dist/{useRenderTool-DUqpS97B.mjs → useRenderTool-l7M-I8rT.mjs} +18 -33
- package/dist/useRenderTool-l7M-I8rT.mjs.map +1 -0
- package/package.json +9 -6
- package/scripts/__tests__/fixtures/stray-react-dom-headless.js +16 -0
- package/scripts/__tests__/fixtures/tiny-headless.js +10 -0
- package/scripts/__tests__/fixtures/warning-headless.js +13 -0
- package/scripts/__tests__/measure-headless.test.mjs +275 -0
- package/scripts/measure-headless.mjs +310 -0
- package/src/CopilotKitProvider.tsx +1 -2
- package/src/__mocks__/test-copilotkit.tsx +116 -0
- package/src/__mocks__/tool-fixtures.ts +50 -0
- package/src/__tests__/headless-entry-surface.test.ts +464 -46
- package/src/__tests__/headless-integration.test.tsx +12 -1
- package/src/__tests__/headless-value-exports.test.ts +369 -0
- package/src/components/CopilotChat.tsx +218 -32
- package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +5 -126
- package/src/components/__tests__/CopilotChat.test.tsx +5 -49
- package/src/components/__tests__/CopilotChatToolCalls.test.tsx +468 -0
- package/src/headless.ts +36 -14
- package/src/hooks/__tests__/render-tool-call.integration.test.tsx +181 -0
- package/src/hooks/__tests__/useRenderTool.test.tsx +232 -267
- package/src/hooks/index.ts +1 -7
- package/src/hooks/render-tool-types.ts +55 -0
- package/src/hooks/useRenderTool.ts +29 -57
- package/src/index.ts +13 -5
- package/dist/RenderToolContext-CBNKcJqz.cjs +0 -126
- package/dist/RenderToolContext-CBNKcJqz.cjs.map +0 -1
- package/dist/RenderToolContext-D8M-JhD1.mjs +0 -75
- package/dist/RenderToolContext-D8M-JhD1.mjs.map +0 -1
- package/dist/useRenderTool-9YDIfZ0D.d.mts +0 -164
- package/dist/useRenderTool-BugVTDoM.d.cts +0 -164
- package/dist/useRenderTool-DLavcsVB.cjs.map +0 -1
- package/dist/useRenderTool-DUqpS97B.mjs.map +0 -1
- package/src/hooks/RenderToolContext.tsx +0 -150
- package/src/hooks/__tests__/RenderToolContext.test.tsx +0 -264
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
import * as headlessEntry from "../headless";
|
|
6
|
+
import * as barrelEntry from "../index";
|
|
7
|
+
import {
|
|
8
|
+
ToolCallStatus,
|
|
9
|
+
UseAgentUpdate,
|
|
10
|
+
CopilotKitCoreErrorCode,
|
|
11
|
+
CopilotKitCoreRuntimeConnectionStatus,
|
|
12
|
+
AbstractAgent,
|
|
13
|
+
} from "../headless";
|
|
14
|
+
import {
|
|
15
|
+
ToolCallStatus as BarrelToolCallStatus,
|
|
16
|
+
AbstractAgent as BarrelAbstractAgent,
|
|
17
|
+
} from "../index";
|
|
18
|
+
import type { RenderToolProps } from "../headless";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Guards the EXPORT KIND of `@copilotkit/react-native`'s two public entries:
|
|
22
|
+
* `src/headless.ts`, and the default barrel `src/index.ts` which republishes it
|
|
23
|
+
* via `export * from "./headless"`.
|
|
24
|
+
*
|
|
25
|
+
* ─── The defect class this exists to make unreintroducible ───────────────────
|
|
26
|
+
*
|
|
27
|
+
* `export type { X }` strips X's RUNTIME binding. For a genuine type that is
|
|
28
|
+
* correct. For a runtime value — an `enum`, a `class`, a function, a const — it
|
|
29
|
+
* silently deletes the value half of the API:
|
|
30
|
+
*
|
|
31
|
+
* - an enum's members become unnameable, and because an enum is ALSO the type
|
|
32
|
+
* of the field it annotates (and an enum-typed field rejects a bare string
|
|
33
|
+
* literal), there is then NO expression a consumer can compare that field
|
|
34
|
+
* against: `status === ToolCallStatus.Executing` fails `TS1362`, and
|
|
35
|
+
* `status === "executing"` fails `TS2322`. The field is unbranchable.
|
|
36
|
+
* - a class stops being subclassable (`extends`) and stops working with
|
|
37
|
+
* `instanceof`.
|
|
38
|
+
*
|
|
39
|
+
* Five symbols shipped this way from `src/headless.ts` — `ToolCallStatus`,
|
|
40
|
+
* `UseAgentUpdate`, `CopilotKitCoreErrorCode`,
|
|
41
|
+
* `CopilotKitCoreRuntimeConnectionStatus` and the `AbstractAgent` class — while
|
|
42
|
+
* the reference docs told consumers to import and branch on them. Nothing caught
|
|
43
|
+
* it: the package built, typechecked, linted and passed its suite, because
|
|
44
|
+
* NOTHING IN THIS PACKAGE CONSUMED ITS OWN ENTRY the way a consumer does.
|
|
45
|
+
*
|
|
46
|
+
* ─── Why the guard has to live here, in react-native ─────────────────────────
|
|
47
|
+
*
|
|
48
|
+
* `packages/react-core/src/v2/__tests__/headless-type-exports.test-d.ts` cannot
|
|
49
|
+
* cover this, structurally: it asserts against react-core's entry surface, not
|
|
50
|
+
* React Native's. Proof — react-core's own `UseAgentUpdate` was ALREADY a correct
|
|
51
|
+
* value export at the time RN's was wrong. Export kind is a property of the
|
|
52
|
+
* re-exporting module, so only a guard reading RN's own entry can observe it.
|
|
53
|
+
*
|
|
54
|
+
* ─── Why a RUNTIME test rather than a `.test-d.ts` ───────────────────────────
|
|
55
|
+
*
|
|
56
|
+
* A stripped export is an ABSENT MODULE BINDING, which is a first-class runtime
|
|
57
|
+
* observation (`mod.ToolCallStatus === undefined`). That makes a runtime test the
|
|
58
|
+
* direct instrument, and a hard one to fool: no `as`, no `@ts-expect-error` and
|
|
59
|
+
* no structural coincidence can make an absent binding look present, whereas a
|
|
60
|
+
* type-level assertion asserts a *consequence* and can drift from it. It also
|
|
61
|
+
* lets §2 below be self-extending, which a type-level test cannot be.
|
|
62
|
+
*
|
|
63
|
+
* This file is nonetheless BOTH. It lives under `src/`, so `tsc --noEmit`
|
|
64
|
+
* (`nx run @copilotkit/react-native:check-types`) compiles it too, and §3 type-
|
|
65
|
+
* checks the consumer-visible symptom. A regression therefore fails TWICE: in the
|
|
66
|
+
* suite (absent binding, with a message naming the fix) and at check-types
|
|
67
|
+
* (`TS1362`, naming the symbol).
|
|
68
|
+
*/
|
|
69
|
+
|
|
70
|
+
// ─── §1. The runtime-value contract, per symbol ──────────────────────────────
|
|
71
|
+
|
|
72
|
+
type ValueExport = {
|
|
73
|
+
/** Name as a consumer imports it from the entry (post-`as`). */
|
|
74
|
+
readonly name: string;
|
|
75
|
+
/** `typeof` the binding: an enum is an object, a class/function is a function. */
|
|
76
|
+
readonly typeOf: "object" | "function";
|
|
77
|
+
/** For an enum, one member that must be nameable — that is the point of a value export. */
|
|
78
|
+
readonly member?: string;
|
|
79
|
+
/** Declaration site, for the failure message. */
|
|
80
|
+
readonly declaredAs: string;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const RUNTIME_VALUE_EXPORTS: readonly ValueExport[] = [
|
|
84
|
+
{
|
|
85
|
+
name: "ToolCallStatus",
|
|
86
|
+
typeOf: "object",
|
|
87
|
+
member: "Executing",
|
|
88
|
+
declaredAs: "export enum, @copilotkit/core",
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
name: "CopilotKitCoreRuntimeConnectionStatus",
|
|
92
|
+
typeOf: "object",
|
|
93
|
+
member: "Connected",
|
|
94
|
+
declaredAs: "export enum, @copilotkit/core",
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
name: "CopilotKitCoreErrorCode",
|
|
98
|
+
typeOf: "object",
|
|
99
|
+
member: "TOOL_NOT_FOUND",
|
|
100
|
+
declaredAs: "export enum, @copilotkit/core",
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
name: "UseAgentUpdate",
|
|
104
|
+
typeOf: "object",
|
|
105
|
+
member: "OnMessagesChanged",
|
|
106
|
+
declaredAs: "export enum, @copilotkit/react-core/v2/headless",
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
name: "AbstractAgent",
|
|
110
|
+
typeOf: "function",
|
|
111
|
+
declaredAs: "declare abstract class, @ag-ui/client",
|
|
112
|
+
},
|
|
113
|
+
];
|
|
114
|
+
|
|
115
|
+
const howToFix = (file: string) =>
|
|
116
|
+
`Move it OUT of the \`export type { … }\` block in ${file}: ` +
|
|
117
|
+
'`export { X } from "…"`, or drop the inline `type ` prefix. ' +
|
|
118
|
+
"`export type` strips the runtime binding.";
|
|
119
|
+
|
|
120
|
+
const ENTRIES: readonly (readonly [
|
|
121
|
+
label: string,
|
|
122
|
+
file: string,
|
|
123
|
+
mod: Record<string, unknown>,
|
|
124
|
+
])[] = [
|
|
125
|
+
// src/headless.ts — where the export kind is declared.
|
|
126
|
+
[
|
|
127
|
+
"@copilotkit/react-native/headless",
|
|
128
|
+
"src/headless.ts",
|
|
129
|
+
headlessEntry as unknown as Record<string, unknown>,
|
|
130
|
+
],
|
|
131
|
+
// src/index.ts — `export * from "./headless"` forwards the KIND as well as the
|
|
132
|
+
// name, so a type-only re-export breaks this entry too. Asserted rather than
|
|
133
|
+
// assumed: the barrel could grow its own (mis-kinded) re-export at any time,
|
|
134
|
+
// in which case the fix belongs in src/index.ts instead.
|
|
135
|
+
[
|
|
136
|
+
"@copilotkit/react-native",
|
|
137
|
+
'src/headless.ts (via `export * from "./headless"` in src/index.ts)',
|
|
138
|
+
barrelEntry as unknown as Record<string, unknown>,
|
|
139
|
+
],
|
|
140
|
+
];
|
|
141
|
+
|
|
142
|
+
describe("react-native entries: runtime values are exported as VALUES", () => {
|
|
143
|
+
describe.each(ENTRIES)("%s", (label, file, mod) => {
|
|
144
|
+
it.each(RUNTIME_VALUE_EXPORTS.map((v) => [v.name, v] as const))(
|
|
145
|
+
"%s is a runtime binding, not a type-only re-export",
|
|
146
|
+
(name, spec) => {
|
|
147
|
+
const why =
|
|
148
|
+
`\`${name}\` is a runtime value (${spec.declaredAs}) but has NO binding on ` +
|
|
149
|
+
`"${label}". ${howToFix(file)}`;
|
|
150
|
+
|
|
151
|
+
expect(Object.keys(mod), why).toContain(name);
|
|
152
|
+
expect(typeof mod[name], why).toBe(spec.typeOf);
|
|
153
|
+
|
|
154
|
+
if (spec.member !== undefined) {
|
|
155
|
+
// An enum object whose members cannot be named is still unusable.
|
|
156
|
+
expect(
|
|
157
|
+
Object.keys(mod[name] as object),
|
|
158
|
+
`\`${name}.${spec.member}\` must be nameable by consumers of "${label}".`,
|
|
159
|
+
).toContain(spec.member);
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
);
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
// ─── §2. The self-extending half ─────────────────────────────────────────────
|
|
167
|
+
// §1 only knows about today's five symbols. This block needs no table: it reads
|
|
168
|
+
// the entry SOURCE, finds every symbol re-exported type-only, imports the module
|
|
169
|
+
// it came from, and fails if that module has a runtime binding for it. A future
|
|
170
|
+
// contributor who adds a new enum (or class, or const) re-export inside an
|
|
171
|
+
// `export type { … }` block is caught WITHOUT anyone updating §1.
|
|
172
|
+
|
|
173
|
+
const srcDir = path.resolve(__dirname, "..");
|
|
174
|
+
|
|
175
|
+
type ReExport = {
|
|
176
|
+
/** Name as declared in the source module (pre-`as`). */
|
|
177
|
+
readonly imported: string;
|
|
178
|
+
/** Name a consumer imports from the entry (post-`as`). */
|
|
179
|
+
readonly exported: string;
|
|
180
|
+
/** Module specifier it is re-exported from. */
|
|
181
|
+
readonly from: string;
|
|
182
|
+
readonly typeOnly: boolean;
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
// `export [type] { … } from "…"`, across newlines. The entry files are
|
|
186
|
+
// hand-written re-export barrels, so this covers their whole grammar. Comments
|
|
187
|
+
// are stripped from the file first, so a specifier list carrying a `//` note (as
|
|
188
|
+
// headless.ts does around UseAgentUpdate) still parses. `export * from "./x"`
|
|
189
|
+
// forwards kinds unchanged and needs no check of its own — §1 asserts the barrel
|
|
190
|
+
// namespace directly, and "./x" is itself an ENTRY_FILES member.
|
|
191
|
+
const reExportRe =
|
|
192
|
+
/export\s+(type\s+)?\{([\s\S]*?)\}\s*from\s*["']([^"']+)["']/g;
|
|
193
|
+
|
|
194
|
+
function stripComments(code: string): string {
|
|
195
|
+
return code.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, "");
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function parseReExports(file: string): ReExport[] {
|
|
199
|
+
const code = stripComments(fs.readFileSync(file, "utf8"));
|
|
200
|
+
const out: ReExport[] = [];
|
|
201
|
+
for (const m of code.matchAll(reExportRe)) {
|
|
202
|
+
const blockTypeOnly = Boolean(m[1]);
|
|
203
|
+
const from = m[3]!;
|
|
204
|
+
for (const raw of m[2]!.split(",")) {
|
|
205
|
+
const clause = raw.trim();
|
|
206
|
+
if (!clause) continue;
|
|
207
|
+
const inlineType = /^type\s+/.test(clause);
|
|
208
|
+
const parts = clause
|
|
209
|
+
.replace(/^type\s+/, "")
|
|
210
|
+
.split(/\s+as\s+/)
|
|
211
|
+
.map((s) => s.trim());
|
|
212
|
+
const imported = parts[0];
|
|
213
|
+
if (!imported) continue;
|
|
214
|
+
out.push({
|
|
215
|
+
imported,
|
|
216
|
+
exported: parts[1] ?? imported,
|
|
217
|
+
from,
|
|
218
|
+
typeOnly: blockTypeOnly || inlineType,
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Names that are a runtime value at their source but are DELIBERATELY
|
|
227
|
+
* re-exported type-only from an RN entry. Keep this empty unless there is a real
|
|
228
|
+
* reason: every name here is a value a consumer cannot reach.
|
|
229
|
+
*/
|
|
230
|
+
const INTENTIONALLY_TYPE_ONLY: ReadonlySet<string> = new Set<string>();
|
|
231
|
+
|
|
232
|
+
const ENTRY_FILES: readonly (readonly [label: string, file: string])[] = [
|
|
233
|
+
["src/headless.ts", path.join(srcDir, "headless.ts")],
|
|
234
|
+
["src/index.ts", path.join(srcDir, "index.ts")],
|
|
235
|
+
];
|
|
236
|
+
|
|
237
|
+
/** Mirrors the resolver in headless-entry-surface.test.ts. */
|
|
238
|
+
function resolveLocal(fromFile: string, spec: string): string {
|
|
239
|
+
const base = path.resolve(path.dirname(fromFile), spec);
|
|
240
|
+
for (const c of [
|
|
241
|
+
base,
|
|
242
|
+
`${base}.ts`,
|
|
243
|
+
`${base}.tsx`,
|
|
244
|
+
path.join(base, "index.ts"),
|
|
245
|
+
path.join(base, "index.tsx"),
|
|
246
|
+
]) {
|
|
247
|
+
if (fs.existsSync(c) && fs.statSync(c).isFile()) return c;
|
|
248
|
+
}
|
|
249
|
+
throw new Error(`cannot resolve local specifier "${spec}" from ${fromFile}`);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
describe("react-native entries: no runtime value is re-exported type-only", () => {
|
|
253
|
+
it.each(ENTRY_FILES)(
|
|
254
|
+
"%s",
|
|
255
|
+
async (label, file) => {
|
|
256
|
+
const reExports = parseReExports(file);
|
|
257
|
+
// A silently-rotted parser would make this test vacuously green.
|
|
258
|
+
expect(
|
|
259
|
+
reExports.length,
|
|
260
|
+
`parsed no re-exports out of ${label}: the parser in this file has rotted, so ` +
|
|
261
|
+
`this guard asserts nothing. Fix reExportRe / stripComments.`,
|
|
262
|
+
).toBeGreaterThan(10);
|
|
263
|
+
|
|
264
|
+
const offenders: string[] = [];
|
|
265
|
+
for (const re of reExports) {
|
|
266
|
+
if (!re.typeOnly) continue;
|
|
267
|
+
if (INTENTIONALLY_TYPE_ONLY.has(re.exported)) continue;
|
|
268
|
+
|
|
269
|
+
const spec = re.from.startsWith(".")
|
|
270
|
+
? resolveLocal(file, re.from)
|
|
271
|
+
: re.from;
|
|
272
|
+
let source: Record<string, unknown>;
|
|
273
|
+
try {
|
|
274
|
+
source = (await import(/* @vite-ignore */ spec)) as Record<
|
|
275
|
+
string,
|
|
276
|
+
unknown
|
|
277
|
+
>;
|
|
278
|
+
} catch (err) {
|
|
279
|
+
throw new Error(
|
|
280
|
+
`could not import "${re.from}" (re-exported from ${label}) to check the ` +
|
|
281
|
+
`export kind of \`${re.imported}\`: ` +
|
|
282
|
+
(err instanceof Error ? err.message : String(err)),
|
|
283
|
+
{ cause: err },
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
if (typeof source[re.imported] !== "undefined") {
|
|
287
|
+
offenders.push(
|
|
288
|
+
`${re.exported}${re.exported === re.imported ? "" : ` (as ${re.imported})`}` +
|
|
289
|
+
` — a runtime ${typeof source[re.imported]} in "${re.from}"`,
|
|
290
|
+
);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
expect(
|
|
295
|
+
offenders,
|
|
296
|
+
`${label} re-exports runtime value(s) with \`export type\`, which strips the ` +
|
|
297
|
+
`runtime binding:\n ${offenders.join("\n ")}\n${howToFix(label)}\n` +
|
|
298
|
+
`If one is genuinely meant to stay type-only, add its exported name to ` +
|
|
299
|
+
`INTENTIONALLY_TYPE_ONLY in this file, with a reason.`,
|
|
300
|
+
).toEqual([]);
|
|
301
|
+
},
|
|
302
|
+
30_000,
|
|
303
|
+
);
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
// ─── §3. Type-level half — compiled by `tsc --noEmit`, not asserted by vitest ─
|
|
307
|
+
// The consumer-visible symptom, as types. If any of the five regresses to
|
|
308
|
+
// `export type`, this block fails check-types with TS1362 naming the symbol,
|
|
309
|
+
// independently of §1/§2.
|
|
310
|
+
//
|
|
311
|
+
// Everything here is INSIDE the test bodies on purpose. `tsc` checks function
|
|
312
|
+
// bodies just the same, but a `class X extends AbstractAgent` (or a
|
|
313
|
+
// `ToolCallStatus.Executing`) at MODULE scope would throw while vitest is merely
|
|
314
|
+
// COLLECTING the file once the binding is stripped — taking §1 and §2 down with
|
|
315
|
+
// it and replacing their guided messages with a bare
|
|
316
|
+
// "Class extends value undefined". Keeping it lazy means a regression reports as
|
|
317
|
+
// five precise §1 failures plus a §2 offender list, and this block on top.
|
|
318
|
+
|
|
319
|
+
describe("react-native entries: runtime values are usable as values", () => {
|
|
320
|
+
it("branches a render-prop status against ToolCallStatus members", () => {
|
|
321
|
+
// The reported symptom. `RenderToolProps["status"]` is the `ToolCallStatus`
|
|
322
|
+
// enum type, so it rejects a bare `"executing"` literal too — without the
|
|
323
|
+
// value export there is no expression that compiles here at all.
|
|
324
|
+
//
|
|
325
|
+
// Read through an annotated signature so `status` keeps the full enum type
|
|
326
|
+
// instead of narrowing to the single member assigned, which would turn the
|
|
327
|
+
// comparisons below into TS2367 ("no overlap") rather than exercising them.
|
|
328
|
+
const readStatus = (): RenderToolProps<{ city: string }>["status"] =>
|
|
329
|
+
ToolCallStatus.InProgress;
|
|
330
|
+
const status = readStatus();
|
|
331
|
+
const branch: string =
|
|
332
|
+
status === ToolCallStatus.Executing
|
|
333
|
+
? "executing"
|
|
334
|
+
: status === BarrelToolCallStatus.Complete
|
|
335
|
+
? "complete"
|
|
336
|
+
: "other";
|
|
337
|
+
|
|
338
|
+
expect(branch).toBe("other");
|
|
339
|
+
});
|
|
340
|
+
|
|
341
|
+
it("names the enum members consumers pass and compare by value", () => {
|
|
342
|
+
// UseAgentUpdate is passed BY VALUE to useAgent's `updates` option;
|
|
343
|
+
// the other two are compared BY VALUE against error/connection fields.
|
|
344
|
+
const updates: UseAgentUpdate[] = [UseAgentUpdate.OnMessagesChanged];
|
|
345
|
+
const codes: string[] = [
|
|
346
|
+
CopilotKitCoreErrorCode.TOOL_NOT_FOUND,
|
|
347
|
+
CopilotKitCoreRuntimeConnectionStatus.Connected,
|
|
348
|
+
];
|
|
349
|
+
|
|
350
|
+
expect(updates).toEqual(["OnMessagesChanged"]);
|
|
351
|
+
expect(codes).toEqual(["tool_not_found", "connected"]);
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
it("subclasses AbstractAgent and matches it with instanceof", () => {
|
|
355
|
+
// AbstractAgent is the AG-UI extension point: `extends` and `instanceof`
|
|
356
|
+
// both need the runtime class. @ag-ui/client is a dependency (not a peer) of
|
|
357
|
+
// this package, so a consumer cannot reliably reach it any other way.
|
|
358
|
+
class GuardAgent extends AbstractAgent {
|
|
359
|
+
run(): never {
|
|
360
|
+
throw new Error("guard-only agent, never run");
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
const isAgent = (x: unknown): boolean => x instanceof BarrelAbstractAgent;
|
|
364
|
+
|
|
365
|
+
expect(new GuardAgent({ agentId: "guard" })).toBeInstanceOf(AbstractAgent);
|
|
366
|
+
expect(isAgent(new GuardAgent({ agentId: "guard" }))).toBe(true);
|
|
367
|
+
expect(isAgent({})).toBe(false);
|
|
368
|
+
});
|
|
369
|
+
});
|
|
@@ -9,15 +9,17 @@ import {
|
|
|
9
9
|
TextInput,
|
|
10
10
|
TouchableOpacity,
|
|
11
11
|
View,
|
|
12
|
-
type ListRenderItemInfo,
|
|
13
|
-
type ViewStyle,
|
|
14
12
|
} from "react-native";
|
|
15
|
-
import {
|
|
13
|
+
import type { ListRenderItemInfo, ViewStyle } from "react-native";
|
|
14
|
+
import {
|
|
15
|
+
useAgent,
|
|
16
|
+
useRenderToolCall,
|
|
17
|
+
} from "@copilotkit/react-core/v2/headless";
|
|
16
18
|
import { useCopilotKit } from "@copilotkit/react-core/v2/context";
|
|
17
19
|
import { AssistantMessage } from "./messages/AssistantMessage";
|
|
18
20
|
import { UserMessage } from "./messages/UserMessage";
|
|
19
|
-
import { useRenderToolRegistry } from "../hooks/RenderToolContext";
|
|
20
21
|
import type { Message } from "@copilotkit/shared";
|
|
22
|
+
import type { ToolMessage } from "@ag-ui/client";
|
|
21
23
|
|
|
22
24
|
/** Shape of an assistant message with optional tool calls. */
|
|
23
25
|
interface AssistantMessageShape {
|
|
@@ -71,6 +73,148 @@ interface ChatListItem {
|
|
|
71
73
|
}>;
|
|
72
74
|
}
|
|
73
75
|
|
|
76
|
+
/**
|
|
77
|
+
* Lightweight content fingerprint for an agent's message list.
|
|
78
|
+
*
|
|
79
|
+
* The identity of `agent.messages` is NOT a reliable change signal, and it fails
|
|
80
|
+
* in BOTH directions:
|
|
81
|
+
*
|
|
82
|
+
* - It changes on paths that have nothing to do with what is read below.
|
|
83
|
+
* `@ag-ui/client`'s apply pipeline REASSIGNS the array
|
|
84
|
+
* (`AbstractAgent.processApplyEvents` does `this.messages = applied.messages`),
|
|
85
|
+
* so a streaming run hands down a fresh array — and fresh message, `toolCall`
|
|
86
|
+
* and `function` objects — on every applied delta.
|
|
87
|
+
* - It does NOT change on the paths these memos exist to serve. Core inserts
|
|
88
|
+
* tool results by mutating in place —
|
|
89
|
+
* `agent.messages.splice(insertAt, 0, toolMessage)`
|
|
90
|
+
* (packages/core/src/core/run-handler.ts:931, :1080) —
|
|
91
|
+
* `AbstractAgent.addMessage` is a `this.messages.push(...)`, and `useAgent`
|
|
92
|
+
* re-renders with a bare `forceUpdate()` rather than a new array.
|
|
93
|
+
*
|
|
94
|
+
* (Grepping `packages/core/src` for a `.messages` assignment finds test files
|
|
95
|
+
* only, but that proves nothing about identity: the reassignment lives in
|
|
96
|
+
* `@ag-ui/client`, outside that tree.)
|
|
97
|
+
*
|
|
98
|
+
* So anything derived from messages must depend on their CONTENT, not on the
|
|
99
|
+
* array reference.
|
|
100
|
+
*
|
|
101
|
+
* Captures exactly what the derivations below read — id, role, content size,
|
|
102
|
+
* `toolCallId` (so an inserted tool result is visible), and each tool call's id
|
|
103
|
+
* plus argument length (so streaming args advance).
|
|
104
|
+
*
|
|
105
|
+
* String and array content contribute their LENGTH rather than their value, so
|
|
106
|
+
* large text and base64 attachment payloads are never re-serialized on every
|
|
107
|
+
* render. Object content is the deliberate exception and IS serialized: a
|
|
108
|
+
* length-based key is a constant 0 for every object, so an in-place content
|
|
109
|
+
* replacement that keeps the same message id would otherwise be invisible to
|
|
110
|
+
* every memo below.
|
|
111
|
+
*
|
|
112
|
+
* That object branch is convergence, not a fix for a reachable stale render: the
|
|
113
|
+
* producer of same-id object content is an ACTIVITY_SNAPSHOT replace, and
|
|
114
|
+
* `role: "activity"` never reaches `listItems`, which builds rows for `user` and
|
|
115
|
+
* `assistant` only. It follows the SHAPE of react-core's `messagesMemoKey`
|
|
116
|
+
* (react-core #6325). The two are independent implementations of the same idea —
|
|
117
|
+
* a change to that key does not propagate here on its own, so treat this as a
|
|
118
|
+
* documented parallel rather than a mirror.
|
|
119
|
+
*/
|
|
120
|
+
function messagesFingerprint(messages: readonly unknown[]): string {
|
|
121
|
+
return messages
|
|
122
|
+
.map((msg) => {
|
|
123
|
+
const m = msg as {
|
|
124
|
+
id?: string;
|
|
125
|
+
role?: string;
|
|
126
|
+
content?: unknown;
|
|
127
|
+
toolCallId?: string;
|
|
128
|
+
toolCalls?: Array<{ id: string; function?: { arguments?: string } }>;
|
|
129
|
+
};
|
|
130
|
+
const content = m.content;
|
|
131
|
+
const contentKey =
|
|
132
|
+
typeof content === "string" || Array.isArray(content)
|
|
133
|
+
? content.length
|
|
134
|
+
: content && typeof content === "object"
|
|
135
|
+
? objectContentKey(content)
|
|
136
|
+
: 0;
|
|
137
|
+
const toolCallsKey = Array.isArray(m.toolCalls)
|
|
138
|
+
? m.toolCalls
|
|
139
|
+
.map((tc) => `${tc.id}:${tc.function?.arguments?.length ?? 0}`)
|
|
140
|
+
.join(";")
|
|
141
|
+
: "";
|
|
142
|
+
return `${m.id}:${m.role}:${contentKey}:${m.toolCallId ?? ""}:${toolCallsKey}`;
|
|
143
|
+
})
|
|
144
|
+
.join(",");
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Serializes object content for the fingerprint above.
|
|
149
|
+
*
|
|
150
|
+
* Guarded because `JSON.stringify` THROWS on a circular structure and
|
|
151
|
+
* `messagesFingerprint` runs on EVERY render, so a bare call would take the whole
|
|
152
|
+
* chat down on content this component is explicitly required to tolerate —
|
|
153
|
+
* `toolResultContent` below documents why non-string content reaches RN at all,
|
|
154
|
+
* and "does not throw on tool content that cannot be JSON-serialised" pins that a
|
|
155
|
+
* circular tool result must still render.
|
|
156
|
+
*
|
|
157
|
+
* The fallback is a constant, which means a circular object is invisible to the
|
|
158
|
+
* memo exactly as every object used to be. That is the correct trade: it confines
|
|
159
|
+
* the old always-equal behaviour to the pathological case instead of letting it
|
|
160
|
+
* decide the common one. NOTE: this guard is a deliberate divergence from
|
|
161
|
+
* react-core's `messagesMemoKey`, which stringifies unguarded.
|
|
162
|
+
*/
|
|
163
|
+
function objectContentKey(content: object): string {
|
|
164
|
+
try {
|
|
165
|
+
return JSON.stringify(content) ?? "";
|
|
166
|
+
} catch {
|
|
167
|
+
return "[unserializable]";
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Coerces a tool message's `content` to the `string` the renderer contract
|
|
173
|
+
* requires (`ReactToolCallRenderer`'s Complete branch declares `result: string`)
|
|
174
|
+
* WITHOUT inventing an empty result.
|
|
175
|
+
*
|
|
176
|
+
* Tool content is a string by construction across the stack: `ToolMessageSchema`
|
|
177
|
+
* declares `content: z.string()`, the SSE transport zod-parses every
|
|
178
|
+
* TOOL_CALL_RESULT before it reaches `agent.messages`, and core stringifies
|
|
179
|
+
* non-string handler results itself (`JSON.stringify(result)` in run-handler)
|
|
180
|
+
* before inserting the tool message. Non-string content is only reachable from a
|
|
181
|
+
* producer that skipped that validation — restored thread history, a non-SSE
|
|
182
|
+
* transport, or app code casting on `addMessage`. Core hedges against exactly
|
|
183
|
+
* that case too (`normalizeToolResultContent` in run-handler accepts `unknown`
|
|
184
|
+
* and handles arrays of text parts), so this must not answer it with `""`:
|
|
185
|
+
* an empty string is a LEGITIMATE tool result, which makes a dropped result
|
|
186
|
+
* indistinguishable from an empty one. Serialise faithfully — the same
|
|
187
|
+
* representation core uses for non-string results — and warn in dev.
|
|
188
|
+
*/
|
|
189
|
+
function toolResultContent(content: unknown, toolCallId: string): string {
|
|
190
|
+
if (typeof content === "string") return content;
|
|
191
|
+
|
|
192
|
+
// null/undefined carry no payload, so "" loses nothing — but the message is
|
|
193
|
+
// still malformed, so it warns below rather than passing silently.
|
|
194
|
+
let serialized = "";
|
|
195
|
+
if (content !== null && content !== undefined) {
|
|
196
|
+
try {
|
|
197
|
+
serialized =
|
|
198
|
+
JSON.stringify(content) ?? Object.prototype.toString.call(content);
|
|
199
|
+
} catch {
|
|
200
|
+
// Circular or otherwise non-serialisable: keep SOMETHING over dropping
|
|
201
|
+
// the result, and never throw from a render path.
|
|
202
|
+
serialized = Object.prototype.toString.call(content);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (typeof __DEV__ === "undefined" || __DEV__) {
|
|
207
|
+
console.warn(
|
|
208
|
+
`[CopilotChat] Tool message for tool call "${toolCallId}" had non-string ` +
|
|
209
|
+
`content (${content === null ? "null" : typeof content}), but renderers ` +
|
|
210
|
+
`receive \`result: string\`. Rendering a serialized form instead of ` +
|
|
211
|
+
`dropping it: ${serialized === "" ? "<empty>" : serialized}`,
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
return serialized;
|
|
216
|
+
}
|
|
217
|
+
|
|
74
218
|
/**
|
|
75
219
|
* Full-screen chat UI component for React Native.
|
|
76
220
|
*
|
|
@@ -102,19 +246,43 @@ export function CopilotChat({
|
|
|
102
246
|
const flatListRef = useRef<FlatList>(null);
|
|
103
247
|
const messageIdCounter = useRef(0);
|
|
104
248
|
|
|
105
|
-
const { copilotkit
|
|
249
|
+
const { copilotkit } = useCopilotKit();
|
|
106
250
|
const { agent } = useAgent({ agentId: agentName });
|
|
107
251
|
|
|
108
252
|
const messages = agent.messages ?? [];
|
|
109
253
|
const isRunning = agent.isRunning;
|
|
110
254
|
|
|
111
|
-
const
|
|
255
|
+
const renderToolCall = useRenderToolCall();
|
|
112
256
|
|
|
113
|
-
//
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
257
|
+
// Recomputed every render — cheap, and the only honest dependency for the
|
|
258
|
+
// message-derived memos below. See `messagesFingerprint` for why the array
|
|
259
|
+
// reference cannot be trusted as one.
|
|
260
|
+
const messagesKey = messagesFingerprint(messages);
|
|
261
|
+
|
|
262
|
+
// toolCallId -> tool result message. react-core's renderer reports
|
|
263
|
+
// status "complete" with `result` when a tool message exists; RN's chat
|
|
264
|
+
// previously never correlated these, so `result` was always undefined.
|
|
265
|
+
const toolMessages = useMemo(() => {
|
|
266
|
+
const byId = new Map<string, ToolMessage>();
|
|
267
|
+
for (const msg of messages) {
|
|
268
|
+
const m = msg as {
|
|
269
|
+
role?: string;
|
|
270
|
+
id?: string;
|
|
271
|
+
toolCallId?: string;
|
|
272
|
+
content?: unknown;
|
|
273
|
+
};
|
|
274
|
+
if (m.role === "tool" && m.toolCallId) {
|
|
275
|
+
byId.set(m.toolCallId, {
|
|
276
|
+
id: m.id ?? m.toolCallId,
|
|
277
|
+
role: "tool",
|
|
278
|
+
toolCallId: m.toolCallId,
|
|
279
|
+
content: toolResultContent(m.content, m.toolCallId),
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return byId;
|
|
284
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
285
|
+
}, [messagesKey]);
|
|
118
286
|
|
|
119
287
|
// Build flat list items from messages
|
|
120
288
|
const listItems: ChatListItem[] = useMemo(() => {
|
|
@@ -160,7 +328,33 @@ export function CopilotChat({
|
|
|
160
328
|
}
|
|
161
329
|
|
|
162
330
|
return items;
|
|
163
|
-
|
|
331
|
+
// Same reasoning as `toolMessages`: keyed on message CONTENT, because the
|
|
332
|
+
// array reference does not track content in either direction — core's
|
|
333
|
+
// in-place `splice` and `addMessage`'s push leave it untouched, while the
|
|
334
|
+
// AG-UI apply pipeline replaces it on every delta. Without this, an
|
|
335
|
+
// assistant message or tool call appended mid-run never reaches the list.
|
|
336
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
337
|
+
}, [messagesKey, isRunning]);
|
|
338
|
+
|
|
339
|
+
// Id of the trailing row. renderItem needs "is this the last row?" to place
|
|
340
|
+
// the streaming indicator; deriving it here keeps that a named scalar instead
|
|
341
|
+
// of renderItem closing over `listItems` and index-reading its tail.
|
|
342
|
+
const lastItemId = useMemo(
|
|
343
|
+
() => listItems[listItems.length - 1]?.id,
|
|
344
|
+
[listItems],
|
|
345
|
+
);
|
|
346
|
+
|
|
347
|
+
// extraData defeats FlatList's PureComponent shallow-compare for the values
|
|
348
|
+
// renderItem CLOSES OVER, as opposed to the ones it receives per row. Those
|
|
349
|
+
// are exactly the four below, and they mirror renderItem's dependency array —
|
|
350
|
+
// keep the two in sync. `listItems` is deliberately absent: renderItem's only
|
|
351
|
+
// read of it is the tail id, now passed as `lastItemId`, and the array itself
|
|
352
|
+
// is already the `data` prop, which invalidates cells on its own (every
|
|
353
|
+
// rebuild allocates fresh item objects, so each cell's `item` prop differs).
|
|
354
|
+
const extraData = useMemo(
|
|
355
|
+
() => ({ isRunning, lastItemId, renderToolCall, toolMessages }),
|
|
356
|
+
[isRunning, lastItemId, renderToolCall, toolMessages],
|
|
357
|
+
);
|
|
164
358
|
|
|
165
359
|
// Shared logic for sending a message to the agent
|
|
166
360
|
const sendMessage = useCallback(
|
|
@@ -221,31 +415,23 @@ export function CopilotChat({
|
|
|
221
415
|
return (
|
|
222
416
|
<AssistantMessage
|
|
223
417
|
content={item.content ?? ""}
|
|
224
|
-
isLoading={
|
|
225
|
-
isRunning && item.id === listItems[listItems.length - 1]?.id
|
|
226
|
-
}
|
|
418
|
+
isLoading={isRunning && item.id === lastItemId}
|
|
227
419
|
/>
|
|
228
420
|
);
|
|
229
421
|
}
|
|
230
422
|
|
|
231
423
|
if (item.type === "tool-call" && item.toolCalls) {
|
|
232
424
|
const tc = item.toolCalls[0];
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
}
|
|
244
|
-
const status = executingToolCallIds.has(tc.id)
|
|
245
|
-
? "executing"
|
|
246
|
-
: "complete";
|
|
247
|
-
return renderer({ args, status });
|
|
248
|
-
}
|
|
425
|
+
// Partial-parses streaming args, resolves the renderer (exact name ->
|
|
426
|
+
// agent-scoped -> wildcard "*") and derives status — all in react-core,
|
|
427
|
+
// shared with web. Returns ReactElement | null, which is what
|
|
428
|
+
// renderItem requires.
|
|
429
|
+
const rendered = renderToolCall({
|
|
430
|
+
toolCall: tc,
|
|
431
|
+
toolMessage: toolMessages.get(tc.id),
|
|
432
|
+
});
|
|
433
|
+
if (rendered) return <>{rendered}</>;
|
|
434
|
+
|
|
249
435
|
// Subtle indicator for unregistered tool calls
|
|
250
436
|
return (
|
|
251
437
|
<View style={styles.toolCallIndicator}>
|
|
@@ -260,7 +446,7 @@ export function CopilotChat({
|
|
|
260
446
|
|
|
261
447
|
return null;
|
|
262
448
|
},
|
|
263
|
-
[isRunning,
|
|
449
|
+
[isRunning, lastItemId, renderToolCall, toolMessages],
|
|
264
450
|
);
|
|
265
451
|
|
|
266
452
|
const keyExtractor = useCallback((item: ChatListItem) => item.id, []);
|