Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
- Spend dashboard: silently refresh independent providers (Claude/Cursor) when their token publications update, bucket the activity heatmap with the configured IANA timezone, and stop coalescing display-affecting ownership and revision changes (#3106). Thanks @Yuxin-Qiao!
- Spend: add tokscale-compatible local readers for Cursor and Antigravity local history (#3113). Thanks @Yuxin-Qiao!
- Antigravity: map retired Flash wire IDs to their current tier, and count local conversations as an offline fallback when the desktop app is unavailable (#3119). Thanks @Yuxin-Qiao!
- Antigravity: reuse a signed-in `agy` for menu-bar quota refreshes without the desktop app, and report CLI sign-in failures instead of asking users to launch an unavailable app (#3146).

- Fixed single-quota menu-bar icons understating remaining usage: a provider's only meaningful quota now renders as one prominent meter instead of half an icon next to a reserved empty lane, including when it arrives in the secondary slot (#3154, #3155). Thanks @akshayprabhu200!
- Grok: report period-only CLI-proxy responses as unknown usage instead of 0% when Grok Build has hit its free limit, keeping identity and reset metadata (#3157, #3159). Thanks @anupamchugh!
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,21 +31,25 @@ protocol AntigravityCLIProcessLaunching: Sendable {

enum AntigravityCLIAuthenticationPrompt {
static let evidence = Data("Select login method:".utf8)
private static let promptPattern = #"select\s+login\s+method\s*:?"#
private static let authenticationPatterns = [
#"select\s+login\s+method\s*:?"#,
#"you\s+are\s+not\s+logged\s+into\s+antigravity"#,
#"keyring\s*auth\s*:\s*timed\s+out\b"#,
]

static func contains(_ output: Data) -> Bool {
// `agy` briefly prints "You are currently not signed in" before it
// auto-refreshes an existing login. The actual blocking state is the
// interactive login-method prompt. The exact prompt is a CLI-owned TUI
// string, so keep matching tolerant to casing and whitespace changes.
// auto-refreshes an existing login. Only a blocking login prompt, an
// explicit Antigravity logout, or exhausted keyring authentication
// establishes that the managed session cannot recover its credentials.
if output.range(of: self.evidence) != nil {
return true
}
let asciiBytes = output.map { $0 < 0x80 ? $0 : 0x20 }
let text = String(bytes: asciiBytes, encoding: .utf8) ?? ""
return text.range(
of: self.promptPattern,
options: [.regularExpression, .caseInsensitive]) != nil
return self.authenticationPatterns.contains { pattern in
text.range(of: pattern, options: [.regularExpression, .caseInsensitive]) != nil
}
}
}

Expand Down Expand Up @@ -1087,12 +1091,16 @@ final class AntigravitySpawnedPTYProcessHandle: AntigravityCLIProcessHandle, @un
retries = 0
continue
}
if written == 0 { break }
if written == 0 {
break
}

let err = errno
if err == EINTR || err == EAGAIN || err == EWOULDBLOCK {
retries += 1
if retries > 200 { return }
if retries > 200 {
return
}
usleep(5000)
continue
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ public enum AntigravityProviderDescriptor {
}),
fetchPlan: ProviderFetchPlan(
sourceModes: [.auto, .cli, .oauth],
pipeline: ProviderFetchPipeline(resolveStrategies: self.resolveStrategies)),
pipeline: ProviderFetchPipeline(
resolveStrategies: self.resolveStrategies,
resolveFallbackError: self.resolveFallbackError)),
cli: ProviderCLIConfig(
name: "antigravity",
versionDetector: nil))
Expand Down Expand Up @@ -205,6 +207,15 @@ public enum AntigravityProviderDescriptor {
let fileURL = AntigravityOAuthCredentialsStore.defaultURL(home: homeURL)
return FileManager.default.fileExists(atPath: fileURL.path)
}

static func resolveFallbackError(_ previous: Error?, _ current: Error) -> Error {
if (previous as? AntigravityStatusProbeError) == .authenticationRequired,
(current as? AntigravityStatusProbeError) == .notRunning
Comment on lines +212 to +213

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve auth errors when the IDE lacks a CSRF token

When the CLI emits one of the newly recognized signed-out messages and a tokenless Antigravity IDE process is also present, the subsequent IDE probe throws .missingCSRFToken rather than .notRunning. This resolver consequently replaces the actionable .authenticationRequired result and again tells the user to restart Antigravity instead of signing into agy; treat IDE-unavailability errors such as .missingCSRFToken the same as .notRunning when an earlier CLI authentication failure exists.

Useful? React with 👍 / 👎.

{
return previous ?? current
}
return current
}
}

struct AntigravityStatusFetchStrategy: ProviderFetchStrategy {
Expand Down Expand Up @@ -553,10 +564,10 @@ struct AntigravityCLIHTTPSFetchStrategy: ProviderFetchStrategy {
// CodexBar must not manage its lifecycle, idle timeout, or
// `resetAfterFetch` teardown. Those apply only to processes CodexBar
// itself spawns on the fallback path below.
// Long-lived hosts already keep a managed session warm. Restrict external
// process reuse to one-shot CLI calls so app/server lifecycle accounting
// stays entirely inside AntigravityCLISession.
if resetAfterFetch, let warmSnapshot = try await Self.tryWarmAgyFetch(
// Persistent hosts also need the external path: a user-owned, signed-in
// `agy` may have credentials a newly spawned managed session cannot read.
// Owned pids remain excluded, so their lifecycle accounting is unchanged.
if let warmSnapshot = try await Self.tryWarmAgyFetch(
timeout: 2.0,
expectedBinaryPath: binary,
Comment on lines +570 to 572

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Accept PATH-launched agy in persistent warm reuse

When a user starts agy normally from a terminal, its argv commonly begins with the bare agy name, while binary here is the absolute path resolved from PATH. The warm scan therefore reaches commandLine(_:matchesBinaryPath:), which accepts only that absolute path or its resolved symlink, rejects the signed-in process, and falls back to spawning the unauthenticated managed process—the exact menu-bar scenario this change is intended to fix. Match against the discovered executable identity or also safely support the bare argv form.

Useful? React with 👍 / 👎.

expectedAccountEmail: expectedAccountEmail,
Expand Down
8 changes: 6 additions & 2 deletions Sources/CodexBarCore/Providers/ProviderFetchPlan.swift
Original file line number Diff line number Diff line change
Expand Up @@ -306,19 +306,23 @@ extension ProviderFetchStrategy {

public struct ProviderFetchPipeline: Sendable {
public typealias RetrySleeper = @Sendable (TimeInterval) async throws -> Void
public typealias FallbackErrorResolver = @Sendable (Error?, Error) -> Error

public let resolveStrategies: @Sendable (ProviderFetchContext) async -> [any ProviderFetchStrategy]
private let retrySleeper: RetrySleeper
private let resolveFallbackError: FallbackErrorResolver

public init(
resolveStrategies: @escaping @Sendable (ProviderFetchContext) async -> [any ProviderFetchStrategy],
retrySleeper: @escaping RetrySleeper = { seconds in
guard seconds > 0 else { return }
try await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
})
},
resolveFallbackError: @escaping FallbackErrorResolver = { _, error in error })
{
self.resolveStrategies = resolveStrategies
self.retrySleeper = retrySleeper
self.resolveFallbackError = resolveFallbackError
}

public func fetch(context: ProviderFetchContext, provider: UsageProvider) async -> ProviderFetchOutcome {
Expand Down Expand Up @@ -361,7 +365,7 @@ public struct ProviderFetchPipeline: Sendable {
errorDescription: nil))
return ProviderFetchOutcome(result: .success(result), attempts: attempts)
} catch {
lastAvailableError = error
lastAvailableError = self.resolveFallbackError(lastAvailableError, error)
attempts.append(ProviderFetchAttempt(
strategyID: strategy.id,
kind: strategy.kind,
Expand Down
110 changes: 110 additions & 0 deletions Tests/CodexBarTests/AntigravityCLIHTTPSFetchStrategyTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,37 @@ struct AntigravityCLIHTTPSFetchStrategyTests {
#expect(snapshot.accountEmail == "user@example.com")
}

@Test
func `cli HTTPS stops when managed agy reports exhausted keyring authentication`() async {
let output = AntigravityCLIOutputSequence([
Data("You are currently not signed in.\nSigning in...".utf8),
Data("keyringAuth: timed out after 10s, skipping keyring auth".utf8),
])
let portPolls = AntigravityCLICounter()

do {
_ = try await AntigravityCLIHTTPSFetchStrategy.waitForSnapshot(
pid: 123,
deadline: Date().addingTimeInterval(2),
dependencies: AntigravityCLIHTTPSFetchStrategy.SnapshotWaitDependencies(
pollIntervalNanoseconds: 0,
listeningPorts: { _, _ in
portPolls.increment()
return []
},
drainOutput: { output.next() },
fetchSnapshot: { _ in
Issue.record("An unauthenticated helper must not fetch a snapshot")
throw AntigravityStatusProbeError.notRunning
}))
Issue.record("Expected authentication failure")
} catch AntigravityStatusProbeError.authenticationRequired {
#expect(portPolls.value == 1)
} catch {
Issue.record("Expected authenticationRequired, got \(error)")
}
}

@Test
func `cli HTTPS rechecks signed out prompt after snapshot readiness`() async {
let output = AntigravityCLIOutputSequence([
Expand Down Expand Up @@ -952,3 +983,82 @@ struct AntigravityCLIHTTPSFetchStrategyTests {
}
}
}

extension AntigravityCLIHTTPSFetchStrategyTests {
@Test
func `missing IDE cannot replace actionable signed out CLI error`() async {
let pipeline = ProviderFetchPipeline(
resolveStrategies: { _ in
[
AntigravityFallbackFixtureStrategy(
id: "antigravity.cli-https",
error: .authenticationRequired),
AntigravityFallbackFixtureStrategy(
id: "antigravity.ide-local",
error: .notRunning),
]
},
resolveFallbackError: AntigravityProviderDescriptor.resolveFallbackError)

let outcome = await pipeline.fetch(context: self.makeFetchContext(), provider: .antigravity)

#expect(outcome.attempts.map(\.strategyID) == ["antigravity.cli-https", "antigravity.ide-local"])
do {
_ = try outcome.result.get()
Issue.record("Expected the signed-out CLI failure")
} catch {
#expect((error as? AntigravityStatusProbeError) == .authenticationRequired)
}
}

@Test
func `signed out CLI still allows a usable IDE fallback`() async throws {
let pipeline = ProviderFetchPipeline(
resolveStrategies: { _ in
[
AntigravityFallbackFixtureStrategy(
id: "antigravity.cli-https",
error: .authenticationRequired),
AntigravityFallbackFixtureStrategy(id: "antigravity.ide-local", error: nil),
]
},
resolveFallbackError: AntigravityProviderDescriptor.resolveFallbackError)

let outcome = await pipeline.fetch(context: self.makeFetchContext(), provider: .antigravity)

#expect(try outcome.result.get().sourceLabel == "ide")
#expect(outcome.attempts.count == 2)
}

@Test
func `specific later fallback error replaces signed out CLI error`() {
let result = AntigravityProviderDescriptor.resolveFallbackError(
AntigravityStatusProbeError.authenticationRequired,
AntigravityStatusProbeError.apiError("OAuth credentials expired"))

#expect((result as? AntigravityStatusProbeError) == .apiError("OAuth credentials expired"))
}
}

private struct AntigravityFallbackFixtureStrategy: ProviderFetchStrategy {
let id: String
let error: AntigravityStatusProbeError?
let kind: ProviderFetchKind = .localProbe

func isAvailable(_: ProviderFetchContext) async -> Bool {
true
}

func fetch(_: ProviderFetchContext) async throws -> ProviderFetchResult {
if let error {
throw error
}
return self.makeResult(
usage: UsageSnapshot(primary: nil, secondary: nil, updatedAt: Date()),
sourceLabel: "ide")
}

func shouldFallback(on _: Error, context _: ProviderFetchContext) -> Bool {
true
}
}
28 changes: 24 additions & 4 deletions Tests/CodexBarTests/AntigravityCLISessionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,9 @@ private final class AntigravityManualSleeper: @unchecked Sendable {

func waitForSleeps(_ expectedCount: Int) async {
for _ in 0..<200 {
if self.pendingSleepCount >= expectedCount { return }
if self.pendingSleepCount >= expectedCount {
return
}
try? await Task.sleep(nanoseconds: 1_000_000)
}
Issue.record("Timed out waiting for \(expectedCount) sleep continuation(s)")
Expand Down Expand Up @@ -703,7 +705,9 @@ struct AntigravityCLISessionTests {
let lines = output
.split(separator: "\n")
.map(String.init)
if lines.count >= 2, output.hasSuffix("\n") { break }
if lines.count >= 2, output.hasSuffix("\n") {
break
}
}
Thread.sleep(forTimeInterval: 0.01)
}
Expand Down Expand Up @@ -776,6 +780,18 @@ struct AntigravityCLISessionTests {
Data("You are currently not signed in".utf8)))
}

@Test
func `authentication prompt matcher recognizes logged out and exhausted keyring states`() {
#expect(AntigravityCLIHTTPSFetchStrategy.containsAuthenticationPrompt(
Data("You are not logged into Antigravity.".utf8)))
#expect(AntigravityCLIHTTPSFetchStrategy.containsAuthenticationPrompt(
Data("keyringAuth: timed out after 10s, skipping keyring auth".utf8)))
#expect(AntigravityCLIHTTPSFetchStrategy.containsAuthenticationPrompt(
Data("KEYRING auth : timed out after 10s".utf8)))
#expect(!AntigravityCLIHTTPSFetchStrategy.containsAuthenticationPrompt(
Data("Welcome. You are currently not signed in.\nSigning in...".utf8)))
}

@Test
func `session returns complete new output before retaining only its tail`() async throws {
let fixture = self.makeFixture()
Expand Down Expand Up @@ -1454,7 +1470,9 @@ extension AntigravityCLISessionTests {

private func waitForLaunches(_ launcher: FakeAntigravityProcessLauncher, count: Int) async -> Bool {
for _ in 0..<200 {
if launcher.launchedBinarySnapshot().count >= count { return true }
if launcher.launchedBinarySnapshot().count >= count {
return true
}
try? await Task.sleep(nanoseconds: 1_000_000)
}
return false
Expand All @@ -1463,7 +1481,9 @@ extension AntigravityCLISessionTests {
private func waitUntilStopped(_ session: AntigravityCLISession) async {
for _ in 0..<200 {
let running = await session.isRunning
if !running { return }
if !running {
return
}
await Task.yield()
}
Issue.record("Timed out waiting for Antigravity CLI session to stop")
Expand Down
42 changes: 32 additions & 10 deletions Tests/CodexBarTests/AntigravityWarmAgyReuseTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ struct AntigravityWarmAgyReuseTests {
}

@Test
func `long lived session skips external warm scan`() async throws {
func `long lived session reuses signed in external agy without spawning`() async throws {
let spawnCallCount = AntigravityWarmLockedCounter()
let strategy = AntigravityCLIHTTPSFetchStrategy()

Expand All @@ -354,21 +354,43 @@ struct AntigravityWarmAgyReuseTests {
idleWindow: 60,
resetAfterFetch: false,
warmDependencies: AntigravityCLIHTTPSFetchStrategy.WarmAgyDependencies(
processInfos: { _ in
Issue.record("long-lived hosts must use their managed session")
return [Self.cliProcessInfo(pid: 6301)]
},
listeningPorts: { _, _ in [] },
fetchSnapshot: { _, _ in throw AntigravityStatusProbeError.notRunning }),
spawnFetch: { _, _, resetAfterFetch in
processInfos: { _ in [Self.cliProcessInfo(pid: 6301)] },
listeningPorts: { _, _ in [50080] },
fetchSnapshot: { _, _ in Self.usableSnapshot(email: "terminal@example.com") }),
spawnFetch: { _, _, _ in
spawnCallCount.increment()
Issue.record("persistent hosts must reuse an authenticated user-owned agy")
throw AntigravityStatusProbeError.notRunning
})

#expect(result.usage.identity?.accountEmail == "terminal@example.com")
#expect(spawnCallCount.value == 0)
}

@Test
func `long lived session falls back to managed agy when external account mismatches`() async throws {
let spawnCallCount = AntigravityWarmLockedCounter()
let strategy = AntigravityCLIHTTPSFetchStrategy()

let result = try await strategy.fetchUsingWarmSession(
binary: "/usr/local/bin/agy",
idleWindow: 60,
resetAfterFetch: false,
expectedAccountEmail: "selected@example.com",
warmDependencies: AntigravityCLIHTTPSFetchStrategy.WarmAgyDependencies(
processInfos: { _ in [Self.cliProcessInfo(pid: 6301)] },
listeningPorts: { _, _ in [50080] },
fetchSnapshot: { _, _ in Self.usableSnapshot(email: "other@example.com") }),
spawnFetch: { _, idleWindow, resetAfterFetch in
spawnCallCount.increment()
#expect(idleWindow == 60)
#expect(!resetAfterFetch)
return strategy.makeResult(
usage: Self.usableUsage(email: "managed@example.com"),
usage: Self.usableUsage(email: "selected@example.com"),
sourceLabel: AntigravityCLIHTTPSFetchStrategy.sourceLabel)
})

#expect(result.usage.identity?.accountEmail == "managed@example.com")
#expect(result.usage.identity?.accountEmail == "selected@example.com")
#expect(spawnCallCount.value == 1)
}

Expand Down
Loading
Loading