Repository navigation
refactor(react-native)!: converge tool-call rendering onto CopilotKit's shared registry - #6438
Conversation
…erive props from react-core
… glob) react-native was missing from static_bundle_size.yml's package glob, so its dist/ has never been measured despite being the consumer most exposed to the #4893 regression (Metro does not tree-shake). This adds coverage: - Extend the compressed-size-action glob to include react-native. - New scripts/measure-headless.mjs: an esbuild-driven gzip signal for the @copilotkit/react-native/headless entry, mirroring react-core's measure-copilotchat.mjs (stdin + resolveDir, gzip sum, job-summary output). - Wire a build + measure step into the copilotchat-import-size CI job. First baseline: @copilotkit/react-native/headless = 92.8 kB gzip (esbuild regression signal, not a Metro figure). No limit fields (Phase 1 policy — see dev-docs/bundle-size.md). esbuild added as a react-native devDependency (^0.27.0, matching react-core); the root ">=0.25.4" override keeps the monorepo on a single esbuild (0.27.3). Two corrections to the drafted script, verified by running it: - Fed the entry via esbuild stdin with resolveDir=pkgRoot; a temp-dir entry cannot resolve @copilotkit/react-native/headless through workspace node_modules. - Dropped useRenderToolCall from the import list — the RN headless surface deliberately does not export it (DOM-dependent; see src/index.ts). Co-Authored-By: Claude <[email protected]>
…by design
The prior comment framed useRenderToolCall's absence from the size probe's
import list as a permanent design fact ("DOM-dependent … would fail the
build"). That is the same permanent-sounding rationale that let the stale
claim in src/index.ts go unrevisited for months. The export is missing only
because RN's headless entry does not export it yet; the render-tool
convergence on this branch adds it. Reframe the comment as TEMPORARY — REVISIT
so a future engineer restores the symbol and re-baselines the number once RN
headless exports it. Comment-only; measured size unchanged at 92.8 kB.
Co-Authored-By: Claude <[email protected]>
… via react-core's renderer Co-Authored-By: Claude <[email protected]>
…ol-call coverage - SeededAgent.run now declares Observable<BaseEvent> return (via ReturnType<AbstractAgent["run"]>) so check-types passes; throw-only body avoids a runtime rxjs import the RN bundler cannot resolve. - TestCopilotKit accepts optional executingToolCallIds. - Restore executing-status, empty-string-args, and unrepairable-JSON-args coverage as tests driven through the real CopilotKitCoreReact. Co-Authored-By: Claude <[email protected]>
…me react-core's hooks BREAKING CHANGE: useRenderToolRegistry and RenderToolProvider are removed. Render tools now register into CopilotKitCoreReact.renderToolCalls, the same registry react-core uses, so a React Native-specific registry and its provider no longer exist. Use useRenderToolCall() to render a registered component anywhere in your app, including non-chat surfaces, and delete RenderToolProvider from your tree — CopilotKitProvider no longer installs it and nothing needs it. Co-Authored-By: Claude <[email protected]>
…rged path Assertions originally written by David McKay in PR #6346, re-driven through CopilotKitCoreReact's registry instead of a mocked local one. Co-Authored-By: David McKay <[email protected]>
useRenderTool.mdx and CopilotKitProvider.mdx described the removed React Native render-tool registry as if it still existed. Correct the three false statements on useRenderTool.mdx (cleanup unregisters the renderer; RenderToolProvider auto-installed; useRenderToolRegistry live Map) and the false CopilotKitProvider bullet (wraps children in a RenderToolProvider). Document useRenderToolCall for rendering on any surface, note that arguments stream on status "inProgress", and add a migration section for the removed useRenderToolRegistry. Also fix the stale Callout that listed useRenderToolCall as not exported on React Native. Co-Authored-By: Claude <[email protected]>
…urement The RN headless entry now re-exports useRenderToolCall (render-tool convergence), so the measurement's pending-state comment no longer applies. Add the symbol back to the measured import surface and drop the TEMPORARY note. Reported size is essentially flat (92.8 -> 92.7 kB gzip): the hook reuses the renderer registry/resolver useRenderTool already pulls in. Co-Authored-By: Claude <[email protected]>
Co-Authored-By: Claude <[email protected]>
…staleness Final review fix wave for the RN render-tool convergence branch. Substantive: - Extend packages/react-core/scripts/assert-headless-purity.mjs to also scan the built /v2/context chunk (context.mjs/context.cjs), not just /v2/headless. /v2/context carries CopilotKitCoreReact and is imported by react-native, so a future shiki/mermaid/katex leak through it would bloat RN bundles (#4893) while neither hard-fail guard fired. Comment and failure message updated to name both RN-reachable entries. Mutation-verified against context.mjs. - Document the closure-staleness convergence: render is now captured at registration (passed into useFrontendTool) and only refreshed when deps change, no longer re-read every render. Consumers whose render closes over changing state must now pass deps. Documented in the useRenderTool JSDoc, the useRenderTool.mdx reference, and the changeset migration notes. Minor sweep: - CopilotChat extraData now lists what renderItem actually reads ({ isRunning, renderToolCall, toolMessages }); drop unused executingToolCallIds. - headless-type-exports.test-d.ts imports React explicitly instead of relying on the ambient UMD global. - useRenderTool.mdx migration heading no longer names the uncut 1.67.0 version. - Changeset marks @copilotkit/react-core minor (new public type export), matching its body. Co-Authored-By: Claude <[email protected]>
Production Digest-Pinning AuditAll 41 services digest-pinned. Run 2026-08-13 08:31:00 PDT — 0 finding(s). |
@copilotkit/a2ui-renderer
@copilotkit/agentcore-runner
@copilotkit/angular
@copilotkit/channels
@copilotkit/channels-core
@copilotkit/channels-discord
@copilotkit/channels-intelligence
@copilotkit/channels-slack
@copilotkit/channels-teams
@copilotkit/channels-telegram
@copilotkit/channels-ui
@copilotkit/channels-whatsapp
@copilotkit/core
@copilotkit/react-core
@copilotkit/react-native
@copilotkit/react-textarea
@copilotkit/react-ui
@copilotkit/runtime
@copilotkit/runtime-client-gql
@copilotkit/sdk-js
@copilotkit/shared
@copilotkit/sqlite-runner
@copilotkit/voice
@copilotkit/vue
@copilotkit/web-components
@copilotkit/web-inspector
commit: |
|
Size Change: +3.23 kB (+0.25%) Total Size: 1.32 MB 📦 View Changed
ℹ️ View Unchanged
|
Evidence: the #4893 hazard is absent from what React Native shipsThe CI guards prove future regressions get caught. They don't prove today's bundle is clean, so I measured it — bundling each entry a consumer could import and grepping the actual output bytes for the payload, rather than trusting the import graph. 1. What an app bundles today
The hazard is real and unchanged at ~2.9 MB gzipped (consistent with the ~15 MB uncompressed reported in #4893). React Native links none of it — including via the default barrel, which I checked specifically because it re-exports the chat components and is the likeliest place to leak. That last row doubles as the control: if the method couldn't detect the heavy stack, it would have come back clean too. 2. What a regression would costI appended the exact violating import to 30× from a single import line. Metro does not tree-shake, so there is no recovery from this at the app level — which is why it needs a build-time guard rather than a review convention. 3. That the guard stops itWith the violating import present: Reverted (working tree verified identical to HEAD), same guard: The companion guard covers the opposite direction — CaveatThese are esbuild figures, not Metro's — a real React Native release bundle will differ in absolute terms. The method is identical across all four rows, so the ratio and the presence/absence of the heavy stack are the transferable claims; the absolute kB are a relative signal only. The per-PR number in CI ( ReproducingBundle any of the four specifiers with 🤖 Generated with Claude Code |
This repo migrated off Changesets. CLAUDE.md says never to create `.changeset/*` files, and `.github/workflows/static_check-binaries.yml` hard-fails the build on any added or modified path under `.changeset` (`git diff --name-only --diff-filter=AM origin/<base>...HEAD -- '.changeset'` must be empty). `.changeset/rn-render-tool-convergence.md` tripped that gate, so this branch could not go green. Releases here are conventional-commit driven; the change is described in commit subjects and footers instead. Where each piece of the deleted changeset now lives: - Package bumps (`@copilotkit/react-native` minor, `@copilotkit/react-core` minor) -> derived by the release tooling from commit subjects: `refactor(react-native)!` (db67ccf) and `feat(react-core): export ReactToolCallRenderer from the /v2/headless entry` (d5ace8b). - The three fixed bugs (streaming renders, `useComponent` rendering nowhere, degraded chat history) -> commit subjects ebf0f94, 296cd44, db67ccf, and the ported regressions in 4104bd1. - Removal of `useRenderToolRegistry` and `RenderToolProvider`, plus the `useRenderToolCall()` migration diff -> already a `BREAKING CHANGE:` footer on db67ccf, and documented in `showcase/shell-docs/src/content/reference/react-native/hooks/useRenderTool.mdx` (§ "Migrating from `useRenderToolRegistry` (removed)"). - `RenderToolProps` derived from react-core, the `"inProgress" | "executing" | "complete"` discriminated union, `args` partial only while `"inProgress"`, and the new `name` / `toolCallId` render props -> useRenderTool.mdx § `RenderToolProps<T>`; restated in the footer below because ebf0f94 carried it in its subject only. - Unmount no longer unregisters the render function -> useRenderTool.mdx § Behavior ("Cleanup"). - `render` captured at registration, refreshed only on `deps` change -> f4031f3's body, the `useRenderTool` JSDoc, and useRenderTool.mdx (§ Behavior and the `deps` reference). - Wildcard `"*"` renderers and `followUp` -> useFrontendTool.mdx and useCopilotKit.mdx. - The agent-scoped-resolution known limitation -> existed ONLY in the changeset; preserved in the footer below. BREAKING CHANGE: React Native render tools now use CopilotKit's canonical renderer. `useRenderToolRegistry` and `RenderToolProvider` are removed — render functions live in `CopilotKitCoreReact.renderToolCalls`, the registry react-core already owns. Replace registry reads with `useRenderToolCall()`, which renders a registered component on any surface including non-chat ones, and delete `RenderToolProvider` from your tree (`CopilotKitProvider` no longer installs it and nothing needs it). `RenderToolProps` is now derived from react-core's renderer contract, so React Native and web cannot drift: `status` is a discriminated union of `"inProgress" | "executing" | "complete"`, so renderers switching exhaustively on it need an `"inProgress"` branch; `args` is `Partial<T>` **only** when `"inProgress"`; render props gain `name` and `toolCallId`. `render` is now captured at registration and refreshed only when `deps` change, rather than re-read from the latest closure on every render — if your `render` closes over component state or props that change over time, pass those values in `deps` or the chat will keep painting the stale closure. Unmounting no longer unregisters a render function (the tool itself is still removed), so tool calls already in the chat history keep rendering after navigation. Known limitation: agent-scoped renderer resolution does not take effect on React Native — `CopilotChatConfigurationProvider` is not part of the RN provider tree, so `agentId` always resolves to the default. Renderers still resolve by name; two agents registering the same tool name resolve arbitrarily. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…d coverage
The Tier 3 section shipped in this PR made claims the code contradicts:
- The action pin read v2.9.1; static_bundle_size.yml pins 2.10.0 (by SHA).
- assert-headless-purity.mjs asserts four targets — dist/v2/headless.{mjs,cjs}
AND dist/v2/context.{mjs,cjs} — not just the headless pair.
- The package inventory enumerated 9 packages while the workflow glob covers 10:
react-native was neither listed nor classified, and the "no size script" claim
was wrong for it (it ships size:headless).
- "Both directions of the #4893 regression" overclaimed. The purity script is a
substring scan of four emitted files with @copilotkit/core, @copilotkit/shared,
@ag-ui/*, rxjs, zod and uuid external, so it cannot see a heavy dep arriving
through an external edge; the RN test never resolves bare specifiers, so it
cannot enter node_modules. Both limits are now stated, along with the gap
neither guard covers.
- The heading said "two tiers" while three are documented.
Docs only — no change to the script or the workflow.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…er-tool-types The header JSDoc on the new derived `RenderToolProps` claimed the deleted RN type had "args unconditionally partial". The opposite was true: the old `RenderToolContext.tsx` declared `args: T`, so RN promised the FULL argument object at every status — the drift this refactor fixes is that the canonical contract ADDS an `"inProgress"` state in which `args` narrows to `Partial<T>`. Stating the drift backwards in the very file that defines the contract misleads anyone reasoning about the migration, so the historical claims are now spelled out concretely and verified against the deleted type: - old `status` was `"executing" | "complete"` with no `"inProgress"` member - old type omitted `name` and `toolCallId` entirely - old `args` was unconditionally `T`, never `Partial<T>` Comment-only; no type declaration changed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…emantics The documented signature dropped the hook's generic constraint and default (`T extends Record<string, unknown> = Record<string, unknown>`) and rendered the required `options` argument as optional. The render-prop semantics were wrong in two ways verified against the types: `args` is not "fully parsed" on the executing/complete arms — every arm receives the same `partialJSONParse` of the raw argument string and the `parameters` schema is never applied before `render`, so widening `Partial<T>` to `T` is a type-level assertion only. And `result` is the tool result message's `content` correlated by `toolCallId`, not the handler's return value: the complete arm is selected because that message exists, handler returns arrive serialized (`undefined`/`null` -> `""`, else `JSON.stringify`), a thrown handler yields the string `Error: <message>`, a render-only tool completes with `""`, and on reload the value replays from stored history. Also document that the RN entry's re-exported `RenderToolInProgressProps` / `RenderToolExecutingProps` / `RenderToolCompleteProps` are NOT arms of RN's `RenderToolProps<T>`: they are schema-generic, `parameters`-shaped arms of react-core's own union for the web hook. They sit next to `RenderToolProps` on the public barrel, so the resemblance is a real trap worth naming. Commit hook note: the commit-msg commitlint hook cannot run in this worktree (no node_modules, `commitlint` binary unresolvable), so the message was validated by hand against commitlint.config.js — conventional type+scope, 77-char header under the 120 limit, blank-line-separated body and footer. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The deps guidance told readers that a render closure over changing values
is fixed by listing those values in deps. That remedy is inert for the
value types most likely to appear in a render closure.
react-core's useFrontendTool compares deps by serializing the whole array
(packages/react-core/src/v2/hooks/use-frontend-tool.tsx:45, via
JSON.stringify(extraDeps)), not by reference identity like useEffect. In
an array a function or symbol serializes to null, and a Map, a Set, or a
class instance holding state in private fields serializes to {} -- the
same string forever, so such a dep never re-registers the tool. A
circular dep additionally throws while the hook renders.
State the comparator's actual semantics, name the three consequences
(inert non-serializable deps, circular deps throwing, key order
counting), and document what does work: a primitive derived from the
changing value, or a ref the captured render dereferences at call time.
Docs-only. Core's comparator is deliberately unchanged -- it is shared by
every platform and is out of scope for this finding.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…derTool's example
The primary Usage example on the useRenderTool reference page never imported
CopilotChat, and the barrel specifier it implied resolves to the headless
component (packages/react-native/src/CopilotChat.tsx), which returns a bare
context provider around {children} and paints no message list. The page's
headline example therefore rendered nothing at all.
Import CopilotChat from @copilotkit/react-native/components -- the prebuilt UI
that calls useRenderToolCall and renders tool calls inline -- and state the
subpath requirement under the block so the distinction is not silent.
agentName is kept: it is the current, non-deprecated prop on the /components
chat (the deprecation and dev console.warn live on the headless component's
agentName), and it matches the prebuilt-UI usage on the CopilotChat page.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The useRenderTool page's Usage example compared `status` to the string
literal `"executing"`. `status` is typed as the `ToolCallStatus` enum
member union (`ReactToolCallRenderer["render"]` in react-core, which RN's
`RenderToolProps` derives from), so that comparison is TS2367 — the
snippet as printed does not compile.
Compare against `ToolCallStatus.Executing` and import the enum in the
snippet so the example is genuinely compilable.
Depends on `ToolCallStatus` being re-exported as a runtime VALUE from
packages/react-native/src/headless.ts (it currently sits inside an
`export type { … }` block, which strips the enum value). That export fix
is a separate change; both must land together for this snippet's import
to resolve.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The "Rendering a tool call outside the chat" snippet called the hook at module top level, had a `return` at module scope (a syntax error), and referenced an undefined `toolCalls` binding, so it could not be pasted. Wrap it in a real component, source the tool calls from `useAgent()`'s message list, and correlate each call with its tool-result message the way the prebuilt RN chat does — without `toolMessage`, `status` stays "inProgress" and `result` is `undefined` forever. Hooks bypassed: this worktree has no node_modules, so the commitlint commit-msg hook cannot resolve its binary. Subject follows the convention. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The migration note said only that `args` is partial while `status` is "inProgress", with no before side. Read as a migration instruction it implied the opposite of the real change: the old RN `RenderToolProps` declared `args: T` (never partial) and `status: "executing" | "complete"`, so the change ADDS an "inProgress" state in which `args` is `Partial<T>` rather than narrowing a partiality that already existed. Spell out old -> new for `status`, `args` and `result`, and name "inProgress" as a newly-introduced status value. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…validated The React Native guide still described the pre-convergence world: it listed `useRenderToolCall` among the hooks React Native does not export, and told readers React Native keeps a render registry separate from react-core's. Both are now false. - `useRenderToolCall` IS exported (`src/headless.ts`), along with the `ReactToolCallRenderer` type. The remaining three web rendering hooks (`useDefaultRenderTool`, `useRenderCustomMessages`, `useRenderActivityMessage`) are still genuinely absent, and stay listed with the reason each one is held back. - Wildcard resolution now applies on React Native. `useRenderTool` registers through `useFrontendTool` into `CopilotKitCoreReact.renderToolCalls`, and `useRenderToolCall` falls back to a renderer named `"*"`. Noted the one remaining asymmetry: React Native's hook always registers a tool too, so a `"*"` entry still needs `parameters`, where web has a renderer-only overload. - The "two different registries" callout is rewritten. There is one registry, so a `render` passed to `useFrontendTool` does draw in the React Native chat; the reason to prefer `useRenderTool` is now its `ReactElement | null` return type, not registry separation. Left the same bullet's "requires `parameters`" claim alone — still true. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The `deps` array was documented as "similar to `useEffect`" in both the
PropertyReference and the Behavior list. It is not: `useEffect` compares
elements with `Object.is`, while this hook serialises the whole array with
`JSON.stringify` and compares the string
(packages/react-core/src/v2/hooks/use-frontend-tool.tsx:45).
That difference is load-bearing now that React Native's `useRenderTool`
registers through `useFrontendTool` and the documented remedy for its
capture-at-registration semantics is "declare changing values in deps".
Both sites now state the real comparator and link a new "Dependency
comparison" section that tabulates the measured consequences: functions,
`undefined` and symbols serialise to `null`; `Map`/`Set` and instances
whose state is in `#private` fields or prototype getters collapse to `{}`
(own enumerable fields do compare); key order is significant; circular
values and `BigInt` throw during render. The section closes with the two
patterns that work -- a derived primitive, or a latest-value ref.
The react-core/web copy of this page has the same defect and is deferred
to a follow-up.
…ment The esbuild `external` list omitted `react-dom`, unlike react-core's measure-copilotchat.mjs, so a stray web-oriented edge could be absorbed into the figure the PR's bundle claim rests on. Checked empirically before changing anything: `react-dom` is NOT reachable from @copilotkit/react-native/headless today. A metafile run shows 0 of the 653 input modules are react-dom, and no module references it even pre-resolution. The reported figure is therefore UNCHANGED — 94941 B gzip (92.7 kB) before and after, byte for byte. The headline "92.8 kB -> 92.7 kB, flat" claim is unaffected and stays comparable with previously reported numbers. The guard is still worth having. Simulating a stray edge measures the inflation it prevents: +56.3 kB gzip via react-dom/client, +57.3 kB via react-dom/server (not the ~130 kB estimated in review — that is closer to the raw magnitude; react-dom-client.production.js is 536 kB raw). The subtler case is a bare `react-dom` edge at +1.4 kB, small enough to read as noise while still being a real regression. No subpath entries: esbuild prefix-matches package paths, so `react-dom` already covers react-dom/client and react-dom/server (verified on the pinned 0.27.3; esbuild CHANGELOG 0.5.14 and 0.14.13). Listing them would imply they were required. Hoisted the list to an exported HEADLESS_EXTERNAL with per-entry rationale, mirroring the sibling's DEFAULT_EXTERNAL, and made `external` an overridable option so the new test can A/B it rather than assert on a literal. Both new tests fail if react-dom is removed from the list. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… to scan `scripts/assert-headless-purity.mjs` is a hard-fail CI gate, and it did not do what its header said. It read four built entry files and asked `code.includes(dep)`. That is weaker than the claim in both directions, and every item below was reproduced against a real build before this rewrite: 1. It never followed an edge out of those four files. Re-exporting one hook from the fat `@copilotkit/react-core/v2` entry — which links shiki, mermaid, cytoscape, katex and streamdown — left `dist/v2/headless.mjs` importing that entry by name, and the gate printed "clean" for all four files, exit 0. Same for a heavy dep reached through `@copilotkit/core`, which is external to this build: the entry says only `from "@copilotkit/core"` and there is nothing to grep. A split-out relative chunk escaped identically. 2. The header claimed the check "follows into node_modules". It followed nothing — not node_modules, not a relative sibling chunk. 3. `code.includes(dep)` is unanchored, so it matched comments and strings. Not hypothetical in either direction: the built artifact is comment-PRESERVING (233 lines of block comments survive in dist/v2/headless.mjs), and the five banned tokens sit in `src/v2/headless.ts`'s own banner. They are absent from dist only because that module is a re-export shell whose banner attaches to no retained code — moving the same sentence into a module that ships code hard-failed CI on all five tokens while linking none of them. The gate now drives esbuild with `metafile: true` over each built entry and matches on the RESOLVED graph, so it follows relative chunk edges and into node_modules for real, resolves `exports` maps, subpaths and pnpm symlinks, and cannot be fooled or tripped by a comment. Matching is anchored at the package name (`@shikijs/langs` and `cytoscape-fcose` count; `shikimori` does not) and also covers a forbidden dep left external, which resolves to no graph input at all. Unresolvable edges FAIL LOUDLY instead of reading as clean, as does a graph that does not contain its own entry. One edge shape survives a bundler: `import(name)` with a non-literal argument, which esbuild leaves alone without even warning. For that the gate reads text — the only place it does — over the graph's first-party files, using the `stripComments` helper ported from the sibling RN guard so a documented counter-example cannot trip it. Adds `scripts/__tests__/assert-headless-purity.test.mjs` (17 tests, wired into `test:scripts` next to measure-copilotchat's), because a hard-fail gate with no coverage of its own failure mode is how this shipped. Proven after the fix: both false negatives now exit 1, a clean build exits 0, and a banned token that appears only in a comment exits 0. esbuild is already this package's devDependency and already runs in the same CI job, so the gate needs no workflow change. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The #4893 entry-surface guard timed out nondeterministically at full test parallelism ("Test timed out in 5000ms" on `await import("../headless")`), which four independent agents each worked around with --testTimeout or --maxWorkers=2. A flaky hard gate is a gate people learn to ignore. Measured, not guessed. The import is a one-time module-graph load whose VARIANCE — not its mean — broke the default budget: ~0.7-1.1s for this file alone and ~0.9-1.8s inside the full 22-file suite (n=8 each), but 4568ms on the run straight after a cold `nx build`, i.e. 91% of the 5000ms budget spent on an otherwise idle machine. The cost is resolve/transform plus cold-page- cache I/O over the ~283 KB of workspace dist that vitest.config.mjs inlines via `server.deps.inline: [/@copilotkit/]` (core ~218 KB, react-core v2/headless ~55 KB, v2/context, shared); bare-Node `import()` of the equivalent prebuilt dist is 461ms, so evaluation is not the expensive part. Four separate tests each awaited that same import, so all four raced one cost against one budget — and when the first lost the race the other three inherited its in-flight import and timed out with it, which is why the observed signature was three simultaneous failures rather than one. They now share a single explicitly-budgeted `beforeAll`, so the cost lives in exactly one place and each test reports ~0ms. The hook is nested rather than top-level on purpose: its failure domain must cover only the tests that need the module, or an import failure would take down the fs-only graph tests too — the same blast-radius problem as blind spot #4, just relocated into a hook. No assertion is weakened: comment stripping, import()/require() extraction, the exact resolved-graph pin and the revived existence test are untouched, and the guard still fails on a real violation (injecting a lazy `import("@copilotkit/react-core/v2")` into src/streaming-fetch.ts trips 3 assertions; reverted). Verification: 5 consecutive full-suite runs at DEFAULT parallelism, no --maxWorkers or --testTimeout override, 271/271 passing in 3.97-5.87s wall each; plus 3 concurrent full suites (30 workers on 10 cores) all green, and one pass at load average 235. `check-types` clean. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ed Node floor
`assert-headless-purity.mjs` resolved its dist directory with
`import.meta.dirname`, which landed in Node 20.11 and is `undefined` below it.
The root package.json declares `engines: { "node": ">=18" }`, so a contributor
or runner on Node 18 hit this hard-fail CI gate as:
TypeError [ERR_INVALID_ARG_TYPE]: The "paths[0]" argument must be of type
string. Received undefined
at Object.resolve (node:path:1115:7)
at .../scripts/assert-headless-purity.mjs:71:19
— a stack trace into node internals, at module load, that names neither the
gate nor the real problem. Reproduced against a real Node 18.20.8.
Switch to `path.dirname(fileURLToPath(import.meta.url))`, which both sibling
scripts in this CI job already use (react-core's measure-copilotchat.mjs and
react-native's measure-headless.mjs), so all three read the same and none of
them carries a hidden runtime floor its own package does not declare.
Verified under real Node 18.20.8: the script now walks all four entries (650 /
646 / 649 / 645 modules) and exits 0, and still exits 1 with the full
`links the heavy render stack` report when a forbidden dep is injected into a
dist entry. The metafile-driven graph walk, the loud failure on unresolvable
edges and all 17 negative tests are untouched (`test:scripts`: 19 pass).
Skill-staleness check (reskinnable-demo CLAUDE.md rule): not applicable — this
touches packages/react-core, nothing under .claude/skills/reskin/.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
mxmzb
left a comment
There was a problem hiding this comment.
Reviewer's guide to this diff — what to look at, and what each change actually solves
This PR is 27 commits larger than when it was opened; those came out of a review pass and they change the story in two places worth knowing before reading the code.
The three lines that carry the whole convergence
If you read only three hunks, read these — everything else is consequence or scaffolding:
useRenderTool.ts— registration goes throughuseFrontendTool. Collapses RN's private rendererMapintoCopilotKitCoreReact.renderToolCalls. FixesuseComponentrendered nowhere and chat history degraded on unmount outright.components/CopilotChat.tsx— consumption viauseRenderToolCall. RN stops callingJSON.parseon a streaming argument buffer that is invalid JSON by design, and delegates to thepartialJSONParsepath react-core has used since v2. Fixes tool renders never streamed.hooks/render-tool-types.ts— the props type is derived, not declared. Makes the collapse permanent againstReactToolCallRenderer.
Two things the review changed that are worth not skimming
- The headline fix was inert in production.
toolMessagesandlistItemswere memoised onagent.messagesarray identity, but core inserts tool results withspliceanduseAgentre-renders with a bareforceUpdate()— so the dependency never changed. Renderers kept receivingresult: undefined, and messages appended mid-run never reached the flat list. 253 tests were green over it because the test harness reassigns the messages array while production mutates it in place. Inline note on the fingerprint has the detail. - Both #4893 guards passed on real violations. The purity script reported clean while
dist/v2/headless.mjsimported from the fat root entry; the entry-surface guard was harvesting 8 phantom import specifiers from JSDoc examples, and its existence test reportedTests no tests. Both now carry evidence in the direction that matters — introduce the regression, watch it fail.
Bundle size, specifically
Nothing about the 92.7 kB figure changed — byte-identical at 94941 B, and react-dom was verified absent from the graph (0 of 653 modules), so the "flat" claim stands. What changed is whether that number can be trusted and whether the guards behind it work:
- the measurement script could print "0.0 kB" on a broken run — the real reproduction measured 35 B, which still formats as 0.0, so a literal zero-check would have missed it. Now: plausibility floor, surfaced esbuild warnings, and an actionable message when
distis missing. - the purity gate now walks the resolved 650-module graph via esbuild's metafile instead of substring-scanning a fixed file list, and ships 17 negative tests.
- it no longer crashes on Node 18 (
import.meta.dirnameneeds ≥ 20.11 while rootenginessays>=18). dev-docs/bundle-size.mdhad six claims contradicted by the workflow it documents (action pin, package inventory, asserted entries, coverage overclaim) — corrected.
One conceptual gap — and a small edit the description needs
The description says "React Native and web cannot re-diverge — if the contract changes, check-types says so." The first half is earned; the claim as written is not. react-core still publicly exports its own hand-declared RenderToolProps<S> using parameters and string-literal status, so the two same-named public types differ today — and check-types cannot see it, because the one bridge where the shapes meet compiles (a string-enum member is assignable to its own literal type). Detail inline on render-tool-types.ts. Suggested fix: scope the guarantee to "RN cannot drift from ReactToolCallRenderer", and file the web-side alignment separately since it is a breaking web API change.
Status
All 28 mandatory review findings are fixed. Local verification: RN 287/287 tests (23 files, default parallelism, 4.71 s — the flake is gone), react-native + react-core typechecks clean, react-core test:scripts 19/0, oxfmt --check clean, oxlint 0 errors.
Still outstanding: an unbiased confirmation review over these 27 commits, and ~15 deferred findings belonging to two follow-up subjects — pre-existing CopilotKitProvider.mdx docs accuracy, and pre-existing RN CopilotChat/provider defects such as attachment content collapsing to an empty bubble and a failed send destroying the draft.
| // No cast needed: ReactFrontendTool.render is ReactToolCallRenderer<T>["render"], | ||
| // and RenderToolFunction is derived from exactly that props type, returning | ||
| // ReactElement | null (assignable to ComponentType's ReactNode). | ||
| render, |
There was a problem hiding this comment.
★ THE core fix — start here. This one call is what collapses two registries into one.
useFrontendTool writes the renderer into CopilotKitCoreReact.renderToolCalls — the same registry useComponent writes to, and the one RN's provider already instantiated and never used.
Directly solves two of the three reported bugs:
useComponentrendered nowhere — it wrote to core's registry while RN's chat read RN's privateMap. Now there is one registry.- Chat history degraded to
Called: <name>— the privateMapdeleted renderers on unmount; core deliberately retains them.
Note there is no cast on render (see the comment just above): ReactFrontendTool.render is ReactToolCallRenderer<T>["render"], and RenderToolFunction is derived from exactly that props type. If a cast were needed here, the convergence would be cosmetic.
| const isRunning = agent.isRunning; | ||
|
|
||
| const toolRenderers = useRenderToolRegistry(); | ||
| const renderToolCall = useRenderToolCall(); |
There was a problem hiding this comment.
★ The consumption half of the fix — and the reason bug 1 (tool renders never streamed) goes away.
Before, this component did JSON.parse(tc.function.arguments || "{}"). While a model writes a tool call that buffer is invalid JSON by design — AG-UI delivers TOOL_CALL_ARGS deltas that are concatenated client-side — so the parse threw on every delta, warned, and fell back to {}.
The fix is not a better parser: RN stops parsing arguments at all and delegates to react-core's useRenderToolCall, which has used partialJSONParse on this path since v2 shipped. JSON.parse now has zero occurrences in this file — the bug class is removed rather than patched.
| // Recomputed every render — cheap, and the only honest dependency for the | ||
| // message-derived memos below. See `messagesFingerprint` for why the array | ||
| // reference cannot be used. | ||
| const messagesKey = messagesFingerprint(messages); |
There was a problem hiding this comment.
These memos were keyed on [messages], i.e. on agent.messages array identity. Identity is not a reliable change signal, in either direction:
- It does change on streamed deltas —
@ag-ui/client'sAbstractAgent.processApplyEventsreassignsthis.messagesper applied event. (Credit to @BenTaylorDev for probing a real AG-UI run to establish this.) - It does not change on the paths this memo exists to serve — core inserts tool results with
agent.messages.splice(insertAt, 0, toolMessage)(packages/core/src/core/run-handler.ts:931,:1080),AbstractAgent.addMessageis athis.messages.push(...), anduseAgentre-renders with a bareforceUpdate()(react-core/src/v2/hooks/use-agent.tsx~L389).
So a tool result spliced into the existing array left both memos frozen at whatever the first render of a run saw: renderers kept receiving result: undefined with a status that never reached complete, and listItems only recomputed when isRunning flipped, so messages appended mid-run never reached the flat list at all.
Why 253 tests were green over this: the RN chat suites drove messages by re-rendering with a new array, which does change identity. Production splices, which does not — the suite exercised a mutation mode core never uses on that path.
The fingerprint keys on ids, roles, content, toolCallId, and tool-call ids + argument lengths, following the shape of react-core's web messagesMemoKey.
Correction (edited). This comment originally justified the fix by asserting "nothing in production ever reassigns .messages — grepping for that assignment in packages/core/src hits test files only." The grep was accurate but the conclusion was over-general: the reassignment lives in @ag-ui/client, outside that path. The fix stands — core's splice/push paths genuinely leave the reference untouched — but the stated reason was wrong and has been corrected here and in the source comment.
| id: m.id ?? m.toolCallId, | ||
| role: "tool", | ||
| toolCallId: m.toolCallId, | ||
| content: toolResultContent(m.content, m.toolCallId), |
There was a problem hiding this comment.
Silent data loss, and a platform divergence inside a convergence PR.
This was typeof m.content === "string" ? m.content : "" — a non-string tool result became "", which is indistinguishable from a genuinely empty result, with nothing logged.
Reachability is subtle and worth recording: ToolMessageSchema.content is z.string() and the SSE transport zod-parses every event, so the branch is unreachable on the validated path. But core keeps the identical hedge (normalizeToolResultContent, run-handler.ts:721) because protobuf transport, restored thread history and as Message casts all bypass validation.
The clincher: web's CopilotChatToolCallsView.tsx:23 passes content through uncoerced. So on any unvalidated path RN was destroying data web preserves — exactly the asymmetry this PR exists to remove.
| * `React.ComponentProps`. Change that contract and RN's public type changes | ||
| * with it, so `check-types` names every RN renderer the change breaks. | ||
| * | ||
| * What it does NOT buy: parity with the type react-core *publicly exports* |
There was a problem hiding this comment.
★ Conceptual gap — worth reading before merge, and the PR description needs a matching edit.
The derivation below is real and valuable: RN's props cannot drift from ReactToolCallRenderer, the contract every registered renderer is actually invoked against. That is the drift that caused the three bugs, and it is now structurally closed.
What it does not buy is the symmetric claim in the PR body — "React Native and web cannot re-diverge — if the contract changes, check-types says so." As written that is false:
- react-core publicly exports its own
RenderToolProps<S>(src/v2/hooks/use-render-tool.tsx, L9-36) as a separate hand-declared union:parameters(notargs), andstatusas the string literals"inProgress" | "executing" | "complete"(notToolCallStatusmembers). - Both divergences are live today, in this PR. Two packages export a type named
RenderToolPropswith different field names and different status types. - If the canonical contract changes, RN follows automatically and web's public alias silently does not — and nothing fails, because the one place the shapes meet (react-core's own bridge,
use-render-tool.tsx~L178-186) spreads the enum-typed renderer props into the literal-typed slot and compiles: a string-enum member is assignable to its own literal type, but not the reverse. Web'sstatusis a widening of the canonical contract, not a derivation from it.
Confirmed empirically: flipping the canonical status from enum to literals produces 6 tsc errors, all in unrelated files and zero in the type guard — and RN has no such incidental bystanders, so on the RN side that drift would be completely silent.
Suggested body edit: keep the guarantee but scope it to "RN cannot drift from ReactToolCallRenderer", and note that aligning react-core's public alias is a breaking web API change, filed separately.
| // dist, a stubbed entry) — i.e. a broken measurement, not an improvement. | ||
| // Sits ~11x below the real figure so legitimate size work never trips it; if a | ||
| // real change ever approaches it, move the floor in the PR that explains why. | ||
| export const MIN_PLAUSIBLE_BYTES = 8 * 1024; |
There was a problem hiding this comment.
★ Why the reported bundle number is now trustworthy. This script's output is the evidence for the headline "92.8 kB → 92.7 kB, flat" claim, and as written it could silently report a triumph.
It had no zero-output guard (its react-core sibling exits 1), logLevel: "silent" discarded esbuild warnings, and there was no try/catch — so a broken run printed "0.0 kB" straight into the CI job summary.
The detail that made a literal total === 0 check insufficient: reproducing the failure measured 35 bytes, not 0 — and 35 B still formats as "0.0 kB". Copying the sibling's exact guard would have missed the real failure mode, because a broken resolve still emits a tiny stub. Hence a plausibility floor rather than a zero check.
Also fixed: an unbuilt dist now produces an actionable preflight naming the build command instead of a raw esbuild "Could not resolve" stack, and warnings are surfaced with source frames. Verified end-to-end through the CLI, not only via unit tests. Happy path still reports 92.7 kB, unchanged — comparability across PRs is the entire point of the number.
| // `react-dom/client` and `react-dom/server` (esbuild CHANGELOG 0.5.14 / 0.14.13). | ||
| // `react/jsx-runtime` is kept explicit only because it documents that this entry's | ||
| // JSX transform is the host's; it is redundant under that prefix rule. | ||
| export const HEADLESS_EXTERNAL = [ |
There was a problem hiding this comment.
react-dom externalization — finding refuted, guard added anyway; the figure did not move.
Reviewers flagged that react-dom was missing from external (unlike the sibling) and would inflate the measurement by "~130 kB". Checked with a metafile run: 0 of 653 input modules are react-dom, nothing references it even pre-resolution, and all four candidate external lists produce an identical 94941 B. So there was no active inflation, and the headline figure is unaffected.
Two corrections worth recording:
- The "~130 kB" is the raw magnitude, not gzip. Measured inflation a stray edge would actually cause:
react-dom/client+56.3 kB,react-dom/server+57.3 kB, barereact-dom+1.4 kB. Still ~60%, so the guard earns its place — and the nastiest case is the smallest, since +1.4 kB reads as noise rather than a regression. - Subpath entries are unnecessary: esbuild prefix-matches package paths, so
react-domalone covers/clientand/server(verified on the pinned 0.27.3). The sibling's longer list is deliberately not copied verbatim, because listing subpaths implies they are required.
| throw new Error(`cannot resolve local specifier "${spec}" from ${fromFile}`); | ||
| } | ||
|
|
||
| describe("react-native entries: no runtime value is re-exported type-only", () => { |
There was a problem hiding this comment.
★ The most durable thing added here — a self-extending guard, not a symbol list.
Five runtime values had been re-exported type-only. A guard covering those five would rot the moment someone re-exports a sixth enum.
This layer instead parses both entry sources and fails any type-only re-export whose source module has a runtime binding — no symbol list, empty allowlist, so it covers symbols that do not exist yet.
It matters that this lives on the RN side: react-core's headless-type-exports.test-d.ts structurally cannot catch this class. Proof — react-core's own UseAgentUpdate was already a correct value export while RN's was wrong, so a react-core-side guard is blind to RN's entry surface. And the stripped-binding failure is invisible to tsc by construction, which is why the sibling layers here are runtime assertions plus a type-level usage that fails check-types with TS1362.
Proven with three transient FAIL/PASS pairs, including AbstractAgent (a class, which behaves differently from an enum) and UseAgentUpdate via the sneakier inline type prefix rather than the block form.
| for (const m of code.matchAll(importRe)) { | ||
| const spec = m[1] ?? m[2]; | ||
| if (!spec) continue; | ||
| const code = stripComments(fs.readFileSync(file, "utf8")); |
There was a problem hiding this comment.
This #4893 guard did not guard, and the PR body claims it carries mutation evidence. All four defects were reproduced by introducing the violation and watching the guard pass:
- The import regex was blind to dynamic
import()andrequire(), so a lazy optional-peerrequire("@copilotkit/react-core/v2")defeated it entirely. - It matched imports inside comments — and was already harvesting 8 phantom specifiers, exactly half its entire bare-specifier set, purely from JSDoc examples. It also rejected a legitimate "don't do this" counter-example written in a comment, so documenting the hazard could fail the build.
resolveLocalsilently dropped subgraphs it could not resolve, so an unresolvable edge read as clean — and a real/v2re-export hid behind an ESM-style./foo.jsedge.- The existence test was dead:
walkGraphthrew at collection, so it reportedTests no tests— all 11 assertions silently gone, not one failure.
Now strips comments before matching, extracts import() / require() / require.resolve() and flags non-literal loader arguments, resolves emitted extensions, fails loudly on anything still unresolvable, and asserts the resolved graph exactly.
| describe("runtime export surface", () => { | ||
| let mod: typeof HeadlessEntry; | ||
|
|
||
| beforeAll(async () => { |
There was a problem hiding this comment.
Flake fix, with the cost measured rather than the timeout raised blindly.
The await import("../headless") took 4568 ms against a 5000 ms budget on an idle machine — 91% of the allowance before any load — and four tests each awaited that same one cost, which is why the signature was three simultaneous timeouts rather than one slow test.
Root cause: Vite transforming ~283 kB of workspace dist that vitest.config.mjs inlines via server.deps.inline: [/@copilotkit/], per worker, with no persistent cache. A bare-Node import of the same prebuilt dist is 461 ms, so evaluation is cheap — it is resolve/transform plus cold page-cache I/O. The variance broke the budget, not the mean.
Two deliberate constraints: the import could not be made static, because these four checks assert exports exist as runtime values (a static read would weaken the guard); and the hook is nested on purpose, since a top-level one would drag the fs-only graph tests into the import's failure domain — recreating defect 4 above inside a hook.
Acceptance: 5/5 green at default parallelism with no --maxWorkers / --testTimeout overrides, plus 5/5 under load average 180–235 (including one run at 26.96 s wall — the exact failing-baseline profile) and three concurrent full suites green. Every test in the file now reports 0–4 ms.
Why the private registry existed in the first place — the archaeologySince this PR deletes Short version: the original justification was true on the day it was written, stopped being true two and a half months later, and nobody revisited it. OriginThe commit body says only: "Hook for rendering custom tool UIs in React Native with a store-based context provider. Includes tests for register/unregister, subscriber notification, and error handling." No rationale — it documents what, never why. The reasoning does exist, but it was recorded in a different file. At that same commit, // useRenderToolCall — web-specific (depends on DOM elements via DefaultToolCallRenderer)On 2026-05-22 that was a defensible callTwo facts made forking the registry the cheaper option that day:
So at creation, consuming core's hook meant either shipping DOM elements or shipping the fat entry. A 150-line local What changed, and what didn't
That's the actual failure mode, and it isn't "someone made a bad decision". It's a correct decision whose expiry condition was never written down. The comment recorded a true observation about a specific import graph on a specific date; what it didn't record was "revisit this if the hook moves to a lean entry." So when precisely that happened, nothing connected the two. Why the drift then cost real moneyThe fork wasn't merely redundant — it froze RN's contract at May's shape while core's grew. export interface RenderToolProps<T = Record<string, unknown>> {
args: T; // never partial — promised complete args mid-stream
status: "executing" | "complete"; // no "inProgress" state at all
result?: string;
} // no name, no toolCallIdWhich is how you end up with renderers that can't represent a streaming call, and the three bugs this PR fixes. And per the data point already in the description, the fork never bought a byte: Metro doesn't tree-shake, so the hook was already inside the chunk every RN app resolves whole. One correction to the descriptionThe body currently says the exclusion was made "on the stated grounds that it 'depends on DOM elements via That's a little unfair as written. At
Same conclusion, but it survives someone checking the May tree — which matters, because the whole argument of this PR is that stale justifications get trusted. |
BenTaylorDev
left a comment
There was a problem hiding this comment.
Reviewed against current main (54c32a1945). Merges cleanly, CI green across the board. The core of this is right: I traced the three bugs and the convergence holds up. Two small things I'd want changed before it lands, and a few notes.
What I verified independently
- Streaming (bug 1) genuinely fixed. I probed a real AG-UI run to confirm the mechanism rather than trust the memo: every
TOOL_CALL_CHUNKapply produces a new messages array, message,toolCallandfunctionobject. SoToolCallRenderer's comparator (use-render-tool-call.tsx:78-97) sees the changedargumentsstring, re-renders, andpartialJSONParseyields growing partial args. Worth stating explicitly because the opposite — in-place mutation of the sametoolCall— would have silently defeated that comparator and left the headline fix inert. - History retention (bug 3):
useFrontendTool's cleanup removes the tool but deliberately not the renderer (use-frontend-tool.tsx:38-41). Confirmed. useComponentis safe on RN: it's a pure passthrough (use-component.tsx:83-86), no DOM wrapper, so pointing RN at core's registry can't crash it.- The #4893 purity guard actually guards. Ran
assert-headless-purity.mjsagainst a real built dist (clean, 649 modules), then appendedimport "streamdown"todist/v2/headless.mjs— it failed and named shiki/mermaid/cytoscape/katex/streamdown. Mutation evidence reproduced independently. - Suites: RN 287 passing / 23 files, both
node --testscript suites green. Removed coverage (malformed JSON, empty args, executing status) is re-covered against the real registry and expanded. No references touseRenderToolRegistry/RenderToolProviderremain anywhere in the repo.
Things I tried to break and couldn't: render-only tools losing complete (core splices a tool message even with no handler, run-handler.ts:839-876); export { AbstractAgent } adding runtime weight (@ag-ui/client is already fully in the graph via @copilotkit/core); the esbuild manifest/lock specifier mismatch (explained by the root pnpm.overrides entry "esbuild": ">=0.25.4").
Two changes I'd ask for
1. messagesFingerprint is a copy of react-core's pre-#6325 memo key.
CopilotChat.tsx:88-96 uses contentKey = 0 for object content. #6325 (de0a659b2d) landed on main and changed exactly that, serializing object content:
: m.content && typeof m.content === "object"
? JSON.stringify(m.content)
: 0;So the comment's claim that this "mirror[s] react-core's web messagesMemoKey" isn't true as of now. It is not a live RN bug — activity messages carry role: "activity" and RN's list builder only handles user/assistant, so they never reach a renderer. But it re-opens a divergence in the PR whose thesis is closing them, and it's a one-ternary fix.
2. The BREAKING CHANGE: footer on db67ccf is incomplete, and release notes derive from it.
It covers the two removed exports but not the RenderToolProps shape change. Existing RN renderers that read args.foo without first narrowing on status now fail check-types — verified, TS18048, because the inProgress arm makes args Partial<T>. That's the break most consumers will actually hit, and it should be in the footer.
For the record, I checked the other direction too: status === "executing" against the enum union still compiles and narrows, so raw-string comparisons in existing renderers are not a break. The docs' "compare against the enum" guidance is good practice, not a requirement.
Notes, not blockers
- One justification comment is measurably wrong.
CopilotChat.tsx:75-86(and the matching inline comment) says "nothing in production ever reassigns.messages— grepping for that assignment inpackages/core/srchits test files only." The reassignment lives in@ag-ui/client's apply pipeline, outside that grep's scope; the array identity does change on every delta. The fingerprint is still justified — core'sspliceof tool results andaddMessagepushes are genuinely in-place — but in a PR this reliant on its comments being exact, the stated reason should be corrected rather than left as the load-bearing rationale for a perf-sensitive design. - Two deliberate tripwires worth accepting knowingly: the exact-graph snapshot (
headless-entry-surface.test.ts:303-329) will fail any future PR that adds a module or bare import to RN's headless graph, and the purity guard hard-fails on any non-literalimport()/require()in first-party graph files — which includes@copilotkit/coreand@copilotkit/sharedbuilt output. Both are defensible; both put a red check on someone else's unrelated PR when they trip. - The removals are a genuine break in a
1.xpackage. I have no objection to the "pull the plaster off" call — flagging it as Tyler's to ratify rather than mine.
An earlier commit rewrote the useRenderTool reference to say that comparing a render prop's `status` against a raw string no longer type-checks, and called that a breaking change. That was wrong, and it made upgraders believe working code was broken. `ToolCallStatus` is a string enum, and TypeScript relates an enum literal type to a same-valued plain string literal (not the reverse). Equality tests comparability both ways, so `status === "complete"` compiles AND narrows. Only two forms fail: comparing against a string that matches no member (TS2367), and assigning a raw string to a `status`-typed variable (TS2322) — assignment, never comparison. Corrected all three sites that claimed otherwise (the RenderToolProps narrative, the `status` PropertyReference, and the migration section's "both halves are breaking"). The enum-based examples stay, now framed as recommended style — self-documenting, and loud if a member's value changes — rather than a compilation requirement. The migration section now names the added `InProgress` arm as the one genuinely breaking half. Also fixed a separate false claim in the same file: the out-of-chat rendering example said that without a `toolMessage` the status "stays InProgress ... forever". `useRenderToolCall` reads `executingToolCallIds` from the provider and branches toolMessage -> Complete, else isExecuting -> Executing, else InProgress, so the Executing arm is reachable with no tool message at all. Docs only; no source behaviour changes.
`messagesFingerprint`'s header JSDoc and the matching inline comment near the
`listItems` memo justified keying on message CONTENT with a claim that is false:
that `agent.messages` is mutated in place throughout, and that "the AG-UI apply
pipeline reuses one array for a whole run".
It does not. `@ag-ui/client`'s `AbstractAgent.processApplyEvents` REASSIGNS
`this.messages = applied.messages` for every applied event, so a streaming run
hands down a new array — and new message, `toolCall` and `function` objects — per
delta. Verified against a real AG-UI run by the PR reviewer, and confirmed here in
@ag-ui/client 0.0.57's `AbstractAgent`. The old grep behind the claim ("assigning
`.messages` in packages/core/src hits test files only") is accurate but proves
nothing: `@ag-ui/client` is a dependency, outside that tree.
The fix itself stands. Identity is unreliable in BOTH directions, which is the
actual rationale: it changes on the apply path, and it does NOT change on the
paths these memos exist to serve — core splices tool results in place
(`agent.messages.splice(insertAt, 0, toolMessage)`,
packages/core/src/core/run-handler.ts:931, :1080), `AbstractAgent.addMessage` is a
`this.messages.push(...)`, and `useAgent` re-renders with a bare `forceUpdate()`
(packages/react-core/src/v2/hooks/use-agent.tsx:382-396). A signal that both
misses changes and fires without them cannot be a dependency, so the derivations
must key on content.
Comments only: three sites reworded (the JSDoc, the "cannot be used" pointer at
the `messagesKey` call, and the inline note on the `listItems` memo). `git diff`
touches no behaviour, type or dependency array — every changed line is a comment.
The `contentKey` length-vs-value paragraph is left alone; another change owns it.
Note: the same false claim is in commit 77ed31c's body, which cannot be
rewritten, and in a GitHub review comment.
Not run in this worktree: it has no node_modules, and the change is comment-only,
so it cannot affect types, lint or tests.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
e7f3d76 rewrote the #4893 gate from a substring scan of four inlined entry files into an esbuild `metafile` walk over the resolved graph, but the doc was corrected one commit earlier (2158a6f) and so described the deleted implementation. Rewritten to match the code: - Tier 3 item 1 now describes the graph assertion: esbuild with `metafile: true`, matching on resolved input paths (never file contents), `packageNameFor`'s last-`node_modules/` rule, external specifiers collected from `imports[].external`, fail-loud on an unresolvable edge / an entry missing from its own graph / graph-blinding warnings, comment stripping before the one text scan, and the negative tests in scripts/__tests__/assert-headless-purity.test.mjs. - Dropped the now-false claims: "substring scan of four files", "cannot follow edges", "a forbidden name in a comment fails it", and "a dep arriving transitively through an externalized package would pass" (the gate re-bundles with only react/react-dom external). - `size:headless` no longer described as never hard-failing: it exits non-zero on an unbuilt dist, an esbuild error, and a total of 0 or under MIN_PLAUSIBLE_BYTES. `size:headline` keeps its zero-output guard. Phase 1's "no hard-fail" is now scoped to size *thresholds*. - Added a Known limitations list so the doc does not overclaim in the other direction: the first-character-after-`(` literal check (a template literal or concatenation starting with a quote is skipped), unmatched `__require(...)`, string literals not stripped before the text scan, workspace-sibling `dist` counted as first-party (so a dep inlined there yields no package name), only the four .mjs/.cjs targets asserted, and the `@`-prefix family match's over-reach. - Tier 3 item 2 now reflects that the RN walker also extracts dynamic import()/require() and fails loudly on unresolvable local edges. Workflow claims verified against .github/workflows/static_bundle_size.yml: the action pin (2.10.0) and the "step names /v2/headless, script covers /v2/context" note were already correct and are unchanged. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The guide told readers that a `"*"` entry resolves as a renderer-only wildcard
on React Native "exactly as it does on the web", and framed the one difference
as an ergonomic tax (a `"*"` entry "still needs `parameters`"). That is false,
and the real consequence is not ergonomic.
react-core's `useRenderTool` is renderer-only: its body's sole registration is
`addHookRenderToolCall` (use-render-tool.tsx:190), and it special-cases
`name === "*" && !parameters` into a schema-less fallback renderer
(use-render-tool.tsx:166) which `useRenderToolCall` resolves last
(use-render-tool-call.tsx:151). React Native's hook instead delegates wholesale
to `useFrontendTool` (useRenderTool.ts:53), which calls `addTool`
unconditionally (use-frontend-tool.tsx:23). So on RN `name: "*"` registers a
frontend tool literally named `*`. `buildFrontendTools` has no wildcard
exclusion (run-handler.ts:1236), so that tool is advertised to the model in the
run's tool list, and it occupies core's separate wildcard-executable-tool slot
(run-handler.ts:610, 626) whose handler is invoked for every unmatched tool call
with args wrapped as `{ toolName, args }` (run-handler.ts:988) rather than in
the caller's declared shape.
- Rewrote the bullet to advise against `"*"` on React Native and state the
mechanism. Also completed its requirements list: `description` is as
non-optional as `parameters` (useRenderTool.ts:13), and react-core's hook
takes no `description` at all.
- Fixed the example's `status !== "complete"`, which was a web-shaped parity
assumption that does not compile: RN's props derive from
`ReactToolCallRenderer`, whose `status` is the `ToolCallStatus` enum, not
web's string literals. Branches on `ToolCallStatus.Complete` now, and notes
the `args`-vs-`parameters` difference alongside it.
- Added a Known limitations entry, in the voice of the `threadId` one, covering
the wildcard gap plus two more the audit turned up: `followUp` and
`available` are accepted by `useFrontendTool` and not forwarded, and the
`handler` type drops the `context` argument core does pass at runtime
(run-handler.ts:821). All tracked for the convergence follow-up.
No `followUp` claim was present on the page to correct — the gap is real, so it
is documented as a limitation rather than a retraction. No behaviour change:
`packages/react-native/src/hooks/useRenderTool.ts` is untouched, the
convergence is its own PR.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The PR's reviewer asked that the `RenderToolProps` shape change be covered where upgraders actually read it. A `BREAKING CHANGE:` footer on ec42161 already describes it, but that footer reaches no reader: `scripts/release/lib/changes.ts:43` collects commits with `--format=%H %s`, and `grep -rn "BREAKING" scripts/release/` returns zero hits, so no footer in this repo has ever reached generated release notes. The docs page is the destination that does reach users. (The collector is a release-pipeline bug, filed separately.) Checked every item in ec42161's inventory against the page. All were present and accurate except one: the page said renderers "must now tolerate missing fields while in progress" and stopped there, naming no error code and never mentioning `check-types`. That is the half of the change most existing renderers trip over, and it breaks the build, not the screen. Added to the migration section: on the un-narrowed union `args` is `Partial<T> | T`, so `args.foo` reads as `T["foo"] | undefined` and a strict `tsc --noEmit` rejects any use needing the field present — TS18048 when dereferencing or calling it, TS2322/TS2345 when passing it into a slot typed without `undefined`. Deliberately NOT claimed as a blanket "every read fails": a bare JSX interpolation still compiles because an element accepts `undefined` children, and the page's own Usage example does exactly that, so the blanket form would have contradicted a working example on the same page. Added a fix diff narrowing on `status`, and a cross-link to the two Behavior-section breaks a migration-only reader would otherwise miss (render captured at registration, unmount keeping the renderer). Verified against source, not just the footer: the three-arm union in react-core/src/v2/types/react-tool-call-renderer.ts, the effect keyed on JSON.stringify(deps) and the cleanup that removes only the tool in use-frontend-tool.tsx, and `"strict": true` plus `check-types` in the react-native package. Docs only; one file, no restructuring, nothing removed. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…t on growth
The headless import-graph guard pinned the resolved graph EXACTLY — the
11-module list and the 8 bare specifiers, both `toEqual`. That catch-all was
deliberate (a heavy dependency nobody enumerated still had to be looked at),
but it also went red on innocent growth: adding any first-party `src/` module
to the headless graph failed it, on someone else's unrelated PR. A guard that
fails on innocent changes gets deleted by the third person who hits it, and
then it guards nothing.
Express the catch-all over PACKAGES instead of MODULES: the graph may only
reach packages a headless consumer is guaranteed to be able to resolve — this
package's `dependencies` plus its NON-optional `peerDependencies`, read from
package.json rather than hand-copied. That is precisely the promise the
headless entry sells ("bundles with nothing stubbed in metro.config.js"), so
it still fails on any new third-party edge, on every optional peer, on a
devDependency, and on a Node builtin — while a new first-party module or
another import of an already-sanctioned package is free.
The two other things the pin bought are kept explicitly:
- Comment stripping. The eight phantom specifiers JSDoc examples used to
harvest were all self-references, and this package's own name is not in the
guaranteed set, so a `stripComments` regression still fails here.
- Non-vacuity. Every remaining graph assertion is a deny-list, and a deny-list
over a truncated graph passes for the wrong reason, so a subset floor
asserts the walk still reaches the provider, the polyfills and the
react-core headless edge.
Not changed: comment stripping itself, the import()/require()/require.resolve
extraction, non-literal loader flagging, emitted-extension resolution, the
loud failure on unresolvable edges, the entry-presence tests, the #4893
fat-entry ban (still the assertion that catches `@copilotkit/react-core/v2`)
or the heavy-dependency ban. The runtime-export `beforeAll` is untouched.
Proven both directions: a new first-party module passes the loosened guard and
fails the old pin; `@copilotkit/react-core/v2`, `shiki`, an unenumerated
devDependency edge and a truncated walk each fail.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…paths Both scripts decided "am I the entrypoint?" by comparing `import.meta.url` to a `file://`-concatenated `process.argv[1]`. `import.meta.url` is percent-encoded and symlink-resolved; raw argv[1] is neither. So the comparison was false for any checkout path containing a space, for any invocation through a symlink (macOS /tmp is one), and on Windows — and a false guard skipped the whole CLI block. Reproduced before fixing: the #4893 purity gate and the bundle-size measurement both exited 0 having printed nothing and asserted nothing, which is worse than a gate with holes because it manufactures confidence. The guard was added by this PR so the modules could export internals to their new negative tests; making the gates testable introduced a way for them not to run. Both now compare real filesystem paths through an exported `isEntrypoint`: `fileURLToPath` defeats the encoding and Windows forms, `fs.realpathSync` on both sides defeats symlinks, and a `path.resolve` fallback keeps a nonexistent argv[1] from throwing. Each `node --test` suite gains five entry-guard tests, including an end-to-end spawn of the real script through a symlinked package-root alias whose name contains a space — the only case that catches the call site regressing back to a string comparison (verified: it fails against the old expression). The unit cases assert the naive comparison really would have failed, so none of them can pass vacuously. Both negative gates were re-proven to still bite: a doctored dist entry pulling streamdown fails the purity gate, and a stubbed dist entry trips the measurement's plausibility floor. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`messagesFingerprint`'s content key collapsed every object to 0, so an in-place content replacement that kept the same message id was invisible to every memo derived from it. Its comment claimed to mirror react-core's `messagesMemoKey`, which stopped being true when react-core #6325 (de0a659) taught that key to serialize object content. Serialize object content here too, keeping the length-not-value treatment for string and array content so large text and base64 attachment payloads are still never re-serialized per render. Serialization is guarded: the fingerprint runs on every render and `JSON.stringify` throws on a circular structure, which this component is already required to tolerate (see the existing "does not throw on tool content that cannot be JSON-serialised" assertion) — react-core stringifies unguarded, so the guard is a deliberate and documented divergence. Not a live stale-render bug via the activity path: same-id object content comes from an ACTIVITY_SNAPSHOT replace, and `role: "activity"` never reaches `listItems`, which builds rows for `user` and `assistant` only. Object content DOES reach a renderer through the `role: "tool"` correlation, though, which is what the added test drives: an object tool result replaced in place used to leave the renderer showing the first object's serialization. The comment no longer claims to mirror a moving target — it records what the key captures, why the object branch exists, and that the two implementations are independent. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The #4893 hard-fail gate's loader-call detector gave WRONG VERDICTS IN BOTH DIRECTIONS. It layered two regexes — a comment/string/template alternation that blanked only the comment branch, and `\b(?:import|require(?:\.resolve)?)\s*\(` over the result — then classified an argument as static from the FIRST CHARACTER after the paren. All nine shapes below were reproduced against the real gate before the rewrite: false FAIL throw new Error("use require(path) instead") false FAIL `import(${x})` inside a template false FAIL o.import(y) / mod.require(x) (member calls, not loaders) false PASS /https:\/\//; …import(n) (the regex's `//` blanked the rest of the line, hiding a real dynamic call) false PASS import(`stream${n}`) (merely STARTS with a quote) false PASS import("zo" + n) (same) false PASS import(`${base}/v2/index.mjs`) (same — the fat entry) false PASS __require(name) (no \b inside `__require`) Replaced with `scanSource`, a single-pass tokenizer that classifies every character as code / comment / string / template / regex and returns a length-preserving masked view plus a literal-span list. The one surviving regex now only ever sees code, so import-shaped TEXT cannot reach it at all; an argument counts as static only when it is one COMPLETE literal with no concatenation or interpolation; `__require` is matched; and a member call is rejected both by lookbehind and by a whitespace-skipping back-scan (so `m\n .import(x)` is not a loader either). Proven in both directions: nine innocent/violation pairs run through the real `assertEntryPurity`, each innocent form CLEAN and each matching real violation FAIL. Re-proved end-to-end by prepending `import "streamdown"` to the real dist/v2/headless.mjs — exit 1 naming all five families — then restoring it byte-identically. On the untouched dist the scan sees 66 loader calls in the `.cjs` graph and classifies all 66 static, so it passes because it LOOKED. Also adds the first `.cjs` fixtures: every existing fixture was `.mjs`, leaving the script's `format: "cjs"` branch and the `require()` shape asserted by nothing. Tests 24 → 47. `stripComments` is renamed `maskNonCode`, since it now blanks literals and regexes too; it had no caller outside this script and its test. The RN guard keeps its own copy, untouched. dev-docs/bundle-size.md: the four holes a sibling agent documented as known limitations this round are closed and removed from that list; what genuinely remains (regex-vs-division heuristic, no JSX/TS, indirect loaders) replaces them. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
@BenTaylorDev — thanks, this was a genuinely useful review. Both requested changes have landed, plus three of your notes. Two of them I handled differently from what you asked, and one of those overrides your judgement, so I want those visible rather than buried in a diff. Nine commits since you reviewed ( 1. Memo key is a pre-#6325 copy — fixed (
|
BenTaylorDev
left a comment
There was a problem hiding this comment.
Re-reviewed at 4b17ea7d35 against current main (f13fcb09e9 — 117 commits ahead of this branch's base). Merges clean, CI green. Both changes I asked for are resolved, and on one of them my premise was wrong and yours was right. Approving the code; the one thing I'm still not ratifying is below.
The two asks
1. Memo key — fixed, and better than what I asked for. messagesFingerprint's object branch (CopilotChat.tsx:131-136) now matches react-core's messagesMemoKey (CopilotChat.tsx:989-1007). The try/catch around JSON.stringify is a divergence react-core doesn't have, and it's the right direction — react-core will throw on circular content in a render path, which is worth the separate issue you noted.
The new test is a genuine red-green: same id, role and toolCallId, and the two objects serialize to the same length, so a key measuring type or size alone still misses it. That's the assertion I'd have wanted and didn't ask for.
2. BREAKING CHANGE: footer — you were right, I was wrong. I said release notes derive from the footer. They don't, and I checked rather than take it:
scripts/release/lib/changes.tscollectsgit log --format=%H %s;Commitis{ hash, subject }— there is no field a body could occupy.grep -rn "BREAKING" scripts/release/is empty.prepare-release.ts:41-42buckets on/^feat[:(]/and/^fix[:(]/only, so a breakingrefactor!renders under "Other Changes" with its subject verbatim.
So the footer was never the channel I claimed it was, and putting the TS18048 break in useRenderTool.mdx is the better destination. ec42161670's footer already covers the Partial<T> shape change in full, so git log readers are served too. #6479 is the right home for the collector gap. Nothing further needed here.
What I checked in the delta rather than took on trust
- The allow-list relaxation does not weaken #4893. My concern was that computing the allow-list from
dependencieslets@copilotkit/react-core/v2through, since react-core is a legitimate dependency. It does — and the fat-entry ban is a separate, package-wide test (ALLOWED_REACT_CORE_ENTRIES,it.each(ENTRIES)) that survives untouched, as does theFORBIDDEN_HEAVYdeny-list. Your call over mine here was correct: the pin failed on innocent first-party growth, the replacement fails on undeclared third-party edges, and the guard that actually encodes #4893 never depended on the pin. - The wildcard retraction is inherited, not introduced. I traced it to
mainbefore accepting the framing:main's RNuseRenderToolalready pipesnamestraight intouseFrontendTool(useRenderTool.ts:71-82), and the oldRenderToolContexthad no"*"special-case either. Soname: "*"advertised a tool literally named*before this PR too. The retraction corrects the description, it doesn't confess a regression. - Numbers reproduce. RN vitest 289 passing / 23 files, react-core
test:scripts47/0, RNtest:scripts17/0 (the second needed the newesbuilddevDependency, which is real, not a wiring problem). - The
sideEffectsfinding is real. Builtdist/headless.mjsis 918 bytes of re-exports with zero polyfill references; the payload sits unimported indist/polyfills/*. Pre-existing and correctly out of scope — but worth knowing thatREQUIRED_HEADLESS_MODULES'polyfills.tsentry pins a source-graph edge the build then strips, so it proves slightly less than it reads like.
One thing to fix, not blocking
The tokenizer still hard-fails on a comment sitting next to an otherwise-static loader argument — the same false-positive class 4b17ea7d35 set out to close. isCompleteLiteralArgument runs its surround check against code rather than masked, so the comment text survives the .trim():
"magic comment before literal" -> ["import(/* @vite-ignore */ \"./a.js\");"]
"comment after literal" -> ["require(\"a\" /* side */);"]
Nothing in react-core's graph trips it today, but @vite-ignore is already idiomatic in this repo (packages/vue/src/v2/hooks/use-katex-styles.ts:38), so it's a live shape. Switching those two slices to masked fixes it and keeps concatenation and interpolation caught, since masked preserves length and blanks only comments and literals.
Still not mine to ratify
Removing useRenderToolRegistry and RenderToolProvider — two documented exports — in a minor of a 1.x package is a product call, and my approval isn't it. Please get Tyler's explicit sign-off before merging. Everything technical that would make that decision risky has been closed out; what's left is whether we want to pull the plaster off now.
Two bits of housekeeping when this lands: #6346 (@davidmckayv) is still open and should be closed with a pointer here — the Co-Authored-By credit is already in place. And your reply says the PR is still a draft, but GitHub has it marked ready; worth reconciling.
I bless the code with a glad heart.
…6533) Closes #6438's deferred review finding **5b**. #6438 shipped 5a — retracting the false claim that React Native supported wildcard renderers, and documenting the gap as a known limitation. This is the actual fix. ## The defect: one cause, not nine React Native's `useRenderTool` was **not** react-core's `useRenderTool`. Its entire body forwarded to a *different* hook while wearing the other one's name: ```ts useFrontendTool<T>({ name, description, parameters, handler, agentId, render }, deps); ``` react-core has two hooks: | hook | registers | wildcard `"*"` | | --- | --- | --- | | `useFrontendTool` | a tool **and** its renderer (`addTool`) | no special case | | `useRenderTool` | a renderer **only** (`addHookRenderToolCall`) | special-cased into a schema-less fallback | RN aliased the first under the second's name. Because that took the `addTool` path, `name: "*"` registered a frontend tool **literally named `*`**. **Correction from review.** Earlier revisions of this description said that tool was advertised to the model. It was not, and @BenTaylorDev caught it: core filters the wildcard name out of the advertised list in `run-handler.ts`, and that filter landed in `31aa1e2162` — before this PR was opened, but after the base it was originally written against. The 1273-commit rebase moved the code forward and left the prose behind. All seven code and doc sites have been corrected. **What it actually did is worse.** A tool named `*` is core's catch-all *handler*. When a tool call has no exact-name frontend tool and no result yet, core reaches for the wildcard tool and runs `executeWildcardTool` — and the tool-result splice sits *outside* the `if (wildcardTool?.handler)` guard. So an RN app whose author wanted a display-only fallback was also auto-answering every otherwise-unanswered tool call with an empty tool result and requesting a follow-up turn. Measured by driving a real turn through both paths: the old handler-less `*` produced **2 turns and a spliced `{ toolCallId, content: "" }`**; the shim's route produces 1 turn and no result. Eight further reported symptoms share that single cause: a render-only registration was advertised and shadowed a same-named server tool; `addTool` evicted an existing same-named handler with only a `console.warn`; `description` / `parameters` were required though both are *tool* fields; `followUp` / `available` were not forwarded; `handler` dropped core's context argument, leaving `stopAgent()`'s abort signal unreachable; `agentId` changes never re-registered; two structurally incompatible `RenderTool*Props` families shipped side by side; and `hooks/index.ts` was a dead barrel. ## The fix RN's own implementation is gone. `useRenderTool` and `useFrontendTool` are now re-exported from react-core, so each capability has exactly one implementation — **and `"*"` works as a real wildcard on React Native for the first time.** Deleting rather than re-pointing the name was deliberate: re-pointing would let a `{ name, parameters, render }` call with no handler keep compiling while silently ceasing to register the tool. ## The landing is soft, on purpose Following @BenTaylorDev's review, `useRenderTool` **still exists on React Native** as a deprecated shim for one minor. It routes by shape and warns in development, once per tool name: | call shape | routes to | why | | --- | --- | --- | | `name: "*"` | core's `useRenderTool` (renderer-only) | **unconditional — wildcard always wins**, even with old tool fields present | | carries `handler` or `description` | `useFrontendTool` | that is what the old hook actually did | | anything else | core's `useRenderTool` | renderer-only was the intent | The wildcard rule is deliberately not the obvious reading. The old hook made `description` **required**, so anyone who ever attempted a wildcard renderer necessarily wrote it *with* the old tool fields. Routing "has old fields" to `useFrontendTool` would have recreated the original `*`-named-tool bug for exactly the people who tried hardest to use the wildcard. **Why a shim rather than a clean break.** `@copilotkit/react-native` sits in the `monorepo` release scope — 16 packages versioned in lockstep, all currently `1.68.1`. A major would take every `@copilotkit/*` package to `2.0.0`. So this ships in a minor and the `!` marker buys a release-note line, nothing more. That leaves the compiler as the only signal reaching consumers, and there are shapes it cannot see: a hoisted config whose `render` ignores its props, old fields arriving via a spread, and untyped or `@ts-nocheck` call sites. In all three, core's hook silently ignores `description` and `handler`, and because the bridge spreads `{ ...props, parameters: props.args }`, an old `render: ({ args }) => …` keeps painting — the screen looks unchanged while the tool stops being advertised and the handler never runs. The shim's warning is the only mechanism that reaches that population. **What the shim does not restore:** the old *render prop* name. A renderer reading `args` still fails `TS2339`. The registration keeps working; the render body still needs the rename. ##⚠️ BREAKING — needs product ratification Removes `RenderToolProps`, `RenderToolFunction` and `UseRenderToolOptions` from `@copilotkit/react-native`. `useRenderTool` is deprecated, not removed, and is scheduled for removal next minor. **@tylerslaton — this needs your explicit sign-off.** @BenTaylorDev has clarified that his deferral on #6438 was not a precedent, and would rather both removals be ratified together. ### Migration | Before (RN) | After | | --- | --- | | `useRenderTool({ name, description, parameters, handler, render }, deps)` | `useFrontendTool({ …identical object }, deps)` — the shim keeps this working with a warning this release | | renderer-only registration: impossible | `useRenderTool({ name, parameters, render, agentId? }, deps)` | | wildcard: registers a tool named `*` | `useRenderTool({ name: "*", render })` — works, same as web | | render props `{ args, status, … }` | `{ parameters, status, … }` — **not** covered by the shim | | `RenderToolProps<T>` (args-shaped) | `RenderToolProps<S>` (parameters-shaped, generic over schema) | | bare `RenderToolProps` | now `TS2314` — core's has no default type argument; supply the schema type | | `UseRenderToolOptions<T>` | gone — write the config inline (`RenderToolConfig` is core-internal) | | `RenderToolFunction<T>` | gone — see `FrontendToolRenderFunction<T>` below | The table also lives on the docs page, deliberately: the release-note collector reads `git log --format=%H %s` into a `{ hash, subject }` type, so a `BREAKING CHANGE:` footer has nowhere to land (#6479). ## Restoring the React Native render-type safety Ben caught a property the migration silently traded away. RN's deleted `RenderToolFunction` was the only thing narrowing an RN render to `React.ReactElement | null`. `useFrontendTool`'s `render` is a `React.ComponentType`, so it returns `ReactNode` — meaning a bare string now compiles and then throws *Text strings must be rendered within a `<Text>` component* on device. Before the rename that call site was rejected. `FrontendToolRenderFunction<T>` is now exported from `/headless` for that. It derives its props from core's canonical `ReactToolCallRenderer` unchanged and narrows only the return type, so it cannot drift from the contract. It is **opt-in** — annotate your renderer to get the protection — and the hazard is now documented on `useFrontendTool.mdx`, which previously had zero mentions of `ReactElement`, `ReactNode` or `FlatList`. ## `status` changes vocabulary, and that is NOT a break RN's `status` moves from the `ToolCallStatus` enum to core's string-literal union. A string-enum member is assignable to its own literal type, so `status === ToolCallStatus.Complete` compiles **and narrows** against the union — verified in all four combinations. No migration work follows. This PR also deletes a false claim #6438 shipped: that comparing the enum to a bare string literal does not typecheck. Ben raised exactly this in #6438's review; it was corrected in the migration note and left standing in the guide bullet. ## The react-core half (2 files, 6 lines) `ReactToolCallRenderer.render` is a `React.ComponentType`, and a function component returns `ReactNode` — of which `null` is a member. So `null` already worked where a renderer is *invoked*; only the two build-side helpers forbade it. Widened to `React.ReactElement | null` in `use-render-tool.tsx` and `types/defineToolCallRenderer.ts`. Both are required — widening only the hook yields `TS2322`. Three things this does **not** claim: - **Not type-only.** oxlint's `consistent-type-imports` converted `defineToolCallRenderer.ts`'s `ToolCallStatus` import to `import type`, removing a runtime `@copilotkit/core` import from the emitted JS. Harmless, but not a types-only diff. - **Not uniform.** `useDefaultRenderTool` still requires `ReactElement`, so core's two wildcard entry points differ. That divergence fails loudly (`TS2322`) and gets its own change. - **Not web-only in reach.** `defineToolCallRenderer` is re-exported from `@copilotkit/react-native`. It lives in its own commit and lifts out cleanly if you would rather this PR stay RN-only. ## Two symptoms are documented, not fixed - **`agentId` re-registration** — both core hooks omit `agentId` from the effect's dependency check, so the `deps` workaround stands. - **`useDefaultRenderTool`'s narrower render return**, per above. ## Testing - **Red-green on the wildcard.** Before the deletion, `getTool({ toolName: "*" })` returned a real tool object — `{ name: "*", description: undefined, parameters: undefined }` — the defect verbatim. Green after: the `"*"` renderer paints for an unmatched call **and** no tool named `*` is registered. The shim has its own version of this test, since its wildcard rule exists to prevent that exact regression. Note per the correction above that the **registry** assertions are the discriminating ones; the `advertised` assertions are kept as forward guards against someone making `*` advertisable later, and their comments now say so rather than claiming to be load-bearing. - **All three shim routing rules**, asserted on core's observable state — `getTool`, `core.tools`, and the advertised tool list core hands an agent on a real run. - **The identity guard was replaced, not weakened.** `headless-entry-surface.test.ts` previously asserted only that `useRenderTool` was *present*, never which hook it was, so it would have stayed green through this entire change. The identity assertion closed that; the shim made identity false, so it is now a delegation test plus a graph-wide deny-list on `addTool` / `removeTool` / `addHookRenderToolCall` / `renderToolCalls` / `createContext`. Five mutations were run against it: re-growing a local registry fails both new guards; an early-return shim that still *looks* delegating fails 14 behavioural tests; removing the wildcard rule reproduces the original bug; removing the production gate and the warn-once dedup each fail their own test. - **A test whose name asserted the opposite of its behaviour** was replaced — it claimed to prove agent scoping and never checked that a scoped renderer does not paint under the default agent. - The RN suite was rewritten around what RN owns. The old file tested forwarding through a double so thin that its own header comment recorded that deleting the `deps`/`handler`/`agentId` forwarding left it fully green. - **A coverage pin was re-homed, not dropped.** An RN test pinning core's `JSON.stringify(extraDeps)` comparator was testing core, and no react-core test covered the case. - **`FrontendToolRenderFunction` is mutation-proved both ways** — widening the return to `ReactNode` or loosening the props each break the type test. - `packages/react-native/USAGE.md` was still teaching the deleted API. It **ships in the published tarball** (no `files` array, no `.npmignore`). ### Results ``` check-types (--skip-nx-cache) 2 projects + 34 dependency tasks ✅ react-native vitest 298 passed / 23 files ✅ react-core src/v2 vitest 1503 passed / 120 files ✅ react-core test:scripts 47 pass / 0 fail ✅ react-native test:scripts 26 pass / 0 fail ✅ ``` vitest transpiles without type-checking, so `tsc --noEmit` is the only guard against a re-narrowing of the six widened annotations. `static_quality.yml`'s `check-types` job runs it, and `nx.json`'s `targetDefaults.check-types.dependsOn` builds react-core's dist first, so the RN-side typecheck is meaningful rather than stale. ### What is NOT covered Worth stating plainly: **nothing here proves the package works on a real device.** The RN suite runs in jsdom with `react-native` aliased to a 52-line stub whose `FlatList` is a mock; no CI job runs Metro, a simulator, or Detox; and `examples/v2/react-native/demo` is not built or typechecked in CI. What this PR verifies is types, export surface, and behaviour against core's real registry. Separately, #6438's finding that RN's dist-relative `sideEffects` globs strip the polyfill import from the built entries is still live and still out of scope. ## Follow-ups (not in this PR) - Widen `use-default-render-tool.tsx`'s four render annotations, or document why core's two wildcard entry points differ. - Remove the shim next minor — tracked in #6976 and Linear OSS-1148, and cited in the shim's JSDoc. - Build or typecheck the RN example app in CI — the cheapest real-RN signal available. - `assert-headless-purity.mjs`'s `isCompleteLiteralArgument` reads `code` rather than `masked` — @BenTaylorDev's non-blocking ask on #6438, never actioned. - #6346 (@davidmckayv) is still open; Ben asked for it to be closed with a pointer when #6438 landed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Renderers can now return `null` to intentionally suppress tool-call UI. - React Native supports renderer-only tool-call registration, including named and wildcard renderers. - Added type guidance for React Native-safe renderer return values. - **Bug Fixes** - Improved compatibility routing for existing React Native `useRenderTool` configurations. - Prevented unnecessary renderer re-registration when dependencies are non-serializable. - **Documentation** - Updated React Native guidance for `useFrontendTool`, `useRenderTool`, shared rendering, migration, and deprecation behavior. - Clarified renderer props, status values, and `null` rendering behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
What does this PR do?
@copilotkit/react-nativemaintained a private tool-call render registry (hooks/RenderToolContext.tsx) alongside the canonical one thatCopilotKitCoreReactalready provides — and which every React Native app already ships, unused. This PR deletes the fork and points React Native at the shared registry.That fork caused three bugs:
useRenderTool/useComponentpainted nothing until the tool call completedCopilotChatusedJSON.parseon the argument buffer. While a model writes a tool call that buffer is invalid JSON by design — AG-UI deliversTOOL_CALL_ARGSdeltas that are concatenated client-side — so the parse threw on every delta, warned, and fell back to{}useComponentrendered nowhereMapCalled: <name>placeholderMapdeleted renderers on unmount; core deliberately keeps them@copilotkit/react-corehas usedpartialJSONParseon this path since v2 shipped. React Native diverged becauseuseRenderToolCallwas excluded from its re-exports on the stated grounds that it "depends on DOM elements viaDefaultToolCallRenderer" — a claim that was never true of the hook itself. It was only ever reachable through the fat/v2entry, whose weight is the real hazard (#4893). #5883 moved it into/v2/headlesson 2026-07-23; the exclusion comment was rewritten the next day without revisiting the reason.What changed
useRenderToolregisters throughuseFrontendToolintoCopilotKitCoreReact.renderToolCalls.CopilotChatand any custom surface consume react-core'suseRenderToolCall.RenderToolPropsis nowReact.ComponentProps<ReactToolCallRenderer<T>["render"]>, so React Native cannot drift fromReactToolCallRenderer— the contract every registered renderer is actually invoked against. Change that contract andcheck-typesnames every React Native renderer the change breaks. React Native narrows only the return type toReactElement | null, whichFlatList'srenderItemgenuinely requires.Scope of that guarantee (corrected during review): it does not extend to the type react-core publicly exports under the same name. Web's
RenderToolProps<S>(react-core/src/v2/hooks/use-render-tool.tsx) is a separate hand-declared union, generic over a schema, carrying arguments underparameters(notargs) and declaringstatusas string literals rather thanToolCallStatusmembers. Both divergences are live today and nothing type-checks them shut — the one place the shapes meet, react-core's own bridge, compiles because a string-enum member is assignable to its own literal type but not the reverse. Aligning web's alias is a breaking web API change, filed separately.RenderToolContext.tsxdeleted (−150 lines), along with 15 tests that described the removed subsystem. One of them —unregisters the render function on unmount— asserted the chat-history bug as a requirement./v2entry, and a script failing if react-core's/v2/headlessor/v2/contextchunks ever link shiki/mermaid/cytoscape/katex/streamdown. Both were verified able to fail by deliberately introducing the regression. These are structural assertions, not size budgets —dev-docs/bundle-size.mdfreezeslimitfields until OSS-122.react-nativeadded to the bundle-size glob, which it had never been in, plus asize:headlessmeasurement.React Native also gains capabilities it lacked: render props inferred from your schema,
name/toolCallIdon render props, andresulton completed calls.Corrected during review — two capabilities this originally claimed are not delivered:
"*") renderers do not work on React Native. BecauseuseRenderToolroutes throughuseFrontendTool(which callsaddTool),name: "*"registers a frontend tool literally named*— advertised to the model, and colliding with core's separate wildcard-executable-tool path. react-core'suseRenderToolis renderer-only and special-cases the wildcard; React Native's is not. The guide now advises against it.followUp(andavailable) are not forwarded, and the handler'scontextargument is dropped, sostopAgent()'s abort signal is unreachable from an RN handler.Both are tracked in § Known limitations for the follow-up that converges React Native onto react-core's hooks — deleting RN's
useRenderToolin favour of re-exportinguseFrontendTool(tool + renderer) and react-core'suseRenderTool(renderer-only, wildcard-capable). That is an API change with its own migration note, so it is not in this PR.useRenderToolRegistryandRenderToolProviderare removed. Both are documented on the docs site, so this is a real break — see theBREAKING CHANGE:footer ondb67ccf, which is what the release notes derive from, plus the rewritten reference pages.Also note two semantic changes:
argsisPartial<T>only whilestatusis"inProgress", and a render function is now captured at registration — if it closes over changing values you must declare them indeps(React Native previously refreshed the closure on every render).Known limitation: agent-scoped renderer resolution does not take effect on React Native.
CopilotChatConfigurationProvideris not in RN's provider tree, soagentIdalways resolves to the default. Renderers still resolve by name; two agents registering the same tool name resolve arbitrarily. Filed separately.A data point worth recording
Adding
useRenderToolCallto the measured headless entry moved the bundle 92.8 kB → 92.7 kB. Flat. The hook React Native spent months not using was already inside the chunk every RN app resolves whole — Metro doesn't tree-shake, so the fork never saved a byte. It cost them.Testing
@copilotkit/react-native: 253 passing / 22 files ·@copilotkit/react-core: 1480 passing / 123 files ·check-typesandbuildgreen for both.CopilotKitCoreReact— no mocking of the code under test.Follow-up
useRenderTool's JSDoc is split across two blocks, which orphans the primary description from IDE hover (the@param depswarning still surfaces). One-line fix, deliberately left out of the final fix wave.Related PRs and Issues
Co-Authored-Byon4104bd1./v2/headlessentry this PR consumes.Checklist
🤖 Generated with Claude Code