mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-27 11:40:00 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The native Runner executes Google Antigravity on local hosts, Core managed sandboxes, and plugin Runner-task environments such as Paperclip Computer. > - Before this change, Paperclip refused Google sign-in on all remote targets even after release, returned an unavailable error when testing Antigravity on plugin Runner-task environments, and did not wire remote refresh-token write-back on Core sandboxes or released Antigravity profile resolution. > - Paperclip Cloud needs Google Antigravity to run with both Gemini API keys and Google sign-in on both plugin Runner-task environments and Core managed sandboxes once the profile flips from pending to qualified. > - This pull request lifts the released-state remote sign-in refusal, wires plugin Runner-task probing and released profile resolution for Antigravity, adds Core sandbox remote sign-in write-back and checkpoint exclusion, and keeps pending-release candidate grants restricted to API-key non-plugin targets. > - The benefit is that flipping the Antigravity profile from pending to qualified immediately enables picker selection, agent creation/save, Test probing, and execution with either Gemini API keys or Google sign-in on both plugin Runner-task environments and Core sandboxes. ## Linked Issues or Issue Description - Refs #22923 (Item 6 of `doc/plans/2026-11-25-antigravity-cloud-rollout.md`, gaps G6 and G7) - Pairs with #22933 (Item 2: Antigravity sign-in task credential and plugin write-back) and #22935 (Item 3: keep per-turn-only harnesses per-turn on warm environments) - Refs #22930 (Item 1: Gemini API key task credential for plugin Runners) ## What Changed - **Remote Google sign-in policy & credential preparation (`antigravity-connection-policy.ts`, `antigravity-runner-credentials.ts`)**: - Allow both Gemini API key and Google sign-in on remote targets in `antigravityConnectionRefusal` once `releasePending` is `false`, while keeping `lifecycleMode: "warm"` refused and keeping pending-release candidate grants API-key-only on non-plugin remote targets. - Strip all `GOOGLE_*` and non-selected `GEMINI_*` variables (plus `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`) in `prepareAntigravityRunnerCredentials`, enforce `antigravityConnectionRefusal` using `antigravityReleasePending()`, and pass pure sanitized sign-in JSON on remote runs (without local `/swarm` metadata). - **Core sandbox remote sign-in write-back & checkpoint safety (`native-credential-store.ts`, `native-session-executor.ts`, `antigravity-runner-credentials.ts`)**: - Extend `createNativeCredentialStore` to support `provider: "antigravity"` (`acp_token.json` and `auth-refresh.json`) over local and remote command runners. - Add optional `runtimeStore` support to `antigravityCredentialTurn` and wire it in `native-session-executor.ts` for Core remote sandboxes so rotated Google refresh tokens copy back after process retirement and remote credential files are scrubbed. - Exclude `antigravity-home/antigravity-acp/{acp_token.json,auth-refresh.json,auth-refresh.json.tmp,logs}` from remote ACPX session checkpoints. - Enforce `antigravityConnectionRefusal` in `preparePluginTaskOwner` and reject pending `pluginTask` execution in `assertAntigravityExecutionAdmissible` (defense in depth). - **Plugin Runner-task probing, released profile resolution & agent save/setup (`provider-profile.ts`, `plugin-runner-probe.ts`, `antigravity-connection-probe.ts`, `agent-environment-test.ts`, `agents.ts`, `NewAgentSetup.tsx`)**: - Add `antigravity` to `DEFAULT_ACPX_RUNNER_MODELS` and the qualified ACPX agent allowlist in `provider-profile.ts`, requiring an explicit non-placeholder model ID and checking `antigravityReleasePending()`. - Wire `testAntigravityConnection` to delegate plugin Runner-task targets to `probePluginRunnerEnvironment` instead of returning `"Google Antigravity is unavailable in this hosting environment."`, and update `probePluginRunnerEnvironment` to run `admissionOnly: true` for Antigravity with either Gemini API key or Google sign-in once released, returning `antigravity_metadata_verified`. - Allow Core sandbox/SSH `probeAntigravityExecutionTarget` for Google sign-in once released, preserve `antigravity_remote_runtime_ready` warn status in `agent-environment-test.ts` and `NewAgentSetup.tsx`. - Allow released Antigravity creation without `enableNativeRunner`, allow released remote sign-in account model discovery on the tenant host, and refuse pending plugin targets even when a `linux-x64` candidate grant exists. - Note on existing >1,000-line files: edits to `server/src/routes/agents.ts` and `server/src/services/native-runtime/native-session-executor.ts` are minimal wiring at existing Antigravity call sites (+12 and +26 net lines). - **Tests**: - Updated `antigravity-runner-credentials.test.ts`, `native-credential-store.test.ts`, `antigravity-save-refusal.test.ts`, `antigravity-connection-probe.test.ts`, `antigravity-release.test.ts`, `adapter-routes.test.ts`, `agent-runner-selection.test.ts`, `agent-environment-test-status.test.ts`, `native-session-executor.test.ts`, and `ui/src/lib/cloud-harness-policy.test.ts`. - Added `server/src/services/native-runtime/plugin-runner-probe-antigravity.test.ts`. ## Verification - Local Vitest (all passed against a released-profile fixture as well as the real pending profile): - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/antigravity-runner-credentials.test.ts src/services/native-runtime/native-credential-store.test.ts src/services/native-runtime/antigravity-release.test.ts src/services/native-runtime/plugin-runner-probe-antigravity.test.ts src/services/native-runtime/plugin-runner-probe-runner-mismatch.test.ts src/services/native-runtime/plugin-runner-credentials.test.ts src/__tests__/antigravity-connection-probe.test.ts src/__tests__/antigravity-save-refusal.test.ts src/__tests__/antigravity-managed-subscription.test.ts src/__tests__/antigravity-plugin-task-credential-writeback.test.ts src/services/agent-runner-selection.test.ts src/services/agent-environment-test-status.test.ts` (12 files, 425 tests passed) - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/adapter-routes.test.ts --hookTimeout=60000` (36 passed) - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/agent-test-environment-routes.test.ts --hookTimeout=60000 -t "passes the selected Antigravity"` (1 passed) - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts -t "projects the selected Antigravity subscription"` (2 passed) - `pnpm --filter @paperclipai/ui exec vitest run src/lib/cloud-harness-policy.test.ts` (36 passed) - Typechecks: - `pnpm --filter @paperclipai/server exec tsc --noEmit` (passed) - `pnpm --filter @paperclipai/ui typecheck` (passed) - Not run live: the real Antigravity profile remains `pending` until Item 8; live staging verification on Paperclip Computer and Core managed sandboxes is covered by Item 12. ## Risks - Low risk while the Antigravity profile remains `pending`: all new remote sign-in and plugin Runner-task paths stay gated behind `!antigravityReleasePending()`, and pending-release candidate behavior remains unchanged (and tighter on plugin environments). - Once Item 8 flips the profile to qualified, released Antigravity agents on Core sandboxes and plugin Runner-task environments will use the paths tested here; live acceptance on staging is gated by Items 9–12. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Google Gemini (Antigravity agent with tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
458 lines
34 KiB
TypeScript
458 lines
34 KiB
TypeScript
import { access, chmod, link, mkdir, mkdtemp, readFile, readdir, realpath, rm, stat, symlink, writeFile } from "node:fs/promises";
|
|
import { constants } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { antigravityAccountDigest, antigravityCredentialTurn, antigravitySwarmChannel, bindAntigravityCredentialTurn, bindAntigravityTransportRetirement, prepareAntigravityRunnerCredentials } from "./antigravity-runner-credentials.js";
|
|
import { sanitizeAntigravityCredential } from "../../vendor/paperclip-runner/index.js";
|
|
import { completeManagedNativeCredentialTurn } from "./managed-native-credentials.js";
|
|
import type { NativeSession, createRunnerdCodexTransport } from "../../vendor/paperclip-runner/index.js";
|
|
import { bindRetainedGoogleCredentialHome } from "../retained-google-credential-cleanup.js";
|
|
import { AntigravityConnectionConfigurationError, antigravityConnectionRefusal } from "./antigravity-connection-policy.js";
|
|
import { NATIVE_PROVIDER_STARTUP_REJECTED, nativeSessionFailureDisposition, nativeSessionFailureSourceCode } from "./native-session-executor.js";
|
|
|
|
const copyFault = vi.hoisted(() => ({ phase: "", destination: "", source: "", collisionPath: "", failedRemoval: "", removals: [] as string[], hits: 0 }));
|
|
const release = vi.hoisted(() => ({ pending: true }));
|
|
vi.mock("./antigravity-release.js", async importOriginal => ({
|
|
...await importOriginal<typeof import("./antigravity-release.js")>(),
|
|
antigravityReleasePending: () => release.pending,
|
|
}));
|
|
vi.mock("./runner-api-files.js", async importOriginal => {
|
|
const actual = await importOriginal<typeof import("./runner-api-files.js")>();
|
|
return { ...actual, openRunnerWorkspaceFile: async (...args: Parameters<typeof actual.openRunnerWorkspaceFile>) => {
|
|
const path = args[0];
|
|
if (copyFault.phase === "stage-create" && copyFault.hits === 0 && path.includes("/.acp_token.copyback-") && (args[1] & constants.O_EXCL)) {
|
|
copyFault.hits++; copyFault.collisionPath = path;
|
|
await writeFile(path, "fixture-unowned-stage", { mode: 0o600, flag: "wx" });
|
|
}
|
|
const handle = await actual.openRunnerWorkspaceFile(...args);
|
|
const staged = path.includes("/.acp_token.copyback-");
|
|
const writable = staged || path === copyFault.destination;
|
|
return new Proxy(handle, { get(target, key) {
|
|
const value = Reflect.get(target, key, target);
|
|
if (typeof value !== "function") return value;
|
|
return async (...callArgs: unknown[]) => {
|
|
if (writable && copyFault.hits === 0 && copyFault.phase === "partial-write" && key === "write") {
|
|
copyFault.hits++;
|
|
await Reflect.apply(value, target, [callArgs[0], callArgs[1], Math.floor(Number(callArgs[2]) / 2), callArgs[3]]);
|
|
throw new Error("fixture partial-write");
|
|
}
|
|
if (staged && copyFault.hits === 0 && copyFault.phase === "stage-stat" && key === "stat") {
|
|
copyFault.hits++; throw new Error("fixture stage-stat");
|
|
}
|
|
if (writable && copyFault.hits === 0 && copyFault.phase === "stage-sync" && key === "sync") {
|
|
copyFault.hits++; throw new Error("fixture stage-sync");
|
|
}
|
|
if (writable && copyFault.hits === 0 && copyFault.phase === "stage-close" && key === "close") {
|
|
copyFault.hits++; await Reflect.apply(value, target, callArgs); throw new Error("fixture stage-close");
|
|
}
|
|
if (path === copyFault.destination.slice(0, copyFault.destination.lastIndexOf("/"))
|
|
&& copyFault.hits === 0 && copyFault.phase === "directory-sync" && key === "sync") {
|
|
copyFault.hits++; throw new Error("fixture directory-sync");
|
|
}
|
|
if (path === copyFault.destination && copyFault.hits === 0 && copyFault.phase === "confirmation-change" && key === "sync") {
|
|
copyFault.hits++; await writeFile(copyFault.destination, credential("fixture-concurrent"), { mode: 0o600 });
|
|
}
|
|
if (staged && copyFault.hits === 0 && copyFault.phase === "generation-change" && key === "sync") {
|
|
copyFault.hits++; await writeFile(copyFault.destination, credential("fixture-concurrent"), { mode: 0o600 });
|
|
}
|
|
return Reflect.apply(value, target, callArgs);
|
|
};
|
|
} });
|
|
} };
|
|
});
|
|
vi.mock("node:fs/promises", async importOriginal => {
|
|
const actual = await importOriginal<typeof import("node:fs/promises")>();
|
|
return { ...actual, rename: async (...args: Parameters<typeof actual.rename>) => {
|
|
if (String(args[1]) === copyFault.destination && copyFault.hits === 0 && copyFault.phase.startsWith("rename-")) {
|
|
copyFault.hits++;
|
|
if (copyFault.phase === "rename-after") await actual.rename(...args);
|
|
throw new Error("fixture " + copyFault.phase);
|
|
}
|
|
return actual.rename(...args);
|
|
}, rm: async (...args: Parameters<typeof actual.rm>) => {
|
|
const path = String(args[0]);
|
|
if (path.includes("/.acp_token.copyback-")) copyFault.removals.push(path);
|
|
if (copyFault.hits === 0 && ((copyFault.phase === "stage-remove" && path.includes("/.acp_token.copyback-"))
|
|
|| (copyFault.phase === "runtime-remove" && path === copyFault.source))) {
|
|
copyFault.hits++; copyFault.failedRemoval = path;
|
|
throw new Error("fixture " + copyFault.phase);
|
|
}
|
|
return actual.rm(...args);
|
|
} };
|
|
});
|
|
|
|
const roots: string[] = [];
|
|
const credential = (token: string) => JSON.stringify({
|
|
client_id: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com", client_secret: "fixture-client-secret",
|
|
refresh_token: token, token_uri: "https://oauth2.googleapis.com/token", scopes: ["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/aicode"],
|
|
});
|
|
async function home() { const root = await realpath(await mkdtemp(join(tmpdir(), "antigravity-controller-test-"))); roots.push(root); await mkdir(join(root, "antigravity-acp"), { mode: 0o700 }); return root; }
|
|
beforeEach(async () => { release.pending = true; vi.stubEnv("PAPERCLIP_HOME", await home()); });
|
|
afterEach(async () => { copyFault.phase = ""; copyFault.destination = ""; copyFault.source = ""; copyFault.collisionPath = ""; copyFault.failedRemoval = ""; copyFault.removals = []; copyFault.hits = 0; vi.unstubAllEnvs(); await Promise.all(roots.splice(0).map(path => rm(path, { recursive: true, force: true }))); });
|
|
|
|
describe("Antigravity managed Runner credentials", () => {
|
|
it("requires a selected managed account and never borrows the ambient Google home or inline secret", async () => {
|
|
const ambient = await home();
|
|
await writeFile(join(ambient, "antigravity-acp", "acp_token.json"), credential("fixture-ambient"), { mode: 0o600 });
|
|
vi.stubEnv("GEMINI_HOME", ambient);
|
|
vi.stubEnv("GEMINI_API_KEY", "fixture-ambient-key");
|
|
await expect(prepareAntigravityRunnerCredentials({ remote: false, environment: { GEMINI_HOME: ambient, PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: credential("fixture-spoofed") } })).rejects.toThrow("selected managed Google account");
|
|
});
|
|
it("uses the explicit API key while removing all subscription home and payload inputs", async () => {
|
|
expect(await prepareAntigravityRunnerCredentials({ remote: true, environment: {
|
|
GEMINI_API_KEY: "fixture-selected", GEMINI_MODEL: "ambient-model", GOOGLE_API_KEY: "other", GOOGLE_GEMINI_BASE_URL: "https://ambient.invalid",
|
|
GEMINI_HOME: "/ambient", GOOGLE_APPLICATION_CREDENTIALS: "/ambient.json",
|
|
GOOGLE_CLOUD_ACCESS_TOKEN: "ambient", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "spoofed",
|
|
} })).toEqual({ home: null, environment: { GEMINI_API_KEY: "fixture-selected" } });
|
|
});
|
|
it("binds the deployment's swarm channel and only a digest of the connection account to the credential", async () => {
|
|
const managedHome = await home();
|
|
await writeFile(join(managedHome, "antigravity-acp", "acp_token.json"), credential("fixture-selected"), { mode: 0o600 });
|
|
const previous = process.env.PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL;
|
|
process.env.PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL = "stable";
|
|
try {
|
|
const { environment } = await prepareAntigravityRunnerCredentials({ remote: false, managedHome, environment: {}, accountEmail: "Owner@Example.test" });
|
|
const secret = environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET!;
|
|
expect(JSON.parse(secret).paperclip).toEqual({ swarmChannel: "stable", accountSha256: antigravityAccountDigest("owner@example.test") });
|
|
expect(secret).not.toMatch(/example\.test/i);
|
|
// Pinned: the Runner's antigravityAccountDigest pins the same value for the CLI's sign-in.
|
|
expect(antigravityAccountDigest("OWNER@example.test")).toBe("0fde1d32467703827f511884b66298187e2944f4bfe260303f893a0af908f81e");
|
|
} finally {
|
|
if (previous === undefined) delete process.env.PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL; else process.env.PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL = previous;
|
|
}
|
|
expect(antigravitySwarmChannel({})).toBe("provider_default");
|
|
expect(antigravitySwarmChannel({ PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL: "daily" })).toBe("provider_default");
|
|
});
|
|
it("projects only the selected private token, refuses remote sign-in while pending, and accepts remote sign-in once released", async () => {
|
|
const managedHome = await home();
|
|
await writeFile(join(managedHome, "antigravity-acp", "acp_token.json"), credential("fixture-selected"), { mode: 0o600 });
|
|
const projected = await prepareAntigravityRunnerCredentials({ remote: false, managedHome, environment: { GEMINI_HOME: "/untrusted" } });
|
|
expect(projected).toMatchObject({ home: managedHome, credential: credential("fixture-selected") });
|
|
expect(Object.keys(projected.environment)).toEqual(["PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET"]);
|
|
// The selected token, plus the swarm route's run facts, which the Runner's sanitizer drops before any write.
|
|
expect(JSON.parse(projected.environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET!)).toEqual({
|
|
...JSON.parse(credential("fixture-selected")), paperclip: { swarmChannel: "provider_default" } });
|
|
expect(sanitizeAntigravityCredential(projected.environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET!)).toBe(credential("fixture-selected"));
|
|
// While pending, remote sign-in and warm sessions are refused permanently by name.
|
|
for (const [input, code] of [[{ remote: true, environment: {} }, "antigravity_remote_sign_in_unsupported"],
|
|
[{ remote: false, lifecycleMode: "warm" as const, environment: {} }, "antigravity_warm_unsupported"],
|
|
[{ remote: false, lifecycleMode: "warm" as const, environment: { GEMINI_API_KEY: "fixture-selected" } }, "antigravity_warm_unsupported"]] as const) {
|
|
const refusal = await prepareAntigravityRunnerCredentials({ managedHome, ...input }).catch(error => error);
|
|
// Configuration save and Test refuse this first; a run that still
|
|
// reaches it stops permanently by name instead of offering a Retry.
|
|
expect(refusal).toBeInstanceOf(AntigravityConnectionConfigurationError);
|
|
expect(refusal).toMatchObject({ code });
|
|
expect(refusal.message).toMatch(code === "antigravity_warm_unsupported" ? /^Google Antigravity runs one turn at a time\. Turn off warm sessions for this agent\.$/ : /Google API key/);
|
|
const failure = nativeSessionFailureSourceCode(refusal);
|
|
expect(failure).toBe(NATIVE_PROVIDER_STARTUP_REJECTED);
|
|
expect(nativeSessionFailureDisposition(1, new Date(), failure)).toMatchObject({ phase: "terminal_failure", failureCode: NATIVE_PROVIDER_STARTUP_REJECTED });
|
|
}
|
|
// Once released, remote sign-in delivers the pure sanitized credential and strips GOOGLE_*/GEMINI_* overrides; warm stays refused.
|
|
release.pending = false;
|
|
const remoteProjected = await prepareAntigravityRunnerCredentials({
|
|
remote: true,
|
|
managedHome,
|
|
accountEmail: "Owner@Example.test",
|
|
environment: { GEMINI_HOME: "/untrusted", GOOGLE_CLOUD_PROJECT: "untrusted", GEMINI_MODEL: "untrusted", KEEP: "ok" },
|
|
});
|
|
expect(remoteProjected).toEqual({
|
|
home: managedHome,
|
|
credential: credential("fixture-selected"),
|
|
environment: { KEEP: "ok", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: credential("fixture-selected") },
|
|
});
|
|
const remoteWarm = await prepareAntigravityRunnerCredentials({
|
|
remote: true, managedHome, lifecycleMode: "warm", environment: {},
|
|
}).catch(error => error);
|
|
expect(remoteWarm).toBeInstanceOf(AntigravityConnectionConfigurationError);
|
|
expect(remoteWarm).toMatchObject({ code: "antigravity_warm_unsupported" });
|
|
});
|
|
it("names the connection choices each target supports in both release states", () => {
|
|
expect(antigravityConnectionRefusal({ apiKey: true, remote: true, releasePending: false })).toBeNull();
|
|
// Per-turn is one contract for both routes: an API key does not enable warm.
|
|
for (const apiKey of [true, false]) {
|
|
for (const remote of [false, true]) {
|
|
expect(antigravityConnectionRefusal({ apiKey, remote, lifecycleMode: "warm", releasePending: false })?.code).toBe("antigravity_warm_unsupported");
|
|
expect(antigravityConnectionRefusal({ apiKey, remote, lifecycleMode: "per_turn", releasePending: false })).toBeNull();
|
|
}
|
|
}
|
|
expect(antigravityConnectionRefusal({ apiKey: false, remote: false, releasePending: false })).toBeNull();
|
|
// Once released, Google sign-in is accepted on remote targets too.
|
|
expect(antigravityConnectionRefusal({ apiKey: false, remote: true, releasePending: false })).toBeNull();
|
|
expect(antigravityConnectionRefusal({ apiKey: true, remote: true, releasePending: true })?.code).toBe("antigravity_remote_unavailable");
|
|
expect(antigravityConnectionRefusal({ apiKey: false, remote: false, releasePending: true })).toBeNull();
|
|
// While pending, an operator's cloud grant admits an API key in a cloud environment, never Google sign-in.
|
|
expect(antigravityConnectionRefusal({ apiKey: true, remote: true, releasePending: true, remoteCandidateAdmitted: true })).toBeNull();
|
|
expect(antigravityConnectionRefusal({ apiKey: false, remote: true, releasePending: true, remoteCandidateAdmitted: true })?.code)
|
|
.toBe("antigravity_remote_sign_in_unsupported");
|
|
expect(antigravityConnectionRefusal({ apiKey: true, remote: true, releasePending: true, remoteCandidateAdmitted: false })?.code)
|
|
.toBe("antigravity_remote_unavailable");
|
|
expect(antigravityConnectionRefusal({ apiKey: true, remote: true, lifecycleMode: "warm", releasePending: true, remoteCandidateAdmitted: true })?.code)
|
|
.toBe("antigravity_warm_unsupported");
|
|
});
|
|
it("exports rotated refreshes and scrubs remote credentials via a remote runtimeStore after session retirement", async () => {
|
|
const managedHome = await home(), runtimeHome = await home();
|
|
const destination = join(managedHome, "antigravity-acp", "acp_token.json");
|
|
await writeFile(destination, credential("fixture-original"), { mode: 0o600 });
|
|
const order: string[] = [];
|
|
const close = vi.fn(async () => { order.push("close"); });
|
|
const runtimeStore = {
|
|
read: vi.fn(async () => { order.push("read"); return credential("fixture-remote-refreshed"); }),
|
|
remove: vi.fn(async () => { order.push("remove"); }),
|
|
};
|
|
const session = bindAntigravityCredentialTurn({ close } as unknown as NativeSession,
|
|
{ managedHome, runtimeHome, credential: credential("fixture-original"), runtimeStore });
|
|
await completeManagedNativeCredentialTurn(session);
|
|
expect(order).toEqual(["close", "read", "remove"]);
|
|
expect(await readFile(destination, "utf8")).toBe(credential("fixture-remote-refreshed"));
|
|
await session.close({ reason: "completed" });
|
|
expect(close).toHaveBeenCalledOnce();
|
|
expect(runtimeStore.read).toHaveBeenCalledOnce();
|
|
expect(runtimeStore.remove).toHaveBeenCalledOnce();
|
|
});
|
|
it.each(["symlink", "public", "invalid"])("rejects a %s selected token without using a fallback", async kind => {
|
|
const managedHome = await home(), token = join(managedHome, "antigravity-acp", "acp_token.json");
|
|
const other = join(managedHome, "other.json");
|
|
await writeFile(other, credential("fixture-other"), { mode: 0o600 });
|
|
if (kind === "symlink") await symlink(other, token);
|
|
else await writeFile(token, kind === "invalid" ? "{}" : credential("fixture-selected"), { mode: kind === "public" ? 0o644 : 0o600 });
|
|
await expect(prepareAntigravityRunnerCredentials({ remote: false, managedHome, environment: {} })).rejects.toThrow("selected Google Antigravity account is unavailable");
|
|
});
|
|
it.each(["acp_token.json", "auth-refresh.json"])("preserves %s refreshes, then scrubs runtime credentials only after provider close", async source => {
|
|
const managedHome = await home(), runtimeHome = await home();
|
|
const destination = join(managedHome, "antigravity-acp", "acp_token.json"), runtime = join(runtimeHome, "antigravity-acp");
|
|
await writeFile(destination, credential("fixture-original"), { mode: 0o600 });
|
|
for (const name of [source, "auth-refresh.json.tmp"]) await writeFile(join(runtime, name), credential("fixture-refreshed"), { mode: 0o600 });
|
|
const close = vi.fn(async () => { expect(await readFile(join(runtime, source), "utf8")).toBe(credential("fixture-refreshed")); });
|
|
const session = bindAntigravityCredentialTurn({ close } as unknown as NativeSession,
|
|
{ managedHome, runtimeHome, credential: credential("fixture-original") });
|
|
await completeManagedNativeCredentialTurn(session);
|
|
expect(await readFile(destination, "utf8")).toBe(credential("fixture-refreshed"));
|
|
expect((await stat(destination)).mode & 0o777).toBe(0o600);
|
|
expect(close).toHaveBeenCalledOnce();
|
|
await expect(access(join(runtime, source))).rejects.toMatchObject({ code: "ENOENT" });
|
|
await session.close({ reason: "completed" });
|
|
expect(close).toHaveBeenCalledOnce();
|
|
for (const name of ["acp_token.json", "auth-refresh.json", "auth-refresh.json.tmp"]) await expect(access(join(runtime, name))).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
it("keeps a newer invocation destination and fails closed on an invalid runtime token", async () => {
|
|
const managedHome = await home(), runtimeHome = await home();
|
|
const destination = join(managedHome, "antigravity-acp", "acp_token.json"), source = join(runtimeHome, "antigravity-acp", "acp_token.json");
|
|
await writeFile(destination, credential("fixture-concurrent"), { mode: 0o600 });
|
|
await writeFile(source, credential("fixture-refreshed"), { mode: 0o600 });
|
|
const turn = antigravityCredentialTurn({ managedHome, runtimeHome, credential: credential("fixture-original") });
|
|
await expect(turn.copyBack()).rejects.toThrow("destination changed");
|
|
expect(await readFile(destination, "utf8")).toBe(credential("fixture-concurrent"));
|
|
await chmod(source, 0o644);
|
|
await expect(turn.copyBack()).rejects.toThrow("handoff is invalid");
|
|
expect(await readFile(destination, "utf8")).toBe(credential("fixture-concurrent"));
|
|
});
|
|
it("can confirm a completed identical copy after losing its prior completion", async () => {
|
|
const managedHome = await home(), runtimeHome = await home();
|
|
const destination = join(managedHome, "antigravity-acp", "acp_token.json");
|
|
const source = join(runtimeHome, "antigravity-acp", "auth-refresh.json");
|
|
await writeFile(destination, credential("fixture-refreshed"), { mode: 0o600 });
|
|
await writeFile(source, credential("fixture-refreshed"), { mode: 0o600 });
|
|
await antigravityCredentialTurn({ managedHome, runtimeHome, credential: credential("fixture-original") }).copyBack();
|
|
expect(await readFile(destination, "utf8")).toBe(credential("fixture-refreshed"));
|
|
});
|
|
it("retains a rotated refresh after failed copy-back and retries the retired owner before scrubbing", async () => {
|
|
const managedHome = await home(), runtimeHome = await home();
|
|
const destination = join(managedHome, "antigravity-acp", "acp_token.json");
|
|
const source = join(runtimeHome, "antigravity-acp", "auth-refresh.json");
|
|
await writeFile(destination, credential("fixture-original"), { mode: 0o644 });
|
|
await writeFile(source, credential("fixture-refreshed"), { mode: 0o600 });
|
|
const close = vi.fn(async () => {});
|
|
const session = bindAntigravityCredentialTurn({ close } as unknown as NativeSession,
|
|
{ managedHome, runtimeHome, credential: credential("fixture-original") });
|
|
await expect(completeManagedNativeCredentialTurn(session)).rejects.toThrow("destination is invalid");
|
|
expect(await readFile(source, "utf8")).toBe(credential("fixture-refreshed"));
|
|
await chmod(destination, 0o600);
|
|
await session.close({ reason: "retry credential handoff" });
|
|
expect(close).toHaveBeenCalledOnce();
|
|
expect(await readFile(destination, "utf8")).toBe(credential("fixture-refreshed"));
|
|
await expect(access(source)).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
it("settles the retained runtime refresh before reusing its original home", async () => {
|
|
const managedHome = await home(), runtimeHome = await home();
|
|
const release = bindRetainedGoogleCredentialHome(managedHome, { companyId: "company", accountKey: managedHome });
|
|
const destination = join(managedHome, "antigravity-acp", "acp_token.json");
|
|
const source = join(runtimeHome, "antigravity-acp", "auth-refresh.json");
|
|
await writeFile(destination, credential("fixture-original"), { mode: 0o644 });
|
|
await writeFile(source, credential("fixture-refreshed"), { mode: 0o600 });
|
|
const close = vi.fn(async () => {});
|
|
const session = bindAntigravityCredentialTurn({ close } as unknown as NativeSession,
|
|
{ managedHome, runtimeHome, credential: credential("fixture-original") });
|
|
try {
|
|
await expect(completeManagedNativeCredentialTurn(session)).rejects.toThrow("destination is invalid");
|
|
await expect(prepareAntigravityRunnerCredentials({ managedHome, remote: false, environment: {} }))
|
|
.rejects.toMatchObject({ details: { code: "ai_credential_cleanup_pending" } });
|
|
expect(await readFile(source, "utf8")).toBe(credential("fixture-refreshed"));
|
|
await chmod(destination, 0o600);
|
|
expect((await prepareAntigravityRunnerCredentials({ managedHome, remote: false, environment: {} })).credential)
|
|
.toBe(credential("fixture-refreshed"));
|
|
expect(close).toHaveBeenCalledOnce();
|
|
await expect(access(source)).rejects.toMatchObject({ code: "ENOENT" });
|
|
} finally { release(); }
|
|
});
|
|
it.each(["turn completion", "direct close"])("retries original process proof after rejected %s before reusing the original home, without clearing session failure", async origin => {
|
|
const managedHome = await home(), runtimeHome = await home();
|
|
const release = bindRetainedGoogleCredentialHome(managedHome, { companyId: "company-retirement", accountKey: managedHome });
|
|
const destination = join(managedHome, "antigravity-acp", "acp_token.json"), source = join(runtimeHome, "antigravity-acp", "auth-refresh.json");
|
|
await writeFile(destination, credential("fixture-original"), { mode: 0o600 });
|
|
await writeFile(source, credential("fixture-refreshed"), { mode: 0o600 });
|
|
const terminal = Object.assign(new Error("fixture native session durable suspension failed"), { code: "native_session_close_unrecoverable" });
|
|
const close = vi.fn(async () => { throw terminal; });
|
|
let physicallyRetired = false;
|
|
let releaseProof!: () => void;
|
|
const proofGate = new Promise<void>(resolve => { releaseProof = resolve; });
|
|
const proof = vi.fn(async () => {
|
|
if (!physicallyRetired) throw new Error("fixture original process still alive");
|
|
await proofGate;
|
|
});
|
|
const transport = bindAntigravityTransportRetirement({ transport: { close }, retireProbeResources: proof } as unknown as ReturnType<typeof createRunnerdCodexTransport>);
|
|
const session = bindAntigravityCredentialTurn({ close: () => transport.close() } as unknown as NativeSession,
|
|
{ managedHome, runtimeHome, credential: credential("fixture-original") });
|
|
try {
|
|
await expect(origin === "turn completion" ? completeManagedNativeCredentialTurn(session) : session.close({ reason: "direct close" })).rejects.toBe(terminal);
|
|
await expect(prepareAntigravityRunnerCredentials({ managedHome, remote: false, environment: {} }))
|
|
.rejects.toMatchObject({ details: { code: "ai_credential_cleanup_pending" } });
|
|
expect(proof).toHaveBeenCalledOnce();
|
|
expect(await readFile(source, "utf8")).toBe(credential("fixture-refreshed"));
|
|
expect(await readFile(destination, "utf8")).toBe(credential("fixture-original"));
|
|
physicallyRetired = true;
|
|
const first = prepareAntigravityRunnerCredentials({ managedHome, remote: false, environment: {} });
|
|
const second = prepareAntigravityRunnerCredentials({ managedHome, remote: false, environment: {} });
|
|
let admitted = false;
|
|
const preparing = Promise.all([first, second]).then(result => { admitted = true; return result; });
|
|
await vi.waitFor(() => expect(proof).toHaveBeenCalledTimes(2));
|
|
expect(admitted).toBe(false);
|
|
expect(await readFile(source, "utf8")).toBe(credential("fixture-refreshed"));
|
|
releaseProof();
|
|
const next = await preparing;
|
|
expect(next.every(value => value.credential === credential("fixture-refreshed"))).toBe(true);
|
|
expect(proof).toHaveBeenCalledTimes(2);
|
|
expect(close).toHaveBeenCalledOnce();
|
|
await expect(access(source)).rejects.toMatchObject({ code: "ENOENT" });
|
|
await expect(session.close({ reason: "original session remains quarantined" })).rejects.toBe(terminal);
|
|
expect(close).toHaveBeenCalledOnce();
|
|
} finally { releaseProof(); release(); }
|
|
});
|
|
it.each(["partial-write", "stage-stat", "stage-sync", "stage-close", "rename-before", "rename-after", "directory-sync", "stage-remove", "runtime-remove"])(
|
|
"retains an intact token and retries the retired owner after %s", async phase => {
|
|
const managedHome = await home(), runtimeHome = await home();
|
|
const directory = join(managedHome, "antigravity-acp"), destination = join(directory, "acp_token.json");
|
|
const source = join(runtimeHome, "antigravity-acp", "auth-refresh.json");
|
|
const original = credential("fixture-original"), refreshed = credential("fixture-refreshed");
|
|
await writeFile(destination, original, { mode: 0o600 });
|
|
await writeFile(source, refreshed, { mode: 0o600 });
|
|
const close = vi.fn(async () => {});
|
|
const session = bindAntigravityCredentialTurn({ close } as unknown as NativeSession, { managedHome, runtimeHome, credential: original });
|
|
const release = bindRetainedGoogleCredentialHome(managedHome, { companyId: "company-atomic", accountKey: managedHome });
|
|
copyFault.phase = phase; copyFault.destination = destination; copyFault.source = source; copyFault.hits = 0;
|
|
try {
|
|
await expect(completeManagedNativeCredentialTurn(session)).rejects.toThrow("fixture " + phase);
|
|
expect(copyFault.hits).toBe(1);
|
|
expect(await readFile(destination, "utf8")).toBe(["rename-after", "directory-sync", "stage-remove", "runtime-remove"].includes(phase) ? refreshed : original);
|
|
expect(await readFile(source, "utf8")).toBe(refreshed);
|
|
expect((await stat(destination)).mode & 0o777).toBe(0o600);
|
|
expect(await readdir(directory)).toEqual(["acp_token.json"]);
|
|
copyFault.phase = "";
|
|
const next = await prepareAntigravityRunnerCredentials({ managedHome, remote: false, environment: {} });
|
|
expect(next.credential).toBe(refreshed);
|
|
if (phase === "stage-remove") expect(copyFault.removals.filter(path => path === copyFault.failedRemoval)).toHaveLength(2);
|
|
expect(close).toHaveBeenCalledOnce();
|
|
await expect(access(source)).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(await readdir(directory)).toEqual(["acp_token.json"]);
|
|
} finally { copyFault.phase = ""; release(); }
|
|
});
|
|
it.each(["missing", "reset"])("retains staging cleanup when its runtime refresh is unexpectedly %s", async state => {
|
|
const managedHome = await home(), runtimeHome = await home();
|
|
const destination = join(managedHome, "antigravity-acp", "acp_token.json");
|
|
const source = join(runtimeHome, "antigravity-acp", "auth-refresh.json");
|
|
const original = credential("fixture-original"), refreshed = credential("fixture-refreshed");
|
|
await writeFile(destination, original, { mode: 0o600 });
|
|
await writeFile(source, refreshed, { mode: 0o600 });
|
|
const turn = antigravityCredentialTurn({ managedHome, runtimeHome, credential: original });
|
|
copyFault.phase = "stage-remove"; copyFault.destination = destination;
|
|
await expect(turn.copyBack()).rejects.toThrow("fixture stage-remove");
|
|
expect(await readFile(destination, "utf8")).toBe(refreshed);
|
|
copyFault.phase = "";
|
|
if (state === "missing") await rm(source);
|
|
else await writeFile(source, original, { mode: 0o600 });
|
|
await expect(turn.copyBack()).rejects.toThrow("handoff is invalid");
|
|
await writeFile(source, refreshed, { mode: 0o600 });
|
|
await turn.copyBack();
|
|
expect(copyFault.removals.filter(path => path === copyFault.failedRemoval)).toHaveLength(2);
|
|
await turn.remove();
|
|
expect(await readFile(destination, "utf8")).toBe(refreshed);
|
|
await expect(access(source)).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
it("rechecks destination generation after staging without overwriting a concurrent credential", async () => {
|
|
const managedHome = await home(), runtimeHome = await home();
|
|
const directory = join(managedHome, "antigravity-acp"), destination = join(directory, "acp_token.json");
|
|
const source = join(runtimeHome, "antigravity-acp", "auth-refresh.json");
|
|
await writeFile(destination, credential("fixture-original"), { mode: 0o600 });
|
|
await writeFile(source, credential("fixture-refreshed"), { mode: 0o600 });
|
|
copyFault.phase = "generation-change"; copyFault.destination = destination;
|
|
await expect(antigravityCredentialTurn({ managedHome, runtimeHome, credential: credential("fixture-original") }).copyBack()).rejects.toThrow("destination changed");
|
|
expect(copyFault.hits).toBe(1);
|
|
expect(await readFile(destination, "utf8")).toBe(credential("fixture-concurrent"));
|
|
expect(await readFile(source, "utf8")).toBe(credential("fixture-refreshed"));
|
|
expect(await readdir(directory)).toEqual(["acp_token.json"]);
|
|
});
|
|
it("does not remove a staging file that it failed to create exclusively", async () => {
|
|
const managedHome = await home(), runtimeHome = await home();
|
|
const destination = join(managedHome, "antigravity-acp", "acp_token.json");
|
|
const source = join(runtimeHome, "antigravity-acp", "auth-refresh.json");
|
|
await writeFile(destination, credential("fixture-original"), { mode: 0o600 });
|
|
await writeFile(source, credential("fixture-refreshed"), { mode: 0o600 });
|
|
copyFault.phase = "stage-create"; copyFault.destination = destination;
|
|
const turn = antigravityCredentialTurn({ managedHome, runtimeHome, credential: credential("fixture-original") });
|
|
await expect(turn.copyBack()).rejects.toMatchObject({ code: "EEXIST" });
|
|
expect(await readFile(copyFault.collisionPath, "utf8")).toBe("fixture-unowned-stage");
|
|
expect(await readFile(destination, "utf8")).toBe(credential("fixture-original"));
|
|
expect(await readFile(source, "utf8")).toBe(credential("fixture-refreshed"));
|
|
copyFault.phase = "";
|
|
await turn.copyBack();
|
|
expect(await readFile(destination, "utf8")).toBe(credential("fixture-refreshed"));
|
|
expect(await readFile(copyFault.collisionPath, "utf8")).toBe("fixture-unowned-stage");
|
|
});
|
|
it("does not confirm a different generation after an uncertain successful rename", async () => {
|
|
const managedHome = await home(), runtimeHome = await home();
|
|
const destination = join(managedHome, "antigravity-acp", "acp_token.json");
|
|
const source = join(runtimeHome, "antigravity-acp", "auth-refresh.json");
|
|
await writeFile(destination, credential("fixture-refreshed"), { mode: 0o600 });
|
|
await writeFile(source, credential("fixture-refreshed"), { mode: 0o600 });
|
|
copyFault.phase = "confirmation-change"; copyFault.destination = destination;
|
|
await expect(antigravityCredentialTurn({ managedHome, runtimeHome, credential: credential("fixture-original") }).copyBack()).rejects.toThrow("destination changed");
|
|
expect(copyFault.hits).toBe(1);
|
|
expect(await readFile(destination, "utf8")).toBe(credential("fixture-concurrent"));
|
|
expect(await readFile(source, "utf8")).toBe(credential("fixture-refreshed"));
|
|
});
|
|
it("rejects a hard-linked destination without changing either name", async () => {
|
|
const managedHome = await home(), runtimeHome = await home();
|
|
const destination = join(managedHome, "antigravity-acp", "acp_token.json"), other = join(managedHome, "other.json");
|
|
await writeFile(other, credential("fixture-original"), { mode: 0o600 });
|
|
await link(other, destination);
|
|
await writeFile(join(runtimeHome, "antigravity-acp", "auth-refresh.json"), credential("fixture-refreshed"), { mode: 0o600 });
|
|
await expect(antigravityCredentialTurn({ managedHome, runtimeHome, credential: credential("fixture-original") }).copyBack()).rejects.toThrow("destination is invalid");
|
|
expect(await readFile(other, "utf8")).toBe(credential("fixture-original"));
|
|
expect(await readFile(destination, "utf8")).toBe(credential("fixture-original"));
|
|
});
|
|
it("does not copy or scrub a successor's credentials after the controller detached", async () => {
|
|
const managedHome = await home(), runtimeHome = await home();
|
|
const destination = join(managedHome, "antigravity-acp", "acp_token.json"), source = join(runtimeHome, "antigravity-acp", "acp_token.json");
|
|
await writeFile(destination, credential("fixture-original"), { mode: 0o600 });
|
|
await writeFile(source, credential("fixture-refreshed"), { mode: 0o600 });
|
|
const close = vi.fn(async () => {}), detach = vi.fn(async () => {});
|
|
const session = bindAntigravityCredentialTurn({ close, detachControllerForRestart: detach } as unknown as NativeSession,
|
|
{ managedHome, runtimeHome, credential: credential("fixture-original") });
|
|
await session.detachControllerForRestart!();
|
|
await session.close({ reason: "old controller" });
|
|
expect(close).not.toHaveBeenCalled();
|
|
expect(await readFile(destination, "utf8")).toBe(credential("fixture-original"));
|
|
expect(await readFile(source, "utf8")).toBe(credential("fixture-refreshed"));
|
|
});
|
|
});
|