Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/main/rate-limits/antigravity-usage-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,19 @@ export const ANTIGRAVITY_USAGE_ARGS: readonly string[] = [
*/
export const ANTIGRAVITY_USAGE_TIMEOUT_MS = 30_000

/**
* Why 1.1.11: older agy answers `/usage` as a billable model turn instead of a quota report, so a
* CLI below this floor must never see the usage args. The floor is compared as semver, so
* `1.1.11-rc.1` stays below it and cannot spawn the read early.
*/
export const ANTIGRAVITY_MIN_USAGE_VERSION = '1.1.11'

/** The version probe; free in every sense — no conversation, no quota. */
export const ANTIGRAVITY_VERSION_ARGS: readonly string[] = ['--version']

/** Why bound it: the probe runs before every quota read, so a wedged CLI must not stall the cycle. */
export const ANTIGRAVITY_VERSION_TIMEOUT_MS = 5_000

/** Cap on captured output; the envelope is a single JSON line well under a kilobyte. */
export const ANTIGRAVITY_USAGE_MAX_OUTPUT_BYTES = 512 * 1024

Expand Down
96 changes: 88 additions & 8 deletions src/main/rate-limits/antigravity-usage-fetcher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
fetchAntigravityRateLimits,
resetAntigravityUsageSupportForTests
} from './antigravity-usage-fetcher'
import { ANTIGRAVITY_USAGE_ARGS } from './antigravity-usage-command'
import { ANTIGRAVITY_USAGE_ARGS, ANTIGRAVITY_VERSION_ARGS } from './antigravity-usage-command'
import type { ProcessResult } from '../../shared/child-process/process-spec'

const USAGE_ENVELOPE = JSON.stringify({
Expand Down Expand Up @@ -38,13 +38,24 @@ function processResult(overrides: Partial<ProcessResult> = {}): ProcessResult {
function harness(
options: {
result?: ProcessResult
versionResult?: ProcessResult
runCommand?: ReturnType<typeof vi.fn>
program?: string | null
env?: NodeJS.ProcessEnv
} = {}
) {
// Why the per-call split: the fetcher probes `--version` before the quota read, and a fixture
// that answers both alike either fakes a version line into `/usage` or a usage envelope into the
// version probe.
const runCommand =
options.runCommand ?? vi.fn().mockResolvedValue(options.result ?? processResult())
options.runCommand ??
vi
.fn()
.mockImplementation(async (spec: { args?: readonly string[] }) =>
spec.args?.[0] === '--version'
? (options.versionResult ?? processResult({ stdout: 'agy version 1.2.11\n' }))
: (options.result ?? processResult())
)
// Why the `in` check and not `??`: an explicit `program: null` is the absent-CLI case.
const resolveCommand = vi
.fn()
Expand Down Expand Up @@ -103,12 +114,13 @@ describe('fetchAntigravityRateLimits', () => {
}
})

it('runs the resolved absolute path with the quota arguments and the login-shell env', async () => {
it('probes the version, then runs the quota read with the resolved path and login-shell env', async () => {
const h = harness({ result: processResult({ stdout: USAGE_ENVELOPE }) })
await h.fetch()

expect(h.runCommand).toHaveBeenCalledTimes(1)
const spec = h.runCommand.mock.calls[0]![0]
expect(h.runCommand).toHaveBeenCalledTimes(2)
expect(h.runCommand.mock.calls[0]![0].args).toEqual(ANTIGRAVITY_VERSION_ARGS)
const spec = h.runCommand.mock.calls[1]![0]
expect(spec.program).toBe('/Users/x/.local/bin/agy')
expect(spec.args).toEqual(ANTIGRAVITY_USAGE_ARGS)
// Why the login-shell PATH: agy installs to ~/.local/bin, which Electron's inherited PATH omits.
Expand Down Expand Up @@ -141,6 +153,18 @@ describe('fetchAntigravityRateLimits', () => {
expect(result.error).toContain('Sign in with `agy`')
})

it('reports an auth failure on stderr as sign-in guidance, not as a broken read', async () => {
// Why pinned: the other shape of "signed out" — a non-zero exit with an auth diagnostic — used
// to land in the parse-failure branch as a generic refresh error.
const result = await harness({
result: processResult({ code: 1, stderr: 'Not authenticated. Run agy login.' })
}).fetch()

expect(result.status).toBe('unavailable')
expect(result.usageMetadata?.failureKind).toBe('missing-credentials')
expect(result.error).toContain('Sign in with `agy`')
})

it('reports a timeout as its own failure kind', async () => {
const result = await harness({ result: processResult({ timedOut: true }) }).fetch()

Expand Down Expand Up @@ -216,13 +240,13 @@ describe('agy versions that answer /usage as a prompt', () => {
it('never spawns agy again once a turn was spent', async () => {
const h = harness({ result: processResult({ stdout: MODEL_TURN_ENVELOPE }) })
await h.fetch()
expect(h.runCommand).toHaveBeenCalledTimes(1)
expect(h.runCommand).toHaveBeenCalledTimes(2)

// Why: the evidence costs a turn of the user's quota, so rediscovering it on a 15-minute
// cadence would keep paying for the same answer.
await h.fetch()
await h.fetch()
expect(h.runCommand).toHaveBeenCalledTimes(1)
expect(h.runCommand).toHaveBeenCalledTimes(2)
})

it('does not latch when the usage payload parsed, whatever else the envelope says', async () => {
Expand All @@ -234,7 +258,7 @@ describe('agy versions that answer /usage as a prompt', () => {

expect(first.status).toBe('ok')
expect(second.status).toBe('ok')
expect(h.runCommand).toHaveBeenCalledTimes(2)
expect(h.runCommand).toHaveBeenCalledTimes(4)
})

it('does not latch on an empty or unparsable answer', async () => {
Expand All @@ -245,6 +269,62 @@ describe('agy versions that answer /usage as a prompt', () => {
// Why: a transient failure is not evidence that the command is unsupported.
expect(first.status).toBe('error')
expect(second.status).toBe('error')
expect(h.runCommand).toHaveBeenCalledTimes(4)
})
})

describe('the agy version gate', () => {
beforeEach(() => {
resetAntigravityUsageSupportForTests()
})

it('never runs the quota read below the floor', async () => {
const h = harness({
versionResult: processResult({ stdout: 'agy version 1.1.10\n' }),
result: processResult({ stdout: USAGE_ENVELOPE })
})
const result = await h.fetch()

expect(result.status).toBe('unavailable')
expect(result.usageMetadata?.failureKind).toBe('usage-unavailable')
expect(result.error).toContain('needs agy 1.1.11 or newer (found 1.1.10)')
// Why the assertion: below the floor `/usage` is a billed model turn, so it must not run at all.
expect(h.runCommand).toHaveBeenCalledTimes(1)
expect(h.runCommand.mock.calls[0]![0].args).toEqual(ANTIGRAVITY_VERSION_ARGS)
})

it('holds a prerelease below the floor', async () => {
// Why pinned: `1.1.11-rc.1` sorts below stable `1.1.11`; reading the core alone would let a
// release candidate spawn the billable read early.
const h = harness({ versionResult: processResult({ stdout: 'agy version 1.1.11-rc.1\n' }) })
const result = await h.fetch()

expect(result.status).toBe('unavailable')
expect(result.error).toContain('found 1.1.11-rc.1')
expect(h.runCommand).toHaveBeenCalledTimes(1)
})

it.each([
['a garbled version line', processResult({ stdout: 'agy version unknown\n' })],
['a failed version probe', processResult({ code: 1, stderr: 'boom' })]
])('reports %s instead of guessing', async (_label, versionResult) => {
const h = harness({ versionResult })
const result = await h.fetch()

expect(result.status).toBe('unavailable')
expect(result.usageMetadata?.failureKind).toBe('usage-unavailable')
expect(result.error).toContain('version could not be read')
expect(h.runCommand).toHaveBeenCalledTimes(1)
})

it('runs the quota read at exactly the floor', async () => {
const h = harness({
versionResult: processResult({ stdout: 'agy version 1.1.11\n' }),
result: processResult({ stdout: USAGE_ENVELOPE })
})
const result = await h.fetch()

expect(result.status).toBe('ok')
expect(h.runCommand).toHaveBeenCalledTimes(2)
})
})
74 changes: 58 additions & 16 deletions src/main/rate-limits/antigravity-usage-fetcher.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { runProcess } from '../../shared/child-process/run-process'
import { hasReachedAppVersion, parseCliVersion } from '../../shared/app-version'
import { resolveCommandOnLocalPath } from '../ipc/command-path-resolver'
import { resolveLoginShellEnvironment } from '../startup/login-shell-environment'
import type { ProviderRateLimits, UsageRateLimitFailureKind } from '../../shared/rate-limit-types'
import {
ANTIGRAVITY_MIN_USAGE_VERSION,
ANTIGRAVITY_USAGE_ARGS,
ANTIGRAVITY_USAGE_MAX_OUTPUT_BYTES,
ANTIGRAVITY_USAGE_TIMEOUT_MS,
ANTIGRAVITY_VERSION_ARGS,
ANTIGRAVITY_VERSION_TIMEOUT_MS,
antigravityCommandName
} from './antigravity-usage-command'
import { parseAntigravityUsageStdout, stdoutShowsModelTurn } from './antigravity-usage-response'
Expand All @@ -17,6 +21,12 @@ import { parseAntigravityUsageStdout, stdoutShowsModelTurn } from './antigravity
*/
const NOT_SIGNED_IN_MARKER = 'not logged into antigravity'

/**
* The other shape of "signed out": agy failing the read with an auth diagnostic on stderr and a
* non-zero exit. Same user action as the marker above, so same verdict.
*/
const NOT_SIGNED_IN_STDERR_RE = /auth|login|sign.?in|credential/i
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved

const UNSUPPORTED_USAGE_COMMAND_REASON =
'Antigravity usage is not available. This version of the Antigravity CLI answers `/usage` as a prompt instead of a command, so Orca stopped asking rather than spend quota on it. Update `agy` and restart Orca.'

Expand Down Expand Up @@ -66,6 +76,10 @@ function unavailable(
}
}

function spawnFailureMessage(error: unknown): string {
return `Antigravity usage is not available. The Antigravity CLI could not be started: ${error instanceof Error ? error.message : 'unknown error'}.`
}

function failed(
message: string,
failureKind: UsageRateLimitFailureKind,
Expand Down Expand Up @@ -120,6 +134,33 @@ export async function fetchAntigravityRateLimits(
)
}

// Why the version is re-checked before every read: it is the only thing that separates a free
// metadata read from a billed model turn, and the CLI can be swapped or updated while Orca runs.
// Below the floor `/usage` is a prompt, so the gate must decide from `--version` alone.
let versionRun: Awaited<ReturnType<typeof runProcess>>
try {
versionRun = await run({
program,
args: ANTIGRAVITY_VERSION_ARGS,
env,
timeoutMs: ANTIGRAVITY_VERSION_TIMEOUT_MS,
maxOutputBytes: ANTIGRAVITY_USAGE_MAX_OUTPUT_BYTES,
signal: options.signal
})
} catch (error) {
return failed(spawnFailureMessage(error), 'cli-unavailable', now())
}
const version = versionRun.code === 0 ? parseCliVersion(versionRun.stdout) : null
if (!version || !hasReachedAppVersion(version, ANTIGRAVITY_MIN_USAGE_VERSION)) {
return unavailable(
version
? `Antigravity usage needs agy ${ANTIGRAVITY_MIN_USAGE_VERSION} or newer (found ${version}). Update the agy CLI to show quota in the status bar.`
: `Antigravity usage is unavailable because the agy CLI version could not be read. Update agy to ${ANTIGRAVITY_MIN_USAGE_VERSION} or newer.`,
'usage-unavailable',
now()
)
}

let result: Awaited<ReturnType<typeof runProcess>>
try {
result = await run({
Expand All @@ -131,11 +172,7 @@ export async function fetchAntigravityRateLimits(
signal: options.signal
})
} catch (error) {
return failed(
`Antigravity usage is not available. The Antigravity CLI could not be started: ${error instanceof Error ? error.message : 'unknown error'}.`,
'cli-unavailable',
now()
)
return failed(spawnFailureMessage(error), 'cli-unavailable', now())
}

if (result.timedOut) {
Expand All @@ -146,25 +183,30 @@ export async function fetchAntigravityRateLimits(
)
}

const output = `${result.stdout}\n${result.stderr}`
if (output.toLowerCase().includes(NOT_SIGNED_IN_MARKER)) {
return unavailable(
'Antigravity usage is not available. Sign in with `agy` to report this account’s quota.',
'missing-credentials',
now()
)
}

const reading = parseAntigravityUsageStdout(result.stdout)
// Why the successful read is checked first: a real reading can never be evidence of a prompt, so
// ordering it ahead of the turn check makes a false latch impossible.
if (!reading && stdoutShowsModelTurn(result.stdout)) {
usageCommandUnsupported = true
return unavailable(UNSUPPORTED_USAGE_COMMAND_REASON, 'usage-unavailable', now())
}
// Why two shapes: a signed-out agy either exits 0 with the observed marker below or fails the
// read with an auth diagnostic on stderr. Both mean "sign in", not "the read broke". Checked
// after the turn check so a spent turn always latches first.
const output = `${result.stdout}\n${result.stderr}`
const signedOut =
output.toLowerCase().includes(NOT_SIGNED_IN_MARKER) ||
(result.code !== 0 && result.code !== null && NOT_SIGNED_IN_STDERR_RE.test(result.stderr))
if (signedOut) {
return unavailable(
'Antigravity usage is not available. Sign in with `agy` to report this account’s quota.',
'missing-credentials',
now()
)
}
if (!reading) {
// Why a non-zero exit is reported only here: `runProcess` treats the exit code as data, and agy
// exits 0 for a signed-out read, so the code only adds detail once the payload is missing.
// Why a non-zero exit is reported only here: `runProcess` treats the exit code as data, and a
// signed-out read is classified above, so the code only adds detail once the payload is missing.
const exitDetail = result.code === 0 || result.code === null ? '' : ` (exit ${result.code})`
return failed(
`Antigravity usage is not available. The Antigravity CLI did not report a quota${exitDetail}.`,
Expand Down
Loading