@copilotkit/react-native 1.70.2 → 1.71.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/USAGE.md +76 -5
  2. package/dist/headless.cjs +1 -1
  3. package/dist/headless.d.cts +59 -3
  4. package/dist/headless.d.mts +59 -3
  5. package/dist/headless.mjs +1 -1
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +3 -3
  8. package/dist/index.d.mts +3 -3
  9. package/dist/index.mjs +1 -1
  10. package/dist/useRenderTool-DFz206nL.d.cts +149 -0
  11. package/dist/useRenderTool-DsCxzyAP.d.mts +149 -0
  12. package/dist/useRenderTool-L3Rw6SYD.cjs +298 -0
  13. package/dist/useRenderTool-L3Rw6SYD.cjs.map +1 -0
  14. package/dist/useRenderTool-pLM3upcs.mjs +285 -0
  15. package/dist/useRenderTool-pLM3upcs.mjs.map +1 -0
  16. package/package.json +4 -4
  17. package/src/__mocks__/test-copilotkit.tsx +14 -2
  18. package/src/__tests__/frontend-tool-render.test-d.tsx +148 -0
  19. package/src/__tests__/headless-entry-surface.test.ts +232 -2
  20. package/src/__tests__/headless-value-exports.test.ts +16 -5
  21. package/src/components/__tests__/CopilotChatToolCalls.test.tsx +26 -22
  22. package/src/headless.ts +79 -7
  23. package/src/hooks/__tests__/render-tool-call.integration.test.tsx +17 -15
  24. package/src/hooks/__tests__/useRenderTool.test.tsx +733 -202
  25. package/src/hooks/useRenderTool.ts +482 -49
  26. package/dist/useRenderTool-BBxnOOeJ.d.mts +0 -161
  27. package/dist/useRenderTool-BWo11PCL.d.cts +0 -161
  28. package/dist/useRenderTool-CKEPq7MQ.cjs +0 -162
  29. package/dist/useRenderTool-CKEPq7MQ.cjs.map +0 -1
  30. package/dist/useRenderTool-l7M-I8rT.mjs +0 -149
  31. package/dist/useRenderTool-l7M-I8rT.mjs.map +0 -1
  32. package/src/hooks/index.ts +0 -3
  33. package/src/hooks/render-tool-types.ts +0 -55
@@ -1,27 +1,62 @@
1
1
  import React from "react";
2
2
  import { act, render, waitFor } from "@testing-library/react";
3
- import { describe, it, expect, vi } from "vitest";
3
+ import { describe, it, expect, vi, beforeEach } from "vitest";
4
4
  import { z } from "zod";
5
-
6
- import { useRenderTool } from "../useRenderTool";
7
- import { useCopilotKit, useRenderToolCall } from "../../headless";
5
+ import { AbstractAgent } from "@ag-ui/client";
6
+ import type { RunAgentParameters, RunAgentResult } from "@ag-ui/client";
7
+
8
+ import {
9
+ useCopilotKit,
10
+ useRenderTool,
11
+ useRenderToolCall,
12
+ } from "../../headless";
8
13
  import type { CopilotKitContextValue } from "../../headless";
9
14
  import { TestCopilotKit } from "../../__mocks__/test-copilotkit";
15
+ import { __resetRenderToolShimWarnings } from "../useRenderTool";
10
16
 
11
17
  /**
12
- * `useRenderTool` is a THIN FORWARDER: every field it accepts is handed to
13
- * react-core's `useFrontendTool`, and every behaviour it claims is really that
14
- * hook's behaviour. So this suite must not mock `useFrontendTool` — an earlier
15
- * version did, and the double it substituted only modelled `name`/`render`.
16
- * Deleting the `deps`, `handler` and `agentId` forwarding from the hook left
17
- * that suite fully green: it could not detect a regression in any of the three
18
- * things the hook exists to forward.
18
+ * `useRenderTool` on `@copilotkit/react-native` is a DEPRECATED COMPATIBILITY
19
+ * SHIM over react-core's two hooks (`src/hooks/useRenderTool.ts`), scheduled
20
+ * for removal in the next minor. It registers nothing itself — every route
21
+ * delegates — and the delegation is asserted structurally in
22
+ * `src/__tests__/headless-entry-surface.test.ts` and behaviourally here.
23
+ *
24
+ * ─── What this file is for ───────────────────────────────────────────────────
25
+ *
26
+ * RN previously shipped a local `useRenderTool` whose entire body forwarded to
27
+ * react-core's `useFrontendTool` — core's OTHER hook, wearing this one's name.
28
+ * The two are not interchangeable, and the difference is exactly what a
29
+ * consumer gets billed for: `useFrontendTool` registers a TOOL (advertised to
30
+ * the model, callable by it) alongside its renderer, while `useRenderTool`
31
+ * registers a RENDERER ONLY. Under the alias, `name: "*"` — the documented way
32
+ * to spell "decorate every tool call that has no renderer of its own" —
33
+ * registered a frontend tool literally named `*`.
34
+ *
35
+ * Core never OFFERED that tool to the model: `buildFrontendTools` filters the
36
+ * name out of the list it hands the agent. What the registration did instead is
37
+ * claim core's catch-all HANDLER slot. When a tool call has no matching
38
+ * frontend tool and no result yet, core reaches for the `*` tool and runs
39
+ * `executeWildcardTool`, whose tool-result splice and follow-up return sit
40
+ * OUTSIDE its `if (wildcardTool?.handler)` guard. So a display-only wildcard —
41
+ * the thing the old hook's users were writing — auto-answered every
42
+ * otherwise-unanswered tool call with an EMPTY tool result and asked for
43
+ * another turn.
19
44
  *
20
- * Everything here therefore drives a REAL `CopilotKitCoreReact` through
21
- * `TestCopilotKit` (as the sibling `render-tool-call.integration.test.tsx`
22
- * does) and asserts on core's own observable behaviour — what `runTool`
23
- * executes, what `getTool` resolves, what actually paints — rather than on a
24
- * mock's call arguments.
45
+ * So the assertions below are about which core hook a given call shape reaches,
46
+ * and about the property that would silently regress if a local implementation
47
+ * ever re-grew under this name: the wildcard must register no TOOL, only a
48
+ * renderer.
49
+ *
50
+ * ─── Why nothing here is mocked ──────────────────────────────────────────────
51
+ *
52
+ * An earlier version of this suite mocked `useFrontendTool`, and the double it
53
+ * substituted modelled only `name`/`render`. Deleting whole fields from the
54
+ * hook under test left it fully green. Everything here therefore drives a REAL
55
+ * `CopilotKitCoreReact` through `TestCopilotKit` and asserts on core's own
56
+ * observable behaviour — what `getTool` resolves, what `runTool` executes, what
57
+ * core advertises on a run, what actually paints — never on a mock's call
58
+ * arguments. A hook that registered nothing at all could satisfy a mock; it
59
+ * cannot satisfy these.
25
60
  */
26
61
 
27
62
  type Core = CopilotKitContextValue["copilotkit"];
@@ -37,263 +72,759 @@ function CaptureCore({
37
72
  return null;
38
73
  }
39
74
 
40
- // ─── Registration basics ──────────────────────────────────────────────────────
75
+ /**
76
+ * Records the tool list core advertises on each run.
77
+ *
78
+ * "Advertised" is the claim that matters for a render-only registration, and it
79
+ * is not the same observation as "present in the registry": core builds the
80
+ * wire-level list inside `RunHandler.runAgent` (`buildFrontendTools`), which is
81
+ * private to core, so the only consumer-reachable vantage point is the agent's
82
+ * own `runAgent` input. Overriding `runAgent` (rather than `run`) stops the run
83
+ * at exactly that boundary: the input has been built, and no transport, event
84
+ * stream or follow-up turn is needed to read it.
85
+ */
86
+ class ToolListRecordingAgent extends AbstractAgent {
87
+ readonly advertised: string[][] = [];
41
88
 
42
- describe("useRenderTool", () => {
43
- it("registers the tool with react-core, name/description/schema intact", () => {
44
- const coreRef: { current: Core | null } = { current: null };
45
- const schema = z.object({ query: z.string() });
46
-
47
- function Probe() {
48
- useRenderTool({
49
- name: "searchLedger",
50
- description: "Search the ledger",
51
- parameters: schema,
52
- render: () => null,
53
- });
54
- return null;
55
- }
89
+ async runAgent(parameters?: RunAgentParameters): Promise<RunAgentResult> {
90
+ this.advertised.push((parameters?.tools ?? []).map((tool) => tool.name));
91
+ return { result: undefined, newMessages: [] };
92
+ }
56
93
 
57
- render(
94
+ run(): ReturnType<AbstractAgent["run"]> {
95
+ throw new Error("ToolListRecordingAgent.run() is not used in tests");
96
+ }
97
+ }
98
+
99
+ /** The single tool name each `render` call is asked to paint. */
100
+ const renderOneCall = (name: string, args = "{}") => ({
101
+ toolCall: {
102
+ id: "tc-1",
103
+ type: "function" as const,
104
+ function: { name, arguments: args },
105
+ },
106
+ });
107
+
108
+ // ─── The wildcard renderer ────────────────────────────────────────────────────
109
+
110
+ /**
111
+ * Registers `"*"` and paints one tool call of the caller's choosing, so a test
112
+ * can name a tool NOBODY registered a renderer for and still see output.
113
+ */
114
+ function WildcardProbe({ paints }: { paints: string }) {
115
+ useRenderTool(
116
+ {
117
+ name: "*",
118
+ render: ({ name, status }) => <>{`wildcard|${name}|${status}`}</>,
119
+ },
120
+ [],
121
+ );
122
+ const renderToolCall = useRenderToolCall();
123
+ return <>{renderToolCall(renderOneCall(paints))}</>;
124
+ }
125
+
126
+ describe("the wildcard renderer, registered through RN's entry", () => {
127
+ it("paints for a tool call that has no exact-name renderer", async () => {
128
+ const { container } = render(
58
129
  <TestCopilotKit messages={[]}>
59
- <CaptureCore into={coreRef} />
60
- <Probe />
130
+ <WildcardProbe paints="somethingNobodyRegistered" />
61
131
  </TestCopilotKit>,
62
132
  );
63
133
 
64
- const tool = coreRef.current!.getTool({ toolName: "searchLedger" });
65
- expect(tool).toBeDefined();
66
- expect(tool!.description).toBe("Search the ledger");
67
- expect(tool!.parameters).toBe(schema);
134
+ // Registration happens in an effect, so the first paint predates it; the
135
+ // renderer-registry subscription is what brings the text in.
136
+ await waitFor(() =>
137
+ expect(container.textContent).toBe(
138
+ "wildcard|somethingNobodyRegistered|inProgress",
139
+ ),
140
+ );
68
141
  });
69
- });
70
142
 
71
- describe("useRenderTool registry target", () => {
72
- it("registers its renderer into core's renderToolCalls, not a local map", () => {
73
- // The whole point of the convergence: one registry. react-core's
74
- // useRenderToolCall reads copilotkit.renderToolCalls, so a renderer that
75
- // does not land there renders nowhere outside RN's own chat.
143
+ it("registers NO frontend tool named `*`", async () => {
144
+ // The defect this exists for. RN's deleted hook forwarded to
145
+ // `useFrontendTool`, so `name: "*"` became a real frontend tool called `*` —
146
+ // which is core's catch-all HANDLER name. Core never advertised it, but the
147
+ // registration made core auto-answer every otherwise-unanswered tool call
148
+ // with an empty tool result and request a follow-up turn.
76
149
  const coreRef: { current: Core | null } = { current: null };
77
-
78
- function Probe() {
79
- useRenderTool({
80
- name: "showWeather",
81
- description: "Show weather",
82
- parameters: z.object({ city: z.string() }),
83
- render: () => null,
84
- });
85
- return null;
86
- }
150
+ const agent = new ToolListRecordingAgent();
87
151
 
88
152
  render(
89
- <TestCopilotKit messages={[]}>
153
+ <TestCopilotKit messages={[]} agent={agent}>
90
154
  <CaptureCore into={coreRef} />
91
- <Probe />
155
+ <WildcardProbe paints="somethingNobodyRegistered" />
92
156
  </TestCopilotKit>,
93
157
  );
158
+ const core = coreRef.current!;
94
159
 
95
- expect(coreRef.current!.renderToolCalls.map((r) => r.name)).toContain(
96
- "showWeather",
160
+ // Wait for the registration itself, so the assertions below are about a
161
+ // registered wildcard rather than about an effect that has not run yet.
162
+ await waitFor(() =>
163
+ expect(core.renderToolCalls.map((r) => r.name)).toContain("*"),
97
164
  );
165
+
166
+ // THESE TWO are the discriminating assertions: the tool REGISTRY is what
167
+ // the old hook actually polluted, so they are what fails if this route
168
+ // ever forwards to `useFrontendTool` again, the way the alias did.
169
+ expect(core.getTool({ toolName: "*" })).toBeUndefined();
170
+ expect(core.tools.map((t) => t.name)).not.toContain("*");
171
+
172
+ // The advertisement check below is a FORWARD GUARD, not a regression test.
173
+ // It cannot fail for the old defect: core's `buildFrontendTools` already
174
+ // filters `*` out of the advertised list, so `origin/main`'s hook — which
175
+ // did register the tool — recorded `[[]]` here too. What this pins is that
176
+ // nobody later makes `*` advertisable.
177
+ await act(async () => {
178
+ await core.runAgent({ agent });
179
+ });
180
+ // Spelled as the whole recording rather than as `not.toContain("*")`: the
181
+ // latter also passes when no run happened at all, and nothing else here
182
+ // registers a tool, so the exact expectation is one run advertising nothing.
183
+ expect(agent.advertised).toEqual([[]]);
98
184
  });
99
185
  });
100
186
 
101
- // ─── Forwarded concern: handler ───────────────────────────────────────────────
187
+ // ─── A render-only registration ───────────────────────────────────────────────
102
188
 
103
- describe("useRenderTool forwards handler", () => {
104
- it("runs the caller's handler when core executes the tool", async () => {
105
- // Observed through core's real execution path (`runTool` → the same
106
- // `executeToolHandler` an LLM-driven turn uses), not by inspecting the
107
- // registered object: a handler that is registered but never reached is
108
- // indistinguishable from a missing one to the app.
109
- const coreRef: { current: Core | null } = { current: null };
110
- const handler = vi.fn(
111
- async (args: { city: string }) => `sunny in ${args.city}`,
112
- );
189
+ /**
190
+ * Registers a renderer for `searchDocs` and paints a `searchDocs` call.
191
+ *
192
+ * `searchDocs` stands for a tool the SERVER owns: the frontend supplies its UI
193
+ * and nothing else. Nothing in this component registers a handler, and there is
194
+ * deliberately no way to — that is the hook's contract.
195
+ */
196
+ function ServerToolProbe() {
197
+ useRenderTool(
198
+ {
199
+ name: "searchDocs",
200
+ parameters: z.object({ query: z.string() }),
201
+ render: ({ status, parameters }) => (
202
+ <>{`${status}|${parameters.query ?? ""}`}</>
203
+ ),
204
+ },
205
+ [],
206
+ );
207
+ const renderToolCall = useRenderToolCall();
208
+ return (
209
+ <>{renderToolCall(renderOneCall("searchDocs", '{"query":"invoices"}'))}</>
210
+ );
211
+ }
113
212
 
114
- function Probe() {
115
- useRenderTool({
116
- name: "getWeather",
117
- description: "Get weather",
118
- parameters: z.object({ city: z.string() }),
119
- render: () => null,
120
- handler,
121
- });
122
- return null;
123
- }
213
+ describe("a render-only registration", () => {
214
+ it("does not produce a callable tool", async () => {
215
+ const coreRef: { current: Core | null } = { current: null };
124
216
 
125
217
  render(
126
218
  <TestCopilotKit messages={[]}>
127
219
  <CaptureCore into={coreRef} />
128
- <Probe />
220
+ <ServerToolProbe />
129
221
  </TestCopilotKit>,
130
222
  );
223
+ const core = coreRef.current!;
224
+
225
+ await waitFor(() =>
226
+ expect(core.renderToolCalls.map((r) => r.name)).toContain("searchDocs"),
227
+ );
131
228
 
132
- let outcome: Awaited<ReturnType<Core["runTool"]>> | undefined;
229
+ expect(core.getTool({ toolName: "searchDocs" })).toBeUndefined();
230
+ // Asserted through core's real execution path, not just the lookup: a tool
231
+ // that resolves but cannot run, and one that was never registered, are
232
+ // different failures and only this tells them apart.
233
+ await expect(
234
+ core.runTool({ name: "searchDocs", parameters: { query: "invoices" } }),
235
+ ).rejects.toThrow("Tool not found: searchDocs");
236
+ });
237
+
238
+ it("does not shadow a same-named server tool — it paints the call and advertises nothing", async () => {
239
+ // The two halves of "not shadowing", together. If registering a renderer
240
+ // also registered a tool, the client would claim `searchDocs` on the wire
241
+ // and the runtime would route the call to a frontend handler that does not
242
+ // exist, instead of to the server tool that owns the name.
243
+ const coreRef: { current: Core | null } = { current: null };
244
+ const agent = new ToolListRecordingAgent();
245
+
246
+ const { container } = render(
247
+ <TestCopilotKit messages={[]} agent={agent}>
248
+ <CaptureCore into={coreRef} />
249
+ <ServerToolProbe />
250
+ </TestCopilotKit>,
251
+ );
252
+ const core = coreRef.current!;
253
+
254
+ // Half one: the server's call still gets the frontend's UI.
255
+ await waitFor(() =>
256
+ expect(container.textContent).toBe("inProgress|invoices"),
257
+ );
258
+
259
+ // Half two: nothing named `searchDocs` goes out with the run.
133
260
  await act(async () => {
134
- outcome = await coreRef.current!.runTool({
135
- name: "getWeather",
136
- parameters: { city: "Berlin" },
137
- });
261
+ await core.runAgent({ agent });
138
262
  });
139
-
140
- expect(handler).toHaveBeenCalledTimes(1);
141
- expect(handler.mock.calls[0]![0]).toEqual({ city: "Berlin" });
142
- // Core writes the handler's return value into the tool result. Drop the
143
- // forwarding and this is the empty string a handler-less tool produces.
144
- expect(outcome!.result).toBe("sunny in Berlin");
263
+ expect(agent.advertised).toEqual([[]]);
145
264
  });
146
265
  });
147
266
 
148
- // ─── Forwarded concern: agentId ───────────────────────────────────────────────
267
+ // ─── agentId on a render-only registration ────────────────────────────────────
149
268
 
150
- describe("useRenderTool forwards agentId", () => {
151
- it("scopes the tool and its renderer to that agent, not globally", () => {
152
- const coreRef: { current: Core | null } = { current: null };
269
+ /** Registers an `escalate` renderer scoped to `support`, then paints `escalate`. */
270
+ function ScopedProbe() {
271
+ useRenderTool(
272
+ {
273
+ name: "escalate",
274
+ parameters: z.object({ reason: z.string() }),
275
+ agentId: "support",
276
+ render: ({ name }) => <>{`scoped|${name}`}</>,
277
+ },
278
+ [],
279
+ );
280
+ const renderToolCall = useRenderToolCall();
281
+ return <>{renderToolCall(renderOneCall("escalate"))}</>;
282
+ }
153
283
 
154
- function Probe() {
155
- useRenderTool({
156
- name: "escalate",
157
- description: "Escalate to a human",
158
- parameters: z.object({ reason: z.string() }),
159
- render: () => null,
160
- agentId: "support",
161
- });
162
- return null;
163
- }
284
+ describe("agentId on a render-only registration", () => {
285
+ it("PINS the limitation: a scoped renderer still paints under a different agent", async () => {
286
+ // `agentId` keys the renderer entry (`${agentId}:${name}`) so a scoped and a
287
+ // global renderer of the same name can coexist — but RESOLUTION does not
288
+ // enforce it: `useRenderToolCall` prefers an agentId match and then falls
289
+ // back to any same-named entry, deliberately ("we show all tool calls
290
+ // regardless of agentId"). Here the only `escalate` renderer is scoped to
291
+ // `support` while the chat resolves under the default agent, and it paints
292
+ // anyway.
293
+ //
294
+ // Pinned rather than fixed, and stated as a LIMITATION rather than as
295
+ // scoping: the predecessor of this test was named for the scoping claim,
296
+ // checked `getTool` and `renderer.agentId` instead, and so asserted the
297
+ // opposite of the behaviour while staying green.
298
+ const coreRef: { current: Core | null } = { current: null };
164
299
 
165
- render(
300
+ const { container } = render(
166
301
  <TestCopilotKit messages={[]}>
167
302
  <CaptureCore into={coreRef} />
168
- <Probe />
303
+ <ScopedProbe />
169
304
  </TestCopilotKit>,
170
305
  );
171
306
 
172
- const core = coreRef.current!;
307
+ await waitFor(() => expect(container.textContent).toBe("scoped|escalate"));
173
308
 
174
- // Reachable for the agent it was scoped to …
175
- expect(
176
- core.getTool({ toolName: "escalate", agentId: "support" }),
177
- ).toBeDefined();
178
-
179
- // … and NOT as a global tool. This is the assertion that bites: core's
180
- // `getTool` falls back to global tools only when `tool.agentId` is unset,
181
- // so a dropped agentId turns a scoped tool into one every agent can call.
182
- expect(core.getTool({ toolName: "escalate" })).toBeUndefined();
183
-
184
- // The renderer half is keyed `${agentId}:${name}`, which is what lets a
185
- // scoped renderer coexist with a global one of the same name.
186
- const renderer = core.renderToolCalls.find((r) => r.name === "escalate");
187
- expect(renderer).toBeDefined();
188
- expect(renderer!.agentId).toBe("support");
309
+ // The scoping that IS real: the entry records the agent it was filed under.
310
+ const renderer = coreRef.current!.renderToolCalls.find(
311
+ (r) => r.name === "escalate",
312
+ );
313
+ expect(renderer?.agentId).toBe("support");
189
314
  });
190
315
  });
191
316
 
192
- // ─── Forwarded concern: deps ──────────────────────────────────────────────────
317
+ // ─── The routing rules of the compatibility shim ──────────────────────────────
193
318
 
194
319
  /**
195
- * Paints whatever `label` the renderer captured at registration time, through
196
- * react-core's real `useRenderToolCall`. The render closure is deliberately
197
- * stale-able: `useFrontendTool` captures it in an effect, so the painted text
198
- * only changes when that effect re-runs.
320
+ * The three rules `src/hooks/useRenderTool.ts` implements, each asserted on
321
+ * core's OWN observable state rather than on a spy's call arguments:
322
+ *
323
+ * 1. `name === "*"` wins UNCONDITIONALLY -> core's `useRenderTool`
324
+ * (renderer-only, wildcard path), whatever else was supplied.
325
+ * 2. otherwise `handler` or `description` present -> core's `useFrontendTool`
326
+ * (tool AND renderer), which is what the old RN hook actually did.
327
+ * 3. otherwise -> core's `useRenderTool`.
328
+ *
329
+ * Rule 1 is the load-bearing one and it is deliberately not the obvious
330
+ * reading. The old RN hook made `description` REQUIRED, so every wildcard
331
+ * renderer anyone ever wrote carries the old tool fields; routing "has old
332
+ * fields" to `useFrontendTool` would recreate the `*`-named-tool bug for exactly
333
+ * the people who had tried hardest to use the wildcard.
334
+ *
335
+ * Each probe uses a tool name no other test in this file uses, because the
336
+ * shim's deprecation warning is deduped per tool name for the lifetime of the
337
+ * module.
199
338
  */
200
- function LabelProbe({
201
- label,
202
- deps,
203
- }: {
204
- label: string;
205
- deps: ReadonlyArray<unknown>;
206
- }) {
339
+
340
+ /**
341
+ * Rule 1: a wildcard call carrying the OLD tool fields — the only shape the old
342
+ * hook's required `description` allowed.
343
+ */
344
+ function LegacyWildcardProbe({ paints }: { paints: string }) {
207
345
  useRenderTool(
208
346
  {
209
- name: "showLabel",
210
- description: "Show a label",
211
- parameters: z.object({}),
212
- render: () => <>{label}</>,
347
+ name: "*",
348
+ description: "renders every tool call nothing else claims",
349
+ parameters: z.object({ anything: z.string() }),
350
+ handler: async () => "should never be registered, let alone run",
351
+ render: ({ name, status }) => <>{`legacy-wildcard|${name}|${status}`}</>,
213
352
  },
214
- deps,
353
+ [],
215
354
  );
216
355
  const renderToolCall = useRenderToolCall();
217
- return (
218
- <>
219
- {renderToolCall({
220
- toolCall: {
221
- id: "tc-label",
222
- type: "function",
223
- function: { name: "showLabel", arguments: "{}" },
224
- },
225
- })}
226
- </>
227
- );
356
+ return <>{renderToolCall(renderOneCall(paints))}</>;
228
357
  }
229
358
 
230
- /**
231
- * A dep array holding a FRESH function identity on every call. `JSON.stringify`
232
- * flattens it to the constant `"[null]"`, so `useFrontendTool` can never see it
233
- * change however often the caller re-renders.
234
- */
235
- const freshNonSerialisableDeps = (): ReadonlyArray<unknown> => [
236
- () => "callback",
237
- ];
238
-
239
- describe("useRenderTool forwards deps", () => {
240
- it("re-registers the render closure when a dep changes", async () => {
241
- // The hook's own JSDoc promises exactly this: values a render closes over
242
- // must be passed in `deps` or the chat keeps painting the stale closure.
243
- // Without the forwarding, `useFrontendTool` sees an empty dep array, its
244
- // effect never re-runs, and "before" is painted forever.
245
- const { container, rerender } = render(
246
- <TestCopilotKit messages={[]}>
247
- <LabelProbe label="before" deps={["before"]} />
359
+ describe('rule 1: `name: "*"` wins unconditionally', () => {
360
+ it("paints as a fallback renderer and registers NO tool named `*`", async () => {
361
+ // The regression rule 1 exists to prevent. Under the old hook this exact
362
+ // call shape registered a frontend tool literally named `*` — claiming
363
+ // core's catch-all HANDLER slot, so every otherwise-unanswered tool call
364
+ // got auto-answered with an empty tool result plus a follow-up turn.
365
+ const coreRef: { current: Core | null } = { current: null };
366
+ const agent = new ToolListRecordingAgent();
367
+
368
+ const { container } = render(
369
+ <TestCopilotKit messages={[]} agent={agent}>
370
+ <CaptureCore into={coreRef} />
371
+ <LegacyWildcardProbe paints="someServerToolNobodyClaimed" />
248
372
  </TestCopilotKit>,
249
373
  );
374
+ const core = coreRef.current!;
250
375
 
251
- await waitFor(() => expect(container.textContent).toBe("before"));
252
-
253
- rerender(
254
- <TestCopilotKit messages={[]}>
255
- <LabelProbe label="after" deps={["after"]} />
256
- </TestCopilotKit>,
376
+ // Half one: it still paints, as a FALLBACK — the tool call it renders has
377
+ // no renderer of its own.
378
+ await waitFor(() =>
379
+ expect(container.textContent).toBe(
380
+ "legacy-wildcard|someServerToolNobodyClaimed|inProgress",
381
+ ),
257
382
  );
383
+ expect(core.renderToolCalls.map((r) => r.name)).toContain("*");
258
384
 
259
- await waitFor(() => expect(container.textContent).toBe("after"));
385
+ // Half two: nothing named `*` is a TOOL. These two are the discriminating
386
+ // assertions — the tool registry is the thing rule 1 keeps clean, and
387
+ // mutating rule 1 kills exactly this pair.
388
+ expect(core.getTool({ toolName: "*" })).toBeUndefined();
389
+ expect(core.tools.map((t) => t.name)).not.toContain("*");
390
+
391
+ // Forward guard only, as in the sibling test above: `buildFrontendTools`
392
+ // already withholds `*`, so this recorded `[[]]` on `origin/main` too and
393
+ // cannot fail for the old defect. It pins that `*` stays unadvertisable.
394
+ await act(async () => {
395
+ await core.runAgent({ agent });
396
+ });
397
+ expect(agent.advertised).toEqual([[]]);
260
398
  });
399
+ });
261
400
 
262
- it("PINS the limitation: a non-serialisable dep can never re-register", async () => {
263
- // `useFrontendTool` compares deps with `JSON.stringify(extraDeps)`, so a
264
- // function / Map / Set / private-field class instance collapses to a
265
- // CONSTANT and cannot trigger re-registration however often its identity
266
- // changes. This is a documented sharp edge, not a bug to fix here — it is
267
- // pinned so that changing the comparator (e.g. to reference equality) fails
268
- // loudly and forces the hook's JSDoc to be updated with it.
401
+ /**
402
+ * Rule 2: the old tool-plus-renderer shape, under a real name.
403
+ *
404
+ * `handler` returns a value the test can observe through core's own execution
405
+ * path, because "the handler never runs again" is the silent half of the break
406
+ * this shim exists for.
407
+ */
408
+ function LegacyToolProbe() {
409
+ useRenderTool(
410
+ {
411
+ name: "sendEmail",
412
+ description: "Send an email on the user's behalf",
413
+ parameters: z.object({ to: z.string() }),
414
+ handler: async ({ to }) => `sent to ${to}`,
415
+ render: ({ status, parameters }) => (
416
+ <>{`legacy-tool|${status}|${parameters.to ?? ""}`}</>
417
+ ),
418
+ },
419
+ [],
420
+ );
421
+ const renderToolCall = useRenderToolCall();
422
+ return (
423
+ <>{renderToolCall(renderOneCall("sendEmail", '{"to":"a@b.example"}'))}</>
424
+ );
425
+ }
426
+
427
+ describe("rule 2: `handler`/`description` route to `useFrontendTool`", () => {
428
+ it("registers a callable, advertised tool AND its renderer", async () => {
269
429
  const coreRef: { current: Core | null } = { current: null };
430
+ const agent = new ToolListRecordingAgent();
270
431
 
271
- const { container, rerender } = render(
272
- <TestCopilotKit messages={[]}>
432
+ const { container } = render(
433
+ <TestCopilotKit messages={[]} agent={agent}>
273
434
  <CaptureCore into={coreRef} />
274
- <LabelProbe label="before" deps={freshNonSerialisableDeps()} />
435
+ <LegacyToolProbe />
275
436
  </TestCopilotKit>,
276
437
  );
438
+ const core = coreRef.current!;
277
439
 
278
- await waitFor(() => expect(container.textContent).toBe("before"));
279
- const registeredBefore = coreRef.current!.renderToolCalls.find(
280
- (r) => r.name === "showLabel",
281
- )!.render;
440
+ await waitFor(() =>
441
+ expect(core.getTool({ toolName: "sendEmail" })).toBeDefined(),
442
+ );
282
443
 
283
- rerender(
284
- <TestCopilotKit messages={[]}>
444
+ // The tool half: present, described, advertised, and — the assertion that
445
+ // separates "registered" from "works" — actually executable through core.
446
+ expect(core.getTool({ toolName: "sendEmail" })?.description).toBe(
447
+ "Send an email on the user's behalf",
448
+ );
449
+ expect(core.tools.map((t) => t.name)).toContain("sendEmail");
450
+ await expect(
451
+ core.runTool({ name: "sendEmail", parameters: { to: "a@b.example" } }),
452
+ ).resolves.toMatchObject({
453
+ result: "sent to a@b.example",
454
+ error: undefined,
455
+ });
456
+ await act(async () => {
457
+ await core.runAgent({ agent });
458
+ });
459
+ expect(agent.advertised).toEqual([["sendEmail"]]);
460
+
461
+ // The renderer half: registered through the same call, and painting.
462
+ expect(container.textContent).toBe("legacy-tool|inProgress|a@b.example");
463
+ });
464
+ });
465
+
466
+ /** Rule 3: the new, renderer-only shape — no tool fields at all. */
467
+ function ModernRendererProbe() {
468
+ useRenderTool(
469
+ {
470
+ name: "renderInvoice",
471
+ parameters: z.object({ id: z.string() }),
472
+ render: ({ status, parameters }) => (
473
+ <>{`modern|${status}|${parameters.id ?? ""}`}</>
474
+ ),
475
+ },
476
+ [],
477
+ );
478
+ const renderToolCall = useRenderToolCall();
479
+ return (
480
+ <>{renderToolCall(renderOneCall("renderInvoice", '{"id":"inv-7"}'))}</>
481
+ );
482
+ }
483
+
484
+ describe("rule 3: no tool fields routes to core's `useRenderTool`", () => {
485
+ it("lands the renderer in CopilotKitCoreReact's registry and advertises nothing", async () => {
486
+ // Also the behavioural half of the delegation guard: a registration made
487
+ // through RN's shim has to end up in CORE's registry, which is the property
488
+ // an RN-local registry (RN once had one) would break while every
489
+ // export-surface check stayed green.
490
+ const coreRef: { current: Core | null } = { current: null };
491
+ const agent = new ToolListRecordingAgent();
492
+
493
+ const { container } = render(
494
+ <TestCopilotKit messages={[]} agent={agent}>
285
495
  <CaptureCore into={coreRef} />
286
- <LabelProbe label="after" deps={freshNonSerialisableDeps()} />
496
+ <ModernRendererProbe />
287
497
  </TestCopilotKit>,
288
498
  );
289
- // Let any pending effect + subscriber notification settle, so this asserts
290
- // "nothing happened" rather than "nothing has happened yet".
291
- await act(async () => {});
292
-
293
- expect(
294
- coreRef.current!.renderToolCalls.find((r) => r.name === "showLabel")!
295
- .render,
296
- ).toBe(registeredBefore);
297
- expect(container.textContent).toBe("before");
499
+ const core = coreRef.current!;
500
+
501
+ await waitFor(() =>
502
+ expect(core.renderToolCalls.map((r) => r.name)).toContain(
503
+ "renderInvoice",
504
+ ),
505
+ );
506
+ expect(container.textContent).toBe("modern|inProgress|inv-7");
507
+
508
+ expect(core.getTool({ toolName: "renderInvoice" })).toBeUndefined();
509
+ expect(core.tools.map((t) => t.name)).not.toContain("renderInvoice");
510
+ await act(async () => {
511
+ await core.runAgent({ agent });
512
+ });
513
+ expect(agent.advertised).toEqual([[]]);
514
+ });
515
+ });
516
+
517
+ // ─── The deprecation warning ──────────────────────────────────────────────────
518
+
519
+ /**
520
+ * A legacy tool-shaped call whose tool NAME the caller chooses, so each warning
521
+ * test gets a name of its own — the warning is deduped per tool name for the
522
+ * lifetime of the module, which is the property under test.
523
+ */
524
+ function WarningProbe({ name }: { name: string }) {
525
+ useRenderTool(
526
+ {
527
+ name,
528
+ description: "a legacy tool-plus-renderer registration",
529
+ parameters: z.object({ x: z.string() }),
530
+ handler: async () => "ok",
531
+ render: () => null,
532
+ },
533
+ [],
534
+ );
535
+ return null;
536
+ }
537
+
538
+ /**
539
+ * The renderer-only call with NO legacy fields at all: `{ name, parameters,
540
+ * render }`. Simultaneously the correct new spelling and the one old-JS shape
541
+ * the shim cannot tell apart from it, so the warning carries it.
542
+ */
543
+ function RendererOnlyProbe({ name }: { name: string }) {
544
+ useRenderTool(
545
+ {
546
+ name,
547
+ parameters: z.object({ x: z.string() }),
548
+ render: () => null,
549
+ },
550
+ [],
551
+ );
552
+ return null;
553
+ }
554
+
555
+ /**
556
+ * A call whose SHAPE changes between renders — `handler`/`description` appear
557
+ * only once `legacy` is true, which is what a `handler: enabled ? fn : undefined`
558
+ * call site looks like from the shim's side.
559
+ */
560
+ function ShapeShiftingProbe({ legacy }: { legacy: boolean }) {
561
+ useRenderTool(
562
+ {
563
+ name: "shapeShifter",
564
+ parameters: z.object({ x: z.string() }),
565
+ render: () => null,
566
+ ...(legacy
567
+ ? { description: "now a tool as well", handler: async () => "ok" }
568
+ : {}),
569
+ },
570
+ [],
571
+ );
572
+ return null;
573
+ }
574
+
575
+ describe("the shim's deprecation warning", () => {
576
+ // The dedup key is the tool NAME and it lives as long as the module, so
577
+ // without this the wildcard's warning (always `"*"`) would already have been
578
+ // consumed by the rule-1 test above and these tests would have to depend on
579
+ // file order to observe anything.
580
+ beforeEach(() => {
581
+ __resetRenderToolShimWarnings();
582
+ });
583
+
584
+ it("fires once per distinct tool name, not once per render", async () => {
585
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
586
+ try {
587
+ const { rerender, unmount } = render(
588
+ <TestCopilotKit messages={[]}>
589
+ <WarningProbe name="warnOnceTool" />
590
+ </TestCopilotKit>,
591
+ );
592
+ await waitFor(() => expect(warn).toHaveBeenCalledTimes(1));
593
+
594
+ // Re-render the same tree several times. A warning emitted from the
595
+ // render path — or keyed on anything per-render — shows up here as a
596
+ // growing count.
597
+ for (let i = 0; i < 3; i++) {
598
+ rerender(
599
+ <TestCopilotKit messages={[]}>
600
+ <WarningProbe name="warnOnceTool" />
601
+ </TestCopilotKit>,
602
+ );
603
+ }
604
+ await waitFor(() => expect(warn).toHaveBeenCalledTimes(1));
605
+
606
+ // Then MOUNT IT AGAIN, which is what makes the module-level dedup set the
607
+ // load-bearing part rather than the effect's dependency array: a fresh
608
+ // mount runs a fresh effect. On a real device this is navigating back to
609
+ // a screen, and re-warning there would put the notice in a loop.
610
+ unmount();
611
+ render(
612
+ <TestCopilotKit messages={[]}>
613
+ <WarningProbe name="warnOnceTool" />
614
+ </TestCopilotKit>,
615
+ );
616
+ await waitFor(() => expect(warn).toHaveBeenCalledTimes(1));
617
+
618
+ const message = String(warn.mock.calls[0]![0]);
619
+ // What was received, which hook it was routed to, and what to change the
620
+ // call to — a warning that says less than that is not actionable.
621
+ expect(message).toContain("[CopilotKit]");
622
+ expect(message).toContain("warnOnceTool");
623
+ expect(message).toContain("`description`");
624
+ expect(message).toContain("`handler`");
625
+ expect(message).toContain("`useFrontendTool`");
626
+ expect(message).toContain("removal in the next minor");
627
+ } finally {
628
+ warn.mockRestore();
629
+ }
630
+ });
631
+
632
+ it("names the fields a wildcard call ignored, and says no `*` tool is registered", async () => {
633
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
634
+ try {
635
+ render(
636
+ <TestCopilotKit messages={[]}>
637
+ <LegacyWildcardProbe paints="anything" />
638
+ </TestCopilotKit>,
639
+ );
640
+ await waitFor(() => expect(warn).toHaveBeenCalledTimes(1));
641
+
642
+ const message = String(warn.mock.calls[0]![0]);
643
+ expect(message).toContain("IGNORED");
644
+ expect(message).toContain("`description`");
645
+ expect(message).toContain("`handler`");
646
+ expect(message).toContain("`parameters`");
647
+ expect(message).toContain("RENDERER ONLY");
648
+ } finally {
649
+ warn.mockRestore();
650
+ }
651
+ });
652
+
653
+ it("warns on the renderer-only route even with NO legacy fields to name", async () => {
654
+ // The one shape routing cannot discriminate, and therefore the one the
655
+ // warning has to carry alone.
656
+ //
657
+ // `{ name, parameters, render }` is BOTH the correct new renderer-only
658
+ // spelling AND — for an untyped JS caller, the population this shim exists
659
+ // for — a call that on `origin/main` registered and ADVERTISED a real tool.
660
+ // (`description` was required by the old hook's types, so TypeScript
661
+ // callers could not reach this shape; `FrontendTool.handler` is optional
662
+ // and `buildFrontendTools` does not filter on it, so the registration and
663
+ // the advertisement both happened without either field.) Measured against
664
+ // a vendored copy of the old hook, this call went from advertising
665
+ // `["rendererOnlyNoLegacyFields"]` to advertising nothing — so silence
666
+ // here would be the exact failure the shim exists to prevent.
667
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
668
+ try {
669
+ const coreRef: { current: Core | null } = { current: null };
670
+ render(
671
+ <TestCopilotKit messages={[]}>
672
+ <CaptureCore into={coreRef} />
673
+ <RendererOnlyProbe name="rendererOnlyNoLegacyFields" />
674
+ </TestCopilotKit>,
675
+ );
676
+
677
+ // Wait on the REGISTRATION, not on the warning: a hook that did nothing
678
+ // at all could satisfy a warning-only assertion.
679
+ await waitFor(() =>
680
+ expect(coreRef.current!.renderToolCalls.map((r) => r.name)).toContain(
681
+ "rendererOnlyNoLegacyFields",
682
+ ),
683
+ );
684
+ await waitFor(() => expect(warn).toHaveBeenCalledTimes(1));
685
+
686
+ const message = String(warn.mock.calls[0]![0]);
687
+ expect(message).toContain("rendererOnlyNoLegacyFields");
688
+ expect(message).toContain("RENDERER ONLY");
689
+ // The actionable half: what was lost, and what to use if it was wanted.
690
+ expect(message).toContain("advertised");
691
+ expect(message).toContain("`useFrontendTool`");
692
+
693
+ // And the registration really is renderer-only.
694
+ expect(
695
+ coreRef.current!.getTool({ toolName: "rendererOnlyNoLegacyFields" }),
696
+ ).toBeUndefined();
697
+ } finally {
698
+ warn.mockRestore();
699
+ }
700
+ });
701
+
702
+ it("dedups the renderer-only warning per tool name, and stays silent in production", async () => {
703
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
704
+ try {
705
+ const { rerender, unmount } = render(
706
+ <TestCopilotKit messages={[]}>
707
+ <RendererOnlyProbe name="rendererOnlyDedup" />
708
+ </TestCopilotKit>,
709
+ );
710
+ await waitFor(() => expect(warn).toHaveBeenCalledTimes(1));
711
+
712
+ rerender(
713
+ <TestCopilotKit messages={[]}>
714
+ <RendererOnlyProbe name="rendererOnlyDedup" />
715
+ </TestCopilotKit>,
716
+ );
717
+ unmount();
718
+ render(
719
+ <TestCopilotKit messages={[]}>
720
+ <RendererOnlyProbe name="rendererOnlyDedup" />
721
+ </TestCopilotKit>,
722
+ );
723
+ await waitFor(() => expect(warn).toHaveBeenCalledTimes(1));
724
+ } finally {
725
+ warn.mockRestore();
726
+ }
727
+
728
+ // Same route, production gate on: nothing at all.
729
+ const prodWarn = vi.spyOn(console, "warn").mockImplementation(() => {});
730
+ const previous = process.env.NODE_ENV;
731
+ process.env.NODE_ENV = "production";
732
+ try {
733
+ const coreRef: { current: Core | null } = { current: null };
734
+ render(
735
+ <TestCopilotKit messages={[]}>
736
+ <CaptureCore into={coreRef} />
737
+ <RendererOnlyProbe name="rendererOnlyProdSilent" />
738
+ </TestCopilotKit>,
739
+ );
740
+ await waitFor(() =>
741
+ expect(coreRef.current!.renderToolCalls.map((r) => r.name)).toContain(
742
+ "rendererOnlyProdSilent",
743
+ ),
744
+ );
745
+ expect(prodWarn).not.toHaveBeenCalled();
746
+ } finally {
747
+ process.env.NODE_ENV = previous;
748
+ prodWarn.mockRestore();
749
+ }
750
+ });
751
+
752
+ it("reports, rather than silently acts on, a config that changes shape mid-life", async () => {
753
+ // The route is frozen at first render because a hook cannot be called
754
+ // conditionally unless the condition is stable for the component's
755
+ // lifetime. That is a real limitation, so it is stated out loud rather than
756
+ // papered over: the registration stays where it started (renderer-only
757
+ // here, so `shapeShifter` never becomes a tool) and the consumer is told to
758
+ // call the hook they actually want.
759
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
760
+ try {
761
+ const coreRef: { current: Core | null } = { current: null };
762
+ const { rerender } = render(
763
+ <TestCopilotKit messages={[]}>
764
+ <CaptureCore into={coreRef} />
765
+ <ShapeShiftingProbe legacy={false} />
766
+ </TestCopilotKit>,
767
+ );
768
+ await waitFor(() =>
769
+ expect(coreRef.current!.renderToolCalls.map((r) => r.name)).toContain(
770
+ "shapeShifter",
771
+ ),
772
+ );
773
+ // Rule 3 on the first render. This warns too — the renderer-only route
774
+ // is never silent, because on the old hook this same shape registered
775
+ // and advertised a tool (see the dedicated test below).
776
+ await waitFor(() => expect(warn).toHaveBeenCalledTimes(1));
777
+ expect(String(warn.mock.calls[0]![0])).toContain("RENDERER ONLY");
778
+
779
+ rerender(
780
+ <TestCopilotKit messages={[]}>
781
+ <CaptureCore into={coreRef} />
782
+ <ShapeShiftingProbe legacy />
783
+ </TestCopilotKit>,
784
+ );
785
+
786
+ // Wait for the DRIFT message specifically: the renderer-only notice
787
+ // above has already been emitted, so a bare `toHaveBeenCalled()` would
788
+ // be satisfied by it and never observe the drift warning at all.
789
+ await waitFor(() => {
790
+ const messages = warn.mock.calls.map((call) => String(call[0]));
791
+ expect(
792
+ messages.some((m) => m.includes("changed shape between renders")),
793
+ ).toBe(true);
794
+ });
795
+ // And the frozen route is the observable consequence: still no tool.
796
+ expect(
797
+ coreRef.current!.getTool({ toolName: "shapeShifter" }),
798
+ ).toBeUndefined();
799
+ } finally {
800
+ warn.mockRestore();
801
+ }
802
+ });
803
+
804
+ it("is silent in production", async () => {
805
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
806
+ const previous = process.env.NODE_ENV;
807
+ process.env.NODE_ENV = "production";
808
+ try {
809
+ const coreRef: { current: Core | null } = { current: null };
810
+ render(
811
+ <TestCopilotKit messages={[]}>
812
+ <CaptureCore into={coreRef} />
813
+ <WarningProbe name="productionSilentTool" />
814
+ </TestCopilotKit>,
815
+ );
816
+ // Wait for the REGISTRATION rather than for a timeout: the claim is
817
+ // "routed and silent", and a test that only waited for silence would pass
818
+ // just as well if the hook had done nothing at all.
819
+ await waitFor(() =>
820
+ expect(
821
+ coreRef.current!.getTool({ toolName: "productionSilentTool" }),
822
+ ).toBeDefined(),
823
+ );
824
+ expect(warn).not.toHaveBeenCalled();
825
+ } finally {
826
+ process.env.NODE_ENV = previous;
827
+ warn.mockRestore();
828
+ }
298
829
  });
299
830
  });