Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
18 changes: 15 additions & 3 deletions server/drivers/antigravity-acp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export interface AntigravityProfile {
directory: string;
tokenPath: string;
legacyTokenPath: string;
usageTokenPath?: string;
environment: NodeJS.ProcessEnv;
tempDirectory?: string;
}
Expand Down Expand Up @@ -87,7 +88,7 @@ const REMOVED_ENVIRONMENT_KEYS = new Set([
// Another Antigravity host (IDE, T3 Code, CLI) exports ANTIGRAVITY_LS_ADDRESS, CSRF tokens, and app-data dirs into child shells.
const REMOVED_ENVIRONMENT_PREFIXES = ["ANTIGRAVITY_", "AGY_", "JETSKI_"] as const;

function isRemovedAntigravityEnvKey(key: string): boolean {
export function isRemovedAntigravityEnvKey(key: string): boolean {
const upper = key.toUpperCase();
return REMOVED_ENVIRONMENT_KEYS.has(upper)
|| REMOVED_ENVIRONMENT_PREFIXES.some((prefix) => upper.startsWith(prefix));
Expand Down Expand Up @@ -168,16 +169,26 @@ export async function removeAntigravityProfile(instanceId: string, baseDir = DAT
});
}

export function antigravityUsageHome(profileDirectory: string): string {
return join(profileDirectory, "usage-home");
}

export function antigravityUsageTokenPath(profileDirectory: string): string {
return join(antigravityUsageHome(profileDirectory), ".gemini", "antigravity-cli", ANTIGRAVITY_CLI_TOKEN_FILE);
}

/** Signing out forgets only this account's stored Google sign-in; its profile stays for the next sign-in. */
export async function removeAntigravitySignIn(instanceId: string, baseDir = DATA_DIR): Promise<void> {
const acpDirectory = join(antigravityProfileDirectory(instanceId, baseDir), ANTIGRAVITY_APP_DATA_DIR);
const profileDir = antigravityProfileDirectory(instanceId, baseDir);
const acpDirectory = join(profileDir, ANTIGRAVITY_APP_DATA_DIR);
await forgetAntigravitySignIn({
tokenPath: join(acpDirectory, ANTIGRAVITY_CLI_TOKEN_FILE),
legacyTokenPath: join(acpDirectory, ANTIGRAVITY_LEGACY_TOKEN_FILE),
usageTokenPath: antigravityUsageTokenPath(profileDir),
});
}

function resolveLinuxCaBundle(baseEnv: NodeJS.ProcessEnv, platform: NodeJS.Platform): string | undefined {
export function resolveLinuxCaBundle(baseEnv: NodeJS.ProcessEnv, platform: NodeJS.Platform): string | undefined {
if (platform !== "linux" || baseEnv.SSL_CERT_FILE !== undefined || baseEnv.SSL_CERT_DIR !== undefined) {
return undefined;
}
Expand Down Expand Up @@ -259,6 +270,7 @@ export async function prepareAntigravityProfile(input: {
directory,
tokenPath: join(acpDirectory, ANTIGRAVITY_CLI_TOKEN_FILE),
legacyTokenPath: join(acpDirectory, ANTIGRAVITY_LEGACY_TOKEN_FILE),
usageTokenPath: antigravityUsageTokenPath(directory),
environment,
...(tempDirectory ? { tempDirectory } : {}),
};
Expand Down
6 changes: 5 additions & 1 deletion server/drivers/antigravity-signin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";

import { antigravityProfileAuthenticated, prepareAntigravityProfile, removeAntigravitySignIn } from "./antigravity-acp.ts";
import { antigravityProfileAuthenticated, antigravityUsageTokenPath, prepareAntigravityProfile, removeAntigravitySignIn } from "./antigravity-acp.ts";
import {
acceptNewAntigravitySignIn,
antigravityKeepPath,
Expand Down Expand Up @@ -91,11 +91,15 @@ describe("the Google sign-in survives what happens to its file", () => {
it("removeAntigravitySignIn takes the copy too", async () => {
const base = temp();
const profile = await prepareAntigravityProfile({ instanceId: "acct", runtime: { executablePath: "agy", version: "1.5.0" } as never, baseDir: base, baseEnv: { PATH: process.env.PATH } });
const usageToken = antigravityUsageTokenPath(profile.directory);
writeFileSync(profile.tokenPath, token("r1"));
mkdirSync(join(usageToken, ".."), { recursive: true });
writeFileSync(usageToken, token("r1"));
await ensureAntigravitySignIn(profile);
await removeAntigravitySignIn("acct", base);
expect(existsSync(profile.tokenPath)).toBe(false);
expect(existsSync(antigravityKeepPath(profile.tokenPath))).toBe(false);
expect(existsSync(usageToken)).toBe(false);
});
});

Expand Down
2 changes: 2 additions & 0 deletions server/drivers/antigravity-signin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const MAX_TOKEN_BYTES = 1024 * 1024;
export interface AntigravityTokenPaths {
tokenPath: string;
legacyTokenPath?: string;
usageTokenPath?: string;
}

export type TokenState = "durable" | "short-lived" | "missing" | "corrupt";
Expand Down Expand Up @@ -94,6 +95,7 @@ export async function forgetAntigravitySignIn(paths: AntigravityTokenPaths): Pro
rm(antigravityKeepPath(paths.tokenPath), { force: true, maxRetries: 4, retryDelay: 250 }),
rm(paths.tokenPath, { force: true, maxRetries: 4, retryDelay: 250 }),
...(paths.legacyTokenPath ? [rm(paths.legacyTokenPath, { force: true, maxRetries: 4, retryDelay: 250 })] : []),
...(paths.usageTokenPath ? [rm(paths.usageTokenPath, { force: true, maxRetries: 4, retryDelay: 250 })] : []),
]);
});
}
Expand Down
265 changes: 265 additions & 0 deletions server/drivers/antigravity-usage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";

import type { PlanAccount } from "../plan-usage-types.ts";
import {
ANTIGRAVITY_APP_DATA_DIR,
ANTIGRAVITY_CLI_TOKEN_FILE,
antigravityProfileDirectory,
antigravityUsageHome,
antigravityUsageTokenPath,
} from "./antigravity-acp.ts";
import { AntigravitySetupError, type AntigravityRuntime } from "./antigravity-runtime.ts";
import {
ANTIGRAVITY_USAGE_UPDATE_MESSAGE,
antigravityUsageEnvironment,
createAntigravityUsageProbe,
type AntigravityUsageCommandRunner,
} from "./antigravity-usage.ts";

const tempDirs: string[] = [];

afterEach(() => {
for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});

function makeTempDir(prefix: string): string {
const dir = mkdtempSync(join(tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}

function account(overrides: Partial<PlanAccount> = {}): PlanAccount {
return {
id: "antigravity",
name: "Antigravity",
driver: "antigravity",
environment: {},
...overrides,
};
}

function writeFakeCli(dir: string, scriptBody: string): string {
const scriptPath = join(dir, "fake-agy.mjs");
writeFileSync(scriptPath, `#!/usr/bin/env node\n${scriptBody}`, "utf8");
if (process.platform !== "win32") chmodSync(scriptPath, 0o755);
return scriptPath;
}

function seedProfileToken(dataDir: string, instanceId: string, content: string): { profileDir: string; tokenPath: string } {
const profileDir = antigravityProfileDirectory(instanceId, dataDir);
const tokenPath = join(profileDir, ANTIGRAVITY_APP_DATA_DIR, ANTIGRAVITY_CLI_TOKEN_FILE);
mkdirSync(dirname(tokenPath), { recursive: true });
writeFileSync(tokenPath, content, "utf8");
return { profileDir, tokenPath };
}

describe("Antigravity CLI usage probe", () => {
it("isolates usage-home, copies the profile token, strips foreign env vars, and parses agy usage --json", async () => {
const dataDir = makeTempDir("dusk-agy-usage-data-");
const binDir = makeTempDir("dusk-agy-usage-bin-");
const tokenContent = JSON.stringify({ token: { access_token: "live-tok", refresh_token: "live-ref" } });
const { profileDir } = seedProfileToken(dataDir, "antigravity", tokenContent);

const fakeCli = writeFakeCli(
binDir,
`
import { readFileSync } from "node:fs";
import { join } from "node:path";
if (process.argv[2] !== "usage" || process.argv[3] !== "--json") {
console.error("bad args", process.argv.slice(2));
process.exit(2);
}
if (process.env.GEMINI_API_KEY || process.env.AGY_ACP_DEFAULT_MODEL || process.env.ANTIGRAVITY_LS_ADDRESS) {
console.error("leaked env");
process.exit(3);
}
if (process.env.AGY_CLI_FORCE_FILE_TOKEN_STORAGE !== "1" || process.env.AGY_ACP_FORCE_FILE_STORAGE !== "1" || !process.env.SSH_CONNECTION) {
console.error("missing file storage flags");
process.exit(4);
}
const home = process.platform === "win32" ? process.env.USERPROFILE : process.env.HOME;
const staged = readFileSync(join(home, ".gemini", "antigravity-cli", "antigravity-oauth-token"), "utf8");
if (!staged.includes("live-ref")) {
console.error("missing staged token");
process.exit(5);
}
console.log(JSON.stringify({
status: "SUCCESS",
command: {
name: "usage",
data: {
groups: [
{
name: "Gemini",
buckets: [
{ id: "gemini-5h", window: "5h", remaining_fraction: 0.75, reset_time: "2027-01-01T05:00:00Z" },
{ id: "gemini-weekly", window: "weekly", remaining_fraction: 0.9, reset_time: "2027-01-07T00:00:00Z" },
],
},
{
name: "Claude & GPT",
buckets: [
{ id: "3p-5h", window: "5h", remaining_fraction: 1, reset_time: "1970-01-01T00:00:00Z" },
],
},
],
},
},
}));
`,
);

const probe = createAntigravityUsageProbe({
dataDir,
env: {
...process.env,
HOME: "/should/not/be/used",
USERPROFILE: "C:\\should\\not\\be\\used",
GEMINI_API_KEY: "secret-key",
AGY_ACP_DEFAULT_MODEL: "gemini-3",
ANTIGRAVITY_LS_ADDRESS: "127.0.0.1:9999",
},
resolveRuntime: async (): Promise<AntigravityRuntime> => ({
executablePath: fakeCli,
source: "managed",
version: "1.5.22",
}),
});

const outcome = await probe(account());
expect(outcome).toEqual({
kind: "ok",
windows: {
plan: null,
fiveHour: { available: true, usedPercent: 25, remainingPercent: 75, resetsAt: "2027-01-01T05:00:00.000Z" },
weekly: { available: true, usedPercent: 10, remainingPercent: 90, resetsAt: "2027-01-07T00:00:00.000Z" },
extra: [],
models: [
{
name: "Claude & GPT",
windows: [{ label: "5-hour", usedPercent: 0, remainingPercent: 100, resetsAt: null }],
},
],
},
});
expect(readFileSync(antigravityUsageTokenPath(profileDir), "utf8")).toBe(tokenContent);
});

it("refuses versions older than 1.5.22 without spawning agy", async () => {
const dataDir = makeTempDir("dusk-agy-old-");
seedProfileToken(dataDir, "antigravity", JSON.stringify({ token: { access_token: "a", refresh_token: "r" } }));
const runCommand = vi.fn<AntigravityUsageCommandRunner>();
const probe = createAntigravityUsageProbe({
dataDir,
resolveRuntime: async () => ({ executablePath: "agy", source: "path", version: "1.5.17" }),
runCommand,
});
const outcome = await probe(account());
expect(outcome).toEqual({ kind: "other", error: ANTIGRAVITY_USAGE_UPDATE_MESSAGE });
expect(runCommand).not.toHaveBeenCalled();
});

it("maps unknown-version unexpected argument errors to the 1.5.22 update message", async () => {
const dataDir = makeTempDir("dusk-agy-override-");
seedProfileToken(dataDir, "antigravity", JSON.stringify({ token: { access_token: "a", refresh_token: "r" } }));
const probe = createAntigravityUsageProbe({
dataDir,
resolveRuntime: async () => ({ executablePath: "/custom/agy", source: "override", version: null }),
runCommand: async () => ({
exitCode: 1,
stdout: "",
stderr: 'Error: unexpected argument "usage".',
timedOut: false,
}),
});
expect(await probe(account({ cli: "/custom/agy" }))).toEqual({
kind: "other",
error: ANTIGRAVITY_USAGE_UPDATE_MESSAGE,
});
});

it("clears any stale usage-home token copy and asks to sign in when the profile has no token", async () => {
const dataDir = makeTempDir("dusk-agy-missing-");
const profileDir = antigravityProfileDirectory("antigravity", dataDir);
const staleUsageToken = antigravityUsageTokenPath(profileDir);
mkdirSync(dirname(staleUsageToken), { recursive: true });
writeFileSync(staleUsageToken, "stale-token", "utf8");

const runCommand = vi.fn<AntigravityUsageCommandRunner>();
const probe = createAntigravityUsageProbe({
dataDir,
resolveRuntime: async () => ({ executablePath: "agy", source: "managed", version: "1.5.22" }),
runCommand,
});
expect(await probe(account())).toEqual({ kind: "auth", error: "Sign in again in Antigravity" });
expect(existsSync(staleUsageToken)).toBe(false);
expect(runCommand).not.toHaveBeenCalled();
});

it("classifies auth, rate-limit, setup, and timeout failures cleanly", async () => {
const dataDir = makeTempDir("dusk-agy-err-");
seedProfileToken(dataDir, "antigravity", JSON.stringify({ token: { access_token: "a", refresh_token: "r" } }));

const setupProbe = createAntigravityUsageProbe({
dataDir,
resolveRuntime: async () => { throw new AntigravitySetupError("Antigravity is not installed."); },
});
expect(await setupProbe(account())).toEqual({ kind: "other", error: "Antigravity is not installed." });

const authProbe = createAntigravityUsageProbe({
dataDir,
resolveRuntime: async () => ({ executablePath: "agy", source: "managed", version: "1.5.22" }),
runCommand: async () => ({ exitCode: 1, stdout: "", stderr: "Please sign in first.", timedOut: false }),
});
expect(await authProbe(account())).toEqual({ kind: "auth", error: "Sign in again in Antigravity" });

const rateProbe = createAntigravityUsageProbe({
dataDir,
resolveRuntime: async () => ({ executablePath: "agy", source: "managed", version: "1.5.22" }),
runCommand: async () => ({ exitCode: 1, stdout: "", stderr: "HTTP 429 Too Many Requests", timedOut: false }),
});
expect(await rateProbe(account())).toEqual({
kind: "rate_limit",
error: "Antigravity is temporarily limiting usage checks. Trying again soon.",
});

const binDir = makeTempDir("dusk-agy-timeout-");
const slowCli = writeFakeCli(binDir, "setTimeout(() => {}, 10_000);\n");
const timeoutProbe = createAntigravityUsageProbe({
dataDir,
resolveRuntime: async () => ({ executablePath: slowCli, source: "managed", version: "1.5.22" }),
});
expect(await timeoutProbe(account(), { timeoutMs: 150 })).toEqual({
kind: "transient",
error: "Could not reach Antigravity",
});
});

it("sets isolated HOME, USERPROFILE, and Windows TEMP without leaking case-variant keys", () => {
const usageHome = antigravityUsageHome("/tmp/profile");
const env = antigravityUsageEnvironment(
{
PATH: "/usr/bin",
home: "/old/home",
UserProfile: "C:\\old\\home",
Temp: "C:\\old\\temp",
GEMINI_API_KEY: "bad",
},
usageHome,
{ platform: "win32", tempDirectory: "C:\\dusk\\tmp\\agy\\abc" },
);
expect(env.HOME).toBe(usageHome);
expect(env.USERPROFILE).toBe(usageHome);
expect(env.home).toBeUndefined();
expect(env.UserProfile).toBeUndefined();
expect(env.TEMP).toBe("C:\\dusk\\tmp\\agy\\abc");
expect(env.TMP).toBe("C:\\dusk\\tmp\\agy\\abc");
expect(env.Temp).toBeUndefined();
expect(env.GEMINI_API_KEY).toBeUndefined();
expect(env.AGY_CLI_FORCE_FILE_TOKEN_STORAGE).toBe("1");
expect(env.AGY_CLI_DISABLE_AUTO_UPDATE).toBe("1");
});
});
Loading
Loading