Skip to content

WIP: almost usable v0.1 - #1

Merged
ataibarkai merged 24 commits into
mainfrom
atai/0619/react_input_bindings
Jun 30, 2023
Merged

ataibarkai merged 24 commits into
mainfrom
atai/0619/react_input_bindings

Conversation

@ataibarkai

Copy link
Copy Markdown
Contributor

All code is in the openai example, not the library

@ataibarkai
ataibarkai merged commit 0d207ed into main Jun 30, 2023
@ataibarkai
ataibarkai deleted the atai/0619/react_input_bindings branch June 30, 2023 23:18
bobbyo pushed a commit to bobbyo/CopilotKit that referenced this pull request Oct 10, 2025
…itching

Adds a collapsible thread manager component to demonstrate and test the
frontend race condition fix (TanStack Query implementation).

## Features

**SimpleThreadManager Component:**
- Tracks threads in local state (compatible with future RemoteThreadManager schema)
- Collapsible accordion that appears when 2+ threads exist
- Shows thread list with names ("Thread CopilotKit#1", etc.), truncated IDs, and timestamps
- Clean UI suitable for non-dev users, IDs visible for developers
- New Thread button creates fresh UUID

**Thread Switching:**
- Click thread in list to switch
- Each thread maintains independent conversation history
- Demonstrates frontend fix eliminates race conditions

**UI/UX:**
- Fixed position top-left, unobtrusive
- Closed by default, no auto-closing
- Thread IDs shown discretely in gray
- Relative timestamps ("5m ago", "1h ago")

## Testing

Manual test plan in examples/coagents-starter/ui/TESTING.md covers:
- Basic thread creation
- Thread switching
- Rapid switching (race condition test)
- Thread list UI
- State isolation between threads

## Architecture

Data structure matches future RemoteThreadManager:
```typescript
type ThreadMetadata = {
  id: string;
  name: string;
  createdAt: Date;
};
```

CopilotKit moved from layout.tsx to page.tsx to enable dynamic threadId.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
shaneholloman pushed a commit to shaneholloman/copilotkit that referenced this pull request Jun 19, 2026
…list

CR-round hardening that builds on the bug CopilotKit#1/CopilotKit#2 fixes: the P2 in-flight race
guard now reads the running digest from meta.imageDigest (the dead guard
never REFUSEd before) and is skipped on the --digest override path. Refresh
the snapshot ivar-lint allowlist line numbers after the surrounding CR line
drift.
AlemTuzlak added a commit that referenced this pull request Jul 6, 2026
…rwarded inbound headers (#5782)

## Problem

When a self-hosted v2 `CopilotRuntime` is configured with a server-side
agent (an `@ag-ui/client` `HttpAgent` with static `headers` for
service-to-service auth), the runtime forwards inbound
`authorization`/`x-*` request headers onto the agent's outgoing call
**and lets them override the headers the server configured** — silently
breaking service-to-service auth to a secured backend (e.g. a private
Cloud Run agent behind IAM).

`Fixes #5712`

## Root cause


`packages/runtime/src/v2/runtime/handlers/shared/agent-utils.ts:125-128`
merged forwarded inbound headers **last**, so they won on collision:

```ts
agent.headers = {
  ...agent.headers,                      // server-configured
  ...extractForwardableHeaders(request), // inbound — overrode the above
};
```

There are actually **two** failure modes:

1. **Same-case collision** — inbound `authorization` overwrites a server
`authorization` (last-write-wins).
2. **Case-mismatch collision** — `extractForwardableHeaders` lowercases
inbound keys (`authorization`), while the server typically configures
canonical casing (`Authorization`). A plain spread treats those as
*distinct* keys and emits **both** — which undici downstream comma-joins
into a single invalid `"Bearer A, Bearer B"` ("multiple JWTs") value.
Flipping the spread order alone does **not** fix this case.

## Fix

In `agent-utils.ts`, make server-configured `agent.headers`
authoritative on collision, matched **case-insensitively**: drop any
forwarded inbound header whose name (case-insensitively) is already set
on the agent, and let non-colliding inbound headers pass through
unchanged. This preserves the existing forward-for-auth behavior for
headers the server does *not* set, while guaranteeing a server-set token
is never overridden or duplicated.

The merge logic lives in a shared
`mergeForwardableHeaders(serverHeaders, request)` helper in
`packages/runtime/src/v2/runtime/handlers/header-utils.ts` so the
precedence semantics are defined in exactly one place.

### Scope note

This is the conservative precedence + case-insensitive-dedup fix (the
issue's suggested fix #1). I did **not** tighten the default allowlist
to drop hop-by-hop/platform `x-*` headers (`x-serverless-*`,
`x-forwarded-*`, …) or add an opt-out — those alter existing forwarding
behavior and are worth a separate, deliberate change. The precedence fix
alone resolves the reported breakage (the server-set token now wins
regardless of what the platform injects on a colliding header name).

A documented workaround already exists for users on released versions:
pass a custom `fetch` to the `HttpAgent` that builds outgoing headers
from scratch (it runs after `configureAgentForRequest` and survives the
per-request `agent.clone()`).

## Red-green proof (the real fix — `/run` path)

The load-bearing assertion: there must be exactly **one** authorization
header carrying the **server** value.

### RED (fix stashed, against unmodified `agent-utils.ts`)

```
 ❯ src/v2/runtime/__tests__/agent-header-precedence.test.ts (2 tests | 1 failed)
   × configureAgentForRequest — header precedence (#5712) > server-configured agent headers win over a colliding inbound header
AssertionError: expected [ 'Authorization', 'authorization' ] to have a length of 1 but got 2
     81|     expect(authKeys).toHaveLength(1);
 Test Files  1 failed (1)
      Tests  1 failed | 1 passed (2)
```

The pre-existing `agent-utils-header-forwarding.test.ts` also failed,
because it explicitly encoded the buggy behavior
(`expect(...["x-aimock-context"]).toBe("new-context")` — inbound
winning):

```
 FAIL  src/v2/runtime/__tests__/agent-utils-header-forwarding.test.ts > ... > request forwardable headers override matching pre-existing agent headers
AssertionError: expected 'old-context' to be 'new-context'
```

### GREEN (fix applied)

```
 ✓ src/v2/runtime/__tests__/agent-header-precedence.test.ts (2 tests) 2ms
 ✓ src/v2/runtime/__tests__/agent-utils-header-forwarding.test.ts (8 tests) 3ms
 Test Files  2 passed (2)
      Tests  10 passed (10)
```

The colliding test (`agent-utils-header-forwarding.test.ts`) was updated
from asserting the old bug to asserting corrected precedence + a new
case-insensitive-dedup guard. The non-colliding-forward test is retained
unchanged as a regression guard.

## Quality gates

```
NX  Successfully ran target check-types for project @copilotkit/runtime
NX  Successfully ran target test for project @copilotkit/runtime  — Test Files 113 passed (113), Tests 1576 passed (1576)
```

---

## `/connect`-path change — forward-looking plumbing, inert today

The original issue and a prior eval flagged the same forwarding pattern
at `handlers/sse/connect.ts`. To keep the two paths' merge semantics
consistent, the `/connect` path now builds the same server-wins merged
headers (via the shared `mergeForwardableHeaders` helper) and passes
them into `runner.connect()`.

**This is not an active auth fix, and it is not red-green-proven as one
— because there is no live bug to fix on the connect path today.** No
shipped runner consumes the `headers` field of
`AgentRunnerConnectRequest`: the in-memory, intelligence, telemetry, and
sqlite runners all destructure only `threadId` from the connect request
and ignore `headers` entirely. Connect is a thread replay/reconnect, not
a fresh outgoing agent call. So whatever headers we pass into
`runner.connect()` are dropped on the floor by every runner that ships.

What this change actually does:

- Threads the per-request agent clone through `handle-connect.ts →
handleSseConnect` so the connect path *has access to* the
server-configured `agent.headers` (it previously did not).
- Passes `mergeForwardableHeaders(agent?.headers, request)` into
`runner.connect()` — the correct, server-wins argument **shape** for a
future outbound-connecting runner that *would* consume connect-path
headers.
- Rewrites the comments/JSDoc on this path to say this plainly, rather
than implying an active auth fix. It also documents that the
connect-site `cloneAgentForRequest` call is the sole `agentId`-existence
guard (the intelligence branch never re-validates the id), and documents
`cloneAgentForRequest`'s `AbstractAgent | Response` (404) dual-return
contract that both callers depend on.

The real outbound header forwarding — the thing that fixes #5712 — is
the `/run` path's `agent.headers` mutation described above. The connect
change is staged plumbing so that if/when a runner starts honoring
connect-path headers, it inherits the same server-wins precedence
without a second fix.

### Tests on the `/connect` path

The connect tests assert the *merge shape* that reaches
`runner.connect()` (server value wins on collision, exactly one
`authorization` key, non-colliding `x-*` still forwards) and that the
agent-undefined case (no server `agent.headers`) degrades to forwarding
allowlisted inbound headers only and does not crash. These verify the
argument we construct is correctly shaped — not that any shipped runner
consumes it.

## Files

- `packages/runtime/src/v2/runtime/handlers/header-utils.ts` — shared
`mergeForwardableHeaders` helper (case-insensitive, server-wins).
- `packages/runtime/src/v2/runtime/handlers/shared/agent-utils.ts` —
`/run` path uses the helper so server headers win on collision (**the
real fix**).
- `packages/runtime/src/v2/runtime/handlers/sse/connect.ts` — `/connect`
path uses the helper; forward-looking plumbing, inert until a runner
consumes connect-path headers.
- `packages/runtime/src/v2/runtime/handlers/handle-connect.ts` — threads
the per-request agent clone into `handleSseConnect`.
-
`packages/runtime/src/v2/runtime/__tests__/agent-header-precedence.test.ts`
— `/run` regression test exercising the real `configureAgentForRequest`
surface with a real `HttpAgent`.
-
`packages/runtime/src/v2/runtime/__tests__/agent-utils-header-forwarding.test.ts`
— updated the test that encoded the old (buggy) precedence; added a
case-mismatch dedup guard.
-
`packages/runtime/src/v2/runtime/handlers/sse/__tests__/sse-connect-agent-id.test.ts`
— connect-path merge-shape + agent-undefined coverage.

### Notes

- A documented `@ag-ui/client` `HttpAgent` `fetch` workaround already
exists for attaching service-to-service auth the runtime can't override
(see the issue). This change makes the workaround unnecessary for the
`/run` precedence case.
- Conservative scope: this is the **precedence flip on `/run`** plus
forward-looking connect plumbing. Tightening the default allowlist
(dropping hop-by-hop / platform `x-serverless-*`, `x-forwarded-*`,
`x-cloud-trace-context`, …) and an opt-out switch — issue suggestions
#2/#3 — are intentionally left as a follow-up to keep the
security-policy change minimal.
jpr5 added a commit that referenced this pull request Jul 14, 2026
…d failures (#5956)

## Two silent-failure gaps in the showcase build/deploy/notify pipeline

These are **pre-existing** silent-failure holes surfaced in code review
(not
caused by any recent PR). This PR fixes the two load-bearing ones.

### 1. Green-but-zero-redeploy (silent "we thought we shipped but
didn't")

The `redeploy-staging` job computes the redeploy set as the intersection
of the
build matrix and the build-success set. This job **only runs when
`aggregate-build-results.outputs.any_success == 'true'`** (job-level
`if:`
guard). So if that intersection comes back **EMPTY**, it does NOT mean
"nothing
to deploy" — it means at least one slot built successfully yet none of
those
successes maps back to a matrix `dispatch_name`. That's a
`dispatch_name`↔
`service` contract skew (the aggregator's `service` values and the
matrix's
`dispatch_name` values drifted apart).

The old code emitted `services=` (empty) and exited 0 → the build went
**GREEN
while redeploying NOTHING**, silently.

**Fix:** on an empty intersection in this any_success-guaranteed step,
fail loud
(`::error::` + `exit 1`) with a diagnostic naming both sides of the
skew.
The legitimate "nothing changed / nothing succeeded" no-op paths are
guarded at
the **job level** (`has_changes=='true' && any_success=='true'`), so the
fixed
step never runs there — no false-red.

### 2. Starter build failures had no alert surface (invisible failures)

The `notify` job's `needs` (and its `if: failure()`) omitted
`detect-starter-changes` and `build-starters`, and `build-starters`
wrote no
per-slot build-result artifact. So a **failed starter image build
produced NO
Slack alert and NO PR comment** — it shipped silently.

**Fix:**
- Added `detect-starter-changes` + `build-starters` to `notify.needs` so
`if: failure()` sees a starter build failure → Slack alert + PR comment.
- Gave `build-starters` a per-slot build-result artifact **mirroring the
main
  `build` matrix** (same `{service,status}` shape, `cancelled→skipped`
  normalization, `if: always()`, `if-no-files-found: error`), using a
  **distinct `starter-build-result-*` prefix** so it never matches the
aggregator's `build-result-*` download pattern (starters must not
pollute the
  showcase redeploy set keyed by `dispatch_name`).

### Red / Green

**Finding #1** — extracted the step's shell/jq logic and drove it with
synthetic
inputs:

RED (pre-fix), any_success=true + empty intersection:
```
No services in matrix ∩ success-set — skipping redeploy.
Computed services CSV (matrix ∩ build-success):
EXIT=0        # $GITHUB_OUTPUT: services=   -> silent pass, redeploys NOTHING
```
GREEN (post-fix), same inputs:
```
::error::Build succeeded (any_success=true) but matrix ∩ success-set is EMPTY — dispatch_name/service contract skew; nothing would be redeployed.
Successful build service values: ["shell-RENAMED","mastra-RENAMED"]
Scheduled matrix dispatch_name values: ["shell","mastra"]
EXIT=1        # fails loud
```
No-regression: non-empty intersection → `EXIT=0 ; services=shell`. The
nothing-changed/nothing-succeeded paths are skipped at the job level
(never
reach the step) → no false-red.

**Finding #2** — modeled `if: failure()` (fires iff any `needs` job
result is
`failure`):
```
BEFORE (starters NOT in needs), starter=failure -> notify fires = False  (INVISIBLE, the bug)
AFTER  (starters IN needs),     starter=failure -> notify fires = True   (FIXED)
AFTER no-regression, starters=skipped, all green -> notify fires = False (quiet)
```

### Validation
- `python3 yaml.safe_load` parses OK.
- `actionlint`: only pre-existing findings remain (matrix jq SC2086 +
the known
`depot-ubuntu-24.04-4` runner-label warning); no new errors in edited
regions.
- `yamllint`: only pre-existing line-length/document-start/truthy
warnings.

### Scope
Touches **only** `.github/workflows/showcase_build.yml`, and only these
two
concerns. Does NOT touch the `shell_dashboard` paths-filter region (PR
#5955's
domain), nor the other backlog debt (false-root-cause comment,
double-alert,
check-lockfile guard). Self-contained; not stacked on #5955.
tylerslaton added a commit that referenced this pull request Jul 18, 2026
#6035)

## What

Follow-up nit from [PR
#5969](#5969) review
([OSS-488](https://linear.app/copilotkit/issue/OSS-488)). Fixes the
`getMessages` JSDoc in
`packages/channels-intelligence/src/intelligence-adapter.ts`, which
oversold image support.

The comment cited *"what was in the image"* as a `read_thread` use case,
but image/file parts contribute **no text** in this mapping —
`read_thread` is text-only by design. Image *content* reaches the model
only via `conversationStore`'s seeding of `agent.messages`. The comment
now says so explicitly instead of implying `read_thread` can see image
content.

Comment-only change — no runtime/API behavior change, so no changeset.

## Scope of OSS-488

The ticket listed three nits; this PR addresses the one still
actionable:

- **#1 (double-space when joining content parts)** — ✅ already resolved
on `main` (the `.filter(Boolean).join(" ")` fix + updated test landed
via the OSS-476 CR round). Nothing to do.
- **#2 (JSDoc oversells image support)** — ✅ **this PR**.
- **#3 (duplicate `getHistory` fetch per turn)** — intentionally
**deferred**. A per-turn memo would need turn-scoped caching with a
clear-on-turn-start hook; without one it risks serving stale history — a
correctness regression on something the ticket itself rates "acceptable
for an on-demand tool." Not worth it here.

The **known limitation** (speakers collapse to `user`/`bot` because
upstream `AgentMessage` carries no names) is unchanged and not
actionable at this layer.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
jpr5 added a commit that referenced this pull request Jul 24, 2026
…op its failure blanking the matrix

PR #6156 widened the browser's supplemental `signal` fetch from "comm-error
aggregate rows only" to "comm-error aggregates ∪ every non-green row, all
dimensions", and in doing so removed the early return that had bounded the work.
What was left was a `for(;;)` with no page cap, unprojected, awaited before any
row is returned — so it degrades exactly when the dashboard matters most.
Measured against production: nominally 357 of 3082 rows (one page, 429 KB), but
under a full-column outage the non-green set trends toward the whole collection —
7 pages, 1.73 MB — all of it on the critical path to first paint. Against a
server that never returns a short page it does not terminate at all.

Worse than slow: a supplemental rejection propagated through fetchInitial →
connect() → the retry chain → `setRows([])` + `status: "error"`. A failure of an
ENRICHMENT fetch blanked the ENTIRE dashboard, which directly contradicts the
fail-safe rationale the PR was written to establish. (It also leaked an unhandled
rejection per attempt, because the promise rejects while the bulk pages are still
in flight and nothing is awaiting it yet.)

Three changes, all on the dashboard hook:

PAGE CAP. Both initial-fetch loops now share one bounded implementation
(`fetchStatusPages`) and one cap, `MAX_INITIAL_FETCH_PAGES = 20`. Sized as a
runaway guard rather than a budget: ~3x the real collection, so it never
truncates a legitimate read including the degenerate all-non-green case. The
supplemental loop also picks up the wave-concurrency and short-page merge guards
the bulk loop already had and it did not, which is what made the parity
structural instead of a promise two comment blocks made to each other. On-cap
behavior is deliberately ASYMMETRIC: supplemental truncation DEGRADES (warn, use
what arrived — the unreached rows keep their signal-less bulk copy, which
classifyRung paints RED), while bulk truncation THROWS, because rows the bulk
never read are whole cells that would render as no-data GRAY, i.e. exactly the
masked-failure polarity this PR exists to remove.

NON-FATAL ENRICHMENT. The rejection handler is attached at the fetch site, so a
supplemental failure yields an empty row set, the merge degrades to "bulk rows,
unenriched", and the dashboard RENDERS. Reds stay red via the classifier's
fail-safe polarity; the residual cost is that a comm-error overlay on a green
aggregate waits for its next SSE delta — the pre-CF7-F3-#1 behavior for the
duration of one failed request, instead of a blank matrix. Attaching at creation
also removes the unhandled rejection.

PROJECTION. The supplemental fetch now sends `STATUS_LIST_FIELDS + signal`
instead of no projection. That is exactly the declared StatusRow shape, derived
from the drift-guarded constant so the two cannot diverge, which drops the
columns PocketBase adds and nothing reads (collectionId, collectionName, created,
updated, state_written_at, written_by): 429,085 → 362,982 bytes measured on the
real non-green set, ~260 KB at incident scale. Deliberately NOT narrower — the
merge treats a supplemental row as a COMPLETE row (replaces its bulk twin
wholesale, appends one the bulk snapshot missed), so `key,observed_at,signal`
would have saved another 58 KB by forcing a graft onto a row of a different
vintage, which is the chimera `supplementalRowIsOlder` exists to prevent.

It stays on the first-paint path. Enriching after first render would have removed
it from the critical path, but a non-green row's chip can move once its signal
lands (red → gray for a positively-infra red, red → amber for a soft-class first
strike), and a cold-load verdict that corrects itself a beat later is the class of
symptom this PR set out to eliminate. With the fetch bounded, wave-concurrent and
projected it runs inside the bulk fetch's own round-trip budget, so gating first
paint costs nothing on the happy path.

Tests are REAL-SDK over real sockets, with fake endpoints that actually evaluate
`filter`/`fields`/`sort` (new `__tests__/pb-query-eval.ts`) so a response is a
function of the query the hook sent rather than of fixture layout. Verified by
mutation: restoring the unbounded loop, the fatal rejection, or the missing
projection each turns its own test red.
BenTaylorDev pushed a commit that referenced this pull request Aug 29, 2026
…llowlist

Commits the one-off diagnostic that produced the highest-severity finding of PR
#6156's round-2 review (slot 1-A #1) as a permanent guard. The diagnostic
reconstructed both engines in scratch dirs and diffed them field-by-field; that
form depends on `origin/main` at a moment in time. This is the committable form:
the invariant plus a shape-exact allowlist, one engine, no cross-revision diff.

INV7 promoted from six fixtures to the whole domain — the 6^7 = 279,936
cross-product of the seven status rows an agent-axis cell is derived from (7
slots x {absent, green, greenStale, redFresh, redInfra, redStripped}) — asserting
that no combination renders a red depth pill under a non-committal chip unless
every contributing red row carries positive INFRA_ERROR_CLASSES attribution.
Reproduces slot 1-A's measurement exactly: 19,328 of 279,936, in the same eight
red-pill buckets (pinned separately as SLOT_1A_RED_PILL_BUCKETS).

Two tables, not one, because the residue is not one mechanism:

  - KNOWN_I1_GAP_BREAK_SHAPES (7 shapes, 17,088) — EXCUSED as invariant-I1 debt.
    `scanWorst` breaks at the first ABSENT rung, so a red above the gap is never
    folded and the chip provably never read it. Round-2 partition bucket (d4).
  - QUARANTINED_NON_GAP_MASKING (6 entries, 2,240) — NOT excused. 2,048 are a
    non-infra red D6 sitting outside `scanWorst`'s [D3,D4,D5] walk; 192 have
    their gap at or above the red. The chip read a verdict and still hid a red;
    contiguity excuses nothing here. Separate table, separate wording, separate
    follow-ups, so the I1 note cannot be read as covering them.

The gap predicate mirrors `ladderGapDepth` from cell-model.coherence.test.ts @
49bf40943f: a rung is a gap when no row exists for any of its keys (equivalent to
`classifyRung`'s ABSENT), NOT the strip's `status === null`. Keying off the strip
mis-files the 192 non-gap combinations as excused — measured, not assumed. When
both land, the shared helper should be imported and this copy deleted; the header
says so.

Two-sided by construction, and mutation-proven against the real engine:
  - a shape in no table fails ("NEW masking shape") — proven by deleting an
    entry: reported as 864 + 96 unlisted combinations;
  - an allowlisted shape that stops masking fails ("RATCHET ... OVER-BROAD"), so
    fixing the gap-break forces the table to shrink rather than leaving stale
    cover — proven by inflating an entry 2880 -> 2881;
  - a quarantined shape that stops masking fails ("QUARANTINE SHRANK") — proven
    by inflating an entry 64 -> 65.
In-suite teeth cover the same three directions, including that an emulated (d4)
fix clears all seven allowlisted shapes while leaving the quarantine intact.

Exhaustive, not sampled: the full sweep runs ~2.1 s, so no covering array is
needed. The LiveStatusMap is built once and mutated one key per step in
mixed-radix reflected Gray-code order (Knuth 7.2.1.1 Algorithm H); a control
test re-runs the whole domain rebuilding a fresh map per combination and asserts
an identical histogram. Deterministic: fixed `now` literal, pure engine, no
randomness, no I/O, no wall-clock. The domain identity is asserted too — 6^7
distinct tuples visited exactly once, every (slot, variant) pair 6^6 times, every
step a single-slot delta — so the sweep cannot silently degenerate into a subset.

Product logic is untouched: this is a new test file and nothing else.

NOTE: gates nothing until PR #6168 lands the harness/shell-dashboard unit suites
in CI (they were excluded twice over, by `paths-ignore: showcase/**` and by
`--projects='packages/**'`). Until then it is a local + cr-loop pre-audit
instrument.
BenTaylorDev added a commit that referenced this pull request Aug 29, 2026
#6466)

## Root cause

The harness's PocketBase client
(`showcase/harness/src/storage/pb-client.ts`) re-authenticated its
superuser token **only on HTTP 401**. But when the superuser/admin auth
token's ~14-day TTL expires, PocketBase does **not** return 401 — it
treats the request as an unauthenticated *guest* and returns:

```
HTTP 403 {"code":403,"message":"Only admins can perform this action.","data":{}}
```

on every write. Because 403 was never treated as an auth-expiry signal,
the expired token was never refreshed, so **all `status` writes failed
permanently** until the process restarted. `classifyWriterError` maps
403 → `pb_permission` (a terminal reason), so the failure looked like a
permission problem rather than an expired session. This is what blanked
the dashboard for ~46h.

## The fix

In `request()`, treat a 403 as the same stale-session signal as a 401 —
**but only when the request actually carried an `Authorization` header**
(`sentAuth`). A 403 on a request that sent no token is a genuine
guest-forbidden result that re-auth cannot fix, so it is left to
surface.

- The retry stays bounded by `MAX_AUTH_RETRIES` (1). A 403 that
**persists after a fresh, successful re-auth** is a real permission
error and falls through to the caller (still classified `pb_permission`)
— never an infinite re-auth loop.
- No change to the 401 path, the retry envelope, or any other status
class.

```
(res.status === 401 || (res.status === 403 && sentAuth)) &&
authRetries < MAX_AUTH_RETRIES && attempts < maxAttempts
```

## Local red-green proof (real PocketBase, real client — not a fake)

Stood up a live **PocketBase v0.22.21** (the pinned version) locally,
created an admin + a superuser-gated `status` collection, and set
`adminAuthToken.duration = 5` (5s — the server's minimum). A temporary
driver drove the **real `createPbClient`** against it: write #1 caches a
token, sleep 6.5s so the cached token **genuinely expires**, then write
#2.

First confirmed the raw failure surface — an expired admin token on a
write:

```
EXPIRED-token write status + body:
{"code":403,"message":"Only admins can perform this action.","data":{}}
HTTP 403
```

### RED (unmodified code)

```
[driver] write#1 OK id=setjh0ca1s09s14 — token now cached
[driver] sleeping 6.5s for the cached admin token to expire...
CVDIAG component=pb-client:create:status ... status=error error=status=403 {"code":403,"message":"Only admins can perform this action.","data":{}}
[driver] RED: write#2 FAILED after expiry: Error: pb create failed: 403 {"code":403,"message":"Only admins can perform this action.","data":{}}
EXIT=1
```

The expired token 403s, **no re-auth occurs**, the write stays failed.

### GREEN (with this fix)

```
[driver] write#1 OK id=tkl59dt5d3xt11g — token now cached
[driver] sleeping 6.5s for the cached admin token to expire...
[driver] GREEN: write#2 SUCCEEDED after expiry id=uns9y2dgysynpwz
EXIT=0
```

Same repro, same expired token: the 403 now triggers re-auth, the write
is retried once and **succeeds**.

## Regression tests

Added three tests to `pb-client.test.ts`:

1. `re-auths on 403 (expired superuser token treated as guest) then
retries the write` — 403-with-token → re-auth → retry succeeds (2 auths,
2 writes).
2. `caps 403 re-auth at 1 — a 403 that persists after a fresh auth
surfaces (no infinite loop)` — bounded; the persistent 403 surfaces (2
auths, 2 writes, then throws).
3. `does NOT re-auth on 403 when no credentials were sent (genuine
guest-forbidden)` — no token → no re-auth, no retry (0 auths, 1 write).

**Mutation check:** reverting the fix (403 branch removed) makes tests 1
and 2 fail while test 3 still passes — the tests are structurally able
to detect the fix.

## Code-review hardening (Tier-3 cr-loop)

A full-breadth review of the re-auth branch surfaced two additional
load-bearing issues in the exact code this PR modifies; both fixed here
with their own red-green + individual mutation checks:

- **Drain the response body on the re-auth path.** The 401/403 re-auth
branch did `continue` without draining the prior failed response —
unlike the 429/5xx branches, which call `drainBody()` — leaking a
half-consumed socket on every token refresh (F2.3 socket-reuse
discipline). `drainBody` was hoisted above the branch and invoked before
the retry.
- RED: `failed401.bodyUsed` = `false` (undrained). GREEN: body drained
after the fix.
- **Bound the re-auth gate by `attempts < maxAttempts`.** The re-auth
gate checked only `authRetries`, not `attempts` (the 429/5xx gates check
both), so a token expiring on the final attempt could fire a 4th
`fetchImpl`, exceeding the documented `maxAttempts = 3` envelope. Added
the guard for consistency.
- RED: `expected 4 to be 3` (4th fetch fired). GREEN: `writeCount ===
3`.

Full `pb-client.test.ts` suite: **35 passed**. CI green.

## Follow-ups (out of scope for this PR — pre-existing, tracked
separately)

The review confirmed the fix is sound and found no defect in it, but
flagged pre-existing issues in the same file that predate this change
and belong in their own PRs:

- **Observability regression (HF13-B1):** `create()`'s CVDIAG "every
record write failure is greppable" log is unreachable for
retry-exhausted 429/5xx writes, because `request()` now throws
`PbHttpError` before `create()`'s `!res.ok` block runs. (403 writes are
unaffected — they reach the log.)
- **Auth re-auth stampede:** `ensureAuth()` has no single-flight guard,
so at token expiry every concurrent writer re-auths independently.
Fixing this (coalesce concurrent re-auths behind one shared in-flight
promise) benefits both the 401 and 403 paths.
- **401 `sentAuth` symmetry (trivial):** the 401 re-auth path lacks the
`sentAuth` guard the new 403 path has, wasting one bounded attempt when
no credentials are configured.
- **`deleteByFilter` off-by-one:** the iteration cap throws on a
fully-successful delete of exactly a multiple-of-200 ≥ 20000 rows.
- **Inert `RETRY_AFTER_MAX_MS` cap + its mutation-blind test.**
zeekay pushed a commit to Dream-AI-4444/CopilotKit that referenced this pull request Sep 11, 2026
## Summary

Production `showcase-crewai-crews` was stuck at `agent:"down"` for ~4-5h
on 2026-04-21 (retries CopilotKit#1-8, 503 on `/api/health`, 30s+ hang on
`/api/smoke`). Railway runtime logs show the FastAPI agent on `:8000`
handled startup and hundreds of requests cleanly, then silently
**stopped responding** at ~06:56-07:01 UTC after an `unhandledRejection:
UND_ERR_BODY_TIMEOUT`. The Python process did not exit — it hung — so
bash's `wait -n` never fired, the container never restarted, and every
subsequent runtime-to-agent request waited out undici's default 5-minute
headers timeout (`UND_ERR_HEADERS_TIMEOUT` in the logs).

Two defensive fixes in the package:

1. **`entrypoint.sh` — agent watchdog.** Poll
`http://127.0.0.1:8000/health` every 30s (5s `curl --max-time`). After 3
consecutive failures (~90s unreachable), SIGKILL the agent PID so `wait
-n` returns and Railway restarts the container. Also adds `[entrypoint]`
/ `[agent]` / `[nextjs]` / `[watchdog]` log prefixes, a startup
PID-is-alive check, and `PYTHONUNBUFFERED=1` — bringing this package's
entrypoint closer to the starter's richer template.

2. **`src/app/api/smoke/route.ts` — split inner/outer timeouts.**
`UPSTREAM_TIMEOUT_MS = 25_000` on the inner fetch, keeping `maxDuration
= 60` as the route budget. Previously the single
`AbortSignal.timeout(45000)` on the upstream fetch, when the agent hung,
consumed nearly all the 60s envelope before Next.js cut the request —
producing HTTP 000 at the caller. Now a wedged agent surfaces as a
structured `stage: "timeout"` JSON response in ~25s.

Upstream `showcase-crewai-crews-production.up.railway.app` verified RED
(503, agent:down) via `curl` before this PR. Merge will trigger GHCR
build + Railway redeploy; recovery expected within ~4 min of deploy.

## Test plan

- [ ] Railway deploys latest image after merge; container boots healthy
- [ ] `curl
https://showcase-crewai-crews-production.up.railway.app/api/health`
returns 200 `agent:"ok"`
- [ ] `curl
https://showcase-crewai-crews-production.up.railway.app/api/smoke`
returns 200 within ~25s (or 502 `stage:"timeout"` if aimock glitches)
- [ ] Logs show `[entrypoint]` / `[agent]` / `[watchdog]` prefixes
(evidence the new entrypoint is active)
- [ ] Induce hang by sending a malformed agent request; verify watchdog
kicks in after ~90s (visible in logs as `[watchdog] Agent health probe
failed` + container restart)
- [ ] Starter service (`showcase-starter-crewai-crews`) unaffected —
only the package entrypoint/smoke route changed
zeekay pushed a commit to Dream-AI-4444/CopilotKit that referenced this pull request Sep 11, 2026
…opilotKit#4155)

## Summary

Showcase demos (e.g. gen-ui-tool-based's "Traffic pie chart", Beautiful
Chat's pie/bar-chart suggestions) were rendering nothing in prod because
aimock's substring-match fixtures cross-fired across demos with
different tool surfaces, returning tool names the target agent never
registered. This PR narrows the fixture patterns to fix the immediate
breakage and adds a static validator so the same class of drift fails CI
before it reaches prod.

## What broke

Aimock serves deterministic responses in prod for cost reasons. Fixtures
substring-match the user message and return hardcoded tool calls. The
`"pie chart"` pattern returned `query_data` (for Beautiful Chat's
two-step flow where it has that tool), but the same substring also fires
for gen-ui-tool-based's suggestions — which only registers
`render_pie_chart`. The returned `query_data` call dangles, no UI
renders.

Beautiful Chat also looped on the same fixture: aimock has no
conversation-turn awareness, so after `query_data` returned its tool
result, the follow-up model call had the same user-message context and
the fixture re-matched, emitting `query_data` again — infinite until
LangGraph's iteration cap.

Exposed by PR CopilotKit#4113 (showcase-ops) / the prod-mode migration cluster
that started routing prod traffic through aimock. The fixtures
themselves had been incrementally drifting for a while, but the routing
change turned silent drift into user-visible breakage across many demos
simultaneously.

## Fix CopilotKit#1 — narrow the fixture patterns

`showcase/aimock/feature-parity.json`:

- Replaced the generic `"pie chart"` / `"bar chart"` / `"show pie"` /
`"show bar"` patterns with **6 per-suggestion specific-phrase matches**.
gen-ui-tool-based and declarative-gen-ui get `render_pie_chart` /
`render_bar_chart` directly; Beautiful Chat gets `pieChart` / `barChart`
with real data (skipping the query_data loop).
- Narrowed `"schedule"` + `"meeting"` into one match for Beautiful
Chat's "30-minute meeting to learn about CopilotKit" → `scheduleTime`.
- Narrowed `"flight"` / `"fly"` to `"flights from SFO to JFK"`.
- Narrowed `"background"` to `"sunset-themed gradient"`.
- Removed `"trip"`, `"sales"`, `"pipeline"`, `"todo"` — too generic,
substring-false-firing across unrelated demos. Interrupt and A2UI demos
with those prompts fall through to the real LLM proxy.

## Fix CopilotKit#2 — static drift guardrail

New `showcase/scripts/validate-fixture-tool-surface.ts`:

- Pure `validate()` function: for each fixture with tool-call responses,
finds every demo whose suggestion prompt contains the fixture's match
substring, then asserts the fixture's returned tool names are all
registered by that demo's agent.
- CLI walks `packages/*/` collecting:
  - suggestions from `page.tsx` + sibling `hooks/*.tsx`
- frontend tools from `useComponent` / `useHumanInTheLoop` /
`useFrontendTool` / `useRenderTool` / `useDefaultRenderTool` calls
- backend tools via `api/copilotkit*/route.ts` → agentId→graphId map →
`langgraph.json` graph→Python-file → `@tool` decorators + `tools=[...]`
arrays
- 7 vitest cases written TDD-first (watched fail, then implemented)
covering: drift detection, content-only fixtures, no-matching-demo,
case-insensitivity, multi-demo cross-check, multi-tool responses.

Runs as `npx tsx showcase/scripts/validate-fixture-tool-surface.ts`.
Exit 0 = clean; exit 1 = per-fixture drift report.

Current state: **33 fixtures × 191 demos, no drift.**

Counterfactual: reverting just the pie-chart fixture fix correctly flags
`langgraph-python/gen-ui-tool-based` and
`langgraph-python/declarative-gen-ui` — i.e. the exact demos that broke
in prod.

## Also fixed — unrelated LangGraph Python Dockerfile bug

`showcase/packages/langgraph-python/Dockerfile`: `WORKDIR /app` left
`/app` owned by root; the explicit `--chown=app:app` on COPY lines
chowned *contents* but not the directory itself, so the `app` user
couldn't create `.langgraph_api` (the in-memory LangGraph runtime's
cache dir) and the agent crashed on boot with `PermissionError: [Errno
13]`. Added a non-recursive `chown app:app /app` (preserves the perf
intent of not doing a recursive chown).

## Known follow-ups (out of scope for this PR)

- Interrupt demos (`gen-ui-interrupt`, `interrupt-headless`,
`hitl-in-chat`) and A2UI demos (`declarative-gen-ui`,
`a2ui-fixed-schema`, `mcp-apps`, Calculator App) currently fall through
to the real LLM when unmatched. Faithful fakes would need per-agent
fixture keying in the aimock engine — separate upstream change.
- Python backend-tool parser uses regex; misses star-spread collections
like `tools=[query_data, *todo_tools]`. Safe failure mode — missing
tools surface as guardrail drift rather than silently pass.
- Add this validator to `.github/workflows/showcase_*.yml` so CI runs it
on every PR touching fixtures or demos.

## Test plan

- [x] `npx vitest run
showcase/scripts/__tests__/validate-fixture-tool-surface.test.ts` — 7/7
pass
- [x] `npx vitest run
showcase/scripts/__tests__/aimock-fixtures.test.ts` — 17/17 still pass
(no regression)
- [x] `npx tsx showcase/scripts/validate-fixture-tool-surface.ts` — 33
fixtures × 191 demos, 0 drift
- [x] Counterfactual: revert fixture fix, validator flags
gen-ui-tool-based + declarative-gen-ui exactly
- [x] Direct aimock probe (localhost:4010) for all 8 fixed prompts →
returns correct tool call
- [x] End-to-end through local LangGraph agent (localhost:3100) →
gen-ui-tool-based "Traffic pie chart" suggestion → `render_pie_chart`
with real data
- [ ] Merge → Railway redeploys aimock + langgraph-python → smoke cycle
on Beautiful Chat + gen-ui-tool-based + declarative-gen-ui suggestions
jpr5 added a commit that referenced this pull request Sep 15, 2026
…ke @chat able to fail (#7143)

> **Expect red `smoke-starter-production-image` slots on this PR, and
that is the point.** This PR touches the workflow and
`showcase/tests/**`, so the gate runs all 12 starters. It will be red
for `strands-python` (fixed by #7136), `langgraph-python` /
`langgraph-js` / `langgraph-fastapi` (#7138, and fastapi/python also hit
the `ag-ui-langgraph` pin bug noted at the bottom) and `llamaindex`
(#7139) — the starters that are broken in production **right now** while
`smoke-starter` is green on all of them. The reds are the gate working.

## Problem

Three starter fixes landed today (#7136 strands, #7138 langgraph trio,
#7139 llamaindex). All three found **green CI on genuinely broken
code**, by three different mechanisms. Only the third is about the test;
the first two are about the artifact.

**1 & 2 — CI never builds what production runs.**

`showcase_build.yml` → `build-starters` publishes:

```
context: examples/integrations/${{ matrix.starter.slug }}
file:    examples/integrations/${{ matrix.starter.slug }}/Dockerfile
tags:    ghcr.io/copilotkit/starter-<slug>:<sha>
```

That **root** `Dockerfile` — one container, its own `entrypoint.sh`
starting the Next.js server and the agent sidecar, its own
`docker-route-override.ts` swap — is what the Railway starter services
pull.

The only pre-merge gate, `smoke-starter`, runs each starter's
`docker-compose.test.yml`, which builds `docker/Dockerfile.app` +
`docker/Dockerfile.agent` into a **two**-container stack and injects
`AGENT_URL` / `LANGGRAPH_DEPLOYMENT_URL` from compose. **Nothing in CI
ever built the root Dockerfile**, and `build-starters` itself only runs
on `push: main`, so even the build was post-merge-only.

The masking is structural, not incidental — compose supplies the exact
value whose absence was the strands bug, and builds the unmodified
`[[...slug]]` route the langgraph Dockerfile deletes.

**3 — the `@chat` assertion cannot tell success from failure.**
`sendChatMessage` swallowed its 60s `waitForFunction` timeout in a bare
`catch {}`, and CopilotKit renders a `RUN_ERROR` as an assistant message
— so `gotResponse && responseText.length > 0` is satisfied by a run that
failed outright. llamaindex rode that through 1345 consecutive failed
probe runs. The only tell was `@chat` taking 1.1 minutes instead of ~1
second.

## Divergences found (all 14 starter dirs inspected firsthand)

| | Divergence | Consequence |
|---|---|---|
| D1 | Different Dockerfiles: prod `<slug>/Dockerfile` vs CI
`<slug>/docker/Dockerfile.app`. Different bases
(`python:3.12.10-slim`+node vs `node:22-alpine`), different pins,
different build flags (`next build --webpack` vs `next build`). | The
whole prod build path is ungated. `langgraph-python`/`langgraph-js`
currently cannot build their prod image at all (npm EOVERRIDE) with
`smoke-starter` green. |
| D2 | Different topology: prod = 1 container + `entrypoint.sh`; CI = 2
containers on a compose network. | `entrypoint.sh` never runs in CI —
the strands bug (#7136). |
| D3 | CI **injects** `AGENT_URL` / `LANGGRAPH_DEPLOYMENT_URL`; prod
relies on defaults baked into the override/entrypoint. | CI supplies the
value whose absence is the bug. |
| D4 | The route override exists only in the prod Dockerfile. | The
langgraph 404 (#7138) is invisible to CI by construction. |
| D5 | `smoke-starter` runs 14 slugs, `build-starters` publishes 12.
`crewai-flows` (no root Dockerfile) and `strands-typescript` are tested
but never shipped. | Nothing to gate for those two. |
| D6 | `build-starters` is `push: main` only, not a PR check. | A
prod-image build break merges freely. |
| D7 | Assertion blindness (above). | Right artifact, wrong verdict. |
| D8 | Latent, not fixed: `langgraph-fastapi`/`strands-python`
`entrypoint.sh` both print `"Starting: langgraph-python starter"`, and
their compose default is `STARTER=${STARTER:-langgraph-python}`. |
Harmless in CI (the workflow sets `STARTER`), misleading locally. |

## Fix

**`examples/integrations/docker-compose.production-image.yml`** — one
`$STARTER`-parameterised stack (aimock + the **root Dockerfile** image +
the existing `starter-smoke` spec). One file, not 12, so it cannot drift
per starter. Nothing is injected that the Railway service does not also
get.

**`examples/integrations/production-image-gate.sh`** — the
tests-container entrypoint (readiness poll, then playwright). In a file
because Compose shell-word-splits a multi-line `command:` string into
argv.

**`.github/workflows/test_smoke-starter.yml`** — new
`detect-production-starters` + `smoke-starter-production-image` jobs. A
first step greps `showcase_build.yml` for `file:
examples/integrations/.*/Dockerfile` and fails loudly if that path ever
moves, so the divergence cannot silently reopen.

Not build-only: the gate asserts `@health`, `@agent` (incl.
`/api/copilotkit/info`), `@chat` (a real AG-UI round-trip against
aimock) and `@interaction`. The langgraph bug builds clean and 404s at
runtime.

**`showcase/tests/e2e/helpers.ts` + `starter-smoke.spec.ts`** —
`sendChatMessage` now captures the `/api/copilotkit` SSE transcript off
the wire and returns `agui: { runFinished, runError, sawTextDelta,
timedOut, transcriptBytes }`. The timeout is recorded instead of
swallowed; the drain is bounded at 15s so a mid-stream hang yields a
real assertion failure. `@chat` now requires a terminal `RUN_FINISHED`,
no `RUN_ERROR`, no timeout, and — for prose-answering starters;
strands-typescript answers with an A2UI render — at least one non-empty
`TEXT_MESSAGE_CONTENT` delta. `integration-smoke.spec.ts` reads only
`gotResponse`/`responseText` and is unaffected.

## Scope — what is and is NOT gated

- **Gated on PRs:** only starters whose own
`examples/integrations/<slug>/**` changed; all 12 when the workflow,
compose file, gate script, or `showcase/tests/**` change. Each slot is a
full Next.js + Python/.NET image build (~10-15 min), so all-12-per-PR
would add hours to every starter PR.
- **NOT gated on PRs:** a starter broken from outside its own directory
(`packages/**`, a floating transitive dep, an upstream release). The
existing 6h `schedule` and post-release `workflow_run` triggers run
**all 12** and cover exactly that.
- **NOT covered at all:** `crewai-flows`, `strands-typescript` —
`build-starters` publishes no image for them.
- A reduced or empty matrix is printed with `::notice::`. Coverage is
never silently dropped.

## Red / green

All runs: real `docker compose` on `origin/main` d9bec20, `--builder
desktop-linux`, aimock offline.

### A. Artifact divergence — same starter, same commit, two gates

`langgraph-fastapi`, unmodified main:

```
# EXISTING gate (docker/Dockerfile.app two-container stack)
$ STARTER=langgraph-fastapi docker compose -f docker-compose.test.yml up --build \
    --abort-on-container-exit --exit-code-from tests
  ✓  4 @agent langgraph-fastapi — agent endpoint is reachable (94ms)
  ✓  2 @health langgraph-fastapi — health endpoint responds (138ms)
  ✓  3 @Interaction langgraph-fastapi — UI interactions work (3.3s)
  ✓  1 @chat langgraph-fastapi — chat round-trip via aimock (1.1m)
  4 passed (1.2m)
EXIT=0                      <-- GREEN, while production 404s

# NEW gate (root Dockerfile, same commit, same spec)
$ STARTER=langgraph-fastapi docker compose -f docker-compose.production-image.yml up --build \
    --abort-on-container-exit --exit-code-from tests
  ✓  2 @health ... (102ms)
  ✘  1 @agent langgraph-fastapi — agent endpoint is reachable (108ms)
  ✘  3 @Interaction langgraph-fastapi — UI interactions work (3.0s)
  [console.error] [CopilotKit] Error (runtime_info_fetch_failed): Runtime info request failed with status 404
  2 failed / 2 passed
EXIT=1                      <-- RED on the real bug (red in prod since 2026-06-04)
```

With #7138's Dockerfile fix applied, `@agent` and `@interaction` flip ✓
— the gate tracks the fix, it is not red on everything.

### B. Assertion blindness — llamaindex, the full 2×2

Pre-fix `llamaindex` ignores `OPENAI_BASE_URL` (LlamaIndex reads
`OPENAI_API_BASE`), dials api.openai.com with the aimock key and gets
`openai.AuthenticationError: 401 Incorrect API key provided:
test-key*******mock`. **The production image is built and exercised
correctly in every cell below — only the assertion differs.**

```
# NEW gate, OLD assertions, pre-fix llamaindex
  ✓ @health (165ms)  ✓ @agent (352ms)  ✓ @Interaction (969ms)
  ✓ @chat llamaindex — chat round-trip via aimock (1.1m)
  4 passed (1.2m)   EXIT=0      <-- GREEN on an agent that 401s

# NEW gate, HARDENED assertions, pre-fix llamaindex
  ✓ @health (72ms)  ✓ @agent (374ms)  ✓ @Interaction (1.0s)
  ✘ @chat llamaindex — chat round-trip via aimock (1.1m)
  ✘ @chat llamaindex — chat round-trip via aimock (retry #1) (1.1m)
  1 failed / 3 passed (2.3m)   EXIT=1      <-- RED

# NEW gate, HARDENED assertions, + PR #7139
  ✓ @health (41ms)  ✓ @agent (336ms)  ✓ @Interaction (981ms)
  ✓ @chat llamaindex — chat round-trip via aimock (1.3s)
  4 passed (7.8s)   EXIT=0      <-- GREEN
```

| llamaindex, production image | OLD assertions | HARDENED assertions |
|---|---|---|
| pre-fix (main) | 4 passed, exit 0, `@chat` **1.1m** | **1 failed, exit
1** |
| + PR #7139 | — | 4 passed, exit 0, `@chat` **1.3s** |

1.1 min → 1.3 s. The `1.1m` on a *passing* `@chat` is the tell-tale.

The same flip reproduces on `langgraph-fastapi` **with #7138 applied**,
where the agent 500s on `LangGraphAGUIAgent.__init__() got an unexpected
keyword argument 'enable_legacy_on_interrupt_event'`: old assertions `✓
@chat (1.1m)` → 4 passed / exit 0; hardened assertions `✘ @chat (1.1m)`
→ exit 1.

### C-live. Both gates, same commit, same CI run

| starter | `smoke-starter` (today's gate) |
`smoke-starter-production-image` (this PR) |
|---|---|---|
| langgraph-python | **pass** | **FAIL** |
| langgraph-js | **pass** | **FAIL** |
| adk | pass | pass |
| agno | pass | pass |
| mastra | pass | pass |
| ms-agent-framework-python | pass | pass |
| pydantic-ai | pass | pass |

Five starters agree, two disagree — and the two that disagree are
exactly the
ones whose published production image cannot be built. That is the whole
thesis
of this PR, rendered as a check list.

### C-pre. The gate failing on a real GitHub runner

`smoke-starter-production-image (langgraph-python)` and `(langgraph-js)`
on this PR:

```
#28 0.887 npm error code EOVERRIDE
#28 0.887 npm error Override for @ag-ui/client@* conflicts with direct dependency
Dockerfile:19
failed to solve: process "/bin/sh -c npm install @ag-ui/client" did not complete successfully: exit code: 1
```

The image `build-starters` publishes to GHCR **cannot build at all**
(fixed by
#7138), while `smoke-starter (langgraph-python)` is green on the same
commit
because it builds `docker/Dockerfile.app`. The divergence, observed in
CI rather
than argued.

### C. No false positives

`mastra` production image, unmodified main, both assertion sets:

```
  ✓ @agent (51ms)  ✓ @health (70ms)  ✓ @Interaction (807ms)  ✓ @chat (947ms)
  4 passed (7.7s)   EXIT=0
```

### D. Matrix logic

Table-tested in a real bash script (a jq scoping bug — `$changes |
index(.)` rebinds `.` to `$changes`, silently matching everything — was
caught and fixed this way):

```
pull_request / ["llamaindex"]            -> ["llamaindex"]
pull_request / ["adk","agno"]            -> ["adk","agno"]
pull_request / ["workflow_config","adk"] -> all 12
pull_request / ["crewai-flows"]          -> []        (not a deployed starter)
pull_request / []                        -> []
schedule     / <none>                    -> all 12
```

`actionlint` and `shellcheck` clean; `prettier --check` clean.

## What the hardened `@chat` exposed in the EXISTING gate

Making `@chat` able to fail turned three `smoke-starter` slots red that
have always been green. Two are true positives it was hiding:

- **`smoke-starter (langgraph-fastapi)`** — `Agent execution failed:
TypeError: fetch failed / code: 'ECONNREFUSED'`. The app never reaches
its agent, so that chat has **never** worked. The old assertion passed
it in 1.1m, in CI and locally.
- **`smoke-starter (llamaindex)`** — the 401-against-api.openai.com bug
(#7139), present in the two-container stack too.
- **`smoke-starter (ms-agent-framework-dotnet)`** — `@chat` 1.1m ×2 with
**no agent-side error in the log**, only the 60s DOM wait blowing its
deadline.

Because the dotnet case could not be pinned to a real failure, the
standalone `timedOut` gate was **demoted to a diagnostic**. Waiting on
the `copilot-assistant-message` testid is a rendering detail, not the
contract — the helper has always carried a fallback path precisely
because some shells render the reply without it. The protocol assertions
remain the gate, and a genuine hang still fails because a hung run never
reaches `RUN_FINISHED`. All five `agui` values are printed in every
failure message.

Verified the demotion does not make the gate decorative — pre-fix
llamaindex on the production image still fails, now on the protocol
rather than the DOM:

```
Error: AG-UI stream contained a RUN_ERROR
  [agui runFinished=false runError=true sawTextDelta=false timedOut=true transcriptBytes=1726]
1 failed / 3 passed (2.3m)
```

## Follow-ups (not in this PR)

- `langgraph-fastapi` and `langgraph-python` production images still
cannot complete a chat even with #7138: the root Dockerfile's
`ag-ui-langgraph==0.0.43` + `copilotkit==0.1.96` pins raise
`LangGraphAGUIAgent.__init__() got an unexpected keyword argument
'enable_legacy_on_interrupt_event'` → HTTP 500 on every run. **This gate
will be red for those two until it is fixed — correctly so.**
- `smoke-starter (langgraph-fastapi)`'s two-container stack cannot reach
its agent (`ECONNREFUSED`) — a separate bug from the production-image
ones, newly visible now that `@chat` can fail.
- `crewai-flows` has no root Dockerfile and `strands-typescript` is not
in `build-starters`, yet both are in the `smoke-starter` matrix.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01ErcmeS9SFqc9ggEz5Rjpwp


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Tests**
* Added automated smoke testing for published starter production images.
* Production builds are checked for successful startup, configuration,
and basic browser functionality.
* Chat smoke tests now verify protocol completion, streamed text, and
absence of reported errors.
* Test diagnostics capture protocol activity and container logs to
simplify failure investigation.

* **Chores**
* Smoke tests run automatically for relevant showcase changes and
release-related workflows.
  * Scheduled and post-release test failures can trigger alerts.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---

> **Merge order: this PR must land LAST.** Its new
`smoke-starter-production-image` job is legitimately red until **#7145**
(the consolidated starter production fixes — formerly #7136 / #7138 /
#7139 / #7140 / #7141 / #7144) is merged. That is the point: this gate
is what would have caught those defects. Merge #7145 first, then re-run
this PR's checks.
JadeCong pushed a commit to CloudEngineHub/CopilotKit that referenced this pull request Oct 10, 2026
…-time review

Addresses 5 Important review findings on the Task 5 commit plus 2
controller rulings.

1. CopilotChat.tsx's run-activity effect listed `copilotkit.headers` in
   its deps. A builder's snapshot object churns on every resolve, so a
   run followed by any re-render tore down and rebuilt the standalone
   run-activity store's subscription for no reason (extra
   setContext/stop/start, and a detachActiveRun when wake-reconnect was
   active). Fixed to `copilotkit.ɵheadersGeneration`, matching
   use-threads.tsx's existing pattern.

   Controller ruling: `HeaderSourceResolver.accept()` (core) now keeps
   the previous snapshot object when a resolve's normalized result is
   shallow-equal to it (same keys, same values), so `core.headers`
   only gets a new reference when a header value actually changed --
   this is what makes headers-as-a-dep safe anywhere in react-core/vue/
   angular, not just in the one call site fixed above.

2. The 20-rerenders memo-stability test had no `publicApiKey`, so
   `ɵwithHeaderDefaults`'s empty-defaults passthrough masked a
   deps-only mutation (adding `headersProp` to the deps without
   touching the factory). Added a `publicApiKey` row: with real
   defaults present, `ɵwithHeaderDefaults` wraps in a NEW closure on
   every call, so a deps-only "obvious fix" now genuinely breaks it.

3. The R3 annotation test was circular: the mock had no
   `copilotkit.headers` snapshot, and the mock `ɵruntimeFetch` wrote
   its header AFTER spreading `init.headers`, so a reintroduced stale
   spread would have been silently overwritten either way. Rewrote it
   to give the mock a snapshot with a key the current source cannot
   produce, and assert that key is ABSENT from the sent request (the
   mock no longer masks a regression). Added the missing
   use-learning-containers coverage: both Effect 1's mount emit and
   Effect 2's cleanup/reset emit now have their own snapshot-absence
   test.

4. StrictMode rows only asserted `/info` called once. Added: the
   connection actually reaches Connected, the `/info` request's
   Authorization matches the builder's resolved value (including the
   async row), a `connect()` spy proving the mount effect really
   double-invoked (2 calls), a 4th row (inline builder + publicApiKey),
   and a 50ms (not 30ms) settle window.

5. Controller ruling: `headersRef.current = headersProp` is now
   assigned during render, not inside a passive `useEffect`. React
   fires a child's effects before its parent's own effects
   (bottom-up); if only the provider's effect updated the ref, a child
   effect that fires a request in the SAME commit as a new builder
   closure would still read the previous commit's closure. Verified
   with a plain (non-proxied) HttpAgent -- deliberately NOT wrapped
   with `ɵruntimeFetch`, so `prepareAgentHeadersForRun`'s one
   synchronous resolution is the only place the token can land, with
   no send-time safety net to mask the race.

Mutation checks (all restored after confirming failure):
- CopilotKit#1: CopilotChat.tsx dep reverted to `copilotkit.headers` -> new
  run-activity test failed (3 unwanted setContext/start/stop calls
  instead of 0).
- CopilotKit#1 (core ruling): `accept()` reverted to always replace the
  snapshot -> both new core-header-source tests failed (`toBe` on
  object identity).
- CopilotKit#2: `headersProp` added to the deps array only (factory untouched)
  -> the "with publicApiKey" row failed (20 setHeaders calls); the
  "no publicApiKey" row still passed, exactly as the review predicted.
- CopilotKit#3: put `copilotkit.headers ?? {}` back in use-learn-from-user-action
  and in both use-learning-containers effects -> all three new
  snapshot-absence tests failed.
- CopilotKit#4: commented out `copilotkit.connect()` in the reconnect effect ->
  all 4 StrictMode rows failed on the new Connected-status assertion.
  (A `setHeaders({})` or `setRuntimeUrl` toggle in the effect's own
  cleanup, as the review suggested by example, does NOT reproduce a
  failure here: the effect's setup unconditionally re-applies every
  setter before calling `connect()` again on the second StrictMode
  invoke, so anything a mutation confined to cleanup changes gets
  healed by the very next setup pass. Documented so a future pass
  doesn't re-attempt the same example expecting it to fail.)
- CopilotKit#5: moved `headersRef.current = headersProp` back into a passive
  `useEffect` -> the new same-commit test failed (`agent.headers`
  carried the stale "Bearer tok-1" instead of "Bearer tok-2").

Verification:
- `NX_NO_CLOUD=true pnpm nx run @copilotkit/react-core:test --skip-nx-cache`
  -> 159 files / 1747 tests, all green.
- `NX_NO_CLOUD=true pnpm nx run @copilotkit/core:test --skip-nx-cache`
  -> 81 files / 1002 tests, all green.
- `NX_NO_CLOUD=true pnpm nx run @copilotkit/core:check-types --skip-nx-cache`
  and `NX_NO_CLOUD=true pnpm nx run @copilotkit/react-core:check-types --skip-nx-cache`
  -> both clean.
- Core dist rebuilt (`nx run @copilotkit/core:build --skip-nx-cache`)
  after the header-source.ts change, before re-running react-core.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

1 participant