diff --git a/services/ai-gateway/README.md b/services/ai-gateway/README.md index c6419c9dca..c254d5e8da 100644 --- a/services/ai-gateway/README.md +++ b/services/ai-gateway/README.md @@ -19,7 +19,7 @@ one that serves the whole pool. | **Compatible token fields** | Keeps cc-gateway's `id`, `label`, `account_email`, `status`, `access_token`, `expires_at` and `scopes`, adding metadata for selection — `refresh_at` and `hold` among it — without changing those names | | **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, and refused refresh grants require a new sign-in | +| **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 | | **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 | diff --git a/services/ai-gateway/backend/accounts.test.ts b/services/ai-gateway/backend/accounts.test.ts index 4145ea6d18..b71b496747 100644 --- a/services/ai-gateway/backend/accounts.test.ts +++ b/services/ai-gateway/backend/accounts.test.ts @@ -45,7 +45,11 @@ function gate(): { wait: Promise; open: () => void } { function fakeProvider(id: 'anthropic' | 'openai'): Provider & { usage: UsageWindow[]; usagePlan: Subscription | null; - refusals: { refresh?: RefreshRefusal; usage?: boolean; exchange?: boolean }; + refusals: { + refresh?: RefreshRefusal; + usage?: boolean | 'rejected'; + exchange?: boolean; + }; gates: { refresh?: Promise; usage?: Promise }; refreshCount: number; refreshedExpiresAt: string; @@ -69,7 +73,7 @@ function fakeProvider(id: 'anthropic' | 'openai'): Provider & { usagePlan: null as Subscription | null, refusals: {} as { refresh?: RefreshRefusal; - usage?: boolean; + usage?: boolean | 'rejected'; exchange?: boolean; }, gates: {} as { refresh?: Promise; usage?: Promise }, @@ -172,7 +176,13 @@ function fakeProvider(id: 'anthropic' | 'openai'): Provider & { state.usageCount += 1; await state.gates.usage; if (state.refusals.usage) { - throw new ProviderError(id, 'usage_failed', 'refused'); + throw new ProviderError( + id, + state.refusals.usage === 'rejected' + ? 'access_token_rejected' + : 'usage_failed', + 'refused', + ); } return { windows: state.usage, subscription: state.usagePlan }; }, @@ -738,6 +748,26 @@ describe('createAccountService', () => { expect(cipher.open(stored?.accessToken ?? '')).toBe('access-2'); }); + it('does not reject a replacement generation when an older usage read answers 401', async () => { + const account = await connect(); + const held = gate(); + anthropic.gates.usage = held.wait; + anthropic.refusals.usage = 'rejected'; + now = new Date('2026-09-21T10:10:00.000Z'); + const reading = service.list(); + await vi.waitFor(() => expect(anthropic.usageCount).toBe(2)); + + now = new Date('2026-09-21T10:56:00.000Z'); + const handouts = service.handOutTokens(); + await vi.waitFor(() => expect(anthropic.refreshCount).toBe(1)); + held.open(); + await Promise.all([reading, handouts]); + + const stored = await store.getAccount(account.id); + expect(cipher.open(stored?.accessToken ?? '')).toBe('access-2'); + expect(stored?.status).toBe('active'); + }); + it('keeps the last reading, and when it was read, through a failed read', async () => { await connect(); anthropic.refusals.usage = true; @@ -757,6 +787,48 @@ describe('createAccountService', () => { expect(anthropic.usageCount).toBe(3); }); + it('recovers one exact access-token generation after an authenticated usage rejection', async () => { + const account = await connect(); + anthropic.refusals.usage = 'rejected'; + now = new Date('2026-09-21T10:10:00.000Z'); + + const [row] = await service.list(); + + expect(row?.status).toBe('active'); + expect(anthropic.refreshCount).toBe(1); + expect( + cipher.open((await store.getAccount(account.id))?.accessToken ?? ''), + ).toBe('access-2'); + }); + + it('keeps a rejected generation unavailable when its recovery is rate limited', async () => { + const account = await connect(); + anthropic.refusals.usage = 'rejected'; + anthropic.refusals.refresh = 'failed'; + now = new Date('2026-09-21T10:10:00.000Z'); + + const [row] = await service.list(); + expect(row?.status).toBe('error'); + expect(anthropic.refreshCount).toBe(1); + + now = new Date('2026-09-21T10:30:00.000Z'); + await service.list(); + expect(anthropic.usageCount).toBe(1 + 1); + expect((await store.getAccount(account.id))?.status).toBe('error'); + }); + + it('does not export a known unavailable account through its CLI command', async () => { + const account = await connect(); + anthropic.refusals.refresh = 'failed'; + await store.updateAccount(account.id, (row) => { + row.status = 'error'; + }); + + await expect(service.cliCommand(account.id)).rejects.toMatchObject({ + code: 'unavailable', + }); + }); + it('does not bring back an account removed while it was being read', async () => { const account = await connect(); now = new Date('2026-09-21T10:10:00.000Z'); diff --git a/services/ai-gateway/backend/accounts.ts b/services/ai-gateway/backend/accounts.ts index 89697d3121..378626a6f8 100644 --- a/services/ai-gateway/backend/accounts.ts +++ b/services/ai-gateway/backend/accounts.ts @@ -479,7 +479,11 @@ export function createAccountService( return false; } const refreshAt = plannedRefreshMs(account); - return refreshAt === null || refreshAt <= now().getTime(); + return ( + account.status === 'error' || + refreshAt === null || + refreshAt <= now().getTime() + ); } /** @@ -691,6 +695,19 @@ export function createAccountService( return run; } + function usageAttemptIsNewerThanReading(account: StoredAccount): boolean { + if (!account.usage) return false; + const attempted = account.usageAttemptedAt + ? Date.parse(account.usageAttemptedAt) + : Number.NaN; + const checked = Date.parse(account.usage.checkedAt); + return ( + Number.isFinite(attempted) && + Number.isFinite(checked) && + attempted > checked + ); + } + async function refreshStoredUsage( account: StoredAccount, force: boolean, @@ -698,7 +715,20 @@ export function createAccountService( const stored = await store.getAccount(account.id); if (!stored) return account; const current = await ensureFresh(stored); - if (current.status === 'expired') return current; + // A persisted error has already failed a refresh. Keep it out of usage + // polling until a later refresh succeeds; an error produced by this + // call's initial refresh still gets one final usage read, preserving the + // existing transient-refresh behaviour. + if ( + current.status === 'expired' || + (current.status === 'error' && + stored.status === 'error' && + stored.usageAttemptedAt !== null && + (account.status === 'error' || + !stored.usage || + usageAttemptIsNewerThanReading(stored))) + ) + return current; if ( current.status === 'error' && current.expiresAt && @@ -756,11 +786,16 @@ export function createAccountService( `[ai-gateway] usage read failed for ${current.provider} account ${current.id}:`, error instanceof Error ? error.message : error, ); + const rejected = + error instanceof ProviderError && + error.code === 'access_token_rejected'; const updated = await store.updateAccount(current.id, (row) => { if (row.accessToken !== current.accessToken) return; row.usageAttemptedAt = now().toISOString(); if (error instanceof CipherError) row.status = 'expired'; + else if (rejected) row.status = 'error'; }); + if (rejected && updated?.status === 'error') return ensureFresh(updated); return updated ?? current; } } @@ -1170,6 +1205,12 @@ export function createAccountService( const account = await store.getAccount(id); if (!account) return null; const fresh = await ensureFresh(account); + if (fresh.status !== 'active') { + throw new AccountError( + 'unavailable', + 'This account is not currently available.', + ); + } try { return providerFor(fresh).cliCommand( cipher.open(fresh.accessToken), diff --git a/services/ai-gateway/backend/providers/openai.test.ts b/services/ai-gateway/backend/providers/openai.test.ts index 2c04f50c3c..a8d6e9375e 100644 --- a/services/ai-gateway/backend/providers/openai.test.ts +++ b/services/ai-gateway/backend/providers/openai.test.ts @@ -283,6 +283,19 @@ describe('fetchUsage', () => { expect(calls[0]?.headers.has('chatgpt-account-id')).toBe(false); }); + it('types an authenticated usage rejection without reading its response body', async () => { + const { fetchImpl } = stubFetch(() => json({ secret: 'never-read' }, 401)); + await expect( + createOpenAiProvider({ fetchImpl }).fetchUsage({ + accessToken: 'access-1', + accountId: null, + }), + ).rejects.toMatchObject({ + code: 'access_token_rejected', + message: 'The OpenAI usage endpoint answered 401.', + }); + }); + it.each([ {}, { error: { code: 'rate_limit_error' } }, diff --git a/services/ai-gateway/backend/providers/openai.ts b/services/ai-gateway/backend/providers/openai.ts index 2564235784..ed73ea4261 100644 --- a/services/ai-gateway/backend/providers/openai.ts +++ b/services/ai-gateway/backend/providers/openai.ts @@ -345,7 +345,7 @@ export function createOpenAiProvider( if (!response.ok) { throw new ProviderError( 'openai', - 'usage_failed', + response.status === 401 ? 'access_token_rejected' : 'usage_failed', `The OpenAI usage endpoint answered ${response.status}.`, ); } diff --git a/services/ai-gateway/backend/providers/types.ts b/services/ai-gateway/backend/providers/types.ts index 44f2ed3ecc..7c30a42a99 100644 --- a/services/ai-gateway/backend/providers/types.ts +++ b/services/ai-gateway/backend/providers/types.ts @@ -243,7 +243,9 @@ export class ProviderError extends Error { | 'refresh_failed' | 'refresh_rejected' | 'identity_failed' - | 'usage_failed', + | 'usage_failed' + /** The provider rejected this exact access-token generation. */ + | 'access_token_rejected', message: string, options?: { cause?: unknown }, ) {