feat(mobile): add safe Codex rate-limit resets (#9394)
* feat(mobile): add safe Codex rate-limit resets * fix(mobile): address reset credit review feedback * review: purge removed-account reset attempts, shared capability constant, rebase test mocks * review: preserve host compatibility and reset durability * fix(mobile): recover reset capability after cutover * fix(mobile): validate runtime capability payloads * fix(mobile): enforce capability payload contract * fix(mobile): route mock terminals to selected worktree * test(mobile): pin malformed probe retry behavior --------- Co-authored-by: Brennan Benson <79079362+brennanb2025@users.noreply.github.com>
This commit is contained in:
co-authored by
Brennan Benson
parent
402b5a1cc8
commit
4a71a0ecb2
@@ -0,0 +1,125 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
EMPTY_CODEX_RESET_CREDIT_ATTEMPT_LEDGER,
|
||||
parseCodexResetCreditAttemptLedger
|
||||
} from './codex-reset-credit-attempt-ledger'
|
||||
|
||||
const hostScope = {
|
||||
target: { runtime: 'host' as const, wslDistro: null },
|
||||
accountId: 'account-host',
|
||||
accountRevision: 42,
|
||||
offerRevision: 'v1:offer-host'
|
||||
}
|
||||
|
||||
describe('Codex reset credit attempt ledger', () => {
|
||||
it('strictly accepts pending and settled durable attempts', () => {
|
||||
expect(
|
||||
parseCodexResetCreditAttemptLedger({
|
||||
version: 1,
|
||||
attempts: [
|
||||
{
|
||||
idempotencyKey: '11111111-1111-4111-8111-111111111111',
|
||||
expectedScope: hostScope,
|
||||
state: 'providerPending'
|
||||
},
|
||||
{
|
||||
idempotencyKey: '22222222-2222-4222-8222-222222222222',
|
||||
expectedScope: {
|
||||
...hostScope,
|
||||
offerRevision: 'v1:offer-settled'
|
||||
},
|
||||
state: 'settled',
|
||||
outcome: 'alreadyRedeemed'
|
||||
}
|
||||
]
|
||||
})
|
||||
).toMatchObject({ version: 1, attempts: [{ state: 'providerPending' }, { state: 'settled' }] })
|
||||
expect(parseCodexResetCreditAttemptLedger(undefined)).toEqual(
|
||||
EMPTY_CODEX_RESET_CREDIT_ATTEMPT_LEDGER
|
||||
)
|
||||
})
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'unknown field',
|
||||
value: { version: 1, attempts: [], extra: true }
|
||||
},
|
||||
{
|
||||
name: 'duplicate idempotency key',
|
||||
value: {
|
||||
version: 1,
|
||||
attempts: [
|
||||
{
|
||||
idempotencyKey: '11111111-1111-4111-8111-111111111111',
|
||||
expectedScope: hostScope,
|
||||
state: 'providerPending'
|
||||
},
|
||||
{
|
||||
idempotencyKey: '11111111-1111-4111-8111-111111111111',
|
||||
expectedScope: { ...hostScope, offerRevision: 'v1:other' },
|
||||
state: 'settled',
|
||||
outcome: 'reset'
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'duplicate claimed offer',
|
||||
value: {
|
||||
version: 1,
|
||||
attempts: [
|
||||
{
|
||||
idempotencyKey: '11111111-1111-4111-8111-111111111111',
|
||||
expectedScope: hostScope,
|
||||
state: 'settled',
|
||||
outcome: 'reset'
|
||||
},
|
||||
{
|
||||
idempotencyKey: '22222222-2222-4222-8222-222222222222',
|
||||
expectedScope: hostScope,
|
||||
state: 'settled',
|
||||
outcome: 'alreadyRedeemed'
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'duplicate pending account scope',
|
||||
value: {
|
||||
version: 1,
|
||||
attempts: [
|
||||
{
|
||||
idempotencyKey: '11111111-1111-4111-8111-111111111111',
|
||||
expectedScope: hostScope,
|
||||
state: 'providerPending'
|
||||
},
|
||||
{
|
||||
idempotencyKey: '22222222-2222-4222-8222-222222222222',
|
||||
expectedScope: { ...hostScope, offerRevision: 'v1:other' },
|
||||
state: 'providerPending'
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'invalid WSL target',
|
||||
value: {
|
||||
version: 1,
|
||||
attempts: [
|
||||
{
|
||||
idempotencyKey: '11111111-1111-4111-8111-111111111111',
|
||||
expectedScope: {
|
||||
...hostScope,
|
||||
target: { runtime: 'wsl', wslDistro: null }
|
||||
},
|
||||
state: 'providerPending'
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
])('rejects $name as a corrupt ledger', ({ value }) => {
|
||||
expect(() => parseCodexResetCreditAttemptLedger(value)).toThrow(
|
||||
'Codex reset-credit attempt ledger is corrupt'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,122 @@
|
||||
import { z } from 'zod'
|
||||
import type { CodexRateLimitResetOutcome } from './rate-limit-types'
|
||||
import type { CodexResetCreditExpectedScope } from './codex-reset-credit-scope'
|
||||
|
||||
const CodexResetCreditTargetSchema = z.discriminatedUnion('runtime', [
|
||||
z.object({ runtime: z.literal('host'), wslDistro: z.null() }).strict(),
|
||||
z.object({ runtime: z.literal('wsl'), wslDistro: z.string().trim().min(1).max(255) }).strict()
|
||||
])
|
||||
|
||||
const CodexResetCreditExpectedScopeSchema = z
|
||||
.object({
|
||||
target: CodexResetCreditTargetSchema,
|
||||
accountId: z.string().min(1).max(512),
|
||||
accountRevision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
||||
offerRevision: z.string().startsWith('v1:').max(4_096)
|
||||
})
|
||||
.strict()
|
||||
|
||||
const DurableCodexResetCreditAttemptSchema = z.discriminatedUnion('state', [
|
||||
z
|
||||
.object({
|
||||
idempotencyKey: z.uuid(),
|
||||
expectedScope: CodexResetCreditExpectedScopeSchema,
|
||||
state: z.literal('providerPending')
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
idempotencyKey: z.uuid(),
|
||||
expectedScope: CodexResetCreditExpectedScopeSchema,
|
||||
state: z.literal('settled'),
|
||||
outcome: z.enum(['reset', 'nothingToReset', 'noCredit', 'alreadyRedeemed'])
|
||||
})
|
||||
.strict()
|
||||
])
|
||||
|
||||
const CodexResetCreditAttemptLedgerSchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
attempts: z.array(DurableCodexResetCreditAttemptSchema).max(10_000)
|
||||
})
|
||||
.strict()
|
||||
.superRefine((ledger, context) => {
|
||||
const keys = new Set<string>()
|
||||
const offers = new Set<string>()
|
||||
const pendingAccountScopes = new Set<string>()
|
||||
for (const [index, attempt] of ledger.attempts.entries()) {
|
||||
const offerScope = JSON.stringify([
|
||||
attempt.expectedScope.target.runtime,
|
||||
attempt.expectedScope.target.wslDistro,
|
||||
attempt.expectedScope.accountId,
|
||||
attempt.expectedScope.accountRevision,
|
||||
attempt.expectedScope.offerRevision
|
||||
])
|
||||
const accountScope = JSON.stringify([
|
||||
attempt.expectedScope.target.runtime,
|
||||
attempt.expectedScope.target.wslDistro,
|
||||
attempt.expectedScope.accountId,
|
||||
attempt.expectedScope.accountRevision
|
||||
])
|
||||
if (keys.has(attempt.idempotencyKey)) {
|
||||
context.addIssue({
|
||||
code: 'custom',
|
||||
message: 'Duplicate idempotency key',
|
||||
path: ['attempts', index, 'idempotencyKey']
|
||||
})
|
||||
}
|
||||
if (offers.has(offerScope)) {
|
||||
context.addIssue({
|
||||
code: 'custom',
|
||||
message: 'Duplicate claimed offer',
|
||||
path: ['attempts', index, 'expectedScope']
|
||||
})
|
||||
}
|
||||
if (attempt.state === 'providerPending' && pendingAccountScopes.has(accountScope)) {
|
||||
context.addIssue({
|
||||
code: 'custom',
|
||||
message: 'Duplicate pending account scope',
|
||||
path: ['attempts', index, 'expectedScope']
|
||||
})
|
||||
}
|
||||
keys.add(attempt.idempotencyKey)
|
||||
offers.add(offerScope)
|
||||
if (attempt.state === 'providerPending') {
|
||||
pendingAccountScopes.add(accountScope)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
export type DurableCodexResetCreditAttempt =
|
||||
| {
|
||||
idempotencyKey: string
|
||||
expectedScope: CodexResetCreditExpectedScope
|
||||
state: 'providerPending'
|
||||
}
|
||||
| {
|
||||
idempotencyKey: string
|
||||
expectedScope: CodexResetCreditExpectedScope
|
||||
state: 'settled'
|
||||
outcome: CodexRateLimitResetOutcome
|
||||
}
|
||||
|
||||
export type CodexResetCreditAttemptLedger = {
|
||||
version: 1
|
||||
attempts: DurableCodexResetCreditAttempt[]
|
||||
}
|
||||
|
||||
export const EMPTY_CODEX_RESET_CREDIT_ATTEMPT_LEDGER: CodexResetCreditAttemptLedger = {
|
||||
version: 1,
|
||||
attempts: []
|
||||
}
|
||||
|
||||
export function parseCodexResetCreditAttemptLedger(value: unknown): CodexResetCreditAttemptLedger {
|
||||
if (value === undefined) {
|
||||
return { version: 1, attempts: [] }
|
||||
}
|
||||
const parsed = CodexResetCreditAttemptLedgerSchema.safeParse(value)
|
||||
if (!parsed.success) {
|
||||
throw new Error('Codex reset-credit attempt ledger is corrupt')
|
||||
}
|
||||
return structuredClone(parsed.data) as CodexResetCreditAttemptLedger
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { ProviderRateLimits } from './rate-limit-types'
|
||||
import type { CodexManagedAccountSummary } from './types'
|
||||
import { buildCodexResetCreditExpectedScope } from './codex-reset-credit-scope'
|
||||
|
||||
const account: CodexManagedAccountSummary = {
|
||||
id: 'account-host',
|
||||
email: 'dev@example.com',
|
||||
managedHomeRuntime: 'host',
|
||||
wslDistro: null,
|
||||
createdAt: 10,
|
||||
updatedAt: 20,
|
||||
lastAuthenticatedAt: 20
|
||||
}
|
||||
|
||||
const limits: ProviderRateLimits = {
|
||||
provider: 'codex',
|
||||
session: {
|
||||
usedPercent: 100,
|
||||
windowMinutes: 300,
|
||||
resetsAt: 1_000,
|
||||
resetDescription: 'soon'
|
||||
},
|
||||
weekly: null,
|
||||
rateLimitResetCredits: {
|
||||
availableCount: 1,
|
||||
totalEarnedCount: 2,
|
||||
nextExpiresAt: 2_000,
|
||||
credits: [{ status: 'available', expiresAt: 2_000, grantedAt: 500 }]
|
||||
},
|
||||
updatedAt: 30,
|
||||
error: null,
|
||||
status: 'ok'
|
||||
}
|
||||
|
||||
describe('buildCodexResetCreditExpectedScope', () => {
|
||||
it('builds a deterministic exact host scope', () => {
|
||||
const first = buildCodexResetCreditExpectedScope({
|
||||
target: { runtime: 'host', wslDistro: null },
|
||||
account,
|
||||
limits
|
||||
})
|
||||
const second = buildCodexResetCreditExpectedScope({
|
||||
target: { runtime: 'host', wslDistro: null },
|
||||
account,
|
||||
limits: {
|
||||
...limits,
|
||||
rateLimitResetCredits: {
|
||||
...limits.rateLimitResetCredits!,
|
||||
credits: [
|
||||
{ status: 'available', expiresAt: 3_000, grantedAt: 600 },
|
||||
...limits.rateLimitResetCredits!.credits!
|
||||
].toReversed()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const firstWithBothRows = buildCodexResetCreditExpectedScope({
|
||||
target: { runtime: 'host', wslDistro: null },
|
||||
account,
|
||||
limits: {
|
||||
...limits,
|
||||
rateLimitResetCredits: {
|
||||
...limits.rateLimitResetCredits!,
|
||||
credits: [
|
||||
...limits.rateLimitResetCredits!.credits!,
|
||||
{ status: 'available', expiresAt: 3_000, grantedAt: 600 }
|
||||
]
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
expect(firstWithBothRows).toEqual(second)
|
||||
expect(first).toMatchObject({
|
||||
target: { runtime: 'host', wslDistro: null },
|
||||
accountId: account.id,
|
||||
accountRevision: account.updatedAt,
|
||||
offerRevision: expect.stringMatching(/^v1:/)
|
||||
})
|
||||
})
|
||||
|
||||
it('changes the offer revision when fetched credit or window data changes', () => {
|
||||
const original = buildCodexResetCreditExpectedScope({
|
||||
target: { runtime: 'host', wslDistro: null },
|
||||
account,
|
||||
limits
|
||||
})
|
||||
const refreshed = buildCodexResetCreditExpectedScope({
|
||||
target: { runtime: 'host', wslDistro: null },
|
||||
account,
|
||||
limits: { ...limits, updatedAt: limits.updatedAt + 1 }
|
||||
})
|
||||
|
||||
expect(refreshed?.offerRevision).not.toBe(original?.offerRevision)
|
||||
})
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'system default account',
|
||||
target: { runtime: 'host', wslDistro: null } as const,
|
||||
candidate: null,
|
||||
candidateLimits: limits
|
||||
},
|
||||
{
|
||||
name: 'no available credit',
|
||||
target: { runtime: 'host', wslDistro: null } as const,
|
||||
candidate: account,
|
||||
candidateLimits: {
|
||||
...limits,
|
||||
rateLimitResetCredits: { ...limits.rateLimitResetCredits!, availableCount: 0 }
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'unknown WSL distro',
|
||||
target: { runtime: 'wsl', wslDistro: null } as const,
|
||||
candidate: { ...account, managedHomeRuntime: 'wsl' as const, wslDistro: 'Ubuntu' },
|
||||
candidateLimits: limits
|
||||
},
|
||||
{
|
||||
name: 'runtime mismatch',
|
||||
target: { runtime: 'wsl', wslDistro: 'Ubuntu' } as const,
|
||||
candidate: account,
|
||||
candidateLimits: limits
|
||||
},
|
||||
{
|
||||
name: 'WSL distro mismatch',
|
||||
target: { runtime: 'wsl', wslDistro: 'Ubuntu' } as const,
|
||||
candidate: { ...account, managedHomeRuntime: 'wsl' as const, wslDistro: 'Debian' },
|
||||
candidateLimits: limits
|
||||
}
|
||||
])('fails closed for $name', ({ target, candidate, candidateLimits }) => {
|
||||
expect(
|
||||
buildCodexResetCreditExpectedScope({
|
||||
target,
|
||||
account: candidate,
|
||||
limits: candidateLimits
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,108 @@
|
||||
import type {
|
||||
ProviderRateLimits,
|
||||
RateLimitRuntimeTarget,
|
||||
RateLimitWindow
|
||||
} from './rate-limit-types'
|
||||
import type { CodexManagedAccountSummary } from './types'
|
||||
|
||||
export type CodexResetCreditExpectedScope = {
|
||||
target: RateLimitRuntimeTarget
|
||||
accountId: string
|
||||
accountRevision: number
|
||||
offerRevision: string
|
||||
}
|
||||
|
||||
type BuildCodexResetCreditExpectedScopeOptions = {
|
||||
target: RateLimitRuntimeTarget
|
||||
account: Pick<
|
||||
CodexManagedAccountSummary,
|
||||
'id' | 'managedHomeRuntime' | 'wslDistro' | 'updatedAt'
|
||||
> | null
|
||||
limits: ProviderRateLimits | null
|
||||
}
|
||||
|
||||
function windowRevision(window: RateLimitWindow | null): readonly unknown[] | null {
|
||||
if (!window) {
|
||||
return null
|
||||
}
|
||||
return [window.usedPercent, window.windowMinutes, window.resetsAt]
|
||||
}
|
||||
|
||||
function buildOfferRevision(limits: ProviderRateLimits): string {
|
||||
const credits = limits.rateLimitResetCredits
|
||||
const creditRows = [...(credits?.credits ?? [])]
|
||||
.map((credit) => [credit.status, credit.expiresAt, credit.grantedAt] as const)
|
||||
.sort((left, right) => {
|
||||
const leftKey = JSON.stringify(left)
|
||||
const rightKey = JSON.stringify(right)
|
||||
return leftKey < rightKey ? -1 : leftKey > rightKey ? 1 : 0
|
||||
})
|
||||
|
||||
// Why: clients treat this as an opaque compare-and-swap token. Including the
|
||||
// fetched-at revision makes a refresh invalidate a confirmation based on old quota data.
|
||||
return `v1:${JSON.stringify([
|
||||
credits?.availableCount ?? 0,
|
||||
credits?.totalEarnedCount ?? null,
|
||||
credits?.nextExpiresAt ?? null,
|
||||
creditRows,
|
||||
windowRevision(limits.session),
|
||||
windowRevision(limits.weekly),
|
||||
limits.updatedAt
|
||||
])}`
|
||||
}
|
||||
|
||||
export function buildCodexResetCreditExpectedScope({
|
||||
target,
|
||||
account,
|
||||
limits
|
||||
}: BuildCodexResetCreditExpectedScopeOptions): CodexResetCreditExpectedScope | null {
|
||||
if (!account || limits?.provider !== 'codex') {
|
||||
return null
|
||||
}
|
||||
if ((limits.rateLimitResetCredits?.availableCount ?? 0) <= 0) {
|
||||
return null
|
||||
}
|
||||
if (
|
||||
!account.id.trim() ||
|
||||
account.id.length > 512 ||
|
||||
!Number.isSafeInteger(account.updatedAt) ||
|
||||
account.updatedAt < 0 ||
|
||||
!Number.isSafeInteger(limits.updatedAt) ||
|
||||
limits.updatedAt < 0
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
const accountRuntime = account.managedHomeRuntime ?? 'host'
|
||||
if (target.runtime === 'host') {
|
||||
if (target.wslDistro !== null || accountRuntime !== 'host') {
|
||||
return null
|
||||
}
|
||||
} else {
|
||||
const targetDistro = target.wslDistro?.trim()
|
||||
const accountDistro = account.wslDistro?.trim()
|
||||
if (
|
||||
!targetDistro ||
|
||||
targetDistro.length > 255 ||
|
||||
accountRuntime !== 'wsl' ||
|
||||
accountDistro !== targetDistro
|
||||
) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const offerRevision = buildOfferRevision(limits)
|
||||
if (offerRevision.length > 4_096) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
target: {
|
||||
runtime: target.runtime,
|
||||
wslDistro: target.runtime === 'wsl' ? target.wslDistro!.trim() : null
|
||||
},
|
||||
accountId: account.id,
|
||||
accountRevision: account.updatedAt,
|
||||
offerRevision
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
WorkspaceSessionState,
|
||||
AgentActivityDisplayMode
|
||||
} from './types'
|
||||
import { EMPTY_CODEX_RESET_CREDIT_ATTEMPT_LEDGER } from './codex-reset-credit-attempt-ledger'
|
||||
import { DEFAULT_STATUS_BAR_ITEMS } from './status-bar-defaults'
|
||||
import { DEFAULT_TERMINAL_FONT_WEIGHT } from './terminal-fonts'
|
||||
import { getDefaultTerminalQuickCommands } from './terminal-quick-commands'
|
||||
@@ -425,7 +426,8 @@ export function getDefaultPersistedState(homedir: string): PersistedState {
|
||||
automations: [],
|
||||
automationRuns: [],
|
||||
onboarding: getDefaultOnboardingState(),
|
||||
featureInteractionTelemetryBuckets: {}
|
||||
featureInteractionTelemetryBuckets: {},
|
||||
codexResetCreditAttemptLedger: structuredClone(EMPTY_CODEX_RESET_CREDIT_ATTEMPT_LEDGER)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ export const TERMINAL_QUICK_COMMANDS_RUNTIME_CAPABILITY = 'terminal.quick-comman
|
||||
// replay ambiguous cutovers when the host advertises idempotent create support.
|
||||
export const WORKTREE_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY =
|
||||
'worktree.create-idempotency.v1' as const
|
||||
export const CODEX_RESET_CREDIT_RUNTIME_CAPABILITY = 'accounts.codex-reset-credit.v1' as const
|
||||
// Why: older hosts cannot reconcile terminal.create's mutation after losing the reply, so clients may only retry unknown outcomes when advertised.
|
||||
export const TERMINAL_CREATE_IDEMPOTENCY_RUNTIME_CAPABILITY =
|
||||
'terminal.create-idempotency.v2' as const
|
||||
@@ -88,7 +89,8 @@ export const RUNTIME_CAPABILITIES = [
|
||||
REMOTE_SERVER_UPDATE_CAPABILITY,
|
||||
AGENT_SESSION_HOST_AUTHORITY_RUNTIME_CAPABILITY,
|
||||
AGENT_SESSION_OMP_RESUME_PATH_RUNTIME_CAPABILITY,
|
||||
FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY
|
||||
FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY,
|
||||
CODEX_RESET_CREDIT_RUNTIME_CAPABILITY
|
||||
] as const
|
||||
|
||||
export type RuntimeCapability = (typeof RUNTIME_CAPABILITIES)[number] | (string & {})
|
||||
|
||||
@@ -43,6 +43,7 @@ import type {
|
||||
import type { UsagePercentageDisplay } from './usage-percentage-display'
|
||||
import type { StatusBarUsageMode } from './status-bar-usage-mode'
|
||||
import type { PersistedNativeChatSessionOptions } from './native-chat-session-options'
|
||||
import type { CodexResetCreditAttemptLedger } from './codex-reset-credit-attempt-ledger'
|
||||
|
||||
// Re-exported for backward compat with renderer call sites that import
|
||||
// `WorkspaceCreateTelemetrySource` from '../../../shared/types'.
|
||||
@@ -3486,6 +3487,8 @@ export type PersistedState = {
|
||||
onboarding: OnboardingState
|
||||
/** Main-owned telemetry de-dupe marker; never exposed through PersistedUIState. */
|
||||
featureInteractionTelemetryBuckets?: FeatureInteractionTelemetryBucketState
|
||||
/** Main-owned reset mutation journal. Never expose this through renderer settings APIs. */
|
||||
codexResetCreditAttemptLedger?: CodexResetCreditAttemptLedger
|
||||
}
|
||||
|
||||
// ─── Filesystem ─────────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user