Architecture
The console is a thin client on top of two backend services. It owns no state of its own — the playground holds scenario definitions and run history, the control plane holds the agent registry, sessions, audit log, trust config, and webhook subscriptions. The console's job is to render that state and let humans drive workflows against it.
This doc is about the console's shape: topology, the BFF proxy, layering, SSE, and data flow. For what each screen does, see FEATURES.md; for the code conventions that follow from this structure, see CONVENTIONS.md.
Topology
┌──────────────────────────────────────────────────────────────┐
│ Browser (single-page, client components) │
│ │
│ TanStack Query ──┐ │
│ │ fetch() │
│ useSse ──────────┤ (only /api/* — never the upstreams) │
│ │ │
└────────────────────┼─────────────────────────────────────────┘
▼
┌──────────────────────────────────────────────────────────────┐
│ Console — Next.js 16 app on :3001 │
│ │
│ src/app/api/playground/** src/app/api/cp/** │
│ │ │ │
│ ▼ ▼ │
│ proxyGet/Post/Sse(...) proxyGet/Post/Sse(...) │
│ adds Auth header adds Auth header │
│ forwards body forwards body │
│ streams SSE streams SSE │
└────────┬────────────────────────────────┬───────────────────┘
│ │
▼ ▼
┌─────────────────────┐ ┌──────────────────────────┐
│ aitp-playground │ │ aitp-cp │
│ FastAPI on :8000 │ │ Next.js on :4000 │
│ Scenarios, runs, │ │ Registry, sessions, │
│ live SSE timeline │ │ audit, dashboard, │
│ │ │ trust, webhooks │
└─────────────────────┘ └──────────────────────────┘Why a BFF proxy
Two reasons:
-
Credentials never reach the browser.
PLAYGROUND_API_KEYandCP_API_KEY(if set) are read inside the route handlers undersrc/app/api/{playground,cp}/**— both runtime values stay on the server, only the request payload crosses to the browser. -
The browser only sees one origin. No CORS dance, no preflight storms. Everything is same-origin
fetch('/api/...')and the proxy re-issues the request to the appropriate upstream.
The cost is one extra hop and a text → string → Response re-pack on
every request. That tradeoff is documented in src/lib/api/proxy.ts.
Every console route's upstream mapping lives in PROXIES.md.
What the BFF verifies
The two routes serving signed manifests (well-known/aitp-manifest and
the per-agent manifest route) do more than hide credentials — they run the artifact through the aitp SDK
server-side before the browser ever sees it, and attach the result as
_verification (see PROXIES.md).
This is deliberately server-side, never client-side: the browser is where
an attacker who can serve the page can also serve a verifier that always
returns true, and the native addon that does the actual check cannot ship
to a client bundle anyway.
This is the console's one exception to "the BFF is credential-hiding and
CORS-avoiding only, no business logic." Rendering a value copied out of an
unauthenticated fetch as though it had been checked is a defect, not a
layering purity question — see plans/cp-signed-artifact-verification.md
(local, not tracked in this repo) for the fuller argument. Both routes
verify a signature directly (verifyManifestJson).
There is no revocation list to verify here. The CP is a registry and relay
for revocations: it records entries per issuer and each issuing agent pulls
its own (GET /api/revocations?iss=<aid>), signs them and serves its own
list (RFC-AITP-0008
§1.5). Verifiers fetch that list from the issuer, never from the CP or this
console. The console only shows the CP's entries, grouped by issuer.
Operator login and Origin check
src/proxy.ts (renamed from middleware.ts in Next 16) runs on every
route except build assets, and applies three checks in order:
- Fail closed. If
CONSOLE_PASSWORDorCONSOLE_SESSION_SECRETis unset, every route returns 503console not configured. - Authentication. Every route except
/loginneeds either the session cookie thatPOST /loginissues or HTTP Basic with the operator password (any username; for scripts). API routes answer 401; pages redirect to/login?next=…. The cookie (__Host-aitp-console-session) is HttpOnly, Secure, SameSite=Strict, host-only and lasts 12 hours. It is HMAC-SHA256-signed withCONSOLE_SESSION_SECRETvia Web Crypto (src/lib/auth/session.ts), so rotating the secret signs everyone out.POST /loginis rate-limited to 10 attempts per IP per minute (in memory, per instance). - Origin on mutations. POST/PUT/PATCH/DELETE (including
/loginand/logout) must carry anOriginequal to this deployment's origin or listed inTRUSTED_ORIGINS. A missing ornullOrigin is rejected with 403, so scripted mutations must send one too.
Passing requests continue untouched (NextResponse.next()), so SSE
streams aren't buffered.
Access model
Two layers decide who may reach an upstream, and the second never trusts the first:
- The edge gate (
src/proxy.ts) decides only whether a route needs a session. WithAITP_CONSOLE_PUBLIC_MODEoff (the default, and how production ships), that is every route except/login, as described above. With it on, pages (except/loginand/logout),/api/cp/*,/api/playground/*and/api/auth/sessionpass without one. Wrong Basic credentials on an open route are counted per IP (10 a minute, 50 shared by callers whose IP is unknown) and answer 429 past that; a garbledAuthorizationheader is treated as anonymous. - The route helpers (
src/lib/api/proxy.ts) callauthorizeUpstream(src/lib/server/access.ts) before reading the request body or making any fetch. It re-derives the flag, the session and the route class from the allowlist (src/lib/server/allowlist.ts), matched on the upstream path after dot-segment resolution. A test (src/lib/api/upstream-boundary.test.ts) keeps every route handler on those helpers.
| Flag off | Flag on | |
|---|---|---|
| Operator (cookie or Basic) | every route | every route; public routes still count against the per-IP limits |
| Anonymous, public route | 401 | allowed, rate-limited |
| Anonymous, admin or unlisted route | 401 | 403 CONSOLE_OPERATOR_SESSION_REQUIRED |
| Console password unset | 503 everywhere | public routes work; everything else 503 console_not_configured |
Limits apply only with the flag on, in memory per instance
(src/lib/server/limits.ts): 300 requests a minute per IP on every public
route; 5 run launches per 10 minutes per IP (on top of the read charge);
for anonymous control-plane reads, 60 a minute per IP and 300 a minute per
instance, so visitors cannot starve the CP's read-key bucket; and 4
concurrent streams per IP, 200 per instance. A slot is freed when the
stream ends, errors, is cancelled or the request aborts, and after 305
seconds at most. The 305-second expiry assumes the platform ends a stream at
the route's 300-second maxDuration, as Vercel does; a self-hosted server
that lets a stream run longer frees its slot while it is still open. On
public routes operators are charged the per-IP read (and launch)
buckets like anyone else; admin-class routes charge nothing, since only
operators reach them. A request refused by any limit spends nothing from the
others. A refusal is 429 {error, code: "CONSOLE_RATE_LIMITED", retryAfterSeconds, limit} with Retry-After; the SSE hook backs off on it
the same way it does on a CP at capacity. IPv6 callers are limited per /64.
Credentials are chosen per route class, never per caller-supplied
header (see PROXIES.md § Auth).
An anonymous caller never gets the CP admin key: a CP read route with no
read key configured answers 503 cp_read_key_unavailable.
What the UI sees. GET /api/auth/session answers
{publicMode, signedIn} (never cached), so the UI can hide operator-only
controls from anonymous visitors. The root layout computes the same answer
while it renders (src/lib/server/initial-session.ts, made per-request by
connection()) and seeds the client with it: with the flag off the UI is the
operator outright and never asks; with it on, the server's answer stands
from the first paint. Hiding is cosmetic; the helpers enforce.
Layering
src/
├── app/
│ ├── api/** ← Edge of the system (BFF proxies)
│ ├── <section>/page.tsx ← Pages: thin compositions of components
│ └── layout.tsx, providers.tsx
│
├── components/
│ ├── layout/ ← Sidebar, topbar, connection-status
│ ├── shared/ ← Cross-cutting primitives (badges, cards…)
│ └── <section>/ ← Section-specific (dashboard/, runs/, …)
│
├── hooks/
│ ├── use-sse.ts ← Single source of SSE behavior
│ ├── use-<sse-stream>.ts ← Domain-specific wrappers
│ └── use-<resource>.ts ← TanStack Query wrappers
│
├── lib/
│ ├── api/
│ │ ├── proxy.ts ← Generic proxy helpers (Get/Post/Put/Delete/Sse)
│ │ └── client.ts ← Typed fetch wrappers used by hooks
│ ├── types/
│ │ ├── playground.ts ← Playground response types
│ │ └── cp.ts ← Control plane response types
│ ├── colors.ts ← Design tokens (mirrors the @theme block in globals.css)
│ ├── config.ts ← serverConfig (env), clientConfig
│ ├── query-options.ts ← Named refetch cadences (REFETCH.*)
│ ├── export.ts ← CSV / NDJSON download helpers
│ └── utils.ts ← cn(), formatAid(), formatGrants(), timeAgo(), shortId()
│
└── test/ ← Shared test utilities, polyfills, stubsEach layer depends only on the layers below it. lib/ knows nothing
about React. hooks/ depends on lib/ and React. components/ depends
on hooks + lib. app/ composes everything.
SSE: why native EventSource
Two streams matter:
/api/playground/runs/[id]/events— per-run event timeline, emitted by the playground as the scenario executes./api/cp/events/stream— global event stream, emitted by the control plane for every registry/handshake/audit event.
Both are read in the browser via useSse (src/hooks/use-sse.ts), which
wraps the native EventSource. We deliberately do not pull in a
WebSocket library:
- Re-connection with exponential backoff is ~20 lines (already done).
- Page-visibility pausing — when the tab is hidden we close the connection and reopen it on focus — keeps idle-tab cost at zero.
- SSE is HTTP, so the same BFF proxy approach works (
proxySsesimply forwardsResponse.bodywithContent-Type: text/event-stream).
The control plane caps concurrent SSE listeners and returns a 503 at the
limit. Because browsers don't expose the EventSource handshake status,
useSse takes an optional capacityProbePath that does a one-shot
fetch() first; a 503 surfaces as a distinct at-capacity state with a
longer backoff. The CP ticker opts into this; the per-run playground
stream does not need it. The probe contract and the CP-side cap are
covered in PROXIES.md.
Data fetching
Every read goes through TanStack Query (@tanstack/react-query). Each
resource has a small hook in src/hooks/use-<resource>.ts that returns
the upstream type directly — there is no mapping layer between fetched
data and rendered components.
Refetch cadences are not per-hook millisecond literals; hooks
reference named buckets in src/lib/query-options.ts
(REFETCH.health / slow / list / realtime / runActive / veryslow). One
file controls how aggressively the console hits each upstream. The runs
list, for example, uses runActive while a run is in flight and list
otherwise.
Writes use useMutation and invalidate the relevant query key on success.
Mutations exist for: triggering and cancelling runs; enrollment-token
minting; trust-anchor / pinned-key / revocation edits; and webhook CRUD
(including circuit-breaker reset).
Type flow
Backend response types live in src/lib/types/playground.ts and
src/lib/types/cp.ts. They mirror the JSON shapes the upstream services
serialize — the source of truth for those shapes is the
playground and CP API docs. Hooks
return these types directly. If an upstream changes shape, fix the type
file and the compiler walks every consumer.
State that lives in the console
Almost none. Some local component state (selected event, timeline
scroll-lock) but no global store. Operator-visible filter / tab state on
/dashboard, /audit, /registry, /monitor, and the run-detail tabs
is synced to the URL with useUrlState (src/hooks/use-url-state.ts) so
views are shareable and survive reload. No zustand — if cross-route
state ever needs persistence we'll add it back deliberately for the
specific feature that needs it.
Things that intentionally aren't here
- shadcn/ui — the mock used pure inline styles for tight visual
control. To preserve that fidelity we built our own primitives in
src/components/shared/. If we later need a full component library, it's an opt-in install. - A WebSocket lib —
EventSourcehandles everything we need. - Server components / Server actions — every page is client-side
because they all subscribe to live data. The only server-side code is
the BFF route handlers, the proxy (
src/proxy.ts), and the routing layer innext.config.ts(the bare-domain/→/dashboardredirect and theX-Frame-Options/X-Content-Type-Optionssecurity headers). - A monorepo build tool — the console builds independently. The sibling services have their own build pipelines.