Repository navigation
Conversation
BenTaylorDev
left a comment
There was a problem hiding this comment.
Async header builders are a capability we want — refreshing an auth token before a request is a real need and the readiness gating is the right shape. One design question needs resolving before this lands, plus a couple of smaller items.
Header builders are invoked during render, once per render
useResolvedHeaders(headersProp) receives the prop unmemoized, and the cache invalidates on cachedEvaluation.source !== source. The documented usage is an inline arrow:
headers={async () => ({ Authorization: `Bearer ${await getToken()}` })}That's a new function identity on every render, so evaluate(source) calls it on every render, each call creating a new promise and a new evaluation, which refires useEffect([evaluation]). attemptRef correctly prevents a state loop, so there's no infinite render — but nothing bounds the number of invocations of the caller's function. During a streaming response, that's a token request per render.
To be clear about the baseline: current main already evaluates during render on every render (CopilotKitProvider.tsx:460), so this pattern is inherited rather than introduced. For a synchronous builder it's cheap and harmless. Extending it to async is what makes the cost real, which is why I think it needs an answer here rather than later — resolving in an effect keyed on something stable, or documenting that the builder must be memoized (and enforcing it), would both work.
Please drop the changeset
.changeset/accept-async-header-builders.md — releases go through nx release, and there are no files under .changeset/ on main. Worth noting your own #6294 gets this right and says so explicitly in its description.
Smaller
reportErrorinuse-resolved-headers.tstakes the error and logs a bare string without it:console.error("[CopilotKit] Failed to resolve request headers"). The structured path is fine — the provider forwards the real error toonErrorwithcontext: { source: "headers", runtimeUrl }— so this is only about the console line losing the cause.isHeaderRecordnow rejects non-string values, so{ "X-Count": 5 }becomes a hard error where it previously reachedfetchand got coerced. Probably the behavior you want, but it's a breaking change for existing callers and worth a line in the description.- The StrictMode deferred-cancellation block in
useHeaderReadiness, plus thevoid | Promise<void>union return, are the parts I'd most like to see shrink — they're load-bearing and hard to reason about.
Process notes
At 41 files this is difficult to review as a single unit. If the react-native and runtime-client-gql propagation could be split from the core hook + provider change, the interesting part would get much better scrutiny.
I have not run this PR's test suites — fork PRs don't get automatic CI here, so nothing has exercised them yet. Also flagging that this shares CopilotChat.tsx with #6295.
) Address review on CopilotKit#6291: document and enforce that async specify headers builders return a stable reference so they are not re-invoked per render, and drop the changeset now that releases run through nx release. Include the cause in the resolution error log and call out the header-record validation as a breaking change.
|
Thanks for the detailed review. I've addressed the blocking items and the smaller ones; a couple of notes on the softer asks below. Design question: async builders invoked per render I've gone with the memoization option you offered. The async I considered the first option (resolving in an effect keyed on something stable), but for an unmemoized inline arrow the effect key is still the unstable identity, so it would re-fire per render exactly like the render path does, without actually bounding invocation, and it carries a lot more risk to the readiness/StrictMode handling. Changeset Dropped reportError The console line now carries the error: isHeaderRecord Non-string values are now rejected where they previously got coerced at the fetch boundary. I've called the breaking change out in the PR description so existing callers see it. StrictMode block and the I kept both rather than shrinking them. The deferred-cancellation block is what distinguishes React StrictMode effect replay from a real unmount, so a pending Process notes I've left the react-native and runtime-client-gql propagation in this PR. Splitting a 41-file live PR here would strand the shared readiness hook the split surfaces depend on, and I'd rather not destabilize it at this point, but happy to revisit if you want it split before merge. On CI: fork PRs don't get automatic runs here, so nothing has exercised the suites on this branch yet; I've run the affected suites locally (react-core 1507, react-native 256). |
BenTaylorDev
left a comment
There was a problem hiding this comment.
Thanks for the turnaround. Three of the five items are closed on my side: the changeset is gone, reportError carries the error and the tests pin it, and the isHeaderRecord breaking change is called out in the description. The useStableArrayProp precedent for an ungated console.error holds, so I'm dropping that as a concern.
The design question is the one I don't think is resolved yet.
Memoizing the builder doesn't bound how often it's invoked
I ran this against the branch — the builder is memoized exactly as the new docs prescribe:
function App() {
const [n, setN] = useState(0);
const headers = useCallback(async () => {
const token = await getToken(); // vi.fn()
return { Authorization: `Bearer ${token}` };
}, []);
return (
<CopilotKitProvider runtimeUrl="https://runtime.example/rest" headers={headers}>
<span>{n}</span>
</CopilotKitProvider>
);
}
// mount, then 20 setN re-renderstoken fetches after mount = 1; after 20 re-renders = 12
At the hook level it's the same shape: 6 invocations across 10 rerender()s.
The mechanism is in use-resolved-headers.ts:83-114. Once an async evaluation settles, skipSettledRefresh suppresses re-evaluation for exactly one render; the render after that re-enters evaluate(source) and calls the builder again. Your own test pins this — use-resolved-headers.test.tsx:67, "refreshes a stable async builder after its first result settles".
To be fair to what this is and isn't: it does not spin on its own. An idle provider with a builder returning a fresh token each call settles at one invocation — there's no feedback loop. The cost only appears when something re-renders the provider, and then it's roughly one builder call per two renders.
So the round-1 problem is halved rather than closed, and two artifacts now describe behavior the code doesn't have:
copilotkit-props.tsx: "memoize the builder so it is not re-invoked with a fresh promise on every render"- the PR description: "A stable reference resolves once and is re-invoked only when the reference changes"
The dev warning has the same gap — it points users at memoization as the fix, and once they apply it the warning stops firing while the re-invocation continues.
Either direction closes this, and I don't have a strong preference:
- Make a settled async evaluation sticky until the source reference actually changes. That's what the docs already promise, and it makes the reference-change refresh path the only refresh path.
- Keep the auto-refresh deliberately, but drive it from something explicit — a TTL, or an invalidate handle returned to the caller — and document that as the contract instead.
Smaller
- Scope vs. description. "New public readiness semantics ... remain outside this target," but
useResolvedHeadersanduseHeaderReadiness(plusHeaderRecord/HeaderSource/ResolvedHeaders) are exported fromv2/headless.tsandv2/hooks/index.ts. That's new public API we'd be committing to. If they're meant to be internal, drop the exports. - Error code. Header resolution failures are reported as
CopilotKitCoreErrorCode.RUNTIME_INFO_FETCH_FAILED(CopilotKitProvider.tsx:485), which isn't what happened. - Unrelated churn.
copilot-task.tscarries animport→import typereflow that isn't part of the fix. - Dead-code removal. I checked the
headersmemo you deleted fromcopilotkit.tsx— it is genuinely unreferenced onmain, so removing it is safe. Just noting it's unrelated to async headers. - Conflicts with
main.use-interrupt.tsxno longer merges cleanly:mainthreadedrunIdthrough the same threerunAgentcall sites you wrap withwaitForHeaders. Mechanical to resolve, but it needs doing.
Test run
Since fork PRs don't get automatic CI here, I ran the suites locally against the branch:
- react-core — 1500 passed, 7 failed. All 7 are pre-existing:
CopilotChatView.pinToSend.test.tsx(6) anduse-pin-to-send.test.tsx(1) fail identically onorigin/mainin the same environment (ResizeObserver mock). Not yours. - runtime-client-gql — 134 passed.
- react-native — could not validate. 77 tests fail on
origin/mainin my setup across 6 files. The branch adds 2 failures, both insrc/components/__tests__/CopilotChat.test.tsx, which fails wholesale in both runs. No branch-specific regression shown, but no confirmation either — I'd want CI on this one rather than my local numbers.
b0100d5 to
25c4b56
Compare
|
Thanks for the detailed follow-up. I rebuilt the branch from current
The focused provider and resolver regressions pass, along with React Core and Core type checks, formatting, lint, and scope checks. The updated branch is ready for CI and maintainer re-review. |
|
Hey @rodboev, The rewrite addressed Ben's round-2 point cleanly — I confirmed the stable-reference cache holds across 20 rerenders with a single invocation, and hoisting resolution up to the provider is the right call: no per-request await, no herd on the token endpoint. Rejection handling is loud and header values stay out of errors and logs. Two things to fix before this can land, and the first one is bigger than async headers.
Second: Related: an unmemoized inline One smaller thing worth splitting out: installing Also: |
25c4b56 to
9a73b52
Compare
|
Implemented the requested rework around the provider-owned resolver.
Focused proof passed: 37 tests across the resolver/provider, barrier, annotation, learning-container, and production-anchor files, plus the two v1 async-header regressions in isolated runs. React Core typecheck, scoped formatting, scoped oxlint with 0 errors, |
BenTaylorDev
left a comment
There was a problem hiding this comment.
Round-2's design question is genuinely closed, and I can measure it now. On the same harness that produced 12 invocations last time:
| invocations across 20 rerenders | |
|---|---|
| memoized async builder | 1 |
unmemoized inline async () => … |
2 |
And Nathan's identity-churn point, measured as setHeaders / connect calls rather than fetches:
headers prop |
this branch | origin/main |
|---|---|---|
| stable object | 0 / 0 | 0 / 0 |
| default (omitted) | 0 / 0 | 0 / 0 |
| inline object literal | 20 / 20 | 20 / 20 |
The default/EMPTY_HEADERS path he flagged is fixed. The inline-literal case still churns, but identically on main, so that one isn't yours.
Children stay mounted through pending and failed resolution, the Authorization console.log is gone, scope is down from 41 files to 21, and the branch is rebuilt on recent main with no changeset or retired-path debris. That's the right shape.
The problem is the new request-path plumbing. I ran the full react-core suite on this head and on origin/main in the same environment: this branch has 8 failures that origin/main does not. Two full runs produced identical failure lists, and all 8 also fail when their files are run in isolation, so none of this is ordering flake. I attributed each one by reverting a single override at a time.
1. Blocker — under StrictMode an async builder never resolves
/info fetches |
connectAgent |
|
|---|---|---|
| StrictMode × async headers | 0 | rejected: Header resolution ended before completion |
| StrictMode × sync headers | 1 | released |
| no StrictMode × async headers | 1 | released |
Both axes are required, which pins it to the disposal latch rather than to async resolution or StrictMode alone.
The mechanism is CopilotKitProvider.tsx:994-998. StrictMode's mount → cleanup → mount runs the cleanup, which calls barrier.dispose(...). dispose() sets disposed = true (header-readiness.ts:110), and ready(), pending() and failed() all early-return on disposed (:73, :63, :96), so the second mount's barrier.ready(headers) is a no-op. The barrier stays rejected for the life of the page, and every path routed through wait() — /info, connect, runAgent, annotations, transcription, MCP — rejects with it. I confirmed the attribution by making dispose() a no-op: the broken cell becomes 1 fetch and connectAgent gets through.
This is the default App Router dev configuration, not an edge case. From the Next.js copy vendored in this repo (next/dist/esm/build/define-env.js:110):
'process.env.__NEXT_STRICT_MODE_APP':
// When next.config.js does not have reactStrictMode it's enabled by default.
config.reactStrictMode === null ? true : config.reactStrictMode,(Pages Router defaults it off, so a Pages-Router app wouldn't hit this.)
The barrier needs to survive a cleanup-then-remount of the same fiber — either drop the dispose-on-unmount entirely (the WeakMap keying already lets it be collected, and a genuine unmount discards barrierRef and builds a fresh barrier on remount anyway), or make dispose() reversible so a later ready() reopens it.
2. The core overrides defer synchronous APIs unconditionally
reloadSuggestions, runAgent, connectAgent and connect all await the barrier before calling super, even when it is already ready. wait() returns Promise.resolve() in that case, but a resolved promise still costs a microtask — and these APIs' synchronous side effects are load-bearing.
react-core.ts:210reloadSuggestions— the "loading" transition is no longer synchronous. 5 failures inuse-suggestions.e2e.test.tsx(expected 'idle' to be 'loading'). Reverting only this override fixes all 5.react-core.ts:223runAgent— the run isn't marked in-progress synchronously. 1 failure:use-configure-suggestions.e2e.test.tsx > defers reloads while a run is in progress and applies them afterward. Reverting only this override fixes it.
Gating on readiness.state === "ready" and calling super synchronously in that case should close both. That's also the common case for everyone not using async headers, so it keeps the cost of this feature at zero for them.
3. applyDeferredHeaderRuntimeUrl calls an unguarded method
header-readiness.ts:190 does barrierCores.get(barrier)?.syncDeferredRuntimeUrl() — optional-chained on the lookup but not on the method. Any bound core that isn't a CopilotKitCoreReact throws inside the mount effect at CopilotKitProvider.tsx:989:
TypeError: barrierCores.get(...)?.syncDeferredRuntimeUrl is not a function
2 failures: CopilotKitProvider.deferWiring.test.tsx (the #5801 regression guard) and CopilotKitProvider.licenseRace.test.tsx. I checked both — each installs a FakeCore via vi.mock("../../lib/react-core"), so production isn't affected. But they're existing guards and they'd be red in CI.
Design — the module-level registry
header-readiness.ts keeps four module-scoped WeakMap/WeakSet registries, and bindHeaderReadiness(copilotkit, headerReadiness) runs during render (CopilotKitProvider.tsx:656). It works, but it makes the barrier an invisible global dependency of CopilotKitCoreReact, recordAnnotation, CopilotTask and the MCP renderer — none of which declare it. recordAnnotation already takes an explicit readiness argument; if the others took it the same way (or read it from context), the coupling would be visible at each call site instead of implied.
use-header-source.ts is the other piece I'd like to see shrink — 242 lines with render-phase ref mutation and a four-deep nested ternary computing each of headers, error and status (:212-241). I couldn't convince myself I'd traced every path, which is why I leaned on measurement above rather than on reading it.
Smaller
CopilotKitProvider.asyncHeaders.test.tsx:47assertscode: CopilotKitCoreErrorCode.HEADER_RESOLUTION_FAILEDagainst a value produced from that same enum member, so it passes for any value the member happens to have — including none. Asserting the literal"header_resolution_failed", the way your v1 test does, makes it load-bearing.setRuntimeUrl(react-core.ts:179) swallows the URL while the barrier isn'treadyand replays it fromsyncDeferredRuntimeUrl. If headers fail and never recover, the deferred URL is never applied andcore.runtimeUrlstays stale. Low impact in practice, since the barrier rejects those requests anyway — but the stale field is observable.CopilotKitProvider.asyncHeaders.production.test.tsxdoesn't setNODE_ENV=production; it's the same assertion as the first test inasyncHeaders.test.tsx.- Docs: the
headerstype change is documented inpackages/react-core/skills/…/provider-setup.mdbut not inshowcase/shell-docs, wheresnippets/shared/reference/copilotkit-component.mdx:59still declaresheadersasRecord<string, string>. That's where users will look.
Verification
react-corefull suite on this head vsorigin/mainin the same environment; 8 failures present on this head and absent onmain, reproduced across two full runs with identical failure lists and again per-file in isolation.- Per-item attribution by reverting one override at a time.
- StrictMode matrix, invocation counts and
setHeaders/connectcounts measured against this head with@testing-library/react; the churn table'smaincolumn is the same probe run onorigin/main.
|
Thanks @rodboev for this, and for sticking with three review rounds. I'm closing this in favor of #7510, which takes a different approach. That approach came out of what this PR's review turned up. The review showed the async-headers ask needs one more thing: headers must be evaluated when each request is sent, not once per builder identity. Otherwise a short-lived token (Clerk: 60 s) still goes stale. We measured that on Several of the traps this PR hit (StrictMode remount, identity churn, sync timing of |
…ync builders) (#7510) ## What does this PR do? The `headers` option now accepts a record, a sync builder, or an async builder. A builder runs **when each request is sent**, not when the provider renders. **The bug on `main`:** a sync builder ran during the provider's render. So if a token rotated without a provider re-render, CopilotKit kept sending the old token. For example, Clerk tokens live for 60 seconds, and typing in the chat input doesn't re-render the provider. After about a minute idle, the next run got a 401. Intelligence makes this worse, because thread refetches and realtime reconnects run without any user action, including in background tabs. There was also no way to pass an async `getToken()` at all (#1937, #2159). Measured with the real `@copilotkit/react-core` v2 build in jsdom, sending real HTTP requests to a local runtime that rejects tokens older than 60 s, after a real 65 s idle with no provider re-render: | Request after 65 s idle | `main` | this branch | |---|---|---| | Send a message (run) | **401**, token 65,053 ms old | 200, token 3–4 ms old | | `useThreads().renameThread()` (via `ɵruntimeFetch`) | **401**, token 65,051 ms old | 200, token 4–6 ms old | ### How it works - **Core** (`@copilotkit/core`): a `HeaderSourceResolver` owns the headers source. - It resolves synchronously for a record or a sync builder, so static and sync users gain no extra `await`. - For an async builder, concurrent requests share one in-flight call. A generation counter makes sure a call started before `setHeaders()` is never reused after it. - New public API: `resolveHeaders()`, `CopilotKitHeadersSource`, `CopilotKitHeaderResolutionError`, and the error code `HEADER_RESOLUTION_FAILED`. - `ɵruntimeFetch` adds the current headers when each request is sent, before the runtime watchdog is armed and before the single-route rewrite. The request's own `Content-Type`/`Accept` still win, and core headers still beat an agent's own headers (#5635 precedence). - `/info`, inspector metadata, runs, connects, stop requests and `/suggest` all resolve current headers. - **React v2** `CopilotKitProvider` and **`<CopilotKit>`** (also the main v2 export): the provider hands core one stable builder and never calls it during render. `<CopilotKit>` accepts async builders too. The one exception is the legacy v1 GraphQL `CopilotTask` path: it doesn't await an async builder, and it logs a one-time dev warning. - **Vue** and **Angular** (Angular accepts a builder for the first time), **web-inspector**, **react-textarea** (a dead render-time headers read was removed), and the **docs**. - **Out of scope:** React Native is unchanged (sync builder, evaluated at render); a follow-up issue will cover it. Cross-origin agent headers (#5635) are unchanged, and the docs now warn about them. ### Behavior changes 1. **A sync builder now runs once per request**, not once per provider render. 2. **A new token from a builder doesn't fire `onHeadersChanged`** and doesn't refetch threads or inspector metadata. Only `setHeaders()` or a new source does. 3. **`setHeaders()` with an equal record is a no-op**, and so is passing the same builder function again. 4. **User switch with a builder:** re-rendering the provider no longer reloads the thread list or re-subscribes realtime, because the builder's identity is stable. On a user switch, remount the provider (for example `key={userId}`), or call `setHeaders` with a new function or a record. The docs say this. Commit 9a69623 carries a `BREAKING CHANGE:` footer, so this lands under Breaking Changes in the release notes. 5. **Fail closed:** if a builder throws or rejects, or returns something that isn't an object (for example `() => token && {...}` before sign-in), the request is not sent. `onError` receives `header_resolution_failed` once per failed call. A header failure replaces the `AGENT_RUN_FAILED`/`AGENT_CONNECT_FAILED` that used to follow. A sync builder that threw used to crash render; now it fails closed. A header failure on `/info` sets the runtime status to Error and logs a warning that names headers. 6. **`copilotkit.headers`** is the last resolved value. With a builder it is `{}` until the first request. Angular's `headers()` signal follows source changes only (`{}` for a builder); use `core.resolveHeaders()` instead. 7. **A proxied runtime agent's `agent.headers` no longer contains core headers.** They are added at send time. Three existing tests (two #5635 remote-agent tests and one registered-proxy test) now assert on the request instead of on the field. 8. **Stop requests** and provisional proxies (React, Vue, Angular) now go through `ɵruntimeFetch` (stop requests are marked non-critical). 9. **v1 `copilotApiConfig.headers`** is a lazy getter, so a sync builder runs when `CopilotTask.run` reads it. 10. **`CpkThreadInspector.headers`** is deprecated in favor of `resolveHeaders`, and still works as a fallback. 11. **Angular `updateRuntime({ headers })`** now applies the license-key default to the new headers, as construction always did. Passing the same builder again is a no-op. 12. **Type widenings:** `CopilotKitCoreConfig.headers`, Angular `CopilotKitConfig.headers`, and the `headers` prop on `CopilotKitProvider`, Vue and `<CopilotKit>`. `resolveHeaders()` returns a read-only record. ### Follow-ups - #7511: `HEADER_RESOLUTION_FAILED` has no agent or thread context. - #7512: React `use-agent` re-applies headers on value changes instead of the generation. - #7513: React Native parity. - #7514: core headers reach user-supplied agents on other origins (#5635 behavior, documented here). - #7515 (stacked on this PR): moves the hand-written v1 `CopilotKit` docs notes into the JSDoc they're generated from, and deletes an orphaned auto-generated snippet. ## Related PRs and Issues - Closes #1937 - Supersedes #6291. Thanks to @rodboev: that PR's review is where the StrictMode, identity-churn and sync-timing traps in this design were found. - Related: #2159 (closed as a duplicate of #1937), #3401 / OSS-551 ## Testing Everything below ran on this branch, rebased onto `origin/main` at `b3d1aad2e3`. Each suite also ran on a clean `origin/main` worktree in the same environment. **Unit and integration suites (branch):** | Package | Result | |---|---| | `@copilotkit/core` | 1007 / 1007 pass; `check-types` clean | | `@copilotkit/react-core` | 1771 vitest + 54 node:test pass; `check-types` clean | | `@copilotkit/vue` | 1160 / 1160 pass; `vue-tsc` clean | | `@copilotkit/angular` | 452 pass, 1 skipped (already skipped on main); `check-types` clean | | `@copilotkit/web-inspector` | 794 / 794 pass; `check-types` clean | | `@copilotkit/react-textarea` | 3 / 3 pass; `check-types` clean | - **Compared with `origin/main`:** no failures appear on the branch only. `use-agent-context-timing.e2e` failed once, during a run that overlapped a parallel `pnpm install`. It didn't recur in 2 full runs, 3 isolated runs or 10 runs under load. Its agent isn't an `HttpAgent`, so this change adds no await on its path. - **Mutation checks:** every new test was checked by breaking the mechanism it guards, confirming the test fails, and restoring. Examples: - render-time builder evaluation → the stale-token tests fail; - dropping the generation guard → the in-flight reuse tests fail; - keying on header values → the no-reload tests fail; - a snapshot spread on a `ɵruntimeFetch` site → the removed-key tests fail; - awaiting unconditionally → the sync-timing tests fail. - **Other gates:** - oxlint: 0 errors. On the 49 modified files, warnings go from 58 on `main` to 49. The 12 new files add 4, for 53 in total. - Public API manifest: unchanged. - Release, config-allowlist and static-quality script tests: pass. - shell-docs search index and typecheck: pass. Its suite passes except 3 PNG checks, which fail only because the worktree has LFS pointer files instead of images. - Size: core is 1.19 kB larger minified. The size job is informational. - Angular showcase initial-bundle budget: 1,479,169 raw bytes on the branch vs 1,479,152 on `main` (cap 1,551,287). An earlier push failed this check because `config.ts` imported a value from `@copilotkit/core`, which pulled all of core into the initial bundle. `config.ts` now imports types only, and a test guards it. - **Not run locally:** `check:packages`, `verify:angular-package`, `verify:runtime-package`, `verify:channels-umbrella`, and the web-inspector browser tests. CI covers them. - **Docs:** every edited `.mdx` parses with the repo's `@mdx-js/mdx`. - **Live check:** the table at the top. I re-ran both scenarios on the final head (`71368fea1e`) with the same results: after a 65 s idle with 0 provider re-renders, the run sent a 2 ms-old token (200) and the rename a 5 ms-old token (200). **Review round (9a69623), after merging `origin/main` at `07d4830ade`:** - Trajectory connect and suggestions from a cloned `HttpAgent` now resolve headers at send time. There are two new rows in `core-headers-request-table.test.ts`. - Mutation check: with both source fixes reverted, the two new rows fail (`Expected: "fresh"`, `Received: "stale"`). With the fixes, the table and trajectory files pass: ``` Test Files 3 passed (3) Tests 85 passed (85) ``` - The React thread-context test now sends a request and re-renders after the token change. Mutation check: with `use-threads.tsx` keyed on `JSON.stringify(copilotkit.headers)`, the test fails (`1 failed`). On the PR code, the file passes (`13 passed`). - `nx run-many -t test check-types lint` for core, react-core, react-textarea, vue, angular and web-inspector: `check-types` passes for all six. Two tests timed out under the parallel load (`CopilotThreadsDrawer.ssr`, `MCPAppsUiMessage.e2e`). Both pass when run alone. `vue:lint` reports 166 errors, which also exist on `main`. None of them is on a line this PR adds. ## 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 - [ ] "Allow edits by maintainers" is checked (not applicable: this branch is in this repo) 🤖 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** * Web providers now accept synchronous and asynchronous header builders, resolving the current headers when requests are sent across runtime requests, agents, threads, transcription, and the Inspector. * Valid public API keys are included by default in request headers. * Changing the header source refreshes relevant thread and Inspector data; token updates from a builder alone do not trigger those refreshes. * Header resolution failures prevent the affected request and report `header_resolution_failed`. * **Documentation** * Updated guidance on header builders and request timing, including React Native’s synchronous-only behavior and the legacy v1 async-builder limitation. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Summary
Web CopilotKit providers accept Promise-returning header builders while keeping descendants mounted and containing outbound requests until initial headers are ready.
Root cause
Header resolution was treated as a render-time value. That allowed unstable identity and stale async completions, withheld the provider subtree after an initial failure, and left direct request paths outside one readiness boundary.
Changes
/info, agent and suggestion operations, tasks, annotations, transcription, and direct MCP requests through that barrier, reading the current merged headers and runtime URL after readiness.Authorizationlog.Backward compatibility
Static records and synchronous builders keep their existing values and timing. Async function identity remains the declarative refresh signal; callers can refresh credentials through
copilotkit.setHeaders().Scope
Web React/Core only. No public readiness API, React Native changes, runtime-client-gql changes, package metadata changes, or
runIdbehavior changes.Related PRs and Issues
Closes #1937.
This extends the synchronous header behavior confirmed in #1937 (comment).
Test plan
git diff --check, scope, and invariant-enumeration checks.static / quality,test / uniton Node 20/22/24).