From 2d2868130b79dabf136a8ad8c04007f5cc3833cf Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 04:18:06 +0100 Subject: [PATCH 1/2] CONTRACT: fix(ui-server): contain secondary backend boot failures --- .changeset/degraded-backend-boot.md | 5 + api-report/ui-server.txt | 11 +- docs/decisions/claude-code-runtime.md | 23 ++- docs/decisions/http-api-boundary.md | 8 +- docs/decisions/proportionate-containment.md | 43 ++++++ docs/decisions/runtime-requirements.md | 2 +- docs/decisions/scheduled-tasks.md | 2 +- docs/decisions/session-principals.md | 6 +- docs/hosting/README.md | 4 +- docs/http-api.md | 23 ++- docs/integration-contract/http.md | 21 +++ .../plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 2 +- docs/plans/chat-history-deletion.md | 2 +- packages/ui-server/README.md | 2 +- packages/ui-server/src/agent/backend.ts | 141 +++++++++++------- packages/ui-server/src/agent/subscription.ts | 22 ++- packages/ui-server/src/app.ts | 40 +++-- packages/ui-server/src/config/env.ts | 2 +- packages/ui-server/src/routes/health.ts | 12 +- packages/ui-server/tests/backend-boot.test.ts | 11 +- .../ui-server/tests/degraded-backend.test.ts | 62 ++++++++ packages/ui-server/tests/runtime-boot.test.ts | 12 +- .../tests/subscription-status.test.ts | 14 +- 24 files changed, 353 insertions(+), 119 deletions(-) create mode 100644 .changeset/degraded-backend-boot.md create mode 100644 packages/ui-server/tests/degraded-backend.test.ts diff --git a/.changeset/degraded-backend-boot.md b/.changeset/degraded-backend-boot.md new file mode 100644 index 0000000000..cbc59c4dac --- /dev/null +++ b/.changeset/degraded-backend-boot.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": minor +--- + +Keep working backends available when a secondary backend fails boot validation, and report invalid subscription mint dates as unknown expiry. diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index bb38ca56b8..892061ffa2 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -242,6 +242,15 @@ signatures (every public export and the types it is made of) export type AwaitableActivityStore = Omit & { [K in ActivityWriteMethod]: (...args: Parameters) => Awaitable>; }; + BackendBootFailure (packages/ui-server/src/agent/backend.ts) + export interface BackendBootFailure { + backendId: string; + phase: "resolution" | "runtime"; + site: "assertBackendResolvable" | "probeBackendRuntimes"; + errorClass: string; + message: string; + at: string; + } BackendRegistry (packages/ui-server/src/agent/backend.ts) export interface BackendRegistry { getBackends(): Promise; @@ -2379,7 +2388,7 @@ signatures (every public export and the types it is made of) turn_usd: z.ZodNumber; }, z.core.$strict>; assertBackendResolvable (packages/ui-server/src/agent/backend.ts) - export function assertBackendResolvable(agent: AgentConfig, resolve?: (specifier: string) => void, load?: (specifier: string) => unknown): void; + export function assertBackendResolvable(agent: AgentConfig, resolve?: (specifier: string) => void, load?: (specifier: string) => unknown): BackendBootFailure[]; attribution (packages/ui-server/src/governance/events.ts) const attribution: z.ZodObject<{ actor: z.ZodEnum<{ diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 0efd5cf1dd..1a08652888 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -44,7 +44,7 @@ next to it. `packages/ui-server/src/config/env.ts:584-584`) and is null when unset (`claudeCodePath`, `packages/ui-server/src/config/env.ts:1200`). The whole `agent` block is copied into the backend's module config (`config: { ...agent }`, - `packages/ui-server/src/agent/backend.ts:505`), read back as a string + `packages/ui-server/src/agent/backend.ts:532`), read back as a string (`const claudeCodePath`, `packages/ui-backend-claude/src/module.ts:266-270`) and handed to the SDK (`backend.claudeCodePath`, `packages/ui-backend-claude/src/sdk-options.ts:385`). Because of the `||` @@ -210,9 +210,9 @@ unnecessary. installed but cannot run — a musl binary with no musl loader — it fails with "exists but failed to launch". Both strings are in `node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs`. The boot probe below - turns either into a refusal to start, for the same reason a missing backend - refuses to boot (`A missing (or unrecognized) agent backend`, - `packages/ui-server/src/app.ts:416-421`). + refuses startup when either failure affects the default backend. Since + #3817, a failed secondary backend is excluded while the working default + continues; health reports degraded and authenticated status retains the cause. - **The published range is still a caret, and that bounds what this repo can guarantee.** `@schlessera/brain-backend-claude` depends on `^0.3.241`, and a host resolves it in its own lockfile. A host can bump the SDK — and so the @@ -259,15 +259,18 @@ than refuses on a mismatch.** the same exec wrapper and environment a turn uses, so a binary the agent's uid cannot execute fails here and not on the first turn. - **What boot does with the answer.** A missing binary, or one that will not - run `--version`: **refuse to start**. A pair other than the measured one: one + run `--version`: **refuse the default backend at boot; exclude a secondary + backend and report degraded health** (#3817). Explicit incompatible version + requirements receive the same containment; that backend never executes. + A pair other than the measured one: one warning naming both pairs, and boot continues. A clean `--version` shows the binary launches, not that a session works; the first turn's `init` is the first proof of that. - **Where it shows.** `/api/status`, which is behind the auth guard and already reports the source commit (`Operational status`, - `packages/ui-server/src/routes/health.ts:57-75`), and the run record. Not + `packages/ui-server/src/routes/health.ts:61-79`), and the run record. Not `/api/health`: it is public and deliberately carries no version - (`Public liveness probe`, `health.ts:14-16`). Not `brain doctor`: it runs on + (`Public liveness probe`, `health.ts:15-17`). Not `brain doctor`: it runs on the user's machine against a different binary. Why warn rather than refuse an unmeasured pair, given that what was measured is @@ -692,7 +695,11 @@ subscription authenticates. server's part: the operator records the mint date (`BRAIN_UI_CLAUDE_TOKEN_MINTED_AT`), the server warns from 30 days before the measured one-year expiry, and `/api/status` shows when the token last - worked. Every auth failure also becomes an instruction: `relogin` for a + worked. Since #3817 an invalid mint date is an explicit "expiry unknown: + invalid mint date" warning in owner status and logs, with the cause retained + in operational settings. It does not refuse boot or silently disable the + warning. Correcting the configured date restores estimation on the next + start; authentication itself is unchanged. Every auth failure also becomes an instruction: `relogin` for a rejected token, `check_account` for an account the token cannot fix, and `check_config` for a turn the backend refused before sending it. A keyless test rehearses the rotation on a headless host. diff --git a/docs/decisions/http-api-boundary.md b/docs/decisions/http-api-boundary.md index d1ef14c473..8c00d3ce5e 100644 --- a/docs/decisions/http-api-boundary.md +++ b/docs/decisions/http-api-boundary.md @@ -46,11 +46,11 @@ explicit supported rows, not silently excluded by this distinction. The source audit on 2026-09-30 used `e0875269b21b707482545be9e94901acb897893b`. The public health mount precedes auth -(`createHealthRoutes`, `packages/ui-server/src/app.ts:998`), the API guard follows -public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1019`), and the -WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1234`). +(`createHealthRoutes`, `packages/ui-server/src/app.ts:1018`), the API guard follows +public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1039`), and the +WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1257`). Static serving is conditional (`if (options.staticRoot)`, -`packages/ui-server/src/app.ts:1254-1275`). That order establishes access; +`packages/ui-server/src/app.ts:1277-1298`). That order establishes access; it does not select compatibility status. A hermetic real-app launch, with temporary brain root, in-memory database, diff --git a/docs/decisions/proportionate-containment.md b/docs/decisions/proportionate-containment.md index d6f4647872..54fe965703 100644 --- a/docs/decisions/proportionate-containment.md +++ b/docs/decisions/proportionate-containment.md @@ -109,3 +109,46 @@ A PR that adds or changes a fail-closed guard answers these in its body: (#3810). - **Restart the server on latch.** Rejected: a durable latch survives restart by design, and a process-lifetime one hides the cause. + +## The two historical boot gates traced in #3817 + +The acceptance criteria permit retaining a boot refusal where tracing shows +that the current host cannot enforce the proposed restricted mode. These two +refusals remain; they are not covered by secondary-backend degraded health. + +**Failed protected-file quarantine.** The result is a protected executable +input still in the brain, not merely a missing history record. The host +reconciles before it prepares the boundary or invokes the brain's CLI; +`reconcileExisting` refuses before installing its writer gate +(`reconcileExisting()`, `packages/ui-server/src/brain/host-execution.ts:100-113`). +The CLI version probe itself evaluates the brain's execution environment. +A read-only UI that continued this normal startup would already have crossed +the forbidden evaluation boundary before serving diagnostics. Neither a +strict turn profile nor a writer lock makes that configuration trusted. +Therefore the full app still refuses when quarantine cannot move the input. +The manifest retains the failed paths and error text with an open end record; +reconciliation retries the move on the next start +(`const close`, `packages/ui-server/src/brain/governed-manifest.ts:258-267`). +Repairing the quarantine destination preserves the bytes and permits that +retry; removing a protected input requires the owner's judgment. A separate +boot path that never evaluates the brain would be needed to serve recovery +while this guard is active; removing the assertion alone is unsafe. + +**Interrupted operational restore.** This is an incomplete replacement of the +whole operational database and staging tree, including principals, schedules, +retained dialogue authority and budget reservations. It is not a single inbox +item. Resume accepts only the original snapshot checksum and root and an +unchanged logical database +(`restoreInboxSnapshot`, `packages/ui-server/src/inbox/snapshot.ts:428-445`). +Even ordinary authentication writes would make that target fail the equality +check. The final transaction settles reservations conservatively, pauses +schedules and invalidates old dialogue authority before marking it ready +(`const recovered`, `packages/ui-server/src/inbox/snapshot.ts:463-480`). +Starting the regular authenticated app over the pending database cannot +preserve this recovery contract, so its refusal remains. The existing local +`brain-ui-inbox restore --db --brain-root --file +--json` operation resumes the same snapshot without starting the app. Choosing +the snapshot is an owner action; the snapshot bytes are not retained by the +pending row, so startup cannot reconstruct them automatically. Serving a +recovery UI here would require authentication independent of the database +being restored, rather than treating its historical principals as current. diff --git a/docs/decisions/runtime-requirements.md b/docs/decisions/runtime-requirements.md index 602e875788..d0bdc751e0 100644 --- a/docs/decisions/runtime-requirements.md +++ b/docs/decisions/runtime-requirements.md @@ -278,7 +278,7 @@ reciprocal host-version negotiation is involved. | `probeBrainCliVersion` / `brainCliCommand` (`export async function probeBrainCliVersion`, `packages/ui-server/src/brain/client.ts:181-248`) | Reuse executable selection, wrapper, deadline and cleanup; add host floor composition, strict comparison and invocation verification without duplicating the 0.33.0 constant. | | `installedAgentSdkVersion` (`export function installedAgentSdkVersion`, `packages/ui-backend-claude/src/runtime-probe.ts:55-61`) | Retain importer-relative resolution; validate package name/version and the owner's manifest range. | | `selectedSpawn` / `probeClaudeRuntime` (`export function selectedSpawn`, `packages/ui-backend-claude/src/runtime-probe.ts:69-96`; `export async function probeClaudeRuntime`, `packages/ui-backend-claude/src/runtime-probe.ts:127-147`) | Keep SDK-selected command capture, native/JS override argv, environment, timeout and group cleanup; add strict identity validation and composed runtime floors. | -| `probeBackendRuntimes` (`export async function probeBackendRuntimes`, `packages/ui-server/src/agent/backend.ts:394-444`) | Forward validated host requirements; retain active-backend selection and separate unmeasured-pair logging. | +| `probeBackendRuntimes` (`export async function probeBackendRuntimes`, `packages/ui-server/src/agent/backend.ts:412-462`) | Forward validated host requirements; retain active-backend selection and separate unmeasured-pair logging. | | `BackendModuleContext` / `BackendRuntimeReport` (`export interface BackendModuleContext`, `packages/ui-sdk/src/server/backend-module.ts:96-111`; `export interface BackendRuntimeReport`, `packages/ui-sdk/src/server/backend-module.ts:118-131`) | Extend the existing construction context for optional minimums. Keep report identities and `measured` meanings; a compatibility result must never occupy `measured.matches`. | | `MEASURED_RUNTIME`, its guard and `scripts/measure-claude-runtime.ts` | Keep the constant, exact pair guard, keyless behavior probe and dated measurement receipts. A permitted pair can still be unmeasured. | | Turn `reportRuntime` / `init` (`export function reportTurnRuntime`, `packages/ui-backend-claude/src/turn-reporting.ts:31-70`; `if (msg.type === "system"`, `packages/ui-backend-claude/src/turn-stream.ts:97-102`; `function initMatchesProbe`, `packages/ui-backend-claude/src/turn-stream.ts:184-196`) | Preserve actual per-turn SDK/runtime observations, billing/permission guards and normal failure terminal behavior. | diff --git a/docs/decisions/scheduled-tasks.md b/docs/decisions/scheduled-tasks.md index 9efe29bae7..e7b7eda851 100644 --- a/docs/decisions/scheduled-tasks.md +++ b/docs/decisions/scheduled-tasks.md @@ -23,7 +23,7 @@ Source inspected at `b5c30c180df5584584f261b446c4d440380d2441`: (`else if (item.status === "scheduled"`, `packages/ui-server/src/inbox/actions.ts:196-197`). The runtime ticks every minute (`INBOX_TICK_MS`, `packages/ui-server/src/inbox/runtime.ts:11-13`). - Production app wiring supplies recovery and budgets, without a dispatcher - (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:542-558`). + (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:556-572`). A scripted nonempty ready-item test still reports no claim, attempt or Activity root. That proves disabled wiring, not safe execution of a schedule. - Headless plumbing checks backend support, a usable principal, lifetime and diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index 8cabbf72a4..e4479ba283 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -96,9 +96,9 @@ Both reviewers verified every row below against the source. | Cookie verify | `auth.ts:265-296` | strict `^(\d+)\.(\d+)$`, safe integers, future/expired rejection, `cookieEpoch === sessionsEpoch(db)` | | Global epoch | `auth.ts:302-318` | `settings` row; missing = 0; non-integer **throws** | | Global revoke | `auth.ts:321-330` | `setSetting` (overflow-guarded) + `clients.closeAll(1008, …)` | -| Auth routes | `authRoutes`, `app.ts:1004` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1019`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | -| Passkey management | `passkeyManagementRoutes`, `app.ts:1029` | mounted **after** the guard ("Mount AFTER the auth guard") | -| WS guard | `"/ws"`, `app.ts:1234-1251` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | +| Auth routes | `authRoutes`, `app.ts:1024` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1039`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | +| Passkey management | `passkeyManagementRoutes`, `app.ts:1048` | mounted **after** the guard ("Mount AFTER the auth guard") | +| WS guard | `"/ws"`, `app.ts:1257-1274` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | | WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context | | WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown | | Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor | diff --git a/docs/hosting/README.md b/docs/hosting/README.md index 263b517ecb..41a5b01993 100644 --- a/docs/hosting/README.md +++ b/docs/hosting/README.md @@ -345,7 +345,9 @@ What the server does between logins: - **Before expiry.** From 30 days before `expiresAt`, and after it, the server logs a WARN at boot and at most once a day, naming the date and this procedure. Without `BRAIN_UI_CLAUDE_TOKEN_MINTED_AT` it cannot tell, and says - so once at boot. A date it cannot read refuses the boot. + so once at boot. An invalid date keeps serving and reports "expiry unknown: + invalid mint date" in authenticated status and the boot log; correct the date + and restart to restore the estimate. - **Proof it works.** `lastProvenAt` is the latest successful turn that ran on the subscription (kept in the database, so it survives a restart and the activity retention window), or a successful model-discovery call with the diff --git a/docs/http-api.md b/docs/http-api.md index 257eee2fc1..a19e02ffd7 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -348,13 +348,16 @@ universal Cache-Control header is promised. the app's SQLite schema. Healthy: 200 `{ status: "healthy", uptime: number, timestamp: string }`, where uptime is milliseconds since the route module initialized and timestamp is ISO UTC. +A failed secondary backend returns 200 with `status: "degraded"` and +`reasons: ["backend_unavailable"]`, retaining uptime and timestamp. Error text +and backend identities remain behind authentication on `/api/status`. An unreadable database yields 503 `{ status: "unhealthy" }`, without detail. It never exposes release, source commit, runtime, credentials or session state; healthy does not certify upstream model or brain CLI availability. **GET /api/status** is protected, accepts no inputs, and returns -`{ healthy: true, uptime, version, software, cronJobs, activeSession, metrics, -runtime?, subscription? }`. `version` is the configured source commit (default +`{ healthy: boolean, uptime, version, software, cronJobs, activeSession, metrics, +runtime?, subscription?, backendAvailability? }`. `version` is the configured source commit (default `"dev"`), not a release; `software` is `{ release, sourceCommit }`. `cronJobs` contains `{ name, lastRunAt, lastStatus, lastDurationMs, lastError }`, nullable when a job has not run; it includes recorded jobs and configured in-process @@ -364,6 +367,15 @@ series have name, kind (counter/updowncounter/histogram/gauge), numeric value and scalar attributes; histogram value is the observation count. Operational reads can fail with the common 500. +`backendAvailability` contains `unavailable` (this boot's excluded backends) and +`lastFailures` (the latest persisted failure per backend, retained after repair). +Each record has `backendId`, `phase: "resolution" | "runtime"`, `errorClass`, +`message`, `site` (the failed boot check) and ISO `at`. `healthy` is false while `unavailable` is nonempty. +The default backend must pass boot validation; unavailable secondary backends +are never constructed or routed to. Correct the package/runtime or host +configuration and start again to revalidate. Prior records alone do not imply +current degradation. + `runtime.workerHost` is whether this host can run agent workers (#1632): `{ ordinary?, restricted? }`, each `{ available, checkedAt, trigger }` plus `requirement` when unavailable. `checkedAt` is ISO UTC; `trigger` is `"boot"`, @@ -400,7 +412,12 @@ and the [sync reporting contract](integration-contract/wire.md#activity-stream-r `subscription` contains `tokenSet`, nullable ISO `mintedAt`, `expiresAt`, `lastProvenAt`, `provenBy: "turn" | "model_discovery" | null` and nullable `lastAuthFailure` (`errorClass`, ISO `at`, `action`, `source`, optional -`runId`, `message`, `status`). It never returns the token. Optional monitoring +`runId`, `message`, `status`). An invalid configured mint date leaves +`mintedAt` and `expiresAt` null and adds `expiryWarning` with +`reason: "invalid_mint_date"`, `message` starting "expiry unknown: invalid mint date", +`errorClass` and ISO `at`. It warns at boot and retains the last cause in the +operational settings store; it never refuses serving or changes authentication. +It never returns the token. Optional monitoring fields reflect injected capabilities; they are not a liveness requirement. ## Login, passkeys and delegated credentials diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 6f8a293b40..33df8128a2 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -162,6 +162,27 @@ additive in 0.42.0; no existing read or CLI/MCP shape changes. +### Degraded backend availability and unknown expiry (additive, #3817) + +A failed secondary backend leaves public `GET /api/health` live (HTTP 200), +with `status: "degraded"` and `reasons: ["backend_unavailable"]`; uptime and +timestamp stay present. Raw causes and backend identities remain protected. +Authenticated `GET /api/status` adds `backendAvailability` with this boot's +`unavailable` array and durable `lastFailures` (latest per backend). Records +carry `backendId`, `phase`, `site`, `errorClass`, `message`, and ISO `at` as specified +in [the HTTP reference](../http-api.md#liveness-and-operational-status). +`healthy` is false while any secondary backend is excluded. The default +backend still must pass; no version-incompatible backend executes. + +An invalid subscription mint date adds `subscription.expiryWarning` with +`reason: "invalid_mint_date"`, `message`, `errorClass`, and ISO `at` while +`mintedAt` and `expiresAt` remain null. Serving and authentication continue. +The missing-date and valid-date shapes are unchanged. These additions ship +in 0.45.0; no CLI/MCP envelope or provider history changes. The exported +`assertBackendResolvable` now returns the excluded secondary backends as +`BackendBootFailure[]`; callers that ignored its former void return continue +to work. Primary-backend and shared profile-configuration errors still throw. + ### Published React health and sync helpers (breaking health correction) `@schlessera/brain-ui-react` exports `createBrainApi` and `BrainApi`; the diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index 4f47e86034..bdf7d860f7 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -226,7 +226,7 @@ Stated before the requirements because five of them derive from it. that is the shape to copy, including its `close()` lifecycle. - R19. **The cron backstop has independent authorization before the general guard.** Mount it on the existing listener before - (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1019`). + (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1039`). Authorize a boot-minted ephemeral token, rotated each boot and stored in a 0600 runtime file, with the actual socket address as an additional check. Proxy headers cannot authorize it. The poke succeeds in every auth mode diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 17508354a9..af41211181 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -131,7 +131,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. owns manual triggers/history; it does not tick the inbox. - **Two connections:** (`export function createUiDb(`, `packages/ui-server/src/db/client.ts:28-45`) sets WAL, foreign keys and a 5-second busy timeout. Claims are immediate transactions. -- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1019`) follows public routes; +- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1039`) follows public routes; (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. - **Permission parking:** (`const requestPermission`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:19-188`). Timeout unwind is diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 51b601a105..761fa81941 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -334,7 +334,7 @@ Preserve the existing bounded-wait ownership distinction during that drain. writers; rejection retains the original cleanup continuation, writer and reader until genuine settlement, rather than authorizing their replacement (`guardSqliteCleanup`, `packages/ui-server/src/db/write-worker.ts:206-234`; -`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1344-1394`). +`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1367-1417`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, `packages/ui-server/src/brain/native-brain-leases.ts:274-287`). A caller deadline diff --git a/packages/ui-server/README.md b/packages/ui-server/README.md index c8a2bbcb78..05103ef408 100644 --- a/packages/ui-server/README.md +++ b/packages/ui-server/README.md @@ -364,7 +364,7 @@ under the [service terms](../geo/README.md#configuration). | `BRAIN_UI_CLAUDE_DEFAULT_MODEL` | Model the built-in default Claude profile is pinned to. | claude-opus-5-5 | | `BRAIN_UI_CLAUDE_DEFAULT_THINKING_LEVEL` | Default Claude reasoning effort (off, minimal, low, medium, high, xhigh, max). Unsupported levels resolve to a supported choice. | medium | | `BRAIN_UI_CLAUDE_PROFILES` | JSON array of extra Anthropic-compatible inference profiles ({id,label,model?,baseUrl?,authTokenEnv?,apiKeyEnv?,modelAliases?}). | (none) | -| `BRAIN_UI_CLAUDE_TOKEN_MINTED_AT` | The date CLAUDE_CODE_OAUTH_TOKEN was minted (ISO 8601, e.g. 2026-09-23), set next to the token in the same redeploy. The server counts the token's one-year lifetime from it and warns 30 days before expiry. An unparseable date refuses boot. Server-only. | no expiry warning (one WARN at boot says so) | +| `BRAIN_UI_CLAUDE_TOKEN_MINTED_AT` | The date CLAUDE_CODE_OAUTH_TOKEN was minted (ISO 8601, e.g. 2026-09-23), set next to the token in the same redeploy. The server counts the token's one-year lifetime from it and warns 30 days before expiry. An invalid date keeps serving with an explicit unknown-expiry warning in owner status and logs. Server-only. | no expiry warning (one WARN at boot says so) | | `BRAIN_UI_CLI_PROVIDER_ORIGINS` | Extra recipients for the brain CLI's relayed provider keys: KEY=origin[,origin], separated by semicolons. Each origin is an exact https origin (http only for a loopback host). By default the relay sends GEMINI_API_KEY, ANTHROPIC_API_KEY and OPENAI_API_KEY only to their own first-party origins; a custom endpoint or a custom key variable is refused unless listed here. A malformed value stops the server. | (unset; first-party origins only) | | `BRAIN_UI_COASTLINE` | "0"/"off"/"false" stops the server fetching map geometry. Maps then draw their graticule, pins and scale bar with no coastline, which is still an accurate locator. | enabled | | `BRAIN_UI_COMPUTE_KEYS` | External compute credentials the host may use for hosted jobs (#3108), by built-in provider: semicolon-separated `provider=NAME[,NAME...]` entries, such as `boat=BOAT_CI_KEY,BOAT_HEAVY_KEY`. A listed provider's own default variable is bound too; list it alone (`boat`) to bind only that. A brain.config instance whose apiKeyEnv is not bound here is refused as provider_unavailable. Values are read on the host only and never reach a worker; a bound name that BRAIN_UI_SUBPROCESS_ENV_EXTRA or a profile would forward disables hosted compute. Unset: hosted compute has no credential, not even a provider's default variable. | (empty) | diff --git a/packages/ui-server/src/agent/backend.ts b/packages/ui-server/src/agent/backend.ts index 948d60375b..c5ab4ca2d2 100644 --- a/packages/ui-server/src/agent/backend.ts +++ b/packages/ui-server/src/agent/backend.ts @@ -48,6 +48,8 @@ export interface BackendRegistryOptions { versionRequirements?: Readonly>; brainPath: string; agent: AgentConfig; + /** Backends refused by startup validation; never constructed or routed to. */ + unavailableBackends?: readonly BackendBootFailure[]; getHiddenModelIds?: () => string[]; getDefaultModelId?: () => string | null; getCustomOpenRouterModels?: () => string[]; @@ -280,6 +282,21 @@ function parseBackendDescriptors( return parsed; } +/** A boot refusal contained to one optional backend. No credentials are recorded. */ +export interface BackendBootFailure { + backendId: string; + phase: "resolution" | "runtime"; + site: "assertBackendResolvable" | "probeBackendRuntimes"; + errorClass: string; + message: string; + at: string; +} + +function backendBootFailure(backendId: string, phase: BackendBootFailure["phase"], error: unknown): BackendBootFailure { + return { backendId, phase, site: phase === "resolution" ? "assertBackendResolvable" : "probeBackendRuntimes", errorClass: error instanceof Error ? error.name : "UnknownError", + message: error instanceof Error ? error.message : String(error), at: new Date().toISOString() }; +} + /** * Boot guard. It resolves active optional backend packages and synchronously * loads their descriptors so backend-owned profile validation finishes before @@ -295,36 +312,37 @@ export function assertBackendResolvable( load: (specifier: string) => unknown = (specifier) => { return createRequire(import.meta.url)(specifier); } -): void { +): BackendBootFailure[] { const primary = agent.backend || "claude"; const primaryEntry = firstParty(primary); if (!primaryEntry) throw unknownBackendError(primary); const entries = activeFirstPartyBackends(agent); const descriptors = new Map(); + const failures: BackendBootFailure[] = []; for (const entry of entries) { try { - resolve(entry.specifier); - } catch { - if (entry.id === primary) throw missingBackendError(entry.id); - throw missingConfiguredBackendError(entry); - } - try { - descriptors.set( - entry.id, - backendDescriptorFromModule(entry.id, load(entry.specifier)) - ); - } catch (error) { - if (entry.id === primary && moduleNotFoundSpecifier(error) === entry.specifier) { - throw missingBackendError(entry.id); + try { resolve(entry.specifier); } + catch (error) { + if (moduleNotFoundSpecifier(error) === entry.specifier) + throw entry.id === primary ? missingBackendError(entry.id) : missingConfiguredBackendError(entry); + throw error; } - if (entry.id !== primary && moduleNotFoundSpecifier(error) === entry.specifier) { - throw missingConfiguredBackendError(entry); + try { descriptors.set(entry.id, backendDescriptorFromModule(entry.id, load(entry.specifier))); } + catch (error) { + if (moduleNotFoundSpecifier(error) === entry.specifier) + throw entry.id === primary ? missingBackendError(entry.id) : missingConfiguredBackendError(entry); + throw error; } - throw error; + } catch (error) { + if (entry.id === primary) throw error; + failures.push(backendBootFailure(entry.id, "resolution", error)); } } - parseBackendDescriptors(agent, entries, descriptors); + // Invalid profile definitions and identity collisions still refuse: they + // are shared routing configuration, not an unavailable runtime. + parseBackendDescriptors(agent, entries.filter(entry => descriptors.has(entry.id)), descriptors); + return failures; } /** What a backend's boot-time runtime probe found, keyed to its backend. */ @@ -385,9 +403,9 @@ async function verifyBackendRequirements(descriptor: BackendModule, context: Bac /** * Probe the runtime every active first-party backend would spawn, at boot - * (#211). A backend whose runtime is missing or will not start throws, which - * refuses the boot — the same reason a missing backend package does - * (`assertBackendResolvable`). A runtime that is not the one the backend was + * (#211). The default backend must pass; failures of a secondary backend + * are recorded in `failures` and exclude it from the registry (#3817). + * A runtime that is not the one the backend was * measured against is a warning naming both, not a refusal * (docs/decisions/claude-code-runtime.md). */ @@ -397,48 +415,55 @@ export async function probeBackendRuntimes( log?: Logger, load: (specifier: string) => unknown = (specifier) => createRequire(import.meta.url)(specifier), versionRequirements?: Readonly>, - exec?: import("@schlessera/brain-ui-sdk/server").ExecWrapperConfig + exec?: import("@schlessera/brain-ui-sdk/server").ExecWrapperConfig, + failures: BackendBootFailure[] = [] ): Promise { const validated = validateBackendVersionRequirements(agent, versionRequirements); const probes: BackendRuntimeProbe[] = []; for (const entry of activeFirstPartyBackends(agent)) { - const descriptor = backendDescriptorFromModule(entry.id, load(entry.specifier)); - const report = await verifyBackendRequirements(descriptor, { - exec, - brainPath, - config: { ...agent }, - profiles: [], - confirmBashPatterns: agent.confirmBashPatterns, - settings: {}, - ...(validated?.[entry.id] ? { versionRequirements: validated[entry.id] } : {}), - ...(log ? { log: toBackendLog(log) } : {}), - }, "startup"); - if (!report) continue; - const pair = (runtime: string, sdk?: string) => (sdk ? `${runtime} / SDK ${sdk}` : runtime); - log?.emit({ - severityText: "INFO", - body: report.runtime ? `${entry.id} runtime: ${report.runtime.name} ${report.runtime.version}` : `${entry.id} SDK: ${report.sdk?.name} ${report.sdk?.version}`, - attributes: { - "backend.id": entry.id, - ...(report.runtime ? { - "runtime.version": report.runtime.version, - "runtime.command": report.runtime.command, - "runtime.host_provided": report.runtime.hostProvided, - } : {}), - ...(report.sdk ? { "sdk.version": report.sdk.version } : {}), - }, - }); - if (report.runtime && report.measured && !report.measured.matches) { + if (failures.some(failure => failure.backendId === entry.id)) continue; + try { + const descriptor = backendDescriptorFromModule(entry.id, load(entry.specifier)); + const report = await verifyBackendRequirements(descriptor, { + exec, + brainPath, + config: { ...agent }, + profiles: [], + confirmBashPatterns: agent.confirmBashPatterns, + settings: {}, + ...(validated?.[entry.id] ? { versionRequirements: validated[entry.id] } : {}), + ...(log ? { log: toBackendLog(log) } : {}), + }, "startup"); + if (!report) continue; + const pair = (runtime: string, sdk?: string) => (sdk ? `${runtime} / SDK ${sdk}` : runtime); log?.emit({ - severityText: "WARN", - body: - `${entry.id} runtime ${pair(report.runtime.version, report.sdk?.version)} is not the one its ` + - `behaviour was measured against (${pair(report.measured.runtime, report.measured.sdk)}); ` + - "continuing — re-run scripts/measure-claude-runtime.ts", - attributes: { "backend.id": entry.id, "runtime.host_provided": report.runtime.hostProvided }, + severityText: "INFO", + body: report.runtime ? `${entry.id} runtime: ${report.runtime.name} ${report.runtime.version}` : `${entry.id} SDK: ${report.sdk?.name} ${report.sdk?.version}`, + attributes: { + "backend.id": entry.id, + ...(report.runtime ? { + "runtime.version": report.runtime.version, + "runtime.command": report.runtime.command, + "runtime.host_provided": report.runtime.hostProvided, + } : {}), + ...(report.sdk ? { "sdk.version": report.sdk.version } : {}), + }, }); + if (report.runtime && report.measured && !report.measured.matches) { + log?.emit({ + severityText: "WARN", + body: + `${entry.id} runtime ${pair(report.runtime.version, report.sdk?.version)} is not the one its ` + + `behaviour was measured against (${pair(report.measured.runtime, report.measured.sdk)}); ` + + "continuing — re-run scripts/measure-claude-runtime.ts", + attributes: { "backend.id": entry.id, "runtime.host_provided": report.runtime.hostProvided }, + }); + } + probes.push({ backendId: entry.id, report }); + } catch (error) { + if (entry.id === (agent.backend || "claude")) throw error; + failures.push(backendBootFailure(entry.id, "runtime", error)); } - probes.push({ backendId: entry.id, report }); } return probes; } @@ -484,7 +509,9 @@ export function createBackendRegistry(options: BackendRegistryOptions): BackendR let loadedRegistry: RegistrySnapshot | null = null; async function buildRegistry(): Promise { - const entries = activeFirstPartyBackends(agent); + if (options.unavailableBackends?.some(failure => failure.backendId === primary)) + throw new Error(`Default backend "${primary}" is unavailable.`); + const entries = activeFirstPartyBackends(agent).filter(entry => !options.unavailableBackends?.some(failure => failure.backendId === entry.id)); const descriptors = new Map(); for (const entry of entries) { descriptors.set(entry.id, await loadBackendDescriptor(entry.id)); diff --git a/packages/ui-server/src/agent/subscription.ts b/packages/ui-server/src/agent/subscription.ts index 54bf651908..2cea102d78 100644 --- a/packages/ui-server/src/agent/subscription.ts +++ b/packages/ui-server/src/agent/subscription.ts @@ -39,7 +39,7 @@ const ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\ /** * The mint date as the operator wrote it, or null when unset. Anything that - * is not a real ISO 8601 date refuses boot — a day that does not exist, a + * is not a real ISO 8601 date is rejected — a day that does not exist, a * time with no zone, a date in the future — because a date silently ignored * or misread would move the expiry warning or switch it off. */ @@ -75,6 +75,7 @@ export interface SubscriptionStatus { tokenSet: boolean; mintedAt: string | null; expiresAt: string | null; + expiryWarning?: { reason: "invalid_mint_date"; message: string; errorClass: string; at: string }; /** When the token last demonstrably worked. */ lastProvenAt: string | null; provenBy: "turn" | "model_discovery" | null; @@ -143,13 +144,23 @@ export function keepSubscriptionProof(db: Database, at: number): void { } /** - * Validates the configuration (throwing refuses the boot), logs the boot - * warnings, and starts the daily expiry check. + * Rejects invalid dates as unknown expiry, logs the warning, and starts the daily check. */ export function createSubscriptionMonitor(options: SubscriptionMonitorOptions): SubscriptionMonitor { const { config, log } = options; const now = options.now ?? (() => new Date()); - const mintedAt = parseMintedAt(config.mintedAt, now()); + let mintedAt: Date | null = null; + let expiryWarning: SubscriptionStatus["expiryWarning"]; + try { mintedAt = parseMintedAt(config.mintedAt, now()); } + catch (error) { + expiryWarning = { reason: "invalid_mint_date", message: `expiry unknown: invalid mint date. ${error instanceof Error ? error.message : String(error)}`, + errorClass: error instanceof Error ? error.name : "UnknownError", at: now().toISOString() }; + // Retain the last cause even after the operator corrects the setting. + setSetting(options.db, "subscription.invalidMintDate", expiryWarning); + log.emit({ severityText: "WARN", body: expiryWarning.message, + attributes: { "config.variable": MINTED_AT_ENV, "error.type": expiryWarning.errorClass, + "warning.scope": "subscription_expiry", "warning.site": "createSubscriptionMonitor", "warning.at": expiryWarning.at } }); + } const expiresAt = mintedAt ? new Date(mintedAt.getTime() + TOKEN_LIFETIME_MS) : null; let lastWarnedAt: number | null = null; @@ -199,7 +210,7 @@ export function createSubscriptionMonitor(options: SubscriptionMonitorOptions): }); } - if (config.tokenSet && !mintedAt) { + if (config.tokenSet && !mintedAt && !expiryWarning) { log.emit({ severityText: "WARN", body: @@ -260,6 +271,7 @@ export function createSubscriptionMonitor(options: SubscriptionMonitorOptions): tokenSet: config.tokenSet, mintedAt: mintedAt?.toISOString() ?? null, expiresAt: expiresAt?.toISOString() ?? null, + ...(expiryWarning ? { expiryWarning } : {}), lastProvenAt: proven ? new Date(proven.at).toISOString() : null, provenBy: proven?.by ?? null, lastAuthFailure: failures[0] ?? null, diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index bc264f5e39..156a2bebee 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -48,7 +48,7 @@ import { createApifyPolicyEdits } from "./apify/settings.js"; import { apifyBudgetSource } from "./apify/budget-liability.js"; import { declaredContentRenderers } from "./brain/content-renderers.js"; import { createHealthRoutes, createStatusRoutes } from "./routes/health.js"; -import { createSubscriptionMonitor, parseMintedAt } from "./agent/subscription.js"; +import { createSubscriptionMonitor } from "./agent/subscription.js"; import { probeWorkerHostRecorded, probeWorkerHostRecordedAsync, ROOT_SERVER_WARNING, serverRunsAsRoot } from "./agent/worker-host.js"; import type { WorkerHostMode } from "./activity/runtime-status.js"; import { createNativeBrainManagerClient, PROVIDER_CACHE_FILES, workerLimitsStatus, type WorkerHostProbe } from "@schlessera/brain-ui-sdk/internal"; @@ -131,6 +131,7 @@ import { getDefaultModelId, getHiddenModelIds, getSetting, + setSetting, getThinkingOverrides, } from "./db/settings.js"; import { createActivityRuntime } from "./activity/runtime.js"; @@ -422,22 +423,12 @@ export async function createApp(options: CreateAppOptions = {}): Promise 0) { throw new Error(`Cannot verify host versionRequirements.backends during startup through an injected registry: detected identities unknown; declarations ${JSON.stringify(backendRequirements)}. Use the descriptor-backed default registry, or omit explicit backend requirements.`); } - // A missing (or unrecognized) agent backend refuses to boot HERE, not on the - // first turn — otherwise /api/health reports healthy while every turn is - // guaranteed to fail. Descriptor loading and profile validation happen here; - // backend construction and model discovery remain lazy. - // Skipped when the embedder injects its own registry. - if (!options.registry) assertBackendResolvable(config.agent); - // An unparseable token mint date refuses here, before anything is opened - // (#254): ignoring it would silently switch the expiry warning off. - parseMintedAt(config.subscription.mintedAt); - // The runtime every active backend would spawn, probed now (#211): a - // missing or unstartable binary refuses the boot here instead of failing - // the first turn — and before anything is opened, so a refused boot leaves - // nothing behind. Skipped with an injected registry, like the check above. + // The default must work. A secondary package/runtime failure removes only + // that backend; the same exclusion reaches lazy registry construction. + const unavailableBackends = options.registry ? [] : assertBackendResolvable(config.agent); const runtimeProbes = options.registry ? [] - : await probeBackendRuntimes(config.agent, config.brainPath, observability.logger("agent"), undefined, backendRequirements, config.exec); + : await probeBackendRuntimes(config.agent, config.brainPath, observability.logger("agent"), undefined, backendRequirements, config.exec, unavailableBackends); // Per-instance state: the app's own database, the brain CLI wrapper, the // backend registry, and the WebSocket host. No module-level singletons — @@ -539,6 +530,21 @@ export async function createApp(options: CreateAppOptions = {}): Promise(db, "boot.backendFailures", []); + // Diagnostics cannot turn a malformed historical setting into a new boot gate. + const lastBackendFailures = Array.isArray(storedBackendFailures) ? storedBackendFailures.filter(entry => entry + && ["claude", "pi"].includes(entry.backendId) && ["resolution", "runtime"].includes(entry.phase) + && ["assertBackendResolvable", "probeBackendRuntimes"].includes(entry.site) + && typeof entry.message === "string" && typeof entry.errorClass === "string" && typeof entry.at === "string") : []; + for (const failure of unavailableBackends) { + const previous = lastBackendFailures.findIndex(entry => entry.backendId === failure.backendId); + if (previous < 0) lastBackendFailures.push(failure); else lastBackendFailures[previous] = failure; + observability.logger("agent").emit({ severityText: "WARN", body: `Backend ${failure.backendId} unavailable: ${failure.message}`, + attributes: { "backend.id": failure.backendId, "boot.phase": failure.phase, "boot.site": failure.site, "error.type": failure.errorClass, + "boot.at": failure.at, "boot.scope": "backend" } }); + } + if (unavailableBackends.length) setSetting(db, "boot.backendFailures", lastBackendFailures); + const backendAvailability = { unavailable: unavailableBackends, lastFailures: lastBackendFailures }; // One package-local pricing instance, shared by admission and Activity. // Refresh warms in the background; resolve() is synchronous and rollups // never wait on the network. @@ -628,6 +634,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise getHiddenModelIds(db, dbLog), @@ -1009,7 +1016,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise unavailableBackends.length ? ["backend_unavailable"] : [] })); // Not under /api, and not behind the guard: this is where a system share // lands when no service worker was around to intercept it. See the route. app.route("/", shareTargetFallbackRoutes); @@ -1056,6 +1063,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise backendAvailability, getContentRenderers: async signal => brain.modules ? declaredContentRenderers((await brain.modules({ signal })).enabled) : undefined, getCronStatus: () => cron.getCronStatus(), isTurnActive: () => host.coordinator.isTurnActive(), diff --git a/packages/ui-server/src/config/env.ts b/packages/ui-server/src/config/env.ts index 224152374d..ce11ccb0d2 100644 --- a/packages/ui-server/src/config/env.ts +++ b/packages/ui-server/src/config/env.ts @@ -653,7 +653,7 @@ export const ENV_VARS: readonly EnvVarDescriptor[] = [ "The date CLAUDE_CODE_OAUTH_TOKEN was minted (ISO 8601, e.g. 2026-09-23), " + "set next to the token in the same redeploy. The server counts the " + "token's one-year lifetime from it and warns 30 days before expiry. " + - "An unparseable date refuses boot. Server-only.", + "An invalid date keeps serving with an explicit unknown-expiry warning in owner status and logs. Server-only.", default: "no expiry warning (one WARN at boot says so)", required: false, }, diff --git a/packages/ui-server/src/routes/health.ts b/packages/ui-server/src/routes/health.ts index 49cd4e6e60..c2bbbc2f70 100644 --- a/packages/ui-server/src/routes/health.ts +++ b/packages/ui-server/src/routes/health.ts @@ -6,6 +6,7 @@ import type { ContentRendererDeclaration } from "@schlessera/brain-ui-sdk"; import type { WorkerHostStatus } from "@schlessera/brain-ui-sdk/protocol"; import type { RuntimeStatusSnapshot } from "../activity/runtime-status.js"; +import type { BackendBootFailure } from "../agent/backend.js"; import type { SubscriptionStatus } from "../agent/subscription.js"; import type { MetricSnapshot } from "../observability/index.js"; @@ -22,15 +23,17 @@ const startTime = Date.now(); // SELECT 1 — a constant expression touches no page of the database file, so it // cannot notice a locked or corrupted one. The unhealthy body carries no // detail — the route is public. -export function createHealthRoutes(deps: { db: Database }): Hono { +export function createHealthRoutes(deps: { db: Database; degradedReasons?(): string[] }): Hono { return new Hono().get("/health", (c) => { try { deps.db.query("SELECT name FROM sqlite_master LIMIT 1").get(); } catch { return c.json({ status: "unhealthy" }, 503); } + const reasons = deps.degradedReasons?.() ?? []; return c.json({ - status: "healthy", + status: reasons.length ? "degraded" : "healthy", + ...(reasons.length ? { reasons } : {}), uptime: Date.now() - startTime, timestamp: new Date().toISOString(), }); @@ -38,6 +41,7 @@ export function createHealthRoutes(deps: { db: Database }): Hono { } interface StatusDeps { + getBackendAvailability?(): { unavailable: BackendBootFailure[]; lastFailures: BackendBootFailure[] }; /** Trusted metadata from configured modules; absent with an older CLI. */ getContentRenderers?(signal?: AbortSignal): Promise; /** Git SHA baked at build time (SOURCE_COMMIT), "dev" when unset. */ @@ -59,11 +63,13 @@ interface StatusDeps { // active — none of which should be readable unauthenticated. export function createStatusRoutes(deps: StatusDeps): Hono { return new Hono().get("/status", async (c) => { + const backendAvailability = deps.getBackendAvailability?.(); const subscription = deps.getSubscription ? await deps.getSubscription() : undefined; const contentRenderers = await deps.getContentRenderers?.(c.req.raw.signal).catch(() => undefined); return c.json({ ...(contentRenderers !== undefined ? { contentRenderers } : {}), - healthy: true, + healthy: !backendAvailability?.unavailable.length, + ...(backendAvailability ? { backendAvailability } : {}), uptime: Date.now() - startTime, version: deps.sourceCommit, software: { release: packageInfo.version, sourceCommit: deps.sourceCommit }, diff --git a/packages/ui-server/tests/backend-boot.test.ts b/packages/ui-server/tests/backend-boot.test.ts index b85bff30df..e21d72b49e 100644 --- a/packages/ui-server/tests/backend-boot.test.ts +++ b/packages/ui-server/tests/backend-boot.test.ts @@ -30,7 +30,7 @@ const agent = (backend: string | null) => /** A resolver simulating "this package is not installed". */ const absent = (specifier: string) => { - throw new Error(`Cannot find module '${specifier}'`); + throw Object.assign(new Error(`Cannot find module '${specifier}'`), { code: "MODULE_NOT_FOUND" }); }; describe("assertBackendResolvable", () => { @@ -52,7 +52,7 @@ describe("assertBackendResolvable", () => { ); }); - test("BRAIN_UI_PI_PROFILES with a missing pi package refuses at boot", () => { + test("BRAIN_UI_PI_PROFILES with a missing pi package marks only pi unavailable", () => { const withPiProfiles = resolveServerConfig({ BRAIN_UI_PI_PROFILES: JSON.stringify([ { id: "gpt-sol", label: "Sol", vendor: "openai-codex", model: "gpt-5.6-sol" }, @@ -62,9 +62,10 @@ describe("assertBackendResolvable", () => { const claudeOnly = (specifier: string) => { if (specifier.includes("backend-pi")) absent(specifier); }; - expect(() => assertBackendResolvable(withPiProfiles, claudeOnly)).toThrow( - 'BRAIN_UI_PI_PROFILES is set but "@schlessera/brain-backend-pi" is not installed' - ); + expect(assertBackendResolvable(withPiProfiles, claudeOnly)).toEqual([expect.objectContaining({ + backendId: "pi", phase: "resolution", errorClass: "Error", + message: expect.stringContaining('BRAIN_UI_PI_PROFILES is set but "@schlessera/brain-backend-pi" is not installed'), + })]); // With everything resolvable, the opt-in passes. expect(() => assertBackendResolvable(withPiProfiles)).not.toThrow(); }); diff --git a/packages/ui-server/tests/degraded-backend.test.ts b/packages/ui-server/tests/degraded-backend.test.ts new file mode 100644 index 0000000000..1ef3386f35 --- /dev/null +++ b/packages/ui-server/tests/degraded-backend.test.ts @@ -0,0 +1,62 @@ +import { mockWorkerHostForSdkStream } from "../../ui-backend-claude/tests/helpers/worker-host"; +mockWorkerHostForSdkStream(); +import { expect, spyOn, test } from "bun:test"; +import * as modules from "node:module"; +import { createTestApp } from "./helpers/test-app"; +import { createRecordingObservability } from "../src/observability/index"; +import { getSetting } from "../src/db/settings"; +import { resolveAmbientPrincipal } from "../src/db/principals"; +import { createWsHandlers } from "../src/ws/connection"; +import type { WSContext } from "../src/ws/clients"; + +// The installed secondary SDK cannot satisfy this host floor. The real boot +// probe must contain that failure and the real lazy registry must exclude it. +test.each(["resolution", "runtime"] as const)("a secondary %s failure boots degraded while the default completes a turn", async (phase) => { + const originalRequire = modules.createRequire; + const requireSpy = phase === "resolution" ? spyOn(modules, "createRequire").mockImplementation(filename => { + const require = originalRequire(filename); + const resolve = require.resolve; + require.resolve = Object.assign((specifier: string, options?: { paths?: string[] }) => { + if (specifier === "@schlessera/brain-backend-pi") throw Object.assign(new Error(`Cannot find module '${specifier}'`), { code: "MODULE_NOT_FOUND" }); + return resolve(specifier, options); + }, { paths: resolve.paths }); + return require; + }) : undefined; + const observability = createRecordingObservability(); + let t: Awaited> | undefined; + let start: ReturnType | undefined; + try { + t = await createTestApp({ env: { + BRAIN_UI_PI_PROFILES: JSON.stringify([{ id: "pi-test", label: "Pi test", vendor: "openai", model: "gpt-test" }]), + }, appOptions: { observability, ...(phase === "runtime" ? { versionRequirements: { backends: { pi: { sdk: "999.0.0" } } } } : {}) } }); + const health = await t.fetch("/api/health"); + expect(health.status).toBe(200); + const publicHealth = await health.json() as Record; + expect(publicHealth).toMatchObject({ status: "degraded", reasons: ["backend_unavailable"] }); + expect(Object.keys(publicHealth).sort()).toEqual(["reasons", "status", "timestamp", "uptime"]); + const status = await (await t.fetch("/api/status")).json() as { healthy: boolean; backendAvailability: { unavailable: unknown[] } }; + expect(status.healthy).toBe(false); + expect(status.backendAvailability.unavailable).toEqual([expect.objectContaining({ backendId: "pi", phase, message: expect.stringContaining(phase === "runtime" ? "999.0.0" : "not installed") })]); + expect(getSetting(t.app.db, "boot.backendFailures", [])).toEqual(status.backendAvailability.unavailable); + expect(observability.logs.find({ severity: "WARN" }).filter(log => String(log.body).includes("Backend pi unavailable:"))).toHaveLength(1); + const registry = t.app.wsHost.registry; + expect((await registry.getBackends()).map(backend => backend.id)).toEqual(["claude"]); + expect(await registry.getBackendById("pi")).toBeUndefined(); + await expect(registry.getBackendForSession("pi")).rejects.toThrow(); + const backend = await registry.getDefaultBackend(); + start = spyOn(backend, "startTurn").mockImplementation(async ({ bridge }) => { + bridge.emit({ type: "session_info", sessionId: "ithaca-degraded", isNew: true }); + bridge.emit({ type: "result", sessionId: "ithaca-degraded", durationMs: 1, numTurns: 1, isError: false }); + }); + const sent: Array<{ type: string; isError?: boolean }> = []; + const ws = { send: (data: string) => sent.push(JSON.parse(data)), close() {}, readyState: 1 } as unknown as WSContext; + const principal = resolveAmbientPrincipal(t.app.db, "none", "No authentication", "No authentication"); + const handlers = createWsHandlers(t.app.wsHost, principal); + handlers.onOpen(undefined as never, ws); + handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text: "Plan the journey to Ithaca" }) } as MessageEvent, ws); + const until = Date.now() + 5_000; + while (!sent.some(frame => frame.type === "result") && Date.now() < until) await Bun.sleep(5); + expect(start).toHaveBeenCalledTimes(1); + expect(sent).toContainEqual(expect.objectContaining({ type: "result", isError: false })); + } finally { start?.mockRestore(); requireSpy?.mockRestore(); await t?.teardown(); } +}); diff --git a/packages/ui-server/tests/runtime-boot.test.ts b/packages/ui-server/tests/runtime-boot.test.ts index bfaadeb1da..94159d7803 100644 --- a/packages/ui-server/tests/runtime-boot.test.ts +++ b/packages/ui-server/tests/runtime-boot.test.ts @@ -184,7 +184,7 @@ describe("asynchronous startup resource ordering", () => { }); } - test("invalid subscription configuration refuses before invoking a runtime probe", async () => { + test("invalid subscription configuration boots and still invokes the required runtime probe", async () => { const dir = mkdtempSync(join(tmpdir(), "async-validation-")); scratch.push(dir); mkdirSync(join(dir, "brain")); @@ -194,9 +194,13 @@ describe("asynchronous startup resource ordering", () => { chmodSync(path, 0o755); const dbPath = join(dir, "ui.db"); const config = resolveServerConfig({ AUTH_MODE: "none", HOST: "127.0.0.1", NODE_ENV: "test", BRAIN_PATH: join(dir, "brain"), DB_PATH: dbPath, BRAIN_UI_PRICING_DISCOVERY: "0", CLAUDE_CODE_PATH: path, BRAIN_UI_CLAUDE_TOKEN_MINTED_AT: "last spring" }); - await expect(createApp({ config })).rejects.toThrow("BRAIN_UI_CLAUDE_TOKEN_MINTED_AT"); - expect(existsSync(marker)).toBe(false); - expect(existsSync(dbPath)).toBe(false); + const app = await createApp({ config }); + try { + expect(existsSync(marker)).toBe(true); + expect(existsSync(dbPath)).toBe(true); + const status = await (await app.fetch(new Request("http://localhost/api/status"))).json(); + expect(status).toHaveProperty("subscription.expiryWarning.reason", "invalid_mint_date"); + } finally { await app.close(); } }); }); diff --git a/packages/ui-server/tests/subscription-status.test.ts b/packages/ui-server/tests/subscription-status.test.ts index bf9c55328f..f79afa2793 100644 --- a/packages/ui-server/tests/subscription-status.test.ts +++ b/packages/ui-server/tests/subscription-status.test.ts @@ -33,6 +33,7 @@ import { type BrainUiApp } from "../src/app"; import { createFixtureApp as createApp } from "./helpers/native-app-fixture.js"; import { resolveServerConfig } from "../src/config/env"; import { createUiDb } from "../src/db/client"; +import { getSetting } from "../src/db/settings"; import { resolveAmbientPrincipal } from "../src/db/principals"; import { createRecordingObservability, type RecordingObservability } from "../src/observability/index"; import type { WSContext } from "../src/ws/clients"; @@ -551,9 +552,18 @@ describe("/api/status's subscription", () => { } }); - test("an unparseable mint date refuses boot, naming the variable", async () => { + test("an unparseable mint date boots with an explicit unknown expiry and runs turns", async () => { const at = host(); - await expect(boot(at, { CLAUDE_CODE_OAUTH_TOKEN: FAKE_TOKEN, [MINTED_AT_ENV]: "last spring" })).rejects.toThrow(MINTED_AT_ENV); + const { app, observability } = await boot(at, { CLAUDE_CODE_OAUTH_TOKEN: FAKE_TOKEN, [MINTED_AT_ENV]: "last spring" }, subscriptionRun); + try { + const warning = (await status(app)).subscription; + expect(warning).toMatchObject({ mintedAt: null, expiresAt: null, + expiryWarning: { reason: "invalid_mint_date", message: expect.stringContaining("expiry unknown: invalid mint date") } }); + expect(warnings(observability, "expiry unknown: invalid mint date")).toHaveLength(1); + expect(getSetting(app.db, "subscription.invalidMintDate", null)).toEqual(warning.expiryWarning); + await turn(app); + expect((await status(app)).subscription.lastProvenAt).not.toBeNull(); + } finally { await app.close(); } }); }); From a7fa9657a8bd8cb9e874bd1c3a3fe8029dd41e2b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 10 Nov 2026 04:48:12 +0100 Subject: [PATCH 2/2] fix(ui-server): keep an excluded backend's auth and search routes unloaded A backend that boot excluded never executes, so the pi sign-in and web-search routes now answer as if pi were not configured instead of loading the excluded package's OAuth or extension services. Tests also cover the retained last failure after repair and the dropped malformed history record; the contract index gets its own #3817 entry and the moved app.ts citations point at their anchors again. Co-Authored-By: Claude Opus 5.5 --- docs/decisions/codex-subscription-auth.md | 2 +- docs/decisions/http-api-boundary.md | 8 ++--- docs/decisions/scheduled-tasks.md | 2 +- docs/decisions/session-principals.md | 6 ++-- docs/integration-contract.md | 4 +++ docs/integration-contract/http.md | 4 ++- .../plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 2 +- docs/plans/chat-history-deletion.md | 2 +- packages/ui-server/src/app.ts | 6 ++-- packages/ui-server/src/routes/pi-auth.ts | 16 +++++++--- packages/ui-server/src/routes/web-search.ts | 4 ++- .../ui-server/tests/degraded-backend.test.ts | 32 +++++++++++++++++++ .../ui-server/tests/pi-auth-routes.test.ts | 12 +++++++ .../ui-server/tests/web-search-routes.test.ts | 11 +++++++ 15 files changed, 93 insertions(+), 20 deletions(-) diff --git a/docs/decisions/codex-subscription-auth.md b/docs/decisions/codex-subscription-auth.md index 322b6c5091..499bf25d9f 100644 --- a/docs/decisions/codex-subscription-auth.md +++ b/docs/decisions/codex-subscription-auth.md @@ -80,7 +80,7 @@ flow and expose its own connection state, even if the user chooses the same ChatGPT account. Native client credentials remain private to their owners; responses, logs and documentation must not expose tokens or account identifiers. Pi's existing Accounts flow remains the entry point for pi only -(`createPiAuthRoutes`, `packages/ui-server/src/routes/pi-auth.ts:60-61`; +(`createPiAuthRoutes`, `packages/ui-server/src/routes/pi-auth.ts:66-67`; `PiAccountsSection`, `packages/ui-react/src/components/settings/pi-accounts.tsx:19-24`). This is a go for implementing a separate Codex login in that Settings area, diff --git a/docs/decisions/http-api-boundary.md b/docs/decisions/http-api-boundary.md index 8c00d3ce5e..22f9b00e99 100644 --- a/docs/decisions/http-api-boundary.md +++ b/docs/decisions/http-api-boundary.md @@ -46,11 +46,11 @@ explicit supported rows, not silently excluded by this distinction. The source audit on 2026-09-30 used `e0875269b21b707482545be9e94901acb897893b`. The public health mount precedes auth -(`createHealthRoutes`, `packages/ui-server/src/app.ts:1018`), the API guard follows -public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1039`), and the -WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1257`). +(`createHealthRoutes`, `packages/ui-server/src/app.ts:1019`), the API guard follows +public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1040`), and the +WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1260`). Static serving is conditional (`if (options.staticRoot)`, -`packages/ui-server/src/app.ts:1277-1298`). That order establishes access; +`packages/ui-server/src/app.ts:1280-1301`). That order establishes access; it does not select compatibility status. A hermetic real-app launch, with temporary brain root, in-memory database, diff --git a/docs/decisions/scheduled-tasks.md b/docs/decisions/scheduled-tasks.md index e7b7eda851..bd14caa75e 100644 --- a/docs/decisions/scheduled-tasks.md +++ b/docs/decisions/scheduled-tasks.md @@ -23,7 +23,7 @@ Source inspected at `b5c30c180df5584584f261b446c4d440380d2441`: (`else if (item.status === "scheduled"`, `packages/ui-server/src/inbox/actions.ts:196-197`). The runtime ticks every minute (`INBOX_TICK_MS`, `packages/ui-server/src/inbox/runtime.ts:11-13`). - Production app wiring supplies recovery and budgets, without a dispatcher - (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:556-572`). + (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:557-573`). A scripted nonempty ready-item test still reports no claim, attempt or Activity root. That proves disabled wiring, not safe execution of a schedule. - Headless plumbing checks backend support, a usable principal, lifetime and diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index e4479ba283..c10fa0eb93 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -96,9 +96,9 @@ Both reviewers verified every row below against the source. | Cookie verify | `auth.ts:265-296` | strict `^(\d+)\.(\d+)$`, safe integers, future/expired rejection, `cookieEpoch === sessionsEpoch(db)` | | Global epoch | `auth.ts:302-318` | `settings` row; missing = 0; non-integer **throws** | | Global revoke | `auth.ts:321-330` | `setSetting` (overflow-guarded) + `clients.closeAll(1008, …)` | -| Auth routes | `authRoutes`, `app.ts:1024` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1039`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | -| Passkey management | `passkeyManagementRoutes`, `app.ts:1048` | mounted **after** the guard ("Mount AFTER the auth guard") | -| WS guard | `"/ws"`, `app.ts:1257-1274` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | +| Auth routes | `authRoutes`, `app.ts:1025` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1040`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | +| Passkey management | `passkeyManagementRoutes`, `app.ts:1049` | mounted **after** the guard ("Mount AFTER the auth guard") | +| WS guard | `"/ws"`, `app.ts:1260-1277` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | | WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context | | WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown | | Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor | diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 779f9b8227..27effbd893 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -1143,6 +1143,10 @@ Original fragment identities remain available at this entry point. - [ui-server HTTP routes](integration-contract/http.md#ui-server-http-routes) (original line 1943). + + +- [Degraded backend availability and unknown expiry (additive, #3817)](integration-contract/http.md#degraded-backend-availability-and-unknown-expiry-additive-3817). + - [Published React health and sync helpers (breaking health correction)](integration-contract/http.md#published-react-health-and-sync-helpers-breaking-health-correction) (original line 1964). diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 33df8128a2..95ee486290 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -160,7 +160,7 @@ conflicts, unavailable detail, unknown outcomes and partial work remain explicit voice, agent and autonomous execution do not gain a history action. This is additive in 0.42.0; no existing read or CLI/MCP shape changes. - + ### Degraded backend availability and unknown expiry (additive, #3817) @@ -183,6 +183,8 @@ in 0.45.0; no CLI/MCP envelope or provider history changes. The exported `BackendBootFailure[]`; callers that ignored its former void return continue to work. Primary-backend and shared profile-configuration errors still throw. + + ### Published React health and sync helpers (breaking health correction) `@schlessera/brain-ui-react` exports `createBrainApi` and `BrainApi`; the diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index bdf7d860f7..7623cc6016 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -226,7 +226,7 @@ Stated before the requirements because five of them derive from it. that is the shape to copy, including its `close()` lifecycle. - R19. **The cron backstop has independent authorization before the general guard.** Mount it on the existing listener before - (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1039`). + (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1040`). Authorize a boot-minted ephemeral token, rotated each boot and stored in a 0600 runtime file, with the actual socket address as an additional check. Proxy headers cannot authorize it. The poke succeeds in every auth mode diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index af41211181..f1d94d0471 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -131,7 +131,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. owns manual triggers/history; it does not tick the inbox. - **Two connections:** (`export function createUiDb(`, `packages/ui-server/src/db/client.ts:28-45`) sets WAL, foreign keys and a 5-second busy timeout. Claims are immediate transactions. -- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1039`) follows public routes; +- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1040`) follows public routes; (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. - **Permission parking:** (`const requestPermission`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:19-188`). Timeout unwind is diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 761fa81941..9a11d2924d 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -334,7 +334,7 @@ Preserve the existing bounded-wait ownership distinction during that drain. writers; rejection retains the original cleanup continuation, writer and reader until genuine settlement, rather than authorizing their replacement (`guardSqliteCleanup`, `packages/ui-server/src/db/write-worker.ts:206-234`; -`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1367-1417`). +`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1370-1420`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, `packages/ui-server/src/brain/native-brain-leases.ts:274-287`). A caller deadline diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 156a2bebee..41780621c1 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1221,8 +1221,10 @@ export async function createApp(options: CreateAppOptions = {}): Promise unavailableBackends.some(failure => failure.backendId === "pi"); + app.route("/api", createPiAuthRoutes({ agent: config.agent, excluded: piExcluded })); + app.route("/api", createWebSearchRoutes({ agent: config.agent, excluded: piExcluded })); const apifyOwner = (id: string) => { const principal = resolvePrincipal(db, id); return !!principal && ["owner", "ambient"].includes(principal.kind) && isUsablePrincipal(principal, Date.now()); }; // Settings edits (#3163) go through the existing policy proposals, the only policy writer, in a user journal window. const apifyEdits = createApifyPolicyEdits({ root: config.brainPath, proposals: policyProposals, journal, authorized: apifyOwner }); diff --git a/packages/ui-server/src/routes/pi-auth.ts b/packages/ui-server/src/routes/pi-auth.ts index 978176c15c..4ace25183d 100644 --- a/packages/ui-server/src/routes/pi-auth.ts +++ b/packages/ui-server/src/routes/pi-auth.ts @@ -53,6 +53,12 @@ interface PiAuthMirror { interface PiAuthRoutesDeps { agent: AgentConfig; + /** + * True while boot excluded pi as unavailable (#3817). An excluded backend + * never executes, so its OAuth service is not loaded either: the routes + * answer as if pi were not configured. + */ + excluded?: () => boolean; /** Test seam — forwarded to loadBackendModule. */ importer?: (specifier: string) => Promise; } @@ -77,7 +83,8 @@ export function createPiAuthRoutes(deps: PiAuthRoutesDeps): Hono { } const piConfigured = () => - Boolean(agent.piProfilesJson) || (agent.backend || "claude") === "pi"; + (Boolean(agent.piProfilesJson) || (agent.backend || "claude") === "pi") && !deps.excluded?.(); + const notConfigured = { error: "The pi backend is not configured." } as const; // One service for the app's lifetime: it owns the pending-flow state. let authPromise: Promise | null = null; @@ -118,9 +125,7 @@ export function createPiAuthRoutes(deps: PiAuthRoutesDeps): Hono { providerId?: unknown; } | null; const providerId = typeof body?.providerId === "string" ? body.providerId : ""; - if (!piConfigured()) { - return c.json({ error: "The pi backend is not configured." }, 409); - } + if (!piConfigured()) return c.json(notConfigured, 409); if (!providerId || !(await allowedProviders()).includes(providerId)) { return c.json({ error: "Unknown provider." }, 400); } @@ -137,12 +142,14 @@ export function createPiAuthRoutes(deps: PiAuthRoutesDeps): Hono { } }) .get("/pi-auth/login/:id", async (c) => { + if (!piConfigured()) return c.json(notConfigured, 409); const auth = await getAuth(); const flow = auth.getFlow(c.req.param("id")); if (!flow) return c.json({ error: "Unknown login flow." }, 404); return c.json({ flow }); }) .delete("/pi-auth/login/:id", async (c) => { + if (!piConfigured()) return c.json(notConfigured, 409); const auth = await getAuth(); auth.cancelFlow(c.req.param("id")); return c.json({ ok: true }); @@ -154,6 +161,7 @@ export function createPiAuthRoutes(deps: PiAuthRoutesDeps): Hono { providerId?: unknown; } | null; const providerId = typeof body?.providerId === "string" ? body.providerId : ""; + if (!piConfigured()) return c.json(notConfigured, 409); if (!providerId || !(await allowedProviders()).includes(providerId)) { return c.json({ error: "Unknown provider." }, 400); } diff --git a/packages/ui-server/src/routes/web-search.ts b/packages/ui-server/src/routes/web-search.ts index 0e03392895..3977e5e6db 100644 --- a/packages/ui-server/src/routes/web-search.ts +++ b/packages/ui-server/src/routes/web-search.ts @@ -88,6 +88,8 @@ interface WebSearchConfigView { interface WebSearchRoutesDeps { agent: AgentConfig; + /** True while boot excluded pi as unavailable (#3817): the routes answer as if pi were not configured. */ + excluded?: () => boolean; /** Test seam — overrides the config file location. */ configPath?: string; /** Test seam — overrides the environment credential lookup. */ @@ -135,7 +137,7 @@ export function createWebSearchRoutes(deps: WebSearchRoutesDeps): Hono { const configPath = () => deps.configPath ?? resolveWebSearchConfigPath(env); const piConfigured = () => - Boolean(agent.piProfilesJson) || (agent.backend || "claude") === "pi"; + (Boolean(agent.piProfilesJson) || (agent.backend || "claude") === "pi") && !deps.excluded?.(); /** * The pi models in the picker. Malformed config cannot reach here — diff --git a/packages/ui-server/tests/degraded-backend.test.ts b/packages/ui-server/tests/degraded-backend.test.ts index 1ef3386f35..b269a836db 100644 --- a/packages/ui-server/tests/degraded-backend.test.ts +++ b/packages/ui-server/tests/degraded-backend.test.ts @@ -8,6 +8,8 @@ import { getSetting } from "../src/db/settings"; import { resolveAmbientPrincipal } from "../src/db/principals"; import { createWsHandlers } from "../src/ws/connection"; import type { WSContext } from "../src/ws/clients"; +import { createUiDb } from "../src/db/client"; +import { setSetting } from "../src/db/settings"; // The installed secondary SDK cannot satisfy this host floor. The real boot // probe must contain that failure and the real lazy registry must exclude it. @@ -39,6 +41,13 @@ test.each(["resolution", "runtime"] as const)("a secondary %s failure boots degr expect(status.backendAvailability.unavailable).toEqual([expect.objectContaining({ backendId: "pi", phase, message: expect.stringContaining(phase === "runtime" ? "999.0.0" : "not installed") })]); expect(getSetting(t.app.db, "boot.backendFailures", [])).toEqual(status.backendAvailability.unavailable); expect(observability.logs.find({ severity: "WARN" }).filter(log => String(log.body).includes("Backend pi unavailable:"))).toHaveLength(1); + // The excluded backend's auth and extension services stay unloaded too. + expect(await (await t.fetch("/api/pi-auth/providers")).json()).toEqual({ providers: [] }); + const json = { "content-type": "application/json" }; + expect((await t.fetch("/api/pi-auth/login", { method: "POST", headers: json, body: JSON.stringify({ providerId: "openai" }) })).status).toBe(409); + expect((await t.fetch("/api/pi-auth/logout", { method: "POST", headers: json, body: JSON.stringify({ providerId: "openai" }) })).status).toBe(409); + expect(await (await t.fetch("/api/web-search")).json()).toMatchObject({ configured: false, providers: [] }); + expect((await t.fetch("/api/web-search", { method: "PUT", headers: json, body: JSON.stringify({ enabled: ["exa"] }) })).status).toBe(409); const registry = t.app.wsHost.registry; expect((await registry.getBackends()).map(backend => backend.id)).toEqual(["claude"]); expect(await registry.getBackendById("pi")).toBeUndefined(); @@ -60,3 +69,26 @@ test.each(["resolution", "runtime"] as const)("a secondary %s failure boots degr expect(sent).toContainEqual(expect.objectContaining({ type: "result", isError: false })); } finally { start?.mockRestore(); requireSpy?.mockRestore(); await t?.teardown(); } }); + +// A repaired backend keeps its last recorded failure for the owner, and a +// malformed historical record is dropped rather than becoming a boot gate. +test("a repaired backend boots healthy and keeps its last failure; malformed history is dropped", async () => { + const lastFailure = { backendId: "pi", phase: "runtime", site: "probeBackendRuntimes", errorClass: "Error", + message: "pi SDK 1.0.0 is below the host floor 999.0.0", at: "2026-07-12T08:00:00.000Z" }; + let t: Awaited> | undefined; + try { + t = await createTestApp({ + env: { BRAIN_UI_PI_PROFILES: JSON.stringify([{ id: "pi-test", label: "Pi test", vendor: "openai", model: "gpt-test" }]) }, + prepare: brainPath => { + const db = createUiDb(brainPath.replace(/-brain$/, ".db")); + try { setSetting(db, "boot.backendFailures", [lastFailure, { backendId: "pi", phase: "bogus" }, "not-a-record", null]); } + finally { db.close(); } + }, + }); + const health = await (await t.fetch("/api/health")).json() as { status: string }; + expect(health.status).toBe("healthy"); + const status = await (await t.fetch("/api/status")).json() as { backendAvailability: { unavailable: unknown[]; lastFailures: unknown[] } }; + expect(status.backendAvailability.unavailable).toEqual([]); + expect(status.backendAvailability.lastFailures).toEqual([lastFailure]); + } finally { await t?.teardown(); } +}); diff --git a/packages/ui-server/tests/pi-auth-routes.test.ts b/packages/ui-server/tests/pi-auth-routes.test.ts index 7c93559562..c4661cfde6 100644 --- a/packages/ui-server/tests/pi-auth-routes.test.ts +++ b/packages/ui-server/tests/pi-auth-routes.test.ts @@ -102,6 +102,18 @@ describe("pi-auth routes", () => { expect(body.flow.userCode).toBe("ABCD-1234"); }); + test("a pi backend excluded at boot loads no auth service (#3817)", async () => { + const { importer, calls } = makeFakeModule(); + const routes = createPiAuthRoutes({ agent: agentFor({ BRAIN_UI_PI_PROFILES: PROFILES }), excluded: () => true, importer }); + expect(await (await routes.request("/pi-auth/providers")).json()).toEqual({ providers: [] }); + const post = (path: string) => routes.request(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ providerId: "openai-codex" }) }); + expect((await post("/pi-auth/login")).status).toBe(409); + expect((await post("/pi-auth/logout")).status).toBe(409); + expect((await routes.request("/pi-auth/login/flow-1")).status).toBe(409); + expect((await routes.request("/pi-auth/login/flow-1", { method: "DELETE" })).status).toBe(409); + expect(calls).toEqual([]); + }); + test("login rejects unknown providers and unconfigured deployments", async () => { const { importer } = makeFakeModule(); const unconfigured = createPiAuthRoutes({ agent: agentFor(), importer }); diff --git a/packages/ui-server/tests/web-search-routes.test.ts b/packages/ui-server/tests/web-search-routes.test.ts index 4a224ebbf7..ca74b27537 100644 --- a/packages/ui-server/tests/web-search-routes.test.ts +++ b/packages/ui-server/tests/web-search-routes.test.ts @@ -173,6 +173,17 @@ describe("GET /web-search", () => { }); }); +describe("a pi backend excluded at boot (#3817)", () => { + test("reports not-configured and refuses writes without touching the config", async () => { + const path = tempConfigPath(); + const app = createWebSearchRoutes({ agent: agentFor({ BRAIN_UI_PI_PROFILES: PROFILES }), configPath: path, env: CLEAN_ENV, excluded: () => true, + importer: async () => { throw new Error("an excluded backend is never loaded"); } }); + expect(await get(app)).toMatchObject({ configured: false, providers: [] }); + expect((await put(app, { enabled: ["exa"] })).status).toBe(409); + expect(existsSync(path)).toBe(false); + }); +}); + describe("PUT /web-search", () => { test("rejected when pi is not configured", async () => { const res = await put(appFor(), { enabled: { exa: true } });