From 19f174126c5cb49572ef950affdca82a1b3ff8c3 Mon Sep 17 00:00:00 2001 From: ualtinok <94532+ualtinok@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:51:43 +0100 Subject: [PATCH] OpenCode 2: keep the serving account's scoped windows and credits fresh Refs #864 --- CHANGELOG.md | 1 + .../check-native-quota-compatibility.test.ts | 62 ++++- packages/core/src/accounts.ts | 52 +++- packages/core/src/insula-quota.ts | 37 +-- packages/core/src/native-account-runtime.ts | 6 +- packages/core/src/native-quota-codec.ts | 25 +- packages/core/src/native-vault-runtime.ts | 20 +- .../core/src/tests/native-quota-codec.test.ts | 58 ++++- .../tests/native-vault-insula-quota.test.ts | 36 ++- packages/core/src/tests/ultra-quota.test.ts | 41 ++- .../src/tests/opencode2-native-source.test.ts | 65 +++++ .../tests/opencode2-shared-lifecycle.test.ts | 241 ++++++++++++++++++ .../src/tests/quota-feed.integration.test.ts | 24 +- packages/opencode/src/v2/lifecycle.ts | 46 ++-- 14 files changed, 632 insertions(+), 82 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fa71b133..1182bceb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ This repo is a CortexKit-maintained Anthropic auth monorepo for OpenCode and Pi. ## Unreleased +- OpenCode 2: the serving account's model-scoped weekly windows and credits now refresh from Insula (vault) or the regular poll (local) while response headers keep arriving, so the sidebar no longer shows a growing 'checked … ago' for it. - OpenCode 2: retries after a rate limit try other available accounts before cycling back to one that already refused the request. Accounts with confirmed exhaustion are skipped. - OpenCode 1 and 2: every step served by Anthropic's safety fallback now writes one log line with per-attempt token counts; OpenCode 2 previously logged nothing. The safety-fallback notice no longer says follow-up requests stay on the fallback model. diff --git a/packages/core/scripts/check-native-quota-compatibility.test.ts b/packages/core/scripts/check-native-quota-compatibility.test.ts index a452229dc..71b2ab644 100644 --- a/packages/core/scripts/check-native-quota-compatibility.test.ts +++ b/packages/core/scripts/check-native-quota-compatibility.test.ts @@ -5,6 +5,11 @@ import { pathToFileURL } from 'node:url' import type { QuotaCodec } from '@cortexkit/common-auth/quota' import type { OAuthQuotaSnapshot } from '../src/accounts.ts' import { + mergeInsulaQuota, + normalizeInsulaClaudeQuota, +} from '../src/insula-quota.ts' +import { + fromNativeQuotaMap, type NativeQuotaMap, nativeQuotaCodec, toNativeQuotaMap, @@ -24,11 +29,10 @@ async function run(command: string[], cwd: string) { return stdout } -/** Network integration guard against making a shared pool unreadable after rollback. */ -test('quota maps written by the shared store remain accepted by the published Core 2.2.7 codec', async () => { +async function checkPublishedQuotaCodec(version: string) { const scratch = new URL('../../../target/scratch/', import.meta.url).pathname await mkdir(scratch, { recursive: true }) - const root = await mkdtemp(join(scratch, 'quota-format-227-')) + const root = await mkdtemp(join(scratch, `quota-format-${version}-`)) try { // npm 11 prints an array of records, npm 12 an object keyed by package name. const packed: unknown = JSON.parse( @@ -36,7 +40,7 @@ test('quota maps written by the shared store remain accepted by the published Co [ 'npm', 'pack', - '@cortexkit/anthropic-auth-core@2.2.7', + `@cortexkit/anthropic-auth-core@${version}`, '--json', '--pack-destination', root, @@ -47,7 +51,7 @@ test('quota maps written by the shared store remain accepted by the published Co const [pack] = ( Array.isArray(packed) ? packed : Object.values(packed as object) ) as Array<{ filename: string; version: string; shasum: string }> - if (pack?.version !== '2.2.7') + if (pack?.version !== version) throw new Error('Wrong compatibility release') console.log( 'QUOTA_COMPATIBILITY_PACK', @@ -110,10 +114,47 @@ test('quota maps written by the shared store remain accepted by the published Co five_hour: { usedPercent: 12, remainingPercent: 88, checkedAt: 2000 }, seven_day: { usedPercent: 21, remainingPercent: 79, checkedAt: 2000 }, } + const weeklyOnly = { ...poll, five_hour: undefined } + const weeklyHeaders = { ...headers, five_hour: undefined } + const insula = normalizeInsulaClaudeQuota( + { + provider: 'claude', + account: identity, + fetchedAt: new Date(1500).toISOString(), + source: 'vault', + usage: { secondary: { usedPercent: 15 } }, + }, + { fetchedAt: 1500 }, + ) + if (!insula) throw new Error('Expected a cached quota reading') + const afterHeaders = fromNativeQuotaMap( + nativeQuotaCodec.merge( + toNativeQuotaMap(weeklyOnly), + toNativeQuotaMap(weeklyHeaders), + ), + ) const cases: Array<{ name: string; readings: OAuthQuotaSnapshot[] }> = [ { name: 'full poll', readings: [poll] }, { name: 'poll followed by headers', readings: [poll, headers] }, - { name: 'headers followed by an older poll', readings: [headers, poll] }, + { + name: 'local poll clock survives newer headers on both standard windows', + readings: [{ ...poll, scoped: [] }, headers], + }, + { + name: 'vault Insula reading brings the poll clock forward independently of headers', + readings: [ + weeklyOnly, + weeklyHeaders, + { + ...mergeInsulaQuota(insula, afterHeaders), + accountIdentity: identity, + }, + ], + }, + { + name: 'headers followed by an older poll', + readings: [headers, poll], + }, { name: 'newer complete poll clears optional fields', readings: [poll, { ...headers, source: 'poll', scoped: [] }], @@ -207,4 +248,11 @@ test('quota maps written by the shared store remain accepted by the published Co } finally { await rm(root, { recursive: true, force: true }) } -}, 60_000) +} + +/** Network integration guard against making a shared pool unreadable after rollback. */ +test.each(['2.2.7', '2.16.4'])( + 'quota maps written by the shared store remain accepted by the published Core %s codec', + checkPublishedQuotaCodec, + 60_000, +) diff --git a/packages/core/src/accounts.ts b/packages/core/src/accounts.ts index 5d65e00a5..a2a35dcd9 100644 --- a/packages/core/src/accounts.ts +++ b/packages/core/src/accounts.ts @@ -663,6 +663,35 @@ export function quotaFieldSource( ) } +/** The poll's clock, independent of newer standard windows read from headers. */ +export function quotaPollCheckedAt(quota: OAuthQuotaSnapshot | undefined) { + if (!quota) return 0 + const standard = ['five_hour', 'seven_day'] as const + const hasPoll = + quota.source === 'poll' || + quotaSnapshotOmitsFiveHour(quota) || + quota.scoped !== undefined || + quota.extraUsage !== undefined || + standard.some((key) => quotaFieldSource(quota, key) === 'poll') + if (!hasPoll) return 0 + // Older mixed snapshots could put a header's clock here. Use only the + // surviving poll windows in that case; if none survived, the poll is due. + const topLevelIsHeader = standard.some( + (key) => + quotaFieldSource(quota, key) === 'headers' && + quota[key]?.checkedAt === quota.checkedAt, + ) + return Math.max( + !topLevelIsHeader ? (quota.checkedAt ?? 0) : 0, + ...(quota.scoped ?? []).map((window) => window.checkedAt), + ...standard.map((key) => + quotaFieldSource(quota, key) === 'poll' + ? (quota[key]?.checkedAt ?? 0) + : 0, + ), + ) +} + function fieldSourcesForMergedQuota( existing: OAuthQuotaSnapshot, incoming: OAuthQuotaSnapshot, @@ -712,13 +741,24 @@ export function mergeHeaderQuotaForPersistence( ) { if (!existing || incoming.source !== 'headers') return incoming const preservePollBinding = existing.bindingWindowSource === 'poll' + const pollCheckedAt = quotaPollCheckedAt(existing) + const preservePollFields = + pollCheckedAt > 0 && quotaPollCheckedAt(incoming) <= pollCheckedAt const merged = { ...existing, ...incoming, five_hour: mergeHeaderOwnedWindow(existing, incoming, 'five_hour'), seven_day: mergeHeaderOwnedWindow(existing, incoming, 'seven_day'), - scoped: mergeHeaderScopedQuota(existing, incoming), - extraUsage: existing.extraUsage ?? incoming.extraUsage, + // A response may carry the poll fields seen at dispatch. Do not let it + // restore fields that a newer stored poll removed. Independently timed + // scoped observations still merge by window. + scoped: + preservePollFields && quotaFieldSource(incoming, 'scoped') !== 'headers' + ? existing.scoped + : mergeHeaderScopedQuota(existing, incoming), + extraUsage: preservePollFields + ? existing.extraUsage + : (existing.extraUsage ?? incoming.extraUsage), fallbackAdvised: incoming.fieldSources?.fallbackAdvised !== undefined ? incoming.fallbackAdvised @@ -729,10 +769,10 @@ export function mergeHeaderQuotaForPersistence( bindingWindowSource: preservePollBinding ? 'poll' : (incoming.bindingWindowSource ?? existing.bindingWindowSource), - // Keep the successful poll's absence evidence and original clock so later - // merges can distinguish older polls from newer observations. - ...(quotaSnapshotOmitsFiveHour(existing) && { - checkedAt: existing.checkedAt, + // Headers advance their own windows, not the age of the scoped limits or + // credits. The poll clock also dates evidence that the 5h limit is absent. + ...(pollCheckedAt > 0 && { + checkedAt: pollCheckedAt, }), } satisfies OAuthQuotaSnapshot const fieldSources = fieldSourcesForMergedQuota(existing, incoming, merged) diff --git a/packages/core/src/insula-quota.ts b/packages/core/src/insula-quota.ts index 408cdea13..6920976f9 100644 --- a/packages/core/src/insula-quota.ts +++ b/packages/core/src/insula-quota.ts @@ -9,8 +9,9 @@ import { type OAuthExtraUsageSnapshot, type OAuthQuotaSnapshot, type QuotaFieldSources, + quotaFieldSource, + quotaPollCheckedAt, quotaSnapshotCheckedAt, - quotaSnapshotOmitsFiveHour, } from './accounts.ts' /** An insula reading in the shape our usage poll produces, before the account identity is attached. */ @@ -224,41 +225,31 @@ function newer( * a window read after insula's fetch (a response header, or our own poll). * Stored quota is replaced as one snapshot, newest wins, so publishing the * older insula reading as is would be refused and lose its other windows. - * Keep the newer reading of each window instead. + * Keep newer standard windows, but take scoped limits and credits together + * from the newest poll, including fields it no longer reports. */ export function mergeInsulaQuota( reading: InsulaClaudeQuota, stored: OAuthQuotaSnapshot | undefined, ): OAuthQuotaSnapshot { - if (!stored || quotaSnapshotCheckedAt(stored) <= reading.checkedAt) - return reading - const five_hour = quotaSnapshotOmitsFiveHour(stored) - ? undefined - : !reading.five_hour && - (stored.five_hour?.checkedAt ?? 0) <= reading.checkedAt + if (!stored) return reading + if (quotaPollCheckedAt(stored) > reading.checkedAt) return stored + if (quotaSnapshotCheckedAt(stored) <= reading.checkedAt) return reading + const five_hour = + !reading.five_hour && + (stored.five_hour?.checkedAt ?? 0) <= reading.checkedAt ? undefined : newer(reading.five_hour, stored.five_hour) const seven_day = newer(reading.seven_day, stored.seven_day) - const scoped = new Map(reading.scoped.map((window) => [window.id, window])) - for (const window of stored.scoped ?? []) { - const merged = newer(scoped.get(window.id), window) - if (merged) scoped.set(window.id, merged) - } const fieldSources: QuotaFieldSources = { ...reading.fieldSources } - if (five_hour !== reading.five_hour && stored.fieldSources?.five_hour) - fieldSources.five_hour = stored.fieldSources.five_hour - if (seven_day !== reading.seven_day && stored.fieldSources?.seven_day) - fieldSources.seven_day = stored.fieldSources.seven_day + if (five_hour && five_hour !== reading.five_hour) + fieldSources.five_hour = quotaFieldSource(stored, 'five_hour') + if (seven_day !== reading.seven_day) + fieldSources.seven_day = quotaFieldSource(stored, 'seven_day') return { ...reading, five_hour, ...(seven_day && { seven_day }), - scoped: [...scoped.values()], - checkedAt: quotaSnapshotOmitsFiveHour(stored) - ? stored.checkedAt - : quotaSnapshotOmitsFiveHour(reading) - ? reading.checkedAt - : Math.max(reading.checkedAt, quotaSnapshotCheckedAt(stored)), fieldSources, } } diff --git a/packages/core/src/native-account-runtime.ts b/packages/core/src/native-account-runtime.ts index 0c40cd23b..22bbb2dc0 100644 --- a/packages/core/src/native-account-runtime.ts +++ b/packages/core/src/native-account-runtime.ts @@ -130,7 +130,10 @@ import { stateLayoutOfPaths, } from './pool-paths.ts' import { createNativePoolStore, nativePoolStoreLocks } from './pool-store.ts' -import type { QuotaRequestDispatch } from './quota-manager.ts' +import { + QuotaRefreshDeferred, + type QuotaRequestDispatch, +} from './quota-manager.ts' import { effectiveRelayTransport, type RelayConfig } from './relay.ts' import { createRelayLocationCheck, @@ -2050,6 +2053,7 @@ function buildNativeAccountRuntime( const snapshot = await runtime.read() if (snapshot.mode === 'claustrum') return vault.fetchQuota(routeId, fetchImpl, signal, dispatch, purpose) + if (purpose === 'background-cache') throw new QuotaRefreshDeferred() const before = snapshot.accounts.find((row) => row.id === routeId) const result = await fetchReading( routeId, diff --git a/packages/core/src/native-quota-codec.ts b/packages/core/src/native-quota-codec.ts index db21b939e..023a77b66 100644 --- a/packages/core/src/native-quota-codec.ts +++ b/packages/core/src/native-quota-codec.ts @@ -12,8 +12,8 @@ import { QUOTA_FIELD_NAMES, type QuotaFieldSources, type QuotaMoney, + quotaPollCheckedAt, quotaSnapshotCheckedAt, - quotaSnapshotOmitsFiveHour, } from './accounts.ts' type ScopedMetadata = { @@ -441,13 +441,12 @@ export const nativeQuotaCodec: QuotaCodec = { ) const previousTime = quotaSnapshotCheckedAt(previous) const incomingTime = quotaSnapshotCheckedAt(incoming) + const previousPollAt = quotaPollCheckedAt(previous) // Poll order is the read's own clock, not a retained scoped/header clock. if ( incoming.source === 'poll' && incoming.checkedAt !== undefined && - previous.checkedAt !== undefined && - (previous.source === 'poll' || quotaSnapshotOmitsFiveHour(previous)) && - incoming.checkedAt < previous.checkedAt + incoming.checkedAt < previousPollAt ) return toNativeQuotaMap(previous) // A newer complete poll owns the absence of a session limit even if a @@ -466,9 +465,27 @@ export const nativeQuotaCodec: QuotaCodec = { ? mergeHeaderQuotaForPersistence(incoming, { ...previous, five_hour: undefined, + scoped: undefined, + extraUsage: undefined, }) : incoming, ) + if ( + incoming.source === 'poll' && + incoming.checkedAt !== undefined && + previous.source === 'headers' && + previousPollAt > 0 && + previousTime > incomingTime + ) + // A header can arrive after the poll completed but before it was stored. + // Preserve the newer standard readings without copying old poll fields. + return toNativeQuotaMap( + mergeHeaderQuotaForPersistence(incoming, { + ...previous, + scoped: undefined, + extraUsage: undefined, + }), + ) return toNativeQuotaMap( previousTime > incomingTime || (previousTime === incomingTime && diff --git a/packages/core/src/native-vault-runtime.ts b/packages/core/src/native-vault-runtime.ts index 84d281416..f3d7bf370 100644 --- a/packages/core/src/native-vault-runtime.ts +++ b/packages/core/src/native-vault-runtime.ts @@ -145,6 +145,8 @@ export interface NativeVaultRuntimeOptions { * minute per daemon and enrollment), look the route's account up in it, * and skip the usage GET for a current reading, a cold cache or an upstream * failure. Skipped misses leave the account due for the next sweep. + * - 'background-cache': apply a current reading from the already-warmed + * cache even if recent headers mean a provider poll is not due. * - 'admission': a request needs a reading. Look the served credential's * account up in insula's cache only, never refreshing it, then poll on a * miss except an upstream failure, which uses a dated reading if attached @@ -152,7 +154,7 @@ export interface NativeVaultRuntimeOptions { * Omitted: poll Anthropic directly (explicit user refreshes and other * callers that must see the provider's own reading). */ -export type NativeVaultQuotaPurpose = QuotaReadingPurpose +export type NativeVaultQuotaPurpose = QuotaReadingPurpose | 'background-cache' export interface NativeVaultWatchOptions { intervalMs: number @@ -1249,11 +1251,14 @@ export function createNativeVaultRuntime( }, async fetchQuota(routeId, fetchImpl = fetch, signal, dispatch, purpose) { const row = await rowFor(await runtime.read(), routeId) + const cacheOnly = purpose === 'background-cache' // A background sweep asks insula about the roster row's account (its // list_scoped account_id) before any credential is fetched. let swept: InsulaQuotaResult | undefined - if (purpose === 'background' && row) { - await refreshInsula() + if ((purpose === 'background' || cacheOnly) && row) { + // The background sweep already warmed the cache. Leave provider polling + // to the due-gated background path when there is no current reading. + if (!cacheOnly) await refreshInsula() check(signal) swept = insulaLookup(row.accountIdentity) if (swept.miss === 'cold' || swept.miss === 'upstream-failed') { @@ -1261,6 +1266,8 @@ export function createNativeVaultRuntime( throw new QuotaRefreshDeferred() } } + if (cacheOnly && (swept?.miss || !swept?.reading)) + throw new QuotaRefreshDeferred() const state = await readNativeRuntime(paths.runtime, paths.storageId) const before = state.status === 'ready' @@ -1291,7 +1298,7 @@ export function createNativeVaultRuntime( miss: 'unreachable', } let accountChanged = false - if (purpose === 'background') { + if (purpose === 'background' || cacheOnly) { // The sweep joined the roster row's account; publish it only for // a credential served for that same account. if ( @@ -1331,7 +1338,10 @@ export function createNativeVaultRuntime( stored ? fromNativeQuotaMap(stored) : undefined, ) } - if (purpose === 'admission' && lookup.miss === 'upstream-failed') + if ( + cacheOnly || + (purpose === 'admission' && lookup.miss === 'upstream-failed') + ) return undefined return fetchOAuthQuotaSnapshot({ accessToken: receipt.accessToken, diff --git a/packages/core/src/tests/native-quota-codec.test.ts b/packages/core/src/tests/native-quota-codec.test.ts index 1a4e6649d..b25e64528 100644 --- a/packages/core/src/tests/native-quota-codec.test.ts +++ b/packages/core/src/tests/native-quota-codec.test.ts @@ -6,6 +6,7 @@ import { getScopedQuotaWindowForModel, mergeHeaderQuotaForPersistence, type OAuthQuotaSnapshot, + quotaPollCheckedAt, quotaSnapshotCheckedAt, } from '../accounts.ts' import { @@ -536,7 +537,7 @@ test('captured Team poll and response headers survive the production provider pa expect(fromNativeQuotaMap(toNativeQuotaMap(headers))).toEqual(headers) }) -test('the older-poll gap cannot be closed without a storage-format change because legacy data loses the poll clock', () => { +test('new native header merges retain the poll clock even though legacy data could lose it', () => { const emptyPoll = (checkedAt: number) => toNativeQuotaMap({ accountIdentity: 'synthetic-account-A', @@ -563,11 +564,17 @@ test('the older-poll gap cannot be closed without a storage-format change becaus const latePollAt = 1200 const first = history(earlierPollAt) const second = history(laterPollAt) - // Headers replace the snapshot and shared-window clocks. An empty poll has - // no scoped-window clock, and fieldSources stores labels rather than times. - expect(first).toEqual(second) expect(first.anthropic.source).toBe('headers') - expect(first.anthropic.checkedAt).toBe(2000) + expect(first.anthropic.checkedAt).toBe(earlierPollAt) + expect(second.anthropic.checkedAt).toBe(laterPollAt) + // Before the poll clock was retained, both histories produced the same map. + // Neither the two header windows nor the empty scoped list can recover it. + const legacy = (map: NativeQuotaMap): NativeQuotaMap => ({ + ...map, + anthropic: { ...map.anthropic, checkedAt: 2000 }, + }) + expect(legacy(first)).toEqual(legacy(second)) + expect(quotaPollCheckedAt(fromNativeQuotaMap(legacy(first)))).toBe(0) const latePoll = toNativeQuotaMap({ accountIdentity: 'synthetic-account-A', source: 'poll', @@ -590,13 +597,14 @@ test('the older-poll gap cannot be closed without a storage-format change becaus const afterSecond = fromNativeQuotaMap( nativeQuotaCodec.merge(second, latePoll), ) - // The newest-poll rule would accept the late poll only after the earlier - // history, but identical legacy inputs cannot distinguish those outcomes. - expect(latePollAt > earlierPollAt).toBe(true) - expect(latePollAt > laterPollAt).toBe(false) - expect(afterFirst).toEqual(afterSecond) - expect(afterFirst.scoped).toEqual([]) - expect(afterFirst.extraUsage).toBeUndefined() + expect(afterFirst.checkedAt).toBe(latePollAt) + expect(afterFirst.scoped?.[0]?.id).toBe('fable') + expect(afterFirst.extraUsage).toEqual(full.extraUsage) + expect(afterFirst.five_hour?.checkedAt).toBe(2000) + expect(afterSecond.checkedAt).toBe(laterPollAt) + expect(afterSecond.scoped).toEqual([]) + expect(afterSecond.extraUsage).toBeUndefined() + expect(nativeQuotaCodec.merge(legacy(first), latePoll)).toEqual(legacy(first)) }) test('a newer complete poll replaces the whole snapshot and clears older scoped limits and extra usage', () => { @@ -617,3 +625,29 @@ test('a newer complete poll replaces the whole snapshot and clears older scoped expect(merged.extraUsage).toBeUndefined() } }) + +test('a late header carrying a prior poll cannot restore removed credits or scoped limits', () => { + const old: OAuthQuotaSnapshot = { ...full, source: 'poll' } + const latest: OAuthQuotaSnapshot = { + accountIdentity: full.accountIdentity, + checkedAt: 2000, + source: 'poll', + scoped: [{ ...full.scoped![1]!, checkedAt: 2000 }], + } + const lateHeaders = mergeHeaderQuotaForPersistence(old, { + accountIdentity: full.accountIdentity, + source: 'headers', + checkedAt: 3000, + seven_day: { usedPercent: 30, remainingPercent: 70, checkedAt: 3000 }, + }) + const merged = fromNativeQuotaMap( + nativeQuotaCodec.merge( + toNativeQuotaMap(latest), + toNativeQuotaMap(lateHeaders), + ), + ) + expect(merged.seven_day).toEqual(lateHeaders.seven_day) + expect(merged.scoped).toEqual(latest.scoped) + expect(merged.extraUsage).toBeUndefined() + expect(merged.checkedAt).toBe(2000) +}) diff --git a/packages/core/src/tests/native-vault-insula-quota.test.ts b/packages/core/src/tests/native-vault-insula-quota.test.ts index 81ce26602..9bec08364 100644 --- a/packages/core/src/tests/native-vault-insula-quota.test.ts +++ b/packages/core/src/tests/native-vault-insula-quota.test.ts @@ -900,10 +900,10 @@ test('admission reads only the insula cache: never refreshes it, polls on a miss ) expect(f.counts.insula).toBe(1) expect(f.counts.usage).toEqual([bearer(workRow.id), bearer(mainRow.id)]) - // The cold poll above is newer than insula's fetch, so its standard windows - // stay; the Fable window only insula reported is added. + // The cold poll above is newer than Insula's fetch. Its empty scoped list + // is authoritative, so an older cached poll cannot restore the Fable limit. expect(quota.five_hour).toMatchObject({ usedPercent: 10, checkedAt: now }) - expect(quota.scoped?.map((window) => window.checkedAt)).toEqual([fetchedAt]) + expect(quota.scoped).toEqual([]) }) test('runtimes on one connection file and token path share one insula source until all release it', async () => { @@ -1223,5 +1223,33 @@ test('a newer stored window survives an older insula reading', () => { checkedAt: fetchedAt, }) expect(merged.scoped?.[0]?.checkedAt).toBe(fetchedAt) - expect(merged.checkedAt).toBe(now) + expect(merged.checkedAt).toBe(fetchedAt) +}) + +test('an Insula poll removes unreported scoped limits and credits without reviving them from an older poll', () => { + const earlier = normalizeInsulaClaudeQuota( + entry(uuid, { + pools: [ + { title: 'Extra usage', total: { minor: 100 }, used: { minor: 40 } }, + ], + }), + { fetchedAt }, + ) + const latest = normalizeInsulaClaudeQuota( + entry(uuid, { usage: { secondary: { usedPercent: 15 } } }), + { fetchedAt: fetchedAt + 1000 }, + ) + if (!earlier || !latest) throw new Error('expected readings') + const stored = mergeInsulaQuota(earlier, { + source: 'headers', + checkedAt: now, + seven_day: { checkedAt: now, usedPercent: 22, remainingPercent: 78 }, + }) + expect(stored.scoped).toHaveLength(1) + expect(stored.extraUsage?.used.amountMinor).toBe(40) + const merged = mergeInsulaQuota(latest, stored) + expect(merged.seven_day).toEqual(stored.seven_day) + expect(merged.scoped).toEqual([]) + expect(merged.extraUsage).toBeUndefined() + expect(mergeInsulaQuota(earlier, merged)).toEqual(merged) }) diff --git a/packages/core/src/tests/ultra-quota.test.ts b/packages/core/src/tests/ultra-quota.test.ts index 339cefb7b..a15e6aa94 100644 --- a/packages/core/src/tests/ultra-quota.test.ts +++ b/packages/core/src/tests/ultra-quota.test.ts @@ -21,7 +21,11 @@ import { } from '../native-quota-codec.ts' import { mergeHeaderQuotaSnapshot } from '../quota-headers.ts' import { QuotaManager } from '../quota-manager.ts' -import { buildClaudeQuotaSummary } from '../quotas.ts' +import { + buildClaudeQuotaSummary, + formatQuota, + quotaDisplayProjection, +} from '../quotas.ts' import { decideStickyQuotaFailure, stickyQuotaSnapshotIsFresh, @@ -428,3 +432,38 @@ test('insula merge preserves a poll-removed session limit across independently n expect(merged.five_hour).toBeUndefined() expect(merged.checkedAt).toBe(quota.checkedAt) }) + +test('a fresh Insula poll clears the sidebar age for a weekly-only account with credits', async () => { + const now = Date.now() + const old = now - 60 * 60_000 + const extraUsage = { + used: { amountMinor: 10, currency: 'USD', exponent: 2 }, + limit: { amountMinor: 100, currency: 'USD', exponent: 2 }, + exhausted: false, + } + const headers: OAuthQuotaSnapshot = { + source: 'headers', + checkedAt: now, + seven_day: window(now, 80), + } + const stored = mergeHeaderQuotaForPersistence( + { ...(await poll(0, old)), extraUsage }, + headers, + ) + const at = now - 1000 + const current = await poll(0, at) + const reading: InsulaClaudeQuota = { + ...current, + checkedAt: at, + seven_day: window(at), + scoped: current.scoped!, + extraUsage, + } + const sidebar = (quota: OAuthQuotaSnapshot) => + formatQuota(quotaDisplayProjection(quota, now), { form: 'compact', now }) + expect(sidebar(stored)).toContain('checked 1h ago') + const merged = mergeInsulaQuota(reading, stored) + expect(merged.checkedAt).toBe(at) + expect(merged.seven_day).toEqual(headers.seven_day) + expect(sidebar(merged)).not.toContain('checked') +}) diff --git a/packages/opencode/src/tests/opencode2-native-source.test.ts b/packages/opencode/src/tests/opencode2-native-source.test.ts index 5b3cdc80e..105c28e2b 100644 --- a/packages/opencode/src/tests/opencode2-native-source.test.ts +++ b/packages/opencode/src/tests/opencode2-native-source.test.ts @@ -138,6 +138,71 @@ const exists = (path: string) => ) const cleanups: Array<() => Promise | void> = [] +test('OpenCode 2 admission does not poll a header-fed account with an old poll clock', async () => { + const { paths, runtime, store } = await local() + await store.updateSettings((settings) => ({ + ...settings, + quota: { enabled: true, checkIntervalMinutes: 5 }, + })) + const credential = await runtime.authorizeLocal('main') + if (credential.status !== 'usable') + throw new Error('Missing local credential') + const now = Date.now() + const old = now - 60 * 60_000 + const window = (checkedAt: number, usedPercent: number) => ({ + checkedAt, + usedPercent, + remainingPercent: 100 - usedPercent, + }) + await runtime.publishLocal(credential.subject, { + quota: { + accountIdentity: identity, + source: 'poll', + checkedAt: old, + five_hour: window(old, 10), + seven_day: window(old, 20), + scoped: [ + { + ...window(old, 100), + id: 'fable', + modelName: 'Fable', + title: 'Fable only', + }, + ], + }, + }) + await runtime.publishLocal(credential.subject, { + quota: { + accountIdentity: identity, + source: 'headers', + checkedAt: now, + five_hour: window(now, 12), + seven_day: window(now, 22), + }, + }) + expect((await runtime.read()).accounts[0]?.quota).toMatchObject({ + checkedAt: old, + five_hour: window(now, 12), + seven_day: window(now, 22), + }) + const requests: string[] = [] + const native = createNativeAnthropicSource({ + runtime, + paths, + requestOptions: () => ({}), + fetch: Object.assign( + async (input: Parameters[0]) => { + requests.push(String(input)) + return Response.json({}) + }, + { preconnect: fetch.preconnect }, + ), + }) + cleanups.push(() => native.close()) + expect(await native.chooseAccount(scope)).toBe('main') + expect(requests).toEqual([]) +}) + test('Ultra fresh weekly-only poll passes policy and selects the local OpenCode 2 account', async () => { const fixture = await local() const credential = await fixture.runtime.authorizeLocal('main') diff --git a/packages/opencode/src/tests/opencode2-shared-lifecycle.test.ts b/packages/opencode/src/tests/opencode2-shared-lifecycle.test.ts index fd9e8c8ff..c962b7a8a 100644 --- a/packages/opencode/src/tests/opencode2-shared-lifecycle.test.ts +++ b/packages/opencode/src/tests/opencode2-shared-lifecycle.test.ts @@ -4,9 +4,19 @@ import { tmpdir } from 'node:os' import { join } from 'node:path' import { acquireNativeAccountRuntime, + type NativeAccountRuntime, type NativeCustodyClient, + type OAuthQuotaSnapshot, + QUOTA_URL, resolveNativePoolPaths, } from '@cortexkit/anthropic-auth-core' +import { + fromNativeQuotaMap, + nativeQuotaCodec, + toNativeQuotaMap, +} from '../../../core/src/native-quota-codec.ts' +import { insulaBackground } from '../../../core/src/tests/insula-watch-fixture.ts' +import { initializeNativeTestAuthority } from '../../../core/src/tests/native-authority-fixture.ts' import { createTestLifetimeSuite } from '../../../core/src/tests/test-lifetime.ts' import { recordedTimers, @@ -30,6 +40,237 @@ const ownPoolPaths = (root: string) => join(root, 'anthropic-auth-state.json'), ) +const identity = '11111111-2222-4333-8444-555555555555' +const window = (checkedAt: number, usedPercent: number) => ({ + checkedAt, + usedPercent, + remainingPercent: 100 - usedPercent, +}) + +test('OpenCode 2 sweeps old local poll fields while the serving account receives fresh headers', async () => { + const now = Date.now() + const old = now - 60 * 60_000 + const poll: OAuthQuotaSnapshot = { + source: 'poll', + checkedAt: old, + five_hour: window(old, 20), + seven_day: window(old, 40), + scoped: [ + { + ...window(old, 100), + id: 'claude-weekly-scoped-fable', + title: 'Fable only', + modelName: 'Fable', + }, + ], + } + const headers: OAuthQuotaSnapshot = { + source: 'headers', + checkedAt: now, + five_hour: window(now, 21), + seven_day: window(now, 41), + } + const quota = fromNativeQuotaMap( + nativeQuotaCodec.merge(toNativeQuotaMap(poll), toNativeQuotaMap(headers)), + ) + const tick = Promise.withResolvers<() => unknown>() + const calls: string[] = [] + const runtime = { + async read() { + return { + mode: 'local', + policyStorage: { quota: { enabled: true } }, + accounts: [{ id: 'main', type: 'oauth', enabled: true, quota }], + } + }, + vault: { + watch(options: Parameters[0]) { + tick.resolve(() => options.onRefresh?.()) + return { ready: Promise.resolve(), close() {} } + }, + }, + async fetchQuota(id: string) { + calls.push(id) + }, + async fetchProfile() {}, + } as unknown as NativeAccountRuntime + const lifecycle = startNativeAnthropicLifecycle(runtime) + deferCleanup(() => lifecycle.dispose()) + await (await tick.promise)() + expect(calls).toEqual(['main']) +}) + +test('OpenCode 2 applies cached Insula poll fields on the next vault sweep despite fresh headers', async () => { + const root = await mkdtemp(join(tmpdir(), 'oc2-vault-quota-sweep-')) + deferCleanup(() => rm(root, { recursive: true, force: true })) + const paths = await ownPoolPaths(root) + await initializeNativeTestAuthority(paths) + const tokenPath = join(root, 'enrollment.json') + await writeFile( + tokenPath, + JSON.stringify({ token: '01'.repeat(32), token_generation: 1 }), + { mode: 0o600 }, + ) + const now = Date.now() + let clock = now - 120_000 + let checkedAt = clock + let used = 100 + let insulaReads = 0 + let usageGets = 0 + const background = insulaBackground() + const insula = { + connectionFile: join(root, 'daemon.json'), + watchUsage: background.watchUsage, + async getUsage() { + insulaReads++ + return { + completeProviders: ['claude'], + result: [ + { + provider: 'claude', + source: 'vault', + account: identity, + fetchedAt: new Date(checkedAt).toISOString(), + usage: { + secondary: { usedPercent: 50 }, + extraRateWindows: [ + { id: 'Fable', window: { usedPercent: used } }, + ], + }, + pools: [ + { + title: 'Extra usage', + total: { minor: 100 }, + used: { minor: used }, + }, + ], + }, + ], + } + }, + } + const client: NativeCustodyClient = { + insula, + async listScoped() { + return { + view: 'quota-sweep', + grants: undefined, + grantTuples: undefined, + rows: [ + { + id: 'oauth:anthropic', + accountId: identity, + credentialType: 'oauth', + categories: ['anthropic-native'], + serves: ['anthropic'], + providerIds: [], + refreshAdapter: 'anthropic', + operations: ['read'], + state: 'active', + recordVersion: 1, + createdAtMs: null, + }, + ], + } + }, + async getScoped({ credentialId }) { + return { + credentialId, + accountId: identity, + material: 'synthetic-sweep-access', + recordVersion: 1, + expiresAtMs: now + 3_600_000, + } + }, + async reportAuthFailureScoped() {}, + close() {}, + } + const runtime = acquireNativeAccountRuntime({ + host: 'opencode', + paths, + vault: { + env: { OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_ENROLLMENT_FILE: tokenPath }, + connect: async () => client, + now: () => clock, + setTimeout: background.setTimeout, + clearTimeout: background.clearTimeout, + }, + }) + deferCleanup(() => runtime.close()) + const transport = Object.assign( + async (input: Parameters[0]) => { + if (String(input) === QUOTA_URL) usageGets++ + return Response.json({}) + }, + { preconnect: fetch.preconnect }, + ) + await runtime.vault.refresh() + const snapshot = await runtime.read() + expect(snapshot.mode).toBe('claustrum') + const account = snapshot.accounts.find((account) => account.type === 'oauth') + if (!account) throw new Error('Missing vault OAuth account') + await runtime.fetchQuota( + account.id, + transport, + undefined, + undefined, + 'background', + ) + await runtime.drainQuotaPublications() + const publishHeaders = async (at: number) => { + const receipt = await runtime.authorizeVault(account.id) + expect( + await runtime.vault.publish(receipt, { + quota: { + accountIdentity: identity, + source: 'headers', + checkedAt: at, + seven_day: window(at, 30), + }, + }), + ).toBe(true) + } + const accountQuota = async () => + (await runtime.read()).accounts.find((row) => row.id === account.id)?.quota + await publishHeaders(now - 30_000) + expect((await accountQuota())?.scoped?.[0]?.usedPercent).toBe(100) + + clock = now - 1000 + checkedAt = clock + used = 10 + const readsBeforeNotice = insulaReads + background.notice() + await publishHeaders(now) + expect(insulaReads).toBe(readsBeforeNotice + 1) + + const swept = Promise.withResolvers() + const watch = runtime.vault.watch.bind(runtime.vault) + const spy = spyOn(runtime.vault, 'watch').mockImplementation((options) => + watch({ + ...options, + async onRefresh() { + await options.onRefresh?.() + swept.resolve() + }, + }), + ) + const readsBeforeSweep = insulaReads + const lifecycle = startNativeAnthropicLifecycle(runtime, transport) + deferCleanup(async () => { + await lifecycle.dispose() + spy.mockRestore() + }) + await swept.promise + await runtime.drainQuotaPublications() + expect(insulaReads).toBe(readsBeforeSweep) + expect(usageGets).toBe(0) + expect(await accountQuota()).toMatchObject({ + scoped: [{ checkedAt, usedPercent: 10 }], + extraUsage: { used: { amountMinor: 10 } }, + seven_day: window(now, 30), + }) +}) + test('OpenCode 2 lifecycles share discovery and retain the surviving account lease', async () => { const root = await mkdtemp(join(tmpdir(), 'oc2-shared-lifecycle-')) const paths = await ownPoolPaths(root) diff --git a/packages/opencode/src/tests/quota-feed.integration.test.ts b/packages/opencode/src/tests/quota-feed.integration.test.ts index 90c14e103..8e96675a1 100644 --- a/packages/opencode/src/tests/quota-feed.integration.test.ts +++ b/packages/opencode/src/tests/quota-feed.integration.test.ts @@ -809,13 +809,28 @@ describe('quota header feed integration', () => { const firstResponse = await firstRequest expect(firstResponse.status).toBe(200) await firstResponse.text() - await waitForNativePoolQuota( + const persisted = await waitForNativePoolQuota( 'main', - (quota) => quota?.checkedAt === clock, + (quota) => + quota?.five_hour?.checkedAt === clock && + quota.seven_day?.checkedAt === clock, ) + expect(persisted?.checkedAt).toBe(pollCheckedAt) expect((await readAccountStorage())?.quota?.mainQuota?.scoped).toEqual( scoped, ) + // Storage acceptance does not wait for the detached feed write. + await waitForFeedEntries( + (entries) => + entries.some( + (entry) => + entry !== null && + typeof entry === 'object' && + 'observed_at_ms' in entry && + entry.observed_at_ms === clock, + ), + 'first header observation', + ) clock += 1_000 const secondResponse = await result.fetch(MESSAGES_URL, EMPTY_POST) expect(secondResponse.status).toBe(200) @@ -963,8 +978,11 @@ describe('quota header feed integration', () => { await response.text() const persisted = await waitForAccountStorage( - (candidate) => candidate?.quota?.mainQuota?.checkedAt === clock, + (candidate) => + candidate?.quota?.mainQuota?.five_hour?.checkedAt === clock && + candidate.quota.mainQuota.seven_day?.checkedAt === clock, ) + expect(persisted?.quota?.mainQuota?.checkedAt).toBe(pollCheckedAt) expect(persisted?.quota?.mainQuota?.five_hour?.usedPercent).toBe(11) expect(persisted?.quota?.mainQuota?.seven_day?.usedPercent).toBe(22) expect(persisted?.quota?.mainQuota?.scoped).toEqual(scoped) diff --git a/packages/opencode/src/v2/lifecycle.ts b/packages/opencode/src/v2/lifecycle.ts index 31bedfc13..ed34febda 100644 --- a/packages/opencode/src/v2/lifecycle.ts +++ b/packages/opencode/src/v2/lifecycle.ts @@ -5,6 +5,7 @@ import { type NativeAccountRuntime, nativeAccountCanServe, oauthProfileIsFresh, + quotaPollCheckedAt, quotaSnapshotCheckedAt, readThreeWayBoolean, } from '@cortexkit/anthropic-auth-core' @@ -36,24 +37,37 @@ export function startNativeAnthropicLifecycle( for (const account of current.accounts) { if (abort.signal.aborted) return if (!nativeAccountCanServe(account) || account.type !== 'oauth') continue - if ( - readThreeWayBoolean(current.policyStorage.quota?.enabled, true) && - Date.now() - quotaSnapshotCheckedAt(account.quota) >= interval - ) { + if (readThreeWayBoolean(current.policyStorage.quota?.enabled, true)) { + const vault = current.mode === 'claustrum' + const quota = account.quota + const pollCheckedAt = quotaPollCheckedAt(quota) + // Legacy readings without provenance or poll-only fields have no + // separate poll clock. Their window times still date the reading. + const legacyStandardOnly = + quota?.source === undefined && + quota?.scoped === undefined && + quota?.extraUsage === undefined && + pollCheckedAt === 0 + const checkedAt = + vault || legacyStandardOnly + ? quotaSnapshotCheckedAt(quota) + : Math.min( + pollCheckedAt, + ...(quota?.scoped ?? []).map((window) => window.checkedAt), + ) + const due = Date.now() - checkedAt >= interval // Each quota reading or failure is bound to the credential version // used for its request, so a late result cannot affect a newer login. - // This is the background tick: for a vault account the runtime uses - // a current reading from insula (the vault daemon's quota monitor) - // instead of a usage GET when one exists; see NativeVaultQuotaPurpose. - await runtime - .fetchQuota( - account.id, - fetchImpl, - abort.signal, - undefined, - 'background', - ) - .catch(() => {}) + if (due || vault) + await runtime + .fetchQuota( + account.id, + fetchImpl, + abort.signal, + undefined, + due ? 'background' : 'background-cache', + ) + .catch(() => {}) } if (!oauthProfileIsFresh(account.profile) && !abort.signal.aborted) await runtime