diff --git a/services/ai-gateway/.env.example b/services/ai-gateway/.env.example index f3d0f73755..b843259f81 100644 --- a/services/ai-gateway/.env.example +++ b/services/ai-gateway/.env.example @@ -26,6 +26,14 @@ AI_GATEWAY_ENCRYPTION_KEY= # ----------------------------------------------------------------------------- # Optional # ----------------------------------------------------------------------------- +# May CHANGE accounts over the REST API (/api/v1): start and complete an +# authorization, remove an account. AI_GATEWAY_API_KEY above may only read them. +# Unset, the REST API is read-only and changing answers 403 `control_disabled`. +# Adding an account puts a subscription into the pool, so this is a key of its +# own — or set it to the same value as AI_GATEWAY_API_KEY to run with one. +# Never generated for development. Same generator as above. +# AI_GATEWAY_ADMIN_API_KEY= + # Where accounts.json lives. This file IS the credential pool — back it up. # AI_GATEWAY_DATA_DIR=.data diff --git a/services/ai-gateway/README.md b/services/ai-gateway/README.md index 40902da5c1..0e1c169cdb 100644 --- a/services/ai-gateway/README.md +++ b/services/ai-gateway/README.md @@ -20,10 +20,13 @@ one that serves the whole pool. | **Two providers, one shape** | Anthropic and OpenAI differ in their OAuth callback, their identity claims and their usage payload; the panel and the endpoint do not | | **Connects on its own** | A ChatGPT account connects through OpenAI's device sign-in, and a Claude account — when the panel is opened on localhost — through a redirect straight back to the gateway; there is no code to carry back | | **Token refresh** | Each account's token is refreshed on a schedule of its own, spread across the pool and spaced out per vendor, with a shared-expiry exception; while another account can take new work, one whose planned refresh (`refresh_at`) is closer than the hand-out floor waits for it; transient failures pause retries, an authenticated usage rejection refreshes that exact token generation through the same single-flight path, and refused refresh grants require a new sign-in | -| **Usage in view** | Each account's session and weekly windows — plus any per-model cap the vendor reports — as live bars coloured by how much is spent (green, yellow from half, orange from three quarters, red at the ceiling), beside a short grey one counting the window down to its rollover, which turns green when that is within the hour. An account whose session or weekly window is spent greys out like a disabled row until that window rolls over — only the look: its row menu keeps working | +| **Usage in view** | Each account's session and weekly windows — plus any per-model cap the vendor reports — as live bars coloured by how much is spent (green, yellow from half, orange from three quarters, red at the ceiling), beside a short grey one counting the window down to its rollover | +| **When an account is back** | An account whose session or weekly window is spent is **Limit reached**, and comes back when its *last* spent window rolls over — a session that resets in five minutes beside a spent week is back in three days, and the row says so (**Resets in 3 days**) and reads the week's clock in full strength while the session's steps back. Within the hour the clock turns green. The row greys out like a disabled row until then — only the look: its menu keeps working, and so do its state and its clock | +| **Grouped by what each account is doing** | Vendors together, in the catalog's order; inside a vendor the accounts that can take work, then the ones that hit their limit — soonest back first, no known return last — then the ones that need a person (**Needs reauthentication**, **Last call failed**). The filter and the search know the same states | +| **A REST API for accounts** | `/api/v1/accounts` lists and reads the pool, with the same state and return time the panel shows; with a second key it also starts and completes an authorization and removes an account — see [Manage accounts over REST](#manage-accounts-over-rest) | | **The plan, named** | Each account's plan as its vendor sells it — Max 20x, Pro, Plus, Pro Lite — read from Anthropic's profile and from ChatGPT's own usage answer | | **Encrypted at rest** | AES-256-GCM under `AI_GATEWAY_ENCRYPTION_KEY`; a tampered store fails loudly rather than decrypting to something plausible | -| **One lock, on the tokens** | The token endpoints are behind an API key. The panel has no login of its own — whatever fronts this service decides who reaches it | +| **Locks on the machine doors** | The token endpoints and `/api/v1` are behind API keys — one that reads, and a separate admin key that changes the pool. The panel has no login of its own — whatever fronts this service decides who reaches it | ## Run it @@ -87,6 +90,125 @@ unless Codex is listening, so you paste the whole address bar. Every flow is the public OAuth client each vendor's own CLI uses, with a PKCE S256 challenge. Closing the dialog abandons the attempt. +## Manage accounts over REST + +Everything the panel shows about an account — and the three things it lets you do to +one — is also a REST API, for a script or another service. It lives under `/api/v1`, on +its own prefix, so a proxy that lets machines reach `/api/tokens*` can let them reach +this the same way without opening a single panel route. + +Two keys, because reading a pool and changing it are not the same trust: + +| Key | May | Where it is set | +| --- | --- | --- | +| `AI_GATEWAY_API_KEY` — the token key | **Read** accounts (`GET`) | Required; it is the key the token endpoints already ask for. Everything an account's figures show is a subset of what that key reads from `/api/tokens` already | +| `AI_GATEWAY_ADMIN_API_KEY` — the admin key | Read, and **change**: start and complete an authorization, remove an account | Optional. Without it, changing answers `403 control_disabled` and nothing can be added or removed over the API | + +Adding an account puts someone else's subscription into the pool the platform draws +from, which is not something every holder of a token key should be able to do — so the +two are apart by default. To run with one key, set both variables to the same value. + +Send a key as `Authorization: Bearer ` or `x-api-key: `. A missing or wrong key +is `401 invalid_api_key`; a right key that may not do this is `403` +(`admin_key_required`, or `control_disabled` while no admin key is set). Every answer from +these routes, a refusal included, is `Cache-Control: no-store`, and names are snake_case +like the token endpoints'. + +```bash +curl localhost:3004/api/v1/accounts -H "Authorization: Bearer $AI_GATEWAY_API_KEY" +``` + +```json +{ + "accounts": [ + { + "id": "gateway-account-1", + "provider": "anthropic", + "label": "you@example.com", + "account_email": "you@example.com", + "subscription": { "plan": "max", "tier": "5x" }, + "status": "active", + "state": "limited", + "limited_until": "2026-10-18T10:00:00.000Z", + "expires_at": "2026-10-21T09:40:00.000Z", + "scopes": "org:create_api_key user:profile user:inference", + "created_at": "2026-09-26T10:00:00.000Z", + "last_refreshed_at": "2026-10-15T07:12:30.000Z", + "usage": { + "checked_at": "2026-10-15T10:00:00.000Z", + "stale": false, + "limited": null, + "windows": [ + { + "kind": "session", + "label": null, + "utilization": 100, + "resets_at": "2026-10-15T10:05:00.000Z", + "window_seconds": 18000, + "blocking": true + }, + { + "kind": "weekly", + "label": null, + "utilization": 100, + "resets_at": "2026-10-18T10:00:00.000Z", + "window_seconds": 604800, + "blocking": true + } + ] + } + } + ] +} +``` + +No token, refresh token or other credential is ever in an answer; the token endpoints are +the only door that hands those out. + +**`state`** says what the account is now, in one word, and is what the panel groups on: + +| `state` | Means | +| --- | --- | +| `available` | Nothing stops it taking work, as far as its latest reading shows | +| `limited` | Its session or weekly window is spent. `limited_until` is when it is back: the **latest** rollover among its spent windows — five minutes for a spent session beside a spent week is still three days. Null when a spent window has no stated rollover, or when only the vendor's own `usage.limited` flag says so | +| `expired` | The vendor refused a refresh; someone must sign the account in again. `status` says the same | +| `error` | The latest call to the vendor failed; the gateway keeps trying. `status` says the same | + +`status` stays the credential's own (`active`, `expired`, `error`), as on the token +endpoints; `state` refines `active` into `available` and `limited`. A window's +`blocking` is true when it is why the account is limited — spent, a session or weekly +window rather than a per-model cap, and not yet rolled over. A window whose rollover +has already passed stops blocking at once, before the next reading says so, and +`usage.stale` turns true: the figures are those of the window before. This describes the +account as its own reading shows it; whether the pool will hand it out for *new* work — +which also weighs how fresh the reading is and how close its token is to refresh — is +still the token endpoints' `available`. + +| Method | Path | Key | Purpose | +| --- | --- | --- | --- | +| `GET` | `/api/v1/accounts` | token or admin | The pool, oldest account first. `?provider=anthropic\|openai` and `?state=available\|limited\|expired\|error` narrow it; an unknown value is `400 invalid_request` | +| `GET` | `/api/v1/accounts/{id}` | token or admin | One account, or `404 unknown_account` | +| `POST` | `/api/v1/authorizations` | admin | Start an authorization: `{"provider": "anthropic" \| "openai", "label"?, "account_id"?, "method"?: "browser"}`. `account_id` signs an existing account in again. Answers `201` with how it finishes — `flow: "device"` (`verification_url`, `user_code`, `expires_at`, `poll_interval_seconds`: approve the code in a browser, and the gateway connects the account itself) or `flow: "paste"` (`authorize_url`, `paste_style`: approve, then send what the browser shows) | +| `GET` | `/api/v1/authorizations/{state}` | admin | Where it stands: `pending`, `connected` (with the `account`) or `failed` (with a `code`). For a device code each read may ask the vendor, so poll no faster than `poll_interval_seconds` | +| `POST` | `/api/v1/authorizations/{state}/complete` | admin | Finish a paste flow: `{"pasted": ""}`. Answers `201` with the `account` | +| `DELETE` | `/api/v1/accounts/{id}` | admin | Remove an account and its stored tokens: `204`, or `404 unknown_account` | + +A script never gets a redirect flow: that one needs a browser on a loopback address of +the gateway's own machine, which only the panel can offer. For a Claude account it asks +for the `paste` flow, and a ChatGPT account for its device code. + +```bash +# Add a ChatGPT account from a script: approve the code in a browser, and wait. +curl -X POST localhost:3004/api/v1/authorizations \ + -H "Authorization: Bearer $AI_GATEWAY_ADMIN_API_KEY" \ + -H "Content-Type: application/json" -d '{"provider": "openai"}' +curl localhost:3004/api/v1/authorizations/$STATE \ + -H "Authorization: Bearer $AI_GATEWAY_ADMIN_API_KEY" +``` + +Behind a proxy that fronts the panel with a sign-in, `/api/v1/*` has to be passed past that +sign-in the way `/api/tokens*` is — it carries its own keys, and nothing else guards it. + ## Use the tokens Ask for one vendor — a caller almost always wants one, and a client pointed at @@ -271,6 +393,11 @@ offline. Token and copied-command responses use `Cache-Control: no-store`. | `DELETE` | `/api/accounts/{id}` | none | Remove an account | | `GET` | `/api/tokens/{provider}` | API key | One vendor's tokens, in cc-gateway's shape | | `GET` | `/api/tokens` | API key | The whole pool, each token named by vendor | +| `GET` | `/api/v1/accounts`, `/api/v1/accounts/{id}` | API key or admin key | The pool and one account, without any credential — [Manage accounts over REST](#manage-accounts-over-rest) | +| `POST` | `/api/v1/authorizations` | admin key | Start an authorization (device code or paste) | +| `GET` | `/api/v1/authorizations/{state}` | admin key | Where an authorization stands | +| `POST` | `/api/v1/authorizations/{state}/complete` | admin key | Finish a paste flow | +| `DELETE` | `/api/v1/accounts/{id}` | admin key | Remove an account | | `GET` | `/api/health` | none | Liveness probe | "None" means the app checks nothing — see [Who may open the panel](#who-may-open-the-panel). @@ -279,7 +406,8 @@ offline. Token and copied-command responses use `Cache-Control: no-store`. | Variable | Default | What it is | | --- | --- | --- | -| `AI_GATEWAY_API_KEY` | — | Guards every `GET /api/tokens*`. Required | +| `AI_GATEWAY_API_KEY` | — | Guards every `GET /api/tokens*`, and may read accounts on `/api/v1`. Required | +| `AI_GATEWAY_ADMIN_API_KEY` | — | May also change accounts on `/api/v1`: start and complete an authorization, remove an account. Optional; unset, the REST API is read-only. Set it to the same value as `AI_GATEWAY_API_KEY` to run with one key. Never generated for development | | `AI_GATEWAY_ENCRYPTION_KEY` | — | 32 base64-encoded bytes; encrypts the stored tokens. Required, and irreplaceable — a new key cannot read the old store | | `AI_GATEWAY_DATA_DIR` | `.data` | Where `accounts.json` lives. Back this up; it is the pool | | `AI_GATEWAY_REFRESH_INTERVAL_SECONDS` | `300` | Cadence of the background refresh pass | @@ -309,16 +437,21 @@ its `/api/tokens/` endpoint comes with the id. A new id needs a | `backend/accounts.ts` | The lifecycle: authorize, refresh, read usage, hand out | | `backend/store.ts` | The account document, written atomically and serialized | | `backend/routes.ts` | The HTTP surface, and the API key that guards the tokens | +| `backend/accounts-api.ts` | The REST door for accounts under `/api/v1`, with its read key and its admin key | +| `backend/account-state.ts` | What state an account is in, and until when it is limited — a pure function of the reading and a clock | | `backend/gateway.ts` | Composition root; used by `server.ts` and the Vite dev plugin alike | | `app/` | The panel — one screen, no door, built on `@tale/ui` | -The panel is one screen in the documentation frame's chrome: an `h-13` header -strip carrying the Tale mark, the service's name and the language / theme / -repository cluster, over one account table built as a list page — the same -`useListPage` state Projects and Automations run on, so it scrolls, loads and -counts its rows the way they do. Language is a stored preference here, not a -path segment — the panel ships as one untranslated tree — so the shared -`LanguageSwitcher` runs in its state-driven mode. +The panel is one screen in the platform's page chrome: an `h-13` header strip +carrying the service's name — set as every platform page title is, in +`AdaptiveHeaderTitle` — and the language / theme / repository cluster, over one +account table built as a list page — the same `useListPage` state Projects and +Automations run on, so it scrolls, loads and counts its rows the way they do. The +rows are ordered vendor, then state, then soonest back (`app/lib/account-order.ts`), +and `backend/account-state.ts` is the one place that decides what state an account +is in — the panel and `/api/v1` both read its answer. Language is a stored +preference here, not a path segment — the panel ships as one untranslated tree — so +the shared `LanguageSwitcher` runs in its state-driven mode. ## Develop diff --git a/services/ai-gateway/app/components/accounts-screen.test.tsx b/services/ai-gateway/app/components/accounts-screen.test.tsx index e95044cdea..26714efb7b 100644 --- a/services/ai-gateway/app/components/accounts-screen.test.tsx +++ b/services/ai-gateway/app/components/accounts-screen.test.tsx @@ -1,6 +1,13 @@ import { LocaleProvider } from '@tale/ui/i18n/locale-provider'; import { TooltipProvider } from '@tale/ui/tooltip'; -import { act, fireEvent, render, screen, within } from '@testing-library/react'; +import { + act, + fireEvent, + render, + screen, + waitFor, + within, +} from '@testing-library/react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { ApiError, type AccountView, type UsageWindow } from '@/app/lib/api'; @@ -29,6 +36,8 @@ const account: AccountView = { accountEmail: 'seat@example.com', subscription: { plan: 'max', tier: '20x' }, status: 'active', + state: 'available', + limitedUntil: null, expiresAt: null, scopes: null, createdAt: '2026-09-24T10:00:00.000Z', @@ -36,12 +45,37 @@ const account: AccountView = { usage: null, }; +// The panel reads the clock for its countdowns; every figure below is fixed +// against it. +const NOW = Date.parse('2026-10-15T10:00:00.000Z'); +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; +const at = (offsetMs: number) => new Date(NOW + offsetMs).toISOString(); + +/** One window, resetting `resetsInMs` from now. */ +function win( + kind: UsageWindow['kind'], + utilization: number, + resetsInMs: number, + overrides: Partial = {}, +): UsageWindow { + return { + kind, + label: null, + utilization, + resetsAt: at(resetsInMs), + windowSeconds: kind === 'session' ? 5 * 60 * 60 : 7 * 24 * 60 * 60, + blocking: false, + ...overrides, + }; +} + /** An account in the pool whose reading holds these windows. */ function reading( label: string, - windows: Array< - Pick & Partial - >, + windows: UsageWindow[], + overrides: Partial = {}, ): AccountView { return { ...account, @@ -49,18 +83,29 @@ function reading( label, accountEmail: null, usage: { - windows: windows.map((window) => ({ - label: null, - resetsAt: '2026-09-24T12:00:00.000Z', - windowSeconds: 5 * 60 * 60, - ...window, - })), - checkedAt: '2026-09-24T10:00:00.000Z', + windows, + checkedAt: at(-MINUTE), stale: false, + limited: null, }, + ...overrides, }; } +/** A limited account, back at `limitedUntil`; its spent windows carry the flag. */ +function limited( + label: string, + windows: UsageWindow[], + limitedUntil: string | null, + overrides: Partial = {}, +): AccountView { + return reading(label, windows, { + state: 'limited', + limitedUntil, + ...overrides, + }); +} + /** The table row a label sits in. */ function rowOf(label: string): HTMLElement { const row = screen.getByText(label).closest('tr'); @@ -92,9 +137,12 @@ function show(accounts: AccountView[] | null, error: Error | null) { describe('AccountsScreen', () => { beforeEach(async () => { await i18n.changeLanguage('en'); + // Only the clock: the table's own timers keep running for real. + vi.useFakeTimers({ toFake: ['Date'], now: NOW }); }); afterEach(() => { + vi.useRealTimers(); // Reset, not clear: a test that stops early must not leave its queued // answers for the next one to receive. vi.resetAllMocks(); @@ -183,19 +231,31 @@ describe('AccountsScreen', () => { expect(onReload).toHaveBeenCalledTimes(1); }); - it('greys a row whose session or weekly window is spent, and no other', () => { + it('greys a row whose quota is spent, and no other', () => { show( [ - reading('Session spent', [ - { kind: 'session', utilization: 100 }, - { kind: 'weekly', utilization: 40 }, - ]), - reading('Week spent', [{ kind: 'weekly', utilization: 100 }]), + limited( + 'Session spent', + [ + win('session', 100, 5 * MINUTE, { blocking: true }), + win('weekly', 40, 3 * DAY), + ], + at(5 * MINUTE), + ), + limited( + 'Week spent', + [win('weekly', 100, 3 * DAY, { blocking: true })], + at(3 * DAY), + ), reading('Model capped', [ - { kind: 'session', utilization: 20 }, - { kind: 'scoped', label: 'Fable', utilization: 100 }, + win('session', 20, 2 * HOUR), + win('scoped', 100, 3 * DAY, { label: 'Fable' }), ]), - reading('Nearly spent', [{ kind: 'session', utilization: 99.6 }]), + reading('Nearly spent', [win('session', 99.6, 2 * HOUR)]), + reading('Lapsed', [win('weekly', 100, 3 * DAY)], { + status: 'expired', + state: 'expired', + }), ], null, ); @@ -204,6 +264,34 @@ describe('AccountsScreen', () => { expect(rowOf('Week spent').className).toContain('opacity-60'); expect(rowOf('Model capped').className).not.toContain('opacity'); expect(rowOf('Nearly spent').className).not.toContain('opacity'); + // A credential that needs attention is its own state; its stale figures + // do not also make it look switched off. + expect(rowOf('Lapsed').className).not.toContain('opacity'); + }); + + it('spares the state and the clock from the grey, since they are why the row is grey', () => { + show( + [ + limited( + 'Week spent', + [win('weekly', 100, 3 * DAY, { blocking: true })], + at(3 * DAY), + ), + ], + null, + ); + + const row = rowOf('Week spent'); + const cellOf = (text: string) => { + const cell = within(row).getByText(text).closest('td'); + if (!cell) throw new Error(`No cell holds ${text}`); + return cell; + }; + // The row dims every cell but the menu's and the ones that opt out. + expect(row.className).toContain(':not(.stays-bright)'); + expect(cellOf('Limit reached').className).toContain('stays-bright'); + expect(cellOf('3 days').className).toContain('stays-bright'); + expect(cellOf('Week spent').className).not.toContain('stays-bright'); }); it('keeps every action on a spent row working', async () => { @@ -213,7 +301,16 @@ describe('AccountsScreen', () => { configurable: true, value: { writeText }, }); - show([reading('Week spent', [{ kind: 'weekly', utilization: 100 }])], null); + show( + [ + limited( + 'Week spent', + [win('weekly', 100, 3 * DAY, { blocking: true })], + at(3 * DAY), + ), + ], + null, + ); fireEvent.keyDown( within(rowOf('Week spent')).getByRole('button', { @@ -235,6 +332,266 @@ describe('AccountsScreen', () => { }); }); + it('dims a stale reading once: by itself when the row is not receded, not again when it is', () => { + const stale = (windows: UsageWindow[]) => ({ + windows, + checkedAt: at(-10 * MINUTE), + stale: true, + limited: null, + }); + const spent = [win('weekly', 100, 3 * DAY, { blocking: true })]; + const room = [win('weekly', 10, 3 * DAY)]; + show( + [ + limited('Limited stale', spent, at(3 * DAY), { usage: stale(spent) }), + reading('Ready stale', room, { usage: stale(room) }), + ], + null, + ); + + const figures = (label: string) => { + const grid = rowOf(label).querySelector( + 'div[class*="grid-cols-[4rem_auto]"]', + ); + if (!grid) throw new Error(`No usage figures in ${label}`); + return grid; + }; + // The receded row already carries the dim; stacking the reading's own + // on it leaves a third of full strength. + expect(figures('Limited stale').className).not.toContain('opacity-60'); + expect(rowOf('Limited stale').className).toContain('opacity-60'); + // A row that is not receded dims the old figures itself. + expect(figures('Ready stale').className).toContain('opacity-60'); + }); + + describe('when a limited account comes back', () => { + // The case the column exists for: the session window is back in five + // minutes, the week in three days — and the account is back in three days. + const both = limited( + 'Both spent', + [ + win('session', 100, 5 * MINUTE, { blocking: true }), + win('weekly', 100, 3 * DAY, { blocking: true }), + ], + at(3 * DAY), + ); + + it('says three days in words, not five minutes', () => { + show([both], null); + const row = within(rowOf('Both spent')); + expect(row.getByText('Limit reached')).toBeTruthy(); + expect(row.getByText('Resets in 3 days')).toBeTruthy(); + expect(row.queryByText('Resets in 5 minutes')).toBeNull(); + }); + + it('reads the week’s clock in full strength and the session’s as one that only waits', () => { + show([both], null); + const row = within(rowOf('Both spent')); + const clock = (text: string) => { + const element = row.getByText(text).parentElement; + if (!element) throw new Error(`No clock holds ${text}`); + return element; + }; + expect(clock('3 days').className).toContain('font-medium'); + expect(clock('5 minutes').className).not.toContain('font-medium'); + // Nothing to celebrate yet: the session is back soon, the account is not. + expect(clock('5 minutes').className).not.toContain('text-success'); + expect(clock('3 days').className).not.toContain('text-success'); + }); + + it('reads the session’s clock when only the session is spent', () => { + show( + [ + limited( + 'Session spent', + [ + win('session', 100, 5 * MINUTE, { blocking: true }), + win('weekly', 41, 3 * DAY), + ], + at(5 * MINUTE), + ), + ], + null, + ); + const row = within(rowOf('Session spent')); + expect(row.getByText('Resets in 5 minutes')).toBeTruthy(); + expect(row.getByText('5 minutes').parentElement?.className).toContain( + 'font-medium', + ); + expect(row.getByText('3 days').parentElement?.className).not.toContain( + 'font-medium', + ); + }); + + it('tints the return only inside the hour — and never a countdown nothing waits on', () => { + show( + [ + limited( + 'Back soon', + [ + win('session', 100, 25 * MINUTE, { blocking: true }), + win('weekly', 40, 3 * DAY), + ], + at(25 * MINUTE), + ), + reading('Ready', [ + win('session', 30, 20 * MINUTE), + win('weekly', 40, 3 * DAY), + ]), + ], + null, + ); + const soon = within(rowOf('Back soon')); + expect(soon.getByText('25 minutes').parentElement?.className).toContain( + 'text-success', + ); + expect(soon.getByText('3 days').parentElement?.className).not.toContain( + 'text-success', + ); + // A window that merely resets soon, on an account with quota left, is + // an ordinary countdown. + const ready = within(rowOf('Ready')); + expect( + ready.getByText('20 minutes').parentElement?.className, + ).not.toContain('text-success'); + expect(ready.getByText('Available')).toBeTruthy(); + }); + + it('says so when no return is known', () => { + show( + [ + limited( + 'Unknown', + [win('weekly', 100, 3 * DAY, { blocking: true, resetsAt: null })], + null, + ), + ], + null, + ); + expect( + within(rowOf('Unknown')).getByText('Reset time unknown'), + ).toBeTruthy(); + }); + + it('says now for a rollover that has come, before the next reading catches up', () => { + show( + [ + reading('Rolled over', [win('session', 100, -MINUTE)], { + usage: { + windows: [win('session', 100, -MINUTE)], + checkedAt: at(-10 * MINUTE), + stale: true, + limited: null, + }, + }), + ], + null, + ); + const row = within(rowOf('Rolled over')); + expect(row.getByText('Now')).toBeTruthy(); + expect(row.getByText('Available')).toBeTruthy(); + }); + }); + + it('lists a vendor’s accounts together, and inside it by state, then by who is back first', () => { + show( + [ + reading('Gpt ready', [win('weekly', 10, 2 * DAY)], { + provider: 'openai', + }), + reading('Claude broken', [], { status: 'error', state: 'error' }), + limited( + 'Claude in 3 days', + [win('weekly', 100, 3 * DAY, { blocking: true })], + at(3 * DAY), + ), + reading('Claude lapsed', [], { status: 'expired', state: 'expired' }), + limited( + 'Claude in 5 minutes', + [win('session', 100, 5 * MINUTE, { blocking: true })], + at(5 * MINUTE), + ), + reading('Claude ready', [win('weekly', 10, 2 * DAY)]), + ], + null, + ); + + const rows = screen.getAllByRole('row').map((row) => row.textContent ?? ''); + const position = (label: string) => + rows.findIndex((text) => text.includes(label)); + const ordered = [ + 'Claude ready', + 'Claude in 5 minutes', + 'Claude in 3 days', + 'Claude lapsed', + 'Claude broken', + 'Gpt ready', + ]; + expect(ordered.map(position)).toEqual( + ordered.map(position).toSorted((a, b) => a - b), + ); + expect(ordered.map(position).every((index) => index > 0)).toBe(true); + }); + + it('finds an account by the state the reader sees', async () => { + show( + [ + reading('Claude ready', [win('weekly', 10, 2 * DAY)]), + limited( + 'Claude spent', + [win('weekly', 100, 3 * DAY, { blocking: true })], + at(3 * DAY), + ), + ], + null, + ); + + const search = screen.getByRole('textbox', { name: 'Search accounts' }); + fireEvent.focus(search); + fireEvent.change(search, { target: { value: 'limit' } }); + + await waitFor(() => { + expect(screen.queryByText('Claude ready')).toBeNull(); + }); + expect(screen.getByText('Claude spent')).toBeTruthy(); + }); + + it('filters by the four states the rows are grouped in', async () => { + show( + [ + reading('Claude ready', [win('weekly', 10, 2 * DAY)]), + limited( + 'Claude spent', + [win('weekly', 100, 3 * DAY, { blocking: true })], + at(3 * DAY), + ), + reading('Claude lapsed', [], { status: 'expired', state: 'expired' }), + ], + null, + ); + + fireEvent.click(screen.getByRole('button', { name: 'Filter' })); + // The facet lists the states best to worst, as the rows sit. + const status = await screen.findByRole('button', { name: /Status/ }); + fireEvent.click(status); + await screen.findAllByRole('checkbox'); + for (const name of [ + 'Available', + 'Limit reached', + 'Needs reauthentication', + 'Last call failed', + ]) { + expect(screen.getByRole('checkbox', { name })).toBeTruthy(); + } + + fireEvent.click(screen.getByRole('checkbox', { name: 'Limit reached' })); + await waitFor(() => { + expect(screen.queryByText('Claude ready')).toBeNull(); + }); + expect(screen.getByText('Claude spent')).toBeTruthy(); + expect(screen.queryByText('Claude lapsed')).toBeNull(); + }); + it('keeps an action’s own failure for anything else', async () => { api.command.mockRejectedValueOnce(unreachable()); vi.spyOn(console, 'error').mockImplementation(() => undefined); diff --git a/services/ai-gateway/app/components/accounts-screen.tsx b/services/ai-gateway/app/components/accounts-screen.tsx index c72d3db0a8..39c33af2a6 100644 --- a/services/ai-gateway/app/components/accounts-screen.tsx +++ b/services/ai-gateway/app/components/accounts-screen.tsx @@ -20,14 +20,15 @@ import type { ColumnDef, Row } from '@tanstack/react-table'; import { Copy, KeyRound, Plus, RefreshCw, Trash2 } from 'lucide-react'; import { useCallback, useMemo, useState } from 'react'; +import { compareAccounts } from '@/app/lib/account-order'; import { + ACCOUNT_STATES, gatewayApi, isSignedOut, type AccountView, type ProviderId, } from '@/app/lib/api'; import { reloadPage } from '@/app/lib/leave-for'; -import { planSpent } from '@/app/lib/usage-windows'; import { useT } from '@/lib/i18n/client'; import { AddAccountDialog, type AddAccountTarget } from './add-account-dialog'; @@ -38,22 +39,28 @@ import { ResetsCell } from './resets-cell'; import { StatusCell } from './status-cell'; import { UsageCell } from './usage-cell'; -/** The order the status filter offers, worst last. */ -const STATUS_ORDER = ['active', 'expired', 'error'] as const; +/** + * The class a column carries to say its cells are the explanation of a dimmed + * row, not part of what recedes. A marker the row's own selector reads. + */ +const STAYS_BRIGHT = 'stays-bright'; /** * An account whose session or weekly window is spent recedes the way a * disabled row does, until that window rolls over. * * Only the look changes. Nothing about the account is switched off: it keeps - * its place in the order, its figures stay readable — the reason it is spent, - * and the countdown to when it is not — and its menu keeps full strength, - * because every action in it still works. The menu is the last column, so the - * dim stops one cell short of the end of the row. + * its place in the order, and its menu keeps full strength, because every + * action in it still works. The menu is the last column, so the dim stops one + * cell short of the end of the row. Two cells are spared as well — the state + * and the clock — because they are why the row is dimmed and when it stops + * being: a dimmed explanation would be a dimmed row nobody can account for. */ -function spentRowClassName(row: Row): string { - return planSpent(row.original.usage?.windows ?? []) - ? '[&>td:not(:last-child)]:opacity-60' +function limitedRowClassName(row: Row): string { + // Spelled out whole: Tailwind finds a class by reading it in the source, so + // one assembled from `STAYS_BRIGHT` would never be generated. + return row.original.state === 'limited' + ? '[&>td:not(:last-child):not(.stays-bright)]:opacity-60' : ''; } @@ -197,19 +204,25 @@ export function AccountsScreen({ }, { id: 'status', - accessorFn: (account) => account.status, + accessorFn: (account) => account.state, header: t('columns.status'), - // A glyph and one short phrase. Sized so the common labels sit on one - // line; the longest ("Letzter Aufruf fehlgeschlagen", "Réautorisation - // nécessaire") wrap to two, which the row already has room for — a - // wider column would be empty gutter on every other row. + // A glyph and one short phrase, and under it, for an account that has + // hit its limit, when it comes back. Sized so the common labels sit + // on one line; the longest ("Letzter Aufruf fehlgeschlagen", + // "Réautorisation nécessaire") wrap to two, which the row already has + // room for — a wider column would be empty gutter on every other row. size: 170, // `icon-text`: the loaded cell is a glyph plus one phrase, not a pill. meta: { - className: 'overflow-hidden', + className: `overflow-hidden ${STAYS_BRIGHT}`, skeleton: { type: 'icon-text', iconGap: 2 }, }, - cell: ({ row }) => , + cell: ({ row }) => ( + + ), }, { id: 'usage', @@ -220,7 +233,12 @@ export function AccountsScreen({ // column needs at the table's narrowest. size: 250, meta: { skeleton: { type: 'text', lines: 2 } }, - cell: ({ row }) => , + cell: ({ row }) => ( + + ), }, { id: 'resets', @@ -232,9 +250,12 @@ export function AccountsScreen({ // "2 Tage") fit whole at the narrowest, and the rare longest // ("quelques secondes", the last minute) truncates onto `title`. size: 160, - meta: { skeleton: { type: 'text', lines: 2 } }, + meta: { className: STAYS_BRIGHT, skeleton: { type: 'text', lines: 2 } }, cell: ({ row }) => ( - + ), }, { @@ -323,9 +344,10 @@ export function AccountsScreen({ { key: 'status', title: t('filters.status'), - options: STATUS_ORDER.map((status) => ({ - value: status, - label: tStatus(status), + // Best to worst, the order the rows sit in within a vendor. + options: ACCOUNT_STATES.map((state) => ({ + value: state, + label: tStatus(state), })), selectedValues: statusFilter, onChange: setStatusFilter, @@ -345,13 +367,9 @@ export function AccountsScreen({ * box and the count footer work on, the way Projects hands its list the * rows its team facet leaves. * - * The order is the pool's own shape rather than an alphabet — vendors in - * the catalog's order, and inside a vendor the accounts by address. An - * operator opens this screen to answer "how is my Claude pool doing", which - * a vendor's rows sitting together answers in one glance; sorting on the - * address rather than the label keeps a renamed account where its e-mail - * says it belongs. The comparison runs through `localeCompare` in the - * reader's own locale, so an umlaut sorts where that reader expects it. + * The order is the pool's own shape rather than an alphabet: vendors in the + * catalog's order, inside a vendor what each account is doing, and inside a + * state the soonest to come back first — see `compareAccounts`. */ const rows = useMemo(() => { const matches = (accounts ?? []).filter((account) => { @@ -361,25 +379,10 @@ export function AccountsScreen({ ) { return false; } - return statusFilter.length === 0 || statusFilter.includes(account.status); + return statusFilter.length === 0 || statusFilter.includes(account.state); }); - const providerRank = (id: ProviderId) => { - const index = providers.indexOf(id); - // A provider the catalog no longer offers still has rows; park them - // after the ones it does rather than at the top. - return index === -1 ? providers.length : index; - }; - - return matches.toSorted((a, b) => { - const byProvider = providerRank(a.provider) - providerRank(b.provider); - if (byProvider !== 0) return byProvider; - return (a.accountEmail ?? a.label).localeCompare( - b.accountEmail ?? b.label, - locale, - { sensitivity: 'base' }, - ); - }); + return matches.toSorted(compareAccounts(providers, locale)); }, [accounts, locale, providerFilter, providers, statusFilter]); /** @@ -387,9 +390,10 @@ export function AccountsScreen({ * state, so this table pages and counts exactly the way Projects and * Automations do: the rows scroll inside the frame, more load as the reader * nears the end, and the frame closes on "Showing all N accounts" (or - * "N of M" while a search narrows it). The provider rides as a searched - * value too, so "claude" or "chatgpt" finds a vendor's accounts by the name - * the reader sees rather than by the id the row carries. + * "N of M" while a search narrows it). The provider and the state ride as + * searched values too, so "claude" or "chatgpt" finds a vendor's accounts, + * and "limit" the ones that hit theirs, by the words the reader sees rather + * than by the ids the row carries. */ const list = useListPage({ dataSource: { type: 'query', data: isLoading ? undefined : rows }, @@ -399,6 +403,7 @@ export function AccountsScreen({ 'label', 'accountEmail', (account) => tProviders(account.provider), + (account) => tStatus(account.state), ], placeholder: t('searchPlaceholder'), }, @@ -485,7 +490,7 @@ export function AccountsScreen({ // with a session that ran out, only a page load gets back in. error={accounts === null ? error : null} onRetry={signedOut ? reloadPage : onReload} - rowClassName={spentRowClassName} + rowClassName={limitedRowClassName} /> diff --git a/services/ai-gateway/app/components/add-account-dialog.test.tsx b/services/ai-gateway/app/components/add-account-dialog.test.tsx index ecb607a6a4..6e0b3dfcbb 100644 --- a/services/ai-gateway/app/components/add-account-dialog.test.tsx +++ b/services/ai-gateway/app/components/add-account-dialog.test.tsx @@ -27,6 +27,8 @@ const account: AccountView = { accountEmail: 'you@example.com', subscription: { plan: 'plus', tier: null }, status: 'active', + state: 'available', + limitedUntil: null, expiresAt: null, scopes: null, createdAt: '2026-09-24T10:00:00.000Z', diff --git a/services/ai-gateway/app/components/panel-header.test.tsx b/services/ai-gateway/app/components/panel-header.test.tsx new file mode 100644 index 0000000000..4f6a49499d --- /dev/null +++ b/services/ai-gateway/app/components/panel-header.test.tsx @@ -0,0 +1,71 @@ +import { LocaleProvider } from '@tale/ui/i18n/locale-provider'; +import { TooltipProvider } from '@tale/ui/tooltip'; +import { render, screen } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { i18n } from '@/lib/i18n/i18n'; + +import { PanelHeader } from './panel-header'; + +// The two pickers read the app's router and theme provider, which the panel +// mounts above the screen; the strip itself has nothing to say about them. +vi.mock('@tale/ui/theme-switcher', () => ({ ThemeSwitcher: () => null })); +vi.mock('@tale/ui/language-switcher', () => ({ LanguageSwitcher: () => null })); + +function show() { + return render( + + + + + , + ); +} + +describe('PanelHeader', () => { + beforeEach(async () => { + await i18n.changeLanguage('en'); + }); + + it('names the service in the type every platform page title is set in', () => { + show(); + const title = screen.getByRole('heading', { level: 1, name: 'AI Gateway' }); + // `AdaptiveHeaderTitle`'s own classes — what "Automations" and + // "Knowledge" carry — rather than a size and weight of this panel's own. + expect(title.className).toContain('text-base'); + expect(title.className).toContain('font-semibold'); + expect(title.className).toContain('text-foreground'); + }); + + it('carries no logo — the name beside it already says whose panel this is', () => { + const { container } = show(); + // The only graphics left are the controls': the repository button's mark + // is inside its link, and nothing floats loose beside the title where a + // logo used to be. + const loose = [...container.querySelectorAll('svg')].filter( + (graphic) => graphic.closest('button, a') === null, + ); + expect(loose).toEqual([]); + expect(screen.queryByText('/')).toBeNull(); + }); + + it('is one h-13 strip with its own bottom border, on the page’s own gutter', () => { + const { container } = show(); + const strip = container.querySelector('header'); + expect(strip?.className).toContain('h-13'); + expect(strip?.className).toContain('border-b'); + // The table below keeps `px-4`; a wider gutter here would start the title + // to the right of the first column on a large screen. + expect(strip?.className).toContain('px-4'); + expect(strip?.className).not.toContain('lg:px-6'); + }); + + it('keeps the repository button reachable by name', () => { + show(); + const link = screen.getByRole('link', { name: 'GitHub' }); + expect(link.getAttribute('href')).toBe( + 'https://github.com/tale-project/tale', + ); + expect(link.getAttribute('rel')).toContain('noopener'); + }); +}); diff --git a/services/ai-gateway/app/components/panel-header.tsx b/services/ai-gateway/app/components/panel-header.tsx index e42e82e644..8c95a4b9fa 100644 --- a/services/ai-gateway/app/components/panel-header.tsx +++ b/services/ai-gateway/app/components/panel-header.tsx @@ -1,8 +1,8 @@ +import { AdaptiveHeaderTitle } from '@tale/ui/adaptive-header'; import { Button } from '@tale/ui/button'; import { useLocale } from '@tale/ui/i18n/locale-provider'; import { GithubIcon } from '@tale/ui/icons/github'; import { LanguageSwitcher } from '@tale/ui/language-switcher'; -import { TaleLogo } from '@tale/ui/logo'; import { ThemeSwitcher } from '@tale/ui/theme-switcher'; import { useT } from '@/lib/i18n/client'; @@ -11,14 +11,17 @@ import { useT } from '@/lib/i18n/client'; const REPOSITORY_URL = 'https://github.com/tale-project/tale'; /** - * The panel's title strip — the documentation frame's header row, reused - * measure for measure: one `h-13` box whose own border is the line under it - * (`border-box`, never a bordered wrapper around a fixed-height row), a - * blurred background, and the same `px-4 lg:px-6` gutter. The left is the - * Tale mark and this service's name; the right is the docs footer's cluster - * — language, theme, repository — in that order. + * The panel's title strip — the platform's own page header, measure for + * measure: one `h-13` box whose own border is the line under it (`border-box`, + * never a bordered wrapper around a fixed-height row), the blurred + * `bg-background/80` the platform's sticky header sits on, and the same `px-4` + * gutter the page below keeps, so the title and the table start on one edge. + * The title is the platform's too — `AdaptiveHeaderTitle`, the very component + * "Automations" and "Knowledge" are set in — so the service's name reads in + * the weight and size every page title does. The right is the documentation + * footer's cluster — language, theme, repository — in that order. * - * Deliberately not the platform's `AdaptiveHeader`: that machinery portals a + * Deliberately not the platform's `AdaptiveHeader` machinery: that portals a * page's chrome into a shared shell across breakpoints, and this service is * one screen with no shell. The language picker runs in `LanguageSwitcher`'s * state-driven mode — this panel is served as one untranslated tree, so it @@ -30,28 +33,12 @@ export function PanelHeader() { const { locale, setLocale } = useLocale(); return ( -
- {/* The mark is decorative — the name beside it already says whose - panel this is — and it steps aside on a phone so the title and the - three controls both fit. */} - - - / - - {/* `title`: the name is longer than a phone's share of this row, and a - truncated heading should still be readable somewhere. */} -

+
+ {/* `min-w-0`: the title is the one thing in this row allowed to give way + on a phone, so the three controls beside it always fit. */} + {t('title')} -

+
diff --git a/services/ai-gateway/app/components/resets-cell.tsx b/services/ai-gateway/app/components/resets-cell.tsx index e0f55f6609..38575866a8 100644 --- a/services/ai-gateway/app/components/resets-cell.tsx +++ b/services/ai-gateway/app/components/resets-cell.tsx @@ -7,7 +7,9 @@ import { Fragment } from 'react'; import type { UsageWindow } from '@/app/lib/api'; import { + hasRolledOver, readableWindows, + resetRole, resetsSoon, windowElapsedPercent, windowKey, @@ -19,6 +21,16 @@ import { useT } from '@/lib/i18n/client'; /** Stands in for a window the vendor reported no rollover for. */ const NO_ROLLOVER = '—'; +/** + * The fill of a clock bar: the success tint inside the hour of the account's + * return, a darker grey for the clock that decides it, the ordinary grey for + * every other. + */ +function clockTint(decisive: boolean, soon: boolean): string { + if (soon) return 'bg-success'; + return decisive ? 'bg-foreground/70' : 'bg-muted-foreground/70'; +} + /** * How long each of an account's windows still has to run. * @@ -33,12 +45,23 @@ const NO_ROLLOVER = '—'; * so it is a fraction of the usage bar's length. Grey on purpose: a window * running out is not a warning, it is a clock. * - * The one reset that does get colour is one within the hour: a spent window - * coming back in twenty minutes is an account about to be usable again. Its - * bar and distance turn to the success tint, the distance is set in medium - * weight, and a timer glyph leads it — so the cue does not rest on colour. + * The rows stay line for line with the usage column, so a clock sits beside + * its own spend. What changes with the account is which clock is the one that + * counts. An account whose quota is spent comes back when its LAST spent + * window rolls over — a session that resets in five minutes beside a spent + * week is not back in five minutes — so that window's row is the one read in + * full strength, with a timer glyph, and the rows that only wait on it step + * back. Inside the hour the row takes the success tint: the account is about + * to be usable again. A window that is not holding the account back is an + * ordinary countdown and never gets the tint, whatever its distance. */ -export function ResetsCell({ windows }: { windows: UsageWindow[] }) { +export function ResetsCell({ + windows, + limitedUntil, +}: { + windows: UsageWindow[]; + limitedUntil: string | null; +}) { const { t } = useT('usage'); const { formatDate, formatRelative } = useFormatDate(); // One reading for the whole cell, so its rows cannot disagree about "now" — @@ -52,11 +75,17 @@ export function ResetsCell({ windows }: { windows: UsageWindow[] }) {
{readable.map((window, index) => { const name = windowName(window, t); + const role = resetRole(window, limitedUntil); + const decisive = role === 'return' && window.resetsAt !== null; + const soon = decisive && resetsSoon(window.resetsAt, now); const elapsed = windowElapsedPercent(window, now); - const soon = resetsSoon(window, now); - const until = window.resetsAt - ? formatRelative(window.resetsAt, { withoutSuffix: true }) - : null; + const rolledOver = hasRolledOver(window.resetsAt, now); + let until: string | null = null; + if (window.resetsAt) { + until = rolledOver + ? t('rolledOver') + : formatRelative(window.resetsAt, { withoutSuffix: true }); + } const exact = window.resetsAt ? t('resets', { when: formatDate(window.resetsAt, 'long') }) : null; @@ -69,9 +98,7 @@ export function ResetsCell({ windows }: { windows: UsageWindow[] }) { ) : ( - {soon ? ( + {decisive ? ( ) : null} {until ?? NO_ROLLOVER} diff --git a/services/ai-gateway/app/components/status-cell.test.tsx b/services/ai-gateway/app/components/status-cell.test.tsx new file mode 100644 index 0000000000..a46df8f73e --- /dev/null +++ b/services/ai-gateway/app/components/status-cell.test.tsx @@ -0,0 +1,98 @@ +import { LocaleProvider } from '@tale/ui/i18n/locale-provider'; +import { TooltipProvider } from '@tale/ui/tooltip'; +import { fireEvent, render, screen } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { AccountState } from '@/app/lib/api'; +import { i18n } from '@/lib/i18n/i18n'; + +import { StatusCell } from './status-cell'; + +const NOW = Date.parse('2026-10-15T12:00:00.000Z'); +const at = (offsetMs: number) => new Date(NOW + offsetMs).toISOString(); +const MINUTE = 60_000; +const DAY = 24 * 60 * MINUTE; + +function show(state: AccountState, limitedUntil: string | null) { + return render( + + + + + , + ); +} + +/** What the pointer is told: the cell's own words are hidden on a phone. */ +async function tooltipOf(cell: HTMLElement): Promise { + const trigger = cell.querySelector('span'); + if (!trigger) throw new Error('The cell has no trigger'); + fireEvent.focus(trigger); + return (await screen.findByRole('tooltip')).textContent ?? ''; +} + +describe('StatusCell', () => { + beforeEach(async () => { + await i18n.changeLanguage('en'); + vi.useFakeTimers({ toFake: ['Date'], now: NOW }); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('says which state, and for a limited account when it comes back', () => { + show('limited', at(3 * DAY)); + expect(screen.getByText('Limit reached')).toBeTruthy(); + expect(screen.getByText('Resets in 3 days')).toBeTruthy(); + }); + + it('says only the state for every state that has no return to give', () => { + for (const [state, label] of [ + ['available', 'Available'], + ['expired', 'Needs reauthentication'], + ['error', 'Last call failed'], + ] as const) { + const { unmount } = show(state, null); + expect(screen.getByText(label)).toBeTruthy(); + expect(screen.queryByText(/Resets/)).toBeNull(); + unmount(); + } + }); + + it('puts the exact instant on the tooltip of a limited account', async () => { + const { container } = show('limited', at(3 * DAY)); + expect(await tooltipOf(container)).toMatch( + /^Limit reached · Resets October 18, 2026/, + ); + }); + + it('keeps the state on the tooltip when the return is not known, or is now', async () => { + const unknown = show('limited', null); + expect(await tooltipOf(unknown.container)).toBe( + 'Limit reached · Reset time unknown', + ); + unknown.unmount(); + + const now = show('limited', at(-MINUTE)); + expect(await tooltipOf(now.container)).toBe('Limit reached · Resets now'); + }); + + it('names a state with nothing more to say on its tooltip, so a phone can read it', async () => { + const { container } = show('error', null); + expect(await tooltipOf(container)).toBe('Last call failed'); + }); + + it('turns the hourglass into a timer, in the success tint, inside the hour only', () => { + const soon = show('limited', at(25 * MINUTE)); + expect( + soon.container.querySelector('svg')?.getAttribute('class'), + ).toContain('text-success'); + soon.unmount(); + + const later = show('limited', at(3 * DAY)); + expect( + later.container.querySelector('svg')?.getAttribute('class'), + ).not.toContain('text-success'); + }); +}); diff --git a/services/ai-gateway/app/components/status-cell.tsx b/services/ai-gateway/app/components/status-cell.tsx index 29d492ec36..2576087920 100644 --- a/services/ai-gateway/app/components/status-cell.tsx +++ b/services/ai-gateway/app/components/status-cell.tsx @@ -1,30 +1,53 @@ import { cn } from '@tale/ui/cn'; +import { Text } from '@tale/ui/text'; import { Tooltip } from '@tale/ui/tooltip'; -import { CheckCircle2, TriangleAlert, XCircle } from 'lucide-react'; +import { useFormatDate } from '@tale/ui/use-format-date'; +import { + CheckCircle2, + Hourglass, + TimerReset, + TriangleAlert, + XCircle, +} from 'lucide-react'; -import type { AccountStatus } from '@/app/lib/api'; +import type { AccountState } from '@/app/lib/api'; +import { hasRolledOver, resetsSoon } from '@/app/lib/usage-windows'; +import { useMinute } from '@/app/lib/use-minute'; import { useT } from '@/lib/i18n/client'; /** - * A glyph per status, not only a tint. + * A glyph per state, not only a tint. * * Colour alone carries no meaning for a reader who cannot see it (WCAG 1.4.1), * and below `md` this cell has no room for its label — so the shape is what - * says which of the three states a row is in, at every width. + * says which of the four states a row is in, at every width. */ -const STATUS_MARK = { - active: { icon: CheckCircle2, tone: 'text-success' }, +const STATE_MARK = { + available: { icon: CheckCircle2, tone: 'text-success' }, + // A spent quota is the pool working as designed, not a fault: it comes back + // on its own. So it is the one state that is neither a tick nor an alarm — + // an hourglass, in the neutral tone, until the hour it is about to end. + limited: { icon: Hourglass, tone: 'text-muted-foreground' }, // An expired credential is a chore, not a fault: someone re-authenticates // it and the pool is whole again. A failed call is the alarming one. expired: { icon: TriangleAlert, tone: 'text-warning' }, error: { icon: XCircle, tone: 'text-destructive' }, } as const satisfies Record< - AccountStatus, + AccountState, { icon: unknown; tone: `text-${string}` } >; /** - * An account's state: the glyph always, the words from `md` up. + * An account's state: the glyph always, the words from `md` up — and, for an + * account whose quota is spent, the line that matters most about it: when it + * comes back. + * + * That line is the account's own return, the latest rollover among its spent + * windows. A session that resets in five minutes beside a spent week is not + * "back in five minutes", and reading the per-window clocks to work out which + * one counts is exactly the sum this cell does for the reader. Inside the + * hour the hourglass turns into a timer in the success tint: the account is + * about to take work again. * * The label is never removed, only hidden — `sr-only md:not-sr-only` is the * same collapse `Button` and `Switch` use — so a screen reader announces the @@ -34,23 +57,65 @@ const STATUS_MARK = { * order would buy a keyboard user nothing the accessible name does not * already give them. */ -export function StatusCell({ status }: { status: AccountStatus }) { +export function StatusCell({ + state, + limitedUntil, +}: { + state: AccountState; + limitedUntil: string | null; +}) { const { t } = useT('status'); - const { icon: Icon, tone } = STATUS_MARK[status]; - const label = t(status); + const { t: tUsage } = useT('usage'); + const { formatDate, formatRelative } = useFormatDate(); + // One reading of "now" that also moves, so a panel left open counts down. + const now = useMinute(); + + const soon = state === 'limited' && resetsSoon(limitedUntil, now); + const mark = STATE_MARK[state]; + const Icon = soon ? TimerReset : mark.icon; + const tone = soon ? 'text-success' : mark.tone; + const label = t(state); + + let caption: string | null = null; + let exact: string | null = null; + if (state === 'limited') { + if (limitedUntil === null) { + caption = tUsage('resetUnknown'); + } else if (hasRolledOver(limitedUntil, now)) { + caption = tUsage('resetsNow'); + } else { + caption = tUsage('resets', { when: formatRelative(limitedUntil) }); + exact = tUsage('resets', { when: formatDate(limitedUntil, 'long') }); + } + } return ( - - + + {/* The tint rides the glyph, never the words. A status colour is a 3:1 graphic under WCAG 1.4.11, which these tones clear; as 14px body text they do not reach the 4.5:1 that 1.4.3 asks for - (`text-destructive` measures 3.66:1 on the row surface). */} - - {/* Wraps rather than truncates: the longest labels ("Letzter Aufruf - fehlgeschlagen", "Réautorisation nécessaire") take a second line, - which every row has room for, instead of losing their end. */} - {label} + (`text-destructive` measures 3.66:1 on the row surface). The + nudge centres the 16px glyph on the first 20px line. */} + + + {/* Wraps rather than truncates: the longest labels ("Letzter Aufruf + fehlgeschlagen", "Réautorisation nécessaire") take a second + line, which every row has room for, instead of losing their + end. */} + + {label} + + {caption ? ( + + {caption} + + ) : null} + ); diff --git a/services/ai-gateway/app/components/usage-cell.tsx b/services/ai-gateway/app/components/usage-cell.tsx index 805182fb8f..6291728fcf 100644 --- a/services/ai-gateway/app/components/usage-cell.tsx +++ b/services/ai-gateway/app/components/usage-cell.tsx @@ -33,7 +33,18 @@ import { useT } from '@/lib/i18n/client'; * read. What it must not do is pass for current: weekly figures only climb * during a week, so an old one silently shown reads as simply wrong. */ -export function UsageCell({ usage }: { usage: AccountView['usage'] }) { +export function UsageCell({ + usage, + limited = false, +}: { + usage: AccountView['usage']; + /** + * The row is already receded for hitting its limit. A reading that is also + * stale then keeps its tooltip but not a second dim: two of them stack to + * a third of full strength, which leaves 100 % unreadable. + */ + limited?: boolean; +}) { const { t } = useT('usage'); const { formatRelative } = useFormatDate(); @@ -47,7 +58,7 @@ export function UsageCell({ usage }: { usage: AccountView['usage'] }) {
{readable.map((window, index) => { diff --git a/services/ai-gateway/app/lib/account-order.test.ts b/services/ai-gateway/app/lib/account-order.test.ts new file mode 100644 index 0000000000..7b41444fbc --- /dev/null +++ b/services/ai-gateway/app/lib/account-order.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from 'vitest'; + +import { compareAccounts } from '@/app/lib/account-order'; +import type { AccountView, ProviderId } from '@/app/lib/api'; + +const base: AccountView = { + id: 'base', + provider: 'anthropic', + label: 'base', + accountEmail: null, + subscription: null, + status: 'active', + state: 'available', + limitedUntil: null, + expiresAt: null, + scopes: null, + createdAt: '2026-09-24T10:00:00.000Z', + lastRefreshedAt: null, + usage: null, +}; + +function account( + name: string, + overrides: Partial = {}, +): AccountView { + return { ...base, id: name, label: name, ...overrides }; +} + +const PROVIDERS: ProviderId[] = ['anthropic', 'openai']; + +function order(accounts: AccountView[], providers = PROVIDERS, locale = 'en') { + return accounts + .toSorted(compareAccounts(providers, locale)) + .map((row) => row.id); +} + +describe('compareAccounts', () => { + it('keeps a vendor’s accounts together, vendors in the catalog’s order', () => { + expect( + order([ + account('gpt-1', { provider: 'openai' }), + account('claude-1'), + account('gpt-2', { provider: 'openai' }), + account('claude-2'), + ]), + ).toEqual(['claude-1', 'claude-2', 'gpt-1', 'gpt-2']); + }); + + it('parks a vendor the catalog no longer offers after the ones it does', () => { + expect( + order( + [account('claude-1'), account('gpt-1', { provider: 'openai' })], + ['openai'], + ), + ).toEqual(['gpt-1', 'claude-1']); + }); + + it('groups by state inside a vendor, best first', () => { + expect( + order([ + account('broken', { status: 'error', state: 'error' }), + account('lapsed', { status: 'expired', state: 'expired' }), + account('spent', { + state: 'limited', + limitedUntil: '2026-09-25T10:00:00.000Z', + }), + account('ready'), + ]), + ).toEqual(['ready', 'spent', 'lapsed', 'broken']); + }); + + it('puts the state before the address — a state is a group, not a tiebreak', () => { + expect( + order([ + account('a-limited', { + state: 'limited', + limitedUntil: '2026-09-25T10:00:00.000Z', + }), + account('z-available'), + ]), + ).toEqual(['z-available', 'a-limited']); + }); + + it('lists the accounts that are back soonest first, and those with no known return last', () => { + expect( + order([ + account('in-3-days', { + state: 'limited', + limitedUntil: '2026-09-25T10:00:00.000Z', + }), + account('unknown', { state: 'limited', limitedUntil: null }), + account('in-5-minutes', { + state: 'limited', + limitedUntil: '2026-09-22T10:05:00.000Z', + }), + account('in-a-day', { + state: 'limited', + limitedUntil: '2026-09-23T10:00:00.000Z', + }), + ]), + ).toEqual(['in-5-minutes', 'in-a-day', 'in-3-days', 'unknown']); + }); + + it('orders what a state leaves tied by address rather than label', () => { + expect( + order([ + account('Zed', { accountEmail: 'alex@example.com' }), + account('Alex', { accountEmail: 'zoe@example.com' }), + ]), + ).toEqual(['Zed', 'Alex']); + }); + + it('reads an umlaut where the reader’s own alphabet puts it', () => { + const rows = [ + account('z', { accountEmail: 'zoe@example.com' }), + account('a', { accountEmail: 'ärger@example.com' }), + account('b', { accountEmail: 'bea@example.com' }), + ]; + expect(order(rows, PROVIDERS, 'de')).toEqual(['a', 'b', 'z']); + }); +}); diff --git a/services/ai-gateway/app/lib/account-order.ts b/services/ai-gateway/app/lib/account-order.ts new file mode 100644 index 0000000000..e143900e40 --- /dev/null +++ b/services/ai-gateway/app/lib/account-order.ts @@ -0,0 +1,57 @@ +import { + ACCOUNT_STATES, + type AccountState, + type AccountView, + type ProviderId, +} from '@/app/lib/api'; + +/** + * The order the pool reads in: vendor, then what each account is doing, then + * who comes back first. + * + * An operator opens this screen to answer "how is my Claude pool doing", which + * rows sitting by vendor, and inside a vendor by state, answer in one glance: + * the accounts that can take work first, then the ones waiting on a reset — + * soonest back at the top of that band — and last the ones that need a person. + * Inside a state the accounts go by address rather than label, so a renamed + * account stays where its e-mail says it belongs. + * + * Every comparison but the vendor and the state is in the reader's own locale, + * so an umlaut sorts where that reader expects it. + */ +export function compareAccounts( + providers: readonly ProviderId[], + locale: string, +): (a: AccountView, b: AccountView) => number { + const providerRank = (id: ProviderId) => { + const index = providers.indexOf(id); + // A provider the catalog no longer offers still has rows; park them + // after the ones it does rather than at the top. + return index === -1 ? providers.length : index; + }; + const stateRank = (state: AccountState) => ACCOUNT_STATES.indexOf(state); + // No known return sorts after every known one: it is the account that can + // be promised the least. + const returnAt = (account: AccountView) => + account.state === 'limited' && account.limitedUntil + ? Date.parse(account.limitedUntil) + : Number.POSITIVE_INFINITY; + + return (a, b) => { + const byProvider = providerRank(a.provider) - providerRank(b.provider); + if (byProvider !== 0) return byProvider; + + const byState = stateRank(a.state) - stateRank(b.state); + if (byState !== 0) return byState; + + const aReturn = returnAt(a); + const bReturn = returnAt(b); + if (aReturn !== bReturn) return aReturn < bReturn ? -1 : 1; + + return (a.accountEmail ?? a.label).localeCompare( + b.accountEmail ?? b.label, + locale, + { sensitivity: 'base' }, + ); + }; +} diff --git a/services/ai-gateway/app/lib/api.ts b/services/ai-gateway/app/lib/api.ts index 3282251bc8..6f9c5db93c 100644 --- a/services/ai-gateway/app/lib/api.ts +++ b/services/ai-gateway/app/lib/api.ts @@ -22,6 +22,20 @@ export function isProviderId(value: string): value is ProviderId { export type AccountStatus = 'active' | 'expired' | 'error'; +/** + * What an account is right now, from best to worst — the order the panel + * sorts and filters in. `status` is the credential's own; `state` refines it + * with the quota: an `active` account is `available` or `limited`. + */ +export const ACCOUNT_STATES = [ + 'available', + 'limited', + 'expired', + 'error', +] as const; + +export type AccountState = (typeof ACCOUNT_STATES)[number]; + export type CallbackStyle = 'code' | 'redirect-url'; export interface UsageWindow { @@ -31,6 +45,8 @@ export interface UsageWindow { resetsAt: string | null; /** How long the window runs; what the countdown bar is a fraction of. */ windowSeconds: number | null; + /** This window is why the account is limited: spent, and not yet rolled over. */ + blocking: boolean; } /** @@ -49,19 +65,26 @@ export interface AccountView { accountEmail: string | null; subscription: Subscription | null; status: AccountStatus; + state: AccountState; + /** + * When a limited account comes back — the latest rollover among the windows + * that are spent. Null when it is not limited, or when no reset is known. + */ + limitedUntil: string | null; expiresAt: string | null; scopes: string | null; createdAt: string; lastRefreshedAt: string | null; /** - * `stale`: the latest attempt to read the figures failed, or the account - * cannot be read until it is signed in again — they are shown, dimmed, - * with the time they were read. + * `stale`: the latest attempt to read the figures failed, the account + * cannot be read until it is signed in again, or a window rolled over since + * they were read — they are shown, dimmed, with the time they were read. */ usage: { windows: UsageWindow[]; checkedAt: string; stale: boolean; + limited: boolean | null; } | null; } diff --git a/services/ai-gateway/app/lib/usage-windows.test.ts b/services/ai-gateway/app/lib/usage-windows.test.ts index 3f90bec431..18582b4559 100644 --- a/services/ai-gateway/app/lib/usage-windows.test.ts +++ b/services/ai-gateway/app/lib/usage-windows.test.ts @@ -2,8 +2,9 @@ import { describe, expect, it } from 'vitest'; import type { UsageWindow } from '@/app/lib/api'; import { - planSpent, + hasRolledOver, readableWindows, + resetRole, resetsSoon, windowElapsedPercent, } from '@/app/lib/usage-windows'; @@ -18,6 +19,7 @@ function window(overrides: Partial = {}): UsageWindow { utilization: 40, resetsAt: '2026-09-22T14:00:00.000Z', windowSeconds: FIVE_HOURS, + blocking: false, ...overrides, }; } @@ -30,36 +32,6 @@ describe('readableWindows', () => { }); }); -describe('planSpent', () => { - it('calls a plan spent when its session or its weekly window is', () => { - expect(planSpent([window({ utilization: 100 })])).toBe(true); - expect( - planSpent([ - window({ utilization: 12 }), - window({ kind: 'weekly', utilization: 100 }), - ]), - ).toBe(true); - }); - - it('leaves a plan whose only spent window caps one model alone', () => { - expect( - planSpent([ - window({ utilization: 30 }), - window({ kind: 'scoped', label: 'Fable', utilization: 100 }), - ]), - ).toBe(false); - }); - - it('reads the figure the bar prints, so 99.6 % is not spent', () => { - expect(planSpent([window({ utilization: 99.6 })])).toBe(false); - }); - - it('says nothing about a plan with no reading', () => { - expect(planSpent([])).toBe(false); - expect(planSpent([window({ utilization: null })])).toBe(false); - }); -}); - describe('windowElapsedPercent', () => { it('measures backwards from the rollover', () => { // Two of the five hours are still to run, so three are spent. @@ -98,26 +70,87 @@ describe('windowElapsedPercent', () => { describe('resetsSoon', () => { it('points out a rollover inside the hour', () => { - expect( - resetsSoon(window({ resetsAt: '2026-09-22T12:25:00.000Z' }), NOW), - ).toBe(true); + expect(resetsSoon('2026-09-22T12:25:00.000Z', NOW)).toBe(true); }); it('leaves one an hour or more away alone', () => { - expect( - resetsSoon(window({ resetsAt: '2026-09-22T13:00:00.000Z' }), NOW), - ).toBe(false); - expect(resetsSoon(window(), NOW)).toBe(false); + expect(resetsSoon('2026-09-22T13:00:00.000Z', NOW)).toBe(false); + expect(resetsSoon('2026-09-22T14:00:00.000Z', NOW)).toBe(false); }); it('does not call a rollover that has passed soon', () => { // The reading predates it; the next read replaces the window. - expect( - resetsSoon(window({ resetsAt: '2026-09-22T11:59:00.000Z' }), NOW), - ).toBe(false); + expect(resetsSoon('2026-09-22T11:59:00.000Z', NOW)).toBe(false); }); it('says nothing about a window with no rollover', () => { - expect(resetsSoon(window({ resetsAt: null }), NOW)).toBe(false); + expect(resetsSoon(null, NOW)).toBe(false); + }); +}); + +describe('hasRolledOver', () => { + it('is true from the instant of the rollover on', () => { + expect(hasRolledOver('2026-09-22T11:59:00.000Z', NOW)).toBe(true); + expect(hasRolledOver('2026-09-22T12:00:00.000Z', NOW)).toBe(true); + }); + + it('is false while the rollover is ahead, or when there is none to read', () => { + expect(hasRolledOver('2026-09-22T12:00:01.000Z', NOW)).toBe(false); + expect(hasRolledOver(null, NOW)).toBe(false); + expect(hasRolledOver('not a date', NOW)).toBe(false); + }); +}); + +describe('resetRole', () => { + const session = window({ + kind: 'session', + utilization: 100, + resetsAt: '2026-09-22T12:05:00.000Z', + blocking: true, + }); + const weekly = window({ + kind: 'weekly', + utilization: 100, + resetsAt: '2026-09-25T12:00:00.000Z', + blocking: true, + }); + + it('reads the clock the account waits for as its return, and the one it only waits behind as waiting', () => { + // Session back in five minutes, week in three days: the account is back + // in three days, so that is the clock that counts. + const limitedUntil = '2026-09-25T12:00:00.000Z'; + expect(resetRole(weekly, limitedUntil)).toBe('return'); + expect(resetRole(session, limitedUntil)).toBe('waiting'); + }); + + it('compares instants, not spellings', () => { + expect( + resetRole( + { ...weekly, resetsAt: '2026-09-25T12:00:00+00:00' }, + '2026-09-25T12:00:00.000Z', + ), + ).toBe('return'); + }); + + it('calls every window that is not holding the account back an ordinary countdown', () => { + expect( + resetRole( + window({ resetsAt: '2026-09-22T12:20:00.000Z' }), + '2026-09-25T12:00:00.000Z', + ), + ).toBe('running'); + // Not even when the account itself has nothing to wait for. + expect(resetRole(window(), null)).toBe('running'); + }); + + it('takes the window with no stated rollover as the return when that is the unknown one', () => { + const undated = window({ + utilization: 100, + resetsAt: null, + blocking: true, + }); + expect(resetRole(undated, null)).toBe('return'); + // …and a dated one beside it waits behind it. + expect(resetRole(weekly, null)).toBe('waiting'); }); }); diff --git a/services/ai-gateway/app/lib/usage-windows.ts b/services/ai-gateway/app/lib/usage-windows.ts index 1a530d73a3..eaacc04979 100644 --- a/services/ai-gateway/app/lib/usage-windows.ts +++ b/services/ai-gateway/app/lib/usage-windows.ts @@ -4,14 +4,14 @@ * * A row's plan is drawn twice — how much of each window is spent, and how long * that window still has to run — in two table cells that must stay line for - * line; and a plan that is spent greys the whole row. Anything more than one - * of them decides lives here rather than in any one. + * line; and the account's state, which the gateway derives from those windows, + * decides which of the clocks matters. Anything more than one of them decides + * lives here rather than in any one. */ import type { TFunction } from 'i18next'; import type { UsageWindow } from '@/app/lib/api'; -import { isSpent, spentPercent } from '@/app/lib/usage-tint'; /** * The windows the panel draws. @@ -24,23 +24,6 @@ export function readableWindows(windows: UsageWindow[]): UsageWindow[] { return windows.filter((window) => window.utilization !== null); } -/** - * Whether an account's reading says its plan is used up for now: its session - * or its weekly window stands at the ceiling. - * - * Only those two stop the account as a whole. A scoped window caps one model, - * and the account still answers for every other one — so a spent per-model - * week leaves its row alone. The figure is the one the bar prints, rounded - * down against the same ceiling, so a row reads as spent exactly when one of - * those two bars is red. - */ -export function planSpent(windows: UsageWindow[]): boolean { - return readableWindows(windows).some( - (window) => - window.kind !== 'scoped' && isSpent(spentPercent(window.utilization)), - ); -} - /** * A stable key for a window inside one account's cell. * @@ -63,25 +46,63 @@ export function windowName(window: UsageWindow, t: TFunction): string { return t(window.kind === 'session' ? 'session' : 'weekly'); } -/** Within this of its rollover, a window's reset is close enough to point out. */ +/** Within this of its rollover, a reset is close enough to point out. */ const RESET_SOON_MS = 60 * 60 * 1000; +/** A rollover as an instant, or NaN when there is none to read. */ +function instant(value: string | null): number { + return value === null ? Number.NaN : Date.parse(value); +} + /** - * Whether a window rolls over within the hour. + * Whether an instant lies within the hour ahead. * - * The one reset worth a second look: a spent window that comes back in twenty - * minutes is an account about to be usable again. A rollover already behind - * `now` is not "soon" — the reading predates it, and the next read replaces - * it. + * The one reset worth a second look: a limited account that comes back in + * twenty minutes is about to be usable again. One already behind `now` is not + * "soon" — it is past, and the next read replaces the reading. */ -export function resetsSoon(window: UsageWindow, now: number): boolean { - if (!window.resetsAt) return false; - const remaining = new Date(window.resetsAt).getTime() - now; +export function resetsSoon(resetsAt: string | null, now: number): boolean { + const remaining = instant(resetsAt) - now; return ( Number.isFinite(remaining) && remaining > 0 && remaining < RESET_SOON_MS ); } +/** Whether a rollover has come: the figure it belonged to is out of date. */ +export function hasRolledOver(resetsAt: string | null, now: number): boolean { + const rollover = instant(resetsAt); + return Number.isFinite(rollover) && rollover <= now; +} + +/** + * How one window's rollover bears on the account. + * + * - `return`: the account is limited, and this is the clock it waits for — + * the spent window that rolls over last. + * - `waiting`: spent too, but it rolls over before the account is free, so + * its clock decides nothing yet. + * - `running`: not what holds the account back; an ordinary countdown. + * + * A session that resets in five minutes beside a spent week is `waiting`, and + * the week is the `return`: the account is not back in five minutes, and the + * column says which clock to read. + */ +export type ResetRole = 'return' | 'waiting' | 'running'; + +export function resetRole( + window: UsageWindow, + limitedUntil: string | null, +): ResetRole { + if (!window.blocking) return 'running'; + // Compared as instants: the account's own return is normalised, a window's + // is whatever spelling its vendor used. + const same = + limitedUntil === null || window.resetsAt === null + ? limitedUntil === window.resetsAt + : instant(window.resetsAt) === instant(limitedUntil); + return same ? 'return' : 'waiting'; +} + /** * How far through its window the clock already is, 0–100, or null. * diff --git a/services/ai-gateway/app/lib/use-gateway.test.ts b/services/ai-gateway/app/lib/use-gateway.test.ts index e20a9ec578..9784c2b5d1 100644 --- a/services/ai-gateway/app/lib/use-gateway.test.ts +++ b/services/ai-gateway/app/lib/use-gateway.test.ts @@ -19,6 +19,8 @@ const account: AccountView = { accountEmail: 'you@example.com', subscription: { plan: 'max', tier: '20x' }, status: 'active', + state: 'available', + limitedUntil: null, expiresAt: null, scopes: null, createdAt: '2026-09-24T10:00:00.000Z', diff --git a/services/ai-gateway/backend/account-state.test.ts b/services/ai-gateway/backend/account-state.test.ts new file mode 100644 index 0000000000..7b55ff565e --- /dev/null +++ b/services/ai-gateway/backend/account-state.test.ts @@ -0,0 +1,257 @@ +import { describe, expect, it } from 'vitest'; + +import { + ACCOUNT_STATES, + deriveAccountState, + rolledOverSince, + type StateInput, +} from './account-state'; +import type { UsageWindow } from './providers/types'; + +const NOW = Date.parse('2026-10-15T10:00:00.000Z'); +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; + +const at = (offsetMs: number) => new Date(NOW + offsetMs).toISOString(); + +function window( + kind: UsageWindow['kind'], + utilization: number | null, + resetsInMs: number | null, + label: string | null = null, +): UsageWindow { + return { + kind, + label, + utilization, + resetsAt: resetsInMs === null ? null : at(resetsInMs), + windowSeconds: kind === 'session' ? 18_000 : 604_800, + }; +} + +function input( + windows: UsageWindow[], + extra: Partial & { limited?: boolean | null } = {}, +): StateInput { + const { limited, ...rest } = extra; + return { + status: 'active', + usage: { windows, ...(limited === undefined ? {} : { limited }) }, + ...rest, + }; +} + +describe('deriveAccountState', () => { + it('lists the states from best to worst', () => { + expect(ACCOUNT_STATES).toEqual([ + 'available', + 'limited', + 'expired', + 'error', + ]); + }); + + it('calls an account with no reading available', () => { + expect(deriveAccountState({ status: 'active', usage: null }, NOW)).toEqual({ + state: 'available', + limitedUntil: null, + blocking: [], + }); + }); + + it('calls an account with room in every window available', () => { + const derived = deriveAccountState( + input([window('session', 40, 2 * HOUR), window('weekly', 99.6, 2 * DAY)]), + NOW, + ); + // 99.6 is not the ceiling: it reads 99 and still has something left. + expect(derived).toMatchObject({ state: 'available', limitedUntil: null }); + expect(derived.blocking).toEqual([false, false]); + }); + + it('is back when the session rolls over, if only the session is spent', () => { + const derived = deriveAccountState( + input([ + window('session', 100, 5 * MINUTE), + window('weekly', 41, 3 * DAY), + ]), + NOW, + ); + expect(derived).toEqual({ + state: 'limited', + limitedUntil: at(5 * MINUTE), + blocking: [true, false], + }); + }); + + it('is back in three days, not in five minutes, when the weekly is spent too', () => { + // The case the panel exists to get right: the session window comes back + // soon, and the account does not. + const derived = deriveAccountState( + input([ + window('session', 100, 5 * MINUTE), + window('weekly', 100, 3 * DAY), + ]), + NOW, + ); + expect(derived).toEqual({ + state: 'limited', + limitedUntil: at(3 * DAY), + blocking: [true, true], + }); + }); + + it('is back in three days when only the weekly is spent', () => { + const derived = deriveAccountState( + input([ + window('session', 20, 5 * MINUTE), + window('weekly', 100, 3 * DAY), + ]), + NOW, + ); + expect(derived).toMatchObject({ + state: 'limited', + limitedUntil: at(3 * DAY), + blocking: [false, true], + }); + }); + + it('never limits an account on a per-model cap', () => { + const derived = deriveAccountState( + input([ + window('session', 10, 2 * HOUR), + window('weekly', 30, 2 * DAY), + window('scoped', 100, 2 * DAY, 'Fable'), + ]), + NOW, + ); + expect(derived.state).toBe('available'); + expect(derived.blocking).toEqual([false, false, false]); + }); + + it('stops counting a spent window whose rollover is behind the clock', () => { + const derived = deriveAccountState( + input([window('session', 100, -MINUTE), window('weekly', 12, 2 * DAY)]), + NOW, + ); + expect(derived).toEqual({ + state: 'available', + limitedUntil: null, + blocking: [false, false], + }); + }); + + it('is limited by the window still ahead when its sibling has rolled over', () => { + const derived = deriveAccountState( + input([window('session', 100, -MINUTE), window('weekly', 100, 2 * DAY)]), + NOW, + ); + expect(derived).toMatchObject({ + state: 'limited', + limitedUntil: at(2 * DAY), + blocking: [false, true], + }); + }); + + it('is limited with no known return when a spent window states no rollover', () => { + const derived = deriveAccountState( + input([window('weekly', 100, null)]), + NOW, + ); + expect(derived).toEqual({ + state: 'limited', + limitedUntil: null, + blocking: [true], + }); + }); + + it('does not promise a return that one spent window cannot date', () => { + // The dated window would say tomorrow; the undated one says nothing, and + // the account is back only when both are. + const derived = deriveAccountState( + input([window('session', 100, null), window('weekly', 100, DAY)]), + NOW, + ); + expect(derived.state).toBe('limited'); + expect(derived.limitedUntil).toBeNull(); + }); + + describe('the vendor’s own limit flag', () => { + it('limits an account whose windows do not show it, with no return date', () => { + const derived = deriveAccountState( + input([window('weekly', 80, 2 * DAY)], { limited: true }), + NOW, + ); + expect(derived).toEqual({ + state: 'limited', + limitedUntil: null, + blocking: [false], + }); + }); + + it('yields to a full window that has since rolled over', () => { + const derived = deriveAccountState( + input([window('weekly', 100, -HOUR)], { limited: true }), + NOW, + ); + expect(derived.state).toBe('available'); + }); + + it('dates the return by the full window it agrees with', () => { + const derived = deriveAccountState( + input([window('weekly', 100, DAY)], { limited: true }), + NOW, + ); + expect(derived).toMatchObject({ + state: 'limited', + limitedUntil: at(DAY), + }); + }); + + it('is not a limit when the vendor says it is not', () => { + expect( + deriveAccountState( + input([window('weekly', 30, DAY)], { limited: false }), + NOW, + ).state, + ).toBe('available'); + }); + }); + + it.each(['expired', 'error'] as const)( + 'puts a %s credential first, whatever the quota reads', + (status) => { + const derived = deriveAccountState( + input([window('weekly', 100, 3 * DAY)], { status }), + NOW, + ); + expect(derived).toEqual({ + state: status, + limitedUntil: null, + blocking: [false], + }); + }, + ); +}); + +describe('rolledOverSince', () => { + const spent = window('weekly', 100, -5 * MINUTE); + + it('is true for a rollover after the reading and before now', () => { + expect(rolledOverSince(spent, NOW - 10 * MINUTE, NOW)).toBe(true); + }); + + it('is false for a rollover the reading already knew about', () => { + expect(rolledOverSince(spent, NOW - MINUTE, NOW)).toBe(false); + }); + + it('is false for a rollover still ahead, or none stated', () => { + expect(rolledOverSince(window('weekly', 10, HOUR), NOW - DAY, NOW)).toBe( + false, + ); + expect(rolledOverSince(window('weekly', 10, null), NOW - DAY, NOW)).toBe( + false, + ); + }); +}); diff --git a/services/ai-gateway/backend/account-state.ts b/services/ai-gateway/backend/account-state.ts new file mode 100644 index 0000000000..6f7ff250a5 --- /dev/null +++ b/services/ai-gateway/backend/account-state.ts @@ -0,0 +1,144 @@ +/** + * What an account is right now, in one word — and, when its quota is spent, + * until when. + * + * The panel groups and words its rows from this, and the REST API hands the + * same verdict to a script, so the two cannot disagree about which accounts + * are limited or when they come back. It is a pure function of the stored + * reading and a clock: nothing is persisted, so no document written by an + * older release needs to change. + * + * Deliberately not `quotaAvailability()` in `accounts.ts`, which answers a + * different question — may this account take NEW work — for the token + * endpoints, and so also distrusts a reading older than fifteen minutes and + * weighs the refresh floor. This describes the account as its own latest + * reading shows it, which is what a person looking at the figures expects the + * row to say; the two share the rule that matters, that only the session and + * weekly windows stop an account and that a rollover already behind `now` + * stops nothing. + */ + +import type { UsageWindow } from './providers/types'; + +/** + * `available` — can take work, as far as its reading says. + * `limited` — its session or weekly window is spent; it comes back when + * every spent window has rolled over. + * `expired` / `error` — the credential needs attention first, whatever the + * quota reads: a refresh was refused, or the latest call failed. + */ +export type AccountState = 'available' | 'limited' | 'expired' | 'error'; + +/** The order a pool reads best to worst; the panel sorts on it. */ +export const ACCOUNT_STATES: readonly AccountState[] = [ + 'available', + 'limited', + 'expired', + 'error', +]; + +/** What the derivation reads off an account — its credential and its figures. */ +export interface StateInput { + status: 'active' | 'expired' | 'error'; + usage: { + windows: readonly UsageWindow[]; + /** The vendor's own "limit reached" signal, when it sends one. */ + limited?: boolean | null; + } | null; +} + +export interface DerivedState { + state: AccountState; + /** + * The instant every spent window has rolled over, or null: not limited, or + * limited with no reset time to give (a spent window the vendor stated no + * rollover for, or only its own "limit reached" flag). Set only while + * `state` is `limited`. + */ + limitedUntil: string | null; + /** + * One flag per window, in the order of `usage.windows`: whether that window + * is why the account is limited — spent, general rather than scoped, and + * not yet rolled over. Every flag is false unless `state` is `limited`. + */ + blocking: boolean[]; +} + +/** A window's rollover as an instant, or NaN when the vendor gave none. */ +function rolloverMs(window: UsageWindow): number { + return window.resetsAt ? Date.parse(window.resetsAt) : Number.NaN; +} + +/** Whether a window's stated rollover is behind `nowMs`. */ +function hasPassed(window: UsageWindow, nowMs: number): boolean { + const rollover = rolloverMs(window); + return Number.isFinite(rollover) && rollover <= nowMs; +} + +/** + * Whether a window has rolled over since `sinceMs`. A rollover the reading + * already knew about — it was taken after it — is the reading's own news, not + * a reason to doubt it. + */ +export function rolledOverSince( + window: UsageWindow, + sinceMs: number, + nowMs: number, +): boolean { + const rollover = rolloverMs(window); + return Number.isFinite(rollover) && rollover > sinceMs && rollover <= nowMs; +} + +/** + * Whether a window stands at its ceiling. Only the session and weekly windows + * can stop an account: a scoped one caps one model, and every other still + * answers. + */ +function isSpentGeneralWindow(window: UsageWindow): boolean { + return ( + window.kind !== 'scoped' && + window.utilization !== null && + Number.isFinite(window.utilization) && + window.utilization >= 100 + ); +} + +export function deriveAccountState( + input: StateInput, + nowMs: number, +): DerivedState { + const windows = input.usage?.windows ?? []; + const none = windows.map(() => false); + + if (input.status !== 'active') { + return { state: input.status, limitedUntil: null, blocking: none }; + } + + // A rollover behind `now` frees the window even before the next reading + // says so; one with no stated time cannot be shown to have passed. + const blocking = windows.map( + (window) => isSpentGeneralWindow(window) && !hasPassed(window, nowMs), + ); + + if (blocking.some(Boolean)) { + const resets = windows + .filter((_, index) => blocking[index]) + .map(rolloverMs); + return { + state: 'limited', + limitedUntil: resets.every(Number.isFinite) + ? new Date(Math.max(...resets)).toISOString() + : null, + blocking, + }; + } + + // The vendor's own flag is authoritative when no window of its own says + // otherwise — but a window that was full and has rolled over since is the + // one thing that answers it. + if (input.usage?.limited === true && !windows.some(isSpentGeneralWindow)) { + return { state: 'limited', limitedUntil: null, blocking: none }; + } + + return { state: 'available', limitedUntil: null, blocking: none }; +} diff --git a/services/ai-gateway/backend/accounts-api.ts b/services/ai-gateway/backend/accounts-api.ts new file mode 100644 index 0000000000..16f3a7e3b6 --- /dev/null +++ b/services/ai-gateway/backend/accounts-api.ts @@ -0,0 +1,333 @@ +/** + * The machine door to the pool: read the accounts, and change them. + * + * The panel's own routes carry no credential, because whatever fronts the + * gateway decides who reaches the panel. A script has no such front door, so + * everything here asks for a key — and asks for two kinds: + * + * - **Reading** takes the same key that opens the token endpoints, or the + * admin key. An account's figures are a subset of what that key already + * reads from `/api/tokens`, so this widens nothing. + * - **Changing** — starting an authorization, completing one, removing an + * account — takes the admin key only, and is off while the gateway has none. + * Adding an account puts someone else's subscription into the pool the + * platform draws from, which is not something every holder of a token key + * should be able to do. An operator who wants one key sets both variables to + * the same value. + * + * Guards are attached per route, never as a wildcard, for the reason + * `routes.ts` gives: a guard that silently widens to another audience is the + * mistake this split exists to prevent. + * + * Names are snake_case, as on the token endpoints, so the same concept has the + * same field wherever a script meets it. + */ + +import { Hono } from 'hono'; +import { createMiddleware } from 'hono/factory'; +import { z } from 'zod'; + +import { ACCOUNT_STATES, type AccountState } from './account-state'; +import type { AccountService, AuthorizationStart } from './accounts'; +import { readApiKey } from './api-key'; +import { secretsMatch } from './crypto'; +import { fail } from './envelope'; +import { isProviderId, PROVIDER_IDS } from './providers/types'; +import type { AccountView } from './store'; + +export interface AccountsApiOptions { + accounts: AccountService; + /** The key of the token endpoints: reads. */ + apiKey: string; + /** The admin key: reads and changes. Null while changing is switched off. */ + adminApiKey: string | null; +} + +const startSchema = z.object({ + provider: z.string().refine(isProviderId, 'Unknown provider'), + /** Set to re-authenticate an existing account instead of adding one. */ + account_id: z.string().min(1).nullish(), + /** A name for the account; a flow that finishes on its own still has it. */ + label: z.string().max(200).nullish(), + /** `browser`: the paste flow, even where a device flow is offered. */ + method: z.literal('browser').nullish(), +}); + +const completeSchema = z.object({ + /** Whatever the person copied out of the browser. */ + pasted: z.string().min(1), +}); + +/** One account as a script sees it: no credential, in the token door's names. */ +function serializeAccount(view: AccountView) { + return { + id: view.id, + provider: view.provider, + label: view.label, + account_email: view.accountEmail, + subscription: view.subscription, + status: view.status, + state: view.state, + limited_until: view.limitedUntil, + expires_at: view.expiresAt, + scopes: view.scopes, + created_at: view.createdAt, + last_refreshed_at: view.lastRefreshedAt, + usage: view.usage + ? { + checked_at: view.usage.checkedAt, + stale: view.usage.stale, + limited: view.usage.limited, + windows: view.usage.windows.map((window) => ({ + kind: window.kind, + label: window.label, + utilization: window.utilization, + resets_at: window.resetsAt, + window_seconds: window.windowSeconds, + blocking: window.blocking, + })), + } + : null, + }; +} + +/** + * A started authorization, as a script is told to finish it. A device flow + * finishes on its own once the code is approved; a paste flow waits for + * `POST …/complete`. A redirect flow never reaches here — it needs a browser + * on a loopback address, and this door passes none — but the union is + * answered whole rather than assumed. + */ +function serializeStart(start: AuthorizationStart) { + if (start.flow === 'device') { + return { + state: start.state, + flow: start.flow, + verification_url: start.verificationUrl, + user_code: start.userCode, + expires_at: start.expiresAt, + poll_interval_seconds: start.pollIntervalSeconds, + }; + } + if (start.flow === 'redirect') { + return { + state: start.state, + flow: start.flow, + authorize_url: start.authorizeUrl, + }; + } + return { + state: start.state, + flow: start.flow, + authorize_url: start.authorizeUrl, + paste_style: start.pasteStyle, + }; +} + +export function createAccountsApi(options: AccountsApiOptions) { + const { accounts } = options; + const app = new Hono(); + + /** + * Who is asking, and whether that is enough. + * + * Both keys are always compared, so how long the answer takes does not say + * which of them was close. A key that is right but not enough is a 403, not + * a 401: the caller is known, and trying another key of the same kind + * cannot help. + */ + function guard(access: 'read' | 'control') { + return createMiddleware(async (c, next) => { + c.header('Cache-Control', 'no-store'); + const provided = readApiKey(c.req.raw.headers); + const isToken = + provided !== null && secretsMatch(provided, options.apiKey); + const isAdmin = + provided !== null && + options.adminApiKey !== null && + secretsMatch(provided, options.adminApiKey); + if (!isToken && !isAdmin) { + c.header('WWW-Authenticate', 'Bearer'); + return c.json( + fail('invalid_api_key', 'Invalid or missing API key.'), + 401, + ); + } + if (access === 'control' && !isAdmin) { + return options.adminApiKey === null + ? c.json( + fail( + 'control_disabled', + 'This gateway has no admin key, so accounts cannot be changed over the API.', + ), + 403, + ) + : c.json( + fail( + 'admin_key_required', + 'This key can read accounts but not change them.', + ), + 403, + ); + } + await next(); + return undefined; + }); + } + + const read = guard('read'); + const control = guard('control'); + + // --- Reading -------------------------------------------------------------- + + /** + * The pool, without a credential in it. Narrowed by `?provider=` and + * `?state=` — a script that only wants the limited Claude accounts should + * not have to filter the whole pool itself. + */ + app.get('/accounts', read, async (c) => { + const provider = c.req.query('provider'); + const state = c.req.query('state'); + if (provider !== undefined && !isProviderId(provider)) { + return c.json( + fail( + 'invalid_request', + `No such provider. This gateway holds ${PROVIDER_IDS.join(' and ')}.`, + ), + 400, + ); + } + if (state !== undefined && !isAccountState(state)) { + return c.json( + fail( + 'invalid_request', + `No such state. Use ${ACCOUNT_STATES.join(', ')}.`, + ), + 400, + ); + } + const views = await accounts.list(); + return c.json({ + accounts: views + .filter( + (view) => + (provider === undefined || view.provider === provider) && + (state === undefined || view.state === state), + ) + .map(serializeAccount), + }); + }); + + app.get('/accounts/:id', read, async (c) => { + const view = await accounts.get(c.req.param('id')); + if (!view) return c.json(fail('unknown_account', 'No such account.'), 404); + return c.json({ account: serializeAccount(view) }); + }); + + // --- Changing ------------------------------------------------------------- + + /** + * Start an authorization. Always the flow that needs no browser on this + * machine's loopback — a device code, or a paste — because a script has no + * `Origin` to be trusted with a redirect, and the body cannot ask for one. + */ + app.post('/authorizations', control, async (c) => { + const body = startSchema.safeParse(await c.req.json().catch(() => null)); + if (!body.success) { + return c.json( + fail( + 'invalid_request', + `Name a provider: ${PROVIDER_IDS.join(' or ')}.`, + ), + 400, + ); + } + const start = await accounts.beginAuthorization({ + provider: body.data.provider, + accountId: body.data.account_id ?? null, + label: body.data.label ?? null, + loopbackOrigin: null, + preferBrowser: body.data.method === 'browser', + }); + audit( + body.data.account_id + ? `started signing account ${body.data.account_id} in again` + : `started adding an account for ${body.data.provider}`, + ); + return c.json({ authorization: serializeStart(start) }, 201); + }); + + /** + * Where an authorization stands. For a device code this is also what moves + * it on — a read may ask the vendor whether it was approved — so a script + * polls it, no faster than the interval the start named. + */ + app.get('/authorizations/:state', control, async (c) => { + const state = c.req.param('state'); + const status = await accounts.authorizationStatus(state); + if (status.status === 'connected') { + // A device code connects its account in a read like this one — the only + // moment this door learns it did — so that read is where it is noted. A + // script that reads on after the connection leaves a line each time. + audit(`connected account ${status.account.id}`); + return c.json({ + authorization: { + state, + status: status.status, + account: serializeAccount(status.account), + }, + }); + } + return c.json({ + authorization: { + state, + status: status.status, + ...(status.status === 'failed' ? { code: status.code } : {}), + }, + }); + }); + + app.post('/authorizations/:state/complete', control, async (c) => { + const body = completeSchema.safeParse(await c.req.json().catch(() => null)); + if (!body.success) { + return c.json( + fail('invalid_request', 'Send what the browser gave back as `pasted`.'), + 400, + ); + } + const account = await accounts.completeAuthorization({ + state: c.req.param('state'), + pasted: body.data.pasted, + }); + audit(`connected account ${account.id}`); + return c.json({ account: serializeAccount(account) }, 201); + }); + + app.delete('/accounts/:id', control, async (c) => { + const id = c.req.param('id'); + const removed = await accounts.remove(id); + if (!removed) { + return c.json(fail('unknown_account', 'No such account.'), 404); + } + audit(`removed account ${id}`); + return c.body(null, 204); + }); + + return app; +} + +/** + * Every change made over this door leaves a line: the one trail a way to + * change the pool owes whoever runs the gateway, and the only one the admin key + * gives, since a key names no person. Only what the gateway itself vouches + * for — an account's id, after the change found it; a vendor's id — never a + * label, an address or anything a credential is made of, and never text the + * caller wrote, which a newline could turn into a line of its own. + */ +function audit(message: string): void { + console.info(`[ai-gateway] accounts API: ${message}`); +} + +function isAccountState(value: string): value is AccountState { + return (ACCOUNT_STATES as readonly string[]).includes(value); +} diff --git a/services/ai-gateway/backend/accounts.test.ts b/services/ai-gateway/backend/accounts.test.ts index 9f555a04f6..59a4cbd61f 100644 --- a/services/ai-gateway/backend/accounts.test.ts +++ b/services/ai-gateway/backend/accounts.test.ts @@ -243,6 +243,107 @@ describe('createAccountService', () => { expect(cipher.open(stored?.accessToken ?? '')).toBe('access-1'); }); + describe('what state an account is in', () => { + const MINUTE = 60_000; + const DAY = 24 * 60 * MINUTE; + const at = (offsetMs: number) => + new Date(now.getTime() + offsetMs).toISOString(); + const window = ( + kind: 'session' | 'weekly', + resetsInMs: number, + utilization = 100, + ) => ({ + kind, + label: null, + utilization, + resetsAt: at(resetsInMs), + windowSeconds: kind === 'session' ? 18_000 : 604_800, + }); + + /** Put a reading on the stored row, read just now, so no re-read follows. */ + async function readAs( + id: string, + windows: ReturnType[], + ): Promise { + await store.updateAccount(id, (row) => { + row.usage = { windows, checkedAt: at(0), limited: null }; + row.usageAttemptedAt = at(0); + }); + } + + it('reads one account as the list shows it, and none for an id it does not hold', async () => { + const connected = await connect(); + const [listed] = await service.list(); + expect(await service.get(connected.id)).toEqual(listed); + expect(await service.get('gone')).toBeNull(); + }); + + it('is back when the last spent window rolls over, by the service’s own clock', async () => { + const connected = await connect(); + await readAs(connected.id, [ + window('session', 2 * MINUTE), + window('weekly', 3 * DAY), + ]); + + expect(await service.get(connected.id)).toMatchObject({ + state: 'limited', + limitedUntil: at(3 * DAY), + usage: { + stale: false, + windows: [{ blocking: true }, { blocking: true }], + }, + }); + + // Two and a half minutes on — inside the polling floor, so nothing is + // read again: the session has rolled over and the week has not. + now = new Date(now.getTime() + 150_000); + expect(await service.get(connected.id)).toMatchObject({ + state: 'limited', + limitedUntil: new Date( + Date.parse('2026-09-21T10:00:00.000Z') + 3 * DAY, + ).toISOString(), + usage: { + // The figure beside the passed rollover is the last of the window + // before it, and says so. + stale: true, + windows: [{ blocking: false }, { blocking: true }], + }, + }); + }); + + it('frees an account the moment its only spent window rolls over', async () => { + const connected = await connect(); + await readAs(connected.id, [ + window('session', 2 * MINUTE), + window('weekly', 3 * DAY, 41), + ]); + expect(await service.get(connected.id)).toMatchObject({ + state: 'limited', + limitedUntil: at(2 * MINUTE), + }); + + now = new Date(now.getTime() + 150_000); + expect(await service.get(connected.id)).toMatchObject({ + state: 'available', + limitedUntil: null, + usage: { stale: true }, + }); + }); + + it('puts a credential that needs attention before any quota', async () => { + const connected = await connect(); + await readAs(connected.id, [window('weekly', 3 * DAY)]); + await store.updateAccount(connected.id, (row) => { + row.status = 'expired'; + }); + expect(await service.get(connected.id)).toMatchObject({ + status: 'expired', + state: 'expired', + limitedUntil: null, + }); + }); + }); + it('takes a name given at the start over the provider identity', async () => { const { state } = await service.beginAuthorization({ provider: 'anthropic', diff --git a/services/ai-gateway/backend/accounts.ts b/services/ai-gateway/backend/accounts.ts index c978a20991..91a215b367 100644 --- a/services/ai-gateway/backend/accounts.ts +++ b/services/ai-gateway/backend/accounts.ts @@ -356,6 +356,8 @@ export type AuthorizationStatus = export interface AccountService { list(): Promise; + /** One account as the list shows it, or null when there is none by that id. */ + get(id: string): Promise; beginAuthorization(input: { provider: ProviderId; accountId?: string | null; @@ -930,7 +932,7 @@ export function createAccountService( try { return { status: 'connected', - account: toAccountView(await finish(pending, grant)), + account: toAccountView(await finish(pending, grant), now().getTime()), }; } catch (error) { if (error instanceof AccountError && error.code !== 'unknown_account') { @@ -948,7 +950,10 @@ export function createAccountService( const account = await store.getAccount(pending.accountId); // Connected, then removed before anyone asked: nothing to show. return account - ? { status: 'connected', account: toAccountView(account) } + ? { + status: 'connected', + account: toAccountView(account, now().getTime()), + } : { status: 'failed', code: 'unknown_state' }; } if (pending.phase === 'failed') { @@ -1047,7 +1052,14 @@ export function createAccountService( const refreshed = await Promise.all( accounts.map((account) => refreshUsage(account)), ); - return refreshed.map(toAccountView); + const nowMs = now().getTime(); + return refreshed.map((account) => toAccountView(account, nowMs)); + }, + + async get(id) { + const account = await store.getAccount(id); + if (!account) return null; + return toAccountView(await refreshUsage(account), now().getTime()); }, async beginAuthorization({ @@ -1177,6 +1189,7 @@ export function createAccountService( codeVerifier: claimed.codeVerifier, redirectUri: claimed.redirectUri, }), + now().getTime(), ); }, diff --git a/services/ai-gateway/backend/config.test.ts b/services/ai-gateway/backend/config.test.ts index 31e1722b9d..92f7d5aad9 100644 --- a/services/ai-gateway/backend/config.test.ts +++ b/services/ai-gateway/backend/config.test.ts @@ -83,6 +83,51 @@ describe('loadConfig', () => { ); }); + describe('the admin key', () => { + it('is off unless it is set', () => { + expect(loadConfig(complete()).config.adminApiKey).toBeNull(); + }); + + it('is read when it is set', () => { + expect( + loadConfig({ ...complete(), AI_GATEWAY_ADMIN_API_KEY: 'admin-key' }) + .config.adminApiKey, + ).toBe('admin-key'); + }); + + // A pipeline that passes every secret it knows of hands an unset one + // over as an empty string; that is "not configured", not a refusal to + // boot — and not a key that an empty `Authorization` could match. + it.each(['', ' '])('reads %j as not set', (blank) => { + expect( + loadConfig({ ...complete(), AI_GATEWAY_ADMIN_API_KEY: blank }).config + .adminApiKey, + ).toBeNull(); + }); + + it('may be the same value as the API key, which makes it one key', () => { + const { config } = loadConfig({ + ...complete(), + AI_GATEWAY_ADMIN_API_KEY: 'api-key', + }); + expect(config.adminApiKey).toBe(config.apiKey); + }); + + // Development generates what it must have to start. Turning on a way to + // change the pool is not that, so it stays the developer's to ask for. + it('is never generated for development', () => { + const { config, generated } = loadConfig( + {}, + { generateMissingSecrets: true }, + ); + expect(generated.map((secret) => secret.name)).toEqual([ + 'AI_GATEWAY_API_KEY', + 'AI_GATEWAY_ENCRYPTION_KEY', + ]); + expect(config.adminApiKey).toBeNull(); + }); + }); + // The panel lost its login: a deployment that still sets the old secrets // must boot, not trip over an unknown key. it('ignores the retired panel-password and session secrets', () => { diff --git a/services/ai-gateway/backend/config.ts b/services/ai-gateway/backend/config.ts index ba598e0ed7..7a301c3ae8 100644 --- a/services/ai-gateway/backend/config.ts +++ b/services/ai-gateway/backend/config.ts @@ -31,8 +31,20 @@ const positiveSeconds = (fallback: number) => const nonNegativeSeconds = (fallback: number) => z.coerce.number().int().nonnegative().default(fallback); +/** + * A variable that may be left blank. A deployment pipeline that passes every + * secret it knows of hands an unset one over as an empty string, which must + * read as "not configured", not as a key that is invalid. + */ +const optionalSecret = z.preprocess( + (value) => + typeof value === 'string' && value.trim() === '' ? undefined : value, + z.string().min(1).optional(), +); + const schema = z.object({ AI_GATEWAY_API_KEY: z.string().min(1), + AI_GATEWAY_ADMIN_API_KEY: optionalSecret, AI_GATEWAY_ENCRYPTION_KEY: z.string().min(1), AI_GATEWAY_DATA_DIR: z.string().min(1).default('.data'), AI_GATEWAY_REFRESH_INTERVAL_SECONDS: positiveSeconds(300), @@ -46,6 +58,12 @@ const schema = z.object({ export interface GatewayConfig { apiKey: string; + /** + * The key that may change accounts over the REST API; null when none is + * set, which leaves the API read-only. Never generated for development — + * switching a way to change the pool on is the operator's choice. + */ + adminApiKey: string | null; encryptionKey: Buffer; dataDir: string; refreshIntervalSeconds: number; @@ -139,6 +157,7 @@ export function loadConfig( return { config: { apiKey: parsed.data.AI_GATEWAY_API_KEY, + adminApiKey: parsed.data.AI_GATEWAY_ADMIN_API_KEY ?? null, encryptionKey, dataDir: parsed.data.AI_GATEWAY_DATA_DIR, refreshIntervalSeconds: parsed.data.AI_GATEWAY_REFRESH_INTERVAL_SECONDS, diff --git a/services/ai-gateway/backend/envelope.ts b/services/ai-gateway/backend/envelope.ts new file mode 100644 index 0000000000..c55009ed3d --- /dev/null +++ b/services/ai-gateway/backend/envelope.ts @@ -0,0 +1,10 @@ +/** + * The error envelope every failing route answers with. + * + * One shape for the panel's routes and the machine doors alike, so a client + * reads a refusal the same way wherever it came from: a stable `code` to + * branch on, and a sentence for a person. + */ +export function fail(code: string, message: string) { + return { error: { code, message } } as const; +} diff --git a/services/ai-gateway/backend/gateway.ts b/services/ai-gateway/backend/gateway.ts index 2c538a03e6..70c6b82110 100644 --- a/services/ai-gateway/backend/gateway.ts +++ b/services/ai-gateway/backend/gateway.ts @@ -54,7 +54,12 @@ export function createGateway(options: CreateGatewayOptions = {}): Gateway { usageMinIntervalSeconds: config.usageMinIntervalSeconds, }); - const api = createApi({ accounts, providers, apiKey: config.apiKey }); + const api = createApi({ + accounts, + providers, + apiKey: config.apiKey, + adminApiKey: config.adminApiKey, + }); return { config, diff --git a/services/ai-gateway/backend/routes.test.ts b/services/ai-gateway/backend/routes.test.ts index 825da563fa..193fb366da 100644 --- a/services/ai-gateway/backend/routes.test.ts +++ b/services/ai-gateway/backend/routes.test.ts @@ -20,6 +20,8 @@ const view: AccountView = { accountEmail: 'you@example.com', subscription: null, status: 'active', + state: 'available', + limitedUntil: null, expiresAt: null, scopes: null, createdAt: '2026-09-21T10:00:00.000Z', @@ -74,7 +76,10 @@ const chatgpt: TokenHandout = { const pool = [claude, chatgpt]; -function build(overrides: Partial = {}) { +function build( + overrides: Partial = {}, + adminApiKey: string | null = null, +) { // Held as a local so assertions never reference the method off the object // (an unbound method reference), and so an override cannot make it stale. const handOutTokens = vi.fn((provider?: ProviderId) => @@ -85,24 +90,32 @@ function build(overrides: Partial = {}) { ), ); + // The calls a refusal must not reach, held the same way. + const list = vi.fn(() => Promise.resolve([view])); + const beginAuthorization = vi.fn(() => + Promise.resolve({ + state: 'state-1', + flow: 'paste' as const, + authorizeUrl: 'https://example.test/authorize', + pasteStyle: 'code' as const, + }), + ); + const completeAuthorization = vi.fn(() => Promise.resolve(view)); + const authorizationStatus = vi.fn(() => + Promise.resolve({ status: 'pending' as const }), + ); + const remove = vi.fn(() => Promise.resolve(true)); + const accounts: AccountService = { - list: vi.fn(() => Promise.resolve([view])), - beginAuthorization: vi.fn(() => - Promise.resolve({ - state: 'state-1', - flow: 'paste' as const, - authorizeUrl: 'https://example.test/authorize', - pasteStyle: 'code' as const, - }), - ), - completeAuthorization: vi.fn(() => Promise.resolve(view)), + list, + get: vi.fn((id: string) => Promise.resolve(id === view.id ? view : null)), + beginAuthorization, + completeAuthorization, completeRedirect: vi.fn(() => Promise.resolve({ status: 'connected' as const, account: view }), ), - authorizationStatus: vi.fn(() => - Promise.resolve({ status: 'pending' as const }), - ), - remove: vi.fn(() => Promise.resolve(true)), + authorizationStatus, + remove, cliCommand: vi.fn(() => Promise.resolve('FAKE_TOKEN=access-1 fake')), refreshAll: vi.fn(() => Promise.resolve()), handOutTokens, @@ -112,15 +125,28 @@ function build(overrides: Partial = {}) { // The real registry: building it touches no network, and the catalog the // panel reads should be the one the gateway would actually offer. const providers = createProviderRegistry(); - const api = createApi({ accounts, providers, apiKey: API_KEY }); + const api = createApi({ accounts, providers, apiKey: API_KEY, adminApiKey }); const call = (path: string, init?: RequestInit) => api.fetch(new Request(`http://gateway.test${path}`, init)); - return { api, call, handOutTokens }; + return { + api, + call, + handOutTokens, + calls: { + list, + beginAuthorization, + completeAuthorization, + authorizationStatus, + remove, + }, + }; } const withKey = { authorization: `Bearer ${API_KEY}` }; +const ADMIN_KEY = 'the-admin-key'; +const withAdminKey = { authorization: `Bearer ${ADMIN_KEY}` }; describe('the panel routes', () => { const paths = [ @@ -575,6 +601,598 @@ describe('the token endpoints', () => { }); }); +describe('the accounts API', () => { + const json = { 'content-type': 'application/json' }; + + const limited: AccountView = { + ...view, + id: 'account-9', + state: 'limited', + limitedUntil: '2026-09-24T10:00:00.000Z', + subscription: { plan: 'max', tier: '20x' }, + usage: { + checkedAt: '2026-09-21T10:00:00.000Z', + stale: false, + limited: null, + windows: [ + { + kind: 'session', + label: null, + utilization: 100, + resetsAt: '2026-09-21T10:05:00.000Z', + windowSeconds: 18_000, + blocking: true, + }, + { + kind: 'weekly', + label: null, + utilization: 100, + resetsAt: '2026-09-24T10:00:00.000Z', + windowSeconds: 604_800, + blocking: true, + }, + ], + }, + }; + + const reads = [ + ['GET', '/api/v1/accounts'], + ['GET', '/api/v1/accounts/account-1'], + ] as const; + + const changes = [ + ['POST', '/api/v1/authorizations', { provider: 'anthropic' }], + ['GET', '/api/v1/authorizations/state-1', undefined], + ['POST', '/api/v1/authorizations/state-1/complete', { pasted: 'code-1' }], + ['DELETE', '/api/v1/accounts/account-1', undefined], + ] as const; + + const all = [ + ...reads.map(([method, path]) => [method, path, undefined] as const), + ...changes, + ]; + + function send( + call: ReturnType['call'], + method: string, + path: string, + body: unknown, + headers: Record = {}, + ) { + return call(path, { + method, + headers: body === undefined ? headers : { ...json, ...headers }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + } + + describe('who may ask', () => { + it.each(all)('refuses %s %s with no key', async (method, path, body) => { + const { call } = build({}, ADMIN_KEY); + const response = await send(call, method, path, body); + expect(response.status).toBe(401); + expect(response.headers.get('www-authenticate')).toBe('Bearer'); + expect(response.headers.get('cache-control')).toBe('no-store'); + expect(await response.json()).toMatchObject({ + error: { code: 'invalid_api_key' }, + }); + }); + + it.each(all)( + 'refuses %s %s with a key that is neither', + async (method, path, body) => { + const { call } = build({}, ADMIN_KEY); + const response = await send(call, method, path, body, { + authorization: 'Bearer wrong', + }); + expect(response.status).toBe(401); + }, + ); + + it.each(reads)('lets the token key read: %s %s', async (method, path) => { + const { call } = build({}, ADMIN_KEY); + expect((await send(call, method, path, undefined, withKey)).status).toBe( + 200, + ); + }); + + it.each(reads)('lets the admin key read: %s %s', async (method, path) => { + const { call } = build({}, ADMIN_KEY); + expect( + (await send(call, method, path, undefined, withAdminKey)).status, + ).toBe(200); + }); + + it.each(changes)( + 'keeps %s %s from the token key, which may only read', + async (method, path, body) => { + const { call, calls } = build({}, ADMIN_KEY); + const response = await send(call, method, path, body, withKey); + expect(response.status).toBe(403); + expect(await response.json()).toMatchObject({ + error: { code: 'admin_key_required' }, + }); + // Refused before the service heard of it. + expect(calls.beginAuthorization).not.toHaveBeenCalled(); + expect(calls.completeAuthorization).not.toHaveBeenCalled(); + expect(calls.authorizationStatus).not.toHaveBeenCalled(); + expect(calls.remove).not.toHaveBeenCalled(); + }, + ); + + it.each(changes)( + 'says %s %s is switched off while the gateway has no admin key', + async (method, path, body) => { + const { call, calls } = build({}, null); + const response = await send(call, method, path, body, withKey); + expect(response.status).toBe(403); + expect(await response.json()).toMatchObject({ + error: { code: 'control_disabled' }, + }); + expect(calls.remove).not.toHaveBeenCalled(); + }, + ); + + it('still lets the token key read while changing is switched off', async () => { + const { call } = build({}, null); + expect( + (await call('/api/v1/accounts', { headers: withKey })).status, + ).toBe(200); + }); + + it('does not let a missing admin key be matched by an empty one', async () => { + const { call } = build({}, null); + const response = await call('/api/v1/accounts/account-1', { + method: 'DELETE', + headers: { authorization: 'Bearer ' }, + }); + expect(response.status).toBe(401); + }); + + it.each(changes)( + 'lets the admin key through to %s %s', + async (method, path, body) => { + const { call } = build({}, ADMIN_KEY); + const response = await send(call, method, path, body, withAdminKey); + expect(response.status).toBeLessThan(300); + }, + ); + + it('is one key when both are the same value', async () => { + const api = build({}, API_KEY); + const response = await send( + api.call, + 'DELETE', + '/api/v1/accounts/account-1', + undefined, + withKey, + ); + expect(response.status).toBe(204); + }); + + it('takes the key in either spelling', async () => { + const { call } = build({}, ADMIN_KEY); + expect( + (await call('/api/v1/accounts', { headers: { 'x-api-key': API_KEY } })) + .status, + ).toBe(200); + expect( + ( + await call('/api/v1/accounts/account-1', { + method: 'DELETE', + headers: { 'x-api-key': ADMIN_KEY }, + }) + ).status, + ).toBe(204); + }); + + it('opens no panel route to a key, and no key route to a browser', async () => { + const { call } = build({}, ADMIN_KEY); + // The panel's routes still ask nothing… + expect((await call('/api/accounts')).status).toBe(200); + // …and the machine door's twin of the same list asks for a key. + expect((await call('/api/v1/accounts')).status).toBe(401); + }); + }); + + describe('reading', () => { + it('lists the pool without a credential, in the token door’s names', async () => { + const { call } = build({ list: vi.fn(() => Promise.resolve([limited])) }); + const response = await call('/api/v1/accounts', { headers: withKey }); + expect(response.status).toBe(200); + expect(response.headers.get('cache-control')).toBe('no-store'); + expect(await response.json()).toEqual({ + accounts: [ + { + id: 'account-9', + provider: 'anthropic', + label: 'you@example.com', + account_email: 'you@example.com', + subscription: { plan: 'max', tier: '20x' }, + status: 'active', + state: 'limited', + limited_until: '2026-09-24T10:00:00.000Z', + expires_at: null, + scopes: null, + created_at: '2026-09-21T10:00:00.000Z', + last_refreshed_at: null, + usage: { + checked_at: '2026-09-21T10:00:00.000Z', + stale: false, + limited: null, + windows: [ + { + kind: 'session', + label: null, + utilization: 100, + resets_at: '2026-09-21T10:05:00.000Z', + window_seconds: 18_000, + blocking: true, + }, + { + kind: 'weekly', + label: null, + utilization: 100, + resets_at: '2026-09-24T10:00:00.000Z', + window_seconds: 604_800, + blocking: true, + }, + ], + }, + }, + ], + }); + }); + + it('never puts a token, a refresh token or a secret on the wire', async () => { + const { call } = build({ list: vi.fn(() => Promise.resolve([limited])) }); + const text = await ( + await call('/api/v1/accounts', { headers: withAdminKey }) + ).text(); + expect(text).not.toMatch(/access_token|refresh_token|accessToken/); + }); + + it('narrows the list by provider and by state', async () => { + const claudeLimited = limited; + const chatgptAvailable: AccountView = { + ...view, + id: 'account-2', + provider: 'openai', + }; + const { call } = build( + { + list: vi.fn(() => + Promise.resolve([claudeLimited, chatgptAvailable, view]), + ), + }, + ADMIN_KEY, + ); + const ids = async (query: string) => + z + .object({ accounts: z.array(z.object({ id: z.string() })) }) + .parse( + await ( + await call(`/api/v1/accounts${query}`, { headers: withKey }) + ).json(), + ) + .accounts.map((account) => account.id); + + expect(await ids('')).toEqual(['account-9', 'account-2', 'account-1']); + expect(await ids('?provider=openai')).toEqual(['account-2']); + expect(await ids('?state=limited')).toEqual(['account-9']); + expect(await ids('?provider=anthropic&state=available')).toEqual([ + 'account-1', + ]); + }); + + it('refuses a provider or a state it does not know', async () => { + const { call, calls } = build(); + for (const query of ['?provider=gemini', '?state=asleep']) { + const response = await call(`/api/v1/accounts${query}`, { + headers: withKey, + }); + expect(response.status).toBe(400); + expect(await response.json()).toMatchObject({ + error: { code: 'invalid_request' }, + }); + } + expect(calls.list).not.toHaveBeenCalled(); + }); + + it('answers one account, and 404 for one that is gone', async () => { + const { call } = build(); + const found = await call('/api/v1/accounts/account-1', { + headers: withKey, + }); + expect(await found.json()).toMatchObject({ + account: { id: 'account-1', state: 'available', limited_until: null }, + }); + const gone = await call('/api/v1/accounts/gone', { headers: withKey }); + expect(gone.status).toBe(404); + expect(await gone.json()).toMatchObject({ + error: { code: 'unknown_account' }, + }); + }); + }); + + describe('changing', () => { + it('starts an authorization that needs no browser on the gateway’s own machine', async () => { + const beginAuthorization = vi.fn(() => + Promise.resolve({ + state: 'state-7', + flow: 'device' as const, + verificationUrl: 'https://auth.example.test/device', + userCode: 'ABCD-1234', + expiresAt: '2026-09-21T10:15:00.000Z', + pollIntervalSeconds: 5, + }), + ); + const { call } = build({ beginAuthorization }, ADMIN_KEY); + const response = await send( + call, + 'POST', + '/api/v1/authorizations', + { + provider: 'openai', + label: 'work', + method: 'browser', + account_id: 'account-2', + // Not read: a script has no `Origin`, and the body cannot name one. + loopbackOrigin: 'http://localhost:9999', + }, + // Even a browser-like caller does not get a redirect flow from here. + { ...withAdminKey, origin: 'http://localhost:3004' }, + ); + expect(response.status).toBe(201); + expect(await response.json()).toEqual({ + authorization: { + state: 'state-7', + flow: 'device', + verification_url: 'https://auth.example.test/device', + user_code: 'ABCD-1234', + expires_at: '2026-09-21T10:15:00.000Z', + poll_interval_seconds: 5, + }, + }); + expect(beginAuthorization).toHaveBeenCalledWith({ + provider: 'openai', + accountId: 'account-2', + label: 'work', + loopbackOrigin: null, + preferBrowser: true, + }); + }); + + it('tells a script how to finish a paste flow', async () => { + const { call } = build({}, ADMIN_KEY); + const response = await send( + call, + 'POST', + '/api/v1/authorizations', + { provider: 'anthropic' }, + withAdminKey, + ); + expect(await response.json()).toEqual({ + authorization: { + state: 'state-1', + flow: 'paste', + authorize_url: 'https://example.test/authorize', + paste_style: 'code', + }, + }); + }); + + it('refuses to start an authorization for a provider it does not hold', async () => { + const { call, calls } = build({}, ADMIN_KEY); + for (const body of [{ provider: 'gemini' }, {}, null]) { + const response = await send( + call, + 'POST', + '/api/v1/authorizations', + body, + withAdminKey, + ); + expect(response.status).toBe(400); + } + expect(calls.beginAuthorization).not.toHaveBeenCalled(); + }); + + it('says where an authorization stands, and what it connected', async () => { + const authorizationStatus = vi + .fn() + .mockResolvedValueOnce({ status: 'pending' }) + .mockResolvedValueOnce({ status: 'connected', account: limited }) + .mockResolvedValueOnce({ status: 'failed', code: 'denied' }); + const { call } = build({ authorizationStatus }, ADMIN_KEY); + const read = async () => + ( + await call('/api/v1/authorizations/state-1', { + headers: withAdminKey, + }) + ).json(); + + expect(await read()).toEqual({ + authorization: { state: 'state-1', status: 'pending' }, + }); + expect(await read()).toMatchObject({ + authorization: { + state: 'state-1', + status: 'connected', + account: { id: 'account-9', state: 'limited' }, + }, + }); + expect(await read()).toEqual({ + authorization: { state: 'state-1', status: 'failed', code: 'denied' }, + }); + }); + + it('completes a paste flow with what the person copied', async () => { + const completeAuthorization = vi.fn(() => Promise.resolve(limited)); + const { call } = build({ completeAuthorization }, ADMIN_KEY); + const response = await send( + call, + 'POST', + '/api/v1/authorizations/state-1/complete', + { pasted: 'code-1#state-1' }, + withAdminKey, + ); + expect(response.status).toBe(201); + expect(await response.json()).toMatchObject({ + account: { id: 'account-9', state: 'limited' }, + }); + expect(completeAuthorization).toHaveBeenCalledWith({ + state: 'state-1', + pasted: 'code-1#state-1', + }); + + const empty = await send( + call, + 'POST', + '/api/v1/authorizations/state-1/complete', + { pasted: '' }, + withAdminKey, + ); + expect(empty.status).toBe(400); + }); + + it('answers a refused authorization with its own code, as the panel does', async () => { + const { call } = build( + { + completeAuthorization: vi.fn(() => + Promise.reject( + new AccountError('unknown_state', 'That authorization expired.'), + ), + ), + beginAuthorization: vi.fn(() => + Promise.reject(new AccountError('unavailable', 'OpenAI is down.')), + ), + }, + ADMIN_KEY, + ); + const complete = await send( + call, + 'POST', + '/api/v1/authorizations/state-1/complete', + { pasted: 'x' }, + withAdminKey, + ); + expect(complete.status).toBe(400); + expect(await complete.json()).toMatchObject({ + error: { code: 'unknown_state' }, + }); + const start = await send( + call, + 'POST', + '/api/v1/authorizations', + { provider: 'openai' }, + withAdminKey, + ); + expect(start.status).toBe(502); + }); + + it('leaves one line for every change that went through and none for a refusal', async () => { + const info = vi + .spyOn(console, 'info') + .mockImplementation(() => undefined); + try { + const { call } = build( + { + // A device code connects its account in a status read. + authorizationStatus: vi.fn(() => + Promise.resolve({ status: 'connected' as const, account: view }), + ), + }, + ADMIN_KEY, + ); + await send( + call, + 'POST', + '/api/v1/authorizations', + { provider: 'anthropic', label: 'work\n[ai-gateway] forged line' }, + withAdminKey, + ); + await send( + call, + 'POST', + '/api/v1/authorizations', + { provider: 'anthropic', account_id: 'account-1' }, + withAdminKey, + ); + await send( + call, + 'POST', + '/api/v1/authorizations/state-1/complete', + { pasted: 'code-1' }, + withAdminKey, + ); + await call('/api/v1/authorizations/state-1', { headers: withAdminKey }); + await call('/api/v1/accounts/account-1', { + method: 'DELETE', + headers: withAdminKey, + }); + + // Refused: the wrong key, or an account that is not there. + await call('/api/v1/accounts/account-1', { + method: 'DELETE', + headers: withKey, + }); + await call('/api/v1/accounts/account-1', { method: 'DELETE' }); + + expect(info.mock.calls.map(([line]) => line)).toEqual([ + '[ai-gateway] accounts API: started adding an account for anthropic', + '[ai-gateway] accounts API: started signing account account-1 in again', + // Finished by a paste, then seen connected by a status read. + '[ai-gateway] accounts API: connected account account-1', + '[ai-gateway] accounts API: connected account account-1', + '[ai-gateway] accounts API: removed account account-1', + ]); + } finally { + info.mockRestore(); + } + }); + + it('does not log an account the gateway could not find', async () => { + const info = vi + .spyOn(console, 'info') + .mockImplementation(() => undefined); + try { + const { call } = build( + { remove: vi.fn(() => Promise.resolve(false)) }, + ADMIN_KEY, + ); + const response = await call('/api/v1/accounts/not-there\nforged', { + method: 'DELETE', + headers: withAdminKey, + }); + expect(response.status).toBe(404); + expect(info).not.toHaveBeenCalled(); + } finally { + info.mockRestore(); + } + }); + + it('removes an account, and 404s one that is gone', async () => { + const remove = vi + .fn() + .mockResolvedValueOnce(true) + .mockResolvedValueOnce(false); + const { call } = build({ remove }, ADMIN_KEY); + const first = await call('/api/v1/accounts/account-1', { + method: 'DELETE', + headers: withAdminKey, + }); + expect(first.status).toBe(204); + expect(first.headers.get('cache-control')).toBe('no-store'); + const second = await call('/api/v1/accounts/account-1', { + method: 'DELETE', + headers: withAdminKey, + }); + expect(second.status).toBe(404); + expect(remove).toHaveBeenCalledWith('account-1'); + }); + }); +}); + describe('createApiDispatcher', () => { it('claims the gateway routes and leaves everything else alone', () => { const { api } = build(); @@ -587,6 +1205,7 @@ describe('createApiDispatcher', () => { expect(at('/api/accounts')).not.toBeNull(); expect(at('/api/tokens/anthropic')).not.toBeNull(); + expect(at('/api/v1/accounts')).not.toBeNull(); // Where a vendor's loopback redirect lands, outside `/api`. expect(at('/callback?state=state-1&code=code-1')).not.toBeNull(); // The shared React server owns the health probe and the SPA. diff --git a/services/ai-gateway/backend/routes.ts b/services/ai-gateway/backend/routes.ts index 1e74a7d951..e7716c4b3d 100644 --- a/services/ai-gateway/backend/routes.ts +++ b/services/ai-gateway/backend/routes.ts @@ -1,11 +1,13 @@ /** * The gateway's HTTP surface. * - * One door, and it guards the tokens. `GET /api/tokens*` sits behind the API - * key and returns nothing but credentials; the panel's routes carry no - * credential of their own, because the panel has no login — whatever fronts - * this service decides who reaches it. Keeping the key OFF the panel routes is - * deliberate: a machine holding it still cannot add or remove an account. + * Three audiences, three doors. `GET /api/tokens*` sits behind the API key and + * returns nothing but credentials. `/api/v1/*` (`accounts-api.ts`) is how a + * script reads and changes the pool: the API key reads, a separate admin key + * changes. The panel's routes carry no credential of their own, because the + * panel has no login — whatever fronts this service decides who reaches it. + * Keeping the keys OFF the panel routes is deliberate: it is what lets a + * proxy pass the machine doors and nothing else without opening the panel. * * The token endpoints answer in the shape the retired cc-gateway used — * `{"tokens": [{ id, label, account_email, status, access_token, expires_at, @@ -22,8 +24,10 @@ import { type AccountService, type TokenHandout, } from './accounts'; +import { createAccountsApi } from './accounts-api'; import { readApiKey } from './api-key'; import { secretsMatch } from './crypto'; +import { fail } from './envelope'; import { describeProviders, type ProviderRegistry } from './providers/index'; import { isProviderId, PROVIDER_IDS } from './providers/types'; @@ -31,6 +35,8 @@ export interface ApiOptions { accounts: AccountService; providers: ProviderRegistry; apiKey: string; + /** May change accounts over `/api/v1`; null or absent leaves it read-only. */ + adminApiKey?: string | null; } const authorizeSchema = z.object({ @@ -49,11 +55,6 @@ const completeSchema = z.object({ pasted: z.string().min(1), }); -/** The error envelope every failing route answers with. */ -function fail(code: string, message: string) { - return { error: { code, message } } as const; -} - /** * One handed-out credential, in cc-gateway's wire shape. * @@ -244,6 +245,20 @@ export function createApi(options: ApiOptions) { return c.json({ tokens: tokens.map(serializeToken) }); }); + // --- The accounts API ---------------------------------------------------- + + // Its own prefix, and a router of its own whose every route names its guard: + // nothing here is the panel's, so a proxy rule that lets `/api/v1` through + // can never open a panel route by accident. + api.route( + '/v1', + createAccountsApi({ + accounts, + apiKey: options.apiKey, + adminApiKey: options.adminApiKey ?? null, + }), + ); + // --- The vendor's way back ---------------------------------------------- /** diff --git a/services/ai-gateway/backend/store.test.ts b/services/ai-gateway/backend/store.test.ts index 6eec335ac0..e3c90d01ce 100644 --- a/services/ai-gateway/backend/store.test.ts +++ b/services/ai-gateway/backend/store.test.ts @@ -265,8 +265,11 @@ describe('createFileAccountStore', () => { }); describe('toAccountView', () => { + // Ten past ten: the instant every reading below was taken is behind it. + const NOW = Date.parse('2026-09-21T10:10:00.000Z'); + it('drops both credentials', () => { - const view = toAccountView(account()); + const view = toAccountView(account(), NOW); expect(view).not.toHaveProperty('accessToken'); expect(view).not.toHaveProperty('refreshToken'); expect(view.label).toBe('you@example.com'); @@ -280,6 +283,7 @@ describe('toAccountView', () => { it('calls a reading current when the latest try at it succeeded', () => { const view = toAccountView( account({ usage: reading, usageAttemptedAt: reading.checkedAt }), + NOW, ); expect(view.usage?.stale).toBe(false); }); @@ -291,6 +295,7 @@ describe('toAccountView', () => { usage: reading, usageAttemptedAt: '2026-09-21T13:00:00.000Z', }), + NOW, ); expect(view.usage).toMatchObject({ checkedAt: '2026-09-21T10:00:00.000Z', @@ -299,7 +304,84 @@ describe('toAccountView', () => { }); it('calls an expired account’s reading stale, since nothing reads it', () => { - const view = toAccountView(account({ status: 'expired', usage: reading })); + const view = toAccountView( + account({ status: 'expired', usage: reading }), + NOW, + ); + expect(view.usage?.stale).toBe(true); + }); + + const weekly = (resetsAt: string, utilization = 100) => ({ + kind: 'weekly' as const, + label: null, + utilization, + resetsAt, + windowSeconds: 604_800, + }); + + it('calls a reading stale once a window has rolled over since it was taken', () => { + const view = toAccountView( + account({ + usage: { + windows: [weekly('2026-09-21T10:05:00.000Z')], + checkedAt: reading.checkedAt, + }, + usageAttemptedAt: reading.checkedAt, + }), + NOW, + ); expect(view.usage?.stale).toBe(true); + // The rollover is behind the clock, so the spent window stops blocking + // even though the figure beside it still says 100. + expect(view.state).toBe('available'); + expect(view.usage?.windows[0]).toMatchObject({ + utilization: 100, + blocking: false, + }); + }); + + it('does not doubt a reading for a rollover it already knew about', () => { + // A vendor that stamps a reset earlier than its own reading is the + // reading's oddity, not news: it would otherwise be stale for ever. + const view = toAccountView( + account({ + usage: { + windows: [weekly('2026-09-21T09:00:00.000Z', 30)], + checkedAt: reading.checkedAt, + }, + usageAttemptedAt: reading.checkedAt, + }), + NOW, + ); + expect(view.usage?.stale).toBe(false); + }); + + it('carries the state, when a limited account comes back, and which window blocks', () => { + const view = toAccountView( + account({ + usage: { + windows: [ + { ...weekly('2026-09-21T10:30:00.000Z'), kind: 'session' }, + weekly('2026-09-24T10:00:00.000Z'), + { ...weekly('2026-09-24T10:00:00.000Z', 100), kind: 'scoped' }, + ], + checkedAt: reading.checkedAt, + limited: true, + }, + usageAttemptedAt: reading.checkedAt, + }), + NOW, + ); + expect(view).toMatchObject({ + status: 'active', + state: 'limited', + limitedUntil: '2026-09-24T10:00:00.000Z', + }); + expect(view.usage?.windows.map((window) => window.blocking)).toEqual([ + true, + true, + false, + ]); + expect(view.usage?.limited).toBe(true); }); }); diff --git a/services/ai-gateway/backend/store.ts b/services/ai-gateway/backend/store.ts index 814da2c57e..b7e25d5a62 100644 --- a/services/ai-gateway/backend/store.ts +++ b/services/ai-gateway/backend/store.ts @@ -20,6 +20,11 @@ import { dirname, join } from 'node:path'; import { z } from 'zod'; +import { + deriveAccountState, + rolledOverSince, + type AccountState, +} from './account-state'; import { isRecord } from './providers/oauth'; import { PROVIDER_IDS } from './providers/types'; import type { ProviderId, Subscription, UsageWindow } from './providers/types'; @@ -433,6 +438,12 @@ export function createMemoryAccountStore(): AccountStore { }; } +/** A usage window as the panel and the REST API draw it. */ +export interface ViewWindow extends UsageWindow { + /** This window is why the account is limited: spent, and not yet rolled over. */ + blocking: boolean; +} + /** What the panel may see: every field except the credentials themselves. */ export interface AccountView { id: string; @@ -440,38 +451,59 @@ export interface AccountView { label: string; accountEmail: string | null; subscription: Subscription | null; + /** The credential's own status; `state` refines it with the quota. */ status: AccountStatus; + /** What the account is now — see `deriveAccountState`. */ + state: AccountState; + /** When a limited account's spent windows have all rolled over, if known. */ + limitedUntil: string | null; expiresAt: string | null; scopes: string | null; createdAt: string; lastRefreshedAt: string | null; /** * The last reading, when it was read, and whether it is stale: the latest - * attempt to read it failed, or the account cannot be read at all until it - * is signed in again. A stale reading is still the best figure there is, - * so it is shown — as what it is. + * attempt to read it failed, the account cannot be read at all until it is + * signed in again, or a window rolled over after the reading was taken. A + * stale reading is still the best figure there is, so it is shown — as what + * it is. */ usage: { - windows: UsageWindow[]; + windows: ViewWindow[]; checkedAt: string; stale: boolean; + /** The vendor's own "limit reached" signal; null when it sends none. */ + limited: boolean | null; } | null; } -/** Whether an account's figures are older than its latest try at them. */ -function readingIsStale(account: StoredAccount): boolean { +/** + * Whether an account's figures no longer describe it: the latest try at them + * failed, the account cannot be read until someone signs it in again, or a + * window rolled over since they were taken — the figure is then the last of + * the window before, not of the one running now. + */ +function readingIsStale(account: StoredAccount, nowMs: number): boolean { if (!account.usage) return false; if (account.status === 'expired') return true; const attempted = account.usageAttemptedAt ? new Date(account.usageAttemptedAt).getTime() : Number.NaN; const read = new Date(account.usage.checkedAt).getTime(); + if (Number.isFinite(attempted) && Number.isFinite(read) && attempted > read) { + return true; + } return ( - Number.isFinite(attempted) && Number.isFinite(read) && attempted > read + Number.isFinite(read) && + account.usage.windows.some((window) => rolledOverSince(window, read, nowMs)) ); } -export function toAccountView(account: StoredAccount): AccountView { +export function toAccountView( + account: StoredAccount, + nowMs: number, +): AccountView { + const { state, limitedUntil, blocking } = deriveAccountState(account, nowMs); return { id: account.id, provider: account.provider, @@ -479,12 +511,22 @@ export function toAccountView(account: StoredAccount): AccountView { accountEmail: account.accountEmail, subscription: account.subscription, status: account.status, + state, + limitedUntil, expiresAt: account.expiresAt, scopes: account.scopes, createdAt: account.createdAt, lastRefreshedAt: account.lastRefreshedAt, usage: account.usage - ? { ...account.usage, stale: readingIsStale(account) } + ? { + windows: account.usage.windows.map((window, index) => ({ + ...window, + blocking: blocking[index], + })), + checkedAt: account.usage.checkedAt, + stale: readingIsStale(account, nowMs), + limited: account.usage.limited ?? null, + } : null, }; } diff --git a/services/ai-gateway/lib/i18n/keys-dynamic.yml b/services/ai-gateway/lib/i18n/keys-dynamic.yml index acdd54fcac..a22330fa46 100644 --- a/services/ai-gateway/lib/i18n/keys-dynamic.yml +++ b/services/ai-gateway/lib/i18n/keys-dynamic.yml @@ -10,7 +10,7 @@ entries: # One key per provider id, chosen by the row's `provider` field. - providers - # One key per account status, chosen by the row's `status` field. + # One key per account state, chosen by the row's `state` field. - status # One key per usage-window kind the providers normalize onto. - usage.session diff --git a/services/ai-gateway/messages/de.yml b/services/ai-gateway/messages/de.yml index 47df84d71b..bda6a7d6ea 100644 --- a/services/ai-gateway/messages/de.yml +++ b/services/ai-gateway/messages/de.yml @@ -43,7 +43,8 @@ accounts: removed: '{label} ist nicht mehr im Pool.' removeFailed: Dieses Konto konnte nicht entfernt werden. status: - active: Aktiv + available: Verfügbar + limited: Limit erreicht expired: Neue Anmeldung nötig error: Letzter Aufruf fehlgeschlagen providers: @@ -56,6 +57,9 @@ usage: spent: '{percent} % verbraucht' spentAsOf: '{percent} % verbraucht, gelesen {when}' resets: Setzt sich {when} zurück + resetsNow: Setzt sich jetzt zurück + resetUnknown: 'Zurücksetzung: Zeitpunkt unbekannt' + rolledOver: Jetzt untilReset: '{window}: verbleibende Zeit bis zur Zurücksetzung' addAccount: title: Konto hinzufügen diff --git a/services/ai-gateway/messages/en.yml b/services/ai-gateway/messages/en.yml index 4b3063f3e7..68687bc8f1 100644 --- a/services/ai-gateway/messages/en.yml +++ b/services/ai-gateway/messages/en.yml @@ -43,7 +43,8 @@ accounts: removed: '{label} is no longer in the pool.' removeFailed: That account could not be removed. status: - active: Active + available: Available + limited: Limit reached expired: Needs reauthentication error: Last call failed providers: @@ -56,6 +57,9 @@ usage: spent: '{percent}% spent' spentAsOf: '{percent}% spent, read {when}' resets: Resets {when} + resetsNow: Resets now + resetUnknown: Reset time unknown + rolledOver: Now untilReset: '{window}: time until the window resets' addAccount: title: Add account diff --git a/services/ai-gateway/messages/fr.yml b/services/ai-gateway/messages/fr.yml index 26e643a3c2..373e58b749 100644 --- a/services/ai-gateway/messages/fr.yml +++ b/services/ai-gateway/messages/fr.yml @@ -43,7 +43,8 @@ accounts: removed: '{label} ne fait plus partie du pool.' removeFailed: Ce compte n’a pas pu être retiré. status: - active: Actif + available: Disponible + limited: Limite atteinte expired: Réautorisation nécessaire error: Dernier appel en échec providers: @@ -56,6 +57,9 @@ usage: spent: '{percent} % consommés' spentAsOf: '{percent} % consommés, lu {when}' resets: Réinitialisation {when} + resetsNow: Se réinitialise maintenant + resetUnknown: Heure de réinitialisation inconnue + rolledOver: Maintenant untilReset: '{window} : temps restant avant la réinitialisation' addAccount: title: Ajouter un compte diff --git a/services/ai-gateway/tests/e2e/specs/smoke.spec.ts b/services/ai-gateway/tests/e2e/specs/smoke.spec.ts index 3ac24f0a0d..247d39f048 100644 --- a/services/ai-gateway/tests/e2e/specs/smoke.spec.ts +++ b/services/ai-gateway/tests/e2e/specs/smoke.spec.ts @@ -73,3 +73,24 @@ test('every token endpoint refuses a request with no API key', async ({ expect(response.headers()['www-authenticate']).toBe('Bearer'); } }); + +test('every accounts-API route refuses a request with no API key', async ({ + request, +}) => { + // The panel's routes ask a browser for nothing; the machine door beside + // them asks everyone for a key, reads and changes alike. + const calls = [ + request.get('/api/v1/accounts'), + request.get('/api/v1/accounts/account-1'), + request.post('/api/v1/authorizations', { data: { provider: 'openai' } }), + request.get('/api/v1/authorizations/state-1'), + request.post('/api/v1/authorizations/state-1/complete', { + data: { pasted: 'code' }, + }), + request.delete('/api/v1/accounts/account-1'), + ]; + for (const response of await Promise.all(calls)) { + expect(response.status()).toBe(401); + expect(response.headers()['www-authenticate']).toBe('Bearer'); + } +}); diff --git a/services/ai-gateway/tests/manual/readme.md b/services/ai-gateway/tests/manual/readme.md index 4d65e487ea..77a4ee1980 100644 --- a/services/ai-gateway/tests/manual/readme.md +++ b/services/ai-gateway/tests/manual/readme.md @@ -36,7 +36,7 @@ prefix may shadow another. | Suite | Prefix | What it is | Resets | Rough cost | |---|---|---|---|---| | [smoke](suites/smoke.md) | `SMOKE-` | is this build even drivable — run it before investing in anything bigger | once, at the start | 10 min | -| [accounts](suites/accounts.md) | `ACCT-` | the credential lifecycle against the real vendors — the one thing no spec can drive | before the suite | 30 min | +| [accounts](suites/accounts.md) | `ACCT-` | the credential lifecycle against the real vendors — the one thing no spec can drive | before the suite | 40 min | ## How a round runs @@ -74,7 +74,10 @@ Change-scoped, by area: | copy or catalogs (any locale) | `SMOKE-4` | | controls, focus, geometry | `SMOKE-5` · [`automation.md`](reference/automation.md) first | | how the panel reads a failed request (`app/lib/api.ts`, the list's re-read) | `ACCT-19`, `ACCT-45`, `ACCT-46` | -| how the panel draws a reading (`app/lib/usage-tint.ts`, `app/lib/usage-windows.ts`, the Usage and Resets in cells, a spent row) | `ACCT-25`, `ACCT-26`, `ACCT-30`, `ACCT-31`, `ACCT-35`, `ACCT-36`, `ACCT-47` | +| how the panel draws a reading (`app/lib/usage-tint.ts`, `app/lib/usage-windows.ts`, the Usage, Status and Resets in cells, a spent row) | `ACCT-25`, `ACCT-26`, `ACCT-30`, `ACCT-31`, `ACCT-35`, `ACCT-36`, `ACCT-47`, `ACCT-48`, `ACCT-49` | +| what state an account is in, or the order of the rows (`backend/account-state.ts`, `app/lib/account-order.ts`) | `ACCT-27`, `ACCT-28`, `ACCT-47`, `ACCT-48`, `ACCT-49`, `ACCT-50` | +| the REST door (`backend/accounts-api.ts`, the admin key in `backend/config.ts`) | `ACCT-50`, `ACCT-51`, `ACCT-52` | +| the header strip | `SMOKE-9`, `SMOKE-11` | ## How a box works diff --git a/services/ai-gateway/tests/manual/reference/automation.md b/services/ai-gateway/tests/manual/reference/automation.md index c7db14a8a3..6aa61adebc 100644 --- a/services/ai-gateway/tests/manual/reference/automation.md +++ b/services/ai-gateway/tests/manual/reference/automation.md @@ -16,6 +16,9 @@ a spec failure and belongs in the gate, not in a round. | The API key guards the tokens and nothing else | `backend/routes.test.ts` + `tests/e2e/specs/smoke.spec.ts` | nothing — all three token endpoints are asserted to answer 401 without a key and with a wrong one, and the panel routes to answer without one | | The split: one endpoint per vendor, in cc-gateway's shape | `backend/routes.test.ts` + `backend/accounts.test.ts` | the live end of it (`ACCT-21` … `ACCT-24`) — the specs pin the field names, the filtering and the 404, but only a real pool proves the token an endpoint hands out is the one its CLI accepts | | OAuth URL construction, callback parsing, PKCE, the three ways a grant comes back | `backend/providers/{anthropic,openai,oauth}.test.ts` + `backend/accounts.test.ts` + `backend/routes.test.ts` | nothing below the vendor's own page — the authorize URLs, the paste shapes, the S256 derivation, the device code and its polling, the loopback redirect chosen from `Origin`, and `/callback` sending the browser back are all asserted. The consent itself is `ACCT-3`, `ACCT-4`, `ACCT-39` | +| The REST door for accounts: who may read, who may change, and every refusal | `backend/routes.test.ts` + `backend/config.test.ts` | the live end of it (`ACCT-50` … `ACCT-52`) — the specs pin the two keys (a missing, wrong or insufficient key answers 401 or 403 before the service hears of the call), `control_disabled` while no admin key is set, one key when both are equal, the panel's open routes staying open beside the door's closed ones, the filters, the answer's field names with no credential in it, the flows a script may and may not be offered, and the blank admin key reading as unset; only a real pool proves the answers agree with the screen and a real vendor completes what a script starts | +| What state an account is in, and until when it is limited | `backend/account-state.test.ts` + `backend/store.test.ts` | how the answer READS — the status words, the hourglass, which clock is in full strength (`ACCT-47` … `ACCT-49`) — the specs pin the rule: only session and weekly windows limit an account, the return is the latest spent rollover (five minutes beside three days is three days), a rollover behind the clock stops blocking and makes the reading stale, an unknown rollover makes the return unknown, and the vendor's own limit flag | +| The order of the rows, and the Status and Resets in cells | `app/lib/account-order.test.ts` + `app/lib/usage-windows.test.ts` + `app/components/accounts-screen.test.tsx` | the look (`ACCT-27`, `ACCT-47` … `ACCT-49`) — the specs pin vendor, then state, then the soonest return, then address in the reader's locale; which window is the return; the success tint only on the account's own return inside the hour; and that the grey spares the two cells that explain it | | Usage-payload mapping (both vendors) | `backend/providers/{anthropic,openai}.test.ts` | how the mapped windows READ in the table — bar widths, the scoped window's vendor name, the reset countdown against the wall clock | | Token refresh, expiry skew, the refresh stagger, the hand-out floor, the usage-poll floor | `backend/accounts.test.ts` + `backend/routes.test.ts` + `backend/config.test.ts` | nothing at the unit level — the specs also stage the races: one refresh shared by callers that arrive together, a rotated grant surviving a read that was in flight, an authenticated usage rejection recovering that exact generation, a late rejection preserving a terminal refresh refusal, a refusal told from a rate limit, a failed read keeping its figures and their time. They pin the pool of the 2026-09-28 incident too: two accounts refreshed together plan their next refreshes hours apart and a month of passes never refreshes both in one pass, two due accounts of a vendor are refreshed ten minutes apart unless a token reaches its skew point, a hand-out refreshes only the account due under its own threshold, a token inside the floor is served `available: false` until its `refresh_at` while another account can take the work and available again once the refresh lands, a floor hold reads `hold: "refresh"` and a spent quota `hold: "quota"` (also when the floor holds too), so a consumer can tell the hold it may fall back to, a vendor's last servable account is never held back, a failing due refresh holds the account back in both its `active` and `error` phases, and `refresh_at` is serialized beside `expires_at`. The live cadence over a real interval is `ACCT-12`, a live failing read `ACCT-38` | | Stable account identity, quota eligibility, and independent account refresh | `backend/accounts.test.ts` + `backend/routes.test.ts` + `backend/store.test.ts` + `backend/rollback.test.ts` | nothing — covers global versus model caps, explicit vendor limit flags, reset and 15-minute freshness boundaries, cached readings, metrics failures preserving valid credentials, coalesced usage calls, parallel accounts, corrupt and removed account isolation, reauthorization across concurrent refreshes, and stored flags surviving a restart while older releases can still read the document | @@ -25,7 +28,7 @@ a spec failure and belongs in the gate, not in a round. | The account document on disk | `backend/store.test.ts` | survival across a real restart (`ACCT-13`) | | Configuration and the fail-fast boot | `backend/config.test.ts` | nothing | | A path no file can carry — a NUL or another C0 control (`/%00`, `/a%00b`), or one past the OS path limit (5000 characters) — answers the panel like any unknown path, never a reported 500 | `packages/ui/src/server/static-paths.integration.test.ts` (`startReactServer`, which `server.ts` runs; `reportError` is not called) | nothing — the panel ships no 404 page, so it answers the shell with a 200, as it does for `/nope` | -| The image: it builds from the workspace, boots on the two secrets, answers `/api/health`, serves the panel, and refuses every token endpoint to a caller with nothing | `services/platform/tests/integration/container-ai-gateway-test.ts` (`bun run docker:test:ai-gateway`; runs on a pull request that touches the service and on every release tag) | nothing | +| The image: it builds from the workspace, boots on the two secrets, answers `/api/health`, serves the panel, and refuses every token endpoint and the accounts API to a caller with nothing | `services/platform/tests/integration/container-ai-gateway-test.ts` (`bun run docker:test:ai-gateway`; runs on a pull request that touches the service and on every release tag) | nothing | | **The OAuth round trip itself** | — | **manual-only** — consent happens on a vendor's screen, for an account only its owner has; nothing headless can approve it | | **Handing a token to the vendor's CLI** | — | **manual-only** — proving `claude` and `codex` actually start on the token needs both CLIs and a live subscription | | Layout, focus order, theme, narrow viewports | — | **manual-only** — `SMOKE-4` … `SMOKE-10` | diff --git a/services/ai-gateway/tests/manual/reference/error-codes.md b/services/ai-gateway/tests/manual/reference/error-codes.md index ac4c0c1cb6..6753dcf00a 100644 --- a/services/ai-gateway/tests/manual/reference/error-codes.md +++ b/services/ai-gateway/tests/manual/reference/error-codes.md @@ -27,9 +27,11 @@ Never a UI message — seeing one of these in the UI is itself a bug. | Code | Where it shows up | |---|---| -| `invalid_api_key` | Any `GET /api/tokens…` with a wrong key or no key. The panel's routes never answer this — the key is not their door. | +| `invalid_api_key` | Any `GET /api/tokens…` or `/api/v1…` call with a wrong key or no key. The panel's routes never answer this — the key is not their door. | +| `admin_key_required` | A change on `/api/v1` (start or complete an authorization, remove an account) with the API key rather than the admin key: `DELETE /api/v1/accounts/` with `AI_GATEWAY_API_KEY` while `AI_GATEWAY_ADMIN_API_KEY` is set to something else. A 403: the caller is known, and the key is not enough. | +| `control_disabled` | The same change while the gateway has no `AI_GATEWAY_ADMIN_API_KEY` at all, with a valid API key. A 403 as well; it says why nothing can be changed over REST here, and reading still works. | | `unknown_provider` | `GET /api/tokens/` with a valid key — `/api/tokens/gemini`. A vendor that exists but holds no accounts is a 200 and an empty list instead. | -| `invalid_request` | A malformed body: a `provider` the registry does not know, a complete with no paste. The panel's own controls cannot produce these. | +| `invalid_request` | A malformed body: a `provider` the registry does not know, a complete with no paste — or a `?provider=` / `?state=` on `GET /api/v1/accounts` that names nothing the gateway knows. The panel's own controls cannot produce these. | ## Must never appear diff --git a/services/ai-gateway/tests/manual/reference/pins.md b/services/ai-gateway/tests/manual/reference/pins.md index 74daf943ad..17d17d5ffd 100644 --- a/services/ai-gateway/tests/manual/reference/pins.md +++ b/services/ai-gateway/tests/manual/reference/pins.md @@ -24,7 +24,7 @@ and name the test that now holds it. Never key a row by round — the journal in | `SMOKE-10` | The panel keeps no door of its own. It once had a password and a signed session cookie in front of the same screen the fleet's SSO gateway already guards, so every operator signed in twice. Both went; whatever fronts the origin is the only gate, and a deployment that puts nothing there exposes the pool. | | `SMOKE-4` | French punctuation spacing survives the catalog. The `%` in a usage bar takes a nonbreaking space before it, and an editor that retypes the line loses it silently — the character is invisible. | | `SMOKE-6` | The row action menu is the only route to three of this panel's four verbs. A toolbar that is reachable but a menu that is not leaves a keyboard user unable to copy a command, re-authenticate or remove. | -| `SMOKE-11` | The strip is the documentation frame's header row, not a second design. Its own border IS the line under it: wrapping a fixed-height row in a bordered parent puts the border outside the height and ends the strip a pixel low. The box asks for the height and the single line for that reason. | +| `SMOKE-11` | The strip is the platform's page header, not a second design: its title is `AdaptiveHeaderTitle`, the component "Automations" and "Knowledge" are set in, so the panel's name reads in the same 16 px semibold and starts on the same `px-4` edge as the table under it. It carried the Tale mark and the documentation frame's 14 px medium title before, which made it the one screen in the product whose title looked unlike every other; the mark went because the name beside it already says whose panel this is. Its own border IS the line under it: wrapping a fixed-height row in a bordered parent puts the border outside the height and ends the strip a pixel low. The box asks for the height and the single line for that reason. | | `SMOKE-13` | The account table is a list page like Projects and Automations: it runs the shared `useListPage` (`@tale/ui/use-list-page`), so its rows load on scroll inside the frame and the frame ends on the same count footer. It used to stretch to the whole screen (`DataTable fillHeight`) and page with numbered controls under the frame, which made it the one list in the product that paged and counted differently. | | `SMOKE-15` | Colour alone is not a status (WCAG 1.4.1), and below `md` the label does not fit. The glyph is what carries the state at every width; the label is hidden, never removed, so the accessible name is the same on a phone as on a desktop. | | `SMOKE-14` | The panel's only landmark used to be the table. A page with no `
` gives a screen-reader user nothing to jump to, and the skip link has to move focus itself — a fragment navigation only scrolls in some browsers. | @@ -49,17 +49,22 @@ and name the test that now holds it. Never key a row by round — the journal in | `ACCT-14` | A store that cannot be decrypted fails loudly. AES-256-GCM's authentication tag is what makes a wrong key an error rather than plausible garbage. | | `ACCT-18` | `docs` — the box used to ask for the create action inside the empty state. The shared list pattern moves it there only when no toolbar chrome needs to stay visible, and this screen always renders its search box, so the button correctly stays in the toolbar. | | `ACCT-19` | `docs` — the box used to say "stop the network, then reload the panel". One process serves the panel and its API, so with the network or the server gone the reload never reaches the panel and the browser shows its own error page. Blocking the one request is what leaves the page up and the list unread. | -| `ACCT-27` | The order is grouped, not alphabetical. An operator opens this screen to judge one vendor's pool; interleaving the two vendors by name makes that a scan instead of a glance. Sorting on the address rather than the label keeps a renamed account where its e-mail puts it. | +| `ACCT-27` | The order is grouped, not alphabetical. An operator opens this screen to judge one vendor's pool; interleaving the two vendors by name makes that a scan instead of a glance — and inside a vendor, a pool read best to worst (accounts that can take work, then the ones waiting on a reset with the soonest back first, then the ones that need a person) answers "what can I use now, and when is the next one back" without reading a column. A group here means rows sitting together: the shared table has no group header rows. Sorting on the address rather than the label keeps a renamed account where its e-mail puts it. Held by `app/lib/account-order.test.ts` and `app/components/accounts-screen.test.tsx`. | | `ACCT-25` | A usage bar is a quota, not a progress bar. The shared `ProgressBar` paints a full bar green — "done" — which on a spent plan says the opposite of what happened. The panel tints it on the owner's five steps instead (green under half, yellow, orange from three quarters, orange running into red from 95 %, red at the ceiling), from the palette hues the platform already paints status fills with, since the tokens name one warning and one failure rather than a scale. The figure is rounded down, as Claude Code's `/usage` prints it: rounding 99.6 up painted a window red and called it spent while it still had something left. | -| `ACCT-47` | A spent row is a look, not a state: the account is not switched off, so only its strength changes — its place in the order, its figures and every action stay, and the menu keeps full strength because it still works. It greys on the reading the bars draw (`planSpent`, against the bars' own ceiling, `isSpent`), so a grey row and a red session or weekly bar can never disagree. A scoped window caps one model while the account still serves the others, so it never greys the row. It is deliberately not the token endpoints' `available`, which also stops trusting a reading after fifteen minutes and honours OpenAI's explicit limit flag: a row can stay grey on an old 100 % reading that the gateway already hands out again. Held by `app/lib/usage-windows.test.ts` and `app/components/accounts-screen.test.tsx`. | +| `ACCT-47` | A spent row is a look, not a state: the account is not switched off, so only its strength changes — its place in the order, its figures and every action stay, and the menu keeps full strength because it still works. It greys when the gateway derives the state `limited` (`backend/account-state.ts`) — the reading's session or weekly window at its ceiling, and not yet rolled over — so a grey row and a red session or weekly bar can only disagree for the minutes between a rollover and the next reading, when the row has already come back and the figures dim as stale. A scoped window caps one model while the account still serves the others, so it never greys the row. The Status and Resets in cells are spared the grey: they are why the row is grey and when it stops being, and an explanation at 60 % strength is a greyed row nobody can account for. It is deliberately not the token endpoints' `available`, which also stops trusting a reading after fifteen minutes and weighs the refresh floor: a row can stay grey on an old 100 % reading that the gateway already hands out again. Held by `backend/account-state.test.ts` and `app/components/accounts-screen.test.tsx`. | | `ACCT-4` | The OpenAI windows are read out of `rate_limit.primary_window` / `secondary_window`, with the length in `limit_window_seconds` and the rollover as epoch seconds. The parser was first written against Codex's internal rate-limit event instead (`rate_limits.primary`, `window_minutes`) — keys the usage endpoint never sends — so every ChatGPT row mapped to zero windows and read "No usage read yet" while the vendor was answering 200. | | `ACCT-30` | The reset is in the row, not behind a hover. "When does this come back" is the question a spent plan raises, and a figure only a mouse can reach does not answer it — for a touch reader it does not answer it at all. The tooltip keeps the exact instant, so hovering still buys precision the relative phrase cannot carry. Both columns filter and key their windows through `app/lib/usage-windows.ts`, which is what keeps their rows opposite each other. | | `ACCT-31` | The grey bar is the clock, not a second quota. It needs the window's own length, which neither vendor states outright: OpenAI reports `limit_window_seconds`, and Anthropic names it (`five_hour`, `seven_day`, a per-model limit's `group`). Grey rather than a status colour because a window running out is not a warning. | | `ACCT-32` | The heading is not the same sentence in every language. dayjs's German declines for the suffix — "in 5 Tagen" is dative, the bare "5 Tage" nominative — so a literal "Zurücksetzung in" over a bare distance is ungrammatical. German and French name the remaining time instead, which takes the bare form correctly. | | `ACCT-34` | The plan used to be read off Anthropic's token answer, whose `organization.name` is the organization — "you@example.com's Organization" — not what it subscribes to, so every Claude row showed a name where its plan belonged. It now comes from the profile's `organization_type` and `rate_limit_tier` (the fields Claude Code maps onto its own subscription types), and ChatGPT's from the `plan_type` its usage answer carries; a profile answer is asked again after six hours, and a document still holding the old `plan` string drops it on read. | -| `ACCT-35` | A reset within the hour is the one worth a second look — a spent window coming back in twenty minutes is an account about to be usable again — so it is pointed out; everything further away stays a grey clock. Colour is not the only cue (WCAG 1.4.1): the timer glyph and the medium weight carry it too, and the success tint clears AA as text in both themes. A rollover already behind the clock is not "soon": the reading predates it and the next read replaces the window. | +| `ACCT-35` | A reset within the hour is the one worth a second look — an account that hit its limit and comes back in twenty minutes is about to be usable again — so it is pointed out; everything further away stays a neutral clock. It is the ACCOUNT's return that is pointed out, not any window's: the tint used to fire on every window inside the hour, so an account with room left and a session resetting in twenty minutes read green and "about to be usable" while it was usable already. Colour is not the only cue (WCAG 1.4.1): the timer glyph and the medium weight carry it too, and the success tint clears AA as text in both themes. A rollover already behind the clock is not "soon": the reading predates it and the next read replaces the window. | | `ACCT-36` | The bars used to fill their columns, and the columns share the table's width in proportion, so a bar's length changed with the window width and with every other column — two readings of 57 % could be drawn a hand apart. Each track is now a fixed length (6.5rem for usage, 2.5rem for the clock), so length means the same thing in every row. | | `ACCT-37` | The Anthropic mapping is the one Claude Code's `/usage` draws: `five_hour`, `seven_day`, and per-model rows from `limits` entries of kind `weekly_scoped` only — Claude Code classifies a row on its `kind`, never on its label. An entry of another kind that named a model used to land beside the weekly one as a second "Fable" with its own figure. The figure rounds down as `/usage` prints it. | | `ACCT-38` | A failed read keeps the old figures AND the time they were read; the floor counts from the attempt instead. Stamping old figures with the new time let a reading from days ago pass for current — and weekly figures only climb during a week, so a frozen one reads as simply wrong while a session figure can still look plausible. The ways a row used to freeze: a 429 on refresh was treated as a dead grant (`expired`, never read again); concurrent refreshes spent a refresh token the vendor had already rotated; a usage write landed an older copy of the row over a freshly rotated grant; and a 200 carrying `{"error": …}` replaced the reading with nothing. | +| `ACCT-48` | An account that hit its limit is back when its LAST spent window rolls over, so a session resetting in five minutes beside a spent week is back in three days. The column used to draw every window's clock alike, and the one that stood out was the soonest — the one that decides nothing — so a reader had to work out which clock counted. The gateway now names the account's return (`limitedUntil`, the latest rollover among the spent windows) and the window that sets it; the Status cell says it in words and the Resets in cell reads that window in full strength and steps the others back. Only the session and weekly windows count, a per-model cap never limits the account, and a window with no stated rollover makes the return unknown rather than guessed. Held by `backend/account-state.test.ts`, `app/lib/usage-windows.test.ts` and `app/components/accounts-screen.test.tsx`. | +| `ACCT-49` | The success tint is the account's, not a window's: it needs a limited account whose return is inside the hour. See `ACCT-35`. | +| `ACCT-50` | The REST door and the panel read the same derivation, not two. `backend/account-state.ts` is the only place that decides `state`, `limited_until` and a window's `blocking`, and the panel's own account list carries the same fields, so a script and a person looking at the screen cannot disagree about which accounts are limited. Neither is the token endpoints' `available`, which answers a different question — may this account take NEW work — and so also distrusts old readings. | +| `ACCT-51` | Changing the pool takes a key of its own. `AI_GATEWAY_API_KEY` reads (what an account shows is a subset of what it already reads from `/api/tokens`), and only `AI_GATEWAY_ADMIN_API_KEY` starts an authorization or removes an account: adding an account puts someone else's subscription into the pool the platform draws from, so it is not a power every holder of a token key should have. Unset, changing answers `403 control_disabled`; set to the same value as the API key, it is one key. A script is never offered a redirect flow, whatever `Origin` it sends — only the panel can reach a loopback address of the gateway's own machine. Held by `backend/routes.test.ts` and `backend/config.test.ts`; this box is the live end of it. | +| `ACCT-52` | Signing an account in again over REST is the panel's own Reauthenticate: the authorization names the existing account and finishing it updates that row in place. | | `ACCT-45` | A re-read that failed used to replace the whole screen — rows, search, filter and **Add account** — with the shared "Something went wrong" page, for a list that had read fine a minute before. The rows are still the best list there is, so they stay, and the warning is what keeps them from passing for current. Only a list never read takes the table's own failure state (`ACCT-19`). Held by `app/components/accounts-screen.test.tsx`. | | `ACCT-46` | The panel has no sign-in of its own (`SMOKE-10`); the SSO gateway in front ends its session on its own clock and from then on answers every panel request with a redirect to its identity provider. `fetch` used to follow that redirect to another origin, where the panel's CSP (`connect-src 'self'`) and CORS both stop it, so the failure looked exactly like a dropped connection: the screen became "Something went wrong", and its **Try again** could never succeed, because only a page load passes through the gate's sign-in. The panel now tells `fetch` not to follow redirects — no route it calls redirects — and reads a held redirect, or a 401 without the gateway's envelope, as `signed_out`. Held by `app/lib/api.test.ts` and `app/components/accounts-screen.test.tsx`. | diff --git a/services/ai-gateway/tests/manual/setup.md b/services/ai-gateway/tests/manual/setup.md index 32764ef693..febe6af681 100644 --- a/services/ai-gateway/tests/manual/setup.md +++ b/services/ai-gateway/tests/manual/setup.md @@ -12,7 +12,7 @@ suites themselves sit in [`suites/`](suites). | **Browser engines** | `npx playwright install chromium firefox webkit` once — the cross-engine boxes and every chauffeur script need them. | | **A viewport** | 1440×900 is the default; responsive boxes name their own. | -| **Fixed secrets** | The two in [`../../.env.example`](../../.env.example), exported before the server starts. Development generates any that are absent — and a generated `AI_GATEWAY_ENCRYPTION_KEY` cannot read what the previous run sealed, so a round without fixed secrets loses its accounts at every restart. | +| **Fixed secrets** | The two in [`../../.env.example`](../../.env.example), exported before the server starts. Development generates any that are absent — and a generated `AI_GATEWAY_ENCRYPTION_KEY` cannot read what the previous run sealed, so a round without fixed secrets loses its accounts at every restart. For the REST boxes (`ACCT-50` … `ACCT-52`) also export `AI_GATEWAY_ADMIN_API_KEY` — development never generates it. | | **A Claude subscription** | A Pro or Max account you own, signed in in the round's browser. Needed from `ACCT-1`. | | **A ChatGPT subscription** | A Plus or Pro account you own, signed in in the same browser. Needed from `ACCT-3`. | | **Both vendor CLIs** | `claude` and `codex` on the path, for the hand-out boxes `ACCT-8` and `ACCT-9`. | @@ -35,6 +35,7 @@ environment, not a finding. ```bash export AI_GATEWAY_API_KEY=… # see ../../.env.example export AI_GATEWAY_ENCRYPTION_KEY=… # 32 base64 bytes +export AI_GATEWAY_ADMIN_API_KEY=… # only for the REST boxes (ACCT-50 … ACCT-52) export AI_GATEWAY_DATA_DIR=/tmp/ai-gateway-round bun run --filter @tale/ai-gateway dev # Vite + the API on :3004 diff --git a/services/ai-gateway/tests/manual/suites/accounts.md b/services/ai-gateway/tests/manual/suites/accounts.md index 7239bc3e76..ba7560c89f 100644 --- a/services/ai-gateway/tests/manual/suites/accounts.md +++ b/services/ai-gateway/tests/manual/suites/accounts.md @@ -1,6 +1,6 @@ # Accounts -> **Prefix** `ACCT-` · **Reset** before the suite · **Cost** ~30 min +> **Prefix** `ACCT-` · **Reset** before the suite · **Cost** ~40 min The credential lifecycle, end to end, against the real vendors: add a Claude account, add a ChatGPT account, watch their tokens stay fresh, hand them to the @@ -35,7 +35,7 @@ specs; see [`../reference/automation.md`](../reference/automation.md). - [ ] `ACCT-2` · **Open that URL, approve, copy the value the console page shows, paste it, Connect** → the dialog closes, a toast names the account, and a row appears carrying the Claude mark, the account's own e-mail, its - plan in the Plan column, **Active**, and usage bars that are already + plan in the Plan column, **Available**, and usage bars that are already populated — not "No usage read yet". - [ ] `ACCT-3` · **Add account → OpenAI (ChatGPT) → Continue** → no paste step: the dialog shows a one-time code with a copy button, a link to @@ -113,15 +113,51 @@ in the pool**, so they run before the removals. its `access_token` and `account_id` in the README's Codex command** → only the ChatGPT row, and Codex starts on it. +### Over REST + +`/api/v1` is the machine door to the same pool: the API key reads, a separate +admin key changes. The keys, the scopes and every refusal are pinned by specs +([`../reference/automation.md`](../reference/automation.md)); what no spec can +do is run the changes against a real vendor, and compare the answers with what +the panel shows. **These boxes need `AI_GATEWAY_ADMIN_API_KEY` set** in the +server's environment. They take an account out and put it back, so the pool is +whole again for the boxes after them. + +- [ ] `ACCT-50` · **`curl localhost:3004/api/v1/accounts -H "Authorization: + Bearer $AI_GATEWAY_API_KEY"` with the pool open in the panel** → every account + in the panel, each with the `state` and `limited_until` the panel shows for it + and its windows' `blocking` flags — the account the panel says is back in + three days says `limited_until` three days out. No token, refresh token or + secret appears anywhere in the body. `?provider=openai` and `?state=limited` + narrow the list to what the panel's own filters would. +- [ ] `ACCT-51` · **With the admin key, `DELETE /api/v1/accounts/`, then `POST /api/v1/authorizations` for `openai`, approve the + code the answer names at OpenAI, and poll `GET + /api/v1/authorizations/`** → the delete answers `204`, the panel's row + is gone at its next read, and `/api/tokens/openai` answers `{"tokens": []}`. + The poll answers `pending` until the approval, then `connected` with the new + account, within the interval the start named; the pool has its ChatGPT row + again, usage bars populated. +- [ ] `ACCT-52` · **Start an authorization for `anthropic` with the admin key + and the Claude account's `account_id`, approve it at Anthropic, and send what + the console prints to `POST …/complete`** → the answer is `201` with the + account, and its row is updated in place: the pool does not grow, and the + account keeps its id and its usage history. + ### Finding an account -- [ ] `ACCT-27` · **Read the row order with both vendors in the pool** → every - Claude account first, then every ChatGPT one, and inside each vendor the - rows in order of the address rather than the label. A renamed account sits - where its e-mail puts it, not where its name would. +- [ ] `ACCT-27` · **Read the row order with both vendors in the pool, and + accounts in several states** → every Claude account first, then every + ChatGPT one; inside each vendor the accounts that can take work (Available), + then the ones that hit their limit with the soonest back first and any with + no known return last, then Needs reauthentication, then Last call failed. + Inside a state the rows are in order of the address rather than the label. A + renamed account sits where its e-mail puts it, not where its name would. - [ ] `ACCT-28` · **Filter → Provider → one vendor** → only that vendor's rows, - and the count footer agrees. Add a Status facet on top and the two narrow - together; **Clear all** puts every row back. + and the count footer agrees. Add the Status facet on top — it lists Available, + Limit reached, Needs reauthentication and Last call failed, in that order — + and the two narrow together; **Clear all** puts every row back. Searching for + "limit" finds the accounts that hit theirs, by the words the row shows. - [ ] `ACCT-29` · **Filter down to nothing** → the no-results state, with the search and the filter button still reachable so the reader can undo it. @@ -138,12 +174,12 @@ in the pool**, so they run before the removals. green: a spent plan is not a completed task. A window at 99.6 % reads 99 % and orange-into-red, not 100 % and red. - [ ] `ACCT-47` · **Find an account whose session or weekly window reads - 100 %** → its whole row greys out like a disabled one — name, plan, status, - bars, countdown and date — yet stays readable, keeps its place in the - order, and keeps its row menu at full strength: every action in it still - works. A per-model window at 100 % (Fable), or a session at 99 %, leaves - its row as it is. Once the spent window rolls over, the next reading brings - the row back by itself. + 100 %** → its row greys out like a disabled one — name, plan, bars and + date — yet stays readable, keeps its place in the order, and keeps its row + menu at full strength: every action in it still works. Its Status and Resets + in cells are not greyed: they say why the row is, and when it stops being. A + per-model window at 100 % (Fable), or a session at 99 %, leaves its row as it + is. Once the spent window rolls over, the row comes back by itself. - [ ] `ACCT-26` · **Hover a usage bar, then the grey bar beside it** → the first names the percentage, the second the exact instant that window resets — the date and the hour, in the panel's language, and the instant the @@ -159,11 +195,30 @@ in the pool**, so they run before the removals. as a coloured bar further along than its grey one. A window the vendor gave no rollover for leaves the grey track empty rather than drawing a fraction of nothing. -- [ ] `ACCT-35` · **Find a window that rolls over within the hour** → its - distance ("25 minutes") reads in green and medium weight behind a timer - glyph, and its clock bar turns green; a window an hour or more away stays - grey. The cue survives without colour: the glyph and the weight still set - it apart in grayscale. +- [ ] `ACCT-35` · **Find an account that hit its limit and comes back within + the hour** → the hourglass beside its state is a green timer, and the clock + that decides its return — "25 minutes" in the Resets in column — reads in + green and medium weight behind a timer glyph, with its clock bar green too; + the line under its state ("Resets in 25 minutes") keeps the ordinary caption + grey. A return an hour or more away stays in the neutral tones. An account + with room left, whose window merely resets within the hour, gets none of it. + The cue survives without colour: the glyphs and the weight still set it + apart in grayscale. +- [ ] `ACCT-48` · **Find an account whose session reads 100 % and resets in + minutes while its weekly window also reads 100 % and resets in days** → its + state reads Limit reached, and the line under it says *Resets in 3 days* + (the week's distance, whatever it is) — never the session's. In the Resets in + column the weekly row is in full strength behind a timer glyph, with a darker + clock bar, and the session row is the plain grey one: it is spent too, but + the account does not come back with it. Nothing on the row can be read as + "back in five minutes". +- [ ] `ACCT-49` · **Find an account whose session reads 100 % and whose weekly + window has room** → Limit reached, *Resets in* the session's distance; the + session row is the one in full strength, and the weekly row stays plain grey. + Put the session inside the hour and the account reads in green — the + state's glyph, the distance in the Resets in column and its clock bar — but + the weekly row never does. + - [ ] `ACCT-36` · **Widen and narrow the window between 1280 and 1920 px** → every usage bar keeps one length in every row and at every width, and every clock bar keeps its own shorter one; only the space around them changes. @@ -188,8 +243,9 @@ in the pool**, so they run before the removals. usage figures move on their own, and the reset countdowns stay consistent with the wall clock rather than drifting by your UTC offset (`ACCT-12`). - [ ] `ACCT-13` · **Restart the server with the same secrets and reload** → - both accounts are still there, still Active: the document on disk survived, - and the stored tokens decrypt. + both accounts are still there, each in the state it had (Available, or Limit + reached until its own reset): the document on disk survived, and the stored + tokens decrypt. - [ ] `ACCT-14` · **Restart the server with a different `AI_GATEWAY_ENCRYPTION_KEY` and reload** → the panel does not pretend: every row reads as failing — its bars dimmed, with the time they were read — and diff --git a/services/ai-gateway/tests/manual/suites/smoke.md b/services/ai-gateway/tests/manual/suites/smoke.md index cc9ee8c49a..599533dd21 100644 --- a/services/ai-gateway/tests/manual/suites/smoke.md +++ b/services/ai-gateway/tests/manual/suites/smoke.md @@ -38,17 +38,20 @@ The dev server up on :3004 per [`../setup.md`](../setup.md), devtools open, a - [ ] `SMOKE-8` · **Open a route the panel does not define** → a real not-found renders; no white screen, no unhandled rejection in the console. - [ ] `SMOKE-9` · **Narrow the viewport to 390×844** → the header stays one - row: the Tale mark steps aside, the name truncates, and the language, theme - and GitHub controls all stay on screen. The table scrolls horizontally + row: the name truncates before anything else gives way, and the language, + theme and GitHub controls all stay on screen. The table scrolls horizontally inside its own frame; no control leaves the viewport. - [ ] `SMOKE-10` · **Open `/` in a fresh private window, with no cookie and no storage for the origin** → the same accounts screen, immediately. The panel keeps no door of its own, so a first-time browser reaches everything a returning one does — and a deployment that wants a door puts one in front. -- [ ] `SMOKE-11` · **Read the header row** → one `h-13` strip, the same height - as the documentation site's, carrying the Tale mark, the panel's name, and — - on the right — the language picker, the theme picker and a GitHub button, in - that order. Its bottom border is one line: nothing sits a pixel below it. +- [ ] `SMOKE-11` · **Read the header row, beside the platform's Automations or + Knowledge page** → one `h-13` strip, the same height as the platform's page + header, carrying only the panel's name — no logo — set in the same type as a + platform page title (16 px, semibold) and starting on the same left edge as + the table below it; and, on the right, the language picker, the theme picker + and a GitHub button, in that order. Its bottom border is one line: nothing + sits a pixel below it. - [ ] `SMOKE-12` · **Follow the GitHub button** → the repository opens in a new tab; the panel is still where it was, with nothing reloaded. - [ ] `SMOKE-13` · **Search until exactly one account matches** → the frame @@ -60,12 +63,13 @@ The dev server up on :3004 per [`../setup.md`](../setup.md), devtools open, a is a skip link that reveals itself; activating it moves focus into the account list rather than only scrolling to it. - [ ] `SMOKE-15` · **Narrow the viewport until the Status column loses its - words** → each row still says which state it is in: a tick, a warning - triangle or a cross, in the state's own colour, and hovering one names it. - The column never shows a bare dot with no other cue. Widen it again at - 1440 px in each language: every label reads whole, the longest ones - ("Letzter Aufruf fehlgeschlagen", "Réautorisation nécessaire") on two - lines rather than cut off. + words** → each row still says which state it is in: a tick, an hourglass, a + warning triangle or a cross, and hovering one names it — for an account at its + limit, with when it comes back. The column never shows a bare dot with no + other cue. Widen it again at 1440 px in each language: every label reads + whole, the longest ones ("Letzter Aufruf fehlgeschlagen", "Réautorisation + nécessaire") on two lines rather than cut off, and the line under Limit + reached ("Setzt sich in 3 Tagen zurück") wraps rather than truncates. - [ ] `SMOKE-16` · **Hover a date in the last column** → the exact instant, with the time, in the language the panel is set to — a German panel gives `22. Oktober 2026 06:25`, an English one `October 22, 2026 6:25 AM`. diff --git a/services/platform/tests/integration/container-ai-gateway-test.ts b/services/platform/tests/integration/container-ai-gateway-test.ts index 5c00d5e737..be1afcf722 100644 --- a/services/platform/tests/integration/container-ai-gateway-test.ts +++ b/services/platform/tests/integration/container-ai-gateway-test.ts @@ -27,11 +27,13 @@ await runStaticSiteTest({ contentTypeIncludes: 'html', bodyIncludes: '