Files
PaperClipAI/server/src/services/agent-environment-test-status.test.ts
T
DottaandPaperclip e04efb9734 feat(antigravity): allow plugin Runner-task and remote Google sign-in targets once released (#22940)
## 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>
2026-11-25 08:36:37 -06:00

186 lines
15 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import * as executionTargets from "@paperclipai/adapter-utils/execution-target";
import type { AdapterEnvironmentTestContext } from "@paperclipai/adapter-utils";
import type { AdapterEnvironmentTestResult } from "@paperclipai/shared";
import type { Db } from "@paperclipai/db";
import { environmentTaskErrorCodeData, JsonRpcCallError, PluginEnvironmentTaskError } from "@paperclipai/plugin-sdk";
const { runtimeProbe, claudeProbe, verifyKey, markAuthFailed } = vi.hoisted(() => ({
runtimeProbe: vi.fn(), claudeProbe: vi.fn(), verifyKey: vi.fn(), markAuthFailed: vi.fn(),
}));
vi.mock("../adapters/index.js", () => ({ requireServerAdapter: (type: string) => ({ testEnvironment: type === "paperclip_runner" ? runtimeProbe : claudeProbe }) }));
vi.mock("./ai-api-key-test.js", () => ({ validateAiApiKey: verifyKey }));
vi.mock("./ai-connections.js", async original => ({ ...await original<typeof import("./ai-connections.js")>(), aiConnectionService: () => ({ markAuthenticationFailed: markAuthFailed }) }));
import { agentEnvironmentTestService } from "./agent-environment-test.js";
import { assertHarnessTestPassed } from "./agent-harness-verification.js";
const checkedAt = new Date(0).toISOString();
function readiness(): AdapterEnvironmentTestResult {
return { adapterType: "paperclip_runner", status: "warn", testedAt: checkedAt, checks: [{
code: "acpx_remote_runtime_unverified", level: "warn", message: "The remote platform is supported. Runtime package integrity and readiness must still be verified by the remote runner before launch.",
}] };
}
const context: AdapterEnvironmentTestContext = { companyId: "company-1", adapterType: "paperclip_runner", environmentName: "Paperclip Sandbox",
config: { provider: "acpx", acpxAgent: "claude", model: "claude-opus-5-5", env: { CLAUDE_CODE_OAUTH_TOKEN: "fixture-token" }, managedAiConnection: { method: "subscription" } },
executionTarget: { kind: "remote" as const, transport: "sandbox" as const, providerKey: "daytona", leaseId: "lease-1", remoteCwd: "/workspace", runner: { execute: vi.fn().mockResolvedValue({ exitCode: 0, timedOut: false, stdout: "", stderr: "", signal: null }) } },
};
async function testConnection(overrides: Partial<AdapterEnvironmentTestContext> = {}) {
const service = agentEnvironmentTestService({} as Db);
return service.testManagedEnvironment("paperclip_runner", { ...context, ...overrides },
{ provider: "anthropic", method: "subscription", mode: "responsible_user" },
{ identity: "fixture-identity", attribution: { provider: "anthropic", connectionId: "connection-1", grantId: "grant-1" } } as Parameters<typeof service.testManagedEnvironment>[3]);
}
afterEach(() => { vi.unstubAllEnvs(); vi.clearAllMocks(); vi.restoreAllMocks(); });
function verifiedClaude() {
runtimeProbe.mockResolvedValue(readiness());
claudeProbe.mockResolvedValue({ adapterType: "claude_local", status: "pass", testedAt: checkedAt,
checks: [{ code: "claude_hello_probe_passed", level: "info", message: "Claude hello probe succeeded." }] });
}
describe("managed Runner connection test status", () => {
it("projects the selected Google home for background verification and rejects a conflicting explicit home", async () => {
const service = agentEnvironmentTestService({} as Db);
const input = { companyId: "company-1", adapterType: "paperclip_runner", executionTarget: null,
config: { provider: "acpx", acpxAgent: "antigravity", model: "exact-google-model", env: {}, managedAiConnection: { method: "subscription" } } };
const binding = { provider: "google", method: "subscription", mode: "responsible_user" } as const;
const managed = { home: "/private/selected-google", identity: "fixture-identity",
attribution: { provider: "google", connectionId: "connection-1", grantId: "grant-1" } } as Parameters<typeof service.testManagedEnvironment>[3];
runtimeProbe.mockResolvedValue({ adapterType: "paperclip_runner", status: "pass", testedAt: checkedAt,
checks: [{ code: "antigravity_metadata_verified", level: "info", message: "Native account and model accepted." }] });
expect((await service.testManagedEnvironment("paperclip_runner", input, binding, managed)).status).toBe("pass");
expect(runtimeProbe).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ managedAiCredentialHome: "/private/selected-google/provider" }));
runtimeProbe.mockClear();
await expect(service.testManagedEnvironment("paperclip_runner", { ...input, managedAiCredentialHome: "/private/other-google/provider" }, binding, managed))
.rejects.toThrow("does not match the selected managed account");
expect(runtimeProbe).not.toHaveBeenCalled();
expect(claudeProbe).not.toHaveBeenCalled();
});
it("accepts only the Antigravity native admission receipt without invoking another provider", async () => {
const service = agentEnvironmentTestService({} as Db);
const input = { companyId: "company-1", adapterType: "paperclip_runner", executionTarget: null,
config: { provider: "acpx", acpxAgent: "antigravity", model: "exact-google-model", env: {}, managedAiConnection: { method: "subscription" } } };
const binding = { provider: "google", method: "subscription", mode: "responsible_user" } as const;
const managed = { identity: "fixture-identity", attribution: { provider: "google", connectionId: "connection-1", grantId: "grant-1" } } as Parameters<typeof service.testManagedEnvironment>[3];
runtimeProbe.mockResolvedValue({ adapterType: "paperclip_runner", status: "pass", testedAt: checkedAt,
checks: [{ code: "antigravity_metadata_verified", level: "info", message: "Native account and model accepted." }] });
expect((await service.testManagedEnvironment("paperclip_runner", input, binding, managed)).status).toBe("pass");
expect(claudeProbe).not.toHaveBeenCalled();
expect(verifyKey).not.toHaveBeenCalled();
runtimeProbe.mockResolvedValue({ adapterType: "paperclip_runner", status: "pass", testedAt: checkedAt, checks: [] });
const missing = await service.testManagedEnvironment("paperclip_runner", input, binding, managed);
expect(missing.status).toBe("fail");
expect(missing.checks).toContainEqual(expect.objectContaining({ code: "ai_connection_validation_incomplete" }));
expect(claudeProbe).not.toHaveBeenCalled();
// A Core remote sandbox verifies the image's patched runtime pack without a prompt and returns warn.
runtimeProbe.mockResolvedValue({ adapterType: "paperclip_runner", status: "warn", testedAt: checkedAt,
checks: [{ code: "antigravity_remote_runtime_ready", level: "warn", message: "Verified remote runtime." }] });
const remoteResult = await service.testManagedEnvironment("paperclip_runner", { ...input, executionTarget: context.executionTarget }, binding, managed);
expect(remoteResult.status).toBe("warn");
expect(remoteResult.checks).toContainEqual(expect.objectContaining({ code: "antigravity_remote_runtime_ready" }));
expect(claudeProbe).not.toHaveBeenCalled();
});
it("passes a healthy Cloud Claude connection without asking the user to verify launch-time runtime preparation", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "managed-fixture");
verifiedClaude();
const result = await testConnection();
expect(result.status).toBe("pass");
expect(result.checks).toContainEqual(expect.objectContaining({ code: "claude_hello_probe_passed" }));
expect(result.checks).toContainEqual(expect.objectContaining({ code: "acpx_remote_runtime_managed", level: "info" }));
expect(claudeProbe).toHaveBeenCalledWith(expect.objectContaining({ executionTarget: context.executionTarget, config: expect.objectContaining({ engine: "cli" }) }));
});
it("keeps remote runtime readiness warnings for self-hosted connections", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", ""); vi.stubEnv("PAPERCLIP_MANAGED_CONFIG", undefined);
verifiedClaude();
const result = await testConnection();
expect(result.status).toBe("warn");
expect(result.checks).toContainEqual(expect.objectContaining({ code: "acpx_remote_runtime_unverified", level: "warn" }));
});
it("does not turn a failed hello into a successful Cloud connection", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "managed-fixture"); verifiedClaude();
claudeProbe.mockResolvedValue({ adapterType: "claude_local", status: "fail", testedAt: checkedAt,
checks: [{ code: "claude_hello_probe_auth_required", level: "error", message: "Authentication required" }] });
expect((await testConnection()).status).toBe("fail");
expect(markAuthFailed).toHaveBeenCalledTimes(1);
});
it("does not promote a runtime error before the provider probe", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "managed-fixture"); verifiedClaude();
runtimeProbe.mockResolvedValue({ adapterType: "paperclip_runner", status: "fail", testedAt: checkedAt,
checks: [{ code: "acpx_runtime_package_missing", level: "error", message: "Runtime missing" }] });
expect((await testConnection()).status).toBe("fail");
expect(claudeProbe).not.toHaveBeenCalled();
});
it("does not promote a missing hello receipt", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "managed-fixture"); verifiedClaude();
claudeProbe.mockResolvedValue({ adapterType: "claude_local", status: "pass", testedAt: checkedAt, checks: [] });
const result = await testConnection();
expect(result.status).toBe("fail");
expect(result.checks).toContainEqual(expect.objectContaining({ code: "ai_connection_validation_incomplete" }));
});
it("passes a managed API-key connection only after provider re-verification", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "managed-fixture"); verifiedClaude();
const result = await testConnection({ config: { ...context.config, env: { ANTHROPIC_API_KEY: "fixture-key" }, managedAiConnection: { method: "api_key" } } });
expect(result.status).toBe("pass");
expect(verifyKey).toHaveBeenCalledExactlyOnceWith("anthropic", "fixture-key");
expect(claudeProbe).not.toHaveBeenCalled();
});
it("keeps a rejected API key failed", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "managed-fixture"); verifiedClaude();
verifyKey.mockRejectedValueOnce(new Error("Rejected key"));
expect((await testConnection({ config: { ...context.config, env: { ANTHROPIC_API_KEY: "fixture-key" }, managedAiConnection: { method: "api_key" } } })).status).toBe("fail");
});
it("keeps SSH runtime warnings even on a Cloud instance", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "managed-fixture"); verifiedClaude();
vi.spyOn(executionTargets, "runAdapterExecutionTargetProcess").mockResolvedValue({ exitCode: 0, signal: null, timedOut: false, stdout: "", stderr: "", pid: null, startedAt: null });
const result = await testConnection({ executionTarget: { kind: "remote", transport: "ssh", remoteCwd: "/workspace", spec: { host: "example.test", port: 22, username: "test", remoteCwd: "/workspace", remoteWorkspacePath: "/workspace", privateKey: null, knownHosts: null, strictHostKeyChecking: true } } });
expect(result.status).toBe("warn");
});
it("never promotes an unexplained warning without the exact deferred check", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "managed-fixture"); verifiedClaude();
runtimeProbe.mockResolvedValue({ adapterType: "paperclip_runner", status: "warn", testedAt: checkedAt, checks: [] });
expect((await testConnection()).status).toBe("warn");
});
it("preserves an unexplained provider warning even with a hello receipt", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "managed-fixture"); verifiedClaude();
claudeProbe.mockResolvedValue({ adapterType: "claude_local", status: "warn", testedAt: checkedAt,
checks: [{ code: "claude_hello_probe_passed", level: "info", message: "Hello completed with an unresolved warning." }] });
expect((await testConnection()).status).toBe("warn");
});
it("reports a plugin task that cannot describe its Runner as a retryable failed check", async () => {
verifiedClaude();
const runnerTask = vi.fn().mockRejectedValue(new Error("Plugin-provided Runner execution operation unavailable; reconcile the same task before retrying"));
const result = await testConnection({ executionTarget: { ...context.executionTarget!, runnerTask } as AdapterEnvironmentTestContext["executionTarget"] });
expect(runnerTask).toHaveBeenCalledExactlyOnceWith({ kind: "describe" });
expect(result.status).toBe("fail");
expect(result.checks).toEqual([expect.objectContaining({ code: "runner_environment_unavailable", level: "error", retryable: true })]);
expect(JSON.stringify(result)).not.toContain("reconcile the same task");
expect(() => assertHarnessTestPassed(result)).toThrow(expect.objectContaining({ code: "test_environment_unavailable" }));
expect(runtimeProbe).not.toHaveBeenCalled();
expect(claudeProbe).not.toHaveBeenCalled();
expect(markAuthFailed).not.toHaveBeenCalled();
});
it("still rejects a plugin task that describes no project authentication check", async () => {
verifiedClaude();
const runnerTask = vi.fn().mockResolvedValue({ kind: "description", taskId: "task-1", runner: { version: "1", digest: `sha256:${"0".repeat(64)}` } });
await expect(testConnection({ executionTarget: { ...context.executionTarget!, runnerTask } as AdapterEnvironmentTestContext["executionTarget"] }))
.rejects.toMatchObject({ status: 422, details: { code: "ai_connection_incompatible" } });
expect(runtimeProbe).not.toHaveBeenCalled();
});
it("keeps the stable Runner revision mismatch result when plugin description fails", async () => {
verifiedClaude();
const refusal = new JsonRpcCallError({ code: -32002, message: "The installed Runner does not match the expected revision",
data: environmentTaskErrorCodeData(new PluginEnvironmentTaskError("runner_revision_mismatch")) });
const runnerTask = vi.fn().mockRejectedValue(refusal);
const result = await testConnection({ executionTarget: { ...context.executionTarget!, runnerTask } as AdapterEnvironmentTestContext["executionTarget"] });
expect(result).toMatchObject({ status: "fail", checks: [{ code: "runner_revision_mismatch", level: "error", retryable: true }] });
expect(() => assertHarnessTestPassed(result)).toThrow(expect.objectContaining({ code: "runner_revision_mismatch" }));
expect(runtimeProbe).not.toHaveBeenCalled();
expect(markAuthFailed).not.toHaveBeenCalled();
});
it("keeps actionable warnings after a successful hello", async () => {
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "managed-fixture"); verifiedClaude();
const result = readiness(); result.checks.push({ code: "provider_configuration_warning", level: "warn", message: "Check the selected provider configuration." }); runtimeProbe.mockResolvedValue(result);
expect((await testConnection()).status).toBe("warn");
});
});