Skip to content

fix(react-core): support async header builders - #6291

Closed
rodboev wants to merge 8 commits into
CopilotKit:mainfrom
rodboev:feat/1937-async-headers
Closed

rodboev wants to merge 8 commits into
CopilotKit:mainfrom
rodboev:feat/1937-async-headers

Conversation

@rodboev

@rodboev rodboev commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Cache canonical normalized records for synchronous and equal async results, preserve stale-completion suppression, and warn once when a pending async source is replaced.
  • Keep provider descendants mounted with concrete headers and use one private barrier for initial pending, initial failure, recovery, and last-good refresh behavior.
  • Route /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.
  • Keep v1 and v2 on the same concrete record, scope the legacy error adapter to header-origin errors, and remove the production-path Authorization log.

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 runId behavior changes.

Related PRs and Issues

Closes #1937.

This extends the synchronous header behavior confirmed in #1937 (comment).

Test plan

  • Focused Vitest regressions: 37 tests across five resolver/provider, barrier, annotation, learning-container, and production-anchor files, plus two isolated v1 async-header tests.
  • React Core typecheck.
  • Scoped Oxfmt, scoped Oxlint with 0 errors, git diff --check, scope, and invariant-enumeration checks.
  • CI green (static / quality, test / unit on Node 20/22/24).

@BenTaylorDev BenTaylorDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  • reportError in use-resolved-headers.ts takes 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 to onError with context: { source: "headers", runtimeUrl } — so this is only about the console line losing the cause.
  • isHeaderRecord now rejects non-string values, so { "X-Count": 5 } becomes a hard error where it previously reached fetch and 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 the void | 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.

rodboev added a commit to rodboev/CopilotKit that referenced this pull request Aug 5, 2026
)

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.
@rodboev

rodboev commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

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 headers builder now documents that it must return a stable function reference (useCallback/useMemo), and the resolver enforces it: with a stable reference the evaluation cache hits on the identity check and the builder is not re-invoked, and it re-resolves only when you change the reference, which is the deliberate refresh path (e.g. an expiring token in the deps). An inline arrow that ignores the contract is surfaced with a once-per-instance dev warning (use-resolved-headers.ts), mirroring the useStableArrayProp enforcement already used in this file. I updated the headers prop docs in copilotkit-props.tsx accordingly.

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 .changeset/accept-async-header-builders.md; release is nx release-owned.

reportError

The console line now carries the error: console.error("[CopilotKit] Failed to resolve request headers", error), and the tests pin it.

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 void | Promise<void> union

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 waitForHeaders() isn't wrongly rejected on replay; that behavior has regression coverage after a few rounds of stabilizing it. The union return is the call-site contract: dispatch synchronously when already ready, await only when resolution is genuinely pending. Shrinking either without breaking those loses more than it gains.

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 BenTaylorDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-renders
token 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:

  1. 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.
  2. 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 useResolvedHeaders and useHeaderReadiness (plus HeaderRecord/HeaderSource/ResolvedHeaders) are exported from v2/headless.ts and v2/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.ts carries an import → import type reflow that isn't part of the fix.
  • Dead-code removal. I checked the headers memo you deleted from copilotkit.tsx — it is genuinely unreferenced on main, so removing it is safe. Just noting it's unrelated to async headers.
  • Conflicts with main. use-interrupt.tsx no longer merges cleanly: main threaded runId through the same three runAgent call sites you wrap with waitForHeaders. 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) and use-pin-to-send.test.tsx (1) fail identically on origin/main in the same environment (ResizeObserver mock). Not yours.
  • runtime-client-gql — 134 passed.
  • react-native — could not validate. 77 tests fail on origin/main in my setup across 6 files. The branch adds 2 failures, both in src/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.

@rodboev
rodboev force-pushed the feat/1937-async-headers branch from b0100d5 to 25c4b56 Compare August 12, 2026 16:43
@rodboev

rodboev commented Aug 12, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed follow-up. I rebuilt the branch from current main around the provider boundary and removed the readiness surface that was causing the repeated evaluations.

  • A stable async header source is evaluated once per function identity, with stale and unmounted completions ignored.
  • The initial web provider subtree waits for one settled concrete record; v1 and v2 reuse that record instead of invoking the builder independently.
  • Refreshes retain the last good record, sync recovery clears prior errors, and core's nullish header normalization remains intact.
  • Header-resolution failures use HEADER_RESOLUTION_FAILED and preserve the original error; unrelated core errors keep the existing console fallback.
  • React Native, runtime-client-gql, use-interrupt.tsx, public readiness exports, and unrelated cleanup remain out of scope.

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.

@NathanTarbert

Copy link
Copy Markdown
Contributor

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.

use-header-source.ts:171 returns evaluation.value, which normalizeHeaders() freshly allocates each render. The sameHeaders fast path at :92 updates evaluationRef.current but never feeds it back into the returned value, and that path covers the default EMPTY_HEADERS case — so every provider, async headers or not, now emits a new headers identity per render. That busts mergedHeaders and re-runs the commit effect at :774, including connect, on every render, where main runs it once. Reading const evaluation = evaluationRef.current!.value after the ref update should do it.

Second: CopilotKitProvider.tsx:997 returns null when headers is null, and an initial rejection sets exactly that with no retry. So a token endpoint that blips once unmounts the whole subtree permanently — and since the provider usually wraps the app, that's a blank screen. Rendering children with an empty or last-good record and gating only the request paths would keep the failure contained to requests.

Related: an unmemoized inline async () => … still re-invokes each render and generation.current += 1 drops the in-flight promise, so a re-render during the first resolution means it never settles — which combines with the above into "app never mounts." The dev warning from the earlier revision would be worth restoring.

One smaller thing worth splitting out: installing handleV2HeaderError as the v2 onError means every non-header error also gets console-logged, and those already reach v1's onError through the error bridge — so v1 consumers see doubled output. An early if (event.context?.source !== "headers") return; keeps it scoped.

Also: packages/react-core/src/v2/providers/__tests__/CopilotKitProvider.asyncHeaders.production.test.tsx has a leftover console.log printing the resolved Authorization value.

@rodboev
rodboev force-pushed the feat/1937-async-headers branch from 25c4b56 to 9a73b52 Compare August 14, 2026 19:05
@rodboev

rodboev commented Aug 14, 2026

Copy link
Copy Markdown
Contributor Author

Implemented the requested rework around the provider-owned resolver.

  1. The resolver reuses its normalized header object when synchronous values are unchanged, so unrelated renders don't repeat header setup work. A new async-builder identity remains the declarative refresh signal, while replacement during pending work produces one value-free development warning.
  2. Children stay mounted while headers are pending or an initial lookup has failed. A private request barrier holds outbound work, releases it after initial resolution, rejects it with HEADER_RESOLUTION_FAILED and the original cause after initial failure, supports recovery through a new source or setHeaders(), and keeps last-good headers during refresh failure.
  3. The same barrier covers /info, agent and suggestion operations, tasks, annotations, transcription, and direct MCP requests. Current merged headers and the runtime URL are read after readiness releases each request.
  4. The v1 error adapter handles header-origin errors once; non-header core errors keep their existing delivery path. The production-path test no longer logs the resolved Authorization value.

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, git diff --check, scope checks, and invariant enumeration passed. The monorepo suite remains CI-only.

@BenTaylorDev BenTaylorDev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:210 reloadSuggestions — the "loading" transition is no longer synchronous. 5 failures in use-suggestions.e2e.test.tsx (expected 'idle' to be 'loading'). Reverting only this override fixes all 5.
  • react-core.ts:223 runAgent — 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:47 asserts code: CopilotKitCoreErrorCode.HEADER_RESOLUTION_FAILED against 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't ready and replays it from syncDeferredRuntimeUrl. If headers fail and never recover, the deferred URL is never applied and core.runtimeUrl stays stale. Low impact in practice, since the barrier rejects those requests anyway — but the stale field is observable.
  • CopilotKitProvider.asyncHeaders.production.test.tsx doesn't set NODE_ENV=production; it's the same assertion as the first test in asyncHeaders.test.tsx.
  • Docs: the headers type change is documented in packages/react-core/skills/…/provider-setup.md but not in showcase/shell-docs, where snippets/shared/reference/copilotkit-component.mdx:59 still declares headers as Record<string, string>. That's where users will look.

Verification

  • react-core full suite on this head vs origin/main in the same environment; 8 failures present on this head and absent on main, 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/connect counts measured against this head with @testing-library/react; the churn table's main column is the same probe run on origin/main.

@BenTaylorDev

Copy link
Copy Markdown
Contributor

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 main too, with a sync builder: after a minute idle, the run got a 401. So #7510 resolves headers inside @copilotkit/core's request path. That covers React, <CopilotKit>, Vue and Angular together, and there's no readiness barrier left to trip over under StrictMode.

Several of the traps this PR hit (StrictMode remount, identity churn, sync timing of runAgent and reloadSuggestions) are now regression tests in #7510. The PR credits you. Thank you.

BenTaylorDev added a commit that referenced this pull request Oct 9, 2026
…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 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🚀 Feature Request: Async Headers

3 participants