mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 10:44:52 +01:00
feat(agents): set up Antigravity with saved Google subscriptions (#18189)
## Thinking Path > - Paperclip manages agents and their work. > - Users choose providers and managed accounts while adding agents. > - Antigravity was missing from the ordinary additional-agent picker and its saved Google path did not complete native readiness. > - A user needs a successful Test, an enabled task action, and a stable account binding. > - This pull request connects the ordinary setup flow to the native candidate. > - It also preserves retired credential refreshes across database failures and server restarts. ## Linked Issues or Issue Description Built on merged #18188 and #18187. Refs: #12503, #14938 for related legacy CLI proposals. **Agent or provider** Google Antigravity ACP 1.4.3. **Why this adapter is useful** Users need to set up an Antigravity agent and run real work through their managed Google subscription. **How the agent is invoked** Native Paperclip Runner uses the pinned Antigravity ACP runtime. Exact operator admission remains required; the local candidate result does not enable general release. ## What Changed - Show Google Antigravity in the ordinary adapter grid and preserve the draft choice when setup resumes. - Reuse the same user’s saved personal default Google subscription and discover the exact low model through the native account. - Run a prompt-free native Test and wait for authoritative readiness before enabling task assignment. - Carry the managed account through native runs and recover retired refreshes through the existing encrypted, fsynced journal with exact generation checks. - Retain the latest rotated credential through verification, storage, and partial home-removal failures. Retry the exact account’s retained cleanup before another provider use. - Reconcile cleanup before taking the credential mutation lock, fence owners arriving during lock acquisition, and support nested lock holders without a join cycle. - Bound sign-in retirement outside database transactions and preserve claims for the existing cleanup owner; one pending sign-in does not block unrelated accounts. - Cover Gemini and Pi API-key recovery, keep API-key bulk manual-model editing usable, and keep adapter discovery available after candidate expiry. - Skip taskless native timer work before run or credential admission. Preserve current master monitor and deadline scheduling. ## Verification - The registered local saved-Google-subscription journey passed all 16 matchers in 196,520 ms using eval source `12aba` against actual serving source `4a37ee7c`. Both turns stayed in one conversation, produced exact downloaded files of 61 and 119 bytes after reload, and used distinct native primary processes. All observed owners retired, leases released, and credential fences settled. Independent readback confirmed Done work, no active owned runs, a connected saved account, and the retained agent paused for inspection. - The measured runtime is production-equivalent to pre-restack `65ef31dc` except its test-only transport fixture correction. Current-master head `ff7c9249` preserves all 99 product paths: 98 exact blobs and only eight inherited plugin-panel lines in `agents.ts`. Its native binary was rebuilt for inherited Codex-only diagnostic changes; the changed Rust behavior is outside Antigravity's ACPX execution path. Shared native/UI changes have focused regression coverage. The recorded live result is not represented as a measured replay of `ff7c9249`. - Full workspace build and typecheck passed on `ff7c9249`. All 376 focused tests in 14 files passed, covering Google credential/retirement controls and the inherited native-tool, redaction, route, and UI recovery changes. Token gates, maps, and diff checks passed. The required-close fixture was separately demonstrated red, then passed all 317 selected provider-wiring cases. - [Current-head CI](https://github.com/paperclipai/paperclip/actions/runs/40959387972) is green: 55 successful checks, two skipped workflow checks, and an optional neutral review check. Required `ci / verify` and `ci / e2e` passed. Greptile and Paperclip Review both report 5/5 on exact `ff7c9249`, with zero unresolved review threads. - This qualifies the selected operator-authorized local saved-subscription candidate. The original exploratory journey remains historical evidence; the repeatable fixed-driver eval is in the next PR. ## Risks - Google refresh recovery must preserve the exact grant, account, and credential generation. An uncertain native owner or failed encrypted handoff retains the private home and blocks cleanup. - A successful local saved-subscription candidate does not qualify fresh OAuth, API keys, Cloud, Linux, other models, or general release. - Timer filtering changes only taskless native Runner admissions. Existing task-bound monitors and legacy adapters retain their owners. ## Model Used OpenAI Codex (GPT-6). The host did not expose the exact model revision or context limit. The model used tools for code edits, tests, and review. ## 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>
This commit is contained in:
1 parent
d7bcf3912f
commit
61bd4ac691
99 files changed
+4697
-366
No files matched your search
@@ -26,7 +26,7 @@ The shared `AI_CONNECTION_CAPABILITIES` contract defines these combinations:
|
||||
| Claude / Anthropic | Claude subscription token or Anthropic API key | Claude |
|
||||
| OpenAI | ChatGPT/Codex subscription or OpenAI API key | Codex |
|
||||
| OpenRouter (legacy, no routing metadata) | API key | OpenCode or Pi, with an `openrouter/` model |
|
||||
| Google | API key | Gemini CLI |
|
||||
| Google | Gemini API key; separate local Antigravity sign-in | Gemini CLI / Pi (API key); Antigravity candidate (pending execution acceptance) |
|
||||
| Grok / xAI | Grok subscription or xAI API key | Grok |
|
||||
|
||||
Native runner supports the corresponding existing Codex, OpenCode, and Claude
|
||||
@@ -425,6 +425,22 @@ allow managed runs to invalidate credentials still used by legacy agents or the
|
||||
operator's terminal. The user completes browser sign-in, then clicks Connect.
|
||||
Grok retains its terminal sign-in flow until it has a local browser login runner.
|
||||
|
||||
Google Antigravity sign-in uses the pinned native ACP runtime installed with
|
||||
`paperclipai runtime setup antigravity`. Its browser redirect returns to a
|
||||
loopback listener; no code is pasted into Paperclip. Setup sends only initialize
|
||||
and authenticate, verifies the Google account email, then saves the credential
|
||||
through the existing encrypted connection grant. It never imports an existing
|
||||
Google CLI, browser, Workspace, or Drive credential. Connection readiness waits
|
||||
for native onboarding and physical login-process retirement. Cancellation and
|
||||
expiry await retirement before removing the private home. After a server restart,
|
||||
start a new Google sign-in attempt.
|
||||
|
||||
Antigravity task execution remains pending acceptance. Its managed subscription
|
||||
path is local and turn-by-turn: native execution retires before refreshed tokens
|
||||
are verified and saved with generation checks. Remote and warm OAuth execution
|
||||
are rejected. Browser sign-in success does not qualify a model turn or the native
|
||||
Runner task lifecycle.
|
||||
|
||||
Attempts reuse `adapter_auth_sessions`, binding company, owner, provider, access
|
||||
intent, reconnect target, and a 30-minute expiry. Validation and completion are
|
||||
serialized; duplicate completion returns the saved connection. Restart retains
|
||||
|
||||
@@ -66,6 +66,30 @@ transitions; no permitted-agent or live-provider journey is claimed here.
|
||||
Companies requiring hire approval keep drafts paused and allocate no agent-owned
|
||||
resource before approval. Selecting an account there is pending verification,
|
||||
not approval or execution authority.
|
||||
The board confirmation follows preparation and verification through the existing
|
||||
foreground detail query before presenting readiness or enabling first-task
|
||||
assignment. The handoff updates only an older cached roster record; it cannot
|
||||
resume an explicit pause, clear an import hold or bypass approval.
|
||||
|
||||
The ordinary picker also exposes pending Google Antigravity configuration when
|
||||
the native Runner adapter is available. This is a board configuration preview: selecting it
|
||||
does not write native execution settings or remove the inactive draft's setup
|
||||
hold. Non-secret draft metadata retains only the selected adapter/provider and
|
||||
runner intent for display and resume; it cannot admit execution. Existing Google connection authorization governs credential setup and
|
||||
account metadata; Test, hire completion and execution still require the normal
|
||||
provider release gates. An isolated operator can authorize one company, exact
|
||||
model and pinned local native candidate until a fixed expiry. Only company-local
|
||||
adapter discovery projects its agent/model as a Candidate; it never returns the
|
||||
launch descriptor or stores that authority on the agent. Server validation and
|
||||
native launch independently enforce the trusted descriptor. The selected managed
|
||||
home feeds a zero-turn native admission Test; uncertain cleanup returns a bounded
|
||||
diagnostic and retains the credential home until physical retirement and refresh
|
||||
handoff, then performs normal writeback. This exception leaves global release
|
||||
qualification pending. UI discoverability grants no additional agent or probe
|
||||
authority. Source: [picker](../../ui/src/components/new-agent/AgentBasicsDialog.tsx)
|
||||
and [setup](../../ui/src/components/new-agent/NewAgentSetup.tsx). This scoped note
|
||||
is source-only and does not claim a permitted-agent journey or live Antigravity
|
||||
task acceptance.
|
||||
|
||||
The creation boundary resolves the request-level runner before adapter validation
|
||||
and credential normalization. Omitted/automatic new Codex selection uses the
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
# Connection setup — agent access
|
||||
|
||||
Google Antigravity runtime sign-in reuses the existing company/owner-bound local
|
||||
AI connection attempts. Agent callers cannot import host credentials, complete
|
||||
another user's attempt, or turn a tool OAuth grant into runtime authentication.
|
||||
Native Google setup is source-tested for early-token rejection and physical
|
||||
retirement before home removal; live Google and database authorization acceptance
|
||||
remain separate. See [AI connections](../../doc/connections/AI-CONNECTIONS.md#local-subscription-sign-in).
|
||||
|
||||
Product map: [connection-setup](../feature-map/connection-setup.md).
|
||||
|
||||
Feature ID: `connection-setup`.
|
||||
|
||||
@@ -196,3 +196,14 @@ Evidence: `source-only` — reviewed at `9ef434fe79c57d976b8b03b14c5242db270b832
|
||||
Verification: `not-run` — Inspect setup identity/path and repeat reuse on an owned disposable published installation. Verify a matching trusted companion import and reject altered/cross-release/linked inventory while preserving unrelated files. Check no instance credentials are loaded and no model is called. Qualify actual adapter/account task execution separately.
|
||||
|
||||
Gaps: Source-checkout setup, different platforms, remote Cursor, provider execution, and published-package acceptance remain separate scopes. Local fixture materialization does not establish remote model readiness.
|
||||
|
||||
Antigravity addition (2026-10-28): `paperclipai runtime setup antigravity` stages
|
||||
the verified official and patched two-executable closures on macOS ARM64. The
|
||||
operator-only authority above is unchanged. The native profile remains pending
|
||||
at API, driver, sidecar and Rust admission; a company grant cannot enable it.
|
||||
Google AI API-key binding is distinct from Workspace OAuth. Evidence remains
|
||||
`source-only` for agent access: [setup](../../cli/src/commands/runtime.ts),
|
||||
[provisioner](../../packages/paperclip-runner/scripts/provision-antigravity.mjs),
|
||||
and [gate regressions](../../packages/paperclip-runner/src/drivers/acpx/antigravity-models.test.ts).
|
||||
Credential-free public-layout provisioning and controlled native tests do not
|
||||
qualify a company agent task or authenticated connection/revocation.
|
||||
@@ -259,6 +259,12 @@ The sandbox uses its injected run credential. See
|
||||
|
||||
Policy: Same company, company-scope read authority and run/task visibility still
|
||||
apply. Task-bound history and recovery records require task read authority.
|
||||
Generic interval scheduling and direct unscoped timer requests cannot create
|
||||
taskless native Runner runs. Task-bound monitors, routines, assignments and
|
||||
timer requests retain existing authorization; Legacy intervals are unchanged.
|
||||
The [queue](../../server/src/services/heartbeat/queue.test.ts) and
|
||||
[scheduler](../../server/src/services/heartbeat/scheduling.test.ts) PostgreSQL
|
||||
regressions use synthetic execution and grant no new agent API or credential authority.
|
||||
Each run-linked task is filtered by the caller's task-read predicate; a readable
|
||||
company run cannot expose inaccessible private task titles. Existing content
|
||||
and credential redaction apply. Adapter installation, raw host login, execution
|
||||
|
||||
@@ -39,6 +39,30 @@ The header shows Finish setup instead of Run or Resume, including during compute
|
||||
preparation and verification. Terminating agents cannot reopen setup. Final
|
||||
submission requests approval when required, then follows the existing preparation
|
||||
and verification lifecycle.
|
||||
The confirmation shows **Finishing agent setup** until the foreground detail
|
||||
query observes actual readiness. **Assign a Task** then hands that current
|
||||
record to the composer, so its status does not come from an older paused draft.
|
||||
Manual/import pauses and required hire approval remain blocking states.
|
||||
|
||||
When the native Runner adapter is available, **Google Antigravity** appears in the ordinary
|
||||
adapter picker. Before runtime acceptance, its card says **Not available yet**.
|
||||
Selecting it opens Google account setup and model configuration without saving
|
||||
an unqualified native execution configuration. The existing inactive draft stays
|
||||
held; Test and Finish remain unavailable, and the page says model and connection settings are not
|
||||
saved. The selected adapter is retained with the draft: **Back to agents**, reload,
|
||||
and **Finish setup** return to the same Google setup. Pending roster rows identify
|
||||
Google Antigravity without implying a configured connection or runnable model.
|
||||
**Change adapter** returns to the picker with the saved choice selected and allows
|
||||
switching that same held draft to another supported adapter.
|
||||
Verify discovery, Google-specific setup, draft preservation and the
|
||||
disabled actions separately from a successful Antigravity hire or task run.
|
||||
|
||||
On an isolated host with a current operator candidate authorization, company-scoped
|
||||
adapter inventory can expose **Candidate** with one exact model. That company can
|
||||
connect, save, reopen, Test and Finish setup while the global release stays pending.
|
||||
Test verifies native account/model admission and cleanup without a model turn.
|
||||
Other companies, remote targets, expired authority and other models stay blocked.
|
||||
Verify this scoped path separately from production qualification and real task acceptance.
|
||||
|
||||
Agent-owned plugin environments prepare the saved draft in the background when
|
||||
their driver declares `requiresAgent`. The draft waits in `verifying` with its
|
||||
|
||||
@@ -9,6 +9,11 @@ setup from either Apps or a task that needs access. A saved draft, a completed
|
||||
provider login, a usable connection, and a resumed task are separate checkpoints.
|
||||
Chat channels additionally require an endpoint and linked sender identity.
|
||||
|
||||
Google runtime setup offers a Gemini API key or a separate local Antigravity
|
||||
browser sign-in. The browser redirect requires no pasted code; setup displays
|
||||
the verified Google email before Connect. Connection setup does not qualify the
|
||||
pending Antigravity execution profile. See [AI connections](../../doc/connections/AI-CONNECTIONS.md#local-subscription-sign-in).
|
||||
|
||||
Feature ID: `connection-setup`.
|
||||
|
||||
Agent access: [companion](../agent-access-map/connection-setup.md).
|
||||
|
||||
@@ -19,7 +19,7 @@ Agent access: [companion](../agent-access-map/instance-operations.md).
|
||||
- `configuration`: `instance-operations/configuration` — configure database, server binding, storage, secrets, and available experimental settings.
|
||||
- `diagnostics`: `instance-operations/diagnostics` — use doctor/health output to distinguish readiness from a listening port.
|
||||
- `backup`: `instance-operations/backup` — create and inspect backups and verify restore only into a separate disposable target.
|
||||
- `runtime-setup`: `instance-operations/runtime-setup` — install verified Pi/Cursor runtime assets or import a release-matched Linux Pi companion into an owned published installation.
|
||||
- `runtime-setup`: `instance-operations/runtime-setup` — install verified Pi/Cursor runtime assets, stage pending Antigravity assets on macOS ARM64, or import a release-matched Linux Pi companion into an owned published installation.
|
||||
|
||||
## How to get to it (user POV)
|
||||
|
||||
@@ -33,7 +33,7 @@ Use currently visible instance settings for experiments/access and `paperclipai
|
||||
|
||||
### `runtime-provisioning`
|
||||
|
||||
On an owned published server installation, use `paperclipai runtime setup pi`, `paperclipai runtime setup cursor`, or `paperclipai runtime import-remote <companion-directory> --sha256 <trusted-companion-json-digest>`. Run as the OS user operating that installation; this is separate from source-checkout dependency installation.
|
||||
On an owned published server installation, use `paperclipai runtime setup pi`, `paperclipai runtime setup cursor`, `paperclipai runtime setup antigravity`, or `paperclipai runtime import-remote <companion-directory> --sha256 <trusted-companion-json-digest>`. Run as the OS user operating that installation; this is separate from source-checkout dependency installation. Antigravity setup stages a pinned patched macOS ARM64 runtime; it remains unavailable for tasks until native acceptance passes.
|
||||
|
||||
## Driving it with Playwright and the Paperclip CLI
|
||||
|
||||
@@ -90,6 +90,13 @@ Manual: Use a disposable published installation and its exact runtime release. R
|
||||
|
||||
Sources: [Runtime CLI](../../cli/src/commands/runtime.ts), [instance-config bypass](../../cli/src/index.ts), [Pi provisioning](../../packages/paperclip-runner/scripts/provision-pi.mjs), [Cursor provisioning](../../packages/paperclip-runner/scripts/provision-cursor.mjs), and [companion importer](../../server/src/services/native-runtime/remote-pi-companion.ts).
|
||||
|
||||
Antigravity: [provisioning](../../packages/paperclip-runner/scripts/provision-antigravity.mjs),
|
||||
[closure/integrity regressions](../../packages/paperclip-runner/scripts/materialize-antigravity-distribution.test.mjs),
|
||||
and [pending admission tests](../../packages/paperclip-runner/src/drivers/acpx/antigravity-models.test.ts).
|
||||
Exercise public-layout setup and verify both native files and cleanup; separately
|
||||
verify that configuration/API/driver/sidecar reject the pending provider. These
|
||||
checks do not establish authenticated task execution.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- Runtime setup operates on a published installation and verifies package assets. It is not a substitute for an account connection, environment qualification, or a useful task run.
|
||||
|
||||
@@ -51,6 +51,14 @@ the existing credential checks. The [launcher controls](../../packages/adapter-u
|
||||
and [real-shell staging controls](../../packages/adapter-utils/src/github-launcher-environment.test.ts)
|
||||
cover this local behavior, separately from live cloud execution and GitHub writes.
|
||||
|
||||
Native Runner agents wait for task-bound work. A generic heartbeat interval does
|
||||
not create a taskless run or put an otherwise ready agent into an error state.
|
||||
Assigned tasks, task monitors, routines and task-bound timer wakes keep their
|
||||
existing admission paths; Legacy adapter intervals remain supported. The
|
||||
[scheduler](../../server/src/services/heartbeat/scheduling.test.ts) and
|
||||
[queue](../../server/src/services/heartbeat/queue.test.ts) regressions exercise
|
||||
this boundary with PostgreSQL and synthetic execution, separately from live task acceptance.
|
||||
|
||||
For latency diagnosis with an operator OTLP endpoint, search the hashed run ID
|
||||
without restricting the root span name. Compare workspace preparation with its
|
||||
`workspace_<step>` intervals. Measure controller readiness separately through
|
||||
|
||||
@@ -36,6 +36,20 @@ function makeValues(overrides: Partial<CreateConfigValues> = {}): CreateConfigVa
|
||||
}
|
||||
|
||||
describe("buildCodexLocalConfig", () => {
|
||||
it("refuses pending Antigravity selection before saving Runner config", () => {
|
||||
expect(() => buildPaperclipRunnerConfig(makeValues({ model: "exact-antigravity-model",
|
||||
adapterSchemaValues: { provider: "acpx", acpxAgent: "antigravity" } })))
|
||||
.toThrow("Google Antigravity is not enabled for production");
|
||||
});
|
||||
it("builds only the exact candidate model from non-persisted UI context", () => {
|
||||
const values = makeValues({ model: "exact-antigravity-model", adapterSchemaValues: { provider: "acpx", acpxAgent: "antigravity" } });
|
||||
const context = { candidateHarnesses: [{ agent: "antigravity" as const, model: "exact-antigravity-model" }] };
|
||||
expect(buildPaperclipRunnerConfig(values, context)).toMatchObject({ provider: "acpx", acpxAgent: "antigravity", model: values.model });
|
||||
expect(buildPaperclipRunnerConfig(values, context)).not.toHaveProperty("candidateHarnesses");
|
||||
expect(() => buildPaperclipRunnerConfig({ ...values, model: "another-model" }, context)).toThrow();
|
||||
expect(() => buildPaperclipRunnerConfig(values)).toThrow();
|
||||
});
|
||||
|
||||
it("preserves explicitly disabled hosted search in native Codex configuration", () => {
|
||||
expect(buildPaperclipRunnerConfig(makeValues({ search: false }))).toHaveProperty("search", false);
|
||||
expect(buildPaperclipRunnerConfig(makeValues({ search: true }))).not.toHaveProperty("search");
|
||||
|
||||
@@ -73,7 +73,9 @@ export function buildCodexLocalConfig(v: CreateConfigValues): Record<string, unk
|
||||
}
|
||||
|
||||
/** Build a provider profile accepted by the experimental Rust runner. */
|
||||
export function buildPaperclipRunnerConfig(v: CreateConfigValues): Record<string, unknown> {
|
||||
export function buildPaperclipRunnerConfig(v: CreateConfigValues, context?: {
|
||||
candidateHarnesses?: readonly { agent: "antigravity"; model: string }[];
|
||||
}): Record<string, unknown> {
|
||||
const config = buildCodexLocalConfig(v);
|
||||
const schemaValues = normalizeLegacyRunnerProvider({ ...(v.adapterSchemaValues ?? {}) });
|
||||
const configuredEffort = typeof v.thinkingEffort === "string"
|
||||
@@ -110,7 +112,10 @@ export function buildPaperclipRunnerConfig(v: CreateConfigValues): Record<string
|
||||
...(typeof schemaValues.dotBindingId === "string" ? { dotBindingId: schemaValues.dotBindingId } : {}) };
|
||||
}
|
||||
const selectedAcpxProfile = PAPERCLIP_RUNNER_ACPX_PROFILES.find(profile => profile.value === schemaValues.acpxAgent);
|
||||
if (provider === "acpx" && selectedAcpxProfile && !selectedAcpxProfile.qualified) {
|
||||
const candidate = context?.candidateHarnesses?.find(candidate => candidate.agent === schemaValues.acpxAgent);
|
||||
const selectedModel = typeof v.model === "string" && v.model ? v.model : schemaValues.model;
|
||||
if (provider === "acpx" && selectedAcpxProfile && !selectedAcpxProfile.qualified
|
||||
&& !(candidate && candidate.model === selectedModel)) {
|
||||
throw new Error(`${selectedAcpxProfile.label} is not enabled for production`);
|
||||
}
|
||||
const acpxAgent = selectedAcpxProfile?.value ?? "claude";
|
||||
|
||||
@@ -42,7 +42,7 @@ export function agentHarnessType(adapterType: string, config: Record<string, unk
|
||||
if (config.provider === "opencode") return "opencode_local";
|
||||
if (config.provider === "acpx") {
|
||||
const agent = config.acpxAgent ?? "claude";
|
||||
return ({ codex: "codex_local", claude: "claude_local", grok: "grok_local", cursor: "cursor", pi: "pi_local" } as Record<string, string>)[String(agent)] ?? `acpx:${String(agent)}`;
|
||||
return ({ codex: "codex_local", claude: "claude_local", grok: "grok_local", cursor: "cursor", pi: "pi_local", antigravity: "antigravity_runtime" } as Record<string, string>)[String(agent)] ?? `acpx:${String(agent)}`;
|
||||
}
|
||||
return String(config.provider);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { agentHarnessType, agentRuntimeSettingsHarness, paperclipRunnerProfileForHarness } from "./agent-runner.js";
|
||||
import { aiConnectionMetadataSchema, isAiConnectionCompatible } from "./ai-connections.js";
|
||||
import { aiRoutingHarness } from "./ai-provider-routing.js";
|
||||
|
||||
describe("Antigravity native runtime identity and credentials", () => {
|
||||
const config = { provider: "acpx", acpxAgent: "antigravity" };
|
||||
const compatible = (connection: Parameters<typeof isAiConnectionCompatible>[0]) =>
|
||||
isAiConnectionCompatible(connection, "paperclip_runner", "exact-model", "acpx", "antigravity");
|
||||
|
||||
it("uses a native harness identity without a legacy adapter transition", () => {
|
||||
expect(agentHarnessType("paperclip_runner", config)).toBe("antigravity_runtime");
|
||||
expect(agentRuntimeSettingsHarness("paperclip_runner", config)).toBe("antigravity_runtime");
|
||||
expect(aiRoutingHarness("paperclip_runner", "acpx", "antigravity")).toBe("antigravity_runtime");
|
||||
expect(paperclipRunnerProfileForHarness("antigravity_runtime")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("accepts Google runtime sign-in and API keys without tool OAuth or custom endpoints", () => {
|
||||
expect(compatible({ provider: "google", method: "api_key" })).toBe(true);
|
||||
expect(compatible({ provider: "google", method: "api_key", mode: "responsible_user" })).toBe(true);
|
||||
expect(compatible({ provider: "google", method: "api_key", mode: "delegated",
|
||||
connectionId: "11111111-1111-4111-8111-111111111111", grantId: "22222222-2222-4222-8222-222222222222" })).toBe(true);
|
||||
expect(compatible({ provider: "google", method: "subscription" })).toBe(true);
|
||||
expect(isAiConnectionCompatible({ provider: "google", method: "subscription" }, "gemini_local")).toBe(false);
|
||||
expect(aiConnectionMetadataSchema.safeParse({ provider: "google", method: "oauth" }).success).toBe(false);
|
||||
for (const provider of ["openai", "anthropic", "openrouter", "github", "xai"] as const) {
|
||||
expect(compatible({ provider, method: "api_key" })).toBe(false);
|
||||
expect(compatible({ provider, method: "api_key", mode: "shared",
|
||||
connectionId: "11111111-1111-4111-8111-111111111111", grantId: "22222222-2222-4222-8222-222222222222" })).toBe(false);
|
||||
}
|
||||
expect(compatible({ provider: "google", method: "api_key", routing: {
|
||||
kind: "openrouter", protocol: "chat", auth: "bearer", models: [],
|
||||
} })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"slug": "google",
|
||||
"name": "Google Gemini",
|
||||
"description": "Connect Google Gemini accounts for your agents.",
|
||||
"name": "Google",
|
||||
"description": "Connect Google Antigravity accounts or Gemini API keys for your agents.",
|
||||
"categories": [
|
||||
"ai"
|
||||
],
|
||||
@@ -13,6 +13,27 @@
|
||||
"https://generativelanguage.googleapis.com/*"
|
||||
],
|
||||
"methods": [
|
||||
{
|
||||
"key": "ai-subscription",
|
||||
"label": "Google Antigravity sign-in",
|
||||
"purpose": "ai",
|
||||
"transport": "runtime_auth",
|
||||
"auth": "oauth",
|
||||
"ai": {
|
||||
"provider": "google",
|
||||
"method": "subscription"
|
||||
},
|
||||
"grantKinds": [
|
||||
"user",
|
||||
"organization"
|
||||
],
|
||||
"ownershipModes": [
|
||||
"customer"
|
||||
],
|
||||
"whenToUse": "Sign in to Google Antigravity on this local execution host.",
|
||||
"guidanceMd": "Uses a separate Google runtime sign-in for this connection. Google Drive and other tool permissions are separate.",
|
||||
"riskTier": "S3"
|
||||
},
|
||||
{
|
||||
"key": "ai-api_key",
|
||||
"label": "Google Gemini API key",
|
||||
|
||||
@@ -21,6 +21,7 @@ const mockPluginLoader = vi.hoisted(() => ({
|
||||
getOrExtractUiParserSource: vi.fn(),
|
||||
reloadExternalAdapter: vi.fn(),
|
||||
}));
|
||||
const mockCandidateAdmission = vi.hoisted(() => vi.fn());
|
||||
|
||||
const overridingConfigSchemaAdapter: ServerAdapterModule = {
|
||||
type: "claude_local",
|
||||
@@ -52,6 +53,10 @@ let adapterRoutes: typeof import("../routes/adapters.js").adapterRoutes;
|
||||
let errorHandler: typeof import("../middleware/index.js").errorHandler;
|
||||
|
||||
function registerModuleMocks() {
|
||||
vi.doMock("../services/native-runtime/acpx-qualification.js", async () => ({
|
||||
...await vi.importActual("../services/native-runtime/acpx-qualification.js"),
|
||||
resolveAntigravityCandidateAdmission: mockCandidateAdmission,
|
||||
}));
|
||||
vi.doMock("node:child_process", async () => vi.importActual("node:child_process"));
|
||||
vi.doMock("../adapters/plugin-loader.js", () => mockPluginLoader);
|
||||
vi.doMock("../services/adapter-plugin-store.js", () => mockAdapterPluginStore);
|
||||
@@ -146,6 +151,55 @@ describe("adapter routes", () => {
|
||||
expect(typeof adapter.capabilities.supportsAcp).toBe("boolean");
|
||||
}
|
||||
});
|
||||
it("projects only the enabled company-local candidate and exact model", async () => {
|
||||
mockCandidateAdmission.mockImplementation(({ companyId }) => companyId === "company-1"
|
||||
? { agent: "antigravity", model: "exact-google-model", profileDigest: "private-profile", nativeClosureDigest: "private-closure" } : undefined);
|
||||
const local = createApp({}, { resolveRunnerTarget: async () => ({ driver: "local" }) });
|
||||
const scoped = await request(local).get("/api/adapters?companyId=company-1");
|
||||
expect(scoped.status).toBe(200);
|
||||
expect(scoped.body.find((adapter: any) => adapter.type === "paperclip_runner").candidateHarnesses)
|
||||
.toEqual([{ agent: "antigravity", model: "exact-google-model" }]);
|
||||
expect(JSON.stringify(scoped.body)).not.toContain("private-profile");
|
||||
expect(JSON.stringify(scoped.body)).not.toContain("private-closure");
|
||||
for (const query of ["", "?companyId=other-company"]) {
|
||||
const response = await request(local).get(`/api/adapters${query}`);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.every((adapter: any) => adapter.candidateHarnesses === undefined)).toBe(true);
|
||||
}
|
||||
const remote = await request(createApp({}, { resolveRunnerTarget: async () => ({ driver: "ssh" }) }))
|
||||
.get("/api/adapters?companyId=company-1&environmentId=remote");
|
||||
expect(remote.body.every((adapter: any) => adapter.candidateHarnesses === undefined)).toBe(true);
|
||||
mockAdapterPluginStore.getDisabledAdapterTypes.mockReturnValue(["paperclip_runner"]);
|
||||
const disabled = await request(local).get("/api/adapters?companyId=company-1");
|
||||
expect(disabled.body.find((adapter: any) => adapter.type === "paperclip_runner").candidateHarnesses).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps ordinary adapter discovery available after candidate startup authority expires", async () => {
|
||||
mockCandidateAdmission.mockImplementation(() => { throw new Error("ACPX candidate startup authorization expired"); });
|
||||
const app = createApp({}, { resolveRunnerTarget: async () => ({ driver: "local" }) });
|
||||
const response = await request(app).get("/api/adapters?companyId=company-1");
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.some((adapter: any) => adapter.type === "claude_local")).toBe(true);
|
||||
expect(response.body.every((adapter: any) => adapter.candidateHarnesses === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it("warns once without startup payloads for malformed candidate authority, while expiry stays quiet", async () => {
|
||||
const { logger } = await import("../middleware/logger.js");
|
||||
const warn = vi.spyOn(logger, "warn").mockImplementation(() => undefined);
|
||||
const app = createApp({}, { resolveRunnerTarget: async () => ({ driver: "local" }) });
|
||||
try {
|
||||
mockCandidateAdmission.mockImplementation(() => { throw new Error("ACPX candidate startup authorization expired"); });
|
||||
expect((await request(app).get("/api/adapters?companyId=company-1")).status).toBe(200);
|
||||
expect(warn).not.toHaveBeenCalled();
|
||||
mockCandidateAdmission.mockImplementation(() => { throw new Error("Invalid Antigravity candidate admission"); });
|
||||
for (let index = 0; index < 2; index++) {
|
||||
const response = await request(app).get("/api/adapters?companyId=company-1");
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.every((adapter: any) => adapter.candidateHarnesses === undefined)).toBe(true);
|
||||
}
|
||||
expect(warn).toHaveBeenCalledExactlyOnceWith({ code: "ANTIGRAVITY_CANDIDATE_ADMISSION_INVALID" }, "Invalid Google Antigravity preview authorization");
|
||||
} finally { warn.mockRestore(); }
|
||||
});
|
||||
|
||||
it("keeps the shared runner implementation available for Codex without the experimental flag", async () => {
|
||||
const disabledResponse = await request(createApp()).get("/api/adapters");
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import express from "express";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import request from "supertest";
|
||||
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { ServerAdapterModule } from "../adapters/index.js";
|
||||
@@ -79,6 +80,8 @@ const mockRemoteAgentProfileService = vi.hoisted(() => ({
|
||||
}));
|
||||
|
||||
const mockLogActivity = vi.hoisted(() => vi.fn());
|
||||
const mockAntigravityModels = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../services/antigravity-connection-models.js", () => ({ antigravityConnectionModels: mockAntigravityModels }));
|
||||
|
||||
vi.mock("../services/index.js", () => ({
|
||||
agentService: () => mockAgentService,
|
||||
@@ -114,6 +117,7 @@ vi.mock("../services/remote-agent-profiles.js", () => ({
|
||||
}));
|
||||
|
||||
function registerModuleMocks() {
|
||||
vi.doMock("../services/antigravity-connection-models.js", () => ({ antigravityConnectionModels: mockAntigravityModels }));
|
||||
vi.doMock("../services/index.js", () => ({
|
||||
agentService: () => mockAgentService,
|
||||
agentInstructionsService: () => mockAgentInstructionsService,
|
||||
@@ -242,6 +246,7 @@ async function unregisterTestAdapter(type: string) {
|
||||
|
||||
describe("agent routes adapter validation", () => {
|
||||
beforeEach(async () => {
|
||||
vi.stubEnv("PAPERCLIP_ACPX_CANDIDATE_ADMISSION", undefined);
|
||||
vi.resetModules();
|
||||
vi.doUnmock("../routes/agents.js");
|
||||
vi.doUnmock("../routes/authz.js");
|
||||
@@ -406,6 +411,7 @@ describe("agent routes adapter validation", () => {
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs();
|
||||
await unregisterTestAdapter("external_test");
|
||||
await unregisterTestAdapter(missingAdapterType);
|
||||
});
|
||||
@@ -447,6 +453,77 @@ describe("agent routes adapter validation", () => {
|
||||
} finally { list.mockRestore(); refresh.mockRestore(); }
|
||||
});
|
||||
|
||||
it("loads setup-only Antigravity account metadata without consulting another harness", async () => {
|
||||
const adapters = await import("../adapters/index.js");
|
||||
const list = vi.spyOn(adapters, "listAdapterModels");
|
||||
const refresh = vi.spyOn(adapters, "refreshAdapterModels");
|
||||
const catalog = [{ id: "caller-exact-google-model", label: "Google account model" }];
|
||||
mockAntigravityModels.mockResolvedValue(catalog);
|
||||
try {
|
||||
const app = await createApp();
|
||||
for (const suffix of ["", "&refresh=true"]) {
|
||||
const response = await requestApp(app, base => request(base).get(`/api/companies/company-1/adapters/paperclip_runner/models?provider=acpx&acpxAgent=antigravity${suffix}`));
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(200);
|
||||
expect(response.body).toEqual(catalog);
|
||||
expect(mockAntigravityModels).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({
|
||||
companyId: "company-1", binding: { provider: "google", method: "subscription", mode: "responsible_user" },
|
||||
}));
|
||||
}
|
||||
expect(list).not.toHaveBeenCalled();
|
||||
expect(refresh).not.toHaveBeenCalled();
|
||||
} finally { list.mockRestore(); refresh.mockRestore(); }
|
||||
});
|
||||
|
||||
it("refuses another provider binding before Antigravity model discovery", async () => {
|
||||
const app = await createApp();
|
||||
const binding = encodeURIComponent(JSON.stringify({ provider: "openai", method: "subscription", mode: "responsible_user" }));
|
||||
const response = await requestApp(app, base => request(base).get(`/api/companies/company-1/adapters/paperclip_runner/models?provider=acpx&acpxAgent=antigravity&aiConnection=${binding}`));
|
||||
expect(response.status).toBe(422);
|
||||
expect(response.body.error).toContain("Google runtime connection");
|
||||
expect(mockAntigravityModels).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["create", "hire", "edit"])("refuses pending Antigravity %s before persistence", async action => {
|
||||
mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableNativeRunner: true });
|
||||
const app = await createApp();
|
||||
const adapterConfig = { provider: "acpx", acpxAgent: "antigravity", model: "exact-antigravity-model" };
|
||||
const response = action === "edit"
|
||||
? await requestApp(app, base => request(base).patch("/api/agents/11111111-1111-4111-8111-111111111111").send({ adapterType: "paperclip_runner", adapterConfig }))
|
||||
: await requestApp(app, base => request(base).post(`/api/companies/company-1/${action === "hire" ? "agent-hires" : "agents"}`).send({ name: "Antigravity", adapterType: "paperclip_runner", adapterConfig }));
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(422);
|
||||
expect(response.body.details).toMatchObject({ code: "paperclip_runner_acpx_agent_unavailable" });
|
||||
expect(mockAgentService.create).not.toHaveBeenCalled();
|
||||
expect(mockAgentService.update).not.toHaveBeenCalled();
|
||||
expect(mockApprovalService.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.runIf(process.platform === "darwin" && process.arch === "arm64")("saves only the exact company-authorized Antigravity candidate without persisting operator authority", async () => {
|
||||
const [{ QUALIFIED_ACPX_PROFILES }, distributionJson] = await Promise.all([
|
||||
import("../vendor/paperclip-runner/index.js"),
|
||||
readFile(new URL("../../../packages/paperclip-runner/antigravity-distributions.json", import.meta.url), "utf8"),
|
||||
]);
|
||||
const distributions = JSON.parse(distributionJson);
|
||||
const adapterConfig = { provider: "acpx", acpxAgent: "antigravity", model: "exact-antigravity-model" };
|
||||
const admission = { schema: "paperclip.acpx-candidate-admission.v1", companyId: "company-1", agent: "antigravity",
|
||||
model: adapterConfig.model, profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest,
|
||||
nativeClosureDigest: `sha256:${distributions.platforms["darwin-arm64"].closureSha256}`,
|
||||
platform: "darwin", architecture: "arm64", expiresAt: Date.now() + 60_000 };
|
||||
vi.stubEnv("PAPERCLIP_ACPX_CANDIDATE_ADMISSION", JSON.stringify(admission));
|
||||
const app = await createApp();
|
||||
const created = await requestApp(app, base => request(base).post("/api/companies/company-1/agents").send({ name: "Antigravity candidate", adapterType: "paperclip_runner", adapterConfig }));
|
||||
expect(created.status, JSON.stringify(created.body)).toBe(201);
|
||||
expect(mockAgentService.create).toHaveBeenCalledWith("company-1", expect.objectContaining({ adapterConfig: expect.objectContaining(adapterConfig) }), expect.any(Object));
|
||||
expect(JSON.stringify(mockAgentService.create.mock.calls)).not.toContain("paperclip.acpx-candidate-admission");
|
||||
expect(QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus).toBe("pending");
|
||||
mockAgentService.create.mockClear();
|
||||
for (const changed of [{ ...admission, companyId: "another-company" }, { ...admission, model: "another-model" }]) {
|
||||
vi.stubEnv("PAPERCLIP_ACPX_CANDIDATE_ADMISSION", JSON.stringify(changed));
|
||||
const denied = await requestApp(app, base => request(base).post("/api/companies/company-1/agents").send({ name: "Antigravity candidate", adapterType: "paperclip_runner", adapterConfig }));
|
||||
expect(denied.status, JSON.stringify(denied.body)).toBe(422);
|
||||
}
|
||||
expect(mockAgentService.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("creates agents for dynamically registered external adapter types", async () => {
|
||||
const { registerServerAdapter } = await import("../adapters/index.js");
|
||||
registerServerAdapter(externalAdapter);
|
||||
|
||||
@@ -687,6 +687,37 @@ describe("agent test-environment route", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("passes the selected Antigravity managed home through ordinary Test and accepts its native admission receipt", async () => {
|
||||
const { registerServerAdapter, getServerAdapter, unregisterServerAdapter } = await import("../adapters/index.js");
|
||||
const previous = getServerAdapter("paperclip_runner");
|
||||
const adapterConfig = { provider: "acpx", acpxAgent: "antigravity", model: "exact-google-model" };
|
||||
const binding = { provider: "google", method: "subscription", mode: "responsible_user" };
|
||||
const agentId = "11111111-1111-4111-8111-111111111111";
|
||||
mockAgentService.getById.mockResolvedValue({ id: agentId, companyId: "company-1", adapterType: "paperclip_runner",
|
||||
adapterConfig, runtimeConfig: { aiConnection: binding }, createdByUserId: "local-board", pauseReason: "setup" });
|
||||
mockPrepareManagedAiRuntime.mockImplementation(async (_db: unknown, input: { config: Record<string, unknown> }) => ({
|
||||
config: { ...input.config, env: { GEMINI_HOME: "/selected-private-home/provider" }, managedAiConnection: { method: "subscription" } },
|
||||
home: "/selected-private-home", cleanup: vi.fn(), accountName: "My Google subscription", attribution: { provider: "google" },
|
||||
}));
|
||||
const nativeProbe = vi.fn(async () => ({ adapterType: "paperclip_runner", status: "pass" as const, testedAt: new Date(0).toISOString(),
|
||||
checks: [{ code: "antigravity_metadata_verified", level: "info" as const, message: "Native account and model accepted without a prompt." }] }));
|
||||
unregisterServerAdapter("paperclip_runner");
|
||||
registerServerAdapter({ ...externalAdapter, type: "paperclip_runner", testEnvironment: nativeProbe });
|
||||
try {
|
||||
const app = await createApp();
|
||||
const response = await request(app).post("/api/companies/company-1/adapters/paperclip_runner/test-environment")
|
||||
.send({ adapterConfig, aiConnection: binding, agentId });
|
||||
expect(response.status, JSON.stringify(response.body)).toBe(200);
|
||||
expect(response.body.status).toBe("pass");
|
||||
expect(nativeProbe).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ companyId: "company-1", managedAiCredentialHome: "/selected-private-home/provider" }));
|
||||
expect(response.body.checks).toContainEqual(expect.objectContaining({ code: "antigravity_metadata_verified" }));
|
||||
expect(response.body.checks.some((check: { code: string }) => check.code.includes("hello_probe"))).toBe(false);
|
||||
} finally {
|
||||
unregisterServerAdapter("paperclip_runner");
|
||||
if (previous) registerServerAdapter(previous);
|
||||
}
|
||||
});
|
||||
|
||||
it("passes one-shot provider credentials only to the probe, never persistence normalization", async () => {
|
||||
const app = await createApp();
|
||||
const res = await request(app)
|
||||
|
||||
@@ -20,6 +20,7 @@ import { createDb, companies, agents, agentTaskSessions, heartbeatRuns, companyM
|
||||
import { startEmbeddedPostgresTestDatabase } from "@paperclipai/db/test-embedded-postgres";
|
||||
import { fetchCompanyQuotaWindows } from "../services/quota-windows.js";
|
||||
import { quotaCredentialRecoveryPath, quotaCredentialRecovery, quotaCredentialHash } from "../services/quota-credential-recovery.js";
|
||||
import { reconcileRetainedAiCleanup, retainAiCredentialCleanup } from "../services/retained-ai-credential-cleanup.js";
|
||||
import { readAiConnectionConfigurationFailure } from "../services/ai-connection-configuration-failure.js";
|
||||
import { aiConnectionService } from "../services/ai-connections.js";
|
||||
import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../services/delivery-work-notifications.js";
|
||||
@@ -30,7 +31,7 @@ import * as executionTarget from "@paperclipai/adapter-utils/execution-target";
|
||||
import * as runnerProbe from "../vendor/paperclip-runner/index.js";
|
||||
import * as nativeCodexRunner from "../services/native-runtime/native-codex-runner.js";
|
||||
import { testNativeRunnerAuthentication } from "../services/native-runtime/setup-readiness.js";
|
||||
import { prepareManagedAiRuntime, withManagedAiProbe, assertManagedAiProjectAuth, isAiConnectionBusy } from "../services/ai-connection-runtime.js";
|
||||
import { prepareManagedAiRuntime, withManagedAiProbe, assertManagedAiProjectAuth, isAiConnectionBusy, managedAiSessionFingerprintConfig } from "../services/ai-connection-runtime.js";
|
||||
import { execute as executeGemini, testEnvironment as testGeminiEnvironment } from "@paperclipai/adapter-gemini-local/server";
|
||||
import { toolAccessService } from "../services/tool-access.js";
|
||||
import { secretService } from "../services/secrets.js";
|
||||
@@ -446,6 +447,61 @@ describe("managed AI connections", () => {
|
||||
expect(await service.credential(row)).toBe(auth);
|
||||
});
|
||||
|
||||
it("fences retained OpenAI credentials before reads, including callers holding the mutation lock", async () => {
|
||||
const owner = "retained-openai-read-fence";
|
||||
await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" });
|
||||
const auth = JSON.stringify({ tokens: { account_id: owner, access_token: "valid-access", refresh_token: "valid-refresh" } });
|
||||
await service.save(companyId, owner, { provider: "openai", method: "subscription", ownership: "personal", name: owner, loginSessionId: "fixture", agentIds: [], allAgents: true }, auth);
|
||||
const [row] = await service.quotaAccounts(companyId, owner);
|
||||
const scope = { companyId, accountKey: row.grant.id }, retired = deferredSignal(), cleanup = vi.fn(async () => {});
|
||||
retainAiCredentialCleanup({ scope, retired: retired.promise, cleanup });
|
||||
try {
|
||||
await expect(service.runtimeCredential(row)).rejects.toMatchObject({ details: { code: "ai_connection_busy" } });
|
||||
await codexAdapter.withAccountHomeSecretMutationLock(undefined, companyId, async () => {
|
||||
await expect(service.runtimeCredential(row, { credentialLockHeld: true })).rejects.toMatchObject({ details: { code: "ai_connection_busy" } });
|
||||
});
|
||||
expect(cleanup).not.toHaveBeenCalled();
|
||||
retired.resolve(); await reconcileRetainedAiCleanup(scope);
|
||||
expect(cleanup).toHaveBeenCalledOnce();
|
||||
await expect(service.runtimeCredential(row)).resolves.toBe(auth);
|
||||
} finally { retired.resolve(); await reconcileRetainedAiCleanup(scope).catch(() => {}); }
|
||||
});
|
||||
|
||||
it("retries retired Codex probe cleanup before the same account can launch again", async () => {
|
||||
const owner = "retired-probe-retry", otherOwner = "retired-probe-other";
|
||||
const auth = (user: string, hour: string) => JSON.stringify({ tokens: { account_id: user, id_token: "identity", access_token: `access-${hour}`, refresh_token: `refresh-${hour}` }, last_refresh: `2026-09-10T${hour}:00:00Z` });
|
||||
for (const user of [owner, otherOwner]) {
|
||||
await db.insert(companyMemberships).values({ companyId, principalId: user, principalType: "user", status: "active", membershipRole: "member" });
|
||||
await service.save(companyId, user, { provider: "openai", method: "subscription", ownership: "personal", name: user, loginSessionId: "fixture", agentIds: [], allAgents: true }, auth(user, "10"));
|
||||
}
|
||||
const [row] = await service.quotaAccounts(companyId, owner);
|
||||
const input = { companyId, agentId, responsibleUserId: owner, adapterType: "codex_local",
|
||||
binding: { provider: "openai", method: "subscription", mode: "responsible_user" } as const, config: {} };
|
||||
const stopped = deferredSignal();
|
||||
const provider = vi.fn(async runtime => readFile(path.join(String(runtime.config.env.CODEX_HOME), "auth.json"), "utf8"));
|
||||
const merge = vi.spyOn(codexAdapter, "decideCodexAuthMerge").mockRejectedValue(new Error("fixture cleanup storage unavailable"));
|
||||
let retained: Awaited<ReturnType<typeof prepareManagedAiRuntime>> | undefined;
|
||||
try {
|
||||
await expect(withManagedAiProbe(db, input, async runtime => {
|
||||
retained = runtime;
|
||||
await writeFile(path.join(String(runtime.config.env.CODEX_HOME), "auth.json"), auth(owner, "11"));
|
||||
throw new runnerProbe.NativeEnvironmentProbeCleanupError(stopped.promise, new Error("fixture probe interruption"), []);
|
||||
})).rejects.toMatchObject({ details: { code: "native_probe_cleanup_pending" } });
|
||||
await expect(withManagedAiProbe(db, input, provider)).rejects.toMatchObject({ details: { code: "ai_connection_busy" } });
|
||||
expect(provider).not.toHaveBeenCalled(); expect(merge).not.toHaveBeenCalled();
|
||||
stopped.resolve();
|
||||
await vi.waitFor(() => expect(merge).toHaveBeenCalledOnce());
|
||||
await expect(withManagedAiProbe(db, input, provider)).rejects.toMatchObject({ details: { code: "ai_connection_busy" } });
|
||||
expect(provider).not.toHaveBeenCalled(); expect(merge).toHaveBeenCalledTimes(2);
|
||||
await expect(withManagedAiProbe(db, { ...input, responsibleUserId: otherOwner }, provider)).resolves.toBe(auth(otherOwner, "10"));
|
||||
expect(await readFile(path.join(String(retained!.config.env.CODEX_HOME), "auth.json"), "utf8")).toBe(auth(owner, "11"));
|
||||
merge.mockRestore();
|
||||
await expect(withManagedAiProbe(db, input, provider)).resolves.toBe(auth(owner, "11"));
|
||||
expect(await service.credential(row)).toBe(auth(owner, "11"));
|
||||
await expect(access(retained!.home!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} finally { stopped.resolve(); merge.mockRestore(); await retained?.cleanup().catch(() => {}); }
|
||||
});
|
||||
|
||||
it("keeps quota refresh outside a manual probe until its rotated credential is saved", async () => {
|
||||
const owner = "manual-probe-race";
|
||||
await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" });
|
||||
@@ -511,6 +567,62 @@ describe("managed AI connections", () => {
|
||||
} finally { probe.mockRestore(); resolveBinary.mockRestore(); }
|
||||
});
|
||||
|
||||
it("keeps the real Codex setup cleanup error and retries its original owner before another probe", async () => {
|
||||
const owner = "native-codex-setup-retirement-retry";
|
||||
const auth = (hour: string) => JSON.stringify({ tokens: { account_id: owner, id_token: "identity", access_token: `access-${hour}`, refresh_token: `refresh-${hour}` }, last_refresh: `2026-09-10T${hour}:00:00Z` });
|
||||
await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" });
|
||||
await service.save(companyId, owner, { provider: "openai", method: "subscription", ownership: "personal", name: owner, loginSessionId: "fixture", agentIds: [], allAgents: true }, auth("10"));
|
||||
const [row] = await service.quotaAccounts(companyId, owner);
|
||||
const input = { companyId, agentId, responsibleUserId: owner, adapterType: "paperclip_runner",
|
||||
binding: { provider: "openai", method: "subscription", mode: "responsible_user" } as const, config: { provider: "codex" } };
|
||||
let rejectRetirement!: (error: Error) => void, physical = false;
|
||||
const retired = new Promise<void>((_resolve, reject) => { rejectRetirement = reject; });
|
||||
void retired.catch(() => undefined);
|
||||
let original: Parameters<typeof runnerProbe.probeNativeRunnerEnvironment>[0], retainedHome: string | undefined;
|
||||
const directories: string[] = [];
|
||||
const retry = vi.fn(async () => {
|
||||
if (!physical) throw new Error("fixture original owner remains live");
|
||||
await original.onCodexCredentialRefresh!(path.join(original.runtimeDirectory, "codex-home", "auth.json"));
|
||||
await original.onCleanupConfirmed!();
|
||||
});
|
||||
const binary = vi.spyOn(nativeCodexRunner, "resolvePaperclipRunnerBinary").mockReturnValue(path.join(home, "fixture-runnerd"));
|
||||
const probe = vi.spyOn(runnerProbe, "probeNativeRunnerEnvironment").mockImplementationOnce(async options => {
|
||||
original = options; directories.push(options.runtimeDirectory);
|
||||
await fs.mkdir(path.join(options.runtimeDirectory, "codex-home"), { mode: 0o700 });
|
||||
await writeFile(path.join(options.runtimeDirectory, "codex-home", "auth.json"), auth("11"), { mode: 0o600 });
|
||||
throw new runnerProbe.NativeEnvironmentProbeCleanupError(retired, new Error("fixture interrupted probe"), [], retry);
|
||||
}).mockImplementation(async options => {
|
||||
directories.push(options.runtimeDirectory);
|
||||
expect(await readFile(path.join(options.transportOptions!.sourceCodexHome!, "auth.json"), "utf8")).toBe(auth("11"));
|
||||
await options.onCleanupConfirmed!();
|
||||
return { provider: "codex", providerDriver: "codex_app_server", effectiveModel: "gpt-5.6-sol", helloProbePassed: true };
|
||||
});
|
||||
const invoke = () => withManagedAiProbe(db, input, runtime => {
|
||||
retainedHome ??= runtime.home;
|
||||
return testNativeRunnerAuthentication({ companyId, adapterType: "paperclip_runner", config: runtime.config,
|
||||
managedAiCredentialHome: path.join(runtime.home!, "provider") }, "codex", "gpt-5.6-sol");
|
||||
});
|
||||
try {
|
||||
await expect(invoke()).rejects.toMatchObject({ details: { code: "native_probe_cleanup_pending" } });
|
||||
await expect(access(retainedHome!)).resolves.toBeUndefined();
|
||||
rejectRetirement(new Error("fixture initial retirement proof failed"));
|
||||
await Promise.resolve();
|
||||
await expect(invoke()).rejects.toMatchObject({ details: { code: "ai_connection_busy" } });
|
||||
expect(probe).toHaveBeenCalledOnce(); expect(retry).toHaveBeenCalledOnce();
|
||||
await expect(access(retainedHome!)).resolves.toBeUndefined();
|
||||
physical = true;
|
||||
expect((await invoke()).status).toBe("pass");
|
||||
expect(retry).toHaveBeenCalledTimes(2); expect(probe).toHaveBeenCalledTimes(2);
|
||||
expect(await service.credential(row)).toBe(auth("11"));
|
||||
await expect(access(retainedHome!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} finally {
|
||||
physical = true; rejectRetirement(new Error("fixture teardown"));
|
||||
await reconcileRetainedAiCleanup({ companyId, accountKey: row.grant.id }).catch(() => {});
|
||||
probe.mockRestore(); binary.mockRestore();
|
||||
await Promise.all(directories.map(directory => rm(directory, { recursive: true, force: true })));
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects preparation when reconnect replaces the selected credential reference", async () => {
|
||||
const owner = "replaced-ref-owner";
|
||||
await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" });
|
||||
@@ -1099,6 +1211,41 @@ describe("managed AI connections", () => {
|
||||
await expect(access(transcript)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} finally { await Promise.all([resumed.cleanup(), peer.cleanup()]); }
|
||||
});
|
||||
it("isolates the selected Google AI credential for pending native Antigravity preparation", async () => {
|
||||
const owner = "antigravity-managed-key";
|
||||
const token = "saved-antigravity-key";
|
||||
await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" });
|
||||
const saved = await service.save(companyId, owner, { provider: "google", method: "api_key", ownership: "personal",
|
||||
name: "Antigravity Google AI", apiKey: token, allAgents: true, agentIds: [] }, token);
|
||||
await service.setDefault(companyId, owner, saved.grantId);
|
||||
const input = { companyId, agentId, responsibleUserId: owner, adapterType: "paperclip_runner",
|
||||
binding: { provider: "google", method: "api_key", mode: "responsible_user" } as const,
|
||||
config: { provider: "acpx", acpxAgent: "antigravity", model: "exact-antigravity-model", env: {
|
||||
GEMINI_API_KEY: "ambient-key", GOOGLE_API_KEY: "ambient-other-key", GEMINI_HOME: "/ambient/home",
|
||||
GOOGLE_APPLICATION_CREDENTIALS: "/ambient/google.json", GOOGLE_CLOUD_ACCESS_TOKEN: "ambient-oauth-token",
|
||||
} } };
|
||||
const runtime = await prepareManagedAiRuntime(db, input);
|
||||
const reopened = await prepareManagedAiRuntime(db, input);
|
||||
try {
|
||||
expect(runtime.attribution).toMatchObject({ provider: "google", method: "api_key", connectionId: saved.connectionId, grantId: saved.grantId });
|
||||
expect(runtime.config).toMatchObject({ provider: "acpx", acpxAgent: "antigravity", model: input.config.model,
|
||||
env: { GEMINI_API_KEY: token, GOOGLE_API_KEY: "", GOOGLE_APPLICATION_CREDENTIALS: "", GOOGLE_CLOUD_ACCESS_TOKEN: "" } });
|
||||
expect(runtime.config.env.GEMINI_HOME).toBe(path.join(runtime.home!, "provider"));
|
||||
const settingsFile = path.join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "settings.json");
|
||||
expect(JSON.parse(await readFile(settingsFile, "utf8"))).toEqual({ auth: { type: "gemini-api-key" } });
|
||||
expect(await readFile(settingsFile, "utf8")).not.toContain(token);
|
||||
expect((await stat(settingsFile)).mode & 0o777).toBe(0o600);
|
||||
expect(managedAiSessionFingerprintConfig(runtime.config, runtime.home))
|
||||
.toEqual(managedAiSessionFingerprintConfig(reopened.config, reopened.home));
|
||||
expect(input.config.env.GEMINI_HOME).toBe("/ambient/home");
|
||||
await expect(prepareManagedAiRuntime(db, { ...input, responsibleUserId: "bob" })).rejects.toThrow();
|
||||
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, saved.grantId));
|
||||
await expect(prepareManagedAiRuntime(db, input)).rejects.toThrow();
|
||||
} finally { await Promise.all([runtime.cleanup(), reopened.cleanup()]); }
|
||||
await expect(access(runtime.home!)).rejects.toThrow();
|
||||
await expect(access(reopened.home!)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("authenticates local Gemini probes and runs with the saved key in an isolated home", async () => {
|
||||
const root = await mkdtemp(path.join(home, "gemini-auth-"));
|
||||
const command = path.join(root, "gemini");
|
||||
@@ -2062,17 +2209,17 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello"
|
||||
const owner = `restart-${provider}`;
|
||||
const intent = { provider, method: "subscription", ownership: "personal", name: "Interrupted sign-in", allAgents: false, agentIds: [] } as const;
|
||||
await db.insert(adapterAuthSessions).values({ id, publicSessionId: id, companyId, environmentId: environment.id, startedByUserId: owner, adapterType: provider === "anthropic" ? "claude_local" : "codex_local", aiConnection: { ...intent, agentIds: [] }, connectionMethod: "local_subscription", status: "waiting_for_user", expiresAt: new Date(Date.now() + 60_000) });
|
||||
const reader = vi.spyOn(localCredentials, "readVerifiedLocalAiCredential").mockRejectedValue(new Error("No credential yet"));
|
||||
const reader = vi.spyOn(localCredentials, "readVerifiedLocalAiCredentialDetails").mockRejectedValue(new Error("No credential yet"));
|
||||
try {
|
||||
const login = localAiLoginService(db);
|
||||
await expect(login.check(companyId, owner, { ...intent, agentIds: [] }, id)).resolves.toEqual({ status: "sign_in_required", error: "The server restarted during sign-in. Start sign-in again." });
|
||||
await expect(login.check(companyId, "bob", { ...intent, agentIds: [] }, id)).rejects.toThrow("not found");
|
||||
reader.mockResolvedValue("completed-before-restart");
|
||||
reader.mockResolvedValue({ credential: "completed-before-restart", accountLabel: undefined });
|
||||
await expect(login.check(companyId, owner, { ...intent, agentIds: [] }, id)).resolves.toEqual({ status: "ready" });
|
||||
} finally { reader.mockRestore(); await db.delete(adapterAuthSessions).where(eq(adapterAuthSessions.id, id)); }
|
||||
});
|
||||
it("requires an owned browser sign-in attempt for local subscriptions", async () => {
|
||||
const reader = vi.spyOn(localCredentials, "readVerifiedLocalAiCredential").mockResolvedValue("fixture-local-token");
|
||||
const reader = vi.spyOn(localCredentials, "readVerifiedLocalAiCredentialDetails").mockResolvedValue({ credential: "fixture-local-token", accountLabel: undefined });
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
@@ -2108,7 +2255,7 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello"
|
||||
} finally { reader.mockRestore(); }
|
||||
});
|
||||
it.each(["anthropic", "openai"] as const)("blocks server-host %s login on a public deployment without a trusted host", async provider => {
|
||||
const reader = vi.spyOn(localCredentials, "readVerifiedLocalAiCredential");
|
||||
const reader = vi.spyOn(localCredentials, "readVerifiedLocalAiCredentialDetails");
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
@@ -2131,7 +2278,7 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello"
|
||||
it.each(["anthropic", "openai"] as const)("lets authenticated users connect only their own isolated %s login", async provider => {
|
||||
const owner = `self-hosted-${provider}`;
|
||||
await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" });
|
||||
const reader = vi.spyOn(localCredentials, "readVerifiedLocalAiCredential").mockResolvedValue("isolated-fixture-token");
|
||||
const reader = vi.spyOn(localCredentials, "readVerifiedLocalAiCredentialDetails").mockResolvedValue({ credential: "isolated-fixture-token", accountLabel: undefined });
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use((req, _res, next) => {
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { access, readFile, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import { promises as fs } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
agents, authUsers, closeRegisteredClients, companies, companyMemberships, companySecrets, companySecretVersions,
|
||||
connectionGrants, createDb, userSecretDefinitions,
|
||||
} from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
||||
import { createIsolatedTestHome } from "./helpers/isolated-test-home.js";
|
||||
import { aiConnectionService } from "../services/ai-connections.js";
|
||||
import { managedAiSessionFingerprintConfig, prepareManagedAiRuntime, withManagedAiProbe } from "../services/ai-connection-runtime.js";
|
||||
import { secretService } from "../services/secrets.js";
|
||||
import { quotaCredentialHash, quotaCredentialRecovery, quotaCredentialRecoveryPath } from "../services/quota-credential-recovery.js";
|
||||
import * as codexAdapter from "@paperclipai/adapter-codex-local/server";
|
||||
import * as workspaceLocks from "@paperclipai/adapter-utils/workspace-restore-merge";
|
||||
import { reconcileRetainedGoogleCleanup, retainGoogleCredentialCleanup } from "../services/retained-google-credential-cleanup.js";
|
||||
|
||||
// External runs require an already migrated dedicated database ending in _test.
|
||||
// The shared helper rejects ordinary application database names and overrides.
|
||||
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_GOOGLE_AI_TEST_DATABASE_URL");
|
||||
const support = external ? { supported: true, reason: undefined } : await getEmbeddedPostgresTestSupport();
|
||||
if (!support.supported) console.warn(`Skipping Google AI PostgreSQL integration on this host: ${support.reason ?? "embedded PostgreSQL unavailable"}`);
|
||||
const describeDatabase = support.supported ? describe : describe.skip;
|
||||
|
||||
const googleCredential = (project?: string, token = "fixture-google-refresh") => 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"],
|
||||
...(project ? { project_id: project } : {}),
|
||||
});
|
||||
|
||||
describeDatabase("Google AI connection authority with real PostgreSQL", () => {
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let embedded: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
|
||||
let isolatedHome: ReturnType<typeof createIsolatedTestHome>;
|
||||
let request: ReturnType<typeof vi.spyOn<typeof globalThis, "fetch">>;
|
||||
|
||||
beforeAll(async () => {
|
||||
isolatedHome = createIsolatedTestHome();
|
||||
vi.stubEnv("PAPERCLIP_HOME", isolatedHome.home);
|
||||
vi.stubEnv("PAPERCLIP_INSTANCE_ID", "google-ai-real-db");
|
||||
if (!external) embedded = await startEmbeddedPostgresTestDatabase("paperclip-google-ai-db-");
|
||||
db = createDb(external ?? embedded!.connectionString);
|
||||
request = vi.spyOn(globalThis, "fetch");
|
||||
}, 90_000);
|
||||
beforeEach(() => { request.mockReset().mockRejectedValue(new Error("Provider network is forbidden in database authority tests")); });
|
||||
afterAll(async () => {
|
||||
request?.mockRestore();
|
||||
if (external) await closeRegisteredClients(external);
|
||||
await db?.$client.end();
|
||||
await embedded?.cleanup();
|
||||
vi.unstubAllEnvs();
|
||||
isolatedHome?.cleanup();
|
||||
});
|
||||
|
||||
async function fixture(method: "api_key" | "subscription", allAgents = true) {
|
||||
const companyId = randomUUID(), otherCompanyId = randomUUID(), agentId = randomUUID(), peerAgentId = randomUUID(), foreignAgentId = randomUUID();
|
||||
const owner = `google-owner-${randomUUID()}`, otherUser = `google-other-${randomUUID()}`;
|
||||
await db.insert(companies).values([
|
||||
{ id: companyId, name: "Google AI authority fixture", issuePrefix: `GAF${companyId.slice(0, 8)}` },
|
||||
{ id: otherCompanyId, name: "Foreign Google AI fixture", issuePrefix: `GAX${otherCompanyId.slice(0, 8)}` },
|
||||
]);
|
||||
await db.insert(authUsers).values([owner, otherUser].map(id => ({ id, name: id, email: `${id}@example.test`, createdAt: new Date(), updatedAt: new Date() })));
|
||||
await db.insert(companyMemberships).values([
|
||||
...[owner, otherUser].map(principalId => ({ companyId, principalId, principalType: "user", status: "active", membershipRole: "member" })),
|
||||
{ companyId: otherCompanyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" },
|
||||
]);
|
||||
await db.insert(agents).values([
|
||||
{ id: agentId, companyId, name: "Selected Google agent", adapterType: "paperclip_runner" },
|
||||
{ id: peerAgentId, companyId, name: "Uninstalled peer", adapterType: "paperclip_runner" },
|
||||
{ id: foreignAgentId, companyId: otherCompanyId, name: "Foreign agent", adapterType: "paperclip_runner" },
|
||||
]);
|
||||
const service = aiConnectionService(db);
|
||||
const credential = method === "api_key" ? "fixture-selected-google-api-key" : googleCredential();
|
||||
const intent = { provider: "google" as const, method, ownership: "personal" as const, name: "Fixture Google account", allAgents,
|
||||
agentIds: allAgents ? [] : [agentId], ...(method === "api_key" ? { apiKey: credential } : { loginSessionId: "verified-fixture" }) };
|
||||
const saved = await service.save(companyId, owner, intent, credential, undefined, new Date(), undefined,
|
||||
method === "subscription" ? "verified-owner@example.test" : undefined);
|
||||
await service.setDefault(companyId, owner, saved.grantId);
|
||||
const binding = { provider: "google", method, mode: "responsible_user" } as const;
|
||||
const config = { provider: "acpx", acpxAgent: "antigravity", model: "caller-selected-model", env: {
|
||||
GEMINI_API_KEY: "fixture-ambient-key", GOOGLE_API_KEY: "fixture-other-key", GEMINI_HOME: "/ambient/home",
|
||||
GOOGLE_APPLICATION_CREDENTIALS: "/ambient/google.json", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "fixture-forged-inline",
|
||||
} };
|
||||
const select = { companyId, userId: owner, agentId, adapterType: "paperclip_runner", runnerProvider: "acpx", acpxAgent: "antigravity", model: config.model, binding };
|
||||
const runtime = { companyId, responsibleUserId: owner, agentId, adapterType: "paperclip_runner", config, binding };
|
||||
const selection = await service.select(select);
|
||||
const secretId = selection.grant.credentialSecretRefs.find(ref => ref.configPath === "ai.credential")!.secretId;
|
||||
return { companyId, otherCompanyId, agentId, peerAgentId, foreignAgentId, owner, otherUser, saved, service, select, runtime, selection, secretId, credential, intent };
|
||||
}
|
||||
|
||||
it.each(["api_key", "subscription"] as const)("prepares the selected %s from a personal encrypted secret and preserves provider identity across private homes", async method => {
|
||||
const f = await fixture(method);
|
||||
const [secret] = await db.select().from(companySecrets).where(eq(companySecrets.id, f.secretId));
|
||||
const [definition] = await db.select().from(userSecretDefinitions).where(eq(userSecretDefinitions.id, secret.userSecretDefinitionId!));
|
||||
const versions = await db.select().from(companySecretVersions).where(eq(companySecretVersions.secretId, secret.id));
|
||||
expect(secret).toMatchObject({ companyId: f.companyId, scope: "user", ownerUserId: f.owner, provider: "local_encrypted", latestVersion: 1 });
|
||||
expect(definition).toMatchObject({ companyId: f.companyId, key: `ai_${f.saved.grantId.replaceAll("-", "_")}` });
|
||||
expect(versions[0].material).toMatchObject({ scheme: "local_encrypted_v1" });
|
||||
expect(JSON.stringify(versions[0].material)).not.toContain(method === "api_key" ? f.credential : "fixture-google-refresh");
|
||||
expect(await f.service.credential(f.selection)).toBe(f.credential);
|
||||
expect(await secretService(db).listCurrentUserSecretValues(f.companyId, f.otherUser)).toMatchObject([{ definition: { id: definition.id }, secret: null }]);
|
||||
const first = await prepareManagedAiRuntime(db, f.runtime), second = await prepareManagedAiRuntime(db, f.runtime);
|
||||
try {
|
||||
expect(first.attribution).toMatchObject({ provider: "google", method, connectionId: f.saved.connectionId, grantId: f.saved.grantId });
|
||||
expect(first.home).not.toBe(second.home);
|
||||
expect(await realpath(first.home!)).toBe(first.home);
|
||||
expect(await realpath(String(first.config.env.GEMINI_HOME))).toBe(first.config.env.GEMINI_HOME);
|
||||
expect(first.config.env).toMatchObject({ GOOGLE_API_KEY: "", GOOGLE_APPLICATION_CREDENTIALS: "", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "",
|
||||
GEMINI_API_KEY: method === "api_key" ? f.credential : "" });
|
||||
const directory = join(String(first.config.env.GEMINI_HOME), "antigravity-acp");
|
||||
expect(JSON.parse(await readFile(join(directory, "settings.json"), "utf8"))).toEqual({ auth: { type: method === "api_key" ? "gemini-api-key" : "oauth-personal" } });
|
||||
if (method === "subscription") expect(await readFile(join(directory, "acp_token.json"), "utf8")).toBe(f.credential);
|
||||
else await expect(access(join(directory, "acp_token.json"))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(managedAiSessionFingerprintConfig(first.config, first.home)).toEqual(managedAiSessionFingerprintConfig(second.config, second.home));
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
} finally { await Promise.all([first.cleanup(), second.cleanup()]); }
|
||||
await expect(access(first.home!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await expect(access(second.home!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it.each(["api_key", "subscription"] as const)("enforces the %s owner's membership, personal audience, company, and agent installation", async method => {
|
||||
const f = await fixture(method, false);
|
||||
const explicit = { provider: "google", method, mode: "delegated", ...f.saved } as const;
|
||||
expect((await f.service.select({ ...f.select, binding: explicit })).grant.id).toBe(f.saved.grantId);
|
||||
await expect(f.service.select({ ...f.select, binding: { ...explicit, mode: "shared" } })).rejects.toThrow("company-shared account");
|
||||
await expect(f.service.select({ ...f.select, userId: f.otherUser, binding: explicit })).rejects.toThrow("not shared");
|
||||
await expect(f.service.select({ ...f.select, companyId: f.otherCompanyId, agentId: f.foreignAgentId, binding: explicit })).rejects.toThrow("unavailable");
|
||||
await expect(f.service.select({ ...f.select, agentId: f.peerAgentId })).rejects.toThrow("not permitted for this agent");
|
||||
await expect(f.service.save(f.companyId, f.owner, { ...f.intent, connectionId: undefined, agentIds: [f.foreignAgentId] }, f.credential)).rejects.toThrow("Agent does not belong");
|
||||
const credentials = await db.select().from(companySecrets).where(eq(companySecrets.companyId, f.companyId));
|
||||
expect(credentials).toHaveLength(1); // The rejected foreign-agent save rolled back its secret too.
|
||||
await db.update(companyMemberships).set({ status: "inactive" }).where(and(eq(companyMemberships.companyId, f.companyId), eq(companyMemberships.principalId, f.owner)));
|
||||
await expect(prepareManagedAiRuntime(db, f.runtime)).rejects.toThrow("not an active company member");
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["api_key", "subscription"] as const)("refuses revoked %s defaults without falling back to another saved credential", async method => {
|
||||
const f = await fixture(method);
|
||||
await f.service.save(f.companyId, f.owner, { ...f.intent, name: "Unselected fallback", connectionId: undefined }, f.credential);
|
||||
await db.update(connectionGrants).set({ status: "revoked", revokedAt: new Date() }).where(eq(connectionGrants.id, f.saved.grantId));
|
||||
await expect(prepareManagedAiRuntime(db, f.runtime)).rejects.toThrow("Reconnect or validate");
|
||||
expect((await f.service.list(f.companyId, f.owner)).find(row => row.grantId === f.saved.grantId)).toMatchObject({ status: "revoked", isDefault: true });
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("persists same-account project discovery with a new encrypted revision while preserving the session epoch", async () => {
|
||||
const f = await fixture("subscription");
|
||||
const [before] = await db.select().from(companySecrets).where(eq(companySecrets.id, f.secretId));
|
||||
const runtime = await prepareManagedAiRuntime(db, f.runtime);
|
||||
await writeFile(join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json"), googleCredential("resolved-project"));
|
||||
await runtime.cleanup();
|
||||
const [after] = await db.select().from(companySecrets).where(eq(companySecrets.id, f.secretId));
|
||||
expect(after.latestVersion).toBe(before.latestVersion + 1);
|
||||
expect(after.aiSessionEpoch).toBe(before.aiSessionEpoch);
|
||||
expect(await f.service.credential(await f.service.select(f.select))).toBe(googleCredential("resolved-project"));
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("waits for a real secret-row lock and preserves an authorized rotation committed while cleanup is blocked", async () => {
|
||||
const f = await fixture("subscription");
|
||||
const runtime = await prepareManagedAiRuntime(db, f.runtime);
|
||||
await writeFile(join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json"), googleCredential("stale-run-project"));
|
||||
let acquired!: () => void, release!: () => void;
|
||||
const locked = new Promise<void>(resolve => { acquired = resolve; });
|
||||
const released = new Promise<void>(resolve => { release = resolve; });
|
||||
const holder = db.transaction(async tx => {
|
||||
await secretService(tx).rotate(f.secretId, { value: googleCredential("authorized-project") }, { userId: f.owner });
|
||||
acquired();
|
||||
await released;
|
||||
});
|
||||
await locked;
|
||||
const cleanup = runtime.cleanup();
|
||||
try {
|
||||
const deadline = Date.now() + 5_000;
|
||||
let waiting = false;
|
||||
while (!waiting && Date.now() < deadline) {
|
||||
const rows = await db.execute(sql`select pid from pg_stat_activity where datname = current_database() and wait_event_type = 'Lock' and query like '%company_secrets%'`);
|
||||
waiting = rows.length > 0;
|
||||
if (!waiting) await new Promise(resolve => setTimeout(resolve, 25));
|
||||
}
|
||||
expect(waiting).toBe(true);
|
||||
} finally { release(); }
|
||||
await holder;
|
||||
await cleanup;
|
||||
expect(await f.service.credential(await f.service.select(f.select))).toBe(googleCredential("authorized-project"));
|
||||
await expect(access(runtime.home!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["rotation", "commit", "lost_reply"] as const)("recovers a retired Google refresh after %s failure and loss of the old controller home", async failure => {
|
||||
const f = await fixture("subscription");
|
||||
const runtime = await prepareManagedAiRuntime(db, f.runtime);
|
||||
const replacement = googleCredential("recovered-project");
|
||||
await writeFile(join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json"), replacement);
|
||||
const journal = quotaCredentialRecovery(f.companyId, f.saved.grantId);
|
||||
const transaction = db.transaction.bind(db);
|
||||
const interrupted = failure === "lost_reply" ? vi.spyOn(db, "transaction").mockImplementationOnce(async (work, config) => {
|
||||
await transaction(work, config);
|
||||
throw new Error("fixture lost Google commit response");
|
||||
}) : undefined;
|
||||
if (!interrupted) await db.execute(sql.raw(`create function reject_google_recovery() returns trigger language plpgsql as $$ begin
|
||||
if new.secret_id = '${f.secretId}'::uuid then raise exception 'fixture Google writeback failure'; end if; return new; end $$;
|
||||
create ${failure === "commit" ? "constraint " : ""}trigger reject_google_recovery ${failure === "commit" ? "after" : "before"} insert on company_secret_versions
|
||||
${failure === "commit" ? "deferrable initially deferred" : ""} for each row execute function reject_google_recovery();`));
|
||||
try {
|
||||
await expect(runtime.cleanup()).rejects.toThrow();
|
||||
await expect(access(runtime.home!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
const encrypted = await readFile(quotaCredentialRecoveryPath(f.companyId, f.saved.grantId), "utf8");
|
||||
expect(encrypted).not.toContain("fixture-google-refresh");
|
||||
expect(encrypted).not.toContain("recovered-project");
|
||||
expect(await journal.read()).toMatchObject({ provider: "google", value: replacement });
|
||||
// A fresh service must defer while the durable replacement cannot commit.
|
||||
if (!interrupted) await expect(prepareManagedAiRuntime(db, f.runtime)).rejects.toMatchObject({ details: { code: "ai_connection_busy" } });
|
||||
} finally {
|
||||
if (interrupted) interrupted.mockRestore();
|
||||
else await db.execute(sql`drop trigger reject_google_recovery on company_secret_versions; drop function reject_google_recovery()`);
|
||||
}
|
||||
// The retired owner's ephemeral files and JS callbacks are no longer needed.
|
||||
await rm(runtime.home!, { recursive: true, force: true });
|
||||
const recovered = await prepareManagedAiRuntime(db, f.runtime);
|
||||
try {
|
||||
expect(await readFile(join(String(recovered.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json"), "utf8")).toBe(replacement);
|
||||
expect(await journal.read()).toBeNull();
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
expect(await db.select().from(companySecretVersions).where(eq(companySecretVersions.secretId, f.secretId))).toHaveLength(2);
|
||||
} finally { await recovered.cleanup(); await journal.clear(); }
|
||||
});
|
||||
|
||||
async function retiredJournal(f: Awaited<ReturnType<typeof fixture>>, value: string, verified = true) {
|
||||
const [secret] = await db.select().from(companySecrets).where(eq(companySecrets.id, f.secretId));
|
||||
const journal = quotaCredentialRecovery(f.companyId, f.saved.grantId);
|
||||
await journal.write({ companyId: f.companyId, grantId: f.saved.grantId, connectionId: f.saved.connectionId,
|
||||
secretId: f.secretId, provider: "google", baseHash: quotaCredentialHash(f.credential), value,
|
||||
google: { sessionEpoch: secret.aiSessionEpoch, baseVersion: secret.latestVersion,
|
||||
versionSelector: "latest", accountEmail: "verified-owner@example.test", verified } });
|
||||
return journal;
|
||||
}
|
||||
|
||||
it("settles a failed probe journal before another provider starts for the same Google account", async () => {
|
||||
const f = await fixture("subscription");
|
||||
const replacement = googleCredential("recovered-probe-project");
|
||||
const journalPath = quotaCredentialRecoveryPath(f.companyId, f.saved.grantId);
|
||||
const realOpen = fs.open.bind(fs);
|
||||
let unavailable = false;
|
||||
const open = vi.spyOn(fs, "open").mockImplementation(async (...args: Parameters<typeof fs.open>) => {
|
||||
if (unavailable && String(args[0]).startsWith(`${journalPath}.`) && String(args[0]).endsWith(".tmp")) {
|
||||
throw new Error("fixture Google journal unavailable");
|
||||
}
|
||||
return realOpen(...args);
|
||||
});
|
||||
let originalHome: string | undefined;
|
||||
const provider = vi.fn(async (runtime: Awaited<ReturnType<typeof prepareManagedAiRuntime>>) => {
|
||||
expect(await readFile(join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json"), "utf8")).toBe(replacement);
|
||||
});
|
||||
try {
|
||||
await expect(withManagedAiProbe(db, f.runtime, async runtime => {
|
||||
originalHome = runtime.home;
|
||||
await writeFile(join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json"), replacement);
|
||||
unavailable = true;
|
||||
})).rejects.toThrow("fixture Google journal unavailable");
|
||||
await expect(access(originalHome!)).resolves.toBeUndefined();
|
||||
await expect(withManagedAiProbe(db, f.runtime, provider)).rejects.toMatchObject({ details: { code: "ai_connection_busy" } });
|
||||
expect(provider).not.toHaveBeenCalled();
|
||||
expect(await f.service.credential(await f.service.select(f.select))).toBe(f.credential);
|
||||
unavailable = false;
|
||||
await withManagedAiProbe(db, f.runtime, provider);
|
||||
expect(provider).toHaveBeenCalledOnce();
|
||||
await expect(access(originalHome!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(await f.service.credential(await f.service.select(f.select))).toBe(replacement);
|
||||
expect(await quotaCredentialRecovery(f.companyId, f.saved.grantId).read()).toBeNull();
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
} finally { unavailable = false; open.mockRestore(); }
|
||||
});
|
||||
|
||||
it("lets retirement cleanup acquire the credential lock before another account use joins it", async () => {
|
||||
const f = await fixture("subscription"), runtime = await prepareManagedAiRuntime(db, f.runtime);
|
||||
const replacement = googleCredential("retirement-concurrency-project");
|
||||
await writeFile(join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json"), replacement);
|
||||
const scope = { companyId: f.companyId, accountKey: f.saved.grantId };
|
||||
let entered!: () => void, release!: () => void, lockEntered!: () => void;
|
||||
const cleanupEntered = new Promise<void>(resolve => { entered = resolve; });
|
||||
const permitCleanup = new Promise<void>(resolve => { release = resolve; });
|
||||
const credentialLockEntered = new Promise<void>(resolve => { lockEntered = resolve; });
|
||||
const cleanup = async () => { entered(); await permitCleanup; await runtime.cleanup(); };
|
||||
retainGoogleCredentialCleanup({ scope, cleanup, retired: Promise.resolve() });
|
||||
await cleanupEntered;
|
||||
const originalLock = codexAdapter.withAccountHomeSecretMutationLock;
|
||||
const originalDirectoryLock = workspaceLocks.withDirectoryMergeLock;
|
||||
let requestedLock = false;
|
||||
const lock = vi.spyOn(codexAdapter, "withAccountHomeSecretMutationLock").mockImplementation((env, company, callback) => {
|
||||
if (requestedLock) return originalLock(env, company, callback);
|
||||
requestedLock = true;
|
||||
return originalLock(env, company, async () => { lockEntered(); return callback(); });
|
||||
});
|
||||
// Exercise the real filesystem mutex with its existing bounded test seam;
|
||||
// a regression reports contention promptly instead of waiting 30 seconds.
|
||||
const directoryLock = vi.spyOn(workspaceLocks, "withDirectoryMergeLock").mockImplementation((directory, callback, env, operation) =>
|
||||
originalDirectoryLock(directory, callback, env, operation, 100));
|
||||
const using = f.service.runtimeCredential(f.selection);
|
||||
void using.catch(() => undefined);
|
||||
try {
|
||||
if (requestedLock) await credentialLockEntered;
|
||||
release();
|
||||
await expect(using).resolves.toBe(replacement);
|
||||
await expect(access(runtime.home!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(await f.service.credential(await f.service.select(f.select))).toBe(replacement);
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
release(); await Promise.allSettled([using]);
|
||||
lock.mockRestore(); directoryLock.mockRestore();
|
||||
await reconcileRetainedGoogleCleanup(scope);
|
||||
await runtime.cleanup();
|
||||
await quotaCredentialRecovery(f.companyId, f.saved.grantId).clear();
|
||||
}
|
||||
});
|
||||
|
||||
it("defers credential use when another retained owner arrives before lock acquisition", async () => {
|
||||
const f = await fixture("subscription"), scope = { companyId: f.companyId, accountKey: f.saved.grantId };
|
||||
let retire!: () => void;
|
||||
const retired = new Promise<void>(resolve => { retire = resolve; });
|
||||
const cleanup = vi.fn(async () => {});
|
||||
const originalLock = codexAdapter.withAccountHomeSecretMutationLock;
|
||||
const lock = vi.spyOn(codexAdapter, "withAccountHomeSecretMutationLock").mockImplementationOnce((env, company, callback) => {
|
||||
retainGoogleCredentialCleanup({ scope, cleanup, retired });
|
||||
return originalLock(env, company, callback);
|
||||
});
|
||||
try {
|
||||
await expect(f.service.runtimeCredential(f.selection)).rejects.toMatchObject({ details: { code: "ai_connection_busy" } });
|
||||
expect(cleanup).not.toHaveBeenCalled();
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
} finally { lock.mockRestore(); retire(); await reconcileRetainedGoogleCleanup(scope); }
|
||||
});
|
||||
|
||||
it("does not join another retirement from cleanup that already holds the credential lock", async () => {
|
||||
const f = await fixture("subscription"), scope = { companyId: f.companyId, accountKey: f.saved.grantId };
|
||||
let retire!: () => void, entered!: () => void;
|
||||
const retired = new Promise<void>(resolve => { retire = resolve; });
|
||||
const cleanupEntered = new Promise<void>(resolve => { entered = resolve; });
|
||||
let failedLock = false, finished = false;
|
||||
const originalDirectoryLock = workspaceLocks.withDirectoryMergeLock;
|
||||
const directoryLock = vi.spyOn(workspaceLocks, "withDirectoryMergeLock").mockImplementation((directory, callback, env, operation) =>
|
||||
originalDirectoryLock(directory, callback, env, operation, 100));
|
||||
retainGoogleCredentialCleanup({ scope, retired, cleanup: async () => {
|
||||
entered();
|
||||
try { await codexAdapter.withAccountHomeSecretMutationLock(undefined, f.companyId, async () => { finished = true; }); }
|
||||
catch (error) { failedLock = true; throw error; }
|
||||
} });
|
||||
try {
|
||||
await codexAdapter.withAccountHomeSecretMutationLock(undefined, f.companyId, async () => {
|
||||
retire(); await cleanupEntered;
|
||||
await expect(f.service.runtimeCredential(f.selection, { credentialLockHeld: true }))
|
||||
.rejects.toMatchObject({ details: { code: "ai_connection_busy" } });
|
||||
expect(failedLock).toBe(false);
|
||||
expect(finished).toBe(false);
|
||||
});
|
||||
} finally {
|
||||
retire(); await reconcileRetainedGoogleCleanup(scope); directoryLock.mockRestore();
|
||||
}
|
||||
expect(finished).toBe(true);
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["epoch", "version", "account"] as const)("discards a retired journal after the selected Google %s changes", async change => {
|
||||
const f = await fixture("subscription");
|
||||
const journal = await retiredJournal(f, googleCredential("stale-retired-project", "fixture-stale-rotated-refresh"), false);
|
||||
if (change === "account") await db.update(connectionGrants).set({ providerTenant: { name: "reconnected-owner@example.test" } }).where(eq(connectionGrants.id, f.saved.grantId));
|
||||
else await secretService(db).rotate(f.secretId, { value: f.credential, preserveAiSessionEpoch: change === "version" }, { userId: f.owner });
|
||||
const runtime = await prepareManagedAiRuntime(db, f.runtime);
|
||||
try {
|
||||
expect(await readFile(join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json"), "utf8")).toBe(f.credential);
|
||||
expect(await journal.read()).toBeNull();
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
} finally { await runtime.cleanup(); await journal.clear(); }
|
||||
});
|
||||
|
||||
it.each(["verified-owner@example.test", "other@example.test"])("verifies %s before an unverified retired refresh can be recovered", async email => {
|
||||
const f = await fixture("subscription");
|
||||
const replacement = googleCredential("recovered-project", "fixture-retired-rotated-refresh");
|
||||
const journal = await retiredJournal(f, replacement, false);
|
||||
request.mockResolvedValueOnce(Response.json({ access_token: "fixture-access", token_type: "Bearer" }))
|
||||
.mockResolvedValueOnce(Response.json({ email_verified: true, email }));
|
||||
if (email === "verified-owner@example.test") {
|
||||
const runtime = await prepareManagedAiRuntime(db, f.runtime);
|
||||
try {
|
||||
expect(await readFile(join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json"), "utf8")).toBe(replacement);
|
||||
expect(await journal.read()).toBeNull();
|
||||
} finally { await runtime.cleanup(); await journal.clear(); }
|
||||
} else {
|
||||
const failure = await prepareManagedAiRuntime(db, f.runtime).catch(error => error);
|
||||
expect(failure).toMatchObject({ details: { code: "ai_connection_busy" } });
|
||||
expect(failure.message).not.toContain("other@example.test");
|
||||
expect(await f.service.credential(await f.service.select(f.select))).toBe(f.credential);
|
||||
expect(await journal.read()).toMatchObject({ value: replacement, google: { verified: false } });
|
||||
await journal.clear();
|
||||
}
|
||||
expect(request).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { access, readFile, stat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
|
||||
const account = vi.hoisted(() => {
|
||||
const refs = [{ configPath: "ai.credential", secretId: "22222222-2222-4222-8222-222222222222", versionSelector: "latest" }];
|
||||
return {
|
||||
refs,
|
||||
credential: "fixture-selected-google-key",
|
||||
selection: {
|
||||
grant: { id: "11111111-1111-4111-8111-111111111111", subjectUserId: "alice", credentialSecretRefs: refs },
|
||||
connection: { id: "33333333-3333-4333-8333-333333333333", name: "Google AI fixture", config: { ai: { provider: "google", method: "api_key" } } },
|
||||
attribution: { connectionId: "33333333-3333-4333-8333-333333333333", grantId: "11111111-1111-4111-8111-111111111111",
|
||||
provider: "google", method: "api_key", mode: "responsible_user", responsibleUserId: "alice" },
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// This fixture exercises real private-home preparation and deletion. The DB-backed
|
||||
// ai-connections suite separately checks membership, selected grants and revocation.
|
||||
vi.mock("../services/ai-connections.js", () => ({ aiConnectionService: () => ({
|
||||
select: async () => account.selection,
|
||||
runtimeCredential: async () => account.credential,
|
||||
}) }));
|
||||
vi.mock("../services/subscription-refresh.js", () => ({ refreshSubscriptionConnection: vi.fn() }));
|
||||
import { managedAiSessionFingerprintConfig, prepareManagedAiRuntime } from "../services/ai-connection-runtime.js";
|
||||
|
||||
describe("Antigravity private managed AI home", () => {
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
it("uses the selected key and explicit native auth settings, then deletes both private homes", async () => {
|
||||
vi.stubEnv("GEMINI_HOME", "/ambient/google-home");
|
||||
vi.stubEnv("GOOGLE_APPLICATION_CREDENTIALS", "/ambient/google-credentials.json");
|
||||
const version = [{ epoch: 1, version: 1 }];
|
||||
const db = { select: (fields: Record<string, unknown>) => ({ from: () => ({
|
||||
where: () => Object.assign(Promise.resolve("refs" in fields ? [{ refs: account.refs, status: "active" }] : version),
|
||||
{ limit: async () => version }),
|
||||
}) }) } as unknown as Db;
|
||||
const input = {
|
||||
companyId: "44444444-4444-4444-8444-444444444444", agentId: "55555555-5555-4555-8555-555555555555", responsibleUserId: "alice",
|
||||
adapterType: "paperclip_runner", binding: { provider: "google", method: "api_key", mode: "responsible_user" } as const,
|
||||
config: { provider: "acpx", acpxAgent: "antigravity", model: "caller-exact-model", env: {
|
||||
GEMINI_API_KEY: "fixture-ambient-key", GOOGLE_API_KEY: "fixture-other-key", GEMINI_HOME: "/ambient/configured-home",
|
||||
GOOGLE_APPLICATION_CREDENTIALS: "/ambient/configured-credentials.json", GOOGLE_CLOUD_ACCESS_TOKEN: "fixture-oauth-token",
|
||||
} },
|
||||
};
|
||||
const first = await prepareManagedAiRuntime(db, input);
|
||||
const second = await prepareManagedAiRuntime(db, input);
|
||||
try {
|
||||
expect(first.config).toMatchObject({ provider: "acpx", acpxAgent: "antigravity", model: "caller-exact-model", env: {
|
||||
GEMINI_API_KEY: account.credential, GOOGLE_API_KEY: "", GOOGLE_APPLICATION_CREDENTIALS: "", GOOGLE_CLOUD_ACCESS_TOKEN: "",
|
||||
} });
|
||||
expect(first.home).not.toBe(second.home);
|
||||
expect(first.config.env.GEMINI_HOME).toBe(path.join(first.home!, "provider"));
|
||||
const settingsPath = path.join(String(first.config.env.GEMINI_HOME), "antigravity-acp", "settings.json");
|
||||
expect(JSON.parse(await readFile(settingsPath, "utf8"))).toEqual({ auth: { type: "gemini-api-key" } });
|
||||
expect((await stat(settingsPath)).mode & 0o777).toBe(0o600);
|
||||
expect(managedAiSessionFingerprintConfig(first.config, first.home)).toEqual(managedAiSessionFingerprintConfig(second.config, second.home));
|
||||
expect(input.config.env.GEMINI_HOME).toBe("/ambient/configured-home");
|
||||
} finally { await Promise.all([first.cleanup(), second.cleanup()]); }
|
||||
await expect(access(first.home!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await expect(access(second.home!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
const mocks = vi.hoisted(() => ({ managed: vi.fn(), discover: vi.fn(), cleanup: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
CleanupError: class extends Error {
|
||||
constructor(readonly retired: Promise<void>) { super("cleanup pending"); }
|
||||
},
|
||||
}));
|
||||
vi.mock("../services/ai-connection-runtime.js", () => ({ prepareManagedAiRuntime: mocks.managed }));
|
||||
vi.mock("../middleware/logger.js", () => ({ logger: { warn: mocks.warn } }));
|
||||
vi.mock("../vendor/paperclip-runner/index.js", () => ({
|
||||
discoverAntigravityModels: mocks.discover, AntigravityModelDiscoveryCleanupError: mocks.CleanupError,
|
||||
}));
|
||||
import { antigravityConnectionModels } from "../services/antigravity-connection-models.js";
|
||||
import { RetiredCredentialRecoveryError } from "../services/quota-credential-recovery.js";
|
||||
import { reconcileRetainedGoogleCleanup } from "../services/retained-google-credential-cleanup.js";
|
||||
|
||||
const input = { companyId: "company", userId: "alice", binding: { provider: "google", method: "subscription", mode: "responsible_user" } as const,
|
||||
allowUninstalledShared: false };
|
||||
let sequence = 0;
|
||||
let scope = { companyId: "company", accountKey: "" };
|
||||
beforeEach(() => { vi.clearAllMocks(); scope = { companyId: "company", accountKey: `catalog-${++sequence}` }; mocks.cleanup.mockResolvedValue(undefined); mocks.managed.mockImplementation(async () => {
|
||||
await reconcileRetainedGoogleCleanup(scope);
|
||||
return {
|
||||
attribution: { method: "subscription" }, config: { env: { GEMINI_HOME: "/private/selected-google-home" } },
|
||||
cleanup: mocks.cleanup, retainedCleanupScope: scope,
|
||||
}; }); });
|
||||
afterEach(async () => { vi.useRealTimers(); mocks.cleanup.mockResolvedValue(undefined); await reconcileRetainedGoogleCleanup(scope); });
|
||||
|
||||
it("uses the selected account lifecycle and returns only its model catalog", async () => {
|
||||
const models = [{ id: "exact-google-model", label: "Google model" }];
|
||||
mocks.discover.mockResolvedValue({ models, defaultModelId: "exact-google-model" });
|
||||
expect(await antigravityConnectionModels({} as never, input)).toEqual(models);
|
||||
expect(mocks.managed).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
companyId: "company", responsibleUserId: "alice", adapterType: "paperclip_runner", binding: input.binding,
|
||||
allowUninstalledPersonal: true, allowUninstalledShared: false, config: { provider: "acpx", acpxAgent: "antigravity" },
|
||||
}));
|
||||
expect(mocks.discover).toHaveBeenCalledWith("/private/selected-google-home");
|
||||
expect(mocks.cleanup).toHaveBeenCalledExactlyOnceWith();
|
||||
});
|
||||
|
||||
it("does not disguise an API key or absent private home as Google subscription discovery", async () => {
|
||||
for (const runtime of [{ attribution: { method: "api_key" }, config: { env: { GEMINI_HOME: "/private/home" } } },
|
||||
{ attribution: { method: "subscription" }, config: { env: {} } }]) {
|
||||
mocks.managed.mockResolvedValue({ ...runtime, cleanup: mocks.cleanup });
|
||||
await expect(antigravityConnectionModels({} as never, input)).rejects.toThrow(/Google|model identifier/);
|
||||
}
|
||||
expect(mocks.discover).not.toHaveBeenCalled();
|
||||
expect(mocks.cleanup).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("preserves account-resolution denial and sanitizes native discovery errors", async () => {
|
||||
mocks.managed.mockRejectedValueOnce(new Error("membership denied"));
|
||||
await expect(antigravityConnectionModels({} as never, input)).rejects.toThrow("membership denied");
|
||||
expect(mocks.cleanup).not.toHaveBeenCalled();
|
||||
mocks.discover.mockRejectedValueOnce(new Error("provider-private-text"));
|
||||
await expect(antigravityConnectionModels({} as never, input)).rejects.toThrow("Could not load models");
|
||||
expect(mocks.cleanup).toHaveBeenCalledExactlyOnceWith();
|
||||
});
|
||||
|
||||
it("retains the selected credential home until uncertain native cleanup proves retirement", async () => {
|
||||
let retire!: () => void;
|
||||
const retired = new Promise<void>((resolve) => { retire = resolve; });
|
||||
mocks.discover.mockRejectedValueOnce(new mocks.CleanupError(retired));
|
||||
await expect(antigravityConnectionModels({} as never, input)).rejects.toThrow("Could not load models");
|
||||
expect(mocks.cleanup).not.toHaveBeenCalled();
|
||||
retire();
|
||||
await retired;
|
||||
await vi.waitFor(() => expect(mocks.cleanup).toHaveBeenCalledExactlyOnceWith());
|
||||
});
|
||||
|
||||
it.each(["success", "failure"])("retains storage failure after native discovery %s without background database retries", async outcome => {
|
||||
vi.useFakeTimers();
|
||||
if (outcome === "success") mocks.discover.mockResolvedValue({ models: [{ id: "exact-model", label: "Model" }] });
|
||||
else mocks.discover.mockRejectedValue(new Error("private-provider-token"));
|
||||
mocks.cleanup.mockRejectedValueOnce(new Error("private-provider-token database write failure"));
|
||||
await expect(antigravityConnectionModels({} as never, input)).rejects.toThrow("Could not complete Google account credential cleanup");
|
||||
expect(mocks.cleanup).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.managed).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.discover).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.warn).toHaveBeenCalledExactlyOnceWith({ companyId: "company", code: "ANTIGRAVITY_CATALOG_CREDENTIAL_CLEANUP_PENDING" },
|
||||
"Antigravity model-discovery credential cleanup is retained for recovery");
|
||||
await vi.advanceTimersByTimeAsync(90_000);
|
||||
expect(mocks.cleanup).toHaveBeenCalledTimes(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("waits for native retirement, then lets the durable journal own failed writeback without a retry loop", async () => {
|
||||
vi.useFakeTimers();
|
||||
let retire!: () => void;
|
||||
const retired = new Promise<void>(resolve => { retire = resolve; });
|
||||
mocks.discover.mockRejectedValueOnce(new mocks.CleanupError(retired));
|
||||
mocks.cleanup.mockRejectedValueOnce(new RetiredCredentialRecoveryError(new Error("private-token first failure")));
|
||||
await expect(antigravityConnectionModels({} as never, input)).rejects.toThrow("Could not load models");
|
||||
await vi.advanceTimersByTimeAsync(90_000);
|
||||
expect(mocks.cleanup).not.toHaveBeenCalled();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
retire();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(mocks.cleanup).toHaveBeenCalledTimes(1);
|
||||
await vi.advanceTimersByTimeAsync(90_000);
|
||||
expect(mocks.cleanup).toHaveBeenCalledTimes(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
expect(mocks.managed).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.discover).toHaveBeenCalledTimes(1);
|
||||
expect(JSON.stringify(mocks.warn.mock.calls)).not.toContain("private-token");
|
||||
});
|
||||
|
||||
it("settles the original failed journal cleanup before retrying model discovery", async () => {
|
||||
const order: string[] = [];
|
||||
mocks.discover.mockImplementation(async () => { order.push("provider"); return { models: [] }; });
|
||||
mocks.cleanup.mockImplementationOnce(async () => { order.push("journal-failed"); throw new Error("storage unavailable"); })
|
||||
.mockImplementation(async () => { order.push("journal-saved"); });
|
||||
await expect(antigravityConnectionModels({} as never, input)).rejects.toThrow("Could not complete Google account credential cleanup");
|
||||
await expect(antigravityConnectionModels({} as never, input)).resolves.toEqual([]);
|
||||
expect(order).toEqual(["provider", "journal-failed", "journal-saved", "provider", "journal-saved"]);
|
||||
});
|
||||
|
||||
it("blocks another provider launch while the original cleanup still cannot journal", async () => {
|
||||
mocks.discover.mockResolvedValue({ models: [] });
|
||||
mocks.cleanup.mockRejectedValue(new Error("storage unavailable"));
|
||||
await expect(antigravityConnectionModels({} as never, input)).rejects.toThrow("Could not complete Google account credential cleanup");
|
||||
await expect(antigravityConnectionModels({} as never, input)).rejects.toThrow("still completing credential cleanup");
|
||||
expect(mocks.discover).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.cleanup).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
import { access, mkdir, rm, stat } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { AdapterEnvironmentTestContext } from "@paperclipai/adapter-utils";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ probe: vi.fn(), admission: vi.fn(), credentials: vi.fn(), copyBack: vi.fn(), remove: vi.fn(), turn: vi.fn(), warn: vi.fn() }));
|
||||
vi.mock("../middleware/logger.js", () => ({ logger: { warn: mocks.warn } }));
|
||||
vi.mock("../vendor/paperclip-runner/index.js", async original => ({
|
||||
...await original<object>(), probeNativeRunnerEnvironment: mocks.probe,
|
||||
}));
|
||||
vi.mock("../services/native-runtime/acpx-qualification.js", () => ({ resolveAntigravityCandidateAdmission: mocks.admission }));
|
||||
vi.mock("../services/native-runtime/antigravity-runner-credentials.js", () => ({
|
||||
prepareAntigravityRunnerCredentials: mocks.credentials, antigravityCredentialTurn: mocks.turn,
|
||||
}));
|
||||
vi.mock("../services/native-runtime/native-codex-runner.js", () => ({ resolvePaperclipRunnerBinary: () => "/owned/runnerd" }));
|
||||
import { antigravityConnectionProbeFailure, testAntigravityConnection } from "../services/antigravity-connection-probe.js";
|
||||
import { NativeEnvironmentProbeCleanupError, resolveAcpxRuntimeRoot } from "../vendor/paperclip-runner/index.js";
|
||||
|
||||
const model = "exact-google-model";
|
||||
const admission = { agent: "antigravity", model, companyId: "company-1" };
|
||||
const roots: string[] = [];
|
||||
const context: AdapterEnvironmentTestContext = { companyId: "company-1", adapterType: "paperclip_runner",
|
||||
config: { provider: "acpx", acpxAgent: "antigravity", model, env: { GEMINI_HOME: "/selected/provider", PATH: "/selected/bin" } },
|
||||
managedAiCredentialHome: "/selected/provider", executionTarget: null,
|
||||
};
|
||||
const receipt = { provider: "acpx", providerDriver: "acpx_runtime", effectiveModel: model,
|
||||
sessionAdmissionPassed: true, admissionOnly: true, helloProbePassed: false };
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.admission.mockReturnValue(admission);
|
||||
mocks.credentials.mockImplementation(async input => ({ environment: { ...input.environment, PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "fixture-managed-credential" }, home: "/selected/provider", credential: "fixture-managed-credential" }));
|
||||
mocks.turn.mockImplementation(() => ({ copyBack: mocks.copyBack, remove: mocks.remove }));
|
||||
mocks.probe.mockImplementation(async options => {
|
||||
roots.push(options.runtimeDirectory);
|
||||
await options.onCleanupConfirmed();
|
||||
return receipt;
|
||||
});
|
||||
});
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs();
|
||||
await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
describe("Google Antigravity setup admission", () => {
|
||||
it("reports the observed installation failure with a repair action and only closed server diagnostics", () => {
|
||||
const privateValue = "fixture-private-token /private/selected-google-home";
|
||||
const error = new Error(privateValue);
|
||||
Object.defineProperty(error, "runnerCommandResult", { value: { commandType: "session.open", status: "failed", request: privateValue,
|
||||
result: { code: "command_execution_failed", message: "failed to start ACPX provider: ACPX sidecar command session.open was rejected (retryable=false, classification=admission_installation)" } } });
|
||||
const result = antigravityConnectionProbeFailure("company-1", error);
|
||||
expect(result).toMatchObject({ status: "fail", checks: [{ code: "antigravity_installation_check_failed",
|
||||
message: "Paperclip could not complete the local Google Antigravity installation check.", hint: expect.stringContaining("instance operator") }] });
|
||||
expect(mocks.warn).toHaveBeenCalledExactlyOnceWith({ companyId: "company-1", code: "antigravity_installation_check_failed",
|
||||
errorClass: "Error", commandCode: "command_execution_failed", classification: "admission_installation", retryable: false },
|
||||
"Antigravity installation check failed before account verification");
|
||||
expect(JSON.stringify([result, mocks.warn.mock.calls])).not.toMatch(/fixture-private-token|\/private\/selected-google-home/);
|
||||
expect(JSON.stringify(result)).not.toMatch(/reconnect|sign in/i);
|
||||
});
|
||||
|
||||
it("does not parse outer serialized errors or copy unknown codes, classes or native output", () => {
|
||||
const privateValue = "fixture-private-token /private/selected-google-home";
|
||||
for (const native of [{ code: privateValue, message: privateValue }, { code: "command_execution_failed",
|
||||
message: "failed to start ACPX provider: ACPX sidecar command session.open was rejected (retryable=false, classification=admission_installation)" + privateValue }]) {
|
||||
const nativeMessage = native.message;
|
||||
const error = new Error(`PRP command session.open failed: ${nativeMessage}`);
|
||||
error.name = privateValue;
|
||||
Object.defineProperty(error, "runnerCommandResult", { value: { commandType: "session.open", status: "failed",
|
||||
result: native } });
|
||||
const result = antigravityConnectionProbeFailure("company-1", error);
|
||||
expect(result.checks[0].code).toBe("antigravity_admission_failed");
|
||||
expect(JSON.stringify([result, mocks.warn.mock.calls])).not.toMatch(/fixture-private-token|\/private\/selected-google-home/);
|
||||
}
|
||||
const rawOnly = new Error('PRP command session.open failed: {"code":"command_execution_failed","classification":"admission_installation"}');
|
||||
expect(antigravityConnectionProbeFailure("company-1", rawOnly).checks[0].code).toBe("antigravity_admission_failed");
|
||||
});
|
||||
|
||||
it("preserves physical cleanup ownership instead of converting its typed error into a connection result", () => {
|
||||
const retired = Promise.resolve();
|
||||
const error = new NativeEnvironmentProbeCleanupError(retired, new Error("fixture-private-token"), [new Error("fixture private path")]);
|
||||
expect(() => antigravityConnectionProbeFailure("company-1", error)).toThrow(error);
|
||||
expect(mocks.warn).not.toHaveBeenCalled();
|
||||
expect(error.retired).toBe(retired);
|
||||
});
|
||||
|
||||
it("uses the selected managed account, exact candidate and a private runtime without a model turn", async () => {
|
||||
vi.stubEnv("GEMINI_API_KEY", "ambient-key-must-not-enter");
|
||||
vi.stubEnv("GOOGLE_APPLICATION_CREDENTIALS", "/ambient-google-credential");
|
||||
const order: string[] = [];
|
||||
mocks.copyBack.mockImplementation(async () => { order.push("copy-back"); });
|
||||
mocks.remove.mockImplementation(async () => { order.push("scrub"); });
|
||||
let root = "";
|
||||
mocks.probe.mockImplementation(async options => {
|
||||
root = options.runtimeDirectory; roots.push(root);
|
||||
expect((await stat(root)).mode & 0o777).toBe(0o700);
|
||||
expect((await stat(options.transportOptions.acpxRuntimeDirectory)).mode & 0o777).toBe(0o700);
|
||||
expect(options).toMatchObject({ provider: "acpx", model, admissionOnly: true,
|
||||
environment: { PATH: "/selected/bin", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "fixture-managed-credential" },
|
||||
transportOptions: { runnerBinary: "/owned/runnerd", acpxAgent: "antigravity", acpxCandidateAdmission: admission,
|
||||
acpxPermissionMode: "approve-reads", acpxPermissionModePinned: true } });
|
||||
expect(options.environment.GEMINI_API_KEY).toBeUndefined();
|
||||
expect(options.environment.GOOGLE_APPLICATION_CREDENTIALS).toBeUndefined();
|
||||
const identity = options.transportOptions.prpIdentity;
|
||||
const nativeHome = join(await resolveAcpxRuntimeRoot(options.transportOptions.acpxRuntimeDirectory, identity.normalizedSessionId), "antigravity-home");
|
||||
expect(mocks.turn).toHaveBeenCalledWith({ managedHome: "/selected/provider", runtimeHome: nativeHome, credential: "fixture-managed-credential" });
|
||||
await mkdir(nativeHome, { recursive: true });
|
||||
order.push("retired");
|
||||
await options.onCleanupConfirmed();
|
||||
await expect(access(root)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
return receipt;
|
||||
});
|
||||
const result = await testAntigravityConnection(context, model);
|
||||
expect(result.status).toBe("pass");
|
||||
expect(result.checks).toContainEqual(expect.objectContaining({ code: "antigravity_metadata_verified" }));
|
||||
expect(mocks.admission).toHaveBeenCalledExactlyOnceWith({ companyId: "company-1", model });
|
||||
expect(mocks.credentials).toHaveBeenCalledWith(expect.objectContaining({ managedHome: "/selected/provider", remote: false, lifecycleMode: "per_turn" }));
|
||||
expect(order).toEqual(["retired", "copy-back", "scrub"]);
|
||||
});
|
||||
|
||||
it.each(["effectiveModel", "providerDriver", "sessionAdmissionPassed", "admissionOnly", "helloProbePassed"] as const)("rejects a mismatched %s receipt after cleanup", async field => {
|
||||
mocks.probe.mockImplementation(async options => {
|
||||
roots.push(options.runtimeDirectory);
|
||||
await options.onCleanupConfirmed();
|
||||
return { ...receipt, [field]: typeof receipt[field] === "string" ? "different" : !receipt[field] };
|
||||
});
|
||||
await expect(testAntigravityConnection(context, model)).rejects.toThrow("no matching account and model admission receipt");
|
||||
expect(mocks.copyBack).toHaveBeenCalledOnce();
|
||||
expect(mocks.remove).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("rejects an unavailable company or remote target before reading credentials or launching native code", async () => {
|
||||
mocks.admission.mockReturnValue(undefined);
|
||||
await expect(testAntigravityConnection(context, model)).rejects.toThrow("not available for this company");
|
||||
await expect(testAntigravityConnection({ ...context, executionTarget: { kind: "remote" } as AdapterEnvironmentTestContext["executionTarget"] }, model))
|
||||
.rejects.toThrow("requires the Paperclip host");
|
||||
expect(mocks.credentials).not.toHaveBeenCalled();
|
||||
expect(mocks.probe).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,286 @@
|
||||
import { access, mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { AiConnectionLoginIntent } from "@paperclipai/shared";
|
||||
import type { LocalBrowserLoginState } from "../services/local-ai-browser-login.js";
|
||||
import { PgDialect } from "drizzle-orm/pg-core";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ root: vi.fn(), browser: vi.fn(), credential: vi.fn(), save: vi.fn(), notify: vi.fn(), activity: vi.fn() }));
|
||||
vi.mock("../home-paths.js", () => ({ resolvePaperclipInstanceRoot: mocks.root }));
|
||||
vi.mock("../services/local-ai-browser-login.js", () => ({ startLocalBrowserLogin: mocks.browser }));
|
||||
vi.mock("../services/local-ai-credentials.js", () => ({ readVerifiedLocalAiCredentialDetails: mocks.credential }));
|
||||
vi.mock("../services/ai-connections.js", () => ({ aiConnectionService: () => ({ save: mocks.save }) }));
|
||||
vi.mock("../services/delivery-work-notifications.js", () => ({ DELIVERY_QUEUES: { localLoginCleanup: "localLoginCleanup" }, notifyDeliveryWork: mocks.notify }));
|
||||
vi.mock("../services/activity-log.js", () => ({ logActivity: mocks.activity }));
|
||||
import { localAiLoginService } from "../services/local-ai-login.js";
|
||||
|
||||
const intent: AiConnectionLoginIntent = { provider: "google", method: "subscription", name: "Google account", ownership: "personal", allAgents: true, agentIds: [] };
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => { vi.useRealTimers(); await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); vi.clearAllMocks(); });
|
||||
|
||||
// This suite exercises service ordering with an explicit transaction result
|
||||
// queue. It does not replace database authorization/concurrency coverage; the
|
||||
// native child/Google protocol has its own controlled-process Runner suite.
|
||||
function database() {
|
||||
const selections: unknown[][] = [];
|
||||
let session: Record<string, any>;
|
||||
const db: any = {
|
||||
selections,
|
||||
expiredSessions: undefined as Record<string, any>[] | undefined,
|
||||
expiredReads: [] as Record<string, any>[],
|
||||
activeTransactions: 0,
|
||||
peakTransactions: 0,
|
||||
get session() { return session; },
|
||||
async transaction(run: (tx: unknown) => unknown) {
|
||||
db.activeTransactions += 1;
|
||||
db.peakTransactions = Math.max(db.peakTransactions, db.activeTransactions);
|
||||
try { return await run(db); }
|
||||
finally { db.activeTransactions -= 1; }
|
||||
},
|
||||
async execute() {},
|
||||
select(fields?: unknown) {
|
||||
let values: unknown[];
|
||||
let tableRows = false;
|
||||
if ((fields && db.expiredSessions) || db.expiryTable) {
|
||||
tableRows = true;
|
||||
values = [...db.expiredSessions];
|
||||
} else if (db.expiredReads.length) values = [db.expiredReads.shift()];
|
||||
else {
|
||||
if (!selections.length) throw new Error("Unexpected test database selection");
|
||||
values = selections.shift()!;
|
||||
}
|
||||
const result: any = { from: () => result, where: (condition: any) => {
|
||||
if (tableRows) {
|
||||
const query = new PgDialect().sqlToQuery(condition);
|
||||
const excluded = query.sql.includes("not in") ? query.params.filter(value => typeof value === "string" && value !== "local_subscription") : [];
|
||||
if (fields) values = values.filter((row: any) => row.expiresAt && !excluded.includes(row.id));
|
||||
else values = values.filter((row: any) => query.params.includes(row.id));
|
||||
if (query.sql.includes(" <= ")) values = values.filter((row: any) => row.expiresAt <= new Date());
|
||||
}
|
||||
return result;
|
||||
}, for: () => result, orderBy: () => result, limit: (count: number) => { values = values.slice(0, count); return result; },
|
||||
then: (resolve: (rows: unknown[]) => unknown, reject: (error: unknown) => unknown) => Promise.resolve(tableRows && fields
|
||||
? values.map((row: any) => (fields as any).at ? { at: row.expiresAt } : { id: row.id }) : values).then(resolve, reject) };
|
||||
return result;
|
||||
},
|
||||
insert() { return { async values(value: Record<string, unknown>) { session = { ...value, createdAt: new Date() }; } }; },
|
||||
update() { return { set(value: Record<string, unknown>) { return { async where(condition: any) {
|
||||
const params = new PgDialect().sqlToQuery(condition).params;
|
||||
const target = db.expiredSessions?.find((row: any) => params.includes(row.id)) ?? session;
|
||||
Object.assign(target, value);
|
||||
} }; } }; },
|
||||
};
|
||||
return db;
|
||||
}
|
||||
|
||||
async function fixture() {
|
||||
const root = await realpath(await mkdtemp(join(tmpdir(), "paperclip-google-local-login-service-"))); roots.push(root);
|
||||
mocks.root.mockReturnValue(root);
|
||||
let release: () => void;
|
||||
const retirement = new Promise<void>(resolve => { release = resolve; });
|
||||
const browser: LocalBrowserLoginState = { authorizationUrl: "https://accounts.google.com/fixture", abort: vi.fn(() => retirement) };
|
||||
mocks.browser.mockReturnValue(browser);
|
||||
mocks.credential.mockResolvedValue({ credential: "private-native-credential", accountLabel: "person@example.test" });
|
||||
mocks.save.mockResolvedValue({ connectionId: "connection-1", grantId: "grant-1" });
|
||||
const db = database(), service = localAiLoginService(db);
|
||||
db.selections.push([], [{ id: "local-environment", driver: "local", status: "active" }]);
|
||||
const attempt = await service.start("company", "user", intent);
|
||||
const home = join(root, "ai-local-logins", attempt.sessionId);
|
||||
return { db, service, browser, attempt, home, release: release! };
|
||||
}
|
||||
|
||||
describe("Google local sign-in service admission", () => {
|
||||
it("does not check or promote an early refresh-token file until native authenticate finishes", async () => {
|
||||
const f = await fixture();
|
||||
await mkdir(join(f.home, "antigravity-acp"), { mode: 0o700 });
|
||||
await writeFile(join(f.home, "antigravity-acp", "acp_token.json"), "early-native-token", { mode: 0o600 });
|
||||
f.db.selections.push([f.db.session]);
|
||||
expect(await f.service.check("company", "user", intent, f.attempt.sessionId)).toMatchObject({ status: "sign_in_required", authorizationUrl: f.browser.authorizationUrl });
|
||||
f.db.selections.push([f.db.session]);
|
||||
await expect(f.service.complete("company", "user", f.attempt.sessionId, intent)).rejects.toThrow("Finish Google browser sign-in");
|
||||
expect(mocks.credential).not.toHaveBeenCalled(); expect(mocks.save).not.toHaveBeenCalled();
|
||||
f.release(); f.db.selections.push([f.db.session], [f.db.session]); await f.service.cancel("company", "user", f.attempt.sessionId);
|
||||
});
|
||||
|
||||
it("returns the verified account email and passes it to the saved connection", async () => {
|
||||
const f = await fixture(); f.browser.outcome = "success";
|
||||
f.db.selections.push([f.db.session]);
|
||||
expect(await f.service.check("company", "user", intent, f.attempt.sessionId)).toEqual({ status: "ready", accountLabel: "person@example.test" });
|
||||
f.release(); f.db.selections.push([f.db.session]);
|
||||
expect(await f.service.complete("company", "user", f.attempt.sessionId, intent)).toEqual({ connectionId: "connection-1", grantId: "grant-1" });
|
||||
expect(mocks.save).toHaveBeenCalledWith("company", "user", intent, "private-native-credential", { id: f.attempt.sessionId }, expect.any(Date), undefined, "person@example.test");
|
||||
await expect(access(f.home)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it("requires a fresh browser exchange after server process state is lost", async () => {
|
||||
const db = database(), service = localAiLoginService(db);
|
||||
const session = { id: "unknown-browser-process", aiConnection: intent, status: "waiting_for_user", connectionMethod: "local_subscription", expiresAt: new Date(Date.now() + 60_000) };
|
||||
mocks.root.mockReturnValue(await realpath(tmpdir()));
|
||||
db.selections.push([session]);
|
||||
expect(await service.check("company", "user", intent, session.id)).toMatchObject({ status: "sign_in_required", error: "The server restarted during sign-in. Start sign-in again." });
|
||||
db.selections.push([session]);
|
||||
await expect(service.complete("company", "user", session.id, intent)).rejects.toThrow("Finish Google browser sign-in");
|
||||
expect(mocks.credential).not.toHaveBeenCalled(); expect(mocks.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("starts another user's provider without waiting for a globally expired Google browser", async () => {
|
||||
const f = await fixture();
|
||||
f.db.session.expiresAt = new Date(Date.now() - 1);
|
||||
const other = database(), otherService = localAiLoginService(other);
|
||||
other.expiredSessions = [f.db.session];
|
||||
other.selections.push([], [{ id: "local-environment", driver: "local", status: "active" }]);
|
||||
mocks.browser.mockReturnValue({ abort: vi.fn() });
|
||||
let attempt: Awaited<ReturnType<typeof otherService.start>> | undefined;
|
||||
let failure: unknown;
|
||||
const starting = otherService.start("another-company", "another-user", { ...intent, provider: "openai" })
|
||||
.then(result => { attempt = result; }, error => { failure = error; });
|
||||
try {
|
||||
await vi.waitFor(() => { if (failure) throw failure; expect(attempt).toBeDefined(); });
|
||||
expect(f.browser.abort).not.toHaveBeenCalled();
|
||||
await expect(access(f.home)).resolves.toBeUndefined();
|
||||
} finally {
|
||||
f.release(); await starting;
|
||||
f.db.selections.push([f.db.session], [f.db.session]); await f.service.cancel("company", "user", f.attempt.sessionId);
|
||||
if (attempt) { other.selections.push([other.session], [other.session]); await otherService.cancel("another-company", "another-user", attempt.sessionId); }
|
||||
}
|
||||
});
|
||||
|
||||
it("does not hold an expired attempt's database transaction while browser retirement is pending", async () => {
|
||||
const f = await fixture();
|
||||
f.db.session.expiresAt = new Date(Date.now() - 1);
|
||||
f.db.selections.push([{ id: f.attempt.sessionId }], [f.db.session]);
|
||||
const reaping = f.service.reapExpired();
|
||||
try {
|
||||
await vi.waitFor(() => expect(f.browser.abort).toHaveBeenCalledOnce());
|
||||
expect(f.db.activeTransactions).toBe(0);
|
||||
await expect(access(f.home)).resolves.toBeUndefined();
|
||||
} finally { f.release(); await reaping; }
|
||||
await expect(access(f.home)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it("starts retirement of other expired attempts while the first browser remains pending", async () => {
|
||||
const f = await fixture(), first = f.db.session;
|
||||
let release!: () => void;
|
||||
const retirement = new Promise<void>(resolve => { release = resolve; });
|
||||
const browser = { abort: vi.fn(() => retirement) };
|
||||
mocks.browser.mockReturnValue(browser);
|
||||
f.db.selections.push([], [{ id: "local-environment", driver: "local", status: "active" }]);
|
||||
const second = await f.service.start("company", "another-user", { ...intent, provider: "openai" });
|
||||
first.expiresAt = f.db.session.expiresAt = new Date(Date.now() - 1);
|
||||
f.db.selections.push([{ id: first.id }, { id: second.sessionId }], [first], [f.db.session]);
|
||||
const reaping = f.service.reapExpired();
|
||||
try {
|
||||
await vi.waitFor(() => { expect(f.browser.abort).toHaveBeenCalledOnce(); expect(browser.abort).toHaveBeenCalledOnce(); });
|
||||
expect(f.db.activeTransactions).toBe(0);
|
||||
await expect(access(f.home)).resolves.toBeUndefined();
|
||||
await expect(access(join(f.home, "..", second.sessionId))).resolves.toBeUndefined();
|
||||
} finally { f.release(); release(); await reaping; }
|
||||
await expect(access(f.home)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await expect(access(join(f.home, "..", second.sessionId))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it("bounds an expiry sweep and wakes the same worker only when retained physical retirement settles", async () => {
|
||||
const f = await fixture(), original = f.db.session;
|
||||
original.expiresAt = new Date(Date.now() - 1);
|
||||
const originalExpiry = original.expiresAt;
|
||||
f.db.expiredSessions = [original];
|
||||
f.db.expiryTable = true;
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
let settled = false;
|
||||
const reaping = f.service.reapExpired().then(() => { settled = true; });
|
||||
try {
|
||||
await vi.waitFor(() => expect(f.browser.abort).toHaveBeenCalledOnce());
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
expect(settled).toBe(true);
|
||||
expect(original.status).toBe("waiting_for_user");
|
||||
expect(original.expiresAt).toBe(originalExpiry);
|
||||
expect(f.db.activeTransactions).toBe(0);
|
||||
await expect(access(f.home)).resolves.toBeUndefined();
|
||||
const wake = vi.fn(), otherWake = vi.fn();
|
||||
const unsubscribe = f.service.subscribeCleanupReady(wake);
|
||||
const unsubscribeOther = localAiLoginService(database()).subscribeCleanupReady(otherWake);
|
||||
try {
|
||||
// Pending physical ownership has no retry deadline or recurring SQL.
|
||||
expect(await f.service.nextCleanupAt()).toBeNull();
|
||||
const later = { ...original, id: "later-expired-attempt", expiresAt: new Date(Date.now() - 1) };
|
||||
f.db.expiredSessions.push(later);
|
||||
await mkdir(join(f.home, "..", later.id), { mode: 0o700 });
|
||||
await f.service.reapExpired();
|
||||
expect(later.status).toBe("timed_out");
|
||||
expect(original.status).toBe("waiting_for_user");
|
||||
expect(wake).not.toHaveBeenCalled();
|
||||
expect(await f.service.nextCleanupAt()).toBeNull();
|
||||
f.release();
|
||||
await vi.waitFor(() => expect(wake).toHaveBeenCalledOnce());
|
||||
expect(otherWake).not.toHaveBeenCalled();
|
||||
expect(await f.service.nextCleanupAt()).toBe(originalExpiry.getTime());
|
||||
await f.service.reapExpired();
|
||||
expect(original.status).toBe("timed_out");
|
||||
await expect(access(f.home)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(await f.service.nextCleanupAt()).toBeNull();
|
||||
} finally { unsubscribe(); unsubscribeOther(); }
|
||||
} finally { f.release(); await reaping; }
|
||||
});
|
||||
|
||||
it("limits concurrent expiry cleanup transactions within a batch", async () => {
|
||||
const f = await fixture();
|
||||
f.release();
|
||||
const sessions = Array.from({ length: 16 }, (_, index) => ({ ...f.db.session,
|
||||
id: index ? `bounded-expiry-${index}` : f.attempt.sessionId, expiresAt: new Date(Date.now() - 1),
|
||||
}));
|
||||
await Promise.all(sessions.slice(1).map(session => mkdir(join(f.home, "..", session.id), { mode: 0o700 })));
|
||||
f.db.expiredSessions = sessions;
|
||||
f.db.expiryTable = true;
|
||||
await f.service.reapExpired();
|
||||
expect(sessions.every(session => session.status === "timed_out" && session.expiresAt === null)).toBe(true);
|
||||
expect(f.db.peakTransactions).toBeLessThanOrEqual(4);
|
||||
expect(await f.service.nextCleanupAt()).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["cancel", "restart"] as const)("bounds %s without holding a transaction and keeps the claim for maintenance", async action => {
|
||||
const f = await fixture();
|
||||
f.db.selections.push([f.db.session], [f.db.session]);
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
let result: unknown;
|
||||
const operation = (action === "cancel" ? f.service.cancel("company", "user", f.attempt.sessionId)
|
||||
: f.service.start("company", "user", intent, true)).then(value => { result = value; }, error => { result = error; });
|
||||
try {
|
||||
await vi.waitFor(() => expect(f.browser.abort).toHaveBeenCalledOnce());
|
||||
expect(f.db.activeTransactions).toBe(0);
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
await operation;
|
||||
expect(result).toMatchObject({ status: 422, details: { code: "ai_connection_busy" } });
|
||||
expect(f.db.session.status).toBe("waiting_for_user");
|
||||
expect(f.db.session.failureReason).toBe("local_login_retirement_pending");
|
||||
expect(f.db.session.expiresAt.getTime()).toBeLessThanOrEqual(Date.now());
|
||||
await expect(access(f.home)).resolves.toBeUndefined();
|
||||
} finally { vi.useRealTimers(); f.release(); await operation; }
|
||||
f.db.selections.push([{ id: f.attempt.sessionId }], [f.db.session]);
|
||||
await f.service.reapExpired();
|
||||
expect(f.db.session.status).toBe("cancelled");
|
||||
expect(f.db.session.expiresAt).toBeNull();
|
||||
await expect(access(f.home)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it.each(["cancel", "expiry", "restart", "complete"] as const)("awaits physical browser retirement before deleting the login home on %s", async action => {
|
||||
const f = await fixture();
|
||||
let operation: Promise<unknown>;
|
||||
if (action === "cancel") {
|
||||
f.db.selections.push([f.db.session], [f.db.session]); operation = f.service.cancel("company", "user", f.attempt.sessionId);
|
||||
} else if (action === "expiry") {
|
||||
f.db.session.expiresAt = new Date(Date.now() - 1);
|
||||
f.db.selections.push([{ id: f.attempt.sessionId }], [f.db.session]); operation = f.service.reapExpired();
|
||||
} else if (action === "restart") {
|
||||
f.db.selections.push([f.db.session], [f.db.session], [{ id: "local-environment", driver: "local", status: "active" }]);
|
||||
operation = f.service.start("company", "user", intent, true);
|
||||
} else {
|
||||
f.browser.outcome = "success";
|
||||
f.db.selections.push([f.db.session]); operation = f.service.complete("company", "user", f.attempt.sessionId, intent);
|
||||
}
|
||||
await vi.waitFor(() => expect(f.browser.abort).toHaveBeenCalledOnce());
|
||||
await expect(access(f.home)).resolves.toBeUndefined();
|
||||
f.release(); await operation;
|
||||
await expect(access(f.home)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,223 @@
|
||||
import { access, readFile, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { promises as fs } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
|
||||
const account = vi.hoisted(() => ({
|
||||
credential: "", epoch: 4, version: 8, status: "active",
|
||||
refs: [{ configPath: "ai.credential", secretId: "22222222-2222-4222-8222-222222222222", versionSelector: "latest" }],
|
||||
rotation: vi.fn(), locks: [] as string[],
|
||||
journal: undefined as undefined | Record<string, unknown>, journalWrite: vi.fn(),
|
||||
}));
|
||||
vi.mock("node:fs/promises", async importOriginal => {
|
||||
const actual = await importOriginal<typeof import("node:fs/promises")>();
|
||||
const { promises } = await import("node:fs");
|
||||
return { ...actual, rm: (...args: Parameters<typeof actual.rm>) => promises.rm(...args) };
|
||||
});
|
||||
const selection = () => ({
|
||||
grant: { id: "11111111-1111-4111-8111-111111111111", subjectUserId: "alice", credentialSecretRefs: account.refs, providerTenant: { name: "alice@example.test" } },
|
||||
connection: { id: "33333333-3333-4333-8333-333333333333", name: "Google account fixture", config: { ai: { provider: "google", method: "subscription" } } },
|
||||
attribution: { connectionId: "33333333-3333-4333-8333-333333333333", grantId: "11111111-1111-4111-8111-111111111111",
|
||||
provider: "google", method: "subscription", mode: "responsible_user", responsibleUserId: "alice" },
|
||||
});
|
||||
vi.mock("../services/ai-connections.js", () => ({ aiConnectionService: () => ({
|
||||
select: async () => selection(), runtimeCredential: async () => account.credential, credential: async () => account.credential,
|
||||
}) }));
|
||||
vi.mock("../services/subscriptions.js", () => ({ subscriptionService: () => ({ register: async () => "subscription-fixture" }) }));
|
||||
vi.mock("../services/subscription-refresh.js", () => ({ refreshSubscriptionConnection: vi.fn() }));
|
||||
vi.mock("../services/secrets.js", () => ({ secretService: () => ({ rotate: account.rotation }) }));
|
||||
vi.mock("../services/quota-credential-recovery.js", () => ({
|
||||
quotaCredentialHash: (value: string) => value,
|
||||
quotaCredentialRecovery: () => ({ read: async () => account.journal,
|
||||
write: account.journalWrite, clear: async () => { account.journal = undefined; } }),
|
||||
RetiredCredentialRecoveryError: class extends Error {
|
||||
constructor(cause: unknown) { super("The selected account credential is awaiting durable recovery. Retry shortly.", { cause }); }
|
||||
},
|
||||
}));
|
||||
vi.mock("@paperclipai/adapter-codex-local/server", () => ({
|
||||
decideCodexAuthMerge: vi.fn(), withAccountHomeSecretMutationLock: async (_environment: unknown, _companyId: unknown, work: () => Promise<void>) => work(),
|
||||
}));
|
||||
import { prepareManagedAiRuntime, withManagedAiProbe } from "../services/ai-connection-runtime.js";
|
||||
import { NativeEnvironmentProbeCleanupError } from "../vendor/paperclip-runner/index.js";
|
||||
|
||||
const credential = (project?: string, token = "fixture-selected-refresh") => 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"],
|
||||
...(project ? { project_id: project } : {}),
|
||||
});
|
||||
const homes: string[] = [];
|
||||
const runtimes: Awaited<ReturnType<typeof prepareManagedAiRuntime>>[] = [];
|
||||
function database(): Db {
|
||||
const db = {
|
||||
select: (fields?: Record<string, unknown>) => ({ from: () => ({ where: () => {
|
||||
const rows = !fields ? [{ ...selection().grant, status: account.status }]
|
||||
: "refs" in fields ? [{ refs: account.refs, status: account.status }]
|
||||
: [{ id: account.refs[0].secretId, epoch: account.epoch, version: account.version }];
|
||||
return Object.assign(Promise.resolve(rows), {
|
||||
limit: async () => rows,
|
||||
for: async (lock: string) => { account.locks.push(`${fields ? "secret" : "grant"}:${lock}`); return rows; },
|
||||
});
|
||||
} }) }),
|
||||
transaction: async (work: (transaction: Db) => Promise<void>) => work(db as unknown as Db),
|
||||
};
|
||||
return db as unknown as Db;
|
||||
}
|
||||
async function prepare() {
|
||||
const runtime = await prepareManagedAiRuntime(database(), {
|
||||
companyId: "44444444-4444-4444-8444-444444444444", agentId: "55555555-5555-4555-8555-555555555555", responsibleUserId: "alice",
|
||||
adapterType: "paperclip_runner", binding: { provider: "google", method: "subscription", mode: "responsible_user" },
|
||||
config: { provider: "acpx", acpxAgent: "antigravity", model: "caller-model", env: { GEMINI_API_KEY: "ambient", GEMINI_HOME: "/ambient" } },
|
||||
});
|
||||
homes.push(runtime.home!);
|
||||
runtimes.push(runtime);
|
||||
return runtime;
|
||||
}
|
||||
beforeEach(() => {
|
||||
account.credential = credential(); account.epoch = 4; account.version = 8; account.status = "active"; account.locks = [];
|
||||
account.refs = [{ configPath: "ai.credential", secretId: "22222222-2222-4222-8222-222222222222", versionSelector: "latest" }];
|
||||
account.rotation.mockReset().mockResolvedValue(undefined);
|
||||
account.journal = undefined;
|
||||
account.journalWrite.mockReset().mockImplementation(async value => { account.journal = value; });
|
||||
});
|
||||
afterEach(async () => {
|
||||
account.journalWrite.mockImplementation(async value => { account.journal = value; });
|
||||
vi.stubGlobal("fetch", vi.fn(async (url: string) => Response.json(url.includes("userinfo")
|
||||
? { email_verified: true, email: "alice@example.test" } : { access_token: "fixture-access", token_type: "Bearer" })));
|
||||
for (const runtime of runtimes.splice(0)) await runtime.cleanup().catch(() => undefined);
|
||||
vi.unstubAllGlobals();
|
||||
await Promise.all(homes.splice(0).map(path => rm(path, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
describe("managed Antigravity subscription projection and writeback", () => {
|
||||
it("returns a bounded cleanup diagnostic and retains the selected home until native retirement and refresh handoff", async () => {
|
||||
let confirmRetirement!: () => void;
|
||||
const retired = new Promise<void>(resolve => { confirmRetirement = resolve; });
|
||||
let home = "", token = "";
|
||||
const result = await withManagedAiProbe(database(), {
|
||||
companyId: "44444444-4444-4444-8444-444444444444", agentId: "55555555-5555-4555-8555-555555555555", responsibleUserId: "alice",
|
||||
adapterType: "paperclip_runner", binding: { provider: "google", method: "subscription", mode: "responsible_user" },
|
||||
config: { provider: "acpx", acpxAgent: "antigravity", model: "caller-model" },
|
||||
}, async runtime => {
|
||||
home = runtime.home!; homes.push(home);
|
||||
token = join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json");
|
||||
throw new NativeEnvironmentProbeCleanupError(retired, new Error("private fixture operation"), [new Error("fixture retirement is pending")]);
|
||||
}).catch(error => error);
|
||||
expect(result).toMatchObject({ status: 422, details: { code: "native_probe_cleanup_pending" } });
|
||||
expect(result.message).not.toContain("private fixture operation");
|
||||
expect(account.rotation).not.toHaveBeenCalled();
|
||||
expect(await readFile(token, "utf8")).toBe(credential());
|
||||
// The native owner completes its one refresh handoff before publishing exit.
|
||||
await writeFile(token, credential("retired-project"));
|
||||
confirmRetirement();
|
||||
await expect.poll(async () => access(home).then(() => false, () => true)).toBe(true);
|
||||
expect(account.rotation).toHaveBeenCalledExactlyOnceWith(account.refs[0].secretId,
|
||||
{ value: credential("retired-project"), preserveAiSessionEpoch: true }, { userId: "alice" });
|
||||
});
|
||||
it("writes a private native token with explicit OAuth settings and saves same-token project resolution under both row locks", async () => {
|
||||
const runtime = await prepare(), provider = String(runtime.config.env.GEMINI_HOME), token = join(provider, "antigravity-acp", "acp_token.json");
|
||||
expect(runtime.config.env).toMatchObject({ GEMINI_API_KEY: "", GOOGLE_API_KEY: "", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "" });
|
||||
expect(await readFile(token, "utf8")).toBe(credential());
|
||||
expect((await stat(token)).mode & 0o777).toBe(0o600);
|
||||
expect(JSON.parse(await readFile(join(provider, "antigravity-acp", "settings.json"), "utf8"))).toEqual({ auth: { type: "oauth-personal" } });
|
||||
await expect(access(join(provider, "auth.json"))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await writeFile(token, credential("resolved-project"));
|
||||
await runtime.cleanup();
|
||||
expect(account.locks).toEqual(["grant:update", "secret:update"]);
|
||||
expect(account.rotation).toHaveBeenCalledWith(account.refs[0].secretId,
|
||||
{ value: credential("resolved-project"), preserveAiSessionEpoch: true }, { userId: "alice" });
|
||||
await expect(access(runtime.home!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
it.each(["revoked", "remapped", "epoch", "version", "concurrent-refresh"] as const)("discards stale refreshes when the selected credential is %s", async change => {
|
||||
const runtime = await prepare(), token = join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json");
|
||||
await writeFile(token, credential("stale-project"));
|
||||
if (change === "revoked") account.status = "revoked";
|
||||
if (change === "remapped") account.refs = [{ ...account.refs[0], secretId: "66666666-6666-4666-8666-666666666666" }];
|
||||
if (change === "epoch") account.epoch += 1;
|
||||
if (change === "version") account.version += 1;
|
||||
if (change === "concurrent-refresh") account.credential = credential("saved-newer-project");
|
||||
await runtime.cleanup();
|
||||
expect(account.rotation).not.toHaveBeenCalled();
|
||||
await expect(access(runtime.home!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
it("transfers a retired refresh to the durable journal when the database write fails", async () => {
|
||||
const runtime = await prepare(), token = join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json");
|
||||
await writeFile(token, credential("resolved-project"));
|
||||
account.rotation.mockRejectedValueOnce(new Error("fixture database write failure"));
|
||||
await expect(runtime.cleanup()).rejects.toMatchObject({ cause: { message: "fixture database write failure" } });
|
||||
expect(account.journal).toMatchObject({ provider: "google", value: credential("resolved-project"),
|
||||
google: { sessionEpoch: 4, baseVersion: 8, verified: true, accountEmail: "alice@example.test" } });
|
||||
expect(account.rotation).toHaveBeenCalledTimes(1);
|
||||
await expect(access(runtime.home!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
it("retains the private refresh home when encrypted journal storage fails", async () => {
|
||||
const runtime = await prepare(), token = join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json");
|
||||
await writeFile(token, credential("resolved-project"));
|
||||
account.journalWrite.mockRejectedValueOnce(new Error("fixture journal unavailable"));
|
||||
await expect(runtime.cleanup()).rejects.toThrow("fixture journal unavailable");
|
||||
expect(await readFile(token, "utf8")).toBe(credential("resolved-project"));
|
||||
expect(account.rotation).not.toHaveBeenCalled();
|
||||
});
|
||||
it("finishes partial removal after durable handoff without rereading a removed token", async () => {
|
||||
const runtime = await prepare(), token = join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json");
|
||||
await writeFile(token, credential("resolved-project"));
|
||||
account.rotation.mockRejectedValueOnce(new Error("fixture database unavailable"));
|
||||
const realRm = fs.rm.bind(fs);
|
||||
let unavailable = true;
|
||||
const remove = vi.spyOn(fs, "rm").mockImplementation(async (...args: Parameters<typeof fs.rm>) => {
|
||||
if (unavailable && args[0] === runtime.home) {
|
||||
await realRm(token, { force: true });
|
||||
throw new Error("fixture partial removal");
|
||||
}
|
||||
return realRm(...args);
|
||||
});
|
||||
try {
|
||||
await expect(runtime.cleanup()).rejects.toThrow("fixture partial removal");
|
||||
expect(account.journal).toMatchObject({ value: credential("resolved-project"), google: { verified: true } });
|
||||
unavailable = false;
|
||||
await runtime.cleanup();
|
||||
await expect(access(runtime.home!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(account.rotation).toHaveBeenCalledOnce();
|
||||
} finally { unavailable = false; remove.mockRestore(); }
|
||||
});
|
||||
it("retains the latest verified rotation when replacing its earlier journal fails", async () => {
|
||||
const runtime = await prepare(), token = join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json");
|
||||
await writeFile(token, credential("resolved-project", "fixture-first-rotation"));
|
||||
const request = vi.fn().mockResolvedValueOnce(Response.json({ access_token: "fixture-access", token_type: "Bearer", refresh_token: "fixture-latest-rotation" }))
|
||||
.mockResolvedValueOnce(Response.json({ email_verified: true, email: "alice@example.test" }));
|
||||
vi.stubGlobal("fetch", request);
|
||||
account.journalWrite.mockImplementationOnce(async value => { account.journal = value; })
|
||||
.mockRejectedValueOnce(new Error("fixture latest journal unavailable"));
|
||||
await expect(runtime.cleanup()).rejects.toThrow();
|
||||
expect(await readFile(token, "utf8")).toBe(credential("resolved-project", "fixture-latest-rotation"));
|
||||
expect(account.journal).toMatchObject({ value: credential("resolved-project", "fixture-first-rotation"), google: { verified: false } });
|
||||
expect(account.rotation).not.toHaveBeenCalled();
|
||||
account.rotation.mockImplementationOnce(async (_secretId, input) => { account.credential = input.value; account.version += 1; });
|
||||
request.mockResolvedValueOnce(Response.json({ access_token: "fixture-access", refresh_token: "fixture-retry-rotation" }))
|
||||
.mockResolvedValueOnce(Response.json({ email_verified: true, email: "alice@example.test" }));
|
||||
const next = await prepare();
|
||||
expect(new URLSearchParams(request.mock.calls[2][1].body).get("refresh_token")).toBe("fixture-latest-rotation");
|
||||
expect(await readFile(join(String(next.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json"), "utf8"))
|
||||
.toBe(credential("resolved-project", "fixture-retry-rotation"));
|
||||
await expect(access(runtime.home!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
it.each(["alice@example.test", "other@example.test"])("verifies %s before a changed refresh token can reach the database", async email => {
|
||||
const runtime = await prepare(), token = join(String(runtime.config.env.GEMINI_HOME), "antigravity-acp", "acp_token.json");
|
||||
await writeFile(token, credential("resolved-project", "fixture-rotated-refresh"));
|
||||
const request = vi.fn().mockResolvedValueOnce(Response.json({ access_token: "fixture-access", token_type: "Bearer" }))
|
||||
.mockResolvedValueOnce(Response.json({ email_verified: true, email }));
|
||||
vi.stubGlobal("fetch", request);
|
||||
if (email === "alice@example.test") {
|
||||
await runtime.cleanup();
|
||||
expect(account.rotation).toHaveBeenCalledWith(account.refs[0].secretId,
|
||||
{ value: credential("resolved-project", "fixture-rotated-refresh"), preserveAiSessionEpoch: true }, { userId: "alice" });
|
||||
await expect(access(runtime.home!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} else {
|
||||
await expect(runtime.cleanup()).rejects.toThrow("The refreshed Google account does not match the selected connection.");
|
||||
expect(account.rotation).not.toHaveBeenCalled();
|
||||
expect(account.locks).toEqual([]);
|
||||
expect(account.journal).toMatchObject({ provider: "google", google: { verified: false }, value: credential("resolved-project", "fixture-rotated-refresh") });
|
||||
expect(await readFile(token, "utf8")).toBe(credential("resolved-project", "fixture-rotated-refresh"));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -137,6 +137,7 @@ import { agentConfigurationDoc as piAgentConfigurationDoc } from "@paperclipai/a
|
||||
import { BUILTIN_ADAPTER_TYPES } from "./builtin-adapter-types.js";
|
||||
import { buildExternalAdapters } from "./plugin-loader.js";
|
||||
import { getDisabledAdapterTypes } from "../services/adapter-plugin-store.js";
|
||||
import { NativeEnvironmentProbeCleanupError } from "../vendor/paperclip-runner/index.js";
|
||||
import { processAdapter } from "./process/index.js";
|
||||
import { httpAdapter } from "./http/index.js";
|
||||
import {
|
||||
@@ -417,7 +418,7 @@ const paperclipRunnerAdapter: ServerAdapterModule = {
|
||||
async testEnvironment(context) {
|
||||
let profile: ReturnType<typeof resolvePaperclipRunnerProviderProfile>;
|
||||
try {
|
||||
profile = resolvePaperclipRunnerProviderProfile(context.config);
|
||||
profile = resolvePaperclipRunnerProviderProfile(context.config, { companyId: context.companyId });
|
||||
} catch (error) {
|
||||
const profileError = error instanceof PaperclipRunnerProviderProfileError
|
||||
? error
|
||||
@@ -449,6 +450,10 @@ const paperclipRunnerAdapter: ServerAdapterModule = {
|
||||
}
|
||||
if (profile.provider === "acpx") {
|
||||
try {
|
||||
if (profile.acpxAgent === "antigravity") {
|
||||
const { testAntigravityConnection } = await import("../services/antigravity-connection-probe.js");
|
||||
return await testAntigravityConnection(context, profile.model);
|
||||
}
|
||||
if (profile.acpxAgent === "copilot") {
|
||||
const configured = context.config.env;
|
||||
const token = configured && typeof configured === "object" && !Array.isArray(configured)
|
||||
@@ -488,6 +493,13 @@ const paperclipRunnerAdapter: ServerAdapterModule = {
|
||||
checks: [{ code: "acpx_runtime_ready", level: "info" as const, message: `ACPX ${profile.acpxAgent} runtime is installed and verified. Model access is checked when it runs.` }],
|
||||
});
|
||||
} catch (error) {
|
||||
// The selected managed credential home must outlive an uncertain
|
||||
// native retirement. Its caller retains writeback until proof arrives.
|
||||
if (error instanceof NativeEnvironmentProbeCleanupError) throw error;
|
||||
if (profile.acpxAgent === "antigravity") {
|
||||
const { antigravityConnectionProbeFailure } = await import("../services/antigravity-connection-probe.js");
|
||||
return antigravityConnectionProbeFailure(context.companyId, error);
|
||||
}
|
||||
if (profile.acpxAgent === "copilot") {
|
||||
const details = error instanceof HttpError && error.details && typeof error.details === "object" && !Array.isArray(error.details)
|
||||
? error.details as Record<string, unknown> : {};
|
||||
|
||||
+6
-1
@@ -1363,11 +1363,16 @@ async function startServerWithDatabaseTeardown(
|
||||
if (skillVersionRetentionWorker) trackHeartbeatSchedulerWork(skillVersionRetentionWorker.ready);
|
||||
const workspaceRecoveryWork = registerWorkspaceRecoveryWork(db, deliveryWork, workspaceRecoveryRuntime,
|
||||
accountingHeartbeat.resumeRemoteStopComments, () => !heartbeatSchedulerStopped);
|
||||
const localLoginCleanup = localAiLoginService(db);
|
||||
const localLoginCleanupWork = registerExecutionControlWork(deliveryWork, [
|
||||
{ queue: DELIVERY_QUEUES.localLoginCleanup, run: localLoginCleanup.reapExpired, next: localLoginCleanup.nextCleanupAt },
|
||||
], () => !heartbeatSchedulerStopped);
|
||||
const unsubscribeLocalLoginCleanup = localLoginCleanup.subscribeCleanupReady(localLoginCleanupWork.wake);
|
||||
server.on("close", unsubscribeLocalLoginCleanup);
|
||||
registerExecutionControlWork(deliveryWork, [
|
||||
{ queue: DELIVERY_QUEUES.executionFinalization, run: () => reconcileAbandonedExecutionControl(db), next: executionSchedule.finalization },
|
||||
{ queue: DELIVERY_QUEUES.executionStatus, run: () => deliverExecutionStatuses(db), next: executionSchedule.status },
|
||||
{ queue: DELIVERY_QUEUES.executionDisposition, run: () => settleUnrecoverableExecutions(db), next: executionSchedule.disposition },
|
||||
{ queue: DELIVERY_QUEUES.localLoginCleanup, run: () => localAiLoginService(db).reapExpired(), next: executionSchedule.localLogin },
|
||||
...(heartbeat ? [
|
||||
{ queue: DELIVERY_QUEUES.executionReplacement, run: () => reconcileSafeNativeReplacements(db, new Date(), { verifyStoppedSession: run => verifyStoppedNativeSessionForReplacement(db, run) }), next: executionSchedule.replacement },
|
||||
{ queue: DELIVERY_QUEUES.executionContinuation, run: () => deliverReconciledExecutions(db, heartbeat.wakeup), next: executionSchedule.continuation },
|
||||
|
||||
@@ -55,8 +55,10 @@ import { assertBoardOrgAccess, assertCompanyAccess, assertInstanceAdmin } from "
|
||||
import { BUILTIN_ADAPTER_TYPES } from "../adapters/builtin-adapter-types.js";
|
||||
import { agentRunnerAvailability, type RunnerTarget } from "../services/agent-runner-selection.js";
|
||||
import type { AgentRunnerAvailability } from "@paperclipai/shared";
|
||||
import { resolveAntigravityCandidateAdmission } from "../services/native-runtime/acpx-qualification.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
let warnedMalformedAntigravityAdmission = false;
|
||||
|
||||
/**
|
||||
* Floor: on cloud-managed instances adapter code is bundled into the platform
|
||||
@@ -127,6 +129,7 @@ interface AdapterCapabilities {
|
||||
}
|
||||
|
||||
interface AdapterInfo extends AgentRunnerAvailability {
|
||||
candidateHarnesses?: Array<{ agent: "antigravity"; model: string }>;
|
||||
type: string;
|
||||
label: string;
|
||||
source: "builtin" | "external";
|
||||
@@ -304,9 +307,26 @@ export function adapterRoutes(options: {
|
||||
// One shared implementation, with independent provider rollouts. Explicit
|
||||
// adapter-admin disabling still applies to both choices.
|
||||
|
||||
const result: AdapterInfo[] = registeredAdapters.map((adapter) =>
|
||||
buildAdapterInfo(adapter, externalRecords.get(adapter.type), disabledSet, target),
|
||||
).sort((a, b) => a.type.localeCompare(b.type));
|
||||
let candidate: ReturnType<typeof resolveAntigravityCandidateAdmission>;
|
||||
if (typeof companyId === "string" && target?.driver === "local") {
|
||||
// An expired optional preview must not hide the ordinary adapter catalog.
|
||||
// Execution and model discovery still perform strict admission checks.
|
||||
try { candidate = resolveAntigravityCandidateAdmission({ companyId }); }
|
||||
catch (error) {
|
||||
candidate = undefined;
|
||||
// Expiry is ordinary catalog state. Invalid trusted startup JSON needs
|
||||
// one operator diagnostic, without logging its payload or error.
|
||||
if (!warnedMalformedAntigravityAdmission && error instanceof Error && error.message === "Invalid Antigravity candidate admission") {
|
||||
warnedMalformedAntigravityAdmission = true;
|
||||
logger.warn({ code: "ANTIGRAVITY_CANDIDATE_ADMISSION_INVALID" }, "Invalid Google Antigravity preview authorization");
|
||||
}
|
||||
}
|
||||
}
|
||||
const result: AdapterInfo[] = registeredAdapters.map((adapter) => ({
|
||||
...buildAdapterInfo(adapter, externalRecords.get(adapter.type), disabledSet, target),
|
||||
...(candidate && adapter.type === "paperclip_runner" && !disabledSet.has(adapter.type) && !externalRecords.has(adapter.type)
|
||||
? { candidateHarnesses: [{ agent: "antigravity" as const, model: candidate.model }] } : {}),
|
||||
})).sort((a, b) => a.type.localeCompare(b.type));
|
||||
|
||||
res.json(result);
|
||||
});
|
||||
|
||||
+55
-12
@@ -40,6 +40,8 @@ import {
|
||||
import { toolConnections } from "@paperclipai/db";
|
||||
import { aiConnectionService } from "../services/ai-connections.js";
|
||||
import { probeCopilotConnection, probeCopilotExecutionTarget } from "../services/copilot-connection-probe.js";
|
||||
import { antigravityConnectionModels } from "../services/antigravity-connection-models.js";
|
||||
import { resolveAntigravityCandidateAdmission } from "../services/native-runtime/acpx-qualification.js";
|
||||
import { defaultAiConnectionForHire } from "../services/agent-ai-connection-default.js";
|
||||
import { assertAiConnectionCreateAccess, canInstallSharedAiConnectionForNewAgent, responsibleUserForAiRequest } from "./ai-connections.js";
|
||||
import { isAiConnectionCompatible } from "@paperclipai/shared";
|
||||
@@ -47,7 +49,7 @@ import { applyConnectorSkills, resolveConnectorAssignments, annotateConnectorSki
|
||||
import { getExecutionBlocker } from "../services/execution-blocker.js";
|
||||
import { canRetryStoppedRun } from "../services/cancelled-native-startup.js";
|
||||
import { getNativeReviewAssignment, readNativeReviewAssignmentContext, type NativeReviewAssignmentContext } from "../services/native-runtime/native-review-participant.js";
|
||||
import { paperclipRunnerTransitionConfig, normalizeLegacyRunnerProvider, isPaperclipRunnerProvider } from "@paperclipai/adapter-utils";
|
||||
import { paperclipRunnerTransitionConfig, normalizeLegacyRunnerProvider, isPaperclipRunnerProvider, PAPERCLIP_RUNNER_ACPX_PROFILES } from "@paperclipai/adapter-utils";
|
||||
import { applyMcpReasoningEffort } from "../services/public-mcp/agent-config.js";
|
||||
import { executionProjectionForRun, executionProjectionsForRuns } from "../services/execution-projection.js";
|
||||
import { selectDashboardRunIds } from "../services/dashboard-run-selection.js";
|
||||
@@ -1870,10 +1872,17 @@ export function agentRoutes(
|
||||
* (listEnabledServerAdapters documents the same rule: hidden from selection,
|
||||
* still functional for agents that already use them).
|
||||
*/
|
||||
async function assertSelectableAdapterType(type: string | null | undefined, config?: unknown): Promise<string> {
|
||||
async function assertSelectableAdapterType(type: string | null | undefined, config?: unknown, companyId?: string): Promise<string> {
|
||||
const adapterType = assertKnownAdapterType(type);
|
||||
if (adapterType === "paperclip_runner") {
|
||||
const experimental = await instanceSettings.getExperimental();
|
||||
const selected = asRecord(config);
|
||||
let antigravityCandidate: ReturnType<typeof resolveAntigravityCandidateAdmission>;
|
||||
if (companyId && selected?.provider === "acpx" && selected.acpxAgent === "antigravity"
|
||||
&& typeof selected.model === "string" && selected.model.trim()) {
|
||||
try { antigravityCandidate = resolveAntigravityCandidateAdmission({ companyId, model: selected.model }); }
|
||||
catch { throw unprocessable("This Google Antigravity candidate requires the exact enabled model and a current operator authorization.", { code: "paperclip_runner_antigravity_candidate_invalid" }); }
|
||||
}
|
||||
if (asRecord(config)?.provider === "openai_dot") {
|
||||
if (experimental.enableOpenAiDot !== true) throw unprocessable(
|
||||
"OpenAI Dot is experimental and disabled on this instance.",
|
||||
@@ -1886,7 +1895,7 @@ export function agentRoutes(
|
||||
} else if (!([undefined, "codex", "opencode"].includes(asRecord(config)?.provider as string | undefined)) &&
|
||||
!(asRecord(config)?.provider === "acpx" && asRecord(config)?.acpxAgent === "copilot") &&
|
||||
!["claude_local", "pi_local", "grok_local"].includes(agentHarnessType("paperclip_runner", asRecord(config) ?? {})) &&
|
||||
experimental.enableNativeRunner !== true) {
|
||||
experimental.enableNativeRunner !== true && !antigravityCandidate) {
|
||||
throw unprocessable(
|
||||
"Paperclip Runner is experimental and disabled on this instance.",
|
||||
{ code: "paperclip_runner_rollout_disabled" },
|
||||
@@ -1921,7 +1930,7 @@ export function agentRoutes(
|
||||
validatePaperclipRunnerDotConfig(adapterConfig, false);
|
||||
return;
|
||||
}
|
||||
profile = resolvePaperclipRunnerProviderProfile(adapterConfig);
|
||||
profile = resolvePaperclipRunnerProviderProfile(adapterConfig, { companyId });
|
||||
} catch (error) {
|
||||
if (error instanceof PaperclipRunnerProviderProfileError) {
|
||||
throw unprocessable(error.message, { code: error.code });
|
||||
@@ -3044,6 +3053,13 @@ export function agentRoutes(
|
||||
const companyId = req.params.companyId as string;
|
||||
assertCompanyAccess(req, companyId);
|
||||
const type = assertKnownAdapterType(req.params.type as string);
|
||||
const pendingAcpxProfile = type === "paperclip_runner" && req.query.provider === "acpx"
|
||||
? PAPERCLIP_RUNNER_ACPX_PROFILES.find(profile => profile.value === req.query.acpxAgent && !profile.qualified)
|
||||
: undefined;
|
||||
// Antigravity's setup-only catalog cannot open a session or send a prompt.
|
||||
// Its execution/save/Test gates continue to require a qualified profile.
|
||||
if (pendingAcpxProfile && req.query.acpxAgent !== "antigravity") throw unprocessable(`${pendingAcpxProfile.label} is awaiting native Runner acceptance. Its profile is not enabled for production runs.`,
|
||||
{ code: "paperclip_runner_acpx_agent_unavailable" });
|
||||
const poolId = asNonEmptyString(req.query.poolId);
|
||||
if (poolId) {
|
||||
const pool = (await aiConnectionRouterService(db).selectable(companyId, responsibleUserForAiRequest(req) ?? "")).find(pool => pool.id === poolId);
|
||||
@@ -3069,6 +3085,31 @@ export function agentRoutes(
|
||||
return;
|
||||
}
|
||||
const provider = asNonEmptyString(req.query.provider);
|
||||
if (type === "paperclip_runner" && provider === "acpx" && req.query.acpxAgent === "antigravity") {
|
||||
if (environment && environment.driver !== "local") throw unprocessable("Google Antigravity account model discovery requires the Paperclip host.");
|
||||
let binding: AiConnectionBinding = { provider: "google", method: "subscription", mode: "responsible_user" };
|
||||
if (typeof req.query.aiConnection === "string") {
|
||||
if (req.query.aiConnection.length > 4096) throw unprocessable("Invalid AI connection binding");
|
||||
try { binding = aiConnectionBindingSchema.parse(JSON.parse(req.query.aiConnection)); }
|
||||
catch { throw unprocessable("Invalid AI connection binding"); }
|
||||
}
|
||||
if (binding.provider !== "google") throw unprocessable("Select a Google runtime connection");
|
||||
const modelAgentId = asNonEmptyString(req.query.agentId);
|
||||
if (modelAgentId) {
|
||||
const modelAgent = await svc.getById(modelAgentId);
|
||||
if (!modelAgent || modelAgent.companyId !== companyId) throw notFound("Agent not found");
|
||||
await assertCanUpdateAgent(req, modelAgent);
|
||||
if (modelAgent.defaultEnvironmentId && !environmentId) {
|
||||
const target = await environmentsSvc.getById(modelAgent.defaultEnvironmentId);
|
||||
if (!target || target.driver !== "local") throw unprocessable("Google Antigravity account model discovery requires the Paperclip host.");
|
||||
}
|
||||
} else await assertCanCreateAgentsForCompany(req, companyId);
|
||||
const allowUninstalledShared = !modelAgentId && await canInstallSharedAiConnectionForNewAgent(db, req, companyId, binding);
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
res.json(await antigravityConnectionModels(db, { companyId, userId: responsibleUserForAiRequest(req),
|
||||
agentId: modelAgentId ?? undefined, binding, allowUninstalledShared }));
|
||||
return;
|
||||
}
|
||||
if (type === "paperclip_runner" && provider === "acpx" && req.query.acpxAgent === "copilot") {
|
||||
const userId = responsibleUserForAiRequest(req);
|
||||
let binding: AiConnectionBinding = { provider: "github", method: "api_key", mode: "responsible_user" };
|
||||
@@ -3191,7 +3232,8 @@ export function agentRoutes(
|
||||
try {
|
||||
if (!target.executionTarget && target.fallbackChecks.length > 0) throw unprocessable("The agent environment is not available for adoption");
|
||||
await withManagedAiProbe(db, { companyId, agentId, responsibleUserId: userId, adapterType, binding, config, allowUninstalledPersonal: newAgent, allowUninstalledShared, allowLegacyValidation: true }, async managed => {
|
||||
const managedAiCredentialHome = adapterType === "paperclip_runner" && asRecord(managed.config)?.provider === "codex" && managed.home
|
||||
const managedAiCredentialHome = adapterType === "paperclip_runner" && (asRecord(managed.config)?.provider === "codex"
|
||||
|| (asRecord(managed.config)?.provider === "acpx" && asRecord(managed.config)?.acpxAgent === "antigravity")) && managed.home
|
||||
? path.join(managed.home, "provider") : undefined;
|
||||
const result = await testManagedEnvironment(adapterType, { companyId, adapterType, config: managed.config, managedAiCredentialHome, executionTarget: target.executionTarget, environmentName: target.environmentName }, binding, managed, agentId);
|
||||
if (binding.provider === "github" && result.status === "fail") {
|
||||
@@ -3285,7 +3327,7 @@ export function agentRoutes(
|
||||
adapterConfigForTest = selection.adapterConfig;
|
||||
if (requestedEnvironment) await assertAdapterTestEnvironmentForCompany(companyId, requestedEnvironment.id, type);
|
||||
const adapter = requireServerAdapter(type);
|
||||
if (!retainsSavedExecution) await assertSelectableAdapterType(type, adapterConfigForTest);
|
||||
if (!retainsSavedExecution) await assertSelectableAdapterType(type, adapterConfigForTest, companyId);
|
||||
if (poolBinding?.mode === "router") {
|
||||
await validateManagedAgentBinding(req, companyId, savedAgentId ?? "", type, adapterConfigForTest, poolBinding, requestedEnvironmentId, false, !savedAgentId || testingSetup);
|
||||
res.json({ adapterType: type, status: "warn", testedAt: new Date().toISOString(), checks: [{ code: "ai_connection_pool_task_test_required", level: "warn", message: "Pool configuration is available. Run a task to verify the selected account and harness; this preview does not allocate a task or contact a provider." }] });
|
||||
@@ -3438,7 +3480,8 @@ export function agentRoutes(
|
||||
}
|
||||
}
|
||||
const result = aiBinding ? await withManagedAiProbe(db, { companyId, agentId: req.body.agentId ?? "", responsibleUserId: responsibleUserForAiRequest(req), adapterType: type, binding: aiBinding, config: effectiveAdapterConfig, allowUninstalledPersonal: !savedAgentId || testingSetup, allowUninstalledShared: (!savedAgentId || testingSetup) && await canInstallSharedAiConnectionForNewAgent(db, req, companyId, aiBinding) }, async managed => {
|
||||
const managedAiCredentialHome = type === "paperclip_runner" && asRecord(managed.config)?.provider === "codex" && managed.home
|
||||
const managedAiCredentialHome = type === "paperclip_runner" && (asRecord(managed.config)?.provider === "codex"
|
||||
|| (asRecord(managed.config)?.provider === "acpx" && asRecord(managed.config)?.acpxAgent === "antigravity")) && managed.home
|
||||
? path.join(managed.home, "provider") : undefined;
|
||||
const tested = await testManagedEnvironment(type, { companyId, adapterType: type, config: managed.config, managedAiCredentialHome, executionTarget, environmentName }, aiBinding, managed, savedAgentId ?? undefined);
|
||||
tested.checks.unshift({ code: "ai_connection_tested", level: "info", message: `Tested ${managed.accountName} — ${managed.accountOwnerUserId ? managed.accountOwnerUserId === responsibleUserForAiRequest(req) ? "your personal account" : "the owner’s account authorized for this agent" : "company-shared account"}. Responsible user: ${req.actor.type === "agent" ? responsibleUserForAiRequest(req) ?? "unavailable" : "the signed-in user"}.` });
|
||||
@@ -4223,7 +4266,7 @@ export function agentRoutes(
|
||||
if (rollbackAdapterType !== existing.adapterType || (rollbackAdapterType === "paperclip_runner"
|
||||
&& rollbackAdapterConfig.provider !== existingRollbackProvider
|
||||
&& (["openai_dot", "muse"].includes(String(rollbackAdapterConfig.provider)) || ["openai_dot", "muse"].includes(String(existingRollbackProvider))))) {
|
||||
await assertSelectableAdapterType(rollbackAdapterType, rollbackAdapterConfig);
|
||||
await assertSelectableAdapterType(rollbackAdapterType, rollbackAdapterConfig, existing.companyId);
|
||||
}
|
||||
assertNoAgentAdapterConfigMutation(req, rollbackAdapterConfig);
|
||||
if (req.actor.type === "agent" && rollbackAdapterConfig.homeMode !== asRecord(existing.adapterConfig)?.homeMode)
|
||||
@@ -4434,7 +4477,7 @@ export function agentRoutes(
|
||||
let configurationWarnings: AgentConfigurationWarning[] = [];
|
||||
Object.assign(hireInput, await resolveNewAgentRunnerForCompany(db, companyId, { ...hireInput, runner: hireRunner,
|
||||
onConfigurationWarnings: warnings => { configurationWarnings = warnings; } }));
|
||||
hireInput.adapterType = await assertSelectableAdapterType(hireInput.adapterType, hireInput.adapterConfig);
|
||||
hireInput.adapterType = await assertSelectableAdapterType(hireInput.adapterType, hireInput.adapterConfig, companyId);
|
||||
const rawHireAdapterConfig = (hireInput.adapterConfig ?? {}) as Record<string, unknown>;
|
||||
assertProviderTraceSettingTransition(req, hireInput.runtimeConfig);
|
||||
await assertFreshPaperclipRunnerProvider(
|
||||
@@ -4771,7 +4814,7 @@ export function agentRoutes(
|
||||
let configurationWarnings: AgentConfigurationWarning[] = [];
|
||||
Object.assign(createInput, await resolveNewAgentRunnerForCompany(db, companyId, { ...createInput, runner: createRunner, setupOnly: Boolean(setupId),
|
||||
onConfigurationWarnings: warnings => { configurationWarnings = warnings; } }));
|
||||
createInput.adapterType = await assertSelectableAdapterType(createInput.adapterType, createInput.adapterConfig);
|
||||
createInput.adapterType = await assertSelectableAdapterType(createInput.adapterType, createInput.adapterConfig, companyId);
|
||||
const rawCreateAdapterConfig = (createInput.adapterConfig ?? {}) as Record<string, unknown>;
|
||||
assertProviderTraceSettingTransition(req, createInput.runtimeConfig);
|
||||
if (!setupId) await assertFreshPaperclipRunnerProvider(
|
||||
@@ -5470,7 +5513,7 @@ export function agentRoutes(
|
||||
: existing.adapterType;
|
||||
const requestedAdapterType = nextAdapterType === existing.adapterType
|
||||
? nextAdapterType
|
||||
: await assertSelectableAdapterType(nextAdapterType, patchData.adapterConfig);
|
||||
: await assertSelectableAdapterType(nextAdapterType, patchData.adapterConfig, existing.companyId);
|
||||
let requestedRuntimeConfig: Record<string, unknown> | null = null;
|
||||
if (hasOwn(patchData, "runtimeConfig")) {
|
||||
const runtimeConfig = asRecord(patchData.runtimeConfig);
|
||||
@@ -5564,7 +5607,7 @@ export function agentRoutes(
|
||||
if (!changingAdapterType && requestedAdapterType === "paperclip_runner"
|
||||
&& rawEffectiveAdapterConfig.provider !== existingRunnerProvider
|
||||
&& (["openai_dot", "muse"].includes(String(rawEffectiveAdapterConfig.provider)) || ["openai_dot", "muse"].includes(String(existingRunnerProvider)))) {
|
||||
await assertSelectableAdapterType(requestedAdapterType, rawEffectiveAdapterConfig);
|
||||
await assertSelectableAdapterType(requestedAdapterType, rawEffectiveAdapterConfig, existing.companyId);
|
||||
}
|
||||
if (!isAgentSetupDraft(existing) && (
|
||||
changingAdapterType ||
|
||||
|
||||
@@ -36,6 +36,40 @@ function verifiedClaude() {
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
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();
|
||||
|
||||
@@ -533,6 +533,14 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin
|
||||
|
||||
async function testManagedEnvironment(adapterType: string, context: Parameters<ReturnType<typeof requireServerAdapter>["testEnvironment"]>[0], binding: AiConnectionBinding, managed: Awaited<ReturnType<typeof prepareManagedAiRuntime>>, agentId?: string) {
|
||||
const startedAt = new Date();
|
||||
if (adapterType === "paperclip_runner" && binding.provider === "google" && context.config.provider === "acpx"
|
||||
&& context.config.acpxAgent === "antigravity" && managed.home) {
|
||||
const selectedHome = join(managed.home, "provider");
|
||||
if (context.managedAiCredentialHome && context.managedAiCredentialHome !== selectedHome) {
|
||||
throw unprocessable("The Google runtime credential home does not match the selected managed account.");
|
||||
}
|
||||
context = { ...context, managedAiCredentialHome: selectedHome };
|
||||
}
|
||||
const target = context.executionTarget;
|
||||
if (managed.credentialWriteback && target?.kind === "remote" && target.transport === "sandbox" && target.runnerTask && target.leaseId) {
|
||||
await registerPluginTaskCredentialHandoff(db, { companyId: context.companyId, leaseId: target.leaseId }, managed.sessionIdentity, managed.credentialWriteback);
|
||||
@@ -552,7 +560,7 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin
|
||||
return result;
|
||||
}
|
||||
|
||||
async function probeManagedEnvironment(adapterType: string, context: Parameters<ReturnType<typeof requireServerAdapter>["testEnvironment"]>[0], binding: AiConnectionBinding, managed: Awaited<ReturnType<typeof prepareManagedAiRuntime>>) {
|
||||
async function probeManagedEnvironment(adapterType: string, context: Parameters<ReturnType<typeof requireServerAdapter>["testEnvironment"]>[0], binding: AiConnectionBinding, managed: Awaited<ReturnType<typeof prepareManagedAiRuntime>>): Promise<AdapterEnvironmentTestResult> {
|
||||
if (binding.provider === "github") {
|
||||
try {
|
||||
const token = parseObject(context.config.env).COPILOT_GITHUB_TOKEN;
|
||||
@@ -572,6 +580,13 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin
|
||||
home: managed.home ? join(managed.home, "provider") : undefined })
|
||||
: await requireServerAdapter(adapterType).testEnvironment(context);
|
||||
if (result.status === "fail") return result;
|
||||
// Antigravity's native admission checks the selected managed account and
|
||||
// exact model without a billable turn. Do not invoke another Google CLI.
|
||||
if (adapterType === "paperclip_runner" && context.config.provider === "acpx" && context.config.acpxAgent === "antigravity") {
|
||||
if (result.status === "pass" && result.checks.some(check => check.code === "antigravity_metadata_verified" && check.level === "info")) return result;
|
||||
return { ...result, status: "fail", checks: [...result.checks, { code: "ai_connection_validation_incomplete", level: "error",
|
||||
message: "The selected Google account has not completed native account and model verification. Retry before adopting it." }] };
|
||||
}
|
||||
// The resolved method, not binding.method — on a responsible_user binding
|
||||
// that field is wire-compat only and the default connection decides.
|
||||
if (adapterType === "paperclip_runner" && context.executionTarget?.kind === "remote"
|
||||
|
||||
@@ -26,6 +26,14 @@ describe("AI authentication failure recovery", () => {
|
||||
it("offers Google's supported API-key method for Gemini recovery", () => {
|
||||
expect(aiBindingForAuthRecovery("gemini_local", {})).toEqual({ provider: "google", method: "api_key", mode: "responsible_user" });
|
||||
});
|
||||
it("offers Google subscription recovery for native Antigravity", () => {
|
||||
expect(aiBindingForAuthRecovery("paperclip_runner", { provider: "acpx", acpxAgent: "antigravity" }))
|
||||
.toEqual({ provider: "google", method: "subscription", mode: "responsible_user" });
|
||||
});
|
||||
it("offers an API key for a Google model in Pi", () => {
|
||||
expect(aiBindingForAuthRecovery("pi_local", { model: "google/fixture-model" }))
|
||||
.toEqual({ provider: "google", method: "api_key", mode: "responsible_user" });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
import { environmentTaskResultSchema } from "@paperclipai/plugin-sdk";
|
||||
import type { PluginTaskCredentialWritebackBinding } from "./plugin-task-credential-writeback.js";
|
||||
import { OPENROUTER_ATTRIBUTION_HEADERS, openRouterClaudeHeaders } from "@paperclipai/shared/openrouter-attribution";
|
||||
import { createHash } from "node:crypto";
|
||||
import { HttpError, unprocessable } from "../errors.js";
|
||||
import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises";
|
||||
import { mkdtemp, mkdir, writeFile, readFile, realpath, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
@@ -23,6 +24,11 @@ import { WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE } from "@paperclipai/adapter-utils/
|
||||
import type { AdapterExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
|
||||
import { runAdapterExecutionTargetProcess } from "@paperclipai/adapter-utils/execution-target";
|
||||
import { decideGrokAuthMerge } from "@paperclipai/adapter-grok-local/server";
|
||||
import { NativeEnvironmentProbeCleanupError, sanitizeAntigravityCredential } from "../vendor/paperclip-runner/index.js";
|
||||
import { readLocalAiCredentialFile } from "./local-ai-credential-file.js";
|
||||
import { prepareAntigravityCredentialWriteback } from "./native-runtime/antigravity-runner-credentials.js";
|
||||
import { quotaCredentialHash, quotaCredentialRecovery, RetiredCredentialRecoveryError } from "./quota-credential-recovery.js";
|
||||
import { assertAiCredentialCleanupSettled, bindRetainedAiCredentialHome, reconcileRetainedAiCleanup, retainAiCredentialCleanup, type RetainedAiCleanupScope } from "./retained-ai-credential-cleanup.js";
|
||||
|
||||
export function isAiConnectionBusy(error: unknown): error is HttpError {
|
||||
return error instanceof HttpError && error.status === 422 &&
|
||||
@@ -34,6 +40,7 @@ export const AI_AUTH_ENV_KEYS = [
|
||||
"COPILOT_GITHUB_TOKEN",
|
||||
"PAPERCLIP_AI_PROVIDER_KEY", "PAPERCLIP_AI_PROVIDER_URL", "PAPERCLIP_CODEX_PROVIDERS",
|
||||
"GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GEMINI_BASE_URL", "GOOGLE_GENAI_USE_VERTEXAI",
|
||||
"GEMINI_HOME", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_ACCESS_TOKEN", "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET",
|
||||
"HERMES_HOME", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_BEARER_TOKEN_BEDROCK", "AWS_PROFILE", "AWS_DEFAULT_PROFILE", "AWS_SHARED_CREDENTIALS_FILE", "AWS_CONFIG_FILE", "AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_ROLE_ARN", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI",
|
||||
"ANTHROPIC_BEDROCK_BASE_URL", "ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL",
|
||||
|
||||
@@ -213,15 +220,23 @@ export function managedAiSessionFingerprintConfig(
|
||||
for (const [key, value] of Object.entries(managedAiHomeEnvironment(managedHome))) {
|
||||
if (env[key] === value) env[key] = stable[key];
|
||||
}
|
||||
if (env.GEMINI_HOME === path.join(managedHome, "provider")) env.GEMINI_HOME = path.join("<managed-ai-home>", "provider");
|
||||
const managed = config.managedAiConnection as Record<string, unknown> | undefined;
|
||||
if (managed?.sessionIdentity) {
|
||||
for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY", "CODEX_API_KEY", "OPENROUTER_API_KEY", "XAI_API_KEY", "GROK_API_KEY", "OPENCODE_AUTH_JSON", "OPENCODE_CONFIG_CONTENT"]) {
|
||||
for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY", "CODEX_API_KEY", "OPENROUTER_API_KEY", "XAI_API_KEY", "GROK_API_KEY", "GEMINI_API_KEY", "GOOGLE_API_KEY", "OPENCODE_AUTH_JSON", "OPENCODE_CONFIG_CONTENT"]) {
|
||||
if (env[key]) env[key] = "<managed-ai-credential>";
|
||||
}
|
||||
}
|
||||
return { ...config, env, ...(managed?.sessionIdentity ? { managedAiConnection: { ...managed, identity: managed.sessionIdentity } } : {}) };
|
||||
}
|
||||
|
||||
const managedProbeCredentialLocks = new AsyncLocalStorage<{ companyId: string; active: boolean }>();
|
||||
async function reconcileManagedCredentialCleanup(scope: RetainedAiCleanupScope): Promise<void> {
|
||||
const ownership = managedProbeCredentialLocks.getStore();
|
||||
if (ownership?.active && ownership.companyId === scope.companyId) assertAiCredentialCleanupSettled(scope);
|
||||
else await reconcileRetainedAiCleanup(scope);
|
||||
}
|
||||
|
||||
export async function prepareManagedAiRuntime(
|
||||
db: Db,
|
||||
input: {
|
||||
@@ -266,10 +281,13 @@ export async function prepareManagedAiRuntime(
|
||||
runnerProvider: input.config.provider,
|
||||
acpxAgent: input.config.acpxAgent,
|
||||
});
|
||||
const retainedCleanupScope = { companyId: input.companyId, accountKey: selection.grant.id };
|
||||
await reconcileManagedCredentialCleanup(retainedCleanupScope);
|
||||
const subscriptionFile =
|
||||
selection.attribution.method === "subscription" &&
|
||||
input.binding.provider !== "anthropic";
|
||||
let home: string | undefined;
|
||||
let releaseCredentialHome: (() => void) | undefined;
|
||||
try {
|
||||
const selectedGrantId = selection.grant.id;
|
||||
selection = await service.select({
|
||||
@@ -303,7 +321,9 @@ export async function prepareManagedAiRuntime(
|
||||
// against a concurrent reconnect or explicit rotation.
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
const before = await readFreshness();
|
||||
const value = await service.runtimeCredential(selection);
|
||||
const ownership = managedProbeCredentialLocks.getStore();
|
||||
const value = await service.runtimeCredential(selection,
|
||||
ownership?.active && ownership.companyId === input.companyId ? { credentialLockHeld: true } : undefined);
|
||||
const after = await readFreshness();
|
||||
if (before && after && before.version === after.version && before.epoch === after.epoch) {
|
||||
return { value, freshness: after };
|
||||
@@ -312,14 +332,18 @@ export async function prepareManagedAiRuntime(
|
||||
}
|
||||
throw unprocessable("The AI credential changed during preparation; retry this execution");
|
||||
})();
|
||||
const antigravitySubscription = harness === "antigravity_runtime" && selection.attribution.method === "subscription";
|
||||
const originalCredential = antigravitySubscription ? sanitizeAntigravityCredential(value) : value;
|
||||
home = await mkdtemp(
|
||||
path.join(
|
||||
os.tmpdir(),
|
||||
`paperclip-ai-${input.companyId}-${selection.grant.id}-`,
|
||||
),
|
||||
);
|
||||
if (harness === "antigravity_runtime") home = await realpath(home);
|
||||
const providerHome = path.join(home, "provider");
|
||||
await mkdir(providerHome, { mode: 0o700 });
|
||||
if (retainedCleanupScope) releaseCredentialHome = bindRetainedAiCredentialHome(providerHome, retainedCleanupScope);
|
||||
const env: Record<string, unknown> = {
|
||||
...stripAiAuthBindings(input.config.env),
|
||||
...Object.fromEntries(AI_AUTH_ENV_KEYS.map((key) => [key, ""])),
|
||||
@@ -330,15 +354,17 @@ export async function prepareManagedAiRuntime(
|
||||
AI_CONNECTION_CAPABILITIES[input.binding.provider].methods[
|
||||
selection.attribution.method
|
||||
]!;
|
||||
const authFile = path.join(providerHome, "auth.json");
|
||||
const authFile = antigravitySubscription
|
||||
? path.join(providerHome, "antigravity-acp", "acp_token.json")
|
||||
: path.join(providerHome, "auth.json");
|
||||
if (harness === "codex_local")
|
||||
await writeFile(
|
||||
path.join(providerHome, "config.toml"),
|
||||
'cli_auth_credentials_store = "file"\n',
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
if (!routing && subscriptionFile) await writeFile(authFile, value, { mode: 0o600 });
|
||||
else if (!routing) env[capability.envKey] = value;
|
||||
if (!routing && subscriptionFile && !antigravitySubscription) await writeFile(authFile, value, { mode: 0o600 });
|
||||
else if (!routing && !subscriptionFile) env[capability.envKey] = value;
|
||||
if (
|
||||
!routing && input.binding.provider === "openai" && harness === "codex_local" &&
|
||||
selection.attribution.method === "api_key"
|
||||
@@ -364,6 +390,17 @@ export async function prepareManagedAiRuntime(
|
||||
security: { auth: { selectedType: "gemini-api-key" } },
|
||||
}), { mode: 0o600 });
|
||||
}
|
||||
if (harness === "antigravity_runtime") {
|
||||
// Native Antigravity reads this explicit auth selection beneath GEMINI_HOME.
|
||||
// The selected AI connection owns this disposable home, not a browser login.
|
||||
env.GEMINI_HOME = providerHome;
|
||||
const antigravityHome = path.join(providerHome, "antigravity-acp");
|
||||
await mkdir(antigravityHome, { mode: 0o700 });
|
||||
await writeFile(path.join(antigravityHome, "settings.json"), JSON.stringify({
|
||||
auth: { type: antigravitySubscription ? "oauth-personal" : "gemini-api-key" },
|
||||
}), { mode: 0o600 });
|
||||
if (antigravitySubscription) await writeFile(authFile, originalCredential, { mode: 0o600 });
|
||||
}
|
||||
const projected = routing ? managedProviderRouting(routing, harness, value, typeof input.config.model === "string" ? input.config.model : "") : undefined;
|
||||
if (projected) {
|
||||
const customHeaders = env.ANTHROPIC_CUSTOM_HEADERS ?? process.env.ANTHROPIC_CUSTOM_HEADERS;
|
||||
@@ -390,13 +427,186 @@ export async function prepareManagedAiRuntime(
|
||||
void refreshSubscriptionConnection(db, subscription, attribution.subscriptionId);
|
||||
}
|
||||
const generation = createHash("sha256")
|
||||
.update(value)
|
||||
.update(originalCredential)
|
||||
.digest("hex")
|
||||
.slice(0, 16);
|
||||
const identity = `${selection.grant.id}:${input.responsibleUserId ?? "shared"}:${generation}`;
|
||||
const sessionIdentity = `${selection.grant.id}:${input.responsibleUserId ?? "shared"}:${noAuth ? "no-auth" : `${credentialRef!.secretId}:${freshness!.epoch}`}`;
|
||||
let homeRemoved = false;
|
||||
let ownsGoogleRecovery = false;
|
||||
let removalOnly = false;
|
||||
let deferredWriteback: { cause: unknown } | undefined;
|
||||
const removeHome = async () => {
|
||||
if (home) await rm(home, { recursive: true, force: true });
|
||||
homeRemoved = true;
|
||||
releaseCredentialHome?.();
|
||||
};
|
||||
const cleanupRuntime = async () => {
|
||||
if (homeRemoved) return;
|
||||
await reconcileManagedCredentialCleanup(retainedCleanupScope);
|
||||
if (homeRemoved) return;
|
||||
const cleanup = async () => {
|
||||
if (removalOnly) {
|
||||
await removeHome();
|
||||
if (deferredWriteback) throw new RetiredCredentialRecoveryError(deferredWriteback.cause);
|
||||
return;
|
||||
}
|
||||
let googleRecovery: ReturnType<typeof quotaCredentialRecovery> | undefined;
|
||||
let durableGoogleRefresh = false;
|
||||
try {
|
||||
if (subscriptionFile) {
|
||||
const incoming = antigravitySubscription
|
||||
? sanitizeAntigravityCredential(await readLocalAiCredentialFile(authFile)) : undefined;
|
||||
if (antigravitySubscription && incoming !== originalCredential) {
|
||||
const accountEmail = selection.grant.providerTenant?.name;
|
||||
if (!credentialRef || !freshness || !accountEmail) throw new Error("The selected Google credential recovery authority is unavailable");
|
||||
googleRecovery = quotaCredentialRecovery(input.companyId, selection.grant.id);
|
||||
const prior = await googleRecovery.read();
|
||||
if (prior && prior.value !== incoming && !ownsGoogleRecovery) {
|
||||
// A previous retired owner keeps its first recoverable refresh.
|
||||
// Settle it before this owner can stage another generation.
|
||||
await aiConnectionService(db).runtimeCredential(selection, { credentialLockHeld: true });
|
||||
}
|
||||
// Physical retirement is the caller's cleanup precondition. Save
|
||||
// before network verification or a database write can fail; only
|
||||
// this exact grant generation may later consume the encrypted copy.
|
||||
await googleRecovery.write({ companyId: input.companyId, grantId: selection.grant.id,
|
||||
connectionId: selection.connection.id, secretId: credentialRef.secretId,
|
||||
baseHash: quotaCredentialHash(value), value: incoming!, provider: "google",
|
||||
google: { sessionEpoch: freshness.epoch, baseVersion: freshness.version,
|
||||
versionSelector: credentialRef.versionSelector ?? "latest", accountEmail, verified: false } });
|
||||
ownsGoogleRecovery = true;
|
||||
}
|
||||
// Verification itself can consume a rotating refresh. Until its
|
||||
// newest result is durably journaled, the private home owns it.
|
||||
durableGoogleRefresh = false;
|
||||
const refreshed = antigravitySubscription
|
||||
? await prepareAntigravityCredentialWriteback({ originalCredential,
|
||||
refreshedCredential: incoming!, managedHome: providerHome,
|
||||
accountEmail: selection.grant.providerTenant?.name,
|
||||
})
|
||||
: await readFile(authFile, "utf8");
|
||||
if (googleRecovery) {
|
||||
const pending = await googleRecovery.read();
|
||||
if (!pending?.google) throw new Error("The Google credential recovery journal is unavailable");
|
||||
await googleRecovery.write({ ...pending, value: refreshed, google: { ...pending.google, verified: true } });
|
||||
durableGoogleRefresh = true;
|
||||
}
|
||||
if (refreshed !== originalCredential) {
|
||||
// A quota exchange can hold this company lock for 60 seconds.
|
||||
// Retry its 30-second acquisition timeout without discarding the
|
||||
// provider's only copy of a rotated, single-use refresh token.
|
||||
const writeBack = () => withAccountHomeSecretMutationLock(undefined, input.companyId, () => db.transaction(async (tx) => {
|
||||
const [grant] = await tx
|
||||
.select()
|
||||
.from(connectionGrants)
|
||||
.where(
|
||||
and(
|
||||
eq(connectionGrants.id, selection.grant.id),
|
||||
eq(connectionGrants.companyId, input.companyId),
|
||||
),
|
||||
)
|
||||
.for("update");
|
||||
// A missing or revoked grant blocks the write-back. Among
|
||||
// active copies, the merge decision below keeps the
|
||||
// credential with the newest provider freshness field.
|
||||
if (!grant || grant.status !== "active") return;
|
||||
const ref = grant.credentialSecretRefs.find(
|
||||
(r) => r.configPath === "ai.credential",
|
||||
);
|
||||
if (!ref) return;
|
||||
if (antigravitySubscription && (!credentialRef || ref.secretId !== credentialRef.secretId
|
||||
|| ref.versionSelector !== credentialRef.versionSelector
|
||||
|| grant.providerTenant?.name?.toLowerCase() !== selection.grant.providerTenant?.name?.toLowerCase())) return;
|
||||
// Lock the referenced secret row for the rest of this
|
||||
// transaction. The grant-row lock above does not cover it,
|
||||
// so an authorized rotation of this secret could otherwise
|
||||
// land between the read and the write below and be
|
||||
// overwritten by this stale write-back.
|
||||
const [currentSecret] = await tx
|
||||
.select({ id: companySecrets.id, epoch: companySecrets.aiSessionEpoch, version: companySecrets.latestVersion })
|
||||
.from(companySecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(companySecrets.id, ref.secretId),
|
||||
eq(companySecrets.companyId, input.companyId),
|
||||
),
|
||||
)
|
||||
.for("update");
|
||||
if (antigravitySubscription && (!freshness || !currentSecret || currentSecret.epoch !== freshness.epoch
|
||||
|| currentSecret.version !== freshness.version)) return;
|
||||
const current = await aiConnectionService(
|
||||
tx as unknown as Db,
|
||||
).credential({ ...selection, grant });
|
||||
if (antigravitySubscription) {
|
||||
// Google refresh tokens have no provider freshness counter. Only
|
||||
// the exact selected generation may replace itself; a reconnect,
|
||||
// rotation, grant remap or concurrent refresh wins over this run.
|
||||
if (sanitizeAntigravityCredential(current) !== originalCredential) return;
|
||||
await secretService(tx).rotate(ref.secretId,
|
||||
{ value: refreshed, preserveAiSessionEpoch: true }, { userId: grant.subjectUserId });
|
||||
return;
|
||||
}
|
||||
const destination = path.join(
|
||||
providerHome,
|
||||
"current-auth.json",
|
||||
);
|
||||
await writeFile(destination, current, { mode: 0o600 });
|
||||
const decision =
|
||||
input.binding.provider === "openai"
|
||||
? await decideCodexAuthMerge(authFile, destination, {
|
||||
errorLabel: "AI account refresh",
|
||||
})
|
||||
: await decideGrokAuthMerge(authFile, destination, {
|
||||
errorLabel: "AI account refresh",
|
||||
});
|
||||
if (decision !== 10) return;
|
||||
await secretService(tx).rotate(
|
||||
ref.secretId,
|
||||
{ value: refreshed, preserveAiSessionEpoch: true },
|
||||
{ userId: grant.subjectUserId },
|
||||
);
|
||||
// Keep grant.updatedAt for explicit account/access changes.
|
||||
// The rotated secret revision invalidates quota caches without
|
||||
// rejecting an otherwise valid in-flight reconnect.
|
||||
}));
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try { await writeBack(); break; }
|
||||
catch (error) {
|
||||
if (attempt >= 2 || (error as NodeJS.ErrnoException)?.code !== WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE) throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
await googleRecovery?.clear();
|
||||
// A committed save, intentional generation discard, or encrypted
|
||||
// recovery handoff must own the refresh before deleting its home.
|
||||
removalOnly = true;
|
||||
await removeHome();
|
||||
} catch (error) {
|
||||
if (!durableGoogleRefresh && !removalOnly) throw error;
|
||||
// Once native retirement and encrypted fsync transfer ownership, the
|
||||
// original controller/home is unnecessary for next-use recovery.
|
||||
if (!removalOnly) {
|
||||
removalOnly = true;
|
||||
deferredWriteback = { cause: error };
|
||||
}
|
||||
await removeHome();
|
||||
if (deferredWriteback) throw new RetiredCredentialRecoveryError(deferredWriteback.cause);
|
||||
}
|
||||
};
|
||||
// Journal writes and generation checks share the same reconnect fence.
|
||||
try {
|
||||
return await (antigravitySubscription
|
||||
? withAccountHomeSecretMutationLock(undefined, input.companyId, cleanup) : cleanup());
|
||||
} catch (error) {
|
||||
if (retainedCleanupScope && !homeRemoved) retainAiCredentialCleanup({ scope: retainedCleanupScope, cleanup: cleanupRuntime });
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
return {
|
||||
sessionIdentity,
|
||||
...(retainedCleanupScope ? { retainedCleanupScope } : {}),
|
||||
...(subscriptionFile && input.binding.provider === "openai" && credentialRef && freshness ? {
|
||||
credentialWriteback: { grantId: selection.grant.id, secretId: credentialRef.secretId, sessionEpoch: freshness.epoch,
|
||||
versionSelector: credentialRef.versionSelector ?? "latest" } satisfies PluginTaskCredentialWritebackBinding,
|
||||
@@ -413,90 +623,11 @@ export async function prepareManagedAiRuntime(
|
||||
accountOwnerUserId: selection.grant.subjectUserId,
|
||||
identity,
|
||||
home,
|
||||
cleanup: async () => {
|
||||
if (subscriptionFile) {
|
||||
const refreshed = await readFile(authFile, "utf8");
|
||||
if (refreshed !== value) {
|
||||
// A quota exchange can hold this company lock for 60 seconds.
|
||||
// Retry its 30-second acquisition timeout without discarding the
|
||||
// provider's only copy of a rotated, single-use refresh token.
|
||||
const writeBack = () => withAccountHomeSecretMutationLock(undefined, input.companyId, () => db.transaction(async (tx) => {
|
||||
const [grant] = await tx
|
||||
.select()
|
||||
.from(connectionGrants)
|
||||
.where(
|
||||
and(
|
||||
eq(connectionGrants.id, selection.grant.id),
|
||||
eq(connectionGrants.companyId, input.companyId),
|
||||
),
|
||||
)
|
||||
.for("update");
|
||||
// A missing or revoked grant blocks the write-back. Among
|
||||
// active copies, the merge decision below keeps the
|
||||
// credential with the newest provider freshness field.
|
||||
if (!grant || grant.status !== "active") return;
|
||||
const ref = grant.credentialSecretRefs.find(
|
||||
(r) => r.configPath === "ai.credential",
|
||||
);
|
||||
if (!ref) return;
|
||||
// Lock the referenced secret row for the rest of this
|
||||
// transaction. The grant-row lock above does not cover it,
|
||||
// so an authorized rotation of this secret could otherwise
|
||||
// land between the read and the write below and be
|
||||
// overwritten by this stale write-back.
|
||||
await tx
|
||||
.select({ id: companySecrets.id })
|
||||
.from(companySecrets)
|
||||
.where(
|
||||
and(
|
||||
eq(companySecrets.id, ref.secretId),
|
||||
eq(companySecrets.companyId, input.companyId),
|
||||
),
|
||||
)
|
||||
.for("update");
|
||||
const current = await aiConnectionService(
|
||||
tx as unknown as Db,
|
||||
).credential({ ...selection, grant });
|
||||
const destination = path.join(
|
||||
providerHome,
|
||||
"current-auth.json",
|
||||
);
|
||||
await writeFile(destination, current, { mode: 0o600 });
|
||||
const decision =
|
||||
input.binding.provider === "openai"
|
||||
? await decideCodexAuthMerge(authFile, destination, {
|
||||
errorLabel: "AI account refresh",
|
||||
})
|
||||
: await decideGrokAuthMerge(authFile, destination, {
|
||||
errorLabel: "AI account refresh",
|
||||
});
|
||||
if (decision !== 10) return;
|
||||
await secretService(tx).rotate(
|
||||
ref.secretId,
|
||||
{ value: refreshed, preserveAiSessionEpoch: true },
|
||||
{ userId: grant.subjectUserId },
|
||||
);
|
||||
// Keep grant.updatedAt for explicit account/access changes.
|
||||
// The rotated secret revision invalidates quota caches without
|
||||
// rejecting an otherwise valid in-flight reconnect.
|
||||
}));
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try { await writeBack(); break; }
|
||||
catch (error) {
|
||||
if (attempt >= 2 || (error as NodeJS.ErrnoException)?.code !== WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE) throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Preserve the private home on any failed write-back, including an
|
||||
// exhausted lock retry or database failure. The caller can retry the
|
||||
// same cleanup; only a committed save or an intentional discard
|
||||
// (revoked grant, older/different identity) permits deletion.
|
||||
if (home) await rm(home, { recursive: true, force: true });
|
||||
},
|
||||
cleanup: cleanupRuntime,
|
||||
};
|
||||
} catch (error) {
|
||||
if (home) await rm(home, { recursive: true, force: true });
|
||||
releaseCredentialHome?.();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -511,15 +642,48 @@ export async function withManagedAiProbe<T>(
|
||||
): Promise<T> {
|
||||
const run = async () => {
|
||||
const runtime = await prepareManagedAiRuntime(db, input);
|
||||
try { return await probe(runtime); }
|
||||
finally { await runtime.cleanup(); }
|
||||
};
|
||||
return input.binding.provider === "openai"
|
||||
? withAccountHomeSecretMutationLock(undefined, input.companyId, run).catch(error => {
|
||||
if ((error as NodeJS.ErrnoException)?.code === WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE) {
|
||||
throw unprocessable("AI credentials are being updated. Retry shortly.", { code: "ai_connection_busy" });
|
||||
let retained = false;
|
||||
try {
|
||||
assertAiCredentialCleanupSettled(runtime.retainedCleanupScope!);
|
||||
return await probe(runtime);
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof NativeEnvironmentProbeCleanupError) {
|
||||
// Keep the selected credential generation until the native owner has
|
||||
// retired and completed its refresh handoff. HTTP need not wait for it.
|
||||
retained = true;
|
||||
const retryCleanup = (error as { retryCleanup?: () => Promise<void> }).retryCleanup;
|
||||
retainAiCredentialCleanup({ scope: runtime.retainedCleanupScope!, cleanup: runtime.cleanup, retired: error.retired,
|
||||
...(typeof retryCleanup === "function" ? { retryRetirement: () => retryCleanup.call(error) } : {}) });
|
||||
throw unprocessable("The native account test is still cleaning up. Retry after runtime cleanup completes.", { code: "native_probe_cleanup_pending" });
|
||||
}
|
||||
throw error;
|
||||
})
|
||||
: run();
|
||||
} finally {
|
||||
if (!retained) {
|
||||
try { await runtime.cleanup(); }
|
||||
catch (error) {
|
||||
if (runtime.retainedCleanupScope && !(error instanceof RetiredCredentialRecoveryError)) {
|
||||
retainAiCredentialCleanup({ scope: runtime.retainedCleanupScope, cleanup: runtime.cleanup });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if (input.binding.provider !== "openai") return run();
|
||||
// A retirement callback may need the company lock. Join it before taking
|
||||
// the probe's outer lock; preparation rechecks this scope synchronously.
|
||||
const selected = await aiConnectionService(db).select({ ...input, userId: input.responsibleUserId,
|
||||
model: input.config.model, runnerProvider: input.config.provider, acpxAgent: input.config.acpxAgent });
|
||||
await reconcileRetainedAiCleanup({ companyId: input.companyId, accountKey: selected.grant.id });
|
||||
return withAccountHomeSecretMutationLock(undefined, input.companyId, async () => {
|
||||
const ownership = { companyId: input.companyId, active: true };
|
||||
try { return await managedProbeCredentialLocks.run(ownership, run); }
|
||||
finally { ownership.active = false; }
|
||||
}).catch(error => {
|
||||
if ((error as NodeJS.ErrnoException)?.code === WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE) {
|
||||
throw unprocessable("AI credentials are being updated. Retry shortly.", { code: "ai_connection_busy" });
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
@@ -43,6 +43,8 @@ import {
|
||||
import { forbidden, notFound, unprocessable } from "../errors.js";
|
||||
import { aiConnectionConfigurationFailure, aiConnectionCredentialNotSharedFailure } from "./ai-connection-configuration-failure.js";
|
||||
import { quotaCredentialRecovery, quotaCredentialHash } from "./quota-credential-recovery.js";
|
||||
import { prepareAntigravityCredentialRecovery } from "./native-runtime/antigravity-runner-credentials.js";
|
||||
import { assertAiCredentialCleanupSettled, reconcileRetainedAiCleanup } from "./retained-ai-credential-cleanup.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import { secretService } from "./secrets.js";
|
||||
@@ -574,6 +576,7 @@ export function aiConnectionService(db: Db) {
|
||||
loginSession?: { id: string; complete?: (tx: Db) => Promise<void> },
|
||||
attemptStartedAt = new Date(),
|
||||
managementContext?: ConnectionManagementContext,
|
||||
verifiedAccountLabel?: string,
|
||||
) {
|
||||
await managementContext?.reauthorize();
|
||||
const routing = "routing" in input ? input.routing : undefined;
|
||||
@@ -799,7 +802,7 @@ export function aiConnectionService(db: Db) {
|
||||
},
|
||||
createdByUserId: userId,
|
||||
});
|
||||
let accountLabel: string | undefined;
|
||||
let accountLabel: string | undefined = input.provider === "google" ? verifiedAccountLabel : undefined;
|
||||
if (input.method === "subscription" && input.provider !== "anthropic") {
|
||||
try {
|
||||
const credential = JSON.parse(verifiedCredential);
|
||||
@@ -930,31 +933,78 @@ export function aiConnectionService(db: Db) {
|
||||
tx: Db, row: Parameters<typeof credential>[0], current: string, onRecoveryStarted?: () => void,
|
||||
) {
|
||||
const metadata = aiConnectionMetadataSchema.safeParse(row.connection.config.ai);
|
||||
if (!metadata.success || metadata.data.provider !== "openai" || metadata.data.method !== "subscription") return null;
|
||||
if (!metadata.success || !["openai", "google"].includes(metadata.data.provider) || metadata.data.method !== "subscription") return null;
|
||||
const recovery = quotaCredentialRecovery(row.connection.companyId, row.grant.id);
|
||||
const pending = await recovery.read();
|
||||
if (!pending) return null;
|
||||
const ref = row.grant.credentialSecretRefs.find(ref => ref.configPath === "ai.credential");
|
||||
if (!ref || pending.secretId !== ref.secretId || pending.connectionId !== row.connection.id || pending.baseHash !== quotaCredentialHash(current)) {
|
||||
if (!ref || (pending.provider ?? "openai") !== metadata.data.provider
|
||||
|| pending.secretId !== ref.secretId || pending.connectionId !== row.connection.id || pending.baseHash !== quotaCredentialHash(current)) {
|
||||
await recovery.clear();
|
||||
return null;
|
||||
}
|
||||
if (metadata.data.provider === "google") {
|
||||
const [secret] = await tx.select({ epoch: companySecrets.aiSessionEpoch, version: companySecrets.latestVersion })
|
||||
.from(companySecrets).where(and(eq(companySecrets.companyId, row.connection.companyId), eq(companySecrets.id, ref.secretId))).for("update");
|
||||
if (!pending.google || pending.google.sessionEpoch !== secret?.epoch || pending.google.baseVersion !== secret?.version
|
||||
|| pending.google.versionSelector !== (ref.versionSelector ?? "latest")
|
||||
|| pending.google.accountEmail.toLowerCase() !== row.grant.providerTenant?.name?.toLowerCase()) {
|
||||
await recovery.clear();
|
||||
return null;
|
||||
}
|
||||
if (!pending.google.verified) {
|
||||
onRecoveryStarted?.();
|
||||
throw new Error("Google credential recovery needs account verification");
|
||||
}
|
||||
}
|
||||
onRecoveryStarted?.();
|
||||
await secretService(tx).rotate(ref.secretId, { value: pending.value, preserveAiSessionEpoch: true }, { userId: row.grant.subjectUserId });
|
||||
// Automatic rotation changes secret revision, not the grant mutation marker
|
||||
// used to fence reconnect attempts. Ownership and access are unchanged.
|
||||
await logActivity(tx, { companyId: row.connection.companyId, actorType: "system", actorId: "quota_recovery",
|
||||
action: "ai_connection.credential_refreshed", entityType: "tool_connection", entityId: row.connection.id,
|
||||
details: { provider: "openai", grantId: row.grant.id } });
|
||||
details: { provider: metadata.data.provider, grantId: row.grant.id } });
|
||||
return pending.value;
|
||||
}
|
||||
|
||||
/** Never hand a consumed token to a new provider while its replacement awaits commit. */
|
||||
async function runtimeCredential(row: Parameters<typeof credential>[0]) {
|
||||
async function runtimeCredential(row: Parameters<typeof credential>[0], ownership?: { credentialLockHeld: true }) {
|
||||
const metadata = aiConnectionMetadataSchema.safeParse(row.connection.config.ai);
|
||||
if (!metadata.success || metadata.data.provider !== "openai" || metadata.data.method !== "subscription") return credential(row);
|
||||
if (!metadata.success || !["openai", "google"].includes(metadata.data.provider) || metadata.data.method !== "subscription") return credential(row);
|
||||
// Retirement callbacks acquire this same mutation lock to persist their
|
||||
// final generation. Join them before taking the lock they need. A caller
|
||||
// already holding it must only check, for both rotated-credential lanes.
|
||||
const scope = { companyId: row.connection.companyId, accountKey: row.grant.id };
|
||||
if (ownership?.credentialLockHeld) assertAiCredentialCleanupSettled(scope);
|
||||
else await reconcileRetainedAiCleanup(scope);
|
||||
let savingReplacement = false;
|
||||
return withAccountHomeSecretMutationLock(undefined, row.connection.companyId, async () => {
|
||||
// An owner can arrive while lock acquisition waits. Never join under it.
|
||||
assertAiCredentialCleanupSettled(scope);
|
||||
if (metadata.data.provider === "google") {
|
||||
const recovery = quotaCredentialRecovery(row.connection.companyId, row.grant.id);
|
||||
const pending = await recovery.read();
|
||||
if (pending?.provider === "google" && pending.google && !pending.google.verified
|
||||
&& pending.connectionId === row.connection.id
|
||||
&& pending.google.accountEmail.toLowerCase() === row.grant.providerTenant?.name?.toLowerCase()) {
|
||||
const ref = row.grant.credentialSecretRefs.find(ref => ref.configPath === "ai.credential");
|
||||
const [secret] = await db.select({ epoch: companySecrets.aiSessionEpoch, version: companySecrets.latestVersion })
|
||||
.from(companySecrets).where(and(eq(companySecrets.companyId, row.connection.companyId), eq(companySecrets.id, pending.secretId)));
|
||||
const current = await credential(row);
|
||||
if (ref?.secretId === pending.secretId && (ref.versionSelector ?? "latest") === pending.google.versionSelector
|
||||
&& secret?.epoch === pending.google.sessionEpoch && secret?.version === pending.google.baseVersion
|
||||
&& pending.baseHash === quotaCredentialHash(current)) {
|
||||
savingReplacement = true;
|
||||
// Network verification runs before acquiring database row locks.
|
||||
// The transaction below rechecks the exact saved generation.
|
||||
await prepareAntigravityCredentialRecovery({ originalCredential: current,
|
||||
refreshedCredential: pending.value, accountEmail: pending.google.accountEmail,
|
||||
scope: { companyId: row.connection.companyId, accountKey: row.grant.id },
|
||||
persistVerified: value => recovery.write({ ...pending, value, google: { ...pending.google!, verified: true } }),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let recovered = false;
|
||||
const value = await db.transaction(async tx => {
|
||||
const [grant] = await tx.select().from(connectionGrants).where(and(
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import type { AiConnectionBinding } from "@paperclipai/shared";
|
||||
import { AntigravityModelDiscoveryCleanupError, discoverAntigravityModels } from "../vendor/paperclip-runner/index.js";
|
||||
import { unprocessable } from "../errors.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { prepareManagedAiRuntime } from "./ai-connection-runtime.js";
|
||||
import { RetiredCredentialRecoveryError } from "./quota-credential-recovery.js";
|
||||
import { retainGoogleCredentialCleanup } from "./retained-google-credential-cleanup.js";
|
||||
|
||||
/** Metadata uses the selected connection's ordinary authority and encrypted
|
||||
* refresh writeback. The native client cannot create a session or send a prompt.
|
||||
*/
|
||||
export async function antigravityConnectionModels(db: Db, input: {
|
||||
companyId: string;
|
||||
userId: string | null;
|
||||
agentId?: string;
|
||||
binding: AiConnectionBinding;
|
||||
allowUninstalledShared: boolean;
|
||||
}) {
|
||||
if (input.binding.provider !== "google") throw unprocessable("Select a Google runtime connection");
|
||||
const runtime = await prepareManagedAiRuntime(db, {
|
||||
companyId: input.companyId, responsibleUserId: input.userId,
|
||||
agentId: input.agentId ?? "00000000-0000-0000-0000-000000000000",
|
||||
adapterType: "paperclip_runner", binding: input.binding,
|
||||
allowUninstalledPersonal: !input.agentId,
|
||||
allowUninstalledShared: input.allowUninstalledShared,
|
||||
config: { provider: "acpx", acpxAgent: "antigravity" },
|
||||
});
|
||||
let retained = false;
|
||||
try {
|
||||
if (runtime.attribution.method !== "subscription") throw unprocessable(
|
||||
"Sign in to Google Antigravity to discover account models. With an API key, enter the exact model identifier.",
|
||||
);
|
||||
const home = runtime.config.env.GEMINI_HOME;
|
||||
if (typeof home !== "string" || !home) throw unprocessable("The selected Google runtime account is unavailable.");
|
||||
try { return (await discoverAntigravityModels(home)).models; }
|
||||
catch (error) {
|
||||
if (error instanceof AntigravityModelDiscoveryCleanupError) {
|
||||
// The native owner retains the live child and immutable command lease.
|
||||
// Keep this selected credential home until that owner proves retirement.
|
||||
retained = true;
|
||||
if (runtime.retainedCleanupScope) retainGoogleCredentialCleanup({
|
||||
scope: runtime.retainedCleanupScope, cleanup: runtime.cleanup, retired: error.retired,
|
||||
});
|
||||
}
|
||||
throw unprocessable("Could not load models for this Google account. Check the account's Antigravity access, then refresh models.");
|
||||
}
|
||||
} finally {
|
||||
if (!retained) {
|
||||
try { await runtime.cleanup(); }
|
||||
catch (error) {
|
||||
if (!(error instanceof RetiredCredentialRecoveryError)) {
|
||||
// Storage failures still retain the private home and block sleep.
|
||||
// No provider or repeated database work is started by this hold.
|
||||
if (runtime.retainedCleanupScope) retainGoogleCredentialCleanup({
|
||||
scope: runtime.retainedCleanupScope, cleanup: runtime.cleanup,
|
||||
});
|
||||
}
|
||||
logger.warn({ companyId: input.companyId, code: "ANTIGRAVITY_CATALOG_CREDENTIAL_CLEANUP_PENDING" },
|
||||
"Antigravity model-discovery credential cleanup is retained for recovery");
|
||||
throw unprocessable("Could not complete Google account credential cleanup. Try model discovery again shortly.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, mkdtemp, realpath, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { AdapterEnvironmentTestContext, AdapterEnvironmentTestResult } from "@paperclipai/adapter-utils";
|
||||
import { NativeEnvironmentProbeCleanupError, probeNativeRunnerEnvironment, resolveAcpxRuntimeRoot } from "../vendor/paperclip-runner/index.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { resolveAntigravityCandidateAdmission } from "./native-runtime/acpx-qualification.js";
|
||||
import { antigravityCredentialTurn, prepareAntigravityRunnerCredentials } from "./native-runtime/antigravity-runner-credentials.js";
|
||||
import { resolvePaperclipRunnerBinary } from "./native-runtime/native-codex-runner.js";
|
||||
|
||||
const TRANSPORT_KEYS = ["PATH", "LANG", "LANGUAGE", "TZ", "TMPDIR", "TEMP", "TMP", "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "ALL_PROXY"];
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> | null => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
||||
|
||||
/** Project only closed Rust admission categories from the private authenticated
|
||||
* command result. Provider output and the outer serialized Error stay private.
|
||||
*/
|
||||
export function antigravityConnectionProbeFailure(companyId: string, error: unknown): AdapterEnvironmentTestResult {
|
||||
if (error instanceof NativeEnvironmentProbeCleanupError) throw error;
|
||||
const command = asRecord(asRecord(error)?.runnerCommandResult);
|
||||
const result = command?.commandType === "session.open" && command.status === "failed" ? asRecord(command.result) : null;
|
||||
const admission = result?.code === "command_execution_failed" && typeof result.message === "string" && result.message.length <= 2_048
|
||||
? /^failed to start ACPX provider: ACPX sidecar command (?:initialize|session\.open) was rejected \(retryable=(true|false), classification=(admission_(?:binding|installation|sandbox|credential|configuration|skills|command|tool_bridge|runtime|identity))\)$/.exec(result.message)
|
||||
: null;
|
||||
const installation = admission?.[2] === "admission_installation";
|
||||
const code = installation ? "antigravity_installation_check_failed" : "antigravity_admission_failed";
|
||||
const errorClass = error instanceof Error && ["Error", "TypeError", "RangeError", "AggregateError"].includes(error.name) ? error.name : "Error";
|
||||
logger.warn({ companyId, code, errorClass,
|
||||
commandCode: admission ? "command_execution_failed" : "unclassified",
|
||||
classification: admission?.[2] ?? "unclassified",
|
||||
...(admission ? { retryable: admission[1] === "true" } : {}),
|
||||
}, installation ? "Antigravity installation check failed before account verification" : "Antigravity runtime admission check failed");
|
||||
return { adapterType: "paperclip_runner", status: "fail", testedAt: new Date().toISOString(), checks: [{ code, level: "error",
|
||||
message: installation ? "Paperclip could not complete the local Google Antigravity installation check."
|
||||
: "Google Antigravity could not complete its runtime check.",
|
||||
hint: installation ? "The instance operator needs to repair this runtime before Test can verify your Google connection."
|
||||
: "Retry Test. If it still fails, ask your Paperclip operator to inspect the runtime check.",
|
||||
}] };
|
||||
}
|
||||
|
||||
/** The ordinary Test uses the selected managed account and no model turn. */
|
||||
export async function testAntigravityConnection(context: AdapterEnvironmentTestContext, model: string): Promise<AdapterEnvironmentTestResult> {
|
||||
if (context.executionTarget?.kind === "remote") throw new Error("Google Antigravity candidate testing requires the Paperclip host.");
|
||||
const admission = resolveAntigravityCandidateAdmission({ companyId: context.companyId, model });
|
||||
if (!admission) throw new Error("Google Antigravity is not available for this company.");
|
||||
const configured = context.config.env;
|
||||
const environment = Object.fromEntries([
|
||||
...TRANSPORT_KEYS.flatMap(key => typeof process.env[key] === "string" ? [[key, process.env[key]!]] : []),
|
||||
...Object.entries(configured && typeof configured === "object" && !Array.isArray(configured) ? configured : {})
|
||||
.filter((entry): entry is [string, string] => typeof entry[1] === "string"),
|
||||
]);
|
||||
const credentials = await prepareAntigravityRunnerCredentials({ environment, remote: false,
|
||||
managedHome: context.managedAiCredentialHome, lifecycleMode: "per_turn" });
|
||||
const runtimeDirectory = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-setup-")));
|
||||
const acpxRuntimeDirectory = join(runtimeDirectory, "acpx");
|
||||
const nonce = randomUUID(), normalizedSessionId = `setup-${nonce}`;
|
||||
let nativeHome: string, runnerBinary: string;
|
||||
try {
|
||||
await mkdir(acpxRuntimeDirectory, { mode: 0o700 });
|
||||
nativeHome = join(await resolveAcpxRuntimeRoot(acpxRuntimeDirectory, normalizedSessionId), "antigravity-home");
|
||||
runnerBinary = resolvePaperclipRunnerBinary();
|
||||
} catch (error) {
|
||||
await rm(runtimeDirectory, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
const turn = credentials.home && credentials.credential
|
||||
? antigravityCredentialTurn({ managedHome: credentials.home, runtimeHome: nativeHome, credential: credentials.credential }) : undefined;
|
||||
const receipt = await probeNativeRunnerEnvironment({ runtimeDirectory, provider: "acpx", model,
|
||||
environment: credentials.environment, admissionOnly: true, timeoutMs: 45_000,
|
||||
transportOptions: { runnerBinary, externallySandboxed: false,
|
||||
acpxAgent: "antigravity", acpxCandidateAdmission: admission, acpxRuntimeDirectory,
|
||||
acpxPermissionMode: "approve-reads", acpxPermissionModePinned: true,
|
||||
prpIdentity: { runnerInstanceId: `setup-runner-${nonce}`, runId: `setup-${nonce}`, normalizedSessionId,
|
||||
environmentLeaseId: `setup-lease-${nonce}`, turnId: `setup-turn-${nonce}`, itemId: `setup-item-${nonce}` } },
|
||||
onCleanupConfirmed: async () => {
|
||||
// The native owner proves physical retirement before this callback.
|
||||
await turn?.copyBack();
|
||||
await turn?.remove();
|
||||
await rm(runtimeDirectory, { recursive: true, force: true });
|
||||
},
|
||||
});
|
||||
if (receipt.provider !== "acpx" || receipt.providerDriver !== "acpx_runtime" || receipt.effectiveModel !== model
|
||||
|| receipt.sessionAdmissionPassed !== true || receipt.admissionOnly !== true || receipt.helloProbePassed !== false) {
|
||||
throw new Error("The selected Google runtime returned no matching account and model admission receipt.");
|
||||
}
|
||||
return { adapterType: "paperclip_runner", status: "pass", testedAt: new Date().toISOString(),
|
||||
checks: [{ code: "antigravity_metadata_verified", level: "info",
|
||||
message: "The Google Antigravity candidate verified the selected account and exact model. No model prompt was sent." }] };
|
||||
}
|
||||
@@ -1,6 +1,16 @@
|
||||
import { agents } from "@paperclipai/db";
|
||||
import { asBoolean, parseObject } from "../adapters/utils.js";
|
||||
|
||||
/** Runner work needs a task; generic interval heartbeats have no task owner.
|
||||
* Task-bound schedules, monitors and external-provider assignments use their
|
||||
* existing wake paths and are unaffected by this interval policy.
|
||||
*/
|
||||
export function supportsUnscopedTimerHeartbeat(
|
||||
agent: Pick<typeof agents.$inferSelect, "adapterType">,
|
||||
) {
|
||||
return agent.adapterType !== "paperclip_runner";
|
||||
}
|
||||
|
||||
export function isHeartbeatWakeOnDemandEnabled(
|
||||
agent: Pick<typeof agents.$inferSelect, "runtimeConfig">,
|
||||
) {
|
||||
|
||||
@@ -3277,6 +3277,7 @@ export function heartbeatService(
|
||||
adapterConfig: agent.adapterConfig,
|
||||
agent: {
|
||||
id: agent.id,
|
||||
companyId: agent.companyId,
|
||||
status: runningAgent.status,
|
||||
adapterType: agent.adapterType,
|
||||
},
|
||||
|
||||
@@ -93,6 +93,24 @@ describe.skipIf(!support.supported)("heartbeat queue database wiring", () => {
|
||||
await db.execute(sql`truncate table companies restart identity cascade`);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ provider: "codex" }, { provider: "acpx", acpxAgent: "antigravity" }, { provider: "muse" },
|
||||
])("rejects direct taskless timer wakes for $provider before a run or request can be persisted", async adapterConfig => {
|
||||
const [company] = await db.insert(companies).values({ name: "Timer scope", issuePrefix: "TS" }).returning();
|
||||
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Ready for a task", status: "idle",
|
||||
adapterType: "paperclip_runner", adapterConfig, runtimeConfig: { heartbeat: { enabled: true, intervalSec: 60 } } }).returning();
|
||||
const deps = callbacks(db);
|
||||
deps.getAgent.mockResolvedValue(agent);
|
||||
const queue = createHeartbeatQueue(db, deps);
|
||||
expect(await queue.enqueueWakeup(agent.id, { source: "timer", reason: "heartbeat_timer", requestedByActorType: "system" })).toBeNull();
|
||||
expect(await db.select().from(heartbeatRuns)).toHaveLength(0);
|
||||
expect(await db.select().from(agentWakeupRequests)).toHaveLength(0);
|
||||
expect((await db.select().from(agents).where(eq(agents.id, agent.id)))[0])
|
||||
.toMatchObject({ status: "idle", lastHeartbeatAt: null });
|
||||
expect(deps.executeRun).not.toHaveBeenCalled();
|
||||
expect(deps.budgets.getInvocationBlock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
async function fixture(status = "running") {
|
||||
const [company] = await db.insert(companies).values({ name: "Queue module", issuePrefix: "QM" }).returning();
|
||||
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Queue agent", role: "engineer", status: "idle", adapterType: "process", adapterConfig: {} }).returning();
|
||||
|
||||
@@ -167,7 +167,7 @@ import {
|
||||
shouldCancelRunsForNonInvokableAgent,
|
||||
type AgentOrgRow,
|
||||
} from "../agent-invokability.js";
|
||||
import { isHeartbeatWakeOnDemandEnabled } from "../heartbeat-policy.js";
|
||||
import { isHeartbeatWakeOnDemandEnabled, supportsUnscopedTimerHeartbeat } from "../heartbeat-policy.js";
|
||||
import { isUuidLike } from "@paperclipai/shared";
|
||||
import { retryChatControlAdmission } from "../chat-control-admission-retry.js";
|
||||
|
||||
@@ -2645,6 +2645,15 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
}
|
||||
const effectiveTaskKey =
|
||||
readNonEmptyString(enrichedContextSnapshot.taskKey) ?? taskKey;
|
||||
const genericTimerWake =
|
||||
source === "timer" &&
|
||||
!issueId &&
|
||||
!wakeCommentId &&
|
||||
!readNonEmptyString(enrichedContextSnapshot.taskId) &&
|
||||
!effectiveTaskKey;
|
||||
// Old or direct timer producers cannot create a doomed taskless Runner
|
||||
// run. Explicit session restoration above can supply a real task scope.
|
||||
if (genericTimerWake && !supportsUnscopedTimerHeartbeat(agent)) return null;
|
||||
const sessionBefore =
|
||||
explicitResumeSession?.sessionDisplayId ??
|
||||
(await resolveSessionBeforeForWakeup(agent, effectiveTaskKey));
|
||||
@@ -2816,12 +2825,6 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
return null;
|
||||
}
|
||||
|
||||
const genericTimerWake =
|
||||
source === "timer" &&
|
||||
!issueId &&
|
||||
!wakeCommentId &&
|
||||
!readNonEmptyString(enrichedContextSnapshot.taskId) &&
|
||||
!readNonEmptyString(enrichedContextSnapshot.taskKey);
|
||||
if (
|
||||
policy.skipTimerWhenNoActionableWork &&
|
||||
genericTimerWake &&
|
||||
|
||||
@@ -729,6 +729,7 @@ export async function selectHeartbeatRuntime(db: Db, input: HeartbeatRuntimeSele
|
||||
)
|
||||
: agent.adapterConfig;
|
||||
const requestedNativeProvider = resolvePaperclipRunnerNativeProviderInput({
|
||||
companyId: agent.companyId,
|
||||
backend: nativeRuntimeResolution.profile.backend,
|
||||
adapterConfig: nativeProviderConfig, managedProfile, agentCoreProfile, dotBinding, museBinding,
|
||||
});
|
||||
@@ -741,6 +742,7 @@ export async function selectHeartbeatRuntime(db: Db, input: HeartbeatRuntimeSele
|
||||
}) : null;
|
||||
const nativeProvider = codexCliVersion
|
||||
? resolvePaperclipRunnerNativeProviderInput({
|
||||
companyId: agent.companyId,
|
||||
backend: nativeRuntimeResolution.profile.backend,
|
||||
adapterConfig: nativeProviderConfig, codexCliVersion, managedProfile, agentCoreProfile, dotBinding, museBinding,
|
||||
}) : requestedNativeProvider;
|
||||
@@ -865,6 +867,10 @@ export async function selectHeartbeatRuntime(db: Db, input: HeartbeatRuntimeSele
|
||||
}
|
||||
nativeSessionId = nativeExecutionWithCheckpoint.normalizedSessionId;
|
||||
}
|
||||
if (nativeResumeCheckpoint && nativeExecution.provider.kind === "acpx"
|
||||
&& nativeExecution.provider.agent === "antigravity") {
|
||||
nativeResumeCheckpoint = { ...nativeResumeCheckpoint, providerRecoveryPolicy: "same_session_only" };
|
||||
}
|
||||
const nativeSandboxLifecycle = resolveNativeSandboxLifecycle({
|
||||
adapterType: agent.adapterType,
|
||||
lifecyclePolicy: nativeExecution.session.lifecyclePolicy,
|
||||
|
||||
@@ -91,14 +91,14 @@ describe("heartbeat scheduling module boundary", () => {
|
||||
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_HEARTBEAT_SCHEDULING_TEST_DATABASE_URL");
|
||||
const postgres = external ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
||||
describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
|
||||
let db: Db;
|
||||
beforeAll(async () => {
|
||||
if (external) await applyPendingMigrations(external);
|
||||
else database = await startEmbeddedPostgresTestDatabase("paperclip-heartbeat-scheduling-module");
|
||||
|
||||
|
||||
db = createDb(external ?? database.connectionString, { idleTimeoutSeconds: 0, maxLifetimeSeconds: 0, connectTimeoutSeconds: 0 });
|
||||
db = createDb(external ?? database!.connectionString, { idleTimeoutSeconds: 0, maxLifetimeSeconds: 0, connectTimeoutSeconds: 0 });
|
||||
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
||||
afterAll(async () => {
|
||||
await db?.$client.end();
|
||||
@@ -109,9 +109,9 @@ describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", (
|
||||
await db.execute(sql`truncate table companies restart identity cascade`);
|
||||
});
|
||||
|
||||
async function fixture() {
|
||||
async function fixture(adapterType = "paperclip_runner") {
|
||||
const [company] = await db.insert(companies).values({ name: "Scheduling", issuePrefix: "SCH" }).returning();
|
||||
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Scheduled agent", adapterType: "paperclip_runner", createdAt: dueAt }).returning();
|
||||
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Scheduled agent", adapterType, createdAt: dueAt }).returning();
|
||||
const [issue] = await db.insert(issues).values({
|
||||
companyId: company.id, title: "Check deployment", status: "in_progress", assigneeAgentId: agent.id,
|
||||
monitorNextCheckAt: dueAt, monitorAttemptCount: 0, createdAt: dueAt,
|
||||
@@ -430,7 +430,7 @@ describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", (
|
||||
});
|
||||
|
||||
it("combines timer and monitor counts and passes the timer claim receipt to admission", async () => {
|
||||
const f = await fixture();
|
||||
const f = await fixture("process");
|
||||
enableTimer(f.deps);
|
||||
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 2, enqueued: 2, skipped: 0 });
|
||||
expect(f.deps.claimDueTimerHeartbeat).toHaveBeenCalledWith(expect.objectContaining({ id: f.agent.id }), now, 60);
|
||||
@@ -440,7 +440,7 @@ describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", (
|
||||
});
|
||||
|
||||
it("does not enqueue a timer after losing its due claim", async () => {
|
||||
const f = await fixture();
|
||||
const f = await fixture("process");
|
||||
enableTimer(f.deps);
|
||||
await db.update(issues).set({ monitorNextCheckAt: null }).where(eq(issues.id, f.issue.id));
|
||||
f.deps.claimDueTimerHeartbeat.mockResolvedValue(null);
|
||||
@@ -449,7 +449,7 @@ describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", (
|
||||
});
|
||||
|
||||
it("enforces worktree cutoffs and agent invokability before timer claims", async () => {
|
||||
const f = await fixture();
|
||||
const f = await fixture("process");
|
||||
enableTimer(f.deps);
|
||||
await db.update(issues).set({ monitorNextCheckAt: null }).where(eq(issues.id, f.issue.id));
|
||||
f.deps.getWorktreeExecutionCutoff.mockResolvedValue(now);
|
||||
@@ -463,6 +463,25 @@ describe.skipIf(!postgres.supported)("heartbeat scheduling database boundary", (
|
||||
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 1, skipped: 0 });
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ provider: "codex" }, { provider: "acpx", acpxAgent: "antigravity" }, { provider: "openai_dot" },
|
||||
])("leaves task-required $provider agents idle between tasks while preserving their due task monitor", async adapterConfig => {
|
||||
const f = await fixture();
|
||||
await db.update(agents).set({ adapterConfig }).where(eq(agents.id, f.agent.id));
|
||||
enableTimer(f.deps);
|
||||
// Only the task-bound monitor is admitted, even though the generic timer is due.
|
||||
expect(await f.scheduler.tickTimers(now)).toEqual({ checked: 1, enqueued: 1, skipped: 0 });
|
||||
expect(f.deps.claimDueTimerHeartbeat).not.toHaveBeenCalled();
|
||||
expect(f.deps.enqueueWakeup).toHaveBeenCalledExactlyOnceWith(f.agent.id,
|
||||
expect.objectContaining({ contextSnapshot: expect.objectContaining({ issueId: f.issue.id }) }));
|
||||
expect((await db.select().from(agents).where(eq(agents.id, f.agent.id)))[0])
|
||||
.toMatchObject({ status: f.agent.status, lastHeartbeatAt: f.agent.lastHeartbeatAt });
|
||||
f.deps.enqueueWakeup.mockClear();
|
||||
expect(await f.scheduler.tickTimers(new Date(now.getTime() + 120_000))).toEqual({ checked: 0, enqueued: 0, skipped: 0 });
|
||||
expect(f.deps.enqueueWakeup).not.toHaveBeenCalled();
|
||||
expect(f.deps.claimDueTimerHeartbeat).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("recovers active goals with stable revision-based admission keys", async () => {
|
||||
const f = await fixture();
|
||||
const active = await session(f);
|
||||
|
||||
@@ -57,6 +57,7 @@ import {
|
||||
import { logger } from "../../middleware/logger.js";
|
||||
import { failRunnerGoalAction } from "../runner-goals.js";
|
||||
import { evaluateAgentInvokability } from "../agent-invokability.js";
|
||||
import { supportsUnscopedTimerHeartbeat } from "../heartbeat-policy.js";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import type { issueService } from "../issues.js";
|
||||
import type { createHeartbeatQueue } from "./queue.js";
|
||||
@@ -1305,6 +1306,7 @@ export function createHeartbeatScheduling(
|
||||
agentsByCompany.get(agent.companyId) ?? [],
|
||||
);
|
||||
if (!invokability.invokable) continue;
|
||||
if (!supportsUnscopedTimerHeartbeat(agent)) continue;
|
||||
const policy = parseHeartbeatPolicy(agent);
|
||||
if (!policy.enabled || policy.intervalSec <= 0) continue;
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import path from "node:path";
|
||||
import { runSetupTokenLogin } from "@paperclipai/adapter-claude-local/server";
|
||||
import { runDeviceLogin } from "@paperclipai/adapter-codex-local/server";
|
||||
import { ensureCommandResolvable, resolveCommandForLogs } from "@paperclipai/adapter-utils/server-utils";
|
||||
import { resolveCodexCommand } from "../vendor/paperclip-runner/index.js";
|
||||
import { resolveCodexCommand, startAntigravityBrowserLogin } from "../vendor/paperclip-runner/index.js";
|
||||
|
||||
export type LocalBrowserLoginState = {
|
||||
authorizationUrl?: string;
|
||||
@@ -47,7 +47,8 @@ sys.exit(os.waitstatus_to_exitcode(status))
|
||||
`;
|
||||
|
||||
/** Run the same browser-code login used by sandbox connections on the local host. */
|
||||
export function startLocalBrowserLogin(provider: "anthropic" | "openai", home: string): LocalBrowserLoginState {
|
||||
export function startLocalBrowserLogin(provider: "anthropic" | "openai" | "google", home: string): LocalBrowserLoginState {
|
||||
if (provider === "google") return startAntigravityBrowserLogin(home);
|
||||
const controller = new AbortController();
|
||||
const state: LocalBrowserLoginState = { abort: () => controller.abort() };
|
||||
const args = provider === "anthropic" ? ["setup-token"] : ["login", "--device-auth"];
|
||||
|
||||
@@ -6,6 +6,19 @@ import { readCodexAuthInfo, fetchCodexQuota } from "@paperclipai/adapter-codex-l
|
||||
import { parseGrokAuthPayload, hasUsableGrokAuthValue } from "@paperclipai/adapter-grok-local/server";
|
||||
import type { AiProvider } from "@paperclipai/shared";
|
||||
import { unprocessable } from "../errors.js";
|
||||
import { verifyAntigravityCredential } from "../vendor/paperclip-runner/index.js";
|
||||
|
||||
export async function readVerifiedLocalAiCredentialDetails(provider: AiProvider, loginHome: string) {
|
||||
if (provider === "google") {
|
||||
try {
|
||||
const verified = await verifyAntigravityCredential(loginHome);
|
||||
return { credential: verified.credential, accountLabel: verified.accountEmail };
|
||||
} catch {
|
||||
throw unprocessable("Could not verify the Google account. Finish browser sign-in, then try Connect again.");
|
||||
}
|
||||
}
|
||||
return { credential: await readVerifiedLocalAiCredential(provider, loginHome), accountLabel: undefined };
|
||||
}
|
||||
|
||||
/** Read and verify a connection-specific login home. */
|
||||
export async function readVerifiedLocalAiCredential(provider: AiProvider, loginHome?: string): Promise<string> {
|
||||
@@ -14,6 +27,7 @@ export async function readVerifiedLocalAiCredential(provider: AiProvider, loginH
|
||||
? "Start local sign-in for this connection before connecting."
|
||||
: "Start browser sign-in for this connection before connecting.");
|
||||
try {
|
||||
if (provider === "google") return (await verifyAntigravityCredential(loginHome)).credential;
|
||||
if (provider === "anthropic") {
|
||||
// Never change process.env or fall back to the server account when an
|
||||
// authenticated user's isolated login is missing or invalid.
|
||||
|
||||
@@ -4,18 +4,23 @@ import { randomUUID } from "node:crypto";
|
||||
import { realpathSync } from "node:fs";
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { and, eq, inArray, lte, sql } from "drizzle-orm";
|
||||
import { adapterAuthSessions, ADAPTER_AUTH_SESSION_ACTIVE_STATES, environments, type Db } from "@paperclipai/db";
|
||||
import { and, eq, inArray, isNotNull, lte, notInArray, sql } from "drizzle-orm";
|
||||
import { adapterAuthSessions, ADAPTER_AUTH_SESSION_ACTIVE_STATES, databaseWorkScopeKey, environments, type Db } from "@paperclipai/db";
|
||||
import type { AiConnectionLoginIntent, LocalAiLoginAttempt, LocalAiLoginStatus } from "@paperclipai/shared";
|
||||
import { resolvePaperclipInstanceRoot } from "../home-paths.js";
|
||||
import { notFound, unprocessable } from "../errors.js";
|
||||
import { aiConnectionService } from "./ai-connections.js";
|
||||
import { readVerifiedLocalAiCredential } from "./local-ai-credentials.js";
|
||||
import { readVerifiedLocalAiCredentialDetails } from "./local-ai-credentials.js";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import { startLocalBrowserLogin, type LocalBrowserLoginState } from "./local-ai-browser-login.js";
|
||||
import { registerIdleLocalWorkProbe } from "./idle-local-work.js";
|
||||
|
||||
const LOCAL_LOGIN_METHOD = "local_subscription";
|
||||
const ATTEMPT_DURATION_MS = 30 * 60 * 1000;
|
||||
const BROWSER_STOP_WAIT_MS = 5_000;
|
||||
const RETIREMENT_PENDING = "local_login_retirement_pending";
|
||||
const CLEANUP_BATCH_SIZE = 16;
|
||||
const CLEANUP_CONCURRENCY = 4;
|
||||
function loginHome(id: string) {
|
||||
const root = resolvePaperclipInstanceRoot();
|
||||
// macOS exposes /var through a system symlink to /private/var. Credential
|
||||
@@ -51,47 +56,167 @@ function sameTarget(a: AiConnectionLoginIntent, b: AiConnectionLoginIntent) {
|
||||
// Route handlers construct this service per request. Keep live browser processes
|
||||
// shared so status polling and code submission can reach the original process.
|
||||
const browserLogins = new Map<string, LocalBrowserLoginState>();
|
||||
const browserRetirements = new Map<string, Promise<void>>();
|
||||
const deferredRetirements = new Map<string, { scope: object; retirement: Promise<void>; ready: boolean }>();
|
||||
const cleanupReadyListeners = new WeakMap<object, Set<() => void>>();
|
||||
registerIdleLocalWorkProbe(() => browserRetirements.size || deferredRetirements.size ? "present" : "none");
|
||||
|
||||
/** Local sign-ins share the durable attempt/credential lifecycle, but never seed
|
||||
* their home from the operator's rotating CLI credential. */
|
||||
export function localAiLoginService(db: Db) {
|
||||
function stopBrowserLogin(id: string) {
|
||||
browserLogins.get(id)?.abort();
|
||||
browserLogins.delete(id);
|
||||
const scope = databaseWorkScopeKey(db);
|
||||
function retirementReady(id: string) {
|
||||
const retained = deferredRetirements.get(id);
|
||||
if (!retained || retained.scope !== scope || retained.ready) return;
|
||||
retained.ready = true;
|
||||
for (const wake of cleanupReadyListeners.get(scope) ?? []) {
|
||||
try { wake(); } catch { process.emitWarning("Local sign-in cleanup wake failed"); }
|
||||
}
|
||||
}
|
||||
function retainRetirement(id: string, retirement: Promise<void>) {
|
||||
if (deferredRetirements.get(id)?.retirement === retirement) return;
|
||||
const retained = { scope, retirement, ready: false };
|
||||
deferredRetirements.set(id, retained);
|
||||
void retirement.then(() => {
|
||||
if (deferredRetirements.get(id) === retained) retirementReady(id);
|
||||
}, () => {
|
||||
// A rejected abort needs an explicit Cancel or Start sign-in again to
|
||||
// retry its original owner. Keep its home/claim and sleep blocker; an
|
||||
// idle timer must not repeatedly signal a process with uncertain state.
|
||||
});
|
||||
}
|
||||
function subscribeCleanupReady(wake: () => void) {
|
||||
let listeners = cleanupReadyListeners.get(scope);
|
||||
if (!listeners) cleanupReadyListeners.set(scope, listeners = new Set());
|
||||
listeners.add(wake);
|
||||
return () => { listeners.delete(wake); };
|
||||
}
|
||||
function waitingRetirementIds() {
|
||||
return [...deferredRetirements].filter(([, owner]) => owner.scope === scope && !owner.ready).map(([id]) => id);
|
||||
}
|
||||
async function nextCleanupAt() {
|
||||
const waiting = waitingRetirementIds();
|
||||
const rows = await db.select({ at: adapterAuthSessions.expiresAt }).from(adapterAuthSessions).where(and(
|
||||
eq(adapterAuthSessions.connectionMethod, LOCAL_LOGIN_METHOD), isNotNull(adapterAuthSessions.expiresAt),
|
||||
waiting.length ? notInArray(adapterAuthSessions.id, waiting) : undefined,
|
||||
)).orderBy(adapterAuthSessions.expiresAt).limit(1);
|
||||
return rows[0]?.at?.getTime() ?? null;
|
||||
}
|
||||
function stopBrowserLogin(id: string): Promise<void> {
|
||||
const pending = browserRetirements.get(id);
|
||||
if (pending) return pending;
|
||||
const owner = browserLogins.get(id);
|
||||
const retirement = Promise.resolve().then(() => owner?.abort()).then(() => {
|
||||
if (browserLogins.get(id) === owner) browserLogins.delete(id);
|
||||
retirementReady(id);
|
||||
});
|
||||
browserRetirements.set(id, retirement);
|
||||
const release = () => { if (browserRetirements.get(id) === retirement) browserRetirements.delete(id); };
|
||||
void retirement.then(release, release);
|
||||
return retirement;
|
||||
}
|
||||
async function retireOwnedAttempt(companyId: string, userId: string, id: string, managementContext?: ConnectionManagementContext) {
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
const retirement = stopBrowserLogin(id);
|
||||
try {
|
||||
await Promise.race([retirement, new Promise<never>((_resolve, reject) => {
|
||||
timeout = setTimeout(() => reject(new Error(RETIREMENT_PENDING)), BROWSER_STOP_WAIT_MS);
|
||||
})]);
|
||||
} catch {
|
||||
retainRetirement(id, retirement);
|
||||
// Keep the active claim and private home. The existing expiry worker may
|
||||
// join the original retirement without holding a database transaction.
|
||||
await db.transaction(async tx => {
|
||||
const [session] = await tx.select().from(adapterAuthSessions).where(and(
|
||||
eq(adapterAuthSessions.id, id), eq(adapterAuthSessions.companyId, companyId),
|
||||
eq(adapterAuthSessions.startedByUserId, userId), eq(adapterAuthSessions.connectionMethod, LOCAL_LOGIN_METHOD),
|
||||
)).for("update");
|
||||
if (!session) return;
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.localLoginCleanup);
|
||||
const now = new Date();
|
||||
await tx.update(adapterAuthSessions).set({ expiresAt: session.expiresAt && session.expiresAt < now ? session.expiresAt : now,
|
||||
failureReason: RETIREMENT_PENDING, updatedAt: now })
|
||||
.where(eq(adapterAuthSessions.id, id));
|
||||
await logActivity(tx as unknown as Db, {
|
||||
companyId, ...(managementContext?.audit ?? { actorType: "user" as const, actorId: userId }),
|
||||
action: "ai_connection.local_login_cleanup_requested", entityType: "adapter_auth_session", entityId: id,
|
||||
details: { provider: session.aiConnection?.provider },
|
||||
});
|
||||
});
|
||||
throw unprocessable("The previous sign-in is still stopping. Retry shortly.", { code: "ai_connection_busy" });
|
||||
} finally { clearTimeout(timeout); }
|
||||
}
|
||||
function ensureBrowserLogin(id: string, provider: string) {
|
||||
if (provider === "xai" || browserLogins.has(id)) return;
|
||||
browserLogins.set(id, startLocalBrowserLogin(provider as "anthropic" | "openai", loginHome(id)));
|
||||
browserLogins.set(id, startLocalBrowserLogin(provider as "anthropic" | "openai" | "google", loginHome(id)));
|
||||
}
|
||||
async function reapExpired() {
|
||||
// Bounded batches use the existing expires-at index. Replaying is safe.
|
||||
// Waiting native owners have a completion wake, not a retry deadline. The
|
||||
// durable expiry remains unchanged and reconstructs cleanup after restart.
|
||||
const waiting = waitingRetirementIds();
|
||||
const rows = await db.select({ id: adapterAuthSessions.id }).from(adapterAuthSessions)
|
||||
.where(and(eq(adapterAuthSessions.connectionMethod, LOCAL_LOGIN_METHOD),
|
||||
lte(adapterAuthSessions.expiresAt, new Date())))
|
||||
.orderBy(adapterAuthSessions.expiresAt).limit(100);
|
||||
for (const row of rows) {
|
||||
lte(adapterAuthSessions.expiresAt, new Date()), waiting.length ? notInArray(adapterAuthSessions.id, waiting) : undefined))
|
||||
.orderBy(adapterAuthSessions.expiresAt).limit(CLEANUP_BATCH_SIZE);
|
||||
// Include completed owners even if a prior cleanup committed but its reply
|
||||
// was lost. Only a durable read may release that uncertain obligation.
|
||||
const ready = [...deferredRetirements].filter(([, owner]) => owner.scope === scope && owner.ready).map(([id]) => id);
|
||||
const ids = [...new Set([...ready.slice(0, CLEANUP_BATCH_SIZE), ...rows.map(row => row.id)])];
|
||||
if (!ids.length) return;
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
const budget = new Promise<false>(resolve => { timeout = setTimeout(() => resolve(false), BROWSER_STOP_WAIT_MS); });
|
||||
async function cleanup(id: string) {
|
||||
const retirement = stopBrowserLogin(id);
|
||||
const retired = await Promise.race([retirement.then(() => true, () => false), budget]);
|
||||
if (!retired) { retainRetirement(id, retirement); return; }
|
||||
await db.transaction(async (tx) => {
|
||||
const [session] = await tx.select().from(adapterAuthSessions)
|
||||
.where(eq(adapterAuthSessions.id, row.id)).for("update");
|
||||
if (!session || !session.expiresAt || session.expiresAt.getTime() > Date.now()) return;
|
||||
stopBrowserLogin(row.id);
|
||||
await rm(loginHome(row.id), { recursive: true, force: true });
|
||||
.where(eq(adapterAuthSessions.id, id)).for("update");
|
||||
if (!session || session.connectionMethod !== LOCAL_LOGIN_METHOD || !session.expiresAt) {
|
||||
deferredRetirements.delete(id);
|
||||
return;
|
||||
}
|
||||
if (session.expiresAt.getTime() > Date.now()) return;
|
||||
await rm(loginHome(id), { recursive: true, force: true });
|
||||
await tx.update(adapterAuthSessions).set({
|
||||
status: session.connectionId ? "authenticated" : "timed_out",
|
||||
status: session.connectionId ? "authenticated" : session.failureReason === RETIREMENT_PENDING ? "cancelled" : "timed_out",
|
||||
failureReason: null,
|
||||
expiresAt: null, finishedAt: session.finishedAt ?? new Date(), updatedAt: new Date(),
|
||||
}).where(eq(adapterAuthSessions.id, row.id));
|
||||
}).where(eq(adapterAuthSessions.id, id));
|
||||
});
|
||||
deferredRetirements.delete(id);
|
||||
}
|
||||
try {
|
||||
const failures: unknown[] = [];
|
||||
for (let offset = 0; offset < ids.length; offset += CLEANUP_CONCURRENCY) {
|
||||
const results = await Promise.allSettled(ids.slice(offset, offset + CLEANUP_CONCURRENCY).map(cleanup));
|
||||
for (const result of results) if (result.status === "rejected") failures.push(result.reason);
|
||||
}
|
||||
if (failures.length) throw new AggregateError(failures, "Local sign-in expiry cleanup failed");
|
||||
} finally { clearTimeout(timeout); }
|
||||
}
|
||||
|
||||
async function start(companyId: string, userId: string, intent: AiConnectionLoginIntent, restart = false, managementContext?: ConnectionManagementContext): Promise<LocalAiLoginAttempt> {
|
||||
if (intent.provider !== "openai" && intent.provider !== "xai" && intent.provider !== "anthropic")
|
||||
if (!["openai", "xai", "anthropic", "google"].includes(intent.provider))
|
||||
throw unprocessable("This provider does not use a separate local login home.");
|
||||
await reapExpired();
|
||||
// Expiry is owned by the durable localLoginCleanup deadline. Starting a
|
||||
// sign-in must not wait for another user's or provider's native retirement.
|
||||
await managementContext?.reauthorize();
|
||||
const adapterType = intent.provider === "google" ? "paperclip_runner" : intent.provider === "openai" ? "codex_local" : intent.provider === "anthropic" ? "claude_local" : "grok_local";
|
||||
let retiredAttemptId: string | undefined;
|
||||
if (restart) {
|
||||
const [existing] = await db.select().from(adapterAuthSessions).where(and(
|
||||
eq(adapterAuthSessions.companyId, companyId), eq(adapterAuthSessions.startedByUserId, userId),
|
||||
eq(adapterAuthSessions.adapterType, adapterType), inArray(adapterAuthSessions.status, [...ADAPTER_AUTH_SESSION_ACTIVE_STATES]),
|
||||
));
|
||||
if (existing) {
|
||||
if (existing.connectionMethod !== LOCAL_LOGIN_METHOD) throw unprocessable("Another sign-in is still open. Finish or cancel it before starting again.");
|
||||
retiredAttemptId = existing.id;
|
||||
await retireOwnedAttempt(companyId, userId, existing.id, managementContext);
|
||||
}
|
||||
}
|
||||
const attempt = await db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`ai-local-login:${companyId}:${userId}:${intent.provider}`}, 0))`);
|
||||
const adapterType = intent.provider === "openai" ? "codex_local" : intent.provider === "anthropic" ? "claude_local" : "grok_local";
|
||||
const [existing] = await tx.select().from(adapterAuthSessions).where(and(
|
||||
eq(adapterAuthSessions.companyId, companyId), eq(adapterAuthSessions.startedByUserId, userId),
|
||||
eq(adapterAuthSessions.adapterType, adapterType),
|
||||
@@ -106,9 +231,9 @@ export function localAiLoginService(db: Db) {
|
||||
}
|
||||
if (!restart || existing.connectionMethod !== LOCAL_LOGIN_METHOD)
|
||||
throw unprocessable("Another sign-in is still open. Finish it, or choose Start sign-in again to replace a local attempt.");
|
||||
stopBrowserLogin(existing.id);
|
||||
if (existing.id !== retiredAttemptId) throw unprocessable("The sign-in attempt changed. Retry Start sign-in again.");
|
||||
await rm(loginHome(existing.id), { recursive: true, force: true });
|
||||
await tx.update(adapterAuthSessions).set({ status: "cancelled", finishedAt: new Date(), updatedAt: new Date() })
|
||||
await tx.update(adapterAuthSessions).set({ status: "cancelled", expiresAt: null, failureReason: null, finishedAt: new Date(), updatedAt: new Date() })
|
||||
.where(eq(adapterAuthSessions.id, existing.id));
|
||||
await logActivity(tx as unknown as Db, {
|
||||
companyId, ...(managementContext?.audit ?? { actorType: "user" as const, actorId: userId }), action: "ai_connection.local_login_cancelled",
|
||||
@@ -143,6 +268,7 @@ export function localAiLoginService(db: Db) {
|
||||
}
|
||||
return presentAttempt(id, expiresAt, intent.provider);
|
||||
});
|
||||
if (retiredAttemptId) deferredRetirements.delete(retiredAttemptId);
|
||||
ensureBrowserLogin(attempt.sessionId, intent.provider);
|
||||
return attempt;
|
||||
}
|
||||
@@ -167,8 +293,9 @@ export function localAiLoginService(db: Db) {
|
||||
directory = loginHome(id);
|
||||
}
|
||||
try {
|
||||
await readVerifiedLocalAiCredential(intent.provider, directory);
|
||||
return { status: "ready" };
|
||||
if (intent.provider === "google" && browserLogins.get(id!)?.outcome !== "success") throw new Error("Google sign-in is incomplete");
|
||||
const verified = await readVerifiedLocalAiCredentialDetails(intent.provider, directory);
|
||||
return { status: "ready", ...(verified.accountLabel ? { accountLabel: verified.accountLabel } : {}) };
|
||||
} catch {
|
||||
const login = id ? browserLogins.get(id) : undefined;
|
||||
return { status: "sign_in_required", authorizationUrl: login?.authorizationUrl, code: login?.code,
|
||||
@@ -219,13 +346,15 @@ export function localAiLoginService(db: Db) {
|
||||
if (session.connectionMethod !== LOCAL_LOGIN_METHOD || session.status !== "waiting_for_user" ||
|
||||
!session.expiresAt || session.expiresAt.getTime() <= Date.now())
|
||||
throw unprocessable("This sign-in attempt has expired or was cancelled. Start sign-in again.");
|
||||
const credential = await readVerifiedLocalAiCredential(intent.provider, loginHome(id));
|
||||
if (intent.provider === "google" && browserLogins.get(id)?.outcome !== "success")
|
||||
throw unprocessable("Finish Google browser sign-in before connecting. If the server restarted, start sign-in again.");
|
||||
const verified = await readVerifiedLocalAiCredentialDetails(intent.provider, loginHome(id));
|
||||
await tx.update(adapterAuthSessions).set({ status: "promoting", updatedAt: new Date() })
|
||||
.where(eq(adapterAuthSessions.id, id));
|
||||
// Nested transaction is a savepoint on this same connection. Holding the
|
||||
// attempt lock makes completion/cancellation/restart retries idempotent.
|
||||
const saved = await aiConnectionService(tx as unknown as Db)
|
||||
.save(companyId, userId, intent, credential, { id }, session.createdAt, managementContext);
|
||||
.save(companyId, userId, intent, verified.credential, { id }, session.createdAt, managementContext, verified.accountLabel);
|
||||
await tx.update(adapterAuthSessions).set({
|
||||
status: "authenticated", connectionMethod: LOCAL_LOGIN_METHOD,
|
||||
finishedAt: new Date(), updatedAt: new Date(),
|
||||
@@ -233,13 +362,20 @@ export function localAiLoginService(db: Db) {
|
||||
return saved;
|
||||
});
|
||||
// Failed cleanup can be retried by the same completed attempt or reaper.
|
||||
stopBrowserLogin(id);
|
||||
await stopBrowserLogin(id);
|
||||
await rm(loginHome(id), { recursive: true, force: true });
|
||||
deferredRetirements.delete(id);
|
||||
return result;
|
||||
}
|
||||
|
||||
async function cancel(companyId: string, userId: string, id: string, managementContext?: ConnectionManagementContext) {
|
||||
await managementContext?.reauthorize();
|
||||
const [owned] = await db.select().from(adapterAuthSessions).where(and(
|
||||
eq(adapterAuthSessions.id, id), eq(adapterAuthSessions.companyId, companyId),
|
||||
eq(adapterAuthSessions.startedByUserId, userId), eq(adapterAuthSessions.connectionMethod, LOCAL_LOGIN_METHOD),
|
||||
));
|
||||
if (!owned) throw notFound("Local sign-in attempt not found.");
|
||||
await retireOwnedAttempt(companyId, userId, id, managementContext);
|
||||
await db.transaction(async (tx) => {
|
||||
const [session] = await tx.select().from(adapterAuthSessions).where(and(
|
||||
eq(adapterAuthSessions.id, id), eq(adapterAuthSessions.companyId, companyId),
|
||||
@@ -247,11 +383,10 @@ export function localAiLoginService(db: Db) {
|
||||
eq(adapterAuthSessions.connectionMethod, LOCAL_LOGIN_METHOD),
|
||||
)).for("update");
|
||||
if (!session) throw notFound("Local sign-in attempt not found.");
|
||||
stopBrowserLogin(id);
|
||||
await rm(loginHome(id), { recursive: true, force: true });
|
||||
if (!session.connectionId && session.status !== "cancelled") {
|
||||
await tx.update(adapterAuthSessions).set({
|
||||
status: "cancelled", finishedAt: new Date(), updatedAt: new Date(),
|
||||
status: "cancelled", expiresAt: null, failureReason: null, finishedAt: new Date(), updatedAt: new Date(),
|
||||
}).where(eq(adapterAuthSessions.id, id));
|
||||
await logActivity(tx as unknown as Db, {
|
||||
companyId, ...(managementContext?.audit ?? { actorType: "user" as const, actorId: userId }), action: "ai_connection.local_login_cancelled",
|
||||
@@ -260,6 +395,7 @@ export function localAiLoginService(db: Db) {
|
||||
});
|
||||
}
|
||||
});
|
||||
deferredRetirements.delete(id);
|
||||
}
|
||||
return { start, check, submitCode, complete, cancel, reapExpired };
|
||||
return { start, check, submitCode, complete, cancel, reapExpired, nextCleanupAt, subscribeCleanupReady };
|
||||
}
|
||||
@@ -9,6 +9,19 @@ const authorize = (value: unknown) => ({ [ACPX_QUALIFICATION_ENV]: JSON.stringif
|
||||
describe("host ACPX qualification admission", () => {
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
it.each([undefined, "malformed", JSON.stringify([{ agent: "antigravity", model: "exact-model" }])])(
|
||||
"keeps pending Antigravity closed despite host authorization (%s)", host => {
|
||||
vi.stubEnv(ACPX_QUALIFICATION_ENV, host);
|
||||
const config = { provider: "acpx", acpxAgent: "antigravity", model: "exact-model",
|
||||
env: { [ACPX_QUALIFICATION_ENV]: JSON.stringify([{ agent: "antigravity", model: "exact-model" }]) } };
|
||||
for (const resolve of [() => resolvePaperclipRunnerProviderProfile(config),
|
||||
() => resolvePaperclipRunnerNativeProviderInput({ backend: "acpx_runtime", adapterConfig: config })]) {
|
||||
expect(resolve).toThrow(expect.objectContaining({ code: "paperclip_runner_acpx_agent_unavailable" }));
|
||||
expect(resolve).toThrow("Google Antigravity is awaiting native Runner acceptance");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("admits only the exact Pi model without host authorization and preserves permission modes", () => {
|
||||
const config = { provider: "acpx", acpxAgent: "pi", model: "openrouter/deepseek/deepseek-v4-flash-0731" };
|
||||
for (const authorization of [undefined, "malformed unrelated candidate authorization"]) {
|
||||
|
||||
@@ -1,5 +1,27 @@
|
||||
import { PAPERCLIP_RUNNER_ACPX_PROFILES } from "@paperclipai/adapter-utils";
|
||||
import type { NativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
|
||||
import { parseAcpxCandidateAdmission, type AcpxCandidateAdmission, type NativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
|
||||
|
||||
/** Trusted operator startup authority, separate from saved agent configuration. */
|
||||
export const ANTIGRAVITY_CANDIDATE_ADMISSION_ENV = "PAPERCLIP_ACPX_CANDIDATE_ADMISSION";
|
||||
|
||||
export function resolveAntigravityCandidateAdmission(
|
||||
input: { companyId?: string; model?: string },
|
||||
hostEnvironment: NodeJS.ProcessEnv = process.env,
|
||||
): AcpxCandidateAdmission | undefined {
|
||||
const encoded = hostEnvironment[ANTIGRAVITY_CANDIDATE_ADMISSION_ENV];
|
||||
if (!encoded || !input.companyId || process.platform !== "darwin" || process.arch !== "arm64") return undefined;
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(encoded); } catch { throw new Error("Invalid Antigravity candidate admission"); }
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid Antigravity candidate admission");
|
||||
const record = value as Record<string, unknown>;
|
||||
// Other companies receive no candidate surface or execution authority.
|
||||
if (record.companyId !== input.companyId) return undefined;
|
||||
return parseAcpxCandidateAdmission(value, {
|
||||
companyId: input.companyId,
|
||||
agent: "antigravity",
|
||||
model: input.model ?? (typeof record.model === "string" ? record.model : ""),
|
||||
});
|
||||
}
|
||||
|
||||
/** Operator-only admission for an exact candidate/model during qualification. */
|
||||
export const ACPX_QUALIFICATION_ENV = "PAPERCLIP_RUNNER_ACPX_QUALIFICATION";
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { QUALIFIED_ACPX_PROFILES } from "../../vendor/paperclip-runner/index.js";
|
||||
import { ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, resolveAntigravityCandidateAdmission } from "./acpx-qualification.js";
|
||||
import { resolvePaperclipRunnerNativeProviderInput, resolvePaperclipRunnerProviderProfile } from "./provider-profile.js";
|
||||
import { resolveNativeRuntimeMode } from "./runtime-mode.js";
|
||||
|
||||
const companyId = "candidate-company";
|
||||
const model = "gemini-3.8-flash-low";
|
||||
const config = { provider: "acpx", acpxAgent: "antigravity", model };
|
||||
const localHost = process.platform === "darwin" && process.arch === "arm64";
|
||||
const distributions = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/antigravity-distributions.json", import.meta.url), "utf8"));
|
||||
const admission = () => ({ schema: "paperclip.acpx-candidate-admission.v1", companyId,
|
||||
agent: "antigravity", model, profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest,
|
||||
nativeClosureDigest: `sha256:${distributions.platforms["darwin-arm64"].closureSha256}`,
|
||||
platform: "darwin", architecture: "arm64", expiresAt: Date.now() + 60_000 });
|
||||
|
||||
describe("Antigravity operator candidate admission", () => {
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
it("keeps saved configuration and runtime environment from authorizing a candidate", () => {
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, undefined);
|
||||
const injected = { ...config, candidateAdmission: admission(),
|
||||
env: { [ANTIGRAVITY_CANDIDATE_ADMISSION_ENV]: JSON.stringify(admission()) } };
|
||||
expect(() => resolvePaperclipRunnerProviderProfile(injected, { companyId }))
|
||||
.toThrow(expect.objectContaining({ code: "paperclip_runner_acpx_agent_unavailable" }));
|
||||
});
|
||||
|
||||
it("requires explicit company authority and never projects it to another company", () => {
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, JSON.stringify(admission()));
|
||||
expect(resolveAntigravityCandidateAdmission({})).toBeUndefined();
|
||||
expect(resolveAntigravityCandidateAdmission({ companyId: "another-company", model })).toBeUndefined();
|
||||
expect(() => resolvePaperclipRunnerProviderProfile(config)).toThrow(/awaiting native Runner acceptance/);
|
||||
expect(() => resolvePaperclipRunnerProviderProfile(config, { companyId: "another-company" }))
|
||||
.toThrow(/awaiting native Runner acceptance/);
|
||||
});
|
||||
|
||||
it("admits only the exact configured local candidate while leaving global release pending", () => {
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, JSON.stringify(admission()));
|
||||
expect(QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus).toBe("pending");
|
||||
if (!localHost) {
|
||||
expect(resolveAntigravityCandidateAdmission({ companyId, model })).toBeUndefined();
|
||||
return;
|
||||
}
|
||||
expect(resolveAntigravityCandidateAdmission({ companyId })).toMatchObject({ companyId, model, agent: "antigravity" });
|
||||
expect(resolvePaperclipRunnerProviderProfile(config, { companyId })).toMatchObject(config);
|
||||
expect(resolvePaperclipRunnerNativeProviderInput({ backend: "acpx_runtime", adapterConfig: config, companyId }))
|
||||
.toMatchObject({ ...config, acpxPermissionMode: "approve-all" });
|
||||
expect(() => resolvePaperclipRunnerProviderProfile({ ...config, model: "different-model" }, { companyId }))
|
||||
.toThrow(expect.objectContaining({ code: "paperclip_runner_acpx_qualification_invalid" }));
|
||||
expect(resolveNativeRuntimeMode({ enabled: false, runtimeConfig: {}, adapterConfig: config,
|
||||
agent: { id: "candidate-agent", companyId, adapterType: "paperclip_runner", status: "active" },
|
||||
issue: { id: "candidate-task", workMode: "standard" }, target: { kind: "local" }, workspaceId: null }))
|
||||
.toMatchObject({ kind: "native", profile: { backend: "acpx_runtime" } });
|
||||
});
|
||||
|
||||
it.runIf(localHost).each([
|
||||
{ expiresAt: 0 }, { profileDigest: `sha256:${"0".repeat(64)}` },
|
||||
{ nativeClosureDigest: `sha256:${"0".repeat(64)}` }, { platform: "linux" },
|
||||
{ architecture: "x64" }, { allowAll: true },
|
||||
])("rejects expired, changed or broad operator authorization %j", changes => {
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, JSON.stringify({ ...admission(), ...changes }));
|
||||
expect(() => resolveAntigravityCandidateAdmission({ companyId, model })).toThrow();
|
||||
expect(() => resolvePaperclipRunnerProviderProfile(config, { companyId }))
|
||||
.toThrow(expect.objectContaining({ code: "paperclip_runner_acpx_qualification_invalid" }));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { access, readFile, rm } from "node:fs/promises";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const homes = vi.hoisted(() => [] as string[]);
|
||||
const removal = vi.hoisted(() => ({ failures: 0 }));
|
||||
vi.mock("node:fs/promises", async importOriginal => {
|
||||
const actual = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return { ...actual, rm: async (...args: Parameters<typeof actual.rm>) => {
|
||||
if (removal.failures && String(args[0]).split("/").at(-1)?.startsWith("paperclip-google-recovery-")) {
|
||||
removal.failures -= 1;
|
||||
await actual.rm(join(String(args[0]), "antigravity-acp", "acp_token.json"), { force: true });
|
||||
throw new Error("fixture partial home removal");
|
||||
}
|
||||
return actual.rm(...args);
|
||||
}, mkdtemp: async (...args: Parameters<typeof actual.mkdtemp>) => {
|
||||
const home = await actual.mkdtemp(...args);
|
||||
homes.push(String(home));
|
||||
return home;
|
||||
} };
|
||||
});
|
||||
import { prepareAntigravityCredentialRecovery } from "./antigravity-runner-credentials.js";
|
||||
import { reconcileRetainedGoogleCleanup } from "../retained-google-credential-cleanup.js";
|
||||
|
||||
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"],
|
||||
});
|
||||
afterEach(async () => {
|
||||
removal.failures = 0;
|
||||
vi.unstubAllGlobals();
|
||||
await Promise.all(homes.splice(0).map(home => rm(home, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
describe("retired Google verification ownership", () => {
|
||||
it("retries partial home removal without reusing an already handed-off token", async () => {
|
||||
const scope = { companyId: randomUUID(), accountKey: randomUUID() };
|
||||
const persistVerified = vi.fn().mockResolvedValue(undefined);
|
||||
const request = vi.fn().mockResolvedValueOnce(Response.json({ access_token: "fixture-access", refresh_token: "fixture-latest" }))
|
||||
.mockResolvedValueOnce(Response.json({ email_verified: true, email: "alice@example.test" }));
|
||||
vi.stubGlobal("fetch", request);
|
||||
removal.failures = 1;
|
||||
await expect(prepareAntigravityCredentialRecovery({ originalCredential: credential("fixture-original"),
|
||||
refreshedCredential: credential("fixture-retired"), accountEmail: "alice@example.test", scope, persistVerified,
|
||||
})).rejects.toThrow("fixture partial home removal");
|
||||
await reconcileRetainedGoogleCleanup(scope);
|
||||
expect(persistVerified).toHaveBeenCalledOnce();
|
||||
expect(request).toHaveBeenCalledTimes(2);
|
||||
await expect(access(homes.at(-1)!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
it("keeps the newest rotated token until verified encrypted replacement succeeds", async () => {
|
||||
const scope = { companyId: randomUUID(), accountKey: randomUUID() };
|
||||
const persistVerified = vi.fn().mockRejectedValueOnce(new Error("fixture encrypted replacement unavailable")).mockResolvedValue(undefined);
|
||||
const request = vi.fn()
|
||||
.mockResolvedValueOnce(Response.json({ access_token: "fixture-access", refresh_token: "fixture-latest" }))
|
||||
.mockResolvedValueOnce(Response.json({ email_verified: true, email: "alice@example.test" }))
|
||||
.mockResolvedValueOnce(Response.json({ access_token: "fixture-access", refresh_token: "fixture-retried" }))
|
||||
.mockResolvedValueOnce(Response.json({ email_verified: true, email: "alice@example.test" }));
|
||||
vi.stubGlobal("fetch", request);
|
||||
await expect(prepareAntigravityCredentialRecovery({ originalCredential: credential("fixture-original"),
|
||||
refreshedCredential: credential("fixture-retired"), accountEmail: "alice@example.test", scope, persistVerified,
|
||||
})).rejects.toThrow("fixture encrypted replacement unavailable");
|
||||
const home = homes.at(-1)!;
|
||||
expect(await readFile(join(home, "antigravity-acp", "acp_token.json"), "utf8")).toBe(credential("fixture-latest"));
|
||||
expect(persistVerified).toHaveBeenNthCalledWith(1, credential("fixture-latest"));
|
||||
await reconcileRetainedGoogleCleanup(scope);
|
||||
expect(new URLSearchParams(request.mock.calls[2][1].body).get("refresh_token")).toBe("fixture-latest");
|
||||
expect(persistVerified).toHaveBeenNthCalledWith(2, credential("fixture-retried"));
|
||||
await expect(access(home)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,353 @@
|
||||
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 { antigravityCredentialTurn, bindAntigravityCredentialTurn, bindAntigravityTransportRetirement, prepareAntigravityRunnerCredentials } from "./antigravity-runner-credentials.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";
|
||||
|
||||
const copyFault = vi.hoisted(() => ({ phase: "", destination: "", source: "", collisionPath: "", failedRemoval: "", removals: [] as string[], hits: 0 }));
|
||||
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 () => { 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", GOOGLE_API_KEY: "other", 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("projects only the selected private token and rejects remote subscription delivery", async () => {
|
||||
const managedHome = await home();
|
||||
await writeFile(join(managedHome, "antigravity-acp", "acp_token.json"), credential("fixture-selected"), { mode: 0o600 });
|
||||
expect(await prepareAntigravityRunnerCredentials({ remote: false, managedHome, environment: { GEMINI_HOME: "/untrusted" } })).toEqual({
|
||||
home: managedHome, credential: credential("fixture-selected"), environment: { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: credential("fixture-selected") },
|
||||
});
|
||||
await expect(prepareAntigravityRunnerCredentials({ remote: true, managedHome, environment: {} })).rejects.toThrow("not qualified for remote");
|
||||
await expect(prepareAntigravityRunnerCredentials({ remote: false, managedHome, environment: {}, lifecycleMode: "warm" })).rejects.toThrow("warm sessions are not qualified");
|
||||
});
|
||||
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 preparing another launch for the same account", 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.toThrow("still completing credential cleanup");
|
||||
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 account reuse, 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.toThrow("still completing credential cleanup");
|
||||
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"));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,357 @@
|
||||
import { constants } from "node:fs";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdir, mkdtemp, realpath, rename, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { sanitizeAntigravityCredential, verifyAntigravityCredential } from "../../vendor/paperclip-runner/index.js";
|
||||
import { readLocalAiCredentialFile } from "../local-ai-credential-file.js";
|
||||
import { reconcileRetainedGoogleCleanupForHome, retainGoogleCredentialCleanupForHome, retainGoogleCredentialCleanup, type RetainedGoogleCleanupScope } from "../retained-google-credential-cleanup.js";
|
||||
import { withDirectoryMergeLock } from "@paperclipai/adapter-utils/workspace-restore-merge";
|
||||
import { withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server";
|
||||
import { openRunnerWorkspaceFile } from "./runner-api-files.js";
|
||||
import type { NativeSession, createRunnerdCodexTransport } from "../../vendor/paperclip-runner/index.js";
|
||||
import { bindManagedNativeCredentialTurn } from "./managed-native-credentials.js";
|
||||
|
||||
const AUTH_SECRET = "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET";
|
||||
const TOKEN_FILE = "acp_token.json";
|
||||
const REFRESH_FILE = "auth-refresh.json";
|
||||
const retirementProofs = new WeakMap<object, () => Promise<void>>();
|
||||
type RunnerdTransport = ReturnType<typeof createRunnerdCodexTransport>;
|
||||
|
||||
/** Preserve the exact process owner's proof without changing a failed native
|
||||
* session's durable settlement error or making that session reusable. */
|
||||
export function bindAntigravityTransportRetirement(bundle: RunnerdTransport): RunnerdTransport["transport"] {
|
||||
const close = bundle.transport.close.bind(bundle.transport);
|
||||
bundle.transport.close = async reason => {
|
||||
try { await close(reason); }
|
||||
catch (error) {
|
||||
if (error && typeof error === "object" && bundle.retireProbeResources) {
|
||||
retirementProofs.set(error, () => bundle.retireProbeResources!());
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
return bundle.transport;
|
||||
}
|
||||
|
||||
/** Only explicit run credentials may enter Antigravity's isolated runtime. */
|
||||
export async function prepareAntigravityRunnerCredentials(input: {
|
||||
environment: NodeJS.ProcessEnv;
|
||||
remote: boolean;
|
||||
managedHome?: string;
|
||||
lifecycleMode?: "per_turn" | "warm";
|
||||
}): Promise<{ environment: NodeJS.ProcessEnv; home: string | null; credential?: string }> {
|
||||
const environment = { ...input.environment };
|
||||
for (const key of [AUTH_SECRET, "GEMINI_HOME", "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_ACCESS_TOKEN"]) delete environment[key];
|
||||
if (environment.GEMINI_API_KEY?.trim()) return { environment, home: null };
|
||||
delete environment.GEMINI_API_KEY;
|
||||
if (input.remote) throw new Error("Google Antigravity subscription authentication is not qualified for remote environments. Select a Google API key or use the Paperclip host.");
|
||||
if (input.lifecycleMode === "warm") throw new Error("Google Antigravity subscription authentication requires turn-by-turn sessions; warm sessions are not qualified.");
|
||||
const home = input.managedHome?.trim();
|
||||
if (!home) throw new Error("Google Antigravity requires a selected managed Google account or Google API key.");
|
||||
await reconcileRetainedGoogleCleanupForHome(home);
|
||||
let credential: string;
|
||||
try {
|
||||
credential = sanitizeAntigravityCredential(await readLocalAiCredentialFile(join(home, "antigravity-acp", TOKEN_FILE)));
|
||||
} catch {
|
||||
throw new Error("The selected Google Antigravity account is unavailable. Reconnect the Google account, then retry.");
|
||||
}
|
||||
environment[AUTH_SECRET] = credential;
|
||||
return { environment, home, credential };
|
||||
}
|
||||
|
||||
/** A changed refresh token must prove the same saved Google identity before
|
||||
* the connection owner may apply its generation-checked encrypted writeback. */
|
||||
export async function prepareAntigravityCredentialWriteback(input: {
|
||||
originalCredential: string;
|
||||
refreshedCredential: string;
|
||||
managedHome: string;
|
||||
accountEmail?: string;
|
||||
}): Promise<string> {
|
||||
const original = JSON.parse(sanitizeAntigravityCredential(input.originalCredential));
|
||||
const refreshed = sanitizeAntigravityCredential(input.refreshedCredential);
|
||||
const candidate = JSON.parse(refreshed);
|
||||
if (candidate.refresh_token === original.refresh_token && candidate.client_secret === original.client_secret) return refreshed;
|
||||
if (!input.accountEmail) throw new Error("The Google account identity is unavailable for credential refresh. Reconnect the account.");
|
||||
const verified = await verifyAntigravityCredential(input.managedHome);
|
||||
if (verified.accountEmail.toLowerCase() !== input.accountEmail.toLowerCase()) {
|
||||
throw new Error("The refreshed Google account does not match the selected connection.");
|
||||
}
|
||||
return verified.credential;
|
||||
}
|
||||
|
||||
/** Recover only an encrypted refresh from an owner that already retired. A
|
||||
* disposable verification home cannot inherit any provider process lifetime. */
|
||||
export async function prepareAntigravityCredentialRecovery(input: {
|
||||
originalCredential: string; refreshedCredential: string; accountEmail: string;
|
||||
scope: RetainedGoogleCleanupScope;
|
||||
persistVerified: (credential: string) => Promise<void>;
|
||||
}): Promise<string> {
|
||||
const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-google-recovery-")));
|
||||
const directory = join(home, "antigravity-acp");
|
||||
try {
|
||||
await mkdir(directory, { mode: 0o700 });
|
||||
await writeFile(join(directory, TOKEN_FILE), sanitizeAntigravityCredential(input.refreshedCredential), { flag: "wx", mode: 0o600 });
|
||||
} catch (error) {
|
||||
await rm(home, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
let verified: string | undefined;
|
||||
let persisted = false;
|
||||
const cleanup = () => withAccountHomeSecretMutationLock(undefined, input.scope.companyId, async () => {
|
||||
// A failed verification may itself have rotated the token. Retry the
|
||||
// private home's current generation, never the earlier journal value.
|
||||
if (!persisted) {
|
||||
const refreshedCredential = await readLocalAiCredentialFile(join(directory, TOKEN_FILE));
|
||||
verified = await prepareAntigravityCredentialWriteback({ ...input, refreshedCredential, managedHome: home });
|
||||
await input.persistVerified(verified);
|
||||
persisted = true;
|
||||
}
|
||||
await rm(home, { recursive: true, force: true });
|
||||
});
|
||||
try {
|
||||
await cleanup();
|
||||
return verified!;
|
||||
} catch (error) {
|
||||
retainGoogleCredentialCleanup({ scope: input.scope, cleanup, home });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Lifecycle callbacks copy into this invocation's home, never a shared login. */
|
||||
export function antigravityCredentialTurn(input: {
|
||||
managedHome: string;
|
||||
runtimeHome: string;
|
||||
credential: string;
|
||||
}) {
|
||||
const runtimeDirectory = join(input.runtimeHome, "antigravity-acp");
|
||||
const destination = join(input.managedHome, "antigravity-acp", TOKEN_FILE);
|
||||
let pendingStage: { path: string; directoryDev: number; directoryIno: number; dev?: number; ino?: number } | undefined;
|
||||
return {
|
||||
copyBack: async () => {
|
||||
let serialized: string;
|
||||
try {
|
||||
try { serialized = await readLocalAiCredentialFile(join(runtimeDirectory, TOKEN_FILE)); }
|
||||
catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||
serialized = await readLocalAiCredentialFile(join(runtimeDirectory, REFRESH_FILE));
|
||||
}
|
||||
} catch (error) {
|
||||
// A provider that never started has no refresh to preserve.
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT" && !pendingStage) return;
|
||||
throw new Error("Google Antigravity credential refresh handoff is invalid.");
|
||||
}
|
||||
const refreshed = sanitizeAntigravityCredential(serialized);
|
||||
if (refreshed === input.credential) {
|
||||
if (pendingStage) throw new Error("Google Antigravity credential refresh handoff is invalid.");
|
||||
return;
|
||||
}
|
||||
const destinationDirectory = join(input.managedHome, "antigravity-acp");
|
||||
await withDirectoryMergeLock(destinationDirectory, async () => {
|
||||
const directory = await openRunnerWorkspaceFile(destinationDirectory, constants.O_RDONLY | constants.O_DIRECTORY);
|
||||
let staged: Awaited<ReturnType<typeof openRunnerWorkspaceFile>> | undefined;
|
||||
let stagedOwned = false;
|
||||
const stagedPath = join(destinationDirectory, `.acp_token.copyback-${randomUUID()}.tmp`);
|
||||
let cleanupStage: (() => Promise<void>) | undefined;
|
||||
try {
|
||||
const owner = await directory.stat();
|
||||
if (!owner.isDirectory() || owner.uid !== process.getuid?.() || (owner.mode & 0o077) !== 0) {
|
||||
throw new Error("Google Antigravity credential destination is invalid.");
|
||||
}
|
||||
const assertDirectoryOwner = async () => {
|
||||
const current = await openRunnerWorkspaceFile(destinationDirectory, constants.O_RDONLY | constants.O_DIRECTORY);
|
||||
try {
|
||||
const metadata = await current.stat();
|
||||
if (metadata.dev !== owner.dev || metadata.ino !== owner.ino || metadata.uid !== owner.uid || (metadata.mode & 0o077) !== 0) {
|
||||
throw new Error("Google Antigravity credential destination changed during execution.");
|
||||
}
|
||||
} finally { await current.close(); }
|
||||
};
|
||||
cleanupStage = async () => {
|
||||
if (!pendingStage) return;
|
||||
if (pendingStage.directoryDev !== owner.dev || pendingStage.directoryIno !== owner.ino) {
|
||||
throw new Error("Google Antigravity credential staging ownership changed.");
|
||||
}
|
||||
if (pendingStage.dev === undefined || pendingStage.ino === undefined) {
|
||||
if (!staged) throw new Error("Google Antigravity credential staging ownership is unavailable.");
|
||||
const created = await staged.stat();
|
||||
pendingStage.dev = created.dev; pendingStage.ino = created.ino;
|
||||
}
|
||||
const previous = await openRunnerWorkspaceFile(pendingStage.path, constants.O_RDONLY)
|
||||
.catch((error: NodeJS.ErrnoException) => { if (error.code === "ENOENT") return null; throw error; });
|
||||
if (previous) {
|
||||
try {
|
||||
const metadata = await previous.stat();
|
||||
if (!metadata.isFile() || metadata.dev !== pendingStage.dev || metadata.ino !== pendingStage.ino
|
||||
|| metadata.nlink !== 1 || metadata.uid !== owner.uid || (metadata.mode & 0o777) !== 0o600) {
|
||||
throw new Error("Google Antigravity credential staging ownership changed.");
|
||||
}
|
||||
} finally { await previous.close(); }
|
||||
}
|
||||
await rm(pendingStage.path, { force: true });
|
||||
pendingStage = undefined;
|
||||
};
|
||||
// A failed removal remains this owner's obligation on the next retry.
|
||||
await cleanupStage();
|
||||
const readDestination = async (sync = false) => {
|
||||
const file = await openRunnerWorkspaceFile(destination, constants.O_RDONLY);
|
||||
const bytes = Buffer.alloc(65_537);
|
||||
try {
|
||||
const metadata = await file.stat();
|
||||
if (!metadata.isFile() || metadata.nlink !== 1 || metadata.uid !== process.getuid?.() || (metadata.mode & 0o777) !== 0o600 || metadata.size > 65_536) {
|
||||
throw new Error("Google Antigravity credential destination is invalid.");
|
||||
}
|
||||
let size = 0;
|
||||
while (size < bytes.length) {
|
||||
const result = await file.read(bytes, size, bytes.length - size, size);
|
||||
if (!result.bytesRead) break;
|
||||
size += result.bytesRead;
|
||||
}
|
||||
if (size > 65_536) throw new Error("Google Antigravity credential destination changed during execution.");
|
||||
const current = sanitizeAntigravityCredential(bytes.subarray(0, size).toString("utf8"));
|
||||
if (current !== input.credential && current !== refreshed) {
|
||||
throw new Error("Google Antigravity credential destination changed during execution.");
|
||||
}
|
||||
if (sync) await file.sync();
|
||||
return { metadata, current };
|
||||
} finally { bytes.fill(0); await file.close(); }
|
||||
};
|
||||
const original = await readDestination();
|
||||
if (original.current === refreshed) {
|
||||
// A previous rename may have committed before its directory fsync
|
||||
// or close failed. Confirm exactly that generation before cleanup.
|
||||
const synced = await readDestination(true);
|
||||
await directory.sync();
|
||||
await assertDirectoryOwner();
|
||||
const confirmed = await readDestination();
|
||||
if (synced.current !== refreshed || confirmed.current !== refreshed || confirmed.metadata.dev !== original.metadata.dev
|
||||
|| confirmed.metadata.ino !== original.metadata.ino || confirmed.metadata.mtimeMs !== original.metadata.mtimeMs
|
||||
|| confirmed.metadata.ctimeMs !== original.metadata.ctimeMs) {
|
||||
throw new Error("Google Antigravity credential destination changed during execution.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
staged = await openRunnerWorkspaceFile(stagedPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
|
||||
stagedOwned = true;
|
||||
pendingStage = { path: stagedPath, directoryDev: owner.dev, directoryIno: owner.ino };
|
||||
const created = await staged.stat();
|
||||
pendingStage.dev = created.dev; pendingStage.ino = created.ino;
|
||||
const replacement = Buffer.from(refreshed);
|
||||
let stagedMetadata;
|
||||
try {
|
||||
let written = 0;
|
||||
while (written < replacement.length) {
|
||||
const result = await staged.write(replacement, written, replacement.length - written, written);
|
||||
if (!result.bytesWritten) throw new Error("Google Antigravity credential copy-back failed.");
|
||||
written += result.bytesWritten;
|
||||
}
|
||||
await staged.sync();
|
||||
stagedMetadata = await staged.stat();
|
||||
if (!stagedMetadata.isFile() || stagedMetadata.nlink !== 1 || stagedMetadata.uid !== owner.uid
|
||||
|| (stagedMetadata.mode & 0o777) !== 0o600 || stagedMetadata.size !== replacement.length) {
|
||||
throw new Error("Google Antigravity credential staging file is invalid.");
|
||||
}
|
||||
} finally { replacement.fill(0); }
|
||||
await staged.close();
|
||||
staged = undefined;
|
||||
await assertDirectoryOwner();
|
||||
const current = await readDestination();
|
||||
if (current.current !== original.current || current.metadata.dev !== original.metadata.dev || current.metadata.ino !== original.metadata.ino
|
||||
|| current.metadata.mtimeMs !== original.metadata.mtimeMs || current.metadata.ctimeMs !== original.metadata.ctimeMs) {
|
||||
throw new Error("Google Antigravity credential destination changed during execution.");
|
||||
}
|
||||
// Never truncate the selected token. Publish only the fully synced
|
||||
// private same-directory file, then make its directory entry durable.
|
||||
await rename(stagedPath, destination);
|
||||
await directory.sync();
|
||||
await assertDirectoryOwner();
|
||||
const published = await readDestination();
|
||||
if (published.current !== refreshed || published.metadata.dev !== stagedMetadata.dev || published.metadata.ino !== stagedMetadata.ino) {
|
||||
throw new Error("Google Antigravity credential destination changed during execution.");
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
if (stagedOwned) await cleanupStage?.();
|
||||
} finally {
|
||||
try { await staged?.close(); } finally { await directory.close(); }
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
remove: async () => {
|
||||
const directory = await openRunnerWorkspaceFile(runtimeDirectory, constants.O_RDONLY | constants.O_DIRECTORY)
|
||||
.catch((error: NodeJS.ErrnoException) => { if (error.code === "ENOENT") return null; throw error; });
|
||||
if (!directory) return;
|
||||
try {
|
||||
const metadata = await directory.stat();
|
||||
if (!metadata.isDirectory() || metadata.uid !== process.getuid?.()) throw new Error("Google Antigravity credential cleanup home is invalid.");
|
||||
} finally { await directory.close(); }
|
||||
await Promise.all([TOKEN_FILE, REFRESH_FILE, `${REFRESH_FILE}.tmp`].map(name => rm(join(runtimeDirectory, name), { force: true })));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Google identity verification can itself rotate a refresh token. Retire the
|
||||
* native process before exporting its final token so no live in-memory client
|
||||
* can retain an older generation while the connection owner verifies/saves it. */
|
||||
export function bindAntigravityCredentialTurn(session: NativeSession, input: Parameters<typeof antigravityCredentialTurn>[0]): NativeSession {
|
||||
const callbacks = antigravityCredentialTurn(input);
|
||||
const close = session.close.bind(session);
|
||||
const detach = session.detachControllerForRestart?.bind(session);
|
||||
let retirement: Promise<void> | undefined;
|
||||
let retired = false;
|
||||
let detached = false;
|
||||
let copied = false;
|
||||
let removed = false;
|
||||
let handoffRunning: Promise<void> | undefined;
|
||||
let proveRetirement: (() => Promise<void>) | undefined;
|
||||
const retryRetirement = async () => {
|
||||
if (retired) return;
|
||||
if (!proveRetirement) throw new Error("Google Antigravity runtime retirement remains unconfirmed.");
|
||||
await proveRetirement();
|
||||
retired = true;
|
||||
};
|
||||
const retain = () => retainGoogleCredentialCleanupForHome(input.managedHome, {
|
||||
cleanup: handoff, ...(retired ? {} : { retired: retirement, ...(proveRetirement ? { retryRetirement } : {}) }),
|
||||
});
|
||||
const retire: NativeSession["close"] = options => retirement ??= Promise.resolve().then(() => close(options)).catch(error => {
|
||||
if (error && typeof error === "object") proveRetirement = retirementProofs.get(error);
|
||||
// close() may be called before the turn-completion callback. It still
|
||||
// owns the same private credential and must keep that account fenced.
|
||||
retain();
|
||||
throw error;
|
||||
});
|
||||
session.close = retire;
|
||||
if (detach) session.detachControllerForRestart = async () => { detached = true; await detach(); };
|
||||
const handoff = (): Promise<void> => handoffRunning ??= (async () => {
|
||||
if (detached) return;
|
||||
try {
|
||||
if (!retired) {
|
||||
await retire({ reason: "Google Antigravity subscription credential handoff" });
|
||||
retired = true;
|
||||
}
|
||||
if (!copied) { await callbacks.copyBack(); copied = true; }
|
||||
if (!removed) { await callbacks.remove(); removed = true; }
|
||||
} catch (error) {
|
||||
// Until copy-back succeeds, this private runtime can hold the only valid
|
||||
// rotated token. The same account must settle this owner before launch.
|
||||
retain();
|
||||
throw error;
|
||||
}
|
||||
})().finally(() => { handoffRunning = undefined; });
|
||||
bindManagedNativeCredentialTurn(session, {
|
||||
copyBack: handoff,
|
||||
remove: async () => {
|
||||
if (copied && !removed) { await callbacks.remove(); removed = true; }
|
||||
},
|
||||
});
|
||||
const managedClose = session.close.bind(session);
|
||||
session.close = async options => {
|
||||
if (detached) return;
|
||||
await managedClose(options);
|
||||
// The shared turn manager settles a failed turn once. Google retains its
|
||||
// failed handoff, so a later close also retries the original private files.
|
||||
if (!removed) await handoff();
|
||||
};
|
||||
return session;
|
||||
}
|
||||
@@ -140,6 +140,7 @@ type BackendFactoryOptions = {
|
||||
};
|
||||
|
||||
type RunnerTransportOptions = {
|
||||
environment?: NodeJS.ProcessEnv;
|
||||
acpxRuntimeDirectory?: string;
|
||||
adoptExistingRunner?: { pid: number; isAlive: () => Promise<boolean> | boolean };
|
||||
stateDirectory?: string;
|
||||
@@ -3772,10 +3773,12 @@ describe("runtime question fallback", () => {
|
||||
});
|
||||
|
||||
describe("native provider bootstrap environment", () => {
|
||||
it.each(["pi", "cursor", "copilot"] as const)("does not promote ambient %s credentials when bindings are omitted", agent => {
|
||||
it.each(["pi", "cursor", "copilot", "antigravity"] as const)("does not promote ambient %s credentials when bindings are omitted", agent => {
|
||||
const provider = { kind: "acpx", agent } as NativeExecutionInput["provider"];
|
||||
const host = { PATH: "/host/bin", HOME: "/host/home", OPENROUTER_API_KEY: "ambient-pi",
|
||||
CURSOR_API_KEY: "ambient-cursor", CURSOR_AUTH_TOKEN: "ambient-cursor-login", COPILOT_GITHUB_TOKEN: "ambient-copilot",
|
||||
GEMINI_API_KEY: "ambient-google", GOOGLE_API_KEY: "ambient-other-google", GEMINI_HOME: "/ambient-google-home",
|
||||
GOOGLE_APPLICATION_CREDENTIALS: "/ambient-google-credential.json", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "ambient-google-subscription",
|
||||
PAPERCLIP_ACPX_CREDENTIAL_BINDING: "ambient-forged-binding" };
|
||||
expect(resolveNativeProviderEnvironment(provider, undefined, host)).toEqual({ PATH: "/host/bin", HOME: "/host/home" });
|
||||
const explicit = { COPILOT_GITHUB_TOKEN: "explicit-company-binding" };
|
||||
@@ -11863,6 +11866,52 @@ describe("runnerd provider runtime wiring", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("projects the selected Antigravity subscription and copies refreshes from the exact native home after close", async () => {
|
||||
const priorHome = process.env.PAPERCLIP_HOME;
|
||||
const privateRoot = await realpath(isolatedStateDirectory);
|
||||
process.env.PAPERCLIP_HOME = privateRoot;
|
||||
const managedHome = join(privateRoot, "antigravity-managed-home");
|
||||
await mkdir(join(managedHome, "antigravity-acp"), { recursive: true, mode: 0o700 });
|
||||
const credential = (project?: string) => JSON.stringify({
|
||||
client_id: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com", client_secret: "fixture-client-secret",
|
||||
refresh_token: "fixture-google-refresh", 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"],
|
||||
...(project ? { project_id: project } : {}),
|
||||
});
|
||||
const managedToken = join(managedHome, "antigravity-acp", "acp_token.json");
|
||||
await writeFile(managedToken, credential(), { mode: 0o600 });
|
||||
const current = { ...execution,
|
||||
provider: { kind: "acpx", agent: "antigravity", model: "caller-selected-model", permissionMode: "deny-all" },
|
||||
session: { ...execution.session, driverKind: "acpx_runtime" },
|
||||
} as unknown as NativeExecutionInputV1;
|
||||
const transportClose = vi.fn(async () => undefined);
|
||||
const nativeTransport = { close: transportClose };
|
||||
state.createTransport.mockReturnValueOnce({ transport: nativeTransport } as never);
|
||||
const close = vi.fn(async () => nativeTransport.close());
|
||||
state.createBackend.mockReturnValueOnce({ kind: "test", openSession: async () => ({ close }) } as never);
|
||||
try {
|
||||
const backend = await createRunnerdBackend({ db: leaseDb(current), execution: current,
|
||||
runnerInstanceId: "antigravity-credential-close", managedAiCredentialHome: managedHome,
|
||||
runnerEnvironment: { GEMINI_HOME: "/ambient", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "spoofed" } });
|
||||
state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!();
|
||||
const transport = state.createTransport.mock.calls.at(-1)![0];
|
||||
expect(transport.environment).toMatchObject({ PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: credential() });
|
||||
expect(transport.environment?.GEMINI_HOME).toBeUndefined();
|
||||
await mkdir(transport.acpxRuntimeDirectory!, { recursive: true, mode: 0o700 });
|
||||
const runtimeHome = join(await resolveAcpxRuntimeRoot(transport.acpxRuntimeDirectory!, execution.session.normalizedSessionId!), "antigravity-home", "antigravity-acp");
|
||||
await mkdir(runtimeHome, { recursive: true, mode: 0o700 });
|
||||
for (const name of ["auth-refresh.json", "auth-refresh.json.tmp"]) await writeFile(join(runtimeHome, name), credential("resolved-project"), { mode: 0o600 });
|
||||
const session = await backend.openSession({} as never);
|
||||
await session.close({ reason: "completed" });
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
expect(transportClose).toHaveBeenCalledOnce();
|
||||
expect(await readFile(managedToken, "utf8")).toBe(credential("resolved-project"));
|
||||
for (const name of ["acp_token.json", "auth-refresh.json", "auth-refresh.json.tmp"]) await expect(access(join(runtimeHome, name))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} finally {
|
||||
if (priorHome === undefined) delete process.env.PAPERCLIP_HOME;
|
||||
else process.env.PAPERCLIP_HOME = priorHome;
|
||||
}
|
||||
});
|
||||
|
||||
it("still cleans up managed Codex credentials after an owned session closes", async () => {
|
||||
const close = vi.fn(async () => undefined);
|
||||
state.copyBackCodexAuth.mockClear();
|
||||
|
||||
@@ -42,9 +42,10 @@ import { readNativePlanWait } from "./native-plan-wait.js";
|
||||
import { nativeProviderLifecycle } from "./provider-lifecycle.js";
|
||||
import { NativePermissionDeclinedError, readCompletedNativePermissionDecline } from "./native-permission-decline.js";
|
||||
import { activeIssueInteractionCondition } from "../issue-question-context.js";
|
||||
import { resolveAcpxQualification } from "./acpx-qualification.js";
|
||||
import { resolveAcpxQualification, resolveAntigravityCandidateAdmission } from "./acpx-qualification.js";
|
||||
import { readLocalAiCredentialFile } from "../local-ai-credential-file.js";
|
||||
import { prepareGrokRunnerCredentials } from "./grok-runner-credentials.js";
|
||||
import { bindAntigravityCredentialTurn, bindAntigravityTransportRetirement, prepareAntigravityRunnerCredentials } from "./antigravity-runner-credentials.js";
|
||||
import { copyBackGrokAuth } from "@paperclipai/adapter-grok-local/server";
|
||||
|
||||
import { inferOpenAiCompatibleBiller, type AdapterUsageCheckpoint } from "@paperclipai/adapter-utils";
|
||||
@@ -907,7 +908,7 @@ export function resolveNativeProviderEnvironment(
|
||||
host: NodeJS.ProcessEnv = process.env,
|
||||
): NodeJS.ProcessEnv {
|
||||
if (configured !== undefined) return configured;
|
||||
if (provider.kind === "acpx" && ["pi", "cursor", "copilot"].includes(provider.agent)) {
|
||||
if (provider.kind === "acpx" && ["pi", "cursor", "copilot", "antigravity"].includes(provider.agent)) {
|
||||
return buildNativeProviderEnvironment({}, host);
|
||||
}
|
||||
return host;
|
||||
@@ -1943,9 +1944,14 @@ function runnerdStateBase(): string {
|
||||
}
|
||||
|
||||
function scopedRunnerdStateRoot(execution: NativeExecutionInput): string {
|
||||
// Antigravity's first release owns a fresh per-turn daemon. Its native
|
||||
// conversation is stored separately and may load under each new run's grant.
|
||||
const scope = execution.provider.kind === "acpx" && execution.provider.agent === "antigravity"
|
||||
? JSON.stringify([nativeSessionScopeKey(execution), execution.binding.runId])
|
||||
: nativeSessionScopeKey(execution);
|
||||
return resolve(
|
||||
runnerdStateBase(),
|
||||
createHash("sha256").update(nativeSessionScopeKey(execution)).digest("hex"),
|
||||
createHash("sha256").update(scope).digest("hex"),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5633,6 +5639,7 @@ function runnerdStateRoot(execution: NativeExecutionInput): string {
|
||||
}
|
||||
return scoped;
|
||||
}
|
||||
if (execution.provider.kind === "acpx" && execution.provider.agent === "antigravity") return scoped;
|
||||
for (const legacy of [
|
||||
legacyCompanyRunnerdStateRoot(execution),
|
||||
legacyRunnerdStateRoot(execution),
|
||||
@@ -8057,6 +8064,17 @@ export async function executePaperclipNativeSession(input: {
|
||||
async function executePaperclipNativeSessionWithinScope(
|
||||
input: Parameters<typeof executePaperclipNativeSession>[0],
|
||||
): Promise<AdapterExecutionResult> {
|
||||
if (input.execution.provider.kind === "acpx" && input.execution.provider.agent === "antigravity") {
|
||||
const candidate = resolveAntigravityCandidateAdmission({
|
||||
companyId: input.execution.binding.companyId, model: input.execution.provider.model,
|
||||
}, process.env);
|
||||
if (!candidate || !input.useRunnerd || input.backend || input.restartRecovery
|
||||
|| input.runnerExecutionTarget?.kind === "remote"
|
||||
|| input.execution.session.lifecyclePolicy.mode !== "per_turn"
|
||||
|| ("homeMode" in input.execution && input.execution.homeMode === "preconfigured")) {
|
||||
throw new Error("paperclip_runner_antigravity_candidate_ineligible: exact local per-turn candidate admission is required");
|
||||
}
|
||||
}
|
||||
const restoredController = input.restartRecovery?.kind === "reattach_remote_runner"
|
||||
? await restoreNativeRunnerCheckpoint(input.db, input.execution.binding, scopedRunnerdStateRoot(input.execution))
|
||||
: null;
|
||||
@@ -13538,8 +13556,9 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
: input.execution;
|
||||
const preconfiguredHome = "homeMode" in input.execution && input.execution.homeMode === "preconfigured";
|
||||
const isGrok = input.execution.provider.kind === "acpx" && input.execution.provider.agent === "grok";
|
||||
const isAntigravity = input.execution.provider.kind === "acpx" && input.execution.provider.agent === "antigravity";
|
||||
let effectiveRunnerEnvironmentBase: NodeJS.ProcessEnv = {
|
||||
...(isGrok
|
||||
...(isGrok || isAntigravity
|
||||
? runnerEnvironment ?? {}
|
||||
: resolveNativeProviderEnvironment(input.execution.provider, runnerEnvironment)),
|
||||
};
|
||||
@@ -13548,6 +13567,11 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
managedHome: input.managedAiCredentialHome,
|
||||
}) : null;
|
||||
if (grokCredential) effectiveRunnerEnvironmentBase = grokCredential.environment;
|
||||
const antigravityCredential = isAntigravity ? await prepareAntigravityRunnerCredentials({
|
||||
environment: effectiveRunnerEnvironmentBase, remote: Boolean(remoteTarget), managedHome: input.managedAiCredentialHome,
|
||||
lifecycleMode: input.execution.session.lifecyclePolicy.mode,
|
||||
}) : null;
|
||||
if (antigravityCredential) effectiveRunnerEnvironmentBase = antigravityCredential.environment;
|
||||
if (relayAssignedMcp) {
|
||||
// The server-held tool authority owns this credential. Do not deliver a
|
||||
// duplicate HTTP MCP server or its bearer token to the remote provider.
|
||||
@@ -13729,8 +13753,8 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
"paperclip-runner",
|
||||
"acpx",
|
||||
),
|
||||
codexTransportFactory: (recoveryContext) =>
|
||||
createRunnerdCodexTransport({
|
||||
codexTransportFactory: (recoveryContext) => {
|
||||
const bundle = createRunnerdCodexTransport({
|
||||
onSpawn: input.onSpawn,
|
||||
...(input.execution.provider.kind === "codex" ? { disableCodexWebSearch: "webSearch" in input.execution.provider && input.execution.provider.webSearch === "disabled" } : {}),
|
||||
homeMode: preconfiguredHome ? "preconfigured" : "isolated",
|
||||
@@ -13760,6 +13784,9 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
acpxCandidateProfile: input.execution.provider.agent === "pi"
|
||||
? undefined
|
||||
: resolveAcpxQualification(input.execution.provider, process.env),
|
||||
acpxCandidateAdmission: input.execution.provider.agent === "antigravity"
|
||||
? resolveAntigravityCandidateAdmission({ companyId: input.execution.binding.companyId, model: input.execution.provider.model }, process.env)
|
||||
: undefined,
|
||||
acpxPermissionMode: input.execution.provider.permissionMode,
|
||||
acpxMode: input.execution.provider.mode,
|
||||
piThinkingLevel: input.execution.provider.piThinkingLevel,
|
||||
@@ -13897,7 +13924,9 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
recoveryContext?.persistedSession?.activeTurnId ?? null,
|
||||
resumeProviderSession: recoveryContext?.persistedSession,
|
||||
providerRecoveryPolicy:
|
||||
recoveryContext?.providerRecoveryPolicy ??
|
||||
input.execution.provider.kind === "acpx" && input.execution.provider.agent === "antigravity"
|
||||
? "same_session_only"
|
||||
: recoveryContext?.providerRecoveryPolicy ??
|
||||
(input.execution.provider.kind === "acpx" &&
|
||||
input.execution.interactionResponses.length > 0
|
||||
? "allow_replacement_after_governed_wait"
|
||||
@@ -14005,10 +14034,20 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
}
|
||||
},
|
||||
}),
|
||||
}).transport,
|
||||
});
|
||||
return antigravityCredential?.home ? bindAntigravityTransportRetirement(bundle) : bundle.transport;
|
||||
},
|
||||
});
|
||||
const boundManagedSessions = new WeakSet<NativeSession>();
|
||||
const wrapManagedSession = (session: NativeSession): NativeSession => {
|
||||
if (antigravityCredential?.home && antigravityCredential.credential && !boundManagedSessions.has(session)) {
|
||||
boundManagedSessions.add(session);
|
||||
const runtimeHome = resolve(resolvePaperclipInstanceRoot(), "runtime", "paperclip-runner", "acpx", "acpx",
|
||||
acpxRuntimeSessionDirectoryName(nativeSessionKey(input.execution)), "antigravity-home");
|
||||
return bindAntigravityCredentialTurn(session, {
|
||||
managedHome: antigravityCredential.home, credential: antigravityCredential.credential, runtimeHome,
|
||||
});
|
||||
}
|
||||
if (isGrok && grokCredential?.home && !boundManagedSessions.has(session)) {
|
||||
boundManagedSessions.add(session);
|
||||
// The launch runtime directory already ends in "acpx"; ACPX adds its
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { chmod, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import { chmod, mkdir, mkdtemp, readFile, rename, rm, stat as fsStat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { createConnection, createServer } from "node:net";
|
||||
@@ -40,6 +40,31 @@ describe("plugin Runner setup", () => {
|
||||
execFileSync("cargo", ["build", "--release", "--locked", "--manifest-path", "packages/paperclip-runner/runner/Cargo.toml",
|
||||
"-p", "paperclip-runner-core", "--bin", "paperclip-runnerd", "--bin", "fake-codex-app-server"], { stdio: "pipe" });
|
||||
}, 600_000);
|
||||
it("preserves the typed cleanup owner and removes its local root only after late proof", async () => {
|
||||
let root: string | undefined, options: Parameters<typeof runnerRuntime.probeNativeRunnerEnvironment>[0] | undefined;
|
||||
let physical = false;
|
||||
const retired = new Promise<void>(() => {});
|
||||
const retry = vi.fn(async () => {
|
||||
if (!physical) throw new Error("fixture owner is still live");
|
||||
await options!.onCleanupConfirmed!();
|
||||
});
|
||||
const failure = new runnerRuntime.NativeEnvironmentProbeCleanupError(retired, new Error("private probe failure"), [], retry);
|
||||
const probe = vi.spyOn(runnerRuntime, "probeNativeRunnerEnvironment").mockImplementation(async input => {
|
||||
root = input.runtimeDirectory; options = input; throw failure;
|
||||
});
|
||||
try {
|
||||
await expect(probePluginRunnerEnvironment({ companyId: "fixture-company", adapterType: "paperclip_runner", config: { provider: "codex", model: "fixture-model" },
|
||||
executionTarget: { kind: "remote", transport: "sandbox", remoteCwd: ".", leaseId: "probe-lease",
|
||||
runnerTaskProbe: { runId: "probe-run", sessionId: "probe-session" },
|
||||
runnerTask: async () => ({ kind: "description", launchPreparationVersion: 1, projectAuthCheckVersion: 1, taskId: "probe-task", runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` } }),
|
||||
} } as Parameters<typeof probePluginRunnerEnvironment>[0])).rejects.toBe(failure);
|
||||
expect((await fsStat(root!)).isDirectory()).toBe(true);
|
||||
await expect(failure.retryCleanup!()).rejects.toThrow("still live");
|
||||
expect((await fsStat(root!)).isDirectory()).toBe(true);
|
||||
physical = true; await failure.retryCleanup!();
|
||||
await expect(fsStat(root!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} finally { probe.mockRestore(); if (root) await rm(root, { recursive: true, force: true }); }
|
||||
});
|
||||
it.each([
|
||||
{ config: { provider: "acpx", acpxAgent: "pi", model: "fixture-model", piThinkingLevel: "high" }, options: { transportOptions: { acpxAgent: "pi", piThinkingLevel: "high" } } },
|
||||
{ config: { provider: "acpx", acpxAgent: "claude", model: "claude-opus-5-5", effort: "high" }, options: { transportOptions: { acpxAgent: "claude", claudeEffort: "high" } } },
|
||||
|
||||
@@ -6,7 +6,7 @@ import { join } from "node:path";
|
||||
import type { AdapterEnvironmentTestContext, AdapterEnvironmentTestResult } from "@paperclipai/adapter-utils";
|
||||
import { resolvePaperclipRunnerPiThinkingLevel } from "@paperclipai/adapter-utils";
|
||||
import { environmentTaskResultSchema } from "@paperclipai/plugin-sdk";
|
||||
import { probeNativeRunnerEnvironment, resolveClaudeEffort, resolveGrokEffort } from "../../vendor/paperclip-runner/index.js";
|
||||
import { NativeEnvironmentProbeCleanupError, probeNativeRunnerEnvironment, resolveClaudeEffort, resolveGrokEffort } from "../../vendor/paperclip-runner/index.js";
|
||||
import { preparePluginRunnerCredentials } from "./plugin-runner-credentials.js";
|
||||
import { createPluginRunnerTaskOwner } from "./plugin-runner-task.js";
|
||||
import { resolvePaperclipRunnerProviderProfile } from "./provider-profile.js";
|
||||
@@ -64,11 +64,12 @@ export async function probePluginRunnerEnvironment(context: AdapterEnvironmentTe
|
||||
prpIdentity: { runnerInstanceId: runnerId, environmentLeaseId: target.leaseId, runId: binding.runId,
|
||||
normalizedSessionId: binding.sessionId, turnId: `turn-${binding.runId}`, itemId: `item-${binding.runId}` },
|
||||
},
|
||||
onCleanupConfirmed: async () => { cleanupConfirmed = true; },
|
||||
onCleanupConfirmed: async () => { rmSync(root, { recursive: true, force: true }); cleanupConfirmed = true; },
|
||||
});
|
||||
return { adapterType: "paperclip_runner", status: "pass", testedAt,
|
||||
checks: [{ code: "runner_hello_probe_passed", level: "info", message: `Runner verified ${result.providerDriver} with model ${result.effectiveModel}.` }] };
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (error instanceof NativeEnvironmentProbeCleanupError) throw error;
|
||||
// Provider failures may contain credentials or private addressing.
|
||||
return { adapterType: "paperclip_runner", status: "fail", testedAt,
|
||||
checks: [{ code: "runner_hello_probe_failed", level: "error", message: "The selected plugin environment did not complete the Runner hello probe and confirmed cleanup. Check its runtime, account, and model access." }] };
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
AGENTCORE_QUALIFIED_MODEL,
|
||||
CLAUDE_MANAGED_QUALIFIED_MODEL,
|
||||
} from "../provider-profile-qualification.js";
|
||||
import { resolveAcpxQualification, type AcpxQualificationCandidate } from "./acpx-qualification.js";
|
||||
import { resolveAcpxQualification, resolveAntigravityCandidateAdmission, type AcpxQualificationCandidate } from "./acpx-qualification.js";
|
||||
import { compatibleCodexModel } from "./codex-model-fallback.js";
|
||||
|
||||
export const QUALIFIED_OPENCODE_RUNNER_VERSION = "1.18.34" as const;
|
||||
@@ -38,7 +38,7 @@ export const DEFAULT_ACPX_RUNNER_MODELS = {
|
||||
|
||||
export type QualifiedPaperclipRunnerAcpxAgent =
|
||||
keyof typeof DEFAULT_ACPX_RUNNER_MODELS;
|
||||
type AdmittedPaperclipRunnerAcpxAgent = QualifiedPaperclipRunnerAcpxAgent | AcpxQualificationCandidate;
|
||||
type AdmittedPaperclipRunnerAcpxAgent = QualifiedPaperclipRunnerAcpxAgent | AcpxQualificationCandidate | "antigravity";
|
||||
|
||||
export type PaperclipRunnerProviderProfile =
|
||||
| { provider: "muse"; backend: "muse_external"; model: null; museBindingId: string }
|
||||
@@ -411,6 +411,7 @@ export function claudeRunnerUnsupportedSettings(config: Record<string, unknown>)
|
||||
*/
|
||||
export function resolvePaperclipRunnerProviderProfile(
|
||||
adapterConfig: unknown,
|
||||
context: { companyId?: string } = {},
|
||||
): PaperclipRunnerProviderProfile {
|
||||
const config = asRecord(adapterConfig);
|
||||
const candidate = config.provider ?? "codex";
|
||||
@@ -554,6 +555,15 @@ export function resolvePaperclipRunnerProviderProfile(
|
||||
const pendingAcpxProfile = PAPERCLIP_RUNNER_ACPX_PROFILES.find(profile => profile.value === acpxAgent && !profile.qualified);
|
||||
if (pendingAcpxProfile) {
|
||||
if (!model) throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_model_required", `${pendingAcpxProfile.label} requires an explicit model ID; there is no default model.`);
|
||||
if (pendingAcpxProfile.value === "antigravity") {
|
||||
try {
|
||||
if (resolveAntigravityCandidateAdmission({ companyId: context.companyId, model }, process.env)) {
|
||||
return { provider: "acpx", backend: "acpx_runtime", model, acpxAgent: "antigravity" };
|
||||
}
|
||||
} catch {
|
||||
throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_qualification_invalid", "Antigravity candidate admission requires the authorized company, exact model and runtime identity.");
|
||||
}
|
||||
}
|
||||
// Qualification authority belongs to the isolated server operator. Never
|
||||
// read this allowlist from adapter config, credential refs, or run env.
|
||||
let qualification: AcpxQualificationCandidate | undefined;
|
||||
@@ -565,7 +575,7 @@ export function resolvePaperclipRunnerProviderProfile(
|
||||
if (qualification) {
|
||||
return { provider: "acpx", backend: "acpx_runtime", model, acpxAgent: qualification };
|
||||
}
|
||||
throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_agent_unavailable", `${pendingAcpxProfile.label} is awaiting local and Daytona qualification. Its profile is not enabled for production runs.`);
|
||||
throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_agent_unavailable", `${pendingAcpxProfile.label} is awaiting native Runner acceptance. Its profile is not enabled for production runs.`);
|
||||
}
|
||||
if ((acpxAgent === "cursor" || acpxAgent === "pi") && !model) {
|
||||
throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_model_required", "This ACPX agent requires an explicit model ID; there is no default model.");
|
||||
@@ -602,6 +612,7 @@ export function resolvePaperclipRunnerProviderProfile(
|
||||
* profile's immutable remote resource identity.
|
||||
*/
|
||||
export function resolvePaperclipRunnerNativeProviderInput(input: {
|
||||
companyId?: string;
|
||||
backend: PaperclipRunnerProviderProfile["backend"];
|
||||
adapterConfig: unknown;
|
||||
/** Verified image CLI version for a fresh remote Codex run only. */
|
||||
@@ -625,7 +636,7 @@ export function resolvePaperclipRunnerNativeProviderInput(input: {
|
||||
} | null;
|
||||
}): PaperclipRunnerNativeProviderInput {
|
||||
const config = asRecord(input.adapterConfig);
|
||||
const profile = resolvePaperclipRunnerProviderProfile(config);
|
||||
const profile = resolvePaperclipRunnerProviderProfile(config, { companyId: input.companyId });
|
||||
if (config.homeMode !== undefined && config.homeMode !== "isolated" && config.homeMode !== "preconfigured") {
|
||||
throw new PaperclipRunnerProviderProfileError("paperclip_runner_home_mode_invalid", "homeMode must be isolated or preconfigured");
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ export function resolveNativeRuntimeMode(input: {
|
||||
grokEnabled?: boolean;
|
||||
runtimeConfig: unknown;
|
||||
adapterConfig?: unknown;
|
||||
agent: { id?: string; status: string; adapterType: string | null };
|
||||
agent: { id?: string; companyId?: string; status: string; adapterType: string | null };
|
||||
issue: { id: string; workMode: string; executionWorkspaceId?: string | null } | null;
|
||||
target: { kind?: string } | null | undefined;
|
||||
workspaceId: string | null;
|
||||
@@ -123,7 +123,7 @@ export function resolveNativeRuntimeMode(input: {
|
||||
}
|
||||
let runnerProfile: PaperclipRunnerProviderProfile;
|
||||
try {
|
||||
runnerProfile = resolvePaperclipRunnerProviderProfile(input.adapterConfig);
|
||||
runnerProfile = resolvePaperclipRunnerProviderProfile(input.adapterConfig, { companyId: input.agent.companyId });
|
||||
} catch (error) {
|
||||
if (error instanceof PaperclipRunnerProviderProfileError) {
|
||||
throw ineligible(error.code, error.message);
|
||||
@@ -140,7 +140,7 @@ export function resolveNativeRuntimeMode(input: {
|
||||
throw ineligible("paperclip_runner_grok_disabled", "Enable Grok Bot, Paperclip Runner, and Assistant connections (MCP) before assigning new work.");
|
||||
} else if (runnerProfile.provider !== "codex" && runnerProfile.provider !== "opencode"
|
||||
&& !(runnerProfile.provider === "acpx"
|
||||
&& (["claude", "copilot", "pi"].includes(runnerProfile.acpxAgent ?? "")))
|
||||
&& (["claude", "copilot", "pi", "antigravity"].includes(runnerProfile.acpxAgent ?? "")))
|
||||
&& !input.enabled) {
|
||||
throw ineligible(
|
||||
"paperclip_runner_rollout_disabled",
|
||||
@@ -292,7 +292,7 @@ export function resolveHeartbeatNativeRuntimeMode(input: {
|
||||
grokEnabled?: boolean;
|
||||
runtimeConfig: unknown;
|
||||
adapterConfig?: unknown;
|
||||
agent: { id?: string; status: string; adapterType: string | null };
|
||||
agent: { id?: string; companyId?: string; status: string; adapterType: string | null };
|
||||
issue: { id: string; workMode: string; executionWorkspaceId?: string | null } | null;
|
||||
target: { kind?: string } | null | undefined;
|
||||
workspaceId: string | null;
|
||||
|
||||
@@ -6,7 +6,7 @@ import { CODEX_CHATGPT_MODEL_REJECTION_RE, codexChatGptRetirementHint } from "@p
|
||||
import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server";
|
||||
import type { AdapterEnvironmentTestContext, AdapterEnvironmentTestResult } from "@paperclipai/adapter-utils";
|
||||
import { ADAPTER_AUTH_MISSING_CHECK_CODE } from "@paperclipai/shared";
|
||||
import { probeNativeRunnerEnvironment, resolveSourceCodexHome } from "../../vendor/paperclip-runner/index.js";
|
||||
import { NativeEnvironmentProbeCleanupError, probeNativeRunnerEnvironment, resolveSourceCodexHome } from "../../vendor/paperclip-runner/index.js";
|
||||
import { resolvePaperclipRunnerBinary, resolveRemotePaperclipRunnerBinary } from "./native-codex-runner.js";
|
||||
import { readLocalAiCredentialFile } from "../local-ai-credential-file.js";
|
||||
import { createNativeSshCommandRunner } from "./native-ssh-command-runner.js";
|
||||
@@ -254,6 +254,7 @@ export async function testNativeRunnerAuthentication(context: AdapterEnvironment
|
||||
return { adapterType: "paperclip_runner", status: "pass", testedAt: new Date().toISOString(), checks: [{ code: `${provider}_hello_probe_passed`, level: "info",
|
||||
message: `The native ${provider} runtime verified the selected account and model in ${remote ? "the selected environment" : "the Paperclip host"}.` }] };
|
||||
} catch (error) {
|
||||
if (error instanceof NativeEnvironmentProbeCleanupError) throw error;
|
||||
const message = redactNativeProbeMessage(error instanceof Error ? error.message : "The selected native runtime could not verify this account.", { ...environment, ...(sourceAuthJson ? { [authKey]: sourceAuthJson } : {}) });
|
||||
const authentication = /(?:invalid (?:api[- ]?key|auth(?:entication)? token)|authentication (?:failed|required)|unauthenticated|unauthorized|not authenticated|please (?:log|sign) in|not logged in|\b(?:401|403)\b)/i.test(message);
|
||||
const rejectedModel = provider === "codex" ? CODEX_CHATGPT_MODEL_REJECTION_RE.exec(message)?.[1] : undefined;
|
||||
|
||||
@@ -9,8 +9,21 @@ import { idleQuotaRecoveryPath } from "./idle-local-work.js";
|
||||
const recoverySchema = z.object({
|
||||
companyId: z.string().uuid(), grantId: z.string().uuid(), connectionId: z.string().uuid(), secretId: z.string().uuid(),
|
||||
baseHash: z.string().length(64), value: z.string().min(1),
|
||||
provider: z.enum(["openai", "google"]).optional(),
|
||||
google: z.object({
|
||||
sessionEpoch: z.number().int().nonnegative(), baseVersion: z.number().int().positive(),
|
||||
versionSelector: z.union([z.literal("latest"), z.number().int().positive()]),
|
||||
accountEmail: z.string().email(), verified: z.boolean(),
|
||||
}).strict().optional(),
|
||||
});
|
||||
type Recovery = z.infer<typeof recoverySchema>;
|
||||
/** The native owner retired and an fsynced encrypted journal owns its refresh. */
|
||||
export class RetiredCredentialRecoveryError extends Error {
|
||||
constructor(cause: unknown) {
|
||||
super("The selected account credential is awaiting durable recovery. Retry shortly.", { cause });
|
||||
this.name = "RetiredCredentialRecoveryError";
|
||||
}
|
||||
}
|
||||
export const quotaCredentialHash = (value: string) => createHash("sha256").update(value).digest("hex");
|
||||
export const quotaCredentialRecoveryPath = (companyId: string, grantId: string) =>
|
||||
path.join(idleQuotaRecoveryPath(), companyId, `${grantId}.json`);
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
import { unprocessable } from "../errors.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { registerIdleLocalWorkProbe } from "./idle-local-work.js";
|
||||
import { RetiredCredentialRecoveryError } from "./quota-credential-recovery.js";
|
||||
|
||||
export type RetainedAiCleanupScope = { companyId: string; accountKey: string };
|
||||
type Cleanup = {
|
||||
scope: RetainedAiCleanupScope;
|
||||
cleanup: () => Promise<void>;
|
||||
retryRetirement?: () => Promise<void>;
|
||||
retired: "pending" | "confirmed" | "failed";
|
||||
running?: Promise<void>;
|
||||
executing?: boolean;
|
||||
warned?: boolean;
|
||||
};
|
||||
const retained = new Map<string, Set<Cleanup>>();
|
||||
const reconciling = new Map<string, Promise<void>>();
|
||||
const homes = new Map<string, RetainedAiCleanupScope>();
|
||||
const active = new AsyncLocalStorage<ReadonlySet<Cleanup>>();
|
||||
const key = (scope: RetainedAiCleanupScope) => JSON.stringify([scope.companyId, scope.accountKey]);
|
||||
registerIdleLocalWorkProbe(() => retained.size ? "present" : "none");
|
||||
|
||||
function pending() {
|
||||
return unprocessable("The selected AI account is still completing credential cleanup. Retry shortly.", { code: "ai_connection_busy" });
|
||||
}
|
||||
function remove(entry: Cleanup) {
|
||||
const entries = retained.get(key(entry.scope));
|
||||
entries?.delete(entry);
|
||||
if (!entries?.size) retained.delete(key(entry.scope));
|
||||
}
|
||||
function warn(entry: Cleanup) {
|
||||
if (entry.warned) return;
|
||||
entry.warned = true;
|
||||
logger.warn({ companyId: entry.scope.companyId, code: "AI_CREDENTIAL_CLEANUP_PENDING" }, "Selected AI credential cleanup remains pending");
|
||||
}
|
||||
function cleaningScope(scope: RetainedAiCleanupScope) {
|
||||
return [...(active.getStore() ?? [])].some(entry => entry.executing && key(entry.scope) === key(scope));
|
||||
}
|
||||
|
||||
/** Check without joining work that may need the mutation lock already held by
|
||||
* the caller. A cleanup's own nested journal recovery shares its ownership. */
|
||||
export function assertAiCredentialCleanupSettled(scope: RetainedAiCleanupScope): void {
|
||||
if (!cleaningScope(scope) && retained.get(key(scope))?.size) throw pending();
|
||||
}
|
||||
function attempt(entry: Cleanup): Promise<void> {
|
||||
if (!retained.get(key(entry.scope))?.has(entry)) return Promise.resolve();
|
||||
if (entry.retired === "pending" || (entry.retired === "failed" && !entry.retryRetirement)) return Promise.reject(pending());
|
||||
return entry.running ??= active.run(new Set([...(active.getStore() ?? []), entry]), async () => {
|
||||
entry.executing = true;
|
||||
try {
|
||||
if (entry.retired === "failed") {
|
||||
await entry.retryRetirement!();
|
||||
entry.retired = "confirmed";
|
||||
}
|
||||
await entry.cleanup(); remove(entry);
|
||||
}
|
||||
catch (error) {
|
||||
// The encrypted journal now owns recovery; the next account preparation
|
||||
// reads it before it can launch another provider.
|
||||
if (entry.retired === "confirmed" && error instanceof RetiredCredentialRecoveryError) { remove(entry); return; }
|
||||
warn(entry);
|
||||
throw pending();
|
||||
} finally { entry.executing = false; }
|
||||
}).finally(() => { entry.running = undefined; });
|
||||
}
|
||||
|
||||
/** A retirement event gets one cleanup attempt. Already-retired failures retry
|
||||
* only on the next same-account action, never on an idle timer or SQL scan. */
|
||||
export function retainAiCredentialCleanup(input: {
|
||||
// Accept legacy Google home metadata for compatibility. Only the explicit
|
||||
// bindRetainedAiCredentialHome mapping grants home-to-account authority.
|
||||
scope: RetainedAiCleanupScope; cleanup: () => Promise<void>; retired?: Promise<void>; retryRetirement?: () => Promise<void>; home?: string;
|
||||
}): void {
|
||||
const scopeKey = key(input.scope);
|
||||
const entries = retained.get(scopeKey) ?? new Set<Cleanup>();
|
||||
if ([...entries].some(entry => entry.cleanup === input.cleanup)) return;
|
||||
const entry: Cleanup = { scope: { ...input.scope }, cleanup: input.cleanup, retryRetirement: input.retryRetirement,
|
||||
retired: input.retired ? "pending" : "confirmed" };
|
||||
entries.add(entry); retained.set(scopeKey, entries);
|
||||
if (input.retired) void input.retired.then(() => {
|
||||
entry.retired = "confirmed";
|
||||
return reconcileRetainedAiCleanup(entry.scope).catch(() => undefined);
|
||||
}, () => { entry.retired = "failed"; warn(entry); });
|
||||
}
|
||||
|
||||
/** Fail closed before another provider starts. Concurrent attempts join the
|
||||
* original cleanup. Nested credential reads skip this account's peer join to
|
||||
* avoid recursing into the current callback. The outer bounded pass and final
|
||||
* fence still settle every peer before any external provider admission. */
|
||||
export async function reconcileRetainedAiCleanup(scope: RetainedAiCleanupScope): Promise<void> {
|
||||
await Promise.resolve();
|
||||
const scopeKey = key(scope);
|
||||
if (cleaningScope(scope)) return;
|
||||
const existing = reconciling.get(scopeKey);
|
||||
if (existing) return existing;
|
||||
const operation = (async () => {
|
||||
for (const entry of [...(retained.get(scopeKey) ?? [])]) await attempt(entry);
|
||||
// A new obligation can arrive while a callback awaits storage. This
|
||||
// request attempts its original bounded set and keeps admission closed.
|
||||
if (retained.get(scopeKey)?.size) throw pending();
|
||||
})();
|
||||
reconciling.set(scopeKey, operation);
|
||||
try { await operation; }
|
||||
finally { if (reconciling.get(scopeKey) === operation) reconciling.delete(scopeKey); }
|
||||
}
|
||||
|
||||
export function bindRetainedAiCredentialHome(home: string, scope: RetainedAiCleanupScope): () => void {
|
||||
const bound = { ...scope };
|
||||
homes.set(home, bound);
|
||||
return () => { if (homes.get(home) === bound) homes.delete(home); };
|
||||
}
|
||||
export async function reconcileRetainedAiCleanupForHome(home: string): Promise<void> {
|
||||
const scope = homes.get(home);
|
||||
if (scope) await reconcileRetainedAiCleanup(scope);
|
||||
}
|
||||
export function retainAiCredentialCleanupForHome(home: string, input: {
|
||||
cleanup: () => Promise<void>; retired?: Promise<void>; retryRetirement?: () => Promise<void>;
|
||||
}): void {
|
||||
const scope = homes.get(home);
|
||||
if (scope) retainAiCredentialCleanup({ ...input, scope, home });
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { expect, it, vi } from "vitest";
|
||||
import {
|
||||
assertGoogleCredentialCleanupSettled, bindRetainedGoogleCredentialHome, reconcileRetainedGoogleCleanup,
|
||||
reconcileRetainedGoogleCleanupForHome, retainGoogleCredentialCleanup,
|
||||
retainGoogleCredentialCleanupForHome,
|
||||
} from "./retained-google-credential-cleanup.js";
|
||||
import { RetiredCredentialRecoveryError } from "./quota-credential-recovery.js";
|
||||
|
||||
let sequence = 0;
|
||||
const scope = () => ({ companyId: "company", accountKey: `retained-${++sequence}` });
|
||||
|
||||
it("retries only on the next same-company account action and coalesces concurrent cleanup", async () => {
|
||||
const owner = scope();
|
||||
let finish!: () => void;
|
||||
const cleanup = vi.fn(() => new Promise<void>(resolve => { finish = resolve; }));
|
||||
retainGoogleCredentialCleanup({ scope: owner, cleanup });
|
||||
await reconcileRetainedGoogleCleanup({ ...owner, companyId: "other-company" });
|
||||
await reconcileRetainedGoogleCleanup({ ...owner, accountKey: "another-account" });
|
||||
expect(cleanup).not.toHaveBeenCalled();
|
||||
const first = reconcileRetainedGoogleCleanup(owner);
|
||||
const second = reconcileRetainedGoogleCleanup(owner);
|
||||
await Promise.resolve();
|
||||
expect(cleanup).toHaveBeenCalledOnce();
|
||||
finish();
|
||||
await Promise.all([first, second]);
|
||||
await reconcileRetainedGoogleCleanup(owner);
|
||||
expect(cleanup).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("preserves failed cleanup for an event-driven retry without launching a provider", async () => {
|
||||
const owner = scope();
|
||||
const cleanup = vi.fn().mockRejectedValueOnce(new Error("private-token journal unavailable")).mockResolvedValue(undefined);
|
||||
const provider = vi.fn();
|
||||
retainGoogleCredentialCleanup({ scope: owner, cleanup });
|
||||
const useAccount = async () => { await reconcileRetainedGoogleCleanup(owner); provider(); };
|
||||
await expect(useAccount()).rejects.toMatchObject({ details: { code: "ai_connection_busy" } });
|
||||
expect(provider).not.toHaveBeenCalled();
|
||||
await useAccount();
|
||||
expect(cleanup).toHaveBeenCalledTimes(2);
|
||||
expect(provider).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("requires confirmed physical retirement before retrying the retained callback", async () => {
|
||||
const owner = scope();
|
||||
let finish!: () => void;
|
||||
const retired = new Promise<void>(resolve => { finish = resolve; });
|
||||
const cleanup = vi.fn(async () => {});
|
||||
retainGoogleCredentialCleanup({ scope: owner, cleanup, retired });
|
||||
await expect(reconcileRetainedGoogleCleanup(owner)).rejects.toMatchObject({ details: { code: "ai_connection_busy" } });
|
||||
expect(cleanup).not.toHaveBeenCalled();
|
||||
finish();
|
||||
await vi.waitFor(() => expect(cleanup).toHaveBeenCalledOnce());
|
||||
await reconcileRetainedGoogleCleanup(owner);
|
||||
expect(cleanup).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("lets a durable encrypted journal take over without replaying the retired callback", async () => {
|
||||
const owner = scope();
|
||||
const cleanup = vi.fn(async () => { throw new RetiredCredentialRecoveryError(new Error("private token")); });
|
||||
retainGoogleCredentialCleanup({ scope: owner, cleanup });
|
||||
await reconcileRetainedGoogleCleanup(owner);
|
||||
await reconcileRetainedGoogleCleanup(owner);
|
||||
expect(cleanup).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("retries a rejected physical proof only on the next account action and coalesces proof ownership", async () => {
|
||||
const owner = scope();
|
||||
const retired = Promise.reject(new Error("fixture initial retirement proof unavailable"));
|
||||
let confirm!: () => void;
|
||||
const retryRetirement = vi.fn().mockRejectedValueOnce(new RetiredCredentialRecoveryError(new Error("fixture owner still present")))
|
||||
.mockImplementationOnce(() => new Promise<void>(resolve => { confirm = resolve; }));
|
||||
const cleanup = vi.fn(async () => {});
|
||||
retainGoogleCredentialCleanup({ scope: owner, cleanup, retired, retryRetirement });
|
||||
await retired.catch(() => {});
|
||||
await expect(reconcileRetainedGoogleCleanup(owner)).rejects.toMatchObject({ details: { code: "ai_connection_busy" } });
|
||||
expect(retryRetirement).toHaveBeenCalledOnce(); expect(cleanup).not.toHaveBeenCalled();
|
||||
const first = reconcileRetainedGoogleCleanup(owner), second = reconcileRetainedGoogleCleanup(owner);
|
||||
await vi.waitFor(() => expect(retryRetirement).toHaveBeenCalledTimes(2));
|
||||
expect(cleanup).not.toHaveBeenCalled();
|
||||
confirm(); await Promise.all([first, second]);
|
||||
expect(cleanup).toHaveBeenCalledOnce();
|
||||
await reconcileRetainedGoogleCleanup(owner);
|
||||
expect(retryRetirement).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not recurse through cleanup wrappers and settles peers once", async () => {
|
||||
const owner = scope();
|
||||
const first = vi.fn(async () => { assertGoogleCredentialCleanupSettled(owner); await reconcileRetainedGoogleCleanup(owner); });
|
||||
const second = vi.fn(async () => { await reconcileRetainedGoogleCleanup(owner); });
|
||||
retainGoogleCredentialCleanup({ scope: owner, cleanup: first });
|
||||
retainGoogleCredentialCleanup({ scope: owner, cleanup: second });
|
||||
expect(() => assertGoogleCredentialCleanupSettled(owner)).toThrow("still completing credential cleanup");
|
||||
await reconcileRetainedGoogleCleanup(owner);
|
||||
expect(first).toHaveBeenCalledOnce();
|
||||
expect(second).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("keeps admission closed when a new obligation arrives during bounded cleanup", async () => {
|
||||
const owner = scope();
|
||||
const second = vi.fn(async () => {});
|
||||
retainGoogleCredentialCleanup({ scope: owner, cleanup: async () => {
|
||||
retainGoogleCredentialCleanup({ scope: owner, cleanup: second });
|
||||
} });
|
||||
await expect(reconcileRetainedGoogleCleanup(owner)).rejects.toMatchObject({ details: { code: "ai_connection_busy" } });
|
||||
expect(second).not.toHaveBeenCalled();
|
||||
await reconcileRetainedGoogleCleanup(owner);
|
||||
expect(second).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("retains the original home's cleanup scope until its owner releases it", async () => {
|
||||
const owner = scope(), home = `/fixture/private-${owner.accountKey}`;
|
||||
const release = bindRetainedGoogleCredentialHome(home, owner);
|
||||
const cleanup = vi.fn(async () => {});
|
||||
retainGoogleCredentialCleanupForHome(home, { cleanup });
|
||||
await reconcileRetainedGoogleCleanupForHome(home);
|
||||
expect(cleanup).toHaveBeenCalledOnce();
|
||||
release();
|
||||
retainGoogleCredentialCleanupForHome(home, { cleanup });
|
||||
await reconcileRetainedGoogleCleanup(owner);
|
||||
expect(cleanup).toHaveBeenCalledOnce();
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
// Compatibility names for Google-specific callers; all managed accounts share
|
||||
// the same company/account-scoped owner and bounded reconciliation registry.
|
||||
export {
|
||||
assertAiCredentialCleanupSettled as assertGoogleCredentialCleanupSettled,
|
||||
bindRetainedAiCredentialHome as bindRetainedGoogleCredentialHome,
|
||||
reconcileRetainedAiCleanup as reconcileRetainedGoogleCleanup,
|
||||
reconcileRetainedAiCleanupForHome as reconcileRetainedGoogleCleanupForHome,
|
||||
retainAiCredentialCleanup as retainGoogleCredentialCleanup,
|
||||
retainAiCredentialCleanupForHome as retainGoogleCredentialCleanupForHome,
|
||||
type RetainedAiCleanupScope as RetainedGoogleCleanupScope,
|
||||
} from "./retained-ai-credential-cleanup.js";
|
||||
+9
@@ -10,6 +10,7 @@
|
||||
type RunnerModule = typeof import("@paperclipai/paperclip-runner");
|
||||
|
||||
export type {
|
||||
AcpxCandidateAdmission,
|
||||
DotHarnessDriver,
|
||||
DotAssignment,
|
||||
PaperclipJsonValue,
|
||||
@@ -99,6 +100,7 @@ export const NativeSessionCleanupQuarantinedError =
|
||||
runner.NativeSessionCleanupQuarantinedError;
|
||||
export const NativeSessionProtocolIntegrityError =
|
||||
runner.NativeSessionProtocolIntegrityError;
|
||||
export const NativeEnvironmentProbeCleanupError = runner.NativeEnvironmentProbeCleanupError;
|
||||
export const SemanticToolOutcomeUnknownError = runner.SemanticToolOutcomeUnknownError;
|
||||
export const PaperclipSemanticDispatcher = runner.PaperclipSemanticDispatcher;
|
||||
export const CAPABILITY_SEMANTIC_TOOL_CATALOG =
|
||||
@@ -112,6 +114,7 @@ export const PAPERCLIP_EXECUTION_PROMPT_REVISION =
|
||||
runner.PAPERCLIP_EXECUTION_PROMPT_REVISION;
|
||||
export const acpxRuntimeSessionDirectoryName =
|
||||
runner.acpxRuntimeSessionDirectoryName;
|
||||
export const resolveAcpxRuntimeRoot = runner.resolveAcpxRuntimeRoot;
|
||||
export const OPENCODE_ISOLATED_HOMES_DIRECTORY =
|
||||
runner.OPENCODE_ISOLATED_HOMES_DIRECTORY;
|
||||
export const opencodeRuntimeSessionDirectoryName =
|
||||
@@ -151,6 +154,7 @@ export const parsePaperclipQuestionSet = runner.parsePaperclipQuestionSet;
|
||||
export const parsePaperclipQuestionResponse =
|
||||
runner.parsePaperclipQuestionResponse;
|
||||
export const resolveQualifiedAcpxProfile = runner.resolveQualifiedAcpxProfile;
|
||||
export const parseAcpxCandidateAdmission = runner.parseAcpxCandidateAdmission;
|
||||
export const resolveClaudeEffort = runner.resolveClaudeEffort;
|
||||
export const resolveGrokEffort = runner.resolveGrokEffort;
|
||||
export const QUALIFIED_ACPX_PROFILES = runner.QUALIFIED_ACPX_PROFILES;
|
||||
@@ -173,6 +177,11 @@ export const completeTerminatedLocalNativeSessionCleanup = runner.completeTermin
|
||||
export const probeAcpxClaudeInstallation = runner.probeAcpxClaudeInstallation;
|
||||
export const probeAcpxGrokInstallation = runner.probeAcpxGrokInstallation;
|
||||
export const probeAcpxPiInstallation = runner.probeAcpxPiInstallation;
|
||||
export const startAntigravityBrowserLogin = runner.startAntigravityBrowserLogin;
|
||||
export const verifyAntigravityCredential = runner.verifyAntigravityCredential;
|
||||
export const sanitizeAntigravityCredential = runner.sanitizeAntigravityCredential;
|
||||
export const discoverAntigravityModels = runner.discoverAntigravityModels;
|
||||
export const AntigravityModelDiscoveryCleanupError = runner.AntigravityModelDiscoveryCleanupError;
|
||||
export const PROVIDER_PACK_COMPATIBILITY = runner.PROVIDER_PACK_COMPATIBILITY;
|
||||
export const bundledRemoteProviderPackManifestPath = runner.bundledRemoteProviderPackManifestPath;
|
||||
export const bundledRemoteRunnerBinary = runner.bundledRemoteRunnerBinary;
|
||||
|
||||
@@ -3,6 +3,19 @@ import { describe, expect, it } from "vitest";
|
||||
import { agentDisplayAdapterType, getAdapterDisplay, getAdapterLabel, getAdapterLabels } from "./adapter-display-registry";
|
||||
|
||||
describe("adapter display registry", () => {
|
||||
it("shows a pending setup choice without changing the saved execution adapter", () => {
|
||||
const agent = { adapterType: "process", adapterConfig: {}, pauseReason: "setup", metadata: {
|
||||
setupAdapterPending: true,
|
||||
setupAdapterChoice: { adapterType: "paperclip_runner", runnerProvider: "antigravity", runner: "auto" },
|
||||
} };
|
||||
expect(getAdapterLabel(agentDisplayAdapterType(agent))).toBe("Google Antigravity");
|
||||
expect(agent.adapterType).toBe("process");
|
||||
expect(agentDisplayAdapterType({ ...agent, pauseReason: "manual" })).toBe("process");
|
||||
});
|
||||
it("keeps a configured Antigravity runner branded as Google Antigravity", () => {
|
||||
const type = agentDisplayAdapterType({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity" } });
|
||||
expect(getAdapterLabel(type)).toBe("Google Antigravity");
|
||||
});
|
||||
it.each([
|
||||
["openai_dot", "OpenAI Dot"],
|
||||
["grok_bot", "Grok Bot"],
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
Cpu,
|
||||
} from "lucide-react";
|
||||
import { OpenCodeLogoIcon } from "@/components/OpenCodeLogoIcon";
|
||||
import { pendingAgentSetupDisplayAdapter } from "@/lib/agent-setup-choice";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Type suffix parsing
|
||||
@@ -61,6 +62,7 @@ export interface AdapterDisplayInfo {
|
||||
}
|
||||
|
||||
const adapterDisplayMap: Record<string, AdapterDisplayInfo> = {
|
||||
antigravity_runtime: { label: "Google Antigravity", description: "Antigravity through Paperclip Runner", icon: Gem, hideFromVisualSelection: true },
|
||||
copilot_runtime: { label: "GitHub Copilot", description: "Copilot through Paperclip Runner", icon: Code, hideFromVisualSelection: true },
|
||||
acpx_local: {
|
||||
label: "ACPX (retired)",
|
||||
@@ -216,13 +218,15 @@ export function getAdapterDisplay(type: string): AdapterDisplayInfo {
|
||||
};
|
||||
}
|
||||
|
||||
export function agentDisplayAdapterType(agent: { adapterType: string; adapterConfig: Record<string, unknown> }): string {
|
||||
export function agentDisplayAdapterType(agent: { adapterType: string; adapterConfig: Record<string, unknown>; pauseReason?: unknown; metadata?: unknown }): string {
|
||||
const pendingSetup = pendingAgentSetupDisplayAdapter(agent);
|
||||
if (pendingSetup) return pendingSetup;
|
||||
if (agent.adapterType !== "paperclip_runner") return agent.adapterType;
|
||||
if (agent.adapterConfig.provider === "openai_dot" || agent.adapterConfig.provider === "grok_bot" || agent.adapterConfig.provider === "muse") {
|
||||
return agent.adapterConfig.provider;
|
||||
}
|
||||
const harness = agentHarnessType(agent.adapterType, agent.adapterConfig);
|
||||
return ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(harness) ? harness : agent.adapterType;
|
||||
return ["codex_local", "claude_local", "opencode_local", "pi_local", "antigravity_runtime"].includes(harness) ? harness : agent.adapterType;
|
||||
}
|
||||
|
||||
export function isKnownAdapterType(type: string): boolean {
|
||||
|
||||
@@ -63,7 +63,9 @@ export interface UIAdapterModule extends TranscriptParserSource {
|
||||
type: string;
|
||||
label: string;
|
||||
ConfigFields: ComponentType<AdapterConfigFieldsProps>;
|
||||
buildAdapterConfig: (values: CreateConfigValues) => Record<string, unknown>;
|
||||
buildAdapterConfig: (values: CreateConfigValues, context?: {
|
||||
candidateHarnesses?: readonly { agent: "antigravity"; model: string }[];
|
||||
}) => Record<string, unknown>;
|
||||
/**
|
||||
* Optional issue-chat transcript presentation hints. Shared rendering code
|
||||
* resolves these through the registry and never branches on adapter
|
||||
|
||||
@@ -34,6 +34,8 @@ export interface AcpTargetDescriptor {
|
||||
}
|
||||
|
||||
export interface AdapterInfo {
|
||||
/** Exact operator-authorized candidates for the requested company and target. */
|
||||
candidateHarnesses?: Array<{ agent: "antigravity"; model: string }>;
|
||||
supportedRunners?: import("@paperclipai/shared").AgentRunner[];
|
||||
defaultRunner?: import("@paperclipai/shared").AgentRunner;
|
||||
type: string;
|
||||
|
||||
@@ -50,6 +50,7 @@ export const CONNECT_SOURCE_NAMES: Record<string, string> = {
|
||||
claude_local: "Claude",
|
||||
codex_local: "OpenAI",
|
||||
grok_local: "Grok",
|
||||
antigravity_runtime: "Google",
|
||||
};
|
||||
|
||||
/** The provider name for a source, falling back to the type when unlisted. */
|
||||
@@ -423,7 +424,7 @@ export function ProviderSubscriptionCard({
|
||||
}: {
|
||||
providerName: string;
|
||||
authorizationUrl?: string;
|
||||
mode: "submitted_code" | "displayed_code";
|
||||
mode: "submitted_code" | "displayed_code" | "browser_redirect";
|
||||
loading?: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
@@ -440,7 +441,8 @@ export function ProviderSubscriptionCard({
|
||||
>
|
||||
Sign in to {providerName}
|
||||
</a>
|
||||
{mode === "submitted_code"
|
||||
{mode === "browser_redirect" ? " then return here"
|
||||
: mode === "submitted_code"
|
||||
? " then come back and enter authorization code"
|
||||
: " by providing the authorization code below"}
|
||||
</>
|
||||
@@ -469,15 +471,15 @@ export function ProviderApiKeyCard({
|
||||
/** Shared instructions for local subscription setup in every authentication host. */
|
||||
export function LocalProviderLoginInstructions({ adapterType, login }: {
|
||||
adapterType: string;
|
||||
login?: { isolated?: boolean; command?: string; authorizationUrl?: string | null; code?: string | null; submitCode?: (code: string) => Promise<void>; preparing: boolean; status?: "ready" | "sign_in_required" | "expired" | null; error: string | null; retry: () => void };
|
||||
login?: { isolated?: boolean; command?: string; authorizationUrl?: string | null; code?: string | null; accountLabel?: string | null; submitCode?: (code: string) => Promise<void>; preparing: boolean; status?: "ready" | "sign_in_required" | "expired" | null; error: string | null; retry: () => void };
|
||||
}) {
|
||||
const [showCommand, setShowCommand] = useState(false);
|
||||
const [browserCode, setBrowserCode] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const provider = adapterType === "claude_local" ? "Claude Code" : adapterType === "grok_local" ? "Grok CLI" : "Codex CLI";
|
||||
const provider = adapterType === "antigravity_runtime" ? "Google Antigravity" : adapterType === "claude_local" ? "Claude Code" : adapterType === "grok_local" ? "Grok CLI" : "Codex CLI";
|
||||
const isolated = login?.isolated ?? (adapterType === "codex_local" || adapterType === "grok_local");
|
||||
const command = login?.command;
|
||||
const browserLogin = adapterType === "claude_local" || adapterType === "codex_local";
|
||||
const browserLogin = adapterType === "claude_local" || adapterType === "codex_local" || adapterType === "antigravity_runtime";
|
||||
async function submitBrowserCode() {
|
||||
if (!browserCode.trim() || !login?.submitCode || submitting) return;
|
||||
setSubmitting(true);
|
||||
@@ -494,14 +496,14 @@ export function LocalProviderLoginInstructions({ adapterType, login }: {
|
||||
const ready = login?.status === "ready";
|
||||
return <div className="min-w-0 max-w-full space-y-3 text-sm text-muted-foreground">
|
||||
{ready ? <>
|
||||
<p role="status" className="flex items-center gap-2 text-foreground"><Check className="size-4 shrink-0 text-(--status-task-icon-done)" />{provider} is signed in. Click Connect to use this account.</p>
|
||||
<p role="status" className="flex items-center gap-2 text-foreground"><Check className="size-4 shrink-0 text-(--status-task-icon-done)" />{login?.accountLabel ?? provider} is signed in. Click Connect to use this account.</p>
|
||||
{!showCommand && <button type="button" className="underline underline-offset-4" onClick={() => browserLogin ? login?.retry() : setShowCommand(true)}>Use a different account</button>}
|
||||
</> : !browserLogin && <p>{isolated ? `Sign in to ${provider} for this connection on the machine running Paperclip. Your existing terminal login stays separate.` : `Connect uses your local ${provider} account on the machine running Paperclip.`}</p>}
|
||||
{browserLogin && !ready && !login?.authorizationUrl && !login?.error && <p role="status">Preparing browser sign-in…</p>}
|
||||
{browserLogin && !ready && !login?.error && login?.authorizationUrl && <ProviderSubscriptionCard
|
||||
providerName={connectSourceName(adapterType)}
|
||||
authorizationUrl={login.authorizationUrl}
|
||||
mode={adapterType === "claude_local" ? "submitted_code" : "displayed_code"}
|
||||
mode={adapterType === "antigravity_runtime" ? "browser_redirect" : adapterType === "claude_local" ? "submitted_code" : "displayed_code"}
|
||||
>
|
||||
{adapterType === "claude_local" ? <div className="flex flex-col gap-2">
|
||||
<OnboardingCardField
|
||||
@@ -511,7 +513,7 @@ export function LocalProviderLoginInstructions({ adapterType, login }: {
|
||||
disabled={submitting}
|
||||
/>
|
||||
<Button type="button" disabled={!browserCode.trim() || submitting} onClick={() => void submitBrowserCode()}>Submit code</Button>
|
||||
</div> : <OnboardingLoginCodeRow code={login.code ?? ""} />}
|
||||
</div> : adapterType === "antigravity_runtime" ? <p>Finish signing in in the Google browser window, then return here.</p> : <OnboardingLoginCodeRow code={login.code ?? ""} />}
|
||||
</ProviderSubscriptionCard>}
|
||||
{!browserLogin && (!ready || showCommand) && !login?.error && <>
|
||||
<p>Run this in a terminal on that machine and finish signing in in your browser. We’ll check automatically when you return.</p>
|
||||
|
||||
@@ -6,6 +6,7 @@ const brandMarks: Record<string, { src: string; dark?: string }> = {
|
||||
claude_local: { src: "/brands/claude-color.svg" },
|
||||
codex_local: { src: "/brands/codex-color.svg" },
|
||||
gemini_local: { src: "/brands/adapters/gemini-color.svg" },
|
||||
antigravity_runtime: { src: "/brands/apps/google.svg" },
|
||||
kimi_local: {
|
||||
src: "/brands/adapters/kimi-color-light.svg",
|
||||
dark: "/brands/adapters/kimi-color.svg",
|
||||
|
||||
@@ -148,6 +148,17 @@ describe("AgentActionButtons", () => {
|
||||
expect(mockNavigate).toHaveBeenCalledWith(expect.stringContaining(`runner=${adapterType === "paperclip_runner" ? "paperclip" : "legacy"}`));
|
||||
expect(mockAgentsApi.resume).not.toHaveBeenCalled();
|
||||
});
|
||||
it("reopens the saved pending Antigravity choice while its execution adapter remains held", async () => {
|
||||
render(makeAgent({ adapterType: "process", adapterConfig: {}, status: "paused", lifecycleState: "paused", pauseReason: "setup",
|
||||
metadata: { setupAdapterPending: true, setupAdapterChoice: { adapterType: "paperclip_runner", runnerProvider: "antigravity", runner: "auto" } } }));
|
||||
await flushReact();
|
||||
const finish = [...container.querySelectorAll("button")].find(button => button.textContent === "Finish setup");
|
||||
await act(() => finish!.click());
|
||||
const params = new URL(mockNavigate.mock.calls[0][0], "http://local").searchParams;
|
||||
expect(Object.fromEntries(params)).toMatchObject({ adapterType: "paperclip_runner", runnerProvider: "antigravity", runner: "auto", setupAgentId: "agent-1" });
|
||||
expect(mockAgentsApi.resume).not.toHaveBeenCalled();
|
||||
expect(mockAgentsApi.invoke).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["paused", "preparing", "verifying", "pausing", undefined] as const)("replaces run controls with one setup action when lifecycle is %s", async lifecycleState => {
|
||||
render(makeAgent({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "claude" }, status: "paused", lifecycleState, pauseReason: "setup" }));
|
||||
|
||||
@@ -34,6 +34,7 @@ import { agentsApi } from "../api/agents";
|
||||
import { ApiError } from "../api/client";
|
||||
import { queryKeys } from "../lib/queryKeys";
|
||||
import { agentRouteRef } from "../lib/utils";
|
||||
import { pendingAgentSetupChoice } from "../lib/agent-setup-choice";
|
||||
import { copyTextToClipboard } from "../lib/clipboard";
|
||||
import { useDialogActions } from "../context/DialogContext";
|
||||
import { useToastActions } from "../context/ToastContext";
|
||||
@@ -391,6 +392,7 @@ export function AgentActionButtons({
|
||||
name: agent.name, adapterType: agent.adapterType, setupAgentId: agent.id,
|
||||
runnerProvider: String(agent.adapterConfig.provider === "acpx" ? agent.adapterConfig.acpxAgent : agent.adapterConfig.provider ?? "codex"),
|
||||
...(agent.adapterType === "paperclip_runner" ? { runner: "paperclip" } : ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(agent.adapterType) ? { runner: "legacy" } : {}),
|
||||
...pendingAgentSetupChoice(agent),
|
||||
})}`);
|
||||
}}>Finish setup</Button>
|
||||
) : showRun && <RunButton
|
||||
|
||||
@@ -1311,6 +1311,36 @@ describe("AgentConfigForm environment selector", () => {
|
||||
expect(result.container.querySelector('[aria-label="Environment override"]')).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["api_key", "subscription"] as const)("loads saved Antigravity %s models through its selected connection without a Claude fallback", async method => {
|
||||
const binding = { provider: "google", method, mode: "responsible_user" } as const;
|
||||
const accounts = vi.spyOn(aiConnectionsApi, "list").mockResolvedValue({ currentUserId: "you", canManageConnections: true, connections: [{
|
||||
id: "google-account", grantId: "google-grant", companyId: "company-1", provider: "google", method, name: "Verified Google",
|
||||
ownership: "personal", ownerUserId: "you", isDefault: true, status: "connected",
|
||||
}] });
|
||||
mockAgentsApi.adapterModels.mockResolvedValue([{ id: "google-exact-model", label: "My Google model" }]);
|
||||
try {
|
||||
const result = await renderForm([makeEnvironment({ id: "local-1", name: "Local", driver: "local" })], {
|
||||
adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "google-exact-model" }, runtimeConfig: { aiConnection: binding },
|
||||
});
|
||||
roots.push(result.root);
|
||||
await vi.waitFor(() => expect(mockAgentsApi.adapterModels).toHaveBeenCalledWith("company-1", "paperclip_runner", expect.objectContaining({
|
||||
provider: "acpx", acpxAgent: "antigravity", aiConnection: binding, agentId: "agent-1",
|
||||
})));
|
||||
expect(result.container.textContent).toContain("My Google model");
|
||||
expect(mockAgentsApi.adapterModels.mock.calls.every(call => call[1] === "paperclip_runner" && call[2]?.acpxAgent === "antigravity")).toBe(true);
|
||||
await clickByText(result.container, "My Google model");
|
||||
const search = document.body.querySelector<HTMLInputElement>('[placeholder="Search models... (type to create)"]');
|
||||
expect(search).not.toBeNull();
|
||||
await act(() => setInputValue(search!, "manual-exact-google-model"));
|
||||
await flushReact();
|
||||
await clickElement(Array.from(document.body.querySelectorAll('[role="option"]')).find(option => option.textContent?.includes("Use manual model")));
|
||||
await clickByText(result.container, "Save");
|
||||
expect(result.onSave).toHaveBeenCalledWith(expect.objectContaining({ adapterConfig: expect.objectContaining({
|
||||
provider: "acpx", acpxAgent: "antigravity", model: "manual-exact-google-model",
|
||||
}) }));
|
||||
} finally { accounts.mockRestore(); }
|
||||
});
|
||||
|
||||
it("refreshes Copilot models after reconnecting the same responsible-user account", async () => {
|
||||
const binding = { mode: "responsible_user", provider: "github", method: "api_key" } as const;
|
||||
const account = { id: "copilot-account", grantId: "copilot-grant", companyId: "company-1", provider: "github", method: "api_key", name: "My Copilot", ownership: "personal", ownerUserId: "you", isDefault: true, status: "needs_attention" } as const;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { COPILOT_MODEL_DISCOVERY_QUERY_OPTIONS } from "@/lib/copilot-task-model-catalog";
|
||||
import { ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS, isAccountBoundAcpxAgent } from "@/lib/native-model-catalog";
|
||||
import { useConnectionModels } from "./ai-connections/useConnectionModels";
|
||||
import { agentHarnessType, agentRunner, paperclipRunnerProfileForHarness, normalizeClaudeRunnerOptions, type AgentRunnerChoice } from "@paperclipai/shared";
|
||||
import { adaptersApi } from "../api/adapters";
|
||||
@@ -1016,10 +1016,11 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
|
||||
const runnerAcpxAgent = adapterType === "paperclip_runner" && runnerProvider === "acpx"
|
||||
? String(isCreate ? props.values.adapterSchemaValues?.acpxAgent ?? "claude" : eff("adapterConfig", "acpxAgent", config.acpxAgent ?? "claude")) : undefined;
|
||||
const modelAiBinding = aiConnectionBindingSchema.safeParse((overlay.runtime.runtimeConfig as Record<string, unknown> | undefined)?.aiConnection ?? runtimeConfig.aiConnection).data;
|
||||
const modelCacheIdentity = runnerAcpxAgent === "copilot" ? `${modelProvider}:${runnerAcpxAgent}:${isCreate ? "new" : props.agent.id}:${JSON.stringify(modelAiBinding ?? null)}` : modelProvider;
|
||||
const accountBoundCatalog = isAccountBoundAcpxAgent(runnerAcpxAgent);
|
||||
const modelCacheIdentity = accountBoundCatalog ? `${modelProvider}:${runnerAcpxAgent}:${isCreate ? "new" : props.agent.id}:${JSON.stringify(modelAiBinding ?? null)}` : modelProvider;
|
||||
const connectionModels = useConnectionModels(isExternalRunner ? null : selectedCompanyId, isCreate ? undefined : modelAiBinding, aiRoutingHarness(adapterType, runnerProvider, runnerAcpxAgent));
|
||||
// Fetch adapter models for the effective provider, including unsaved changes.
|
||||
const modelAdapterType = isRunnerHarness ? harnessType : adapterType;
|
||||
const modelAdapterType = accountBoundCatalog ? "paperclip_runner" : isRunnerHarness ? harnessType : adapterType;
|
||||
const modelQueryKey = selectedCompanyId
|
||||
? queryKeys.agents.adapterModels(selectedCompanyId, modelAdapterType, currentDefaultEnvironmentId || null, modelCacheIdentity)
|
||||
: ["agents", "none", "adapter-models", adapterType];
|
||||
@@ -1037,13 +1038,13 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
|
||||
aiConnection: modelAiBinding,
|
||||
agentId: isCreate ? undefined : props.agent.id,
|
||||
}),
|
||||
...(runnerAcpxAgent === "copilot" ? COPILOT_MODEL_DISCOVERY_QUERY_OPTIONS : {}),
|
||||
...(accountBoundCatalog ? ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS : {}),
|
||||
enabled: Boolean(selectedCompanyId) && !isExternalRunner && !connectionModels,
|
||||
});
|
||||
const copilotModelScope = runnerAcpxAgent === "copilot" ? JSON.stringify(modelQueryKey) : null;
|
||||
const accountModelScope = accountBoundCatalog ? JSON.stringify(modelQueryKey) : null;
|
||||
useEffect(() => {
|
||||
if (copilotModelScope && selectedCompanyId && !isExternalRunner && !connectionModels) void refreshConnectionModels();
|
||||
}, [copilotModelScope, selectedCompanyId, isExternalRunner, connectionModels, refreshConnectionModels]);
|
||||
if (accountModelScope && selectedCompanyId && !isExternalRunner && !connectionModels) void refreshConnectionModels();
|
||||
}, [accountModelScope, selectedCompanyId, isExternalRunner, connectionModels, refreshConnectionModels]);
|
||||
const [refreshModelsError, setRefreshModelsError] = useState<string | null>(null);
|
||||
const [refreshingModels, setRefreshingModels] = useState(false);
|
||||
const models = connectionModels?.models ?? fetchedModels ?? externalModels ?? [];
|
||||
@@ -1410,7 +1411,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
|
||||
setRefreshingModels(true);
|
||||
setRefreshModelsError(null);
|
||||
try {
|
||||
const refreshed = await agentsApi.adapterModels(selectedCompanyId, modelAdapterType, { refresh: true, environmentId: currentDefaultEnvironmentId || null, provider: modelProvider, ...(runnerAcpxAgent === "copilot" ? { acpxAgent: runnerAcpxAgent, aiConnection: modelAiBinding, agentId: !isCreate ? props.agent.id : undefined } : {}) });
|
||||
const refreshed = await agentsApi.adapterModels(selectedCompanyId, modelAdapterType, { refresh: true, environmentId: currentDefaultEnvironmentId || null, provider: modelProvider, ...(accountBoundCatalog ? { acpxAgent: runnerAcpxAgent, aiConnection: modelAiBinding, agentId: !isCreate ? props.agent.id : undefined } : {}) });
|
||||
queryClient.setQueryData(modelQueryKey, refreshed);
|
||||
} catch (error) {
|
||||
setRefreshModelsError(error instanceof Error ? error.message : "Failed to refresh adapter models.");
|
||||
@@ -1871,7 +1872,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
|
||||
model={String(eff("adapterConfig", "model", config.model) ?? "")} environmentId={currentDefaultEnvironmentId || undefined} legacy
|
||||
onChange={binding => {
|
||||
mark("runtime", "runtimeConfig", { ...runtimeConfig, aiConnection: binding });
|
||||
if (runnerAcpxAgent === "copilot" && hashKey([modelAiBinding ?? null]) === hashKey([binding ?? null])) void refreshConnectionModels();
|
||||
if (accountBoundCatalog && hashKey([modelAiBinding ?? null]) === hashKey([binding ?? null])) void refreshConnectionModels();
|
||||
}} />}
|
||||
|
||||
{showInlineAdapterTestEnvironmentFeedback && !props.compactTestFeedback && (testActionError || testEnvironment.error) && (
|
||||
@@ -1953,7 +1954,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
|
||||
onOpenChange={setModelOpen}
|
||||
defaultLabel={adapterType === "claude_local" ? `Default (${DEFAULT_CLAUDE_LOCAL_MODEL})` : undefined}
|
||||
allowDefault={adapterType !== "opencode_local" && adapterType !== "pi_local" && adapterType !== "paperclip_runner"}
|
||||
required={adapterType === "opencode_local" || adapterType === "pi_local"}
|
||||
required={adapterType === "opencode_local" || adapterType === "pi_local" || runnerAcpxAgent === "antigravity"}
|
||||
groupByProvider={!connectionModels && (adapterType === "opencode_local" || adapterType === "pi_local")}
|
||||
preserveOrder={Boolean(connectionModels) || adapterCuratesModelOrder(adapterType)}
|
||||
creatable
|
||||
@@ -1966,7 +1967,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
|
||||
return result.data?.model ?? null;
|
||||
}}
|
||||
onRefreshModels={
|
||||
connectionModels ? connectionModels.refreshModels : supportsAdapterModelRefresh(adapterType)
|
||||
connectionModels ? connectionModels.refreshModels : accountBoundCatalog || supportsAdapterModelRefresh(adapterType)
|
||||
? handleRefreshModels
|
||||
: undefined
|
||||
}
|
||||
@@ -2362,7 +2363,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
|
||||
{props.compactTestFeedback && showInlineAdapterTestEnvironmentFeedback && showAdapterTestEnvironmentButton && (
|
||||
<RuntimeTestCard
|
||||
variant={isExternalRunner ? "prerequisites" : "connection"}
|
||||
metadataOnly={adapterType === "paperclip_runner" && runnerAcpxAgent === "copilot"}
|
||||
metadataOnly={accountBoundCatalog}
|
||||
state={testActionPending ? "running" : testActionError || testEnvironment.error ? "fail" : testResult?.status ?? "idle"}
|
||||
result={testResult ?? null}
|
||||
error={testActionError ?? (testEnvironment.error instanceof Error ? testEnvironment.error.message : null)}
|
||||
|
||||
@@ -2367,15 +2367,18 @@ describe("IssueProperties", () => {
|
||||
act(() => root.unmount());
|
||||
});
|
||||
|
||||
it("discovers Copilot overrides with the assignee connection and environment", async () => {
|
||||
const binding = { provider: "github", method: "api_key", mode: "shared", connectionId: "11111111-1111-4111-8111-111111111111", grantId: "33333333-3333-4333-8333-333333333333" };
|
||||
mockAgentsApi.list.mockResolvedValue([{ id: "agent-1", name: "Copilot", role: "engineer", status: "active",
|
||||
it.each([
|
||||
{ name: "Copilot", acpxAgent: "copilot", provider: "github", method: "api_key", model: "gpt-5.6-luna", label: "Copilot Luna" },
|
||||
{ name: "Antigravity", acpxAgent: "antigravity", provider: "google", method: "subscription", model: "gemini-exact", label: "Personal Gemini" },
|
||||
] as const)("discovers $name overrides with the assignee connection and environment", async ({ acpxAgent, provider, method, model, label }) => {
|
||||
const binding = { provider, method, mode: "shared", connectionId: "11111111-1111-4111-8111-111111111111", grantId: "33333333-3333-4333-8333-333333333333" };
|
||||
mockAgentsApi.list.mockResolvedValue([{ id: "agent-1", name: acpxAgent, role: "engineer", status: "active",
|
||||
adapterType: "paperclip_runner", defaultEnvironmentId: "daytona-1",
|
||||
adapterConfig: { provider: "acpx", acpxAgent: "copilot", model: "gpt-5.6-luna" },
|
||||
adapterConfig: { provider: "acpx", acpxAgent, model },
|
||||
runtimeConfig: { aiConnection: binding } }]);
|
||||
mockAgentsApi.adapterModels.mockResolvedValue([{ id: "gpt-5.6-luna", label: "Copilot Luna" }]);
|
||||
mockAgentsApi.adapterModels.mockResolvedValue([{ id: model, label }]);
|
||||
const { root, queryClient } = renderPropertiesWithQueryClient(container, {
|
||||
issue: createIssue({ assigneeAgentId: "agent-1", assigneeAdapterOverrides: { adapterConfig: { model: "gpt-5.6-luna" } } }),
|
||||
issue: createIssue({ assigneeAgentId: "agent-1", assigneeAdapterOverrides: { adapterConfig: { model } } }),
|
||||
childIssues: [], onUpdate: vi.fn(), inline: true,
|
||||
});
|
||||
await flush();
|
||||
@@ -2385,7 +2388,7 @@ describe("IssueProperties", () => {
|
||||
expect(modelTrigger).toBeDefined();
|
||||
await act(async () => modelTrigger!.click());
|
||||
await waitForAssertion(() => expect(mockAgentsApi.adapterModels).toHaveBeenCalledWith("company-1", "paperclip_runner", {
|
||||
environmentId: "daytona-1", provider: "acpx", acpxAgent: "copilot", agentId: "agent-1", aiConnection: binding,
|
||||
environmentId: "daytona-1", provider: "acpx", acpxAgent, agentId: "agent-1", aiConnection: binding,
|
||||
}));
|
||||
await act(async () => { await queryClient.invalidateQueries({ type: "active" }, { cancelRefetch: false }); });
|
||||
expect(mockAgentsApi.adapterModels).toHaveBeenCalledTimes(1);
|
||||
|
||||
@@ -186,7 +186,7 @@ it("does not navigate after closing while an adapter save is pending", async ()
|
||||
expect(state.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("can save the name when the process adapter is disabled", async () => {
|
||||
await act(async () => cache.setQueryData(queryKeys.adapters.all, [...state.adapters, { type: "process", loaded: true, disabled: true }]));
|
||||
await act(async () => cache.setQueryData(queryKeys.adapters.availability("company-1", null), [...state.adapters, { type: "process", loaded: true, disabled: true }]));
|
||||
await name();
|
||||
expect(agents.create.mock.calls[0][1]).toMatchObject({ adapterType: "codex_local", metadata: { setupAdapterPending: true } });
|
||||
expect(document.querySelector('input[name="new-agent-adapter"]:checked')).toBeNull();
|
||||
@@ -228,10 +228,36 @@ it.each([true, false, undefined])("opens saved-token Copilot setup without an ex
|
||||
expect(query.get("runnerProvider")).toBe("copilot");
|
||||
});
|
||||
it("hides Copilot when its runtime adapter is disabled", async () => {
|
||||
await act(async () => cache.setQueryData(queryKeys.adapters.all, state.adapters.map((entry: any) => entry.type === "paperclip_runner" ? { ...entry, disabled: true } : entry)));
|
||||
await act(async () => cache.setQueryData(queryKeys.adapters.availability("company-1", null), state.adapters.map((entry: any) => entry.type === "paperclip_runner" ? { ...entry, disabled: true } : entry)));
|
||||
await name();
|
||||
expect(document.querySelector('input[value="copilot_runtime"]')).toBeNull();
|
||||
});
|
||||
it.each([true, false])("offers Google Antigravity in the ordinary picker while execution is pending (experimental=%s)", async enableNativeRunner => {
|
||||
await act(async () => cache.setQueryData(queryKeys.instance.experimentalSettings, { enableNativeRunner }));
|
||||
await name();
|
||||
const choice = document.querySelector<HTMLInputElement>('input[value="antigravity_runtime"]');
|
||||
expect(choice).not.toBeNull();
|
||||
expect(choice!.disabled).toBe(false);
|
||||
expect(choice!.closest("label")?.textContent).toContain("Google Antigravity");
|
||||
expect(choice!.closest("label")?.textContent).toContain("Not available yet");
|
||||
expect(choice!.closest("details")).toBeNull();
|
||||
await act(async () => choice!.click());
|
||||
await click("Configure agent");
|
||||
const query = new URL(state.navigate.mock.calls[0][0], "http://local").searchParams;
|
||||
expect(query.get("adapterType")).toBe("paperclip_runner");
|
||||
expect(query.get("runnerProvider")).toBe("antigravity");
|
||||
expect(query.get("setupAgentId")).toBe(agents.create.mock.calls[0][1].setupId);
|
||||
expect(agents.update).toHaveBeenCalledWith(agents.create.mock.calls[0][1].setupId, {
|
||||
name: "Ada & Co", metadata: { setupAdapterPending: true,
|
||||
setupAdapterChoice: { adapterType: "paperclip_runner", runnerProvider: "antigravity", runner: "auto" } },
|
||||
}, "company-1");
|
||||
expect(agents.create.mock.calls[0][1]).toMatchObject({ adapterType: "process", metadata: { setupAdapterPending: true } });
|
||||
});
|
||||
it("hides Google Antigravity when the runtime adapter is disabled", async () => {
|
||||
await act(async () => cache.setQueryData(queryKeys.adapters.availability("company-1", null), state.adapters.map((entry: any) => entry.type === "paperclip_runner" ? { ...entry, disabled: true } : entry)));
|
||||
await name();
|
||||
expect(document.querySelector('input[value="antigravity_runtime"]')).toBeNull();
|
||||
});
|
||||
it.each(["grok", "opencode"])("preserves explicit experimental %s creation in Advanced", async provider => {
|
||||
await name();
|
||||
await act(async () => (document.querySelector("summary") as HTMLElement).click());
|
||||
@@ -248,7 +274,7 @@ it.each(["grok", "opencode"])("preserves explicit experimental %s creation in Ad
|
||||
it.each(["gate off", "disabled adapter"])("hides experimental native creation when %s", async reason => {
|
||||
await act(async () => {
|
||||
if (reason === "gate off") cache.setQueryData(queryKeys.instance.experimentalSettings, { enableNativeRunner: false });
|
||||
else cache.setQueryData(queryKeys.adapters.all, state.adapters.map((entry: any) => entry.type === "paperclip_runner" ? { ...entry, disabled: true } : entry));
|
||||
else cache.setQueryData(queryKeys.adapters.availability("company-1", null), state.adapters.map((entry: any) => entry.type === "paperclip_runner" ? { ...entry, disabled: true } : entry));
|
||||
});
|
||||
await name();
|
||||
expect(document.querySelector('[aria-label="Experimental harness"]')).toBeNull();
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { Agent } from "@paperclipai/shared";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { AgentBulkRoster } from "./AgentBulkRoster";
|
||||
|
||||
vi.mock("@/api/ai-connections", () => ({ aiConnectionsApi: {
|
||||
list: vi.fn(async () => ({ currentUserId: "board", connections: [] })),
|
||||
} }));
|
||||
|
||||
describe("pending agent roster display", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
let client: QueryClient;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
client.clear();
|
||||
container.remove();
|
||||
});
|
||||
|
||||
function render(metadata: Record<string, unknown>) {
|
||||
const agent = { id: "draft", name: "Atlas", adapterType: "process", adapterConfig: {}, runtimeConfig: {},
|
||||
pauseReason: "setup", status: "paused", metadata } as unknown as Agent;
|
||||
flushSync(() => root.render(<QueryClientProvider client={client}>
|
||||
<AgentBulkRoster companyId="company" agents={[agent]} visibleAgents={[agent]} renderAgent={item => <span>{item.name}</span>} />
|
||||
</QueryClientProvider>));
|
||||
return [...container.querySelectorAll("tbody tr")][0] as HTMLTableRowElement;
|
||||
}
|
||||
|
||||
it("retains the pending harness label while keeping the placeholder unavailable for bulk editing", () => {
|
||||
const row = render({ setupAdapterPending: true,
|
||||
setupAdapterChoice: { adapterType: "paperclip_runner", runnerProvider: "antigravity", runner: "auto" } });
|
||||
expect([...row.querySelectorAll("td")].slice(2).map(cell => cell.textContent)).toEqual([
|
||||
"Google Antigravity", "Not configured", "Not available yet",
|
||||
]);
|
||||
const checkbox = row.querySelector<HTMLButtonElement>('[role="checkbox"]');
|
||||
expect(checkbox).not.toBeNull();
|
||||
expect(checkbox!.disabled).toBe(true);
|
||||
expect(container.textContent).not.toContain("Edit connection & model");
|
||||
});
|
||||
|
||||
it("preserves ordinary process display without a saved setup choice", () => {
|
||||
const row = render({ setupAdapterPending: true });
|
||||
expect([...row.querySelectorAll("td")].slice(2).map(cell => cell.textContent)).toEqual([
|
||||
"Process", "Managed externally", "Harness default",
|
||||
]);
|
||||
const checkbox = row.querySelector<HTMLButtonElement>('[role="checkbox"]');
|
||||
expect(checkbox).not.toBeNull();
|
||||
expect(checkbox!.disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import type { Agent } from "@paperclipai/shared";
|
||||
import { aiConnectionsApi } from "@/api/ai-connections";
|
||||
import { getAdapterLabel } from "@/adapters/adapter-display-registry";
|
||||
import { agentConnection, agentDefaultModel, bulkAgentDisabledReason, bulkAgentHarness, bulkConnectionName } from "@/lib/bulk-agent-settings";
|
||||
import { pendingAgentSetupDisplayAdapter } from "@/lib/agent-setup-choice";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Checkbox } from "@/components/ui/checkbox";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
|
||||
@@ -72,13 +73,16 @@ export function AgentBulkRoster({ companyId, agents, visibleAgents, renderAgent
|
||||
<th className="w-10"><Checkbox aria-label="Select all visible editable agents" checked={all ? true : some ? "indeterminate" : false} disabled={!selectable.length} onCheckedChange={toggleAll} /></th>
|
||||
<th>Agent</th><th>Harness</th><th>Connection</th><th>Default model</th>
|
||||
</tr></thead>
|
||||
<tbody>{visible.map(agent => <tr key={agent.id} data-state={selected.includes(agent.id) ? "selected" : undefined} className="border-t border-border data-[state=selected]:bg-accent/30 [&_td]:px-3">
|
||||
<tbody>{visible.map(agent => {
|
||||
const pendingSetup = pendingAgentSetupDisplayAdapter(agent);
|
||||
return <tr key={agent.id} data-state={selected.includes(agent.id) ? "selected" : undefined} className="border-t border-border data-[state=selected]:bg-accent/30 [&_td]:px-3">
|
||||
<td title={bulkAgentDisabledReason(agent)}><Checkbox aria-label={`Select ${agent.name}`} checked={selectedAgents.some(a => a.id === agent.id)} disabled={!!bulkAgentDisabledReason(agent)} onCheckedChange={value => setSelected(value ? [...new Set([...selected, agent.id])] : selected.filter(id => id !== agent.id))} /></td>
|
||||
<td className="min-w-64 p-0">{renderAgent(agent)}</td>
|
||||
<td className="whitespace-nowrap text-xs">{getAdapterLabel(bulkAgentHarness(agent))}</td>
|
||||
<td className="text-xs">{["http", "process"].includes(agent.adapterType) ? "Managed externally" : bulkConnectionName(agentConnection(agent), accounts.data)}</td>
|
||||
<td className="font-mono text-xs">{agentDefaultModel(agent) ?? "Harness default"}</td>
|
||||
</tr>)}</tbody>
|
||||
<td className="whitespace-nowrap text-xs">{getAdapterLabel(pendingSetup ?? bulkAgentHarness(agent))}</td>
|
||||
<td className="text-xs">{pendingSetup ? "Not configured" : ["http", "process"].includes(agent.adapterType) ? "Managed externally" : bulkConnectionName(agentConnection(agent), accounts.data)}</td>
|
||||
<td className="font-mono text-xs">{pendingSetup ? "Not available yet" : agentDefaultModel(agent) ?? "Harness default"}</td>
|
||||
</tr>;
|
||||
})}</tbody>
|
||||
</table></div>
|
||||
{!visible.length && <p className="py-8 text-center text-sm text-muted-foreground">No agents match these filters.</p>}
|
||||
{editing && <Suspense fallback={<p role="status" className="text-sm text-muted-foreground">Loading editor…</p>}><AgentBulkSettingsSheet companyId={companyId} agents={editing} totalSelected={selectedAgents.length} onClose={(updatedIds, complete) => {
|
||||
|
||||
@@ -26,10 +26,15 @@ async function render(agents: Agent[]) {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
await act(async () => root.render(<QueryClientProvider client={client}><TooltipProvider>
|
||||
<AgentBulkSettingsSheet companyId="company-1" agents={agents} totalSelected={agents.length} onClose={onClose} />
|
||||
</TooltipProvider></QueryClientProvider>));
|
||||
const draw = (selected: Agent[]) => root.render(<QueryClientProvider client={client}><TooltipProvider>
|
||||
<AgentBulkSettingsSheet companyId="company-1" agents={selected} totalSelected={selected.length} onClose={onClose} />
|
||||
</TooltipProvider></QueryClientProvider>);
|
||||
await act(async () => draw(agents));
|
||||
await vi.waitFor(() => expect(client.isFetching()).toBe(0));
|
||||
return async (selected: Agent[]) => {
|
||||
await act(async () => draw(selected));
|
||||
await vi.waitFor(() => expect(client.isFetching()).toBe(0));
|
||||
};
|
||||
}
|
||||
|
||||
function button(name: string) {
|
||||
@@ -67,6 +72,53 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
describe("bulk model editing", () => {
|
||||
it("refreshes an Antigravity catalog when its saved binding or environment changes", async () => {
|
||||
const first = { provider: "google", method: "subscription", mode: "shared", connectionId: "11111111-1111-4111-8111-111111111111", grantId: "33333333-3333-4333-8333-333333333333" } as const;
|
||||
const second = { ...first, connectionId: "22222222-2222-4222-8222-222222222222", grantId: "44444444-4444-4444-8444-444444444444" };
|
||||
const google = { ...agent("Antigravity", "paperclip_runner"), defaultEnvironmentId: "local-1",
|
||||
adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "old-model" }, runtimeConfig: { aiConnection: first } } as Agent;
|
||||
const rerender = await render([google]);
|
||||
expect(api.models).toHaveBeenCalledTimes(1);
|
||||
await rerender([{ ...google, defaultEnvironmentId: "remote-2", runtimeConfig: { aiConnection: second } }]);
|
||||
expect(api.models).toHaveBeenCalledTimes(2);
|
||||
expect(api.models).toHaveBeenLastCalledWith("company-1", "paperclip_runner", {
|
||||
provider: "acpx", acpxAgent: "antigravity", agentId: google.id, aiConnection: second, environmentId: "remote-2",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ method: "api_key", responsible: false },
|
||||
{ method: "api_key", responsible: true },
|
||||
{ method: "subscription", responsible: false },
|
||||
{ method: "subscription", responsible: true },
|
||||
] as const)("uses the bound Antigravity catalog and preserves $method manual-model policy (responsible: $responsible)", async ({ method, responsible }) => {
|
||||
const connectionId = "11111111-1111-4111-8111-111111111111", grantId = "33333333-3333-4333-8333-333333333333";
|
||||
const binding = responsible ? { provider: "google", method, mode: "responsible_user" } as const
|
||||
: { provider: "google", method, mode: "shared", connectionId, grantId } as const;
|
||||
const google = { ...agent("Antigravity", "paperclip_runner"), defaultEnvironmentId: "local-1",
|
||||
adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "old-model" }, runtimeConfig: { aiConnection: binding } } as Agent;
|
||||
api.accounts.mockResolvedValue({ currentUserId: "board", canManageConnections: true, pools: [], connections: [{
|
||||
id: connectionId, grantId, companyId: "company-1", provider: "google", method, name: "Selected Google account", status: "connected",
|
||||
ownership: responsible ? "personal" : "shared", ownerUserId: "board", isDefault: true,
|
||||
}] });
|
||||
if (method === "api_key") api.models.mockRejectedValue(new Error("Subscription sign-in is required to discover Google models"));
|
||||
else api.models.mockResolvedValue([{ id: "gemini-exact", label: "gemini-exact" }]);
|
||||
api.update.mockImplementation(async (_id, patch) => ({ ...google, adapterConfig: { ...google.adapterConfig, model: patch.model } }));
|
||||
await render([google]);
|
||||
if (method === "api_key") expect(api.models).not.toHaveBeenCalled();
|
||||
else expect(api.models).toHaveBeenCalledWith("company-1", "paperclip_runner", {
|
||||
provider: "acpx", acpxAgent: "antigravity", agentId: google.id, aiConnection: binding, environmentId: "local-1",
|
||||
});
|
||||
await chooseModel("gemini-custom", true);
|
||||
await vi.waitFor(() => expect(button("Update 1 agent").disabled).toBe(false));
|
||||
await act(async () => button("Update 1 agent").click());
|
||||
await vi.waitFor(() => expect(onClose).toHaveBeenCalledWith(["Antigravity"], true));
|
||||
expect(api.update).toHaveBeenCalledWith("Antigravity", expect.objectContaining({
|
||||
harness: "antigravity_runtime", model: "gemini-custom",
|
||||
expected: { model: "old-model", aiConnection: binding },
|
||||
}), "company-1");
|
||||
});
|
||||
|
||||
it("saves a manual Hermes model when the local adapter has no catalog", async () => {
|
||||
const hermes = agent("Hermes");
|
||||
api.update.mockResolvedValue({ ...hermes, adapterConfig: { model: "provider/custom-model" } });
|
||||
|
||||
@@ -6,6 +6,7 @@ import { agentsApi, type AdapterModel } from "@/api/agents";
|
||||
import { aiConnectionsApi } from "@/api/ai-connections";
|
||||
import { getAdapterLabel } from "@/adapters/adapter-display-registry";
|
||||
import { agentConnection, agentDefaultModel, bulkAgentHarness, bulkConnectionName, mapBulkAgents, resolveBulkConnection, sameBinding } from "@/lib/bulk-agent-settings";
|
||||
import { nativeTaskModelCatalogOptions } from "@/lib/native-model-catalog";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { AgentAvatar } from "@/components/AgentAvatar";
|
||||
import { ModelDropdown } from "@/components/AgentConfigForm";
|
||||
@@ -36,7 +37,7 @@ export function AgentBulkSettingsSheet({ companyId, agents, totalSelected, onClo
|
||||
const [failures, setFailures] = useState<Failure[] | null>(null);
|
||||
const targets = failures ? failures.map(f => f.agent) : agents;
|
||||
const catalogs = useQuery({
|
||||
queryKey: ["bulk-agent-models", companyId, targets.map(a => a.id), changeConnection ? binding : null],
|
||||
queryKey: ["bulk-agent-models", companyId, targets.map(a => [a.id, a.defaultEnvironmentId ?? null, nativeTaskModelCatalogOptions(a) ?? null]), changeConnection ? binding : null],
|
||||
retry: false,
|
||||
queryFn: async () => {
|
||||
const modelRequests = new Map<string, Promise<AdapterModel[]>>();
|
||||
@@ -47,15 +48,19 @@ export function AgentBulkSettingsSheet({ companyId, agents, totalSelected, onClo
|
||||
const connection = resolveBulkConnection(effective, accounts);
|
||||
const routing = connection?.routing;
|
||||
const openRouter = routing?.kind === "openrouter" || (!routing && effective?.provider === "openrouter");
|
||||
const restricted = Boolean(routing?.models.length || openRouter || harness === "copilot_runtime");
|
||||
const nativeCatalog = nativeTaskModelCatalogOptions(agent);
|
||||
let models: AdapterModel[];
|
||||
if (routing?.models.length) {
|
||||
models = routing.models.map(m => ({ id: aiRoutingModel(routing, harness, m.id), label: m.label ?? m.id }));
|
||||
} else if (nativeCatalog?.acpxAgent === "antigravity" && (connection?.method ?? effective?.method) === "api_key") {
|
||||
// Native discovery uses a saved subscription. API-key users retain
|
||||
// the existing unrestricted manual-model configuration path.
|
||||
models = [];
|
||||
} else {
|
||||
const copilot = harness === "copilot_runtime";
|
||||
const type = openRouter ? "opencode_local" : copilot ? "paperclip_runner" : harness;
|
||||
const options = openRouter ? { provider: "openrouter" } : copilot
|
||||
? { provider: "acpx", acpxAgent: "copilot", agentId: agent.id, aiConnection: effective, environmentId: agent.defaultEnvironmentId }
|
||||
const type = nativeCatalog ? "paperclip_runner" : openRouter ? "opencode_local" : harness;
|
||||
const options = nativeCatalog
|
||||
? { provider: "acpx", ...nativeCatalog, aiConnection: effective, environmentId: agent.defaultEnvironmentId }
|
||||
: openRouter ? { provider: "openrouter" }
|
||||
: { environmentId: agent.defaultEnvironmentId };
|
||||
const key = JSON.stringify([type, options]);
|
||||
let request = modelRequests.get(key);
|
||||
@@ -63,6 +68,7 @@ export function AgentBulkSettingsSheet({ companyId, agents, totalSelected, onClo
|
||||
models = await request;
|
||||
if (openRouter && !["opencode_local", "pi_local"].includes(harness)) models = models.map(m => ({ ...m, id: m.id.replace(/^openrouter\//, "") }));
|
||||
}
|
||||
const restricted = Boolean(routing?.models.length || openRouter || harness === "copilot_runtime");
|
||||
return { agent, accounts, binding: effective, models, restricted } satisfies Catalog;
|
||||
});
|
||||
return results.map((result, index) => result.status === "fulfilled" ? result.value : { agent: targets[index], error: result.reason instanceof Error ? result.reason.message : "Couldn’t load connections or models" });
|
||||
|
||||
@@ -34,7 +34,7 @@ type Props = {
|
||||
|
||||
/** Connections hosts the same provider step as agent setup, with its own save intent. */
|
||||
export function AiConnectionCredentialStep(props: Props) {
|
||||
if (props.provider === "openrouter" || props.provider === "github" || props.provider === "google") return <ApiKeyConnectionStep {...props} />;
|
||||
if (props.provider === "openrouter" || props.provider === "github") return <ApiKeyConnectionStep {...props} />;
|
||||
return <SubscriptionConnectionStep {...props} />;
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ function SubscriptionConnectionStep({ companyId, provider, initialMethod, fixedM
|
||||
});
|
||||
} catch (error) { environmentError = error instanceof Error ? error.message : "Could not resolve the sign-in environment."; }
|
||||
const loginEnvironments = (envs.data ?? []).filter((env) =>
|
||||
env.status === "active" && (env.driver === "local" || (env.driver === "sandbox" &&
|
||||
env.status === "active" && (env.driver === "local" || (provider !== "google" && env.driver === "sandbox" &&
|
||||
typeof env.config.provider === "string" &&
|
||||
caps.data?.sandboxProviders?.[env.config.provider]?.supportsLoginPty === true)),
|
||||
);
|
||||
@@ -88,7 +88,7 @@ function SubscriptionConnectionStep({ companyId, provider, initialMethod, fixedM
|
||||
{loading ? <p role="status" className="text-sm text-muted-foreground">Preparing sign-in…</p> : <AgentProviderConnection
|
||||
key={environmentId ?? "local"}
|
||||
companyId={companyId}
|
||||
adapterType={provider === "anthropic" ? "claude_local" : provider === "xai" ? "grok_local" : "codex_local"}
|
||||
adapterType={provider === "google" ? "antigravity_runtime" : provider === "anthropic" ? "claude_local" : provider === "xai" ? "grok_local" : "codex_local"}
|
||||
environmentId={environmentId}
|
||||
canLogin={canLogin}
|
||||
localEnvironment={environment?.driver === "local"}
|
||||
|
||||
@@ -37,6 +37,7 @@ export function aiProviderForAdapter(
|
||||
pi_local: "openrouter",
|
||||
grok_local: "xai",
|
||||
copilot_runtime: "github",
|
||||
antigravity_runtime: "google",
|
||||
gemini_local: "google",
|
||||
hermes_local: "openrouter",
|
||||
} as Record<string, AiProvider>
|
||||
|
||||
@@ -36,7 +36,7 @@ const providers = [
|
||||
name: "Anthropic",
|
||||
description: "Claude subscription or API key",
|
||||
},
|
||||
{ id: "google", name: "Google", description: "Gemini API key" },
|
||||
{ id: "google", name: "Google", description: "Antigravity sign-in or Gemini API key" },
|
||||
{ id: "xai", name: "xAI", description: "Grok subscription or API key" },
|
||||
{
|
||||
id: "openrouter",
|
||||
|
||||
@@ -8,7 +8,7 @@ export const AI_PROVIDERS: Record<
|
||||
{ name: string; subscriptionName?: string; logo?: string }
|
||||
> = {
|
||||
github: { name: "GitHub Copilot", logo: "/brands/apps/github.svg" },
|
||||
google: { name: "Google", logo: "/brands/apps/google.svg" },
|
||||
google: { name: "Google", subscriptionName: "Google Antigravity account", logo: "/brands/apps/google.svg" },
|
||||
anthropic: {
|
||||
name: "Claude",
|
||||
subscriptionName: "Claude subscription",
|
||||
|
||||
@@ -11,6 +11,7 @@ export function useLocalAiLogin(companyId: string | null, intent: AiConnectionLo
|
||||
const [authorizationUrl, setAuthorizationUrl] = useState<string | null>(null);
|
||||
const [code, setCode] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [accountLabel, setAccountLabel] = useState<string | null>(null);
|
||||
const [generation, setGeneration] = useState(0);
|
||||
const latestIntent = useRef(intent);
|
||||
const restartRequested = useRef(false);
|
||||
@@ -28,6 +29,7 @@ export function useLocalAiLogin(companyId: string | null, intent: AiConnectionLo
|
||||
useEffect(() => {
|
||||
setAttempt(null);
|
||||
setError(null);
|
||||
setAccountLabel(null);
|
||||
setStatus(null);
|
||||
setAuthorizationUrl(null);
|
||||
setCode(null);
|
||||
@@ -60,6 +62,7 @@ export function useLocalAiLogin(companyId: string | null, intent: AiConnectionLo
|
||||
setStatus(next.status);
|
||||
setAuthorizationUrl(next.authorizationUrl ?? null);
|
||||
setCode(next.code ?? null);
|
||||
setAccountLabel(next.accountLabel ?? null);
|
||||
setError(next.error ?? (next.status === "expired" ? "This sign-in attempt expired. Start sign-in again." : null));
|
||||
// Stop polling a verified account. Focus rechecks after the provider
|
||||
// browser visit; sign-in never requires repeated Connect clicks.
|
||||
@@ -86,6 +89,7 @@ export function useLocalAiLogin(companyId: string | null, intent: AiConnectionLo
|
||||
command: attempt?.command,
|
||||
authorizationUrl,
|
||||
code,
|
||||
accountLabel,
|
||||
status,
|
||||
preparing: active && !status && !error,
|
||||
error,
|
||||
|
||||
@@ -34,7 +34,7 @@ import { projectsApi } from "../../api/projects";
|
||||
import { useCompany } from "../../context/CompanyContext";
|
||||
import { useSidebar } from "../../context/SidebarContext";
|
||||
import { queryKeys } from "../../lib/queryKeys";
|
||||
import { COPILOT_MODEL_DISCOVERY_QUERY_OPTIONS, copilotTaskModelCatalogOptions } from "../../lib/copilot-task-model-catalog";
|
||||
import { ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS, nativeTaskModelCatalogOptions } from "../../lib/native-model-catalog";
|
||||
import { buildCompanyUserInlineOptions, buildCompanyUserLabelMap, buildCompanyUserProfileMap, isAgentTaskTarget } from "../../lib/company-members";
|
||||
import { ISSUE_OVERRIDE_ADAPTER_TYPES, type IssueModelLane } from "../../lib/issue-assignee-overrides";
|
||||
import { useProjectOrder } from "../../hooks/useProjectOrder";
|
||||
@@ -735,12 +735,12 @@ export function IssueProperties({
|
||||
const assignee = issue.assigneeAgentId
|
||||
? agents?.find((a) => a.id === issue.assigneeAgentId)
|
||||
: null;
|
||||
const copilotCatalog = copilotTaskModelCatalogOptions(assignee);
|
||||
const nativeCatalog = nativeTaskModelCatalogOptions(assignee);
|
||||
const assigneeAdapterType = assignee?.adapterType ?? null;
|
||||
const assigneeAdapterOverrides = issue.assigneeAdapterOverrides ?? null;
|
||||
const showAssigneeAdapterOptions = assigneeAdapterOverrides !== null;
|
||||
const supportsAssigneeOverrides = Boolean(
|
||||
assigneeAdapterType && (ISSUE_OVERRIDE_ADAPTER_TYPES.has(assigneeAdapterType) || copilotCatalog),
|
||||
assigneeAdapterType && (ISSUE_OVERRIDE_ADAPTER_TYPES.has(assigneeAdapterType) || nativeCatalog),
|
||||
);
|
||||
const assigneeOverrideLane = overrideLane(assigneeAdapterOverrides);
|
||||
const assigneeOverrideAdapterConfig = asRecord(assigneeAdapterOverrides?.adapterConfig);
|
||||
@@ -757,24 +757,24 @@ export function IssueProperties({
|
||||
const assigneeOverrideChrome = assigneeAdapterType === "claude_local"
|
||||
&& assigneeOverrideAdapterConfig.chrome === true;
|
||||
const catalogProvider = assigneeAdapterType === "paperclip_runner" ? String(normalizeLegacyRunnerProvider(assigneePrimaryAdapterConfig).provider ?? "codex") : undefined;
|
||||
const catalogEnvironmentId = copilotCatalog ? assignee?.defaultEnvironmentId ?? null : null;
|
||||
const copilotCatalogScope = JSON.stringify(copilotCatalog ?? null);
|
||||
const requestCopilotModels = Boolean(copilotCatalog && assigneeOptionsOpen && showAssigneeAdapterOptions && supportsAssigneeOverrides);
|
||||
const catalogEnvironmentId = nativeCatalog ? assignee?.defaultEnvironmentId ?? null : null;
|
||||
const nativeCatalogScope = JSON.stringify(nativeCatalog ?? null);
|
||||
const requestNativeModels = Boolean(nativeCatalog && assigneeOptionsOpen && showAssigneeAdapterOptions && supportsAssigneeOverrides);
|
||||
const { data: assigneeAdapterModels, refetch: refreshAssigneeModels } = useQuery({
|
||||
queryKey:
|
||||
companyId && assigneeAdapterType
|
||||
? [...queryKeys.agents.adapterModels(companyId, assigneeAdapterType, catalogEnvironmentId, catalogProvider), copilotCatalog ?? null]
|
||||
? [...queryKeys.agents.adapterModels(companyId, assigneeAdapterType, catalogEnvironmentId, catalogProvider), nativeCatalog ?? null]
|
||||
: ["agents", "none", "adapter-models", assigneeAdapterType ?? "none"],
|
||||
queryFn: () => agentsApi.adapterModels(companyId!, assigneeAdapterType!, {
|
||||
provider: catalogProvider,
|
||||
...(copilotCatalog ? { environmentId: catalogEnvironmentId, ...copilotCatalog } : {}),
|
||||
...(nativeCatalog ? { environmentId: catalogEnvironmentId, ...nativeCatalog } : {}),
|
||||
}),
|
||||
...(copilotCatalog ? COPILOT_MODEL_DISCOVERY_QUERY_OPTIONS : {}),
|
||||
enabled: Boolean(companyId) && showAssigneeAdapterOptions && supportsAssigneeOverrides && (!copilotCatalog || requestCopilotModels),
|
||||
...(nativeCatalog ? ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS : {}),
|
||||
enabled: Boolean(companyId) && showAssigneeAdapterOptions && supportsAssigneeOverrides && (!nativeCatalog || requestNativeModels),
|
||||
});
|
||||
useEffect(() => {
|
||||
if (requestCopilotModels) void refreshAssigneeModels();
|
||||
}, [requestCopilotModels, copilotCatalogScope, catalogEnvironmentId, companyId, refreshAssigneeModels]);
|
||||
if (requestNativeModels) void refreshAssigneeModels();
|
||||
}, [requestNativeModels, nativeCatalogScope, catalogEnvironmentId, companyId, refreshAssigneeModels]);
|
||||
const modelOverrideOptions = useMemo<InlineEntityOption[]>(() => {
|
||||
const models = sortAdapterModels(assigneeAdapterModels ?? []);
|
||||
const options = models.map((model) => ({
|
||||
|
||||
@@ -85,12 +85,15 @@ export function AgentBasicsDialog({
|
||||
isPending,
|
||||
error,
|
||||
} = useQuery({
|
||||
queryKey: queryKeys.adapters.all,
|
||||
queryFn: () => adaptersApi.list(),
|
||||
enabled: open,
|
||||
queryKey: queryKeys.adapters.availability(companyId ?? "none", null),
|
||||
queryFn: () => adaptersApi.list({ companyId: companyId! }),
|
||||
enabled: open && Boolean(companyId),
|
||||
});
|
||||
const nativeRunner = adapters?.find(adapter => adapter.type === "paperclip_runner" && adapter.loaded && !adapter.disabled);
|
||||
const copilotAvailable = Boolean(nativeRunner) && PAPERCLIP_RUNNER_ACPX_PROFILES.some(profile => profile.value === "copilot" && profile.qualified);
|
||||
const antigravityQualified = PAPERCLIP_RUNNER_ACPX_PROFILES.some(profile => profile.value === "antigravity" && profile.qualified);
|
||||
const antigravityCandidate = nativeRunner?.candidateHarnesses?.some(candidate => candidate.agent === "antigravity");
|
||||
const antigravityAvailable = Boolean(nativeRunner);
|
||||
const choices = [...(adapters ?? []).filter(
|
||||
(adapter) =>
|
||||
adapter.loaded &&
|
||||
@@ -102,11 +105,12 @@ export function AgentBasicsDialog({
|
||||
}) &&
|
||||
!["process", "http"].includes(adapter.type) &&
|
||||
!getAdapterDisplay(adapter.type).comingSoon,
|
||||
), ...(copilotAvailable ? [{ ...nativeRunner!, type: "copilot_runtime" }] : [])];
|
||||
), ...(copilotAvailable ? [{ ...nativeRunner!, type: "copilot_runtime" }] : []),
|
||||
...(antigravityAvailable ? [{ ...nativeRunner!, type: "antigravity_runtime" }] : [])];
|
||||
const experimentalRunnerAvailable = experimental.data?.enableNativeRunner === true
|
||||
&& adapters?.some(adapter => adapter.type === "paperclip_runner" && adapter.loaded && !adapter.disabled);
|
||||
const validAdapter = choices.some((adapter) => adapter.type === adapterType)
|
||||
|| (experimentalRunnerAvailable && adapterType === "paperclip_runner");
|
||||
|| (experimentalRunnerAvailable && adapterType === "paperclip_runner" && (runnerProvider !== "antigravity" || antigravityQualified));
|
||||
async function submit() {
|
||||
if (busy.current || !name.trim() || (step === "adapter" && !validAdapter)) return;
|
||||
busy.current = true;
|
||||
@@ -127,27 +131,34 @@ export function AgentBasicsDialog({
|
||||
agent = await agentsApi.create(companyId, {
|
||||
setupId: setupId.current, name: name.trim(), appearance: appearanceDraft.appearance,
|
||||
role: existing.length ? "general" : "ceo", ...(leader ? { reportsTo: leader.id } : {}),
|
||||
adapterType: provisionalAdapter === "copilot_runtime" ? "paperclip_runner" : provisionalAdapter,
|
||||
...(provisionalAdapter === "copilot_runtime" ? { adapterConfig: { provider: "acpx", acpxAgent: "copilot" } } : {}),
|
||||
adapterType: ["copilot_runtime", "antigravity_runtime"].includes(provisionalAdapter) ? "paperclip_runner" : provisionalAdapter,
|
||||
...(["copilot_runtime", "antigravity_runtime"].includes(provisionalAdapter) ? { adapterConfig: { provider: "acpx", acpxAgent: provisionalAdapter === "copilot_runtime" ? "copilot" : "antigravity" } } : {}),
|
||||
metadata: { setupAdapterPending: true },
|
||||
runtimeConfig: buildNewAgentRuntimeConfig({ heartbeatEnabled: false }),
|
||||
});
|
||||
if (active.current) setName(agent.name);
|
||||
}
|
||||
saved.current = agent;
|
||||
const nextAdapter = ["openai_dot", "copilot_runtime"].includes(adapterType) ? "paperclip_runner" : adapterType;
|
||||
const nextProvider = adapterType === "copilot_runtime" ? "copilot" : adapterType === "openai_dot" ? "openai_dot" : adapterType === "paperclip_runner" ? runnerProvider : "codex";
|
||||
const nextAdapter = ["openai_dot", "copilot_runtime", "antigravity_runtime"].includes(adapterType) ? "paperclip_runner" : adapterType;
|
||||
const nextProvider = adapterType === "antigravity_runtime" ? "antigravity" : adapterType === "copilot_runtime" ? "copilot" : adapterType === "openai_dot" ? "openai_dot" : adapterType === "paperclip_runner" ? runnerProvider : "codex";
|
||||
// Pending providers can show setup while the saved name-only draft stays held.
|
||||
const pendingAntigravity = nextProvider === "antigravity" && !antigravityQualified;
|
||||
if (step === "adapter" || (!creatingRecord && agent.name !== name.trim())) {
|
||||
const { setupAdapterChoice: _previousChoice, ...metadata } = agent.metadata ?? {};
|
||||
agent = await agentsApi.update(agent.id, {
|
||||
name: name.trim(),
|
||||
...(step === "adapter" ? {
|
||||
...(step === "adapter" && pendingAntigravity ? {
|
||||
metadata: { ...metadata, setupAdapterPending: true,
|
||||
setupAdapterChoice: { adapterType: nextAdapter, runnerProvider: nextProvider, runner: "auto" } },
|
||||
} : {}),
|
||||
...(step === "adapter" && !pendingAntigravity ? {
|
||||
adapterType: nextAdapter, runner: "auto" as const,
|
||||
adapterConfig: nextAdapter === "paperclip_runner" ? {
|
||||
provider: ["claude", "grok", "copilot"].includes(nextProvider) ? "acpx" : nextProvider,
|
||||
...(["claude", "grok", "copilot"].includes(nextProvider) ? { acpxAgent: nextProvider } : {}),
|
||||
provider: ["claude", "grok", "copilot", "antigravity"].includes(nextProvider) ? "acpx" : nextProvider,
|
||||
...(["claude", "grok", "copilot", "antigravity"].includes(nextProvider) ? { acpxAgent: nextProvider } : {}),
|
||||
...(nextProvider === "grok" ? { model: "grok-4.7" } : {}),
|
||||
} : {},
|
||||
metadata: { ...agent.metadata, setupAdapterPending: false },
|
||||
metadata: { ...metadata, setupAdapterPending: false },
|
||||
} : {}),
|
||||
}, companyId);
|
||||
saved.current = agent;
|
||||
@@ -285,6 +296,9 @@ export function AgentBasicsDialog({
|
||||
<span className="text-sm font-medium">
|
||||
{display.label}
|
||||
</span>
|
||||
{adapter.type === "antigravity_runtime" && !antigravityQualified && (
|
||||
<span className="text-xs text-muted-foreground">{antigravityCandidate ? "Candidate" : "Not available yet"}</span>
|
||||
)}
|
||||
{adapterType === adapter.type && (
|
||||
<Check className="absolute right-2 top-2 size-3.5" />
|
||||
)}
|
||||
|
||||
@@ -49,7 +49,7 @@ export function AgentProviderConnection({
|
||||
advancedConnection,
|
||||
}: {
|
||||
companyId: string;
|
||||
adapterType: "claude_local" | "codex_local" | "grok_local";
|
||||
adapterType: "claude_local" | "codex_local" | "grok_local" | "antigravity_runtime";
|
||||
environmentId: string | null;
|
||||
canLogin: boolean;
|
||||
localEnvironment?: boolean;
|
||||
@@ -97,10 +97,10 @@ export function AgentProviderConnection({
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [storedConnection, setStoredConnection] =
|
||||
useState<ProviderConnection | null>(null);
|
||||
const provider = adapterType === "claude_local" ? "Claude" : adapterType === "grok_local" ? "Grok" : "OpenAI";
|
||||
const provider = adapterType === "antigravity_runtime" ? "Google" : adapterType === "claude_local" ? "Claude" : adapterType === "grok_local" ? "Grok" : "OpenAI";
|
||||
const envKey =
|
||||
adapterType === "claude_local" ? "ANTHROPIC_API_KEY" : adapterType === "grok_local" ? "XAI_API_KEY" : "OPENAI_API_KEY";
|
||||
const aiProvider = adapterType === "claude_local" ? "anthropic" : adapterType === "grok_local" ? "xai" : "openai";
|
||||
adapterType === "antigravity_runtime" ? "GEMINI_API_KEY" : adapterType === "claude_local" ? "ANTHROPIC_API_KEY" : adapterType === "grok_local" ? "XAI_API_KEY" : "OPENAI_API_KEY";
|
||||
const aiProvider = adapterType === "antigravity_runtime" ? "google" : adapterType === "claude_local" ? "anthropic" : adapterType === "grok_local" ? "xai" : "openai";
|
||||
const availableKeys = useSavedProviderKeys(companyId, envKey);
|
||||
// Add/reconnect creates the requested account, never copies a saved account's
|
||||
// credential or silently changes its ownership. Agent setup retains reuse.
|
||||
@@ -158,7 +158,7 @@ export function AgentProviderConnection({
|
||||
environmentId ?? undefined,
|
||||
),
|
||||
retry: false,
|
||||
enabled: !managedAccount && !advanced,
|
||||
enabled: !managedAccount && !advanced && adapterType !== "antigravity_runtime",
|
||||
});
|
||||
async function connect() {
|
||||
if (busy || managedAccount?.disabled) return;
|
||||
@@ -230,7 +230,7 @@ export function AgentProviderConnection({
|
||||
}
|
||||
const needsLogin =
|
||||
method === "subscription" &&
|
||||
canLogin &&
|
||||
canLogin && adapterType !== "antigravity_runtime" &&
|
||||
environmentId &&
|
||||
!savedSubscription &&
|
||||
!savedKeys.loading &&
|
||||
@@ -448,7 +448,7 @@ export function AgentProviderConnection({
|
||||
(Boolean(managedAccount) && method === "subscription" && !canLogin && !canUseLocalLogin) ||
|
||||
(localEnvironment && health.isPending) || localLogin.preparing || Boolean(localLogin.error) ||
|
||||
(method === "subscription" && canUseLocalLogin && !savedSubscription && !storedLogin.data && localLogin.status !== "ready") ||
|
||||
(!managedAccount && auth.isPending) ||
|
||||
(!managedAccount && adapterType !== "antigravity_runtime" && auth.isPending) ||
|
||||
savedKeys.loading ||
|
||||
(adapterType === "claude_local" && storedLogin.isPending) ||
|
||||
// The saved-subscription chooser renders outside the opened section,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { COPILOT_MODEL_DISCOVERY_QUERY_OPTIONS } from "@/lib/copilot-task-model-catalog";
|
||||
import { ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS } from "@/lib/native-model-catalog";
|
||||
import { PAPERCLIP_RUNNER_ACPX_PROFILES } from "@paperclipai/adapter-utils";
|
||||
import { ExternalAgentInviteDialog } from "./ExternalAgentInviteDialog";
|
||||
import { useConnectionModels } from "../ai-connections/useConnectionModels";
|
||||
import { AgentCharacter } from "../AgentCharacter";
|
||||
@@ -19,6 +20,7 @@ import { testAgentSetup } from "@/lib/test-agent-setup";
|
||||
import { needsClaudeSetupQualification, qualifyClaudeSetup } from "@/lib/qualify-claude-setup";
|
||||
import { useCloudInstance } from "@/hooks/useCloudInstance";
|
||||
import { isNewAgentAdapterAllowed } from "@/lib/new-agent-adapters";
|
||||
import { pendingAgentSetupChoice } from "@/lib/agent-setup-choice";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { hashKey, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { AnimatePresence, motion, MotionConfig } from "motion/react";
|
||||
@@ -28,7 +30,7 @@ import type {
|
||||
Agent,
|
||||
EnvBinding,
|
||||
} from "@paperclipai/shared";
|
||||
import { ADAPTER_AUTH_MISSING_CHECK_CODE, paperclipRunnerProfileForHarness } from "@paperclipai/shared";
|
||||
import { ADAPTER_AUTH_MISSING_CHECK_CODE, isAgentStatusInvokable, paperclipRunnerProfileForHarness } from "@paperclipai/shared";
|
||||
import { useNavigate, useSearchParams } from "@/lib/router";
|
||||
import { agentsApi } from "@/api/agents";
|
||||
import { ApiError } from "@/api/client";
|
||||
@@ -133,7 +135,9 @@ function Setup({
|
||||
const isRunner = adapterType === "paperclip_runner";
|
||||
const isDot = isRunner && runnerProvider === "openai_dot";
|
||||
const brandType = isDot ? "openai_dot" : isRunner
|
||||
? runnerProvider === "copilot"
|
||||
? runnerProvider === "antigravity"
|
||||
? "antigravity_runtime"
|
||||
: runnerProvider === "copilot"
|
||||
? "copilot_runtime"
|
||||
: runnerProvider === "grok"
|
||||
? "grok_local"
|
||||
@@ -144,9 +148,11 @@ function Setup({
|
||||
: runnerProvider === "pi" ? "pi_local" : runnerProvider === "codex" ? "codex_local" : runnerProvider
|
||||
: adapterType;
|
||||
const connectionAdapter =
|
||||
brandType === "claude_local" || brandType === "codex_local" || brandType === "grok_local"
|
||||
brandType === "claude_local" || brandType === "codex_local" || brandType === "grok_local" || brandType === "antigravity_runtime"
|
||||
? brandType
|
||||
: null;
|
||||
const unreleasedAntigravity = brandType === "antigravity_runtime"
|
||||
&& !PAPERCLIP_RUNNER_ACPX_PROFILES.some(profile => profile.value === "antigravity" && profile.qualified);
|
||||
const multiProvider =
|
||||
brandType === "opencode_local" || brandType === "pi_local";
|
||||
const providerKeys = setupProviderKeys(brandType);
|
||||
@@ -179,6 +185,7 @@ function Setup({
|
||||
: undefined,
|
||||
);
|
||||
const [connection, setConnection] = useState<ProviderConnection | null>(null);
|
||||
const [choosingAdapter, setChoosingAdapter] = useState(false);
|
||||
const aiBinding = runtimeAiBinding ?? connection?.aiConnection;
|
||||
const connectionModels = useConnectionModels(companyId, aiBinding, brandType);
|
||||
const [repository, setRepository] = useState("");
|
||||
@@ -195,13 +202,26 @@ function Setup({
|
||||
queryKey: queryKeys.agents.detail(recordId ?? "new"),
|
||||
queryFn: () => agentsApi.get(recordId!, companyId),
|
||||
enabled: Boolean(recordId) && !creating.current,
|
||||
refetchInterval: query => query.state.data?.pauseReason === "setup"
|
||||
&& ["preparing", "pausing"].includes(query.state.data.lifecycleState ?? "") && !query.state.data.lifecycleError ? 1000 : false,
|
||||
refetchInterval: query => {
|
||||
const agent = query.state.data;
|
||||
if (!agent || agent.lifecycleError) return false;
|
||||
return (agent.pauseReason === "setup" && ["preparing", "pausing"].includes(agent.lifecycleState ?? ""))
|
||||
|| (screen === "saved" && !isDot && ["preparing", "verifying", "resuming", "pausing"].includes(agent.lifecycleState ?? "")) ? 1000 : false;
|
||||
},
|
||||
retry: false,
|
||||
});
|
||||
const created =
|
||||
(savedAgent.data?.companyId === companyId ? savedAgent.data : null) ?? currentCreated;
|
||||
const savedSetupChoice = pendingAgentSetupChoice(created);
|
||||
const resumeSavedChoice = savedSetupChoice && (adapterType !== savedSetupChoice.adapterType || runnerProvider !== savedSetupChoice.runnerProvider);
|
||||
useEffect(() => {
|
||||
if (!resumeSavedChoice || !created || !savedSetupChoice) return;
|
||||
navigate(`/agents/new?${new URLSearchParams({ name: created.name, setupAgentId: created.id, ...savedSetupChoice })}`, { replace: true });
|
||||
}, [resumeSavedChoice, created?.id, created?.name, savedSetupChoice?.adapterType, savedSetupChoice?.runnerProvider, navigate]);
|
||||
const completed = Boolean(created && created.pauseReason !== "setup");
|
||||
const runtimeReady = Boolean(created && isAgentStatusInvokable(created.status)
|
||||
&& (!created.lifecycleState || created.lifecycleState === "ready"));
|
||||
const finishingSetup = !isDot && ["preparing", "verifying", "resuming", "pausing"].includes(created?.lifecycleState ?? "");
|
||||
useEffect(() => {
|
||||
if (brandType !== "pi_local" || created?.adapterType !== "paperclip_runner"
|
||||
|| created.runtimeConfig.aiConnection) return;
|
||||
@@ -311,22 +331,24 @@ function Setup({
|
||||
? cause.message
|
||||
: "Could not resolve the environment.";
|
||||
}
|
||||
const requestCopilotModels = brandType === "copilot_runtime" && showModel && !connectionModels && Boolean(aiBinding)
|
||||
const accountBoundCatalog = brandType === "copilot_runtime" || brandType === "antigravity_runtime";
|
||||
const accountCatalogAvailable = brandType === "copilot_runtime" || (brandType === "antigravity_runtime" && aiBinding?.method === "subscription");
|
||||
const requestAccountModels = accountCatalogAvailable && showModel && !connectionModels && Boolean(aiBinding)
|
||||
&& envs.isSuccess && settings.isSuccess && experimental.isSuccess && general.isSuccess && !environmentError;
|
||||
const copilotModelScope = JSON.stringify([companyId, environmentId, aiBinding]);
|
||||
const accountModelScope = JSON.stringify([companyId, environmentId, aiBinding]);
|
||||
const models = useQuery({
|
||||
queryKey: queryKeys.agents.adapterModels(companyId, brandType, environmentId, brandType === "copilot_runtime" ? JSON.stringify(aiBinding ?? null) : aiBinding?.provider),
|
||||
queryFn: () => agentsApi.adapterModels(companyId, brandType === "copilot_runtime" ? "paperclip_runner" : brandType, brandType === "copilot_runtime"
|
||||
? { provider: "acpx", acpxAgent: "copilot", aiConnection: aiBinding, environmentId }
|
||||
queryKey: queryKeys.agents.adapterModels(companyId, brandType, environmentId, accountBoundCatalog ? JSON.stringify(aiBinding ?? null) : aiBinding?.provider),
|
||||
queryFn: () => agentsApi.adapterModels(companyId, accountBoundCatalog ? "paperclip_runner" : brandType, accountBoundCatalog
|
||||
? { provider: "acpx", acpxAgent: runnerProvider, aiConnection: aiBinding, environmentId }
|
||||
: { provider: aiBinding?.provider, environmentId }),
|
||||
...(brandType === "copilot_runtime" ? COPILOT_MODEL_DISCOVERY_QUERY_OPTIONS : {}),
|
||||
enabled: Boolean(brandType) && showModel && !connectionModels && (brandType !== "copilot_runtime" || requestCopilotModels),
|
||||
...(accountBoundCatalog ? ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS : {}),
|
||||
enabled: Boolean(brandType) && showModel && !connectionModels && (!accountBoundCatalog || requestAccountModels),
|
||||
retry: false,
|
||||
});
|
||||
const refreshCopilotModels = models.refetch;
|
||||
const refreshAccountModels = models.refetch;
|
||||
useEffect(() => {
|
||||
if (requestCopilotModels) void refreshCopilotModels();
|
||||
}, [requestCopilotModels, copilotModelScope, refreshCopilotModels]);
|
||||
if (requestAccountModels) void refreshAccountModels();
|
||||
}, [requestAccountModels, accountModelScope, refreshAccountModels]);
|
||||
const environment = envs.data?.find((env) => env.id === environmentId);
|
||||
const setupEnvironmentKey = JSON.stringify([companyId, environmentId, environment?.config]);
|
||||
const setupEnvironmentRef = useRef("");
|
||||
@@ -336,6 +358,10 @@ function Setup({
|
||||
queryKey: queryKeys.adapters.availability(companyId, environmentId),
|
||||
queryFn: () => adaptersApi.list({ companyId, environmentId }),
|
||||
});
|
||||
const candidateHarnesses = adapters.data?.find(adapter => adapter.type === "paperclip_runner" && adapter.loaded && !adapter.disabled)?.candidateHarnesses;
|
||||
const antigravityCandidate = brandType === "antigravity_runtime" ? candidateHarnesses?.find(candidate => candidate.agent === "antigravity") : undefined;
|
||||
const pendingAntigravity = unreleasedAntigravity && !antigravityCandidate;
|
||||
useEffect(() => { if (antigravityCandidate) setModel(current => current || antigravityCandidate.model); }, [antigravityCandidate?.model]);
|
||||
const defaultRunner = adapters.data?.find(adapter => adapter.type === adapterType)?.defaultRunner;
|
||||
const efforts = brandType === "pi_local" && (runner === "paperclip" || (runner === "auto" && defaultRunner === "paperclip"))
|
||||
? ["off", "low", "high", "max"] : isRunner ? [] : setupEfforts(adapterType, model);
|
||||
@@ -386,6 +412,7 @@ function Setup({
|
||||
nativeRunnerEnabled: experimental.data?.enableNativeRunner === true,
|
||||
openAiDotEnabled: experimental.data?.enableOpenAiDot === true,
|
||||
runnerProvider,
|
||||
candidateHarnesses,
|
||||
}) &&
|
||||
adapterInventory.data?.some(
|
||||
(adapter) =>
|
||||
@@ -394,8 +421,11 @@ function Setup({
|
||||
!adapter.disabled &&
|
||||
!getAdapterDisplay(adapterType).comingSoon,
|
||||
) && (requestAdapterType !== "paperclip_runner" || adapterType === "paperclip_runner" || adapterInventory.data?.some(adapter => adapter.type === "paperclip_runner" && adapter.loaded && !adapter.disabled));
|
||||
const configurationAvailable = available || (pendingAntigravity && adapterInventory.data?.some(
|
||||
adapter => adapter.type === "paperclip_runner" && adapter.loaded && !adapter.disabled,
|
||||
));
|
||||
const connectionSettingsReady = Boolean(
|
||||
available &&
|
||||
configurationAvailable &&
|
||||
(!["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) || runner !== "auto" || Boolean(adapters.data)) &&
|
||||
!environmentError &&
|
||||
!envs.isPending &&
|
||||
@@ -416,7 +446,7 @@ function Setup({
|
||||
const preparingComputer = created?.pauseReason === "setup" && ["preparing", "pausing"].includes(created.lifecycleState ?? "");
|
||||
const environmentSelectionSaved = (!environmentOverride && created?.defaultEnvironmentId == null)
|
||||
|| (created?.defaultEnvironmentId ?? null) === (environmentOverride || (forced.forced || managedOnly ? environmentId : null));
|
||||
const ready = Boolean(created) && environmentSelectionSaved && !environmentSaving && !preparingComputer && connectionSettingsReady && (!needsCurrentSetup || (
|
||||
const ready = (pendingAntigravity || Boolean(created) && environmentSelectionSaved) && !environmentSaving && !preparingComputer && connectionSettingsReady && (!needsCurrentSetup || (
|
||||
envs.isSuccess && !envs.isFetching
|
||||
&& settings.isSuccess && !settings.isFetching
|
||||
&& experimental.isSuccess && !experimental.isFetching
|
||||
@@ -443,9 +473,9 @@ function Setup({
|
||||
...(isRunner
|
||||
? {
|
||||
adapterSchemaValues: {
|
||||
provider: ["claude", "grok", "copilot", "pi"].includes(runnerProvider) ? "acpx" : runnerProvider,
|
||||
provider: ["claude", "grok", "copilot", "pi", "antigravity"].includes(runnerProvider) ? "acpx" : runnerProvider,
|
||||
...(isDot ? { allowUnmeteredProvider } : {}),
|
||||
...(["claude", "grok", "copilot", "pi"].includes(runnerProvider) ? { acpxAgent: runnerProvider } : {}),
|
||||
...(["claude", "grok", "copilot", "pi", "antigravity"].includes(runnerProvider) ? { acpxAgent: runnerProvider } : {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
@@ -456,14 +486,15 @@ function Setup({
|
||||
...(profile.provider === "acpx" ? { acpxPermissionMode: "approve-all" } : {}),
|
||||
...(brandType === "pi_local" && effort ? { piThinkingLevel: effort } : {}),
|
||||
} : {};
|
||||
const config = getUIAdapter(preserveNativeHarness && runner === "paperclip" && brandType !== "pi_local" ? "paperclip_runner" : adapterType).buildAdapterConfig(preserveNativeHarness && runner === "paperclip" ? { ...values, adapterSchemaValues: nativeSchema } : values);
|
||||
const config = getUIAdapter(preserveNativeHarness && runner === "paperclip" && brandType !== "pi_local" ? "paperclip_runner" : adapterType).buildAdapterConfig(preserveNativeHarness && runner === "paperclip" ? { ...values, adapterSchemaValues: nativeSchema } : values,
|
||||
antigravityCandidate ? { candidateHarnesses: [antigravityCandidate] } : undefined);
|
||||
if (preserveNativeHarness && runner === "paperclip" && profile) {
|
||||
Object.assign(config, nativeSchema, profile.provider === "opencode" ? { opencodePermissionMode: "allow" } : profile.provider === "codex" ? { codexPermissionMode: "never" } : {}, { lifecycleMode: "per_turn" });
|
||||
}
|
||||
if (isRunner)
|
||||
Object.assign(config, {
|
||||
provider: ["claude", "grok", "copilot", "pi"].includes(runnerProvider) ? "acpx" : runnerProvider,
|
||||
...(["claude", "grok", "copilot", "pi"].includes(runnerProvider) ? { acpxAgent: runnerProvider } : {}),
|
||||
provider: ["claude", "grok", "copilot", "pi", "antigravity"].includes(runnerProvider) ? "acpx" : runnerProvider,
|
||||
...(["claude", "grok", "copilot", "pi", "antigravity"].includes(runnerProvider) ? { acpxAgent: runnerProvider } : {}),
|
||||
...(model ? { model } : {}),
|
||||
});
|
||||
if (multiProvider && created) {
|
||||
@@ -511,6 +542,8 @@ function Setup({
|
||||
return config;
|
||||
}
|
||||
function preparedConfig(nextConnection = connection, setupRunner?: AgentRunner) {
|
||||
if (brandType === "antigravity_runtime" && (!model.trim() || model !== model.trim() || /\s/.test(model) || ["auto", "default"].includes(model.toLowerCase())))
|
||||
throw new Error("Choose or enter an exact Google Antigravity model ID.");
|
||||
if (brandType === "copilot_runtime" && !models.data?.some(candidate => candidate.id === model))
|
||||
throw new Error("Refresh Copilot models and select an available model before creating this agent.");
|
||||
if (isDot && !allowUnmeteredProvider) throw new Error("Acknowledge external provider billing before creating your Dot agent.");
|
||||
@@ -554,7 +587,7 @@ function Setup({
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!name || !adapterType || !connectionSettingsReady || createdAgentId || created || creating.current
|
||||
if (pendingAntigravity || !name || !adapterType || !connectionSettingsReady || createdAgentId || created || creating.current
|
||||
|| (setupAgentId && !savedAgent.isError)) return;
|
||||
if (savedAgent.error && (!(savedAgent.error instanceof ApiError) || savedAgent.error.status !== 404)) return;
|
||||
creating.current = true;
|
||||
@@ -568,8 +601,9 @@ function Setup({
|
||||
role: existing.length ? "general" : "ceo", ...(leader ? { reportsTo: leader.id } : {}),
|
||||
adapterType: requestAdapterType, runner,
|
||||
adapterConfig: requestAdapterType === "paperclip_runner" ? {
|
||||
provider: ["claude", "grok", "copilot", "pi"].includes(runnerProvider) ? "acpx" : runnerProvider,
|
||||
...(["claude", "grok", "copilot", "pi"].includes(runnerProvider) ? { acpxAgent: runnerProvider } : {}),
|
||||
provider: ["claude", "grok", "copilot", "pi", "antigravity"].includes(runnerProvider) ? "acpx" : runnerProvider,
|
||||
...(["claude", "grok", "copilot", "pi", "antigravity"].includes(runnerProvider) ? { acpxAgent: runnerProvider } : {}),
|
||||
...(antigravityCandidate ? { model: antigravityCandidate.model } : {}),
|
||||
} : {}, defaultEnvironmentId: environmentOverride || (forced.forced || managedOnly ? environmentId : null),
|
||||
runtimeConfig: buildNewAgentRuntimeConfig({ heartbeatEnabled: false }),
|
||||
}).then(async agent => {
|
||||
@@ -579,7 +613,7 @@ function Setup({
|
||||
void cache.invalidateQueries({ queryKey: queryKeys.agents.list(companyId) });
|
||||
}).catch(cause => setError(cause instanceof Error ? cause.message : "Could not create the agent."))
|
||||
.finally(() => { creating.current = false; });
|
||||
}, [name, adapterType, companyId, connectionSettingsReady, creationAttempt, createdAgentId, setupAgentId, savedAgent.isError, created]);
|
||||
}, [name, adapterType, companyId, connectionSettingsReady, creationAttempt, createdAgentId, setupAgentId, savedAgent.isError, created, pendingAntigravity]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!savedAgent.data || restored.current === savedAgent.data.id || savedAgent.data.companyId !== companyId) return;
|
||||
@@ -588,7 +622,7 @@ function Setup({
|
||||
if (agent.pauseReason !== "setup") { setScreen("saved"); return; }
|
||||
const config = agent.adapterConfig;
|
||||
if (multiProvider) setRunner(agent.adapterType === "paperclip_runner" ? "paperclip" : "legacy");
|
||||
setModel(typeof config.model === "string" ? config.model : "");
|
||||
setModel(typeof config.model === "string" && config.model ? config.model : antigravityCandidate?.model ?? "");
|
||||
setEffort(String(config.modelReasoningEffort ?? config.reasoningEffort ?? config.effort ?? config.thinkingEffort ?? config.piThinkingLevel ?? config.thinking ?? ""));
|
||||
setEnvironmentOverride(agent.defaultEnvironmentId ?? "");
|
||||
setRepository(typeof config.repoUrl === "string" ? config.repoUrl : "");
|
||||
@@ -612,6 +646,7 @@ function Setup({
|
||||
}, [savedAgent.data, companyId, connectionAdapter, brandType]);
|
||||
|
||||
async function saveDraft(nextConnection = connection, exit = false, testedConfig?: Record<string, unknown>, selectedEnvironment = environmentOverride) {
|
||||
if (pendingAntigravity) return;
|
||||
if (!created || completed) return;
|
||||
const binding = runtimeAiBinding ?? nextConnection?.aiConnection;
|
||||
const config = testedConfig ?? buildConfig(nextConnection);
|
||||
@@ -634,6 +669,7 @@ function Setup({
|
||||
adapterType: requestAdapterType, runner, adapterConfig: config,
|
||||
defaultEnvironmentId: selectedEnvironment || (forced.forced || managedOnly ? environmentId : null),
|
||||
runtimeConfig: { ...created.runtimeConfig, ...(binding ? { aiConnection: binding } : {}) },
|
||||
...(antigravityCandidate ? { metadata: { ...created.metadata, setupAdapterPending: false, setupAdapterChoice: undefined } } : {}),
|
||||
...(nextConnection?.applyStoredClaudeLogin ? { applyStoredClaudeLogin: true } : {}),
|
||||
}, companyId);
|
||||
rememberCredentials();
|
||||
@@ -654,6 +690,7 @@ function Setup({
|
||||
}
|
||||
|
||||
async function saveAndExit() {
|
||||
if (pendingAntigravity) { navigate("/agents/all"); return; }
|
||||
if (savingRef.current) return;
|
||||
savingRef.current = true;
|
||||
setSaving(true);
|
||||
@@ -673,7 +710,7 @@ function Setup({
|
||||
}
|
||||
|
||||
async function runTest(nextConnection = connection): Promise<Record<string, unknown> | null> {
|
||||
if (!ready) return null;
|
||||
if (!ready || pendingAntigravity) return null;
|
||||
const run = ++generation.current;
|
||||
const setupEnvironment = setupEnvironmentRef.current;
|
||||
setTestState("running");
|
||||
@@ -712,7 +749,8 @@ function Setup({
|
||||
!blocking(tested) &&
|
||||
(tested.checks.some(check => check.code === "environment_agent_approval_required") || !connectionAdapter ||
|
||||
tested.checks.some((check) =>
|
||||
check.code.endsWith("hello_probe_passed") || check.code === "ai_connection_api_key_reverified",
|
||||
check.code.endsWith("hello_probe_passed") || check.code === "ai_connection_api_key_reverified"
|
||||
|| (brandType === "antigravity_runtime" && check.code === "antigravity_metadata_verified"),
|
||||
))
|
||||
) ? config : null;
|
||||
} catch (cause) {
|
||||
@@ -728,6 +766,7 @@ function Setup({
|
||||
async function finish() {
|
||||
if (
|
||||
savingRef.current ||
|
||||
pendingAntigravity ||
|
||||
completed ||
|
||||
!created ||
|
||||
!ready ||
|
||||
@@ -803,6 +842,16 @@ function Setup({
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function assignFirstTask() {
|
||||
if (!created || !runtimeReady) return;
|
||||
const current = cache.getQueryData<Agent>(queryKeys.agents.detail(created.id)) ?? created;
|
||||
if (!isAgentStatusInvokable(current.status) || (current.lifecycleState && current.lifecycleState !== "ready")) return;
|
||||
await cache.cancelQueries({ queryKey: queryKeys.agents.list(companyId) });
|
||||
cache.setQueryData<Agent[]>(queryKeys.agents.list(companyId), agents => agents?.map(agent =>
|
||||
agent.id === current.id && (agent.lifecycleVersion ?? 0) <= (current.lifecycleVersion ?? 0) ? { ...agent, ...current } : agent));
|
||||
openNewIssue({ assigneeAgentId: current.id, status: "todo" });
|
||||
}
|
||||
if (recordId && !created && !creating.current && savedAgent.error && !(savedAgent.error instanceof ApiError && savedAgent.error.status === 404))
|
||||
return (
|
||||
<p
|
||||
@@ -814,22 +863,24 @@ function Setup({
|
||||
: "Loading your agent…"}
|
||||
</p>
|
||||
);
|
||||
if (!name || !adapterType || created?.metadata?.setupAdapterPending === true)
|
||||
if (resumeSavedChoice) return <p role="status" className="text-sm text-muted-foreground">Loading your agent setup…</p>;
|
||||
if (choosingAdapter || !name || !adapterType || (created?.metadata?.setupAdapterPending === true && !unreleasedAntigravity))
|
||||
return (
|
||||
<AgentBasicsDialog
|
||||
open
|
||||
initialAdapter={created?.metadata?.setupAdapterPending ? "" : adapterType}
|
||||
initialAdapter={choosingAdapter && savedSetupChoice ? "antigravity_runtime" : created?.metadata?.setupAdapterPending ? "" : adapterType}
|
||||
initialName={created?.name ?? name}
|
||||
setupAgentId={created?.metadata?.setupAdapterPending ? created.id : setupAgentId ?? undefined}
|
||||
onClose={() => navigate("/agents/all")}
|
||||
onContinue={(basics) =>
|
||||
onClose={() => choosingAdapter ? setChoosingAdapter(false) : navigate("/agents/all")}
|
||||
onContinue={(basics) => {
|
||||
setChoosingAdapter(false);
|
||||
navigate(`/agents/new?${new URLSearchParams(basics)}`, {
|
||||
replace: true,
|
||||
})
|
||||
}
|
||||
});
|
||||
}}
|
||||
/>
|
||||
);
|
||||
if (!created && connectionSettingsReady) return <div className="space-y-4">
|
||||
if (!created && connectionSettingsReady && !pendingAntigravity) return <div className="space-y-4">
|
||||
<p role={error ? "alert" : "status"}>{error ?? "Creating your agent…"}</p>
|
||||
{error && <Button onClick={() => setCreationAttempt(value => value + 1)}>Retry</Button>}
|
||||
</div>;
|
||||
@@ -920,7 +971,16 @@ function Setup({
|
||||
{setupError.message}
|
||||
</p>
|
||||
)}
|
||||
{adapterInventory.data && !available && (
|
||||
{pendingAntigravity && configurationAvailable && (
|
||||
<div className="space-y-2">
|
||||
<p role="status" className="text-sm text-muted-foreground">
|
||||
Google Antigravity is not available yet. You can connect your Google account and review settings. This agent cannot finish setup or run tasks yet. Model and connection settings are not saved to this agent yet.
|
||||
</p>
|
||||
{created && <Button variant="link" className="px-0" onClick={() => setChoosingAdapter(true)}>Change adapter</Button>}
|
||||
</div>
|
||||
)}
|
||||
{antigravityCandidate && <p role="status" className="text-sm text-muted-foreground">Google Antigravity candidate is enabled for testing on this instance.</p>}
|
||||
{adapterInventory.data && !configurationAvailable && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
This adapter is unavailable. Choose an enabled adapter.
|
||||
</p>
|
||||
@@ -1012,7 +1072,14 @@ function Setup({
|
||||
setRuntimeAiBinding(undefined);
|
||||
resetTest();
|
||||
}}
|
||||
testConnection={async next => (await runTest(next)) !== null}
|
||||
testConnection={async next => {
|
||||
if (brandType !== "antigravity_runtime") return (await runTest(next)) !== null;
|
||||
if (next.aiConnection?.method === "subscription") await agentsApi.adapterModels(companyId, "paperclip_runner", {
|
||||
provider: "acpx", acpxAgent: "antigravity", aiConnection: next.aiConnection, environmentId,
|
||||
agentId: !created || created.pauseReason === "setup" ? undefined : created.id,
|
||||
});
|
||||
return true;
|
||||
}}
|
||||
testError={
|
||||
error ??
|
||||
(
|
||||
@@ -1050,7 +1117,8 @@ function Setup({
|
||||
<Check className="size-5" />
|
||||
{created.status === "pending_approval"
|
||||
? "Agent submitted for approval"
|
||||
: isDot ? "Your Dot agent has been created" : "Your agent is ready"}
|
||||
: isDot ? "Your Dot agent has been created"
|
||||
: finishingSetup ? "Finishing agent setup" : runtimeReady ? "Your agent is ready" : "Your agent is paused"}
|
||||
</h2>
|
||||
<dl className="grid grid-cols-2 gap-4 text-sm">
|
||||
<dt className="text-muted-foreground">Adapter</dt>
|
||||
@@ -1069,7 +1137,9 @@ function Setup({
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{created.status === "pending_approval"
|
||||
? "An organization administrator must approve this agent before it can work."
|
||||
: isDot ? "Pair your Dot and test event delivery in configuration before assigning work." : "Assign a task when you’re ready for this agent to work."}
|
||||
: isDot ? "Pair your Dot and test event delivery in configuration before assigning work."
|
||||
: finishingSetup ? "Paperclip is preparing and verifying your agent. You can assign a task when it is ready."
|
||||
: runtimeReady ? "Assign a task when you’re ready for this agent to work." : "Review the agent’s status in configuration before assigning work."}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap justify-between gap-3">
|
||||
@@ -1081,10 +1151,10 @@ function Setup({
|
||||
{isDot ? "Back to Agents" : "Edit configuration"}
|
||||
</Button>
|
||||
<Button
|
||||
disabled={created.status === "pending_approval"}
|
||||
disabled={created.status === "pending_approval" || (!isDot && !runtimeReady)}
|
||||
onClick={() => isDot
|
||||
? navigate(`${agentUrl(created)}/runtime`)
|
||||
: openNewIssue({ assigneeAgentId: created.id, status: "todo" })
|
||||
: void assignFirstTask()
|
||||
}
|
||||
>
|
||||
{isDot ? "Pair Dot" : `Assign ${created.name} a Task`}
|
||||
@@ -1114,7 +1184,7 @@ function Setup({
|
||||
{!connectionAdapter && aiProviderForAdapter(brandType) && (
|
||||
<AiConnectionField companyId={companyId} agentName={name} adapterType={brandType} model={model} environmentId={environmentId ?? undefined} value={aiBinding}
|
||||
onChange={binding => { binding.mode !== "router" && setRuntimeAiBinding(binding); resetTest();
|
||||
if (brandType === "copilot_runtime" && hashKey([aiBinding ?? null]) === hashKey([binding ?? null])) void refreshCopilotModels();
|
||||
if (accountCatalogAvailable && hashKey([aiBinding ?? null]) === hashKey([binding ?? null])) void refreshAccountModels();
|
||||
}} />
|
||||
)}
|
||||
{(connectionModels ? connectionModels.error : models.error) && <p role="alert" className="text-sm text-destructive">Could not load models. Retry or enter a model ID manually.</p>}
|
||||
@@ -1126,8 +1196,8 @@ function Setup({
|
||||
presentation={brandType === "codex_local" ? "searchable" : "native"}
|
||||
models={connectionModels?.models ?? models.data ?? []}
|
||||
loadingModels={connectionModels?.isLoading ?? models.isLoading}
|
||||
onRefreshModels={connectionModels?.refreshModels ?? (brandType === "copilot_runtime" ? async () => { await models.refetch(); } : undefined)}
|
||||
refreshingModels={connectionModels?.refreshing ?? (brandType === "copilot_runtime" ? models.isFetching : undefined)}
|
||||
onRefreshModels={connectionModels?.refreshModels ?? (accountCatalogAvailable ? async () => { await models.refetch(); } : undefined)}
|
||||
refreshingModels={connectionModels?.refreshing ?? (accountCatalogAvailable ? models.isFetching : undefined)}
|
||||
value={model}
|
||||
onChange={(value) => {
|
||||
setModel(connectionModels?.resolveModel(value) ?? value);
|
||||
@@ -1152,8 +1222,8 @@ function Setup({
|
||||
}}
|
||||
open={modelOpen}
|
||||
onOpenChange={setModelOpen}
|
||||
allowDefault={!multiProvider && brandType !== "copilot_runtime"}
|
||||
required={multiProvider || brandType === "copilot_runtime"}
|
||||
allowDefault={!multiProvider && !accountBoundCatalog}
|
||||
required={multiProvider || accountBoundCatalog}
|
||||
creatable={brandType !== "copilot_runtime"}
|
||||
groupByProvider={multiProvider && !connectionModels}
|
||||
preserveOrder={Boolean(connectionModels) || adapterCuratesModelOrder(brandType)}
|
||||
@@ -1426,11 +1496,11 @@ function Setup({
|
||||
</fieldset>
|
||||
<RuntimeTestCard
|
||||
variant={isDot ? "prerequisites" : "connection"}
|
||||
metadataOnly={brandType === "copilot_runtime"}
|
||||
metadataOnly={accountBoundCatalog}
|
||||
state={testState}
|
||||
result={result}
|
||||
error={error}
|
||||
disabled={!ready || busy || Boolean(connectionAdapter && !connection)}
|
||||
disabled={pendingAntigravity || !ready || busy || Boolean(connectionAdapter && !connection)}
|
||||
onTest={() => void runTest()}
|
||||
/>
|
||||
{error && testState !== "fail" && (
|
||||
@@ -1442,7 +1512,7 @@ function Setup({
|
||||
{environmentSaveError && !environmentSelectionSaved && <Button disabled={busy} onClick={() => void changeEnvironment()}>Retry saving environment</Button>}
|
||||
<div className="flex justify-between border-t border-border py-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button type="button" variant="ghost" disabled={busy} onClick={() => void saveAndExit()}>Save & exit</Button>
|
||||
<Button type="button" variant="ghost" disabled={busy} onClick={() => void saveAndExit()}>{pendingAntigravity ? "Back to agents" : "Save & exit"}</Button>
|
||||
{connectionAdapter ? (
|
||||
<Button
|
||||
type="button"
|
||||
@@ -1468,6 +1538,7 @@ function Setup({
|
||||
type="submit"
|
||||
disabled={
|
||||
!ready ||
|
||||
pendingAntigravity ||
|
||||
busy ||
|
||||
testState === "fail" ||
|
||||
Boolean(connectionAdapter && !connection)
|
||||
|
||||
@@ -17,7 +17,7 @@ export function useSavedProviderKeys(
|
||||
envKey: string,
|
||||
enabled = true,
|
||||
) {
|
||||
const provider = ({ ANTHROPIC_API_KEY: "anthropic", OPENAI_API_KEY: "openai", OPENROUTER_API_KEY: "openrouter", XAI_API_KEY: "xai" } as Record<string, AiProvider>)[envKey];
|
||||
const provider = ({ ANTHROPIC_API_KEY: "anthropic", OPENAI_API_KEY: "openai", OPENROUTER_API_KEY: "openrouter", XAI_API_KEY: "xai", GEMINI_API_KEY: "google" } as Record<string, AiProvider>)[envKey];
|
||||
const managed = useQuery({
|
||||
queryKey: ["ai-connections", companyId],
|
||||
queryFn: () => aiConnectionsApi.list(companyId!),
|
||||
|
||||
@@ -276,9 +276,9 @@ describe("composer assignee picker", () => {
|
||||
expect(choices.some((item) => item.includes("GPT-6 Sol"))).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps Copilot discovery passive during reconnect reconciliation and refreshes on opening", async () => {
|
||||
it.each(["copilot", "antigravity"])("keeps %s discovery passive during reconnect reconciliation and refreshes on opening", async acpxAgent => {
|
||||
const copilot = { ...agent, adapterType: "paperclip_runner", defaultEnvironmentId: "daytona-1",
|
||||
adapterConfig: { provider: "acpx", acpxAgent: "copilot", model: "gpt-5.6-luna" } } as Agent;
|
||||
adapterConfig: { provider: "acpx", acpxAgent, model: "gpt-5.6-luna" } } as Agent;
|
||||
const loadModels = vi.spyOn(agentsApi, "adapterModels")
|
||||
.mockResolvedValueOnce([{ id: "gpt-5.6-luna", label: "Copilot Luna" }])
|
||||
.mockResolvedValue([{ id: "gpt-5.6-luna", label: "Updated Copilot Luna" }]);
|
||||
@@ -301,27 +301,42 @@ describe("composer assignee picker", () => {
|
||||
expect(document.body.textContent).toContain("Updated Copilot Luna");
|
||||
});
|
||||
|
||||
it("discovers Copilot task models with the assignee connection and environment", async () => {
|
||||
const binding = { provider: "github", method: "api_key", mode: "shared", connectionId: "11111111-1111-4111-8111-111111111111", grantId: "33333333-3333-4333-8333-333333333333" } as const;
|
||||
const copilot = { ...agent, adapterType: "paperclip_runner", defaultEnvironmentId: "daytona-1",
|
||||
adapterConfig: { provider: "acpx", acpxAgent: "copilot", model: "gpt-5.6-luna" },
|
||||
runtimeConfig: { aiConnection: binding } } as Agent;
|
||||
const loadModels = vi.spyOn(agentsApi, "adapterModels").mockResolvedValueOnce([
|
||||
{ id: "gpt-5.6-luna", label: "Copilot Luna" },
|
||||
]);
|
||||
render(vi.fn(), vi.fn(), true, { agents: new Map([[agent.id, copilot]]), settings: null });
|
||||
it.each([
|
||||
{ name: "Copilot", acpxAgent: "copilot", provider: "github", method: "api_key", model: "gpt-5.6-luna", label: "Copilot Luna" },
|
||||
{ name: "Antigravity", acpxAgent: "antigravity", provider: "google", method: "subscription", model: "gemini-exact", label: "Personal Gemini" },
|
||||
] as const)("discovers $name task models with the assignee connection and environment", async ({ acpxAgent, provider, method, model, label }) => {
|
||||
const binding = { provider, method, mode: "shared", connectionId: "11111111-1111-4111-8111-111111111111", grantId: "33333333-3333-4333-8333-333333333333" } as const;
|
||||
const selectedAgent = { ...agent, adapterType: "paperclip_runner", defaultEnvironmentId: "daytona-1",
|
||||
adapterConfig: { provider: "acpx", acpxAgent, model }, runtimeConfig: { aiConnection: binding } } as Agent;
|
||||
const loadModels = vi.spyOn(agentsApi, "adapterModels").mockResolvedValueOnce([{ id: model, label }]);
|
||||
render(vi.fn(), vi.fn(), true, { agents: new Map([[agent.id, selectedAgent]]), settings: null });
|
||||
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });
|
||||
expect(loadModels).not.toHaveBeenCalled();
|
||||
await click("Select model and effort");
|
||||
expect(loadModels).toHaveBeenCalledWith("company-1", "paperclip_runner", {
|
||||
environmentId: "daytona-1", provider: "acpx", poolId: undefined,
|
||||
acpxAgent: "copilot", agentId: agent.id, aiConnection: binding,
|
||||
acpxAgent, agentId: agent.id, aiConnection: binding,
|
||||
});
|
||||
await click("Choose exact model");
|
||||
expect(document.body.textContent).toContain("Copilot Luna");
|
||||
expect(document.body.textContent).toContain(label);
|
||||
expect(document.body.textContent).not.toContain("Claude Sonnet");
|
||||
});
|
||||
|
||||
it.each(["subscription", "api_key"] as const)("allows an exact Antigravity model absent from its %s catalog", async method => {
|
||||
const selectedAgent = { ...agent, adapterType: "paperclip_runner",
|
||||
adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-default" },
|
||||
runtimeConfig: { aiConnection: { provider: "google", method, mode: "responsible_user" } } } as Agent;
|
||||
vi.spyOn(agentsApi, "adapterModels").mockResolvedValue([{ id: "gemini-listed", label: "Listed native model" }]);
|
||||
const onSettingsChange = vi.fn();
|
||||
render(vi.fn(), onSettingsChange, true, { agents: new Map([[agent.id, selectedAgent]]), settings: null,
|
||||
initialOpen: true, initialView: "models", initialModelSearch: "gemini-custom-exact" });
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
|
||||
const manual = [...document.querySelectorAll<HTMLButtonElement>("button")].find(button => button.textContent?.includes("Use exact ID"));
|
||||
expect(manual?.disabled).toBe(false);
|
||||
await act(async () => manual!.click());
|
||||
expect(onSettingsChange).toHaveBeenLastCalledWith(expect.objectContaining({ model: "gemini-custom-exact" }));
|
||||
});
|
||||
|
||||
it("preserves settings when the selected assignee is chosen again", async () => {
|
||||
const onAssigneeChange = vi.fn();
|
||||
const onSettingsChange = vi.fn();
|
||||
|
||||
@@ -4,7 +4,7 @@ import { ArrowLeft, Check, ChevronDown, Plus, RotateCcw, Search, X, Zap } from "
|
||||
import { aiRuntimeConnectionBindingSchema, agentHarnessType, type Agent, type IssueAssigneeAdapterOverrides } from "@paperclipai/shared";
|
||||
import { agentsApi, type AdapterModel } from "@/api/agents";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { COPILOT_MODEL_DISCOVERY_QUERY_OPTIONS, copilotTaskModelCatalogOptions } from "@/lib/copilot-task-model-catalog";
|
||||
import { ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS, nativeTaskModelCatalogOptions } from "@/lib/native-model-catalog";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useMobileEntityPickerViewportStyle } from "@/hooks/useMobileEntityPickerViewportStyle";
|
||||
import { getLastComposerEffort, rememberComposerEffort } from "@/lib/recent-composer-effort";
|
||||
@@ -117,23 +117,23 @@ export function ComposerRunSettingsPicker({
|
||||
}, [isMuseRunner, settings, onSettingsChange]);
|
||||
const binding = aiRuntimeConnectionBindingSchema.safeParse(agent?.runtimeConfig?.aiConnection).data;
|
||||
const poolId = binding?.mode === "router" ? binding.connectionId : undefined;
|
||||
const copilotCatalog = copilotTaskModelCatalogOptions(agent);
|
||||
const nativeCatalog = nativeTaskModelCatalogOptions(agent);
|
||||
const acpxAgent = agent?.adapterType === "paperclip_runner" && provider === "acpx" && typeof agent.adapterConfig.acpxAgent === "string" ? agent.adapterConfig.acpxAgent : undefined;
|
||||
const copilotCatalogScope = JSON.stringify(copilotCatalog ?? null);
|
||||
const requestCopilotModels = Boolean(copilotCatalog && open && view !== "agents" && !modelOptionsOverride);
|
||||
const nativeCatalogScope = JSON.stringify(nativeCatalog ?? null);
|
||||
const requestNativeModels = Boolean(nativeCatalog && open && view !== "agents" && !modelOptionsOverride);
|
||||
const { data: fetchedModels = [], isPending: modelsPending, refetch: refreshModels } = useQuery({
|
||||
queryKey: agent && modelSupported
|
||||
? [...queryKeys.agents.adapterModels(companyId, agent.adapterType, agent.defaultEnvironmentId ?? null, provider), poolId ?? null, copilotCatalog ?? null, acpxAgent ?? null]
|
||||
? [...queryKeys.agents.adapterModels(companyId, agent.adapterType, agent.defaultEnvironmentId ?? null, provider), poolId ?? null, nativeCatalog ?? null, acpxAgent ?? null]
|
||||
: ["agents", "composer-models", "none"],
|
||||
queryFn: () => agentsApi.adapterModels(companyId, agent!.adapterType, {
|
||||
environmentId: agent!.defaultEnvironmentId ?? null, provider, poolId, acpxAgent, ...copilotCatalog,
|
||||
environmentId: agent!.defaultEnvironmentId ?? null, provider, poolId, acpxAgent, ...nativeCatalog,
|
||||
}),
|
||||
...(copilotCatalog ? COPILOT_MODEL_DISCOVERY_QUERY_OPTIONS : {}),
|
||||
enabled: Boolean(agent && modelSupported && !modelOptionsOverride && (!copilotCatalog || requestCopilotModels)),
|
||||
...(nativeCatalog ? ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS : {}),
|
||||
enabled: Boolean(agent && modelSupported && !modelOptionsOverride && (!nativeCatalog || requestNativeModels)),
|
||||
});
|
||||
useEffect(() => {
|
||||
if (requestCopilotModels) void refreshModels();
|
||||
}, [requestCopilotModels, copilotCatalogScope, companyId, agent?.defaultEnvironmentId, refreshModels]);
|
||||
if (requestNativeModels) void refreshModels();
|
||||
}, [requestNativeModels, nativeCatalogScope, companyId, agent?.defaultEnvironmentId, refreshModels]);
|
||||
// The server resolves instance-declared models first and otherwise returns the
|
||||
// adapter's curated catalog. Do not replace a declared Codex list locally.
|
||||
const models: readonly (AdapterModel & { detail?: string })[] = modelOptionsOverride
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { pendingAgentSetupChoice, pendingAgentSetupDisplayAdapter } from "./agent-setup-choice";
|
||||
|
||||
const choice = { adapterType: "paperclip_runner", runnerProvider: "antigravity", runner: "auto" } as const;
|
||||
describe("held agent setup choice", () => {
|
||||
it("retains only the recognized display and navigation intent", () => {
|
||||
const draft = { pauseReason: "setup", metadata: { setupAdapterPending: true, setupAdapterChoice: { ...choice, env: "must not project" } } };
|
||||
expect(pendingAgentSetupChoice(draft)).toEqual(choice);
|
||||
expect(pendingAgentSetupDisplayAdapter(draft)).toBe("antigravity_runtime");
|
||||
});
|
||||
it.each([
|
||||
{ pauseReason: null, metadata: { setupAdapterPending: true, setupAdapterChoice: choice } },
|
||||
{ pauseReason: "setup", metadata: { setupAdapterPending: false, setupAdapterChoice: choice } },
|
||||
{ pauseReason: "setup", metadata: { setupAdapterPending: true, setupAdapterChoice: { ...choice, runnerProvider: "unknown" } } },
|
||||
])("does not override an active or unrecognized agent ($pauseReason)", draft => {
|
||||
expect(pendingAgentSetupChoice(draft)).toBeUndefined();
|
||||
expect(pendingAgentSetupDisplayAdapter(draft)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
type SetupDraft = { pauseReason?: unknown; metadata?: unknown };
|
||||
export type PendingAgentSetupChoice = { adapterType: "paperclip_runner"; runnerProvider: "antigravity"; runner: "auto" };
|
||||
|
||||
/** Display and navigation intent only; never an execution configuration. */
|
||||
export function pendingAgentSetupChoice(agent: SetupDraft | null | undefined): PendingAgentSetupChoice | undefined {
|
||||
if (agent?.pauseReason !== "setup" || !agent.metadata || typeof agent.metadata !== "object") return;
|
||||
const metadata = agent.metadata as Record<string, unknown>;
|
||||
if (metadata.setupAdapterPending !== true || !metadata.setupAdapterChoice || typeof metadata.setupAdapterChoice !== "object") return;
|
||||
const choice = metadata.setupAdapterChoice as Record<string, unknown>;
|
||||
if (choice.adapterType === "paperclip_runner" && choice.runnerProvider === "antigravity" && choice.runner === "auto") {
|
||||
return { adapterType: "paperclip_runner", runnerProvider: "antigravity", runner: "auto" };
|
||||
}
|
||||
}
|
||||
|
||||
export function pendingAgentSetupDisplayAdapter(agent: SetupDraft | null | undefined): "antigravity_runtime" | undefined {
|
||||
return pendingAgentSetupChoice(agent) ? "antigravity_runtime" : undefined;
|
||||
}
|
||||
@@ -1,7 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { mapBulkAgents, sameBinding } from "./bulk-agent-settings";
|
||||
import type { Agent } from "@paperclipai/shared";
|
||||
import { bulkAgentDisabledReason, mapBulkAgents, sameBinding } from "./bulk-agent-settings";
|
||||
|
||||
describe("bulk agent writes", () => {
|
||||
it("allows Antigravity connection/model edits while preserving router-only editing", () => {
|
||||
const agent = { adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity" }, runtimeConfig: {}, status: "active" } as unknown as Agent;
|
||||
expect(bulkAgentDisabledReason(agent)).toBeUndefined();
|
||||
expect(bulkAgentDisabledReason({ ...agent, status: "terminated" })).toContain("not available");
|
||||
expect(bulkAgentDisabledReason({ ...agent, runtimeConfig: { aiConnection: { mode: "router", connectionId: "11111111-1111-4111-8111-111111111111" } } })).toContain("pool members");
|
||||
});
|
||||
it("bounds concurrent requests and retains each success and failure in input order", async () => {
|
||||
let active = 0;
|
||||
let peak = 0;
|
||||
|
||||
@@ -11,7 +11,7 @@ export const sameBinding = (a: AiRuntimeConnectionBinding | undefined, b: AiRunt
|
||||
export function bulkAgentDisabledReason(agent: Agent): string | undefined {
|
||||
if (["terminated", "pending_approval"].includes(agent.status)) return "This agent is not available for bulk edits";
|
||||
if (agentConnection(agent)?.mode === "router") return "Edit connection pool members on the agent's configuration page";
|
||||
if (!["codex_local", "claude_local", "gemini_local", "grok_local", "opencode_local", "hermes_local", "pi_local", "copilot_runtime", "cursor_local"].includes(bulkAgentHarness(agent))) return "Connection and model are managed externally";
|
||||
if (!["codex_local", "claude_local", "gemini_local", "grok_local", "opencode_local", "hermes_local", "pi_local", "copilot_runtime", "antigravity_runtime", "cursor_local"].includes(bulkAgentHarness(agent))) return "Connection and model are managed externally";
|
||||
}
|
||||
|
||||
export function resolveBulkConnection(binding: AiConnectionBinding | undefined, accounts: AiConnectionList) {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Agent } from "@paperclipai/shared";
|
||||
import { nativeTaskModelCatalogOptions } from "./native-model-catalog";
|
||||
import { isNewAgentAdapterAllowed } from "./new-agent-adapters";
|
||||
|
||||
const agent = { id: "google-agent", adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity" } } as unknown as Agent;
|
||||
describe("Antigravity model catalog scope", () => {
|
||||
it("binds discovery to the assignee and selected Google account", () => {
|
||||
const binding = { provider: "google", method: "subscription", mode: "responsible_user" } as const;
|
||||
expect(nativeTaskModelCatalogOptions({ ...agent, runtimeConfig: { aiConnection: binding } })).toEqual({
|
||||
acpxAgent: "antigravity", agentId: agent.id, aiConnection: binding,
|
||||
});
|
||||
expect(nativeTaskModelCatalogOptions({ ...agent, runtimeConfig: { aiConnection: {
|
||||
provider: "google", method: "api_key", mode: "responsible_user",
|
||||
} } })).not.toEqual(nativeTaskModelCatalogOptions({ ...agent, runtimeConfig: { aiConnection: binding } }));
|
||||
});
|
||||
it("does not substitute Claude for a missing saved account", () => {
|
||||
expect(nativeTaskModelCatalogOptions(agent)).toEqual({ acpxAgent: "antigravity", agentId: agent.id, aiConnection: undefined });
|
||||
expect(nativeTaskModelCatalogOptions({ ...agent, adapterConfig: { provider: "acpx", acpxAgent: "claude" } })).toBeUndefined();
|
||||
});
|
||||
it("keeps pending Antigravity unavailable even when experimental Runner is enabled", () => {
|
||||
expect(isNewAgentAdapterAllowed("paperclip_runner", { cloud: false, nativeRunnerEnabled: true, runnerProvider: "antigravity" })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { aiConnectionBindingSchema, type Agent } from "@paperclipai/shared";
|
||||
import { COPILOT_MODEL_DISCOVERY_QUERY_OPTIONS, copilotTaskModelCatalogOptions } from "./copilot-task-model-catalog";
|
||||
|
||||
/** These ACP catalogs resolve the selected account rather than a generic list. */
|
||||
export function isAccountBoundAcpxAgent(agent: unknown): agent is "copilot" | "antigravity" {
|
||||
return agent === "copilot" || agent === "antigravity";
|
||||
}
|
||||
|
||||
export function nativeTaskModelCatalogOptions(agent: Agent | null | undefined) {
|
||||
if (agent?.adapterType === "paperclip_runner" && agent.adapterConfig.provider === "acpx" && agent.adapterConfig.acpxAgent === "antigravity") {
|
||||
return { acpxAgent: "antigravity", agentId: agent.id,
|
||||
aiConnection: aiConnectionBindingSchema.safeParse(agent.runtimeConfig?.aiConnection).data };
|
||||
}
|
||||
return copilotTaskModelCatalogOptions(agent);
|
||||
}
|
||||
|
||||
/** Account reconciliation must not repeatedly provision catalog discovery. */
|
||||
export const ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS = COPILOT_MODEL_DISCOVERY_QUERY_OPTIONS;
|
||||
@@ -1,3 +1,4 @@
|
||||
import { PAPERCLIP_RUNNER_ACPX_PROFILES } from "@paperclipai/adapter-utils";
|
||||
const CLOUD_ADAPTERS = new Set([
|
||||
"claude_local",
|
||||
"codex_local",
|
||||
@@ -14,12 +15,16 @@ export function isNewAgentAdapterAllowed(
|
||||
openAiDotEnabled = false,
|
||||
museEnabled = false,
|
||||
runnerProvider,
|
||||
}: { cloud: boolean; nativeRunnerEnabled: boolean; openAiDotEnabled?: boolean; museEnabled?: boolean; runnerProvider?: string },
|
||||
candidateHarnesses,
|
||||
}: { cloud: boolean; nativeRunnerEnabled: boolean; openAiDotEnabled?: boolean; museEnabled?: boolean; runnerProvider?: string;
|
||||
candidateHarnesses?: readonly { agent: "antigravity"; model: string }[] },
|
||||
) {
|
||||
if (type === "openai_dot" || (type === "paperclip_runner" && runnerProvider === "openai_dot")) {
|
||||
return openAiDotEnabled;
|
||||
}
|
||||
if (type === "muse" || (type === "paperclip_runner" && runnerProvider === "muse")) return museEnabled && nativeRunnerEnabled;
|
||||
if (type === "paperclip_runner" && runnerProvider === "antigravity") return PAPERCLIP_RUNNER_ACPX_PROFILES.some(profile => profile.value === "antigravity" && profile.qualified)
|
||||
|| Boolean(candidateHarnesses?.some(candidate => candidate.agent === "antigravity" && candidate.model));
|
||||
if (type === "paperclip_runner") return runnerProvider === "copilot" || nativeRunnerEnabled;
|
||||
if (cloud) return CLOUD_ADAPTERS.has(type);
|
||||
return true;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act } from "react";
|
||||
import { PAPERCLIP_RUNNER_ACPX_PROFILES } from "@paperclipai/adapter-utils";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { queryKeys } from "@/lib/queryKeys";
|
||||
import { ApiError } from "@/api/client";
|
||||
@@ -591,6 +592,143 @@ describe("New agent setup", () => {
|
||||
expect(api.testEnvironment).toHaveBeenLastCalledWith("company-1", "codex_local", expect.objectContaining({ runner: "paperclip" }));
|
||||
expect(api.hire.mock.calls[0][1]).toMatchObject({ adapterType: "codex_local", runner: "paperclip" });
|
||||
});
|
||||
it("opens pending Antigravity configuration without creating or admitting a native agent", async () => {
|
||||
await render("paperclip_runner", "antigravity");
|
||||
expect(api.create).not.toHaveBeenCalled();
|
||||
expect(api.adapterModels).not.toHaveBeenCalled();
|
||||
expect(container.textContent).toContain("Google Antigravity is not available yet");
|
||||
expect(container.textContent).toContain("Connect a model");
|
||||
expect(container.textContent).not.toContain("This adapter is unavailable");
|
||||
expect(api.testEnvironment).not.toHaveBeenCalled();
|
||||
expect(api.hire).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([false, true])("connects, saves and finishes the exact company-authorized Antigravity candidate with cached setup %s while release qualification stays pending", async cached => {
|
||||
const id = "00000000-0000-4000-8000-000000000091", model = "exact-antigravity-model";
|
||||
const draft = { id, companyId: "company-1", name: "Atlas", adapterType: "process", adapterConfig: {}, runtimeConfig: {},
|
||||
metadata: { setupAdapterPending: true, setupAdapterChoice: { adapterType: "paperclip_runner", runnerProvider: "antigravity", runner: "auto" } }, pauseReason: "setup", status: "paused" };
|
||||
state.params = new URLSearchParams({ name: "Atlas", adapterType: "paperclip_runner", runnerProvider: "antigravity", setupAgentId: id });
|
||||
api.get.mockResolvedValue(draft);
|
||||
api.update.mockImplementation(async (_id, patch) => ({ ...draft, ...patch }));
|
||||
state.adapters = state.adapters.map((adapter: any) => adapter.type === "paperclip_runner"
|
||||
? { ...adapter, candidateHarnesses: [{ agent: "antigravity", model }] } : adapter);
|
||||
if (cached) {
|
||||
cache.setQueryData(queryKeys.instance.settings, { defaultEnvironmentId: "local-1" });
|
||||
cache.setQueryData(queryKeys.environments.list("company-1"), await envApi.list("company-1"));
|
||||
cache.setQueryData(queryKeys.adapters.availability("company-1", "local-1"), state.adapters);
|
||||
cache.setQueryData(queryKeys.agents.detail(id), draft);
|
||||
}
|
||||
managedApi.list.mockResolvedValue({ currentUserId: "user-1", connections: [{
|
||||
id: "11111111-1111-4111-8111-111111111111", grantId: "22222222-2222-4222-8222-222222222222", companyId: "company-1",
|
||||
provider: "google", method: "subscription", name: "Saved Google", ownership: "personal", ownerUserId: "user-1", isDefault: true, status: "connected",
|
||||
}] } as any);
|
||||
cache.setQueryDefaults(queryKeys.health, { staleTime: Infinity });
|
||||
cache.setQueryData(queryKeys.health, { status: "ok", deploymentMode: "local_trusted", localAiLoginSupported: true });
|
||||
api.testEnvironment.mockResolvedValue({ ...pass, checks: [{ code: "antigravity_metadata_verified", level: "info", message: "Exact model admitted without a prompt" }] });
|
||||
await renderCurrentParams();
|
||||
expect(container.textContent).toContain("Google Antigravity candidate is enabled");
|
||||
await click("Use saved subscription");
|
||||
expect(api.update).toHaveBeenCalledWith(id, expect.objectContaining({
|
||||
adapterType: "paperclip_runner", adapterConfig: expect.objectContaining({ provider: "acpx", acpxAgent: "antigravity", model }),
|
||||
metadata: expect.objectContaining({ setupAdapterPending: false }),
|
||||
}), "company-1");
|
||||
await click("Finish setup");
|
||||
expect(api.testEnvironment).toHaveBeenCalledWith("company-1", "paperclip_runner", expect.objectContaining({ adapterConfig: expect.objectContaining({ model, acpxAgent: "antigravity" }) }));
|
||||
expect(api.hire).toHaveBeenCalledWith("company-1", expect.objectContaining({ setupAgentId: id, adapterConfig: expect.objectContaining({ provider: "acpx", acpxAgent: "antigravity", model }) }));
|
||||
expect(PAPERCLIP_RUNNER_ACPX_PROFILES.find(profile => profile.value === "antigravity")?.qualified).toBe(false);
|
||||
});
|
||||
it("restores the saved Antigravity choice from a reopened physical Process draft", async () => {
|
||||
const id = "00000000-0000-4000-8000-000000000091";
|
||||
state.params = new URLSearchParams({ name: "Atlas", adapterType: "process", runnerProvider: "codex", setupAgentId: id });
|
||||
api.get.mockResolvedValue({ id, companyId: "company-1", name: "Atlas", adapterType: "process", adapterConfig: {}, runtimeConfig: {},
|
||||
metadata: { setupAdapterPending: true, setupAdapterChoice: { adapterType: "paperclip_runner", runnerProvider: "antigravity", runner: "auto" } }, pauseReason: "setup", status: "paused" });
|
||||
await renderCurrentParams();
|
||||
const params = new URL(state.navigate.mock.calls.at(-1)![0], "http://local").searchParams;
|
||||
expect(Object.fromEntries(params)).toMatchObject({ adapterType: "paperclip_runner", runnerProvider: "antigravity", runner: "auto", setupAgentId: id });
|
||||
state.params = params;
|
||||
await renderCurrentParams();
|
||||
expect(container.textContent).toContain("Google Antigravity is not available yet");
|
||||
expect(container.textContent).toContain("Connect a model");
|
||||
expect(container.textContent).not.toContain("Choose an adapter");
|
||||
expect(api.create).not.toHaveBeenCalled();
|
||||
expect(api.update).not.toHaveBeenCalled();
|
||||
expect(api.testEnvironment).not.toHaveBeenCalled();
|
||||
expect(api.hire).not.toHaveBeenCalled();
|
||||
await click("Change adapter");
|
||||
expect(document.querySelector<HTMLInputElement>('input[value="antigravity_runtime"]')?.checked).toBe(true);
|
||||
await act(async () => document.querySelector<HTMLInputElement>('input[value="codex_local"]')!.click());
|
||||
await act(async () => [...document.querySelectorAll("button")].find(button => button.textContent?.trim() === "Configure agent")!.click());
|
||||
await settle();
|
||||
expect(api.update).toHaveBeenCalledWith(id, expect.objectContaining({ adapterType: "codex_local", metadata: { setupAdapterPending: false } }), "company-1");
|
||||
});
|
||||
it.each(["api_key", "subscription"] as const)("reviews pending Antigravity %s settings from the held Add agent draft without execution", async method => {
|
||||
const id = "00000000-0000-4000-8000-000000000091";
|
||||
state.params = new URLSearchParams({ name: "Atlas", adapterType: "paperclip_runner", runnerProvider: "antigravity", setupAgentId: id });
|
||||
api.get.mockResolvedValue({ id, companyId: "company-1", name: "Atlas", adapterType: "process", adapterConfig: {},
|
||||
runtimeConfig: {}, metadata: { setupAdapterPending: true }, pauseReason: "setup", status: "paused" });
|
||||
managedApi.list.mockResolvedValue({ currentUserId: "user-1", connections: [{
|
||||
id: "11111111-1111-4111-8111-111111111111", grantId: "22222222-2222-4222-8222-222222222222", companyId: "company-1",
|
||||
provider: "google", method, name: "Saved Google", ownership: "personal", ownerUserId: "user-1", isDefault: true, status: "connected",
|
||||
}] } as any);
|
||||
api.adapterModels.mockResolvedValue([{ id: "google-exact-model", label: "My Google model" }]);
|
||||
cache.setQueryDefaults(queryKeys.health, { staleTime: Infinity });
|
||||
cache.setQueryData(queryKeys.health, { status: "ok", deploymentMode: "local_trusted", localAiLoginSupported: true });
|
||||
await renderCurrentParams();
|
||||
await click(method === "subscription" ? "Use saved subscription" : "Use saved API key");
|
||||
expect(container.textContent).toContain("Configure your agent");
|
||||
expect(container.textContent).toContain("Google Antigravity is not available yet");
|
||||
await fill("Model", "manual-exact-google-model");
|
||||
const test = container.querySelector<HTMLButtonElement>('[aria-label="Runtime test"] button');
|
||||
expect(test?.disabled).toBe(true);
|
||||
await act(async () => test!.click());
|
||||
const finish = [...container.querySelectorAll<HTMLButtonElement>("button")].find(button => button.textContent?.trim() === "Finish setup");
|
||||
expect(finish?.disabled).toBe(true);
|
||||
await act(async () => finish!.closest("form")!.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })));
|
||||
expect(api.create).not.toHaveBeenCalled();
|
||||
expect(api.update).not.toHaveBeenCalled();
|
||||
expect(api.testEnvironment).not.toHaveBeenCalled();
|
||||
expect(api.hire).not.toHaveBeenCalled();
|
||||
expect(api.adapterModels.mock.calls.every(call => call[1] === "paperclip_runner" && call[2]?.acpxAgent === "antigravity" && !call[2]?.agentId)).toBe(true);
|
||||
if (method === "api_key") expect(api.adapterModels).not.toHaveBeenCalled();
|
||||
else expect(api.adapterModels).toHaveBeenCalled();
|
||||
await click("Back to agents");
|
||||
expect(state.navigate).toHaveBeenLastCalledWith("/agents/all");
|
||||
});
|
||||
it.each(["api_key", "subscription"] as const)("wires a future qualified Antigravity %s account to metadata discovery and the exact model", async method => {
|
||||
// Simulate a future release declaration only inside this mocked UI fixture.
|
||||
// The production declaration remains pending and API execution stays gated.
|
||||
const profile = PAPERCLIP_RUNNER_ACPX_PROFILES.find(item => item.value === "antigravity")! as unknown as { qualified: boolean };
|
||||
const qualified = profile.qualified;
|
||||
profile.qualified = true;
|
||||
try {
|
||||
const binding = { provider: "google", method, mode: "delegated", connectionId: "11111111-1111-4111-8111-111111111111", grantId: "22222222-2222-4222-8222-222222222222" };
|
||||
managedApi.list.mockResolvedValue({ currentUserId: "user-1", connections: [{
|
||||
id: binding.connectionId, grantId: binding.grantId, companyId: "company-1", provider: "google", method,
|
||||
name: "Verified Google", ownership: "personal", ownerUserId: "user-1", isDefault: true, status: "connected",
|
||||
}] } as any);
|
||||
api.adapterModels.mockResolvedValue([{ id: "google-exact-model", label: "My Google model" }]);
|
||||
cache.setQueryDefaults(queryKeys.health, { staleTime: Infinity });
|
||||
cache.setQueryData(queryKeys.health, { status: "ok", deploymentMode: "local_trusted", localAiLoginSupported: true });
|
||||
await render("paperclip_runner", "antigravity");
|
||||
await click(method === "subscription" ? "Use saved subscription" : "Use saved API key");
|
||||
expect(api.testEnvironment).not.toHaveBeenCalled();
|
||||
expect(container.textContent).toContain("Configure your agent");
|
||||
if (method === "api_key") expect(api.adapterModels).not.toHaveBeenCalled();
|
||||
else await vi.waitFor(() => expect(api.adapterModels).toHaveBeenLastCalledWith("company-1", "paperclip_runner", expect.objectContaining({
|
||||
provider: "acpx", acpxAgent: "antigravity", aiConnection: expect.objectContaining({ provider: "google", method }), environmentId: "local-1",
|
||||
})));
|
||||
await click("Finish setup");
|
||||
expect(api.hire).not.toHaveBeenCalled();
|
||||
expect(container.textContent).toContain("exact Google Antigravity model ID");
|
||||
await fill("Model", "manual-exact-google-model");
|
||||
await click("Finish setup");
|
||||
expect(api.hire).toHaveBeenCalledWith("company-1", expect.objectContaining({ adapterType: "paperclip_runner",
|
||||
adapterConfig: expect.objectContaining({ provider: "acpx", acpxAgent: "antigravity", model: "manual-exact-google-model" }),
|
||||
runtimeConfig: expect.objectContaining({ aiConnection: expect.objectContaining({ provider: "google", method }) }),
|
||||
}));
|
||||
expect(api.adapterModels.mock.calls.every(call => call[1] === "paperclip_runner" && call[2]?.acpxAgent === "antigravity")).toBe(true);
|
||||
} finally { profile.qualified = qualified; }
|
||||
});
|
||||
|
||||
it("keeps saved-token Copilot discovery passive while new-agent setup is idle", async () => {
|
||||
api.adapterModels.mockResolvedValue([{ id: "gpt-5.6-luna", label: "Copilot Luna" }]);
|
||||
await render("paperclip_runner", "copilot");
|
||||
@@ -984,6 +1122,50 @@ describe("New agent setup", () => {
|
||||
status: "todo",
|
||||
});
|
||||
});
|
||||
it.each(["preparing", "verifying"] as const)("waits for actual %s completion and hands the current agent to the task composer", async phase => {
|
||||
const id = "00000000-0000-4000-8000-000000000094";
|
||||
const draft = { id, companyId: "company-1", name: "Atlas", role: "general", adapterType: "pi_local",
|
||||
adapterConfig: { model: "openrouter/anthropic/claude-sonnet-4.6" }, runtimeConfig: {},
|
||||
lifecycleState: "paused", lifecycleVersion: 1, pauseReason: "setup" as string | null, status: "paused" };
|
||||
let serverAgent = draft;
|
||||
state.params = new URLSearchParams({ name: "Atlas", adapterType: "pi_local", setupAgentId: id });
|
||||
api.get.mockImplementation(async () => serverAgent);
|
||||
// Keep the roster stale to reproduce the composer warning after activation.
|
||||
api.list.mockResolvedValue([draft]);
|
||||
api.hire.mockImplementation(async () => {
|
||||
serverAgent = { ...draft, lifecycleState: phase, lifecycleVersion: 2, pauseReason: null, status: "paused" };
|
||||
return { agent: serverAgent };
|
||||
});
|
||||
await renderCurrentParams();
|
||||
await click("Finish setup");
|
||||
expect(container.textContent).toContain("Finishing agent setup");
|
||||
expect(container.textContent).not.toContain("Your agent is ready");
|
||||
expect([...container.querySelectorAll("button")].find(button => button.textContent?.trim() === "Assign Atlas a Task")?.disabled).toBe(true);
|
||||
serverAgent = { ...draft, lifecycleState: "ready", lifecycleVersion: 3, pauseReason: null, status: "idle" };
|
||||
await act(async () => { await new Promise(resolve => setTimeout(resolve, 1_100)); });
|
||||
await settle();
|
||||
expect(container.textContent).toContain("Your agent is ready");
|
||||
state.openNewIssue.mockImplementationOnce(() => {
|
||||
expect(cache.getQueryData(queryKeys.agents.list("company-1"))).toEqual([
|
||||
expect.objectContaining({ id, status: "idle", pauseReason: null, lifecycleState: "ready", lifecycleVersion: 3 }),
|
||||
]);
|
||||
});
|
||||
await click("Assign Atlas a Task");
|
||||
expect(state.openNewIssue).toHaveBeenCalledWith({ assigneeAgentId: id, status: "todo" });
|
||||
expect(api.hire).toHaveBeenCalledOnce();
|
||||
});
|
||||
it.each(["manual", "import"])("keeps a genuinely %s-paused agent unavailable for first-task assignment", async pauseReason => {
|
||||
const id = "00000000-0000-4000-8000-000000000095";
|
||||
api.get.mockResolvedValue({ id, companyId: "company-1", name: "Atlas", adapterType: "pi_local", adapterConfig: {}, runtimeConfig: {},
|
||||
lifecycleState: "paused", lifecycleVersion: 3, pauseReason, status: "paused" });
|
||||
state.params = new URLSearchParams({ name: "Atlas", adapterType: "pi_local", createdAgentId: id });
|
||||
await renderCurrentParams();
|
||||
expect(container.textContent).toContain("Your agent is paused");
|
||||
expect(container.textContent).not.toContain("Your agent is ready");
|
||||
await click("Assign Atlas a Task");
|
||||
expect(state.openNewIssue).not.toHaveBeenCalled();
|
||||
expect(api.hire).not.toHaveBeenCalled();
|
||||
});
|
||||
it("does not advance connection after a timed-out provider probe", async () => {
|
||||
api.testEnvironment.mockResolvedValue({
|
||||
...pass,
|
||||
|
||||
Reference in new issue
Block a user