Commit Graph

341 Commits

Author SHA1 Message Date
tylerslaton 9629e930d1 chore: release monorepo v1.69.2 2026-08-26 00:18:42 +00:00
Tyler Slaton b3b339f544 Revert "feat(web-inspector): add Event Snippets and save-as-snippet (#6649)"
This reverts commit ba4260ad66, reversing
changes made to 47c5510b49.
2026-08-26 02:11:19 +02:00
MikeRyanDev 6053e4e262 chore: release monorepo v1.69.1 2026-08-25 18:50:37 +00:00
Alem Tuzlak 5391c4886b feat(web-inspector): add view thread in your app (#6562)
## What does this PR do?

Lets a developer open a saved Inspector thread in the live official
chat.

- New header action: **View in your app**
- Official React and Vue chat switch to that thread
- A pinned `threadId` does not block the switch
- **Stop viewing** or an app thread change restores the previous thread
- Example threads have no action
- Production builds hide the action
- Same agent only. No matching official chat shows an error in the
Inspector

Core owns a two-way EventClient bridge
(`@tanstack/devtools-event-client`). The root import is a no-op in
production.

Docs: Inspector guide, section **View a thread in your app**.

## Related PRs and Issues

-
https://linear.app/copilotkit/issue/OSS-871/new-features-add-a-new-view-thread-in-your-app-feature

## 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
2026-08-25 13:52:52 +02:00
Alem Tuzlak ba4260ad66 feat(web-inspector): add Event Snippets and save-as-snippet (#6649)
Open Inspector Event Snippets on localhost. You can compile, save, and
replay AG-UI events in chat. Chat shows a bookmark icon next to a tool
call, an A2UI block, or generative UI. Click the icon to save that turn
as a snippet.

## What does this PR do?

This PR adds the Inspector Event Snippets pane.

You can:

- Compile a snippet from a recipe (tool-call, reasoning, text, activity,
raw)
- Save snippets in origin-scoped localStorage
(`cpk:inspector:event-snippets`)
- Import and export snippets from the pane header
- Replay a snippet into live chat through Inspector-only Core inject

Each Run remints `messageId`, `parentMessageId`, `toolCallId`, and
`runId`. The second Run of the same snippet is a new turn.

On localhost, chat shows a bookmark icon beside a tool call, A2UI block,
or generative UI. The icon is absolutely positioned. It hangs to the
right when there is room. Otherwise it hangs to the left. The card stays
full chat width.

The React demo adds `sayHello`, `getTime`, `addNumbers`, and a **Call 3
tools** suggestion.

## Related PRs and Issues

- Linear
[OSS-874](https://linear.app/copilotkit/issue/OSS-874/new-features-also-allow-users-to-emit-specific-events-from-the)

## 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 (lets us help iterate on
your PR directly — faster turnaround for everyone)

## Testing

### Commands run

1. Lefthook pre-commit ran `nx` targets `test`, `publint`, and `attw`
for 27 affected projects. All passed.
2. I did not run `pnpm test:pr` (full repo). Lefthook ran the affected
package matrix only.

### Manual test

1. Run `pnpm demo:react` from the repo root.
2. Open http://localhost:3000
3. Open Inspector and select Event Snippets.
4. In chat, click **Call 3 tools**. Confirm three tool cards at full
chat width, with the bookmark hanging outside the card.
5. Click a bookmark, then click Run twice. Chat shows a second turn with
new IDs.

### How this PR makes testing easy

- `packages/web-inspector/src/lib/__tests__/event-snippets.test.ts`
- `packages/core/src/__tests__/inspect-inject.test.ts` (covers two
injects)
- React demo: `examples/v2/react/demo/src/app/page.tsx`

## Linked issues

Linear
[OSS-874](https://linear.app/copilotkit/issue/OSS-874/new-features-also-allow-users-to-emit-specific-events-from-the)

## Risk / rollback

- If ID remint is wrong, a second Run can no-op or duplicate a turn.
- The save icon shows on localhost Inspector (or when `showDevConsole`
is `true`).
- Rollback: revert this PR.

## Public API change

**Before**

Angular has no Inspector service.

```ts
// no CopilotInspector export from @copilotkit/angular
```

**After**

```ts
import { CopilotInspector } from "@copilotkit/angular";

const inspector = inject(CopilotInspector);
inspector.openInspector({
  messageId: "msg-1",
  menu: "event-snippets",
});
```

React and Vue apps that already mount Inspector on localhost need no new
caller code. Chat wires the bookmark through Inspector context.

`@copilotkit/core` exports `ɵinjectInspectorEvents` for Inspector only.
App code must not call it. There is no public Core emit API.
2026-08-25 09:39:37 +02:00
Alem Tuzlak 328ee3cb58 Merge origin/main into feat/OSS-871-view-thread-in-app 2026-08-24 19:58:19 +02:00
Ben Taylor 105ac3cfb9 fix(core): keep exactly one tool result per tool call across message snapshots (#6294)
# fix(core): keep exactly one tool result per tool call across message
snapshots

## Summary

When an agent emits a MESSAGES_SNAPSHOT, AG-UI merges it by message id
and can drop a tool message that TOOL_CALL_RESULT created. The next turn
then sends an assistant tool call without its paired result, which
providers reject.

This PR records observed tool results for the current input and repairs
history through AG-UI's returned-messages mutation channel. It keeps one
tool message per toolCallId and composes with current main's first-seen
message provenance.

## Root cause

@ag-ui/client applies events against its own cloned messages array.
TOOL_CALL_RESULT creates a tool message and inserts it after its
assistant owner. A later MESSAGES_SNAPSHOT is a replace-by-id merge, so
a missing tool entry can remove that result. packages/core had no record
of the result event, so there was nothing to restore it from.

## What changed

- StateManager records one ToolCallResultEvent per toolCallId on the
current RunAgentInput. Events keep flowing through AG-UI's normal path.
- At RUN_FINISHED, RUN_ERROR, and onRunFailed, reconciliation returns a
fresh message array only when a repair is needed. AG-UI applies it
through its normal mutation chain.
- Pending results are released at each finished server-run boundary and
at finalization, so a later server run under one input cannot resurrect
a result removed by its snapshot.
- The "Forwarded to client" sentinel classifier now lives in one
internal module used by StateManager and run-handler.ts.

## The reconciliation rule

toolCallId is the decisive identity:

- No assistant owner for the call: do nothing.
- A real tool message already exists for the call under any message id:
keep one result and remove duplicate same-call representations.
- Only placeholders exist: promote one to the canonical result and drop
the rest.
- Nothing exists: insert the result after its assistant owner and its
contiguous tool messages.

## On the LangGraph duplicate

LangGraph can represent one result with different streamed and
checkpoint message ids. The regression fixture keeps the streamed result
before the snapshot and places both representations in the snapshot. The
final history and next-turn input contain one result for that
toolCallId.

Two tool messages for one toolCallId are one malformed history class.
Keying reconciliation by toolCallId makes that duplicate unrepresentable
while preserving normal event delivery.

## What this does not do

- No direct agent.messages mutation, setMessages from a subscriber, or
stopPropagation. AG-UI remains the owner of message application,
ordering, and publication.
- Reconciliation does not infer or rewrite run identity. Current main's
event-derived run identity and first-seen snapshot provenance remain
intact.
- No message-to-run association is performed inside reconciliation.
- No public API change, export, version bump, or changeset.

## Relationship to #3884

Related to #3884, but not marked as closing it. The event sequence in
that issue has no MESSAGES_SNAPSHOT, and it already produces a correct
turn-2 history on current main. Snapshot-dropped results are a real bug
worth fixing independently, while the reporter's case still needs a raw
event trace.

## Test plan

All cases drive CopilotKitCore.runAgent() against real AbstractAgent
subclasses.

- Two-turn reproduction: a snapshot omits the result, and the next turn
receives exactly one result.
- LangGraph shape: differing message ids under one toolCallId produce
one surviving tool message in real event-before-snapshot order.
- Repeated server runs under one input do not resurrect a result removed
by a later snapshot.
- Terminal mutation, normal result propagation, duplicate results,
placeholders, ownerless results, ordering, RUN_ERROR, local failure, and
run ownership remain covered.
- The focused core tests pass 32/32. Core typecheck, build, formatting,
lint, and diff checks pass. CI checkboxes remain for GitHub.
2026-08-24 11:19:31 -05:00
Alem Tuzlak 7792347674 fix(core): narrow assistant messages in inspector test 2026-08-24 16:10:34 +02:00
Alem Tuzlak 4bd576d4ea Merge branch 'main' into alem/oss-874-inspector-event-snippets 2026-08-24 15:48:38 +02:00
MikeRyanDev 71977ddfce chore: release monorepo v1.69.0 2026-08-21 18:09:45 +00:00
Alem Tuzlak 76c8e23a0b feat(web-inspector): add Event Snippets and save-as-snippet
Developers can compile, save, and replay AG-UI events from Inspector.

Localhost chat can save a live turn as a snippet.
2026-08-21 19:39:18 +02:00
Alem Tuzlak 626f06a344 fix(core): keep live thread events on the matching agent
REST /threads is agent-scoped. The Phoenix user_meta channel is not. Drop live upserts whose agentId does not match the store so Inspector All Agents does not show the same thread twice.
2026-08-20 19:17:27 -07:00
Rod Boev d5fe12043c fix(core): clear tool result state per server run 2026-08-20 21:06:21 -04:00
Rod Boev b2e16947c5 test(core): restore LangGraph event ordering 2026-08-20 20:54:09 -04:00
Rod Boev 1cde1d8f04 fix(core): align tool result history with current main 2026-08-20 20:44:16 -04:00
Rod Boev ca0e094347 fix(core): close terminal lifecycle review gaps
Track the started input through protocol errors so remapped run IDs clean up
the active run without disturbing pre-start failures. Add lifecycle and
multi-call reconciliation coverage.
2026-08-20 20:32:47 -04:00
Rod Boev 08f2655c24 fix(core): deduplicate tool results by toolCallId
Reconcile streamed tool results by call identity so divergent message IDs
cannot append a second real result. Share placeholder normalization between
state reconciliation and run-handler forwarding.
2026-08-20 20:32:39 -04:00
Rod Boev ce8f077733 test(core): cover finalized and overlapping result lifecycles
Exercise same-input finalization cleanup and a pre-start failure while an
earlier input remains active.
2026-08-20 20:31:17 -04:00
Rod Boev 9ecb00192e fix(core): retain all propagated tool results during reconciliation
Leave AG-UI result propagation active and reconcile placeholders, duplicate
identities, and pre-start lifecycle state without suppressing subscribers.
2026-08-20 20:31:06 -04:00
Rod Boev 85cd3c133e fix(core): preserve result ownership across terminal edge cases
Use the input fallback for pre-start terminals, preserve message associations,
and match frontend placeholders by their normalized full content.
2026-08-20 20:30:14 -04:00
Rod Boev 61834d9443 fix(core): preserve tool results after message snapshots
Route canonical tool results through the AG-UI terminal messages mutation so
subsequent runs retain results omitted by later snapshots.
2026-08-20 20:29:12 -04:00
Ben Taylor 6c955686eb feat(react-core): expose AG-UI raw event to feedback callbacks (#6289)
## Summary

React v2 feedback callbacks receive an assistant message without the
trace metadata carried by the direct AG-UI event that created it. This
slice exposes that metadata to thumbs callbacks without changing
canonical messages or future run inputs.

## Root cause

AG-UI keeps `rawEvent` on events while reducer-created assistant
messages remain protocol-clean. `StateManager` sees the direct start
event but previously discarded its correlation before
`CopilotChatMessageView` forwarded the message to feedback callbacks.

## Changes

- Store defined direct `TEXT_MESSAGE_START.rawEvent` metadata by agent,
thread, and message.
- Replace repeated scoped entries and prune them with message removal
and lifecycle cleanup.
- Return a cloned sidecar value through
`CopilotKitCore.getRawEventForMessage`.
- Enrich only thumbs-up and thumbs-down callback arguments at click time
across flat and virtualized rendering.
- Add production-path regressions and document the callback-only type.

## Out of scope

Canonical messages, future `RunAgentInput.messages`, render props,
message identity, stream ordering, snapshots, transformed chunks,
persistence, GraphQL, legacy React, Vue, Angular, and standardized trace
semantics remain outside this slice.

## Related PRs and Issues

Addresses #3039.

The callback-only scope follows
https://github.com/CopilotKit/CopilotKit/issues/3039#issuecomment-5086936452.
Related trace-correlation contract: #4634.

## Test plan

- [x] StateManager sidecar tests, 10 passed. Covers direct capture,
falsey values, replacement, scope isolation, cleanup, snapshots, and
chunks.
- [x] React v2 feedback tests, 4 passed. Covers real callback routing,
canonical and outbound cleanliness, render identity, and flat/virtual
paths.
- [x] Full package suites, 625 core tests, 1,475 React Core tests, and 2
script tests passed.
- [x] Typecheck, formatting, lint, and whitespace validation passed;
lint reported five pre-existing warnings.
- [ ] CI green (`static / quality`, `test / unit` on Node 20/22/24).

## Notes

The clean-base behavioral half of the reproduction remains unproved
because temporary worktree setup hung behind unrelated Git processes.
The PR makes no base execution claim for that half.
2026-08-20 14:17:24 -05:00
Ben Taylor 6787b30203 fix(core): preserve run IDs across SSE connect replay (#6253)
## What does this PR do?

- Uses each `RUN_STARTED.runId` during Runtime SSE connect replay.
- Preserves the first run association when later message snapshots are
cumulative.
- Keeps live message events able to correct an earlier provisional run
association.
- Adds `/connect` and StateManager regression coverage for multiple
server runs.

## Why?

A single `/connect` stream can contain multiple runs. This affects
custom Runtime streams and the built-in in-memory runner, which replays
historic runs through one reconnect stream. StateManager previously
stored replayed state under the connection input ID and reassigned
earlier snapshot messages to the latest run.

## Related PRs and Issues

- Closes #6252

## Validation

- `@copilotkit/core` tests: 59 files, 661 tests passed
- `@copilotkit/core` type check
- Pre-commit lint, test, publint, attw, and commitlint

## Checklist

- [x] I have read the Contribution Guide
- [x] Documentation is not required for this internal bug fix
- [x] Allow edits by maintainers is enabled
2026-08-20 13:03:50 -05:00
BenTaylorDev aa3fb29dce chore: release monorepo v1.68.3 2026-08-20 10:27:07 -07:00
Ben Taylor 9df63beeef fix(runtime): name useSingleEndpoint when a single-route envelope hits a multi-route runtime (#6579)
Closes
[OSS-882](https://linear.app/copilotkit/issue/OSS-882/add-to-existing-journeys-reach-for-the-v1-compat-copilotkit-wrapper).

## The failure

The v1-compatible `<CopilotKit>` provider pins `useSingleEndpoint` to
`true`
([`copilotkit.tsx:108`](https://github.com/CopilotKit/CopilotKit/blob/main/packages/react-core/src/components/copilot-provider/copilotkit.tsx#L108)),
so its startup handshake POSTs `{ method: "info" }` at the base path. A
multi-route runtime — the default — matches no route for that path and
answered a bare `{"error":"Not found"}`, indistinguishable from a wrong
`basePath` or an unmounted handler.

Two independent onboarding validation runs hit this on their first
browser attempt and each had to guess the cause. Both were
*add-to-existing-app* journeys; the greenfield one reached for
`CopilotKitProvider` and never saw it.

## What changed

**The runtime says what happened.** `detectSingleRouteEnvelope`
recognises a POST whose JSON body carries a `method` the single-route
endpoint accepts, and the multi-route handler uses it at the one point
routing gives up. The 404 now carries a `code` and a message naming the
prop, plus a `logger.warn` so it lands in the dev-server terminal too.
Deliberately conservative — wrong verb, non-JSON, unknown method, or a
JSON POST that isn't an envelope all stay ordinary 404s, unchanged in
status and shape.

**The client stops discarding it.** All four `/info` callers (two in
`agent-registry.ts`, two in `agent.ts`) threw away the response body and
reported only the status, so a server-side diagnosis reached nobody.
They now go through `runtimeInfoError`, which folds a string `message`
from the body into the thrown error. Any future server-side diagnosis
reaches the developer for free.

**Docs.** Five pages paired a v2 multi-route handler with `<CopilotKit>`
and never mentioned the prop. Rather than a warning under a snippet that
is still wrong to copy, the snippets themselves now pass
`useSingleEndpoint={false}`, with a short callout linking to the
provider/handler mapping.

Two pages were deliberately left alone: `backend/runtime-endpoints.mdx`
already documents the pairing in full, and `cookbook/arcade.mdx` uses
`mode: "single-route"` on purpose and already explains it.
`backend/copilot-runtime.mdx` keeps its snippet as-is — it pairs with
the v1 endpoint, where the default is correct — and gains the caveat
only on its "switch to v2 handlers" note.

Option 3 in the issue (reconsidering the compat default) is **not** in
this PR.

## Testing

### Both halves connect, end to end

Real `createCopilotRuntimeHandler` + real `CopilotKitCore` configured
the way the v1 wrapper configures it — no mocks on either side:

```
code   : runtime_info_fetch_failed
message: Runtime info request failed with status 404: Received a single-route
         request envelope ({ method: "..." }) but this runtime is mounted in
         multi-route mode, so the request matched no route. If the frontend uses
         <CopilotKit> from @copilotkit/react-core/v2, pass useSingleEndpoint={false}
         — that provider defaults it to true. Otherwise mount the runtime with
         mode: "single-route" to serve this envelope.

PASS — the diagnostic reached the client
```

The server-side `logger.warn` fired in the same run, carrying `{ url,
path, method: 'info' }`.

### Unit tests

`packages/runtime` — `single-route-envelope-diagnostic.test.ts` (2
positive, 5 control):

```
 ✓ src/v2/runtime/__tests__/single-route-envelope-diagnostic.test.ts (7 tests) 26ms
      Tests  7 passed (7)
```

`packages/core` — `runtime-info-error-detail.test.ts` (2 positive, 5
control):

```
 ✓ src/__tests__/runtime-info-error-detail.test.ts (7 tests) 267ms
      Tests  7 passed (7)
```

### Mutation checks

Every new test was verified to fail when its mechanism is broken, in
both directions.

Detector forced to `return null` — the two positives die, the four
controls hold:

```
   × names useSingleEndpoint when the envelope is an info call
   × diagnoses every method the single-route envelope accepts
   ✓ leaves an ordinary unmatched route as a plain 404
   ✓ leaves a JSON POST that is not an envelope as a plain 404
   ✓ leaves an unrecognized method name as a plain 404
   ✓ does not diagnose a non-JSON POST
```

Detector forced to `return "info"` — the controls die instead, proving
they are not vacuous:

```
   ✓ names useSingleEndpoint when the envelope is an info call
   ✓ diagnoses every method the single-route envelope accepts
   × leaves an ordinary unmatched route as a plain 404
   × leaves a JSON POST that is not an envelope as a plain 404
   × leaves an unrecognized method name as a plain 404
   × does not diagnose a non-JSON POST
```

`runtimeInfoError` with the detail dropped, then with the `typeof
message === "string"` guard removed — each kills a different pair:

```
mutation: detail dropped              → 2 failed | 5 passed
mutation: accept any message field    → 2 failed | 5 passed
restored                              → 7 passed
```

### Full suites, builds, docs

| Check | Result |
|---|---|
| `packages/core` full suite | `Test Files 60 passed (60)` / `Tests 662
passed (662)` |
| `packages/runtime` full suite | `Test Files 142 passed (142)` / `Tests
2067 passed (2067)` |
| `packages/core` `tsc --noEmit` | clean |
| `packages/runtime` `tsdown` | `416 files` — build complete |
| MDX compile, 5 edited pages | all `OK` |
| pre-commit `nx run-many -t test,publint,attw` | passed across affected
projects |
| CI on `f94d1ab0` | 72 pass, 3 skipping, 0 fail |

Both suites are fully green. An earlier revision of this description
reported 6
runtime failures as pre-existing on `main`; they were not. They were
artifacts
of a worktree whose `node_modules` had been assembled by hand, and a
proper
`pnpm install` cleared all of them along with the inspector-metadata
failures
from a stale `@copilotkit/shared` dist. `main` is clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-08-20 10:37:40 -05:00
JYbill 61ac927bae Merge branch 'main' into fix/state-manager-run-id 2026-08-20 20:01:26 +08:00
contextablemark b0233c4eb0 chore: release monorepo v1.68.2 2026-08-20 02:19:06 +00:00
Benjamin Taylor f94d1ab0fb fix(runtime): name useSingleEndpoint when a single-route envelope hits a multi-route runtime
The v1-compatible `<CopilotKit>` provider pins `useSingleEndpoint` to `true`,
so it POSTs `{ method: "info" }` at the base path. A multi-route runtime — the
default — matches no route for that path and answered a bare `{"error":"Not
found"}`, which is indistinguishable from a wrong `basePath` or an unmounted
handler. Two independent onboarding validation runs hit this on their first
attempt and had to guess the cause.

The runtime now recognises the envelope at the one point multi-route routing
gives up, and answers the 404 with a message naming the prop, plus a
`logger.warn` so it also lands in the dev server terminal. Status and shape are
unchanged for every other miss.

That message was reaching nobody: all four `/info` callers threw away the
response body and reported only the status. They now route through
`runtimeInfoError`, which folds a string `message` from the body into the
error — so any future server-side diagnosis reaches the developer too.

Docs: five pages paired a v2 multi-route handler with `<CopilotKit>` without
mentioning the prop. Their snippets now pass `useSingleEndpoint={false}` and
link to the provider/handler mapping. `backend/runtime-endpoints.mdx` already
documents the pairing and is untouched; `cookbook/arcade.mdx` deliberately uses
single-route mode and already explains it.

Closes OSS-882

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 17:40:31 -05:00
Tyler Slaton 4b2586bd90 fix(web-inspector): load saved threads in active chats 2026-08-19 15:34:03 -07:00
Alem Tuzlak 06cef9e659 feat(web-inspector): add view thread in your app
Let the Inspector load a saved thread into the official React or Vue chat. Core owns a two-way EventClient bridge. Official chat configuration applies an in-memory override that wins over a pinned threadId. Production builds hide the action.
2026-08-19 13:50:39 +02:00
xiaoqinvar 08f05b39f4 fix(core): preserve live message run reassignment 2026-08-18 17:28:33 +08:00
JYbill 12e89e60fa Merge branch 'main' into fix/state-manager-run-id 2026-08-15 17:48:03 +08:00
tylerslaton 1f9b60b231 chore: release monorepo v1.68.1 2026-08-14 21:05:45 +00:00
tylerslaton e6864b6bdd chore: release monorepo v1.68.0 2026-08-14 20:11:31 +00:00
Ben Taylor a3b814a041 fix(core): refresh Intelligence delegate headers before every join (#6469)
## Summary

`ProxiedCopilotRuntimeAgent` builds its `IntelligenceAgent` delegate
**once** and caches it for the proxy's lifetime, copying `headers` into
the delegate's constructor config. Nothing ever refreshed that copy, so
**a header that changed after the delegate was created never reached
`/connect` or `/run`** — for the life of the agent.

For a multi-tenant app carrying the active tenant in a header, the join
was attempted under the *previous* tenant's identity with the *new*
tenant's thread id, and the platform correctly answered
`THREAD_NOT_FOUND`. Only a full page reload cleared it, because that
rebuilds the delegate. A rotated or refreshed `Authorization` bearer has
the same exposure.

Reported by Sameday against 1.67.1 with a deterministic staging repro:

```
19:45:23.554 | /copilotkit/runtime/threads            | hdr=<tenant B> | 200
19:45:23.886 | /copilotkit/runtime/threads/subscribe  | hdr=<tenant B> | 200
19:45:23.893 | /copilotkit/runtime/agent/<id>/connect | hdr=<tenant A> | body.companyId=<tenant B> | 404
```

`/threads` carries **B** while `/connect` carries **A**, ~340ms apart in
the same switch. Not a race — a stale copy with no refresh path.

## Root cause

`setHeaders` / `applyHeadersToAgent` could not fix this: they write an
agent's `.headers`, and `IntelligenceAgent` exposed only `private
config`. `syncDelegate` *looks* like the refresh path, but its
`hasHeaders` probe is `"headers" in agent` — false for the delegate,
since `headers` is declared on `HttpAgent`, not on `AbstractAgent`. So
`config.headers` was the sole header source for Intelligence REST calls,
with no refresh path at all.

## The fix

Expose `headers` as a public accessor pair backed by `config`, and read
it in `requestJoinCredentials$`.

**The accessor is the entire fix**: it makes `hasHeaders` true, so
`syncDelegate` — which already runs on every `resolveDelegate()`, and is
preceded by `applyHeadersToAgent` in `RunHandler.connectAgent` — starts
actually refreshing the delegate before each join. No new plumbing.

Two things worth flagging for reviewers:

1. **The originally-suggested fix ("make `requestJoinCredentials$` read
live headers") does not work on its own** — and is actively harmful.
There was no live header source on the class to read: without the
accessor, `this.headers` is `undefined` and **every header is dropped**
(verified: only `Content-Type` survives). The read here goes through the
accessor for a single source of truth, not because that read carries the
fix.

2. **The setter replaces the config object rather than mutating it**,
because `clone()` shares the config reference. The join path alone would
mask an in-place write (`syncDelegate` rewrites headers just before
every join), but the credential re-acquisition inside a running pipeline
(`intelligence-agent.ts:563`) does not re-sync — so a clone's tenant
could ride out on the original's socket-error refresh. That's the same
cross-tenant leak this accessor exists to prevent.

`credentials` had the identical defect via `config.credentials`
(`hasCredentials` was false too) and gets the same treatment.

## Testing

**Unit tests (5 new, each written first and watched fail).** The pre-fix
failure is the staging symptom reproduced:

```
FAIL > sends a header changed after the delegate was created
AssertionError: expected { …(2) } to match object { 'X-Tenant': 'tenant-b' }
-   "X-Tenant": "tenant-b",
+   "X-Tenant": "tenant-a",
```

Coverage: a header changed post-construction reaches `/connect`; the
same on the `/run` path (which was independently verified broken
pre-fix, sending tenant A where B was expected); credentials likewise; a
clone's header update must not reach the original
(`IntelligenceAgent.clone()` invariant — this one fails under in-place
config mutation); and a per-thread clone and its original each send
their own tenant.

**Verified beyond the unit tests.** Because the mocked-harness result
alone doesn't prove the production wiring, I drove the real chain —
`CopilotKitCore.setHeaders` → registry → proxy → delegate → outbound
POST — in a plain Node process with no vitest and no `vi.mock`, stubbing
only `fetch` at the network boundary. Same script against the unfixed
file, then the fix:

```
BEFORE (origin/main)                      AFTER (this PR)
"headers" in delegate: false              "headers" in delegate: true
delegate.headers: undefined               delegate.headers: { X-Tenant: tenant-b }
proxy.headers after setHeaders(B):        proxy.headers after setHeaders(B):
  { X-Tenant: tenant-b }                    { X-Tenant: tenant-b }

0: POST /connect  X-Tenant=tenant-a       0: POST /connect  X-Tenant=tenant-a
1: POST /connect  X-Tenant=tenant-a  <--  1: POST /connect  X-Tenant=tenant-b  credentials=include
FAIL (stale headers)                      PASS (live headers reach /connect)
```

The "before" column reproduces the report's tell exactly:
`proxy.headers` correct at tenant B while `/connect` still sends tenant
A, through the very API the report found ineffective.

**Gates** (run in a worktree with a freshly built `@copilotkit/shared`,
since a stale dist otherwise produces 20 unrelated
`core-inspector-metadata` failures and 4 `tsc` errors):

| Gate | Result |
| --- | --- |
| `@copilotkit/core` vitest | **654 passed / 654**, 59/59 files |
| `tsc --noEmit` | clean |
| `oxlint` | 0 errors (2 warnings, both pre-existing test helpers) |
| `oxfmt` | no reformatting needed |

**Not covered:** `fetch` is stubbed, so this does not exercise a live
Intelligence gateway or a browser tenant switch — it proves the outbound
header is correct, not the platform's response to it.

## Note for whoever merges

#6450 and #6468 also touch `intelligence-agent.ts` (thread-restore work)
but neither goes near the header path, so conflicts should be textual at
worst.

## Follow-up left out of scope

Two separate pre-existing defects surfaced while verifying this one.
Neither is touched here.

**1. `credentials` passed to a `ProxiedCopilotRuntimeAgent` constructor
are dropped at registration.** `applyCredentialsToAgent` overwrites
`agent.credentials` from core unconditionally, with no per-agent
baseline — unlike `applyHeadersToAgent`, which merges over the
`agentOwnHeaders` baseline captured for exactly this reason (#5635).
Probed in a real process: an agent constructed with `credentials:
"include"` in a core with none configured reports `undefined`
immediately after registration, and every join goes out without
credentials. Identical before and after this PR, so it is not a
regression from this change — but the headers/credentials asymmetry
looks unintended, given #5433 was specifically about preserving proxied
runtime credentials.

**2. `buildRuntimeUrl` reads `config.agentId`
(`intelligence-agent.ts:770`), (`intelligence-agent.ts:770`), so
`syncDelegate`'s `delegate.agentId = routedAgentId()` is cosmetic for
the REST URL. Same root-cause class as this bug, but latent rather than
live (routing is fixed per proxy instance).

Happy to file both separately.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-08-13 09:12:58 -05:00
Benjamin Taylor 70545f072a test(core): correct an overclaiming comment, tighten the credentials assertion
The per-thread-clone test's comment claimed it guards the copy-on-write
setter. It does not: syncDelegate rewrites headers before every join, so
it passes even with an in-place write (verified). Say what it actually
pins — each proxy's joins carry its own tenant — and point at the
clone-invariant test that does guard the setter.

Also assert the pre-change join carried no credentials, so the
credentials test shows a transition rather than a single end state.
2026-08-13 08:15:52 -05:00
JYbill c06709aff7 Merge branch 'main' into fix/state-manager-run-id 2026-08-13 17:52:08 +08:00
Murat Sari 01c7283210 fix(core): prevent duplicate interrupt tool results (#6201) 2026-08-13 01:18:16 +02:00
Benjamin Taylor 7d1cdc15df test(core): pin the run path against stale Intelligence headers
The report names both /connect and /run. The run path reaches the
delegate through #runViaDelegate, which shares resolveDelegate with the
connect path, so the accessor fixes both — but that was inferred from the
shared call site rather than pinned. Verified failing against the
pre-fix file (sent tenant-a where tenant-b was expected).
2026-08-12 17:01:21 -05:00
Benjamin Taylor a3562c20a6 fix(core): refresh Intelligence delegate headers before every join
`ProxiedCopilotRuntimeAgent` builds its `IntelligenceAgent` delegate once
and caches it for the proxy's lifetime, copying `headers` into the
delegate's constructor config. Nothing ever refreshed that copy, so a
header that changed later never reached `/connect` or `/run` — for the
life of the agent.

`setHeaders`/`applyHeadersToAgent` could not fix it: they write an
agent's `.headers`, and `IntelligenceAgent` exposed only `private
config`. `syncDelegate` looked like the refresh path but its `hasHeaders`
probe is `"headers" in agent`, which was false for the delegate.

Multi-tenant apps that carry the active tenant in a header saw the join
attempted under the previous tenant's identity with the new tenant's
thread id, answered THREAD_NOT_FOUND. A rotated `Authorization` bearer
has the same exposure. Only a full reload cleared it.

Expose `headers` as a public accessor pair backed by `config`. The
accessor is the entire fix: it makes `hasHeaders` true, so `syncDelegate`
— which already runs on every `resolveDelegate()` — starts actually
refreshing the delegate before each join. Note that changing
`requestJoinCredentials$` to read live headers, as the report suggested,
does nothing on its own: there was no live source on the class to read,
and without the accessor `this.headers` is `undefined`, which drops every
header. It reads through the accessor here for a single source of truth,
not because that read carries the fix.

The setter replaces the config object rather than mutating it, because
`clone()` shares the config reference. The join path alone would mask an
in-place write (syncDelegate rewrites headers just before every join),
but the credential re-acquisition inside a running pipeline does not
re-sync, so a clone's tenant could ride out on the original's
socket-error refresh.

`credentials` had the identical defect via `config.credentials`
(`hasCredentials` was false too) and gets the same treatment.

Verified beyond the unit tests by driving the real chain
(`CopilotKitCore.setHeaders` -> registry -> proxy -> delegate ->
outbound POST) in a plain Node process with only `fetch` stubbed:
before, `"headers" in delegate` was false and the join after a tenant
switch still sent tenant A; after, it sends tenant B.

Reported by Sameday against 1.67.1 with a deterministic staging repro.
2026-08-12 16:36:11 -05:00
tylerslaton 10d8f43829 chore: release monorepo v1.67.1 2026-08-10 20:28:46 +00:00
onsclom 48312f4d65 chore: release monorepo v1.67.0 2026-08-10 18:32:14 +00:00
Austin Merrick b32b5539cc feat: add Inspector navigation, usage, and locked Threads (refs ENT-1173) (#6275)
## What does this PR do?

Adds the CopilotKit consumer side of ENT-1173 across Shared, Runtime,
Core, Web Inspector, and the existing Shell Docs pages.

- Defines and parses optional trusted Inspector metadata for identity,
plan, license, action, usage, and expiry. Runtime proxies it through a
private, failure-isolated route, and Core refreshes it without changing
connection state.
- Groups Inspector navigation into Threads, Agents, and Learning.
Threads renders finite, unlimited, unknown, overage, and expiring usage
states plus matching trusted plan or license actions.
- Keeps explicit `threadEndpoints` as the only authority for Thread
requests. Locked or absent capability states make no list, subscription,
detail, message, event, or state calls.
- Keeps the zero-thread video, three example Threads, detail tabs, and
guided tour in empty and locked states. General Intelligence remains the
default onboarding path; only trusted `team_self_hosted` metadata uses
self-hosted onboarding.
- Gives an active license with missing Runtime routes a short **Finish
setting up Rich Threads** state. Users can copy a safe coding-agent
prompt or open the public Runtime setup guide. The same copy control
appears in that guide, and raw Markdown/LLM views include the full
prompt.
- Keeps finite usage green below 90%, orange from 90% to the limit, and
red at or above the limit. At 90%, a trusted plan action changes from
**Manage Your Plan** to a purple **Upgrade Your Plan** without changing
its trusted URL, action kind, or telemetry contract.
- Adds a deterministic 33-state loopback lab for CopilotKit developers.
It has no production route or export, is absent from public docs and
package metadata, and is excluded from the npm tarball.

`Expiring Soon` is display-only; this PR does not enable the thread
culler. Managed Enterprise receives no manage-plan action, and Team
Self-Hosted receives no hosted plan action. Optional metadata and the
additive expiry field remain compatible across mixed producer, Runtime,
Core, and Inspector versions.

A small Channels test-only change updates fetch mocks for current
TypeScript types. It changes no Slack or Teams docs or runtime behavior.

## Related PRs and issues

- Refs
[ENT-1173](https://linear.app/copilotkit/issue/ENT-1173/ship-plg-ready-inspector-navigation-metadata-and-locked-threads)
- Producer:
[CopilotKit/Intelligence#696](https://github.com/CopilotKit/Intelligence/pull/696)

## Validation

- `@copilotkit/web-inspector`: 20 files and 372 tests passed; typecheck
and production build passed.
- Shell Docs: 57 files and 383 tests passed; lint, typecheck, and
production build passed. The build generated all 222 static pages.
- Browser checks cover the copy-prompt flow, unchanged white **Manage
Your Plan**, purple **Upgrade Your Plan**, orange 4,500/5,000 usage, and
red 5,000/5,000 usage.
- Independent review found no Critical or Important issues.
- The broader Runtime, React Native, Channels, package-quality,
compatibility, and Node-version checks from the prior pushed head remain
green.

## Checklist

- [x] I have read the [Contribution
Guide](https://github.com/copilotkit/copilotkit/blob/master/CONTRIBUTING.md)
- [x] I updated the relevant documentation
- [ ] "Allow edits by maintainers" is checked
2026-08-07 14:08:23 -07:00
tylerslaton b40602e698 chore: release monorepo v1.66.4 2026-08-07 01:25:14 +00:00
tylerslaton cfc5cfe727 chore: release monorepo v1.66.3 2026-08-07 00:31:47 +00:00
xiaoqinvar ed559fc4c2 fix(core): preserve fresh event run IDs after completed runs 2026-08-06 14:33:32 +08:00
xiaoqinvar 3fce5ecec4 Merge upstream main into fix/state-manager-run-id 2026-08-06 10:54:23 +08:00
David McKay 696c44244b fix(core): stop HITL continuations reusing the originating run id on the wire
#6296 preserved the logical run id across a HITL resolve by pinning the
originating id on the follow-up's agent invocation. That fixed #3456 (external
tracing saw one logical run split into two halves), but pinning it on the WIRE
made the transport treat the follow-up as a resumption of a run it had already
finished. It re-delivered that run's already-applied half — duplicating every
tool call on the message, each duplicate carrying empty arguments, since a start
event has none and the TOOL_CALL_ARGS deltas that follow are addressed to the
first copy — and the follow-up's own tool call never reached client state, so
its card never rendered.

In the reskinnable-demo banking skin that broke teach mode outright: the agent
called awaitDashboardDemonstration, the server emitted TOOL_CALL_START for it,
and the live "Recording your workflow" card never appeared, leaving no way to
finish or save the demonstration.

#6296's goal is kept, moved one layer up. The continuation is registered against
the originating id (markNextRunAsContinuation already took an expectedRunId
parameter, previously unused) and the state manager re-stamps the continuation's
events onto it. State/message association and external tracing still see ONE
logical run; the wire is simply allowed to identify the invocation honestly.
Nothing from #6296 is reverted.

core-follow-up's run-id test asserted the mechanism (both invocations carry the
same wire id), which this deliberately changes, so it now asserts the goal: the
originating id is pinned on the first invocation and the follow-up leaves it to
the transport. Its sibling assertion — the thread still knows exactly one run —
was already there and still passes untouched. A new StateManager test covers the
re-stamp directly; verified red before green by dropping the expectedRunId
lookup.

Verified in the browser against a live Intelligence stack: before, the recording
card never rendered; after, it renders with its REC indicator and I'm done /
Cancel controls. `@copilotkit/core` 58 files and `@copilotkit/react-core` 123
files pass.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 16:12:12 -07:00
Austin Merrick 4a5bf2b419 test(core): prove inspector expiry snapshots 2026-08-05 11:55:44 -07:00
Austin Merrick 46b692ba24 fix(inspector): drop out-of-scope expiry metadata 2026-08-05 11:55:43 -07:00