Repository navigation
fix(react-core): expose lean hooks from /v2/headless to cut bundle bloat (#4893) - #5883
Conversation
📣 Social Copy GeneratorGenerate social media copies (Twitter/X, LinkedIn, Blog Post) for this PR using Claude.
|
Production Digest-Pinning AuditAll 41 services digest-pinned. Run 2026-07-08 14:27:20 PDT — 0 finding(s). |
@copilotkit/a2ui-renderer
@copilotkit/agentcore-runner
@copilotkit/angular
@copilotkit/channels
@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: +250 B (+0.02%) Total Size: 1.17 MB 📦 View Changed
ℹ️ View Unchanged
|
WalkthroughThis PR expands the public export surface of the react-core v2 headless module by adding Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
ESLint install failed: private package registry requires authentication. Disable ESLint in CodeRabbit settings or use public packages. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/react-core/src/v2/lib/shallow-stable-ref.ts`:
- Around line 21-23: `shallowEqual` in `shallow-stable-ref.ts` is missing a
key-existence check, so objects with different keys but `undefined` values can
compare equal. Update the comparison loop in `shallowEqual` to verify each key
from `keys1` exists on `obj2` using a `hasOwnProperty`-style check before
comparing values, matching React’s `shallowEqual` behavior and keeping the
existing `keys1`/`obj1`/`obj2` logic intact.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: d90212d8-7ae6-432d-a9a2-a60b282b4b47
📒 Files selected for processing (5)
packages/react-core/src/v2/__tests__/headless-exports.test.tspackages/react-core/src/v2/headless.tspackages/react-core/src/v2/lib/shallow-stable-ref.tspackages/react-core/src/v2/lib/slots.tsxpackages/react-core/src/v2/providers/CopilotChatConfigurationProvider.tsx
d6ec9b6 to
8932cb0
Compare
…oat (#4893) The main @copilotkit/react-core/v2 entry re-exports from one monolithic shared chunk, so importing any symbol links the built-in chat-message rendering stack (streamdown -> shiki, mermaid, cytoscape, katex) into the consumer's bundle — ~3MB gzip / ~15MB raw — with no way to tree-shake it. Custom-UI consumers who only use hooks pay the full cost (issue #4893). The separate /v2/headless build entry ships those hooks in their own small chunk without that stack, but it was missing two hooks a custom UI needs and leaked tailwind-merge. - headless: export useCopilotKit and useRenderToolCall (both DOM-free, pull no chat-UI rendering stack). useDefaultRenderTool / useRenderCustomMessages / useRenderActivityMessage stay in /v2 — web-only markup or a2ui-renderer. - headless: fix UseAgentUpdate (a runtime enum) being re-exported via `export type` — under isolatedModules that stripped its runtime binding, so useAgent's `updates` option was unusable from /v2/headless. - Stop headless pulling tailwind-merge: extract the tailwind-free ref helpers (shallowEqual / useShallowStableRef) into lib/shallow-stable-ref and point CopilotChatConfigurationProvider at them. - Add a vitest export-surface test asserting the documented hooks are runtime functions and UseAgentUpdate is a runtime value (the `export type` bug is invisible to tsc). react-core check-types, vitest (1427), and react-native check-types pass. Shipped dist/v2/headless.mjs imports only react, @ag-ui/client, @copilotkit/core, @copilotkit/shared, @copilotkit/react-core/v2/context, zod — no rendering stack. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
BenTaylorDev
left a comment
There was a problem hiding this comment.
Approving — verified end to end, not just read:
- Bundle claim confirmed live. Built the dist and measured
useAgentimported from each entry (react family external, minified+gzipped):/v2= 2.81 MB gzip (bundles streamdown/shiki/mermaid/cytoscape/katex) vs/v2/headless= 64 KB gzip with zero heavy-stack refs — a ~44× reduction, matching the report. - Runtime correctness. The new
headless-exports.test.tspasses 3/3, including the guard thatUseAgentUpdateresolves as a runtime enum — confirming theexport type→exportfix (the isolatedModules-stripping bug) actually works at runtime. - No leak, no regression. Traced every headless-reachable module (incl. the re-exported
CopilotChatConfigurationProvider) — none imports the render stack; the builtheadless.mjschunk contains none of it. MovingshallowEqual/useShallowStableRefinto the tailwind-free leaf module is backward-compatible via the re-export left inslots.tsx(existingCopilotChat+ tests still resolve). - CI green (bundle-size + copilotchat-import-size gates included); mergeable on current main.
Clean, surgical, well-documented, and it fixes a real runtime bug on top of the bundle win.
I bless the code with a glad heart.
…chat/attachment native deps (#6142) ## Problem `@copilotkit/react-native`'s entry (`packages/react-native/src/index.ts`) statically re-exports the prebuilt chat UI — `CopilotChat` / `CopilotModal` / `CopilotSidebar` / `CopilotPopup`, which import `@gorhom/bottom-sheet` — and `useAttachments`, which imports `expo-document-picker` + `expo-file-system`. Those are declared as **optional** peer deps, but a static re-export still forces Metro to resolve them at bundle time. So a **headless** consumer that mounts only `CopilotKitProvider` + `useAgent` + `useFrontendTool` (a fully custom UI, no prebuilt chat) is still forced to install all of those native deps, or Metro's release bundle fails: ``` Unable to resolve module expo-document-picker ``` Today the only workaround is stubbing the modules in `metro.config.js`. ## Fix Add a lean `@copilotkit/react-native/headless` subpath entry that re-exports **only** the provider (`CopilotKitProvider`), the platform-agnostic hooks (`useAgent`, `useFrontendTool`, `useCopilotKit`, `useHumanInTheLoop`, `useInterrupt`, `useThreads`, `useSuggestions`, `useRenderTool`, …), the render-tool registry, and the core/AG-UI types — and **none** of the chat components or `useAttachments`. Those native deps therefore never enter the bundle graph: ```tsx import { CopilotKitProvider, useAgent, useFrontendTool } from "@copilotkit/react-native/headless"; ``` This **retires the `metro.config.js` stub workaround** for headless consumers. ## How it mirrors the precedent (#5883) Directly mirrors `@copilotkit/react-core/v2/headless` (PR #5883, which cut multi-MB bundle bloat by exposing lean hooks from a dedicated entry — and which this RN provider already consumes): - **Standalone entry file** — `src/headless.ts` (the lean surface). - **tsdown** — added to the `entry` list (RN's tsdown auto-externalizes deps/peerDeps, so the native modules stay external and simply never get imported by this entry). - **`package.json`** — new `./headless` condition in `exports`, and `./dist/headless.*` added to `sideEffects` (the entry side-effect-imports the polyfills). - **Regression test** — a static import-graph test (`headless-entry-surface.test.ts`) that walks the transitive graph from `src/headless.ts` and fails if it ever reaches the chat/attachment modules or `@gorhom/bottom-sheet` / `expo-document-picker` / `expo-file-system`. This is the guarantee a normal typecheck can't catch, since those are optional peers. ## Backward compatibility Fully backward compatible. The default barrel (`@copilotkit/react-native`) now does `export * from "./headless"` and layers the chat UI + `useAttachments` on top, so every existing import from `@copilotkit/react-native` is unchanged. The polyfills still auto-install from both entries. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
…chat/attachment native deps The `@copilotkit/react-native` barrel statically re-exports the prebuilt chat UI (CopilotChat / CopilotModal / CopilotSidebar / CopilotPopup, which import `@gorhom/bottom-sheet`) and `useAttachments` (which imports `expo-document-picker` + `expo-file-system`). Those are optional peer deps, but a static re-export still forces Metro to resolve them at bundle time. A headless consumer that uses only `CopilotKitProvider` + `useAgent` + `useFrontendTool` (a fully custom UI) had to install every chat/attachment native dep or stub them in `metro.config.js`, or the release bundle fails with `Unable to resolve module expo-document-picker`. Add a lean `@copilotkit/react-native/headless` entry that re-exports only the provider, the platform-agnostic hooks, the render-tool registry, and the core/AG-UI types — none of the chat UI or `useAttachments` — so those native deps never enter the bundle graph and the metro-stub workaround is retired. Mirrors `@copilotkit/react-core/v2/headless` (CopilotKit#5883): a standalone entry file, wired into the tsdown entry list, the package.json `exports` map, and `sideEffects` (it side-effect-imports the polyfills). The default barrel now does `export * from "./headless"` and layers the chat UI on top, so it stays fully backward compatible. Adds a static import-graph regression test asserting the headless graph never reaches the chat/attachment modules or their native peer deps. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…'s shared registry (#6438) ## What does this PR do? `@copilotkit/react-native` maintained a **private tool-call render registry** (`hooks/RenderToolContext.tsx`) alongside the canonical one that `CopilotKitCoreReact` already 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: | Bug | Symptom | Cause | |---|---|---| | **Tool renders never streamed** | A component registered with `useRenderTool` / `useComponent` painted nothing until the tool call completed | `CopilotChat` used `JSON.parse` on the argument buffer. 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 `{}` | | **`useComponent` rendered nowhere** | Silently, with no error | It writes to core's registry; React Native's chat read React Native's private `Map` | | **Chat history degraded** | Navigating away from the registering screen turned earlier tool calls into a `Called: <name>` placeholder | The private `Map` deleted renderers on unmount; core deliberately keeps them | `@copilotkit/react-core` has used `partialJSONParse` on this path since v2 shipped. React Native diverged because `useRenderToolCall` was excluded from its re-exports on the stated grounds that it "depends on DOM elements via `DefaultToolCallRenderer`" — a claim that was never true of the hook itself. It was only ever reachable through the fat `/v2` entry, whose weight is the real hazard (#4893). #5883 moved it into `/v2/headless` on 2026-07-23; the exclusion comment was rewritten the next day without revisiting the reason. ### What changed - **One registry.** `useRenderTool` registers through `useFrontendTool` into `CopilotKitCoreReact.renderToolCalls`. `CopilotChat` and any custom surface consume react-core's `useRenderToolCall`. - **Types are derived, not declared.** `RenderToolProps` is now `React.ComponentProps<ReactToolCallRenderer<T>["render"]>`, so React Native cannot drift from `ReactToolCallRenderer` — the contract every registered renderer is actually invoked against. Change that contract and `check-types` names every React Native renderer the change breaks. React Native narrows only the *return* type to `ReactElement | null`, which `FlatList`'s `renderItem` genuinely 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 under `parameters` (not `args`) and declaring `status` as string literals rather than `ToolCallStatus` members. 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.tsx` deleted** (−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. - **Two structural CI guards for #4893**, in opposite directions: a test failing if any React Native source imports the fat `/v2` entry, and a script failing if react-core's `/v2/headless` or `/v2/context` chunks 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.md` freezes `limit` fields until OSS-122. - **`react-native` added to the bundle-size glob**, which it had never been in, plus a `size:headless` measurement. React Native also gains capabilities it lacked: render props inferred from your schema, `name`/`toolCallId` on render props, and `result` on completed calls. **Corrected during review — two capabilities this originally claimed are not delivered:** - **Wildcard (`"*"`) renderers do not work on React Native.** Because `useRenderTool` routes through `useFrontendTool` (which calls `addTool`), `name: "*"` registers a frontend tool literally named `*` — advertised to the model, and colliding with core's separate wildcard-executable-tool path. react-core's `useRenderTool` is renderer-only and special-cases the wildcard; React Native's is not. The guide now advises against it. - **`followUp` (and `available`) are not forwarded**, and the handler's `context` argument is dropped, so `stopAgent()`'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 `useRenderTool` in favour of re-exporting `useFrontendTool` (tool + renderer) and react-core's `useRenderTool` (renderer-only, wildcard-capable). That is an API change with its own migration note, so it is not in this PR. ###⚠️ Breaking (in a minor) `useRenderToolRegistry` and `RenderToolProvider` are **removed**. Both are documented on the docs site, so this is a real break — see the `BREAKING CHANGE:` footer on `db67ccf`, which is what the release notes derive from, plus the rewritten reference pages. ```diff - const registry = useRenderToolRegistry(); - const renderer = registry.get(toolCall.function.name); - return renderer ? renderer({ args, status }) : null; + const renderToolCall = useRenderToolCall(); + return renderToolCall({ toolCall }); ``` Also note two semantic changes: `args` is `Partial<T>` **only** while `status` is `"inProgress"`, and a render function is now captured at registration — if it closes over changing values you must declare them in `deps` (React Native previously refreshed the closure on every render). **Known limitation:** agent-scoped renderer resolution does not take effect on React Native. `CopilotChatConfigurationProvider` is not in RN's provider tree, so `agentId` always 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 `useRenderToolCall` to 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-types` and `build` green for both. - Each of the three bugs has a deterministic test driving a real `CopilotKitCoreReact` — no mocking of the code under test. - Both #4893 guards carry mutation evidence: introduce the regression, watch them fail, revert, watch them pass. ### Follow-up `useRenderTool`'s JSDoc is split across two blocks, which orphans the primary description from IDE hover (the `@param deps` warning still surfaces). One-line fix, deliberately left out of the final fix wave. ## Related PRs and Issues - **Supersedes #6346** (@davidmckayv) — its diagnoses were correct and its test assertions are ported here, re-driven through the real registry rather than a mocked local one. Credited via `Co-Authored-By` on `4104bd1`. - Addresses the React Native half of **#4893**. - Builds on **#5883**, which created the lean `/v2/headless` entry this PR consumes. ## Checklist - [x] I have read the Contribution Guide - [x] If the PR changes or adds functionality, I have updated the relevant documentation - [x] "Allow edits by maintainers" is checked 🤖 Generated with [Claude Code](https://claude.com/claude-code)
… below it (closes OSS-956) (#6725) ## What does this PR do? The React Native guide imports `CopilotKitProvider`, `useAgent` and `useCopilotKit` from `@copilotkit/react-native/headless` and names no version. That subpath first ships in **1.64.0** (#6142), so a project pinned to 1.63.x or earlier fails every one of those imports with: ``` Unable to resolve module @copilotkit/react-native/headless ``` On Metro that reads like a broken install rather than a version skew, and it sends the reader into the package-exports and polyfill debugging the same guide warns about a few sections later. The actual fix is one word in an import path. This states the boundary in the three places a reader meets the subpath. Prose only — no snippet in this page changed. ### The version boundary, verified against the registry Not inferred from a changelog — `npm view @copilotkit/react-native@<v> exports` on each: | version | `./headless` | | -- | -- | | 1.62.0, 1.62.2, 1.62.3 | absent | | 1.63.0, 1.63.1, 1.63.2 | absent | | **1.64.0** | **present** | | 1.64.1+, 1.65.0, 1.69.2 | present | `./components` and the polyfill subpaths exist across all of the above, so `/headless` is the only path in the guide that carries a version boundary. Introduced by 0a582df / #6142. ### What changed - **Intro line** — `/headless` is marked `1.64.0+` where the three import surfaces are first introduced. - **Install step** — a `type="warn"` callout, placed where the resolved version is actually decided. States the boundary, quotes the exact Metro error, gives `npm ls @copilotkit/react-native` to check what you resolved, and covers the fallback. - **Import surfaces table** — a new "Available since" column. - **Import surfaces prose** — records what `/headless` *is*, which the guide never said: a lean alternative entry added so custom-UI consumers skip the chat and attachment native deps — **not** a replacement for the root barrel, which remains the package's default full surface and re-exports everything in `/headless`. ### The fallback advice is deliberately not just "import from the root" On 1.62.2 and 1.63.2 the root barrel does export all three names (checked in the shipped tarballs, not assumed). But `package/dist/index.mjs` on those versions statically imports `expo-document-picker` and `expo-file-system`. A reader who switches to the root therefore inherits exactly the peer-dependency resolution failure that this guide's `/headless` choice exists to avoid: ``` Unable to resolve module expo-document-picker ``` So the callout says to prefer upgrading to 1.64.0+, and if you cannot (because you are matching a pinned `@copilotkit/runtime`), names the install-or-stub requirement that comes with the root import rather than presenting it as a free swap. ### Why not backport `./headless` to 1.62.x That was the alternative the issue floated, and it looks unnecessary. `/headless` was never intended as the canonical entry that supersedes the root — #6142's message, `src/index.ts` (`export * from "./headless"`, with a root quick-start that uses the root), and `src/headless.ts` ("existing imports from `@copilotkit/react-native` are unchanged") all agree it is a lean *alternative*. Adding an entry point in a patch of an older line would also change what "the pinned set" means for anyone matching client to runtime. ## Related PRs and Issues - Closes OSS-956 - #6142 — added the `/headless` subpath in 1.64.0 - #5883 — the `@copilotkit/react-core/v2/headless` entry that #6142 mirrors ## Verification - MDX compiles via `@mdx-js/mdx` + `remark-gfm`, edited and baseline both - 4-column Import surfaces table parses; 19/19 `<Callout>` tags balanced - `commitlint` exit 0 - `pnpm check:intelligence-env-names` passes - `.mdx` is not in lefthook's `lint-fix` glob, so oxfmt/oxlint never applied to this file - This page carries no `doctest=` fences, and no fence in it changed, so the guide's snippets stay runnable as they were ## Checklist - [x] I have read the [Contribution Guide](https://github.com/copilotkit/copilotkit/blob/master/CONTRIBUTING.md) - [x] If the PR changes or adds functionality, I have updated the relevant documentation - [x] "Allow edits by maintainers" is checked 🤖 Generated with [Claude Code](https://claude.com/claude-code)
What & why
@copilotkit/react-core's/v2entry (and the root entry) re-exports from asingle monolithic shared chunk, so importing any symbol — even one hook —
pulls the built-in chat-message rendering stack (
streamdown→ shiki,mermaid,cytoscape,katex) into the consumer's bundle: ~3 MB gzip / ~15 MB raw,with no way to tree-shake it. Consumers who build a fully custom chat UI and only
use hooks pay the full cost. (Issue #4893.)
A separate lean build entry —
@copilotkit/react-core/v2/headless— alreadyships those hooks in their own small chunk without that stack (it's how
@copilotkit/react-nativemounts CopilotKit). This PR makes it usable for acustom web UI.
Measured with esbuild (react/react-dom external):
@copilotkit/react-core/v2CopilotChat)@copilotkit/react-core/v2/headlessChanges
headless.ts— exportuseCopilotKit+useRenderToolCall(both DOM-freeand rendering-stack-free); fix
UseAgentUpdate(a runtimeenum) beingre-exported via
export type, which stripped its runtime value underisolatedModules(souseAgent'supdatesoption was unusable from headless— a bug
tsccan't catch).useDefaultRenderTool/useRenderCustomMessages/
useRenderActivityMessagestay in/v2(web-only markup ora2ui-renderer).tailwind-mergeleak — extract the tailwind-free ref helpers(
shallowEqual/useShallowStableRef) intolib/shallow-stable-ref.tsso theheadless graph no longer pulls
tailwind-mergeviaCopilotChatConfigurationProvider.UseAgentUpdateruntime value.Verification
react-coretypecheck + vitest (1427) andreact-nativetypecheck pass. Shippeddist/v2/headless.mjsimports onlyreact,@ag-ui/client,@copilotkit/core,@copilotkit/shared,@copilotkit/react-core/v2/context,zod— no renderingstack.
Notes / follow-ups
/v2<CopilotKitProvider>, so the two can't be mixed — mount a lean provider over/v2/context(as@copilotkit/react-nativedoes). Making the/v2providerreuse the standalone
/v2/contextsingleton would remove that sharp edge andis the natural follow-up.
compressed-size-action) already tracksheadless.mjs,so no new size tooling is added here.
Addresses #4893.
🤖 Generated with Claude Code