@copilotkit/react-native 2.0.0-rc.26 → 2.0.0-rc.28

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.
@@ -1,6 +1,7 @@
1
1
  import React, {
2
2
  useCallback,
3
3
  useEffect,
4
+ useLayoutEffect,
4
5
  useMemo,
5
6
  useRef,
6
7
  useState,
@@ -19,11 +20,15 @@ import {
19
20
  import type { ListRenderItemInfo, ViewStyle } from "react-native";
20
21
  import { useAgent, useRenderToolCall } from "@copilotkit/react-core/headless";
21
22
  import { useCopilotKit } from "@copilotkit/react-core/context";
23
+ import {
24
+ ɵcreateChatSubmitter,
25
+ ɵgetToolResults,
26
+ ɵmessagesFingerprint,
27
+ } from "@copilotkit/core";
28
+ import type { CopilotKitCore } from "@copilotkit/core";
22
29
  import { AssistantMessage } from "./messages/AssistantMessage";
23
30
  import { UserMessage } from "./messages/UserMessage";
24
- import type { Message } from "@copilotkit/shared";
25
31
  import type { ToolMessage } from "@ag-ui/client";
26
- import { contentToText } from "@ag-ui/client";
27
32
 
28
33
  /** Shape of an assistant message with optional tool calls. */
29
34
  interface AssistantMessageShape {
@@ -78,179 +83,37 @@ interface ChatListItem {
78
83
  }
79
84
 
80
85
  /**
81
- * Lightweight content fingerprint for an agent's message list.
82
- *
83
- * The identity of `agent.messages` is NOT a reliable change signal, and it fails
84
- * in BOTH directions:
85
- *
86
- * - It changes on paths that have nothing to do with what is read below.
87
- * `@ag-ui/client`'s apply pipeline REASSIGNS the array
88
- * (`AbstractAgent.processApplyEvents` does `this.messages = applied.messages`),
89
- * so a streaming run hands down a fresh array — and fresh message, `toolCall`
90
- * and `function` objects — on every applied delta.
91
- * - It does NOT change on the paths these memos exist to serve. Core inserts
92
- * tool results by mutating in place —
93
- * `agent.messages.splice(insertAt, 0, toolMessage)`
94
- * (packages/core/src/core/run-handler.ts:931, :1080) —
95
- * `AbstractAgent.addMessage` is a `this.messages.push(...)`, and `useAgent`
96
- * re-renders with a bare `forceUpdate()` rather than a new array.
97
- *
98
- * (Grepping `packages/core/src` for a `.messages` assignment finds test files
99
- * only, but that proves nothing about identity: the reassignment lives in
100
- * `@ag-ui/client`, outside that tree.)
101
- *
102
- * So anything derived from messages must depend on their CONTENT, not on the
103
- * array reference.
104
- *
105
- * Captures exactly what the derivations below read — id, role, content size,
106
- * `toolCallId` (so an inserted tool result is visible), and each tool call's id
107
- * plus argument length (so streaming args advance).
108
- *
109
- * String and array content contribute their LENGTH rather than their value, so
110
- * large text and base64 attachment payloads are never re-serialized on every
111
- * render. Object content is the deliberate exception and IS serialized: a
112
- * length-based key is a constant 0 for every object, so an in-place content
113
- * replacement that keeps the same message id would otherwise be invisible to
114
- * every memo below.
115
- *
116
- * That object branch is convergence, not a fix for a reachable stale render: the
117
- * producer of same-id object content is an ACTIVITY_SNAPSHOT replace, and
118
- * `role: "activity"` never reaches `listItems`, which builds rows for `user` and
119
- * `assistant` only. It follows the SHAPE of react-core's `messagesMemoKey`
120
- * (react-core #6325). The two are independent implementations of the same idea —
121
- * a change to that key does not propagate here on its own, so treat this as a
122
- * documented parallel rather than a mirror.
123
- */
124
- function messagesFingerprint(messages: readonly unknown[]): string {
125
- return messages
126
- .map((msg) => {
127
- const m = msg as {
128
- id?: string;
129
- role?: string;
130
- content?: unknown;
131
- toolCallId?: string;
132
- toolCalls?: Array<{ id: string; function?: { arguments?: string } }>;
133
- };
134
- const content = m.content;
135
- const contentKey =
136
- typeof content === "string" || Array.isArray(content)
137
- ? content.length
138
- : content && typeof content === "object"
139
- ? objectContentKey(content)
140
- : 0;
141
- const toolCallsKey = Array.isArray(m.toolCalls)
142
- ? m.toolCalls
143
- .map((tc) => `${tc.id}:${tc.function?.arguments?.length ?? 0}`)
144
- .join(";")
145
- : "";
146
- return `${m.id}:${m.role}:${contentKey}:${m.toolCallId ?? ""}:${toolCallsKey}`;
147
- })
148
- .join(",");
149
- }
150
-
151
- /**
152
- * Serializes object content for the fingerprint above.
153
- *
154
- * Guarded because `JSON.stringify` THROWS on a circular structure and
155
- * `messagesFingerprint` runs on EVERY render, so a bare call would take the whole
156
- * chat down on content this component is explicitly required to tolerate —
157
- * `toolResultContent` below documents why non-string content reaches RN at all,
158
- * and "does not throw on tool content that cannot be JSON-serialised" pins that a
159
- * circular tool result must still render.
160
- *
161
- * The fallback is a constant, which means a circular object is invisible to the
162
- * memo exactly as every object used to be. That is the correct trade: it confines
163
- * the old always-equal behaviour to the pathological case instead of letting it
164
- * decide the common one. NOTE: this guard is a deliberate divergence from
165
- * react-core's `messagesMemoKey`, which stringifies unguarded.
166
- */
167
- function objectContentKey(content: object): string {
168
- try {
169
- return JSON.stringify(content) ?? "";
170
- } catch {
171
- return "[unserializable]";
172
- }
173
- }
174
-
175
- /**
176
- * Coerces a tool message's `content` to the `string` the renderer contract
177
- * requires (`ReactToolCallRenderer`'s Complete branch declares `result: string`)
178
- * WITHOUT inventing an empty result.
179
- *
180
- * AG-UI 1.0 models tool content as `string | ContentPart[]`: a plain string, or
181
- * an ordered list of typed parts (text, image, audio, video, document). A
182
- * string passes through; a list of parts is rendered as its text parts
183
- * concatenated — the flattening the spec permits for a string-only consumer —
184
- * and the media parts stay on the message for anything that can show them.
185
- * Neither is malformed, so neither warns.
186
- *
187
- * Anything else is only reachable from a producer that skipped validation —
188
- * restored thread history, a non-SSE transport, or app code casting on
189
- * `addMessage`. Core hedges against that case too (it accepts `unknown` content
190
- * and handles arrays of text parts), so this must not answer it with `""`: an
191
- * empty string is a LEGITIMATE tool result, which makes a dropped result
192
- * indistinguishable from an empty one. Serialise faithfully — the same
193
- * representation core uses for non-string results — and warn in dev.
86
+ * The core as the chat's submitter takes it, with a failed run also passed to
87
+ * `onRunError` so the chat can show it. The submitter logs the failure itself.
194
88
  */
195
- const MEDIA_PART_TYPES = new Set(["image", "audio", "video", "document"]);
196
-
197
- /**
198
- * Whether a value is one of the protocol's content parts: a text part with a
199
- * string `text`, or a media part with a `source` that names its kind and
200
- * value. Anything else — an array of typed records from restored history,
201
- * say — is not parts and keeps the serialise-and-warn path.
202
- */
203
- function isContentPart(part: unknown): boolean {
204
- if (typeof part !== "object" || part === null) return false;
205
- const record = part as { type?: unknown; text?: unknown; source?: unknown };
206
- if (record.type === "text") return typeof record.text === "string";
207
- if (typeof record.type !== "string" || !MEDIA_PART_TYPES.has(record.type))
208
- return false;
209
- const source = record.source as
210
- | { type?: unknown; value?: unknown; mimeType?: unknown }
211
- | undefined;
212
- if (typeof source !== "object" || source === null) return false;
213
- if (typeof source.value !== "string") return false;
214
- // Inline bytes need their type; a URL or a provider file handle (AG-UI 1.0
215
- // `file` source) may leave it out.
216
- if (source.type === "data") return typeof source.mimeType === "string";
217
- return (
218
- (source.type === "url" || source.type === "file") &&
219
- (source.mimeType === undefined || typeof source.mimeType === "string")
220
- );
221
- }
222
-
223
- function toolResultContent(content: unknown, toolCallId: string): string {
224
- if (typeof content === "string") return content;
225
-
226
- if (Array.isArray(content) && content.every(isContentPart)) {
227
- return contentToText(content as ToolMessage["content"]);
228
- }
229
-
230
- // null/undefined carry no payload, so "" loses nothing — but the message is
231
- // still malformed, so it warns below rather than passing silently.
232
- let serialized = "";
233
- if (content !== null && content !== undefined) {
234
- try {
235
- serialized =
236
- JSON.stringify(content) ?? Object.prototype.toString.call(content);
237
- } catch {
238
- // Circular or otherwise non-serialisable: keep SOMETHING over dropping
239
- // the result, and never throw from a render path.
240
- serialized = Object.prototype.toString.call(content);
241
- }
242
- }
243
-
244
- if (typeof __DEV__ === "undefined" || __DEV__) {
245
- console.warn(
246
- `[CopilotChat] Tool message for tool call "${toolCallId}" had non-string ` +
247
- `content (${content === null ? "null" : typeof content}), but renderers ` +
248
- `receive \`result: string\`. Rendering a serialized form instead of ` +
249
- `dropping it: ${serialized === "" ? "<empty>" : serialized}`,
250
- );
251
- }
252
-
253
- return serialized;
89
+ function withRunErrorReporting(
90
+ core: CopilotKitCore,
91
+ onRunError: (message: string) => void,
92
+ ): Parameters<typeof ɵcreateChatSubmitter>[0]["core"] {
93
+ return {
94
+ runAgent: async (params) => {
95
+ try {
96
+ return await core.runAgent(params);
97
+ } catch (err) {
98
+ onRunError(
99
+ err instanceof Error ? err.message : "An unexpected error occurred",
100
+ );
101
+ throw err;
102
+ }
103
+ },
104
+ stopAgent: (params) => core.stopAgent(params),
105
+ // This chat does not transcribe, but the submitter's core type covers it.
106
+ get runtimeUrl() {
107
+ return core.runtimeUrl;
108
+ },
109
+ get runtimeTransport() {
110
+ return core.runtimeTransport;
111
+ },
112
+ get credentials() {
113
+ return core.credentials;
114
+ },
115
+ resolveHeaders: () => core.resolveHeaders(),
116
+ };
254
117
  }
255
118
 
256
119
  /**
@@ -282,7 +145,6 @@ export function CopilotChat({
282
145
  const [inputText, setInputText] = useState("");
283
146
  const [error, setError] = useState<string | null>(null);
284
147
  const flatListRef = useRef<FlatList>(null);
285
- const messageIdCounter = useRef(0);
286
148
 
287
149
  const { copilotkit } = useCopilotKit();
288
150
  const { agent } = useAgent({ agentId: agentName });
@@ -306,34 +168,25 @@ export function CopilotChat({
306
168
  return () => subscription.unsubscribe();
307
169
  }, [copilotkit]);
308
170
 
309
- // Recomputed every render — cheap, and the only honest dependency for the
310
- // message-derived memos below. See `messagesFingerprint` for why the array
311
- // reference cannot be trusted as one.
312
- const messagesKey = messagesFingerprint(messages);
171
+ // Recomputed every render: cheap, and the only honest dependency for the
172
+ // message-derived memos below. The array reference does not track content
173
+ // in either direction: core inserts tool results with an in-place `splice`,
174
+ // `addMessage` pushes, and the AG-UI apply pipeline replaces the array on
175
+ // every streamed delta.
176
+ const messagesKey = ɵmessagesFingerprint(messages);
313
177
 
314
- // toolCallId -> tool result message. react-core's renderer reports
315
- // status "complete" with `result` when a tool message exists; RN's chat
316
- // previously never correlated these, so `result` was always undefined.
178
+ // toolCallId -> tool result message, so a renderer reports "complete" with
179
+ // its `result`.
317
180
  const toolMessages = useMemo(() => {
318
181
  const byId = new Map<string, ToolMessage>();
319
- for (const msg of messages) {
320
- const m = msg as {
321
- role?: string;
322
- id?: string;
323
- toolCallId?: string;
324
- content?: unknown;
325
- };
326
- if (m.role === "tool" && m.toolCallId) {
327
- byId.set(m.toolCallId, {
328
- id: m.id ?? m.toolCallId,
329
- role: "tool",
330
- toolCallId: m.toolCallId,
331
- content: toolResultContent(m.content, m.toolCallId),
332
- });
333
- }
182
+ for (const [toolCallId, message] of ɵgetToolResults(messages)) {
183
+ // A copy, so the tool-call renderer's memo sees content that was
184
+ // replaced in place on the same message. Core turns the content into
185
+ // the renderer's `result` string.
186
+ byId.set(toolCallId, { ...message });
334
187
  }
335
188
  return byId;
336
- // eslint-disable-next-line react-hooks/exhaustive-deps
189
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- keyed on message content, see messagesKey
337
190
  }, [messagesKey]);
338
191
 
339
192
  // Build flat list items from messages
@@ -385,7 +238,7 @@ export function CopilotChat({
385
238
  // in-place `splice` and `addMessage`'s push leave it untouched, while the
386
239
  // AG-UI apply pipeline replaces it on every delta. Without this, an
387
240
  // assistant message or tool call appended mid-run never reaches the list.
388
- // eslint-disable-next-line react-hooks/exhaustive-deps
241
+ // oxlint-disable-next-line react-hooks/exhaustive-deps -- keyed on message content, see messagesKey
389
242
  }, [messagesKey, isRunning]);
390
243
 
391
244
  // Id of the trailing row. renderItem needs "is this the last row?" to place
@@ -408,47 +261,46 @@ export function CopilotChat({
408
261
  [isRunning, lastItemId, renderToolCall, toolMessages],
409
262
  );
410
263
 
411
- // Shared logic for sending a message to the agent
412
- const sendMessage = useCallback(
413
- async (text: string) => {
414
- if (!text || isRunning || !agent) return;
415
-
416
- setError(null);
417
- onSendMessage?.(text);
418
-
419
- const id = `user-${++messageIdCounter.current}`;
420
- agent.addMessage({
421
- id,
422
- role: "user",
423
- content: text,
424
- } as Message);
425
-
426
- try {
427
- await copilotkit.runAgent({ agent });
428
- } catch (err) {
429
- const message =
430
- err instanceof Error ? err.message : "An unexpected error occurred";
431
- console.error("[CopilotChat] runAgent failed:", err);
432
- setError(message);
433
- }
434
- },
435
- [isRunning, agent, copilotkit, onSendMessage],
264
+ // The send side lives in core: it builds the message, waits for the run in
265
+ // flight, and runs the agent. A failed run also shows under the list.
266
+ const agentRef = useRef(agent);
267
+ const inputTextRef = useRef(inputText);
268
+ useLayoutEffect(() => {
269
+ agentRef.current = agent;
270
+ inputTextRef.current = inputText;
271
+ });
272
+ const [submitter] = useState(() =>
273
+ ɵcreateChatSubmitter({
274
+ core: withRunErrorReporting(copilotkit, setError),
275
+ getAgent: () => agentRef.current,
276
+ input: {
277
+ get: () => inputTextRef.current,
278
+ set: (value) => {
279
+ inputTextRef.current = value;
280
+ setInputText(value);
281
+ },
282
+ },
283
+ }),
436
284
  );
285
+ useEffect(() => () => submitter.showNotice(null), [submitter]);
437
286
 
438
287
  // Send from the input field
439
288
  const handleSend = useCallback(() => {
440
289
  const text = inputText.trim();
441
290
  if (!text) return;
442
- setInputText("");
443
- void sendMessage(text);
444
- }, [inputText, sendMessage]);
291
+ setError(null);
292
+ onSendMessage?.(text);
293
+ void submitter.submit(text);
294
+ }, [inputText, onSendMessage, submitter]);
445
295
 
446
- // Handle suggestion pill press
296
+ // Handle suggestion pill press. Leaves the typed text alone.
447
297
  const handleSuggestion = useCallback(
448
298
  (text: string) => {
449
- void sendMessage(text);
299
+ setError(null);
300
+ onSendMessage?.(text);
301
+ void submitter.selectSuggestion({ message: text, isLoading: false });
450
302
  },
451
- [sendMessage],
303
+ [onSendMessage, submitter],
452
304
  );
453
305
 
454
306
  // Auto-scroll when content changes
@@ -324,7 +324,7 @@ describe("CopilotChat", () => {
324
324
  expect(getByText("Network timeout")).toBeTruthy();
325
325
  });
326
326
 
327
- it("uses incrementing message IDs instead of Date.now()", async () => {
327
+ it("gives every sent message its own id", async () => {
328
328
  const { getByTestId } = render(<CopilotChat />);
329
329
  const input = getByTestId("text-input");
330
330
  const sendBtn = getByTestId("send-button");
@@ -344,7 +344,11 @@ describe("CopilotChat", () => {
344
344
  });
345
345
 
346
346
  const calls = hoisted.mockAgent.addMessage.mock.calls;
347
- expect(calls[0][0].id).toBe("user-1");
348
- expect(calls[1][0].id).toBe("user-2");
347
+ expect(calls.map(([message]) => message.content)).toEqual([
348
+ "first",
349
+ "second",
350
+ ]);
351
+ expect(calls[0][0].id).toEqual(expect.any(String));
352
+ expect(calls[0][0].id).not.toBe(calls[1][0].id);
349
353
  });
350
354
  });