Files
PaperClipAI/ui/src/components/AgentActionButtons.test.tsx
T
DottaandPaperclip 61bd4ac691 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>
2026-10-29 16:51:50 -05:00

427 lines
19 KiB
TypeScript

// @vitest-environment jsdom
import type { ComponentProps, ReactNode } from "react";
import { flushSync } from "react-dom";
import { createRoot } 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 { AgentActionButtons } from "./AgentActionButtons";
import { useAgentLifecycleStatus } from "./AgentLifecycleStatus";
import { queryKeys } from "../lib/queryKeys";
const mockNavigate = vi.hoisted(() => vi.fn());
const mockOpenNewIssue = vi.hoisted(() => vi.fn());
const mockPushToast = vi.hoisted(() => vi.fn());
const mockAgentsApi = vi.hoisted(() => ({
get: vi.fn(),
invoke: vi.fn(),
pause: vi.fn(),
resume: vi.fn(),
clearError: vi.fn(),
approve: vi.fn(),
terminate: vi.fn(),
resetSession: vi.fn(),
instructionsBundle: vi.fn(),
instructionsFile: vi.fn(),
create: vi.fn(),
hire: vi.fn(),
}));
vi.mock("@/lib/router", () => ({
Link: ({ children, to, ...props }: { children: ReactNode; to: string }) => (
<a href={to} {...props}>{children}</a>
),
useNavigate: () => mockNavigate,
}));
vi.mock("../context/DialogContext", () => ({
useDialogActions: () => ({ openNewIssue: mockOpenNewIssue }),
}));
vi.mock("../context/ToastContext", () => ({
useToastActions: () => ({ pushToast: mockPushToast }),
}));
vi.mock("../api/agents", () => ({
agentsApi: mockAgentsApi,
}));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
async function act(callback: () => void | Promise<void>) {
let result: void | Promise<void> = undefined;
flushSync(() => {
result = callback();
});
await result;
}
async function flushReact() {
await act(async () => {
await Promise.resolve();
await new Promise((resolve) => window.setTimeout(resolve, 0));
});
}
function makeAgent(overrides: Partial<Agent> = {}): Agent {
return {
id: "agent-1",
companyId: "company-1",
name: "Alpha Agent",
urlKey: "alpha",
role: "engineer",
title: null,
icon: null,
status: "active",
reportsTo: null,
capabilities: null,
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
budgetMonthlyCents: 0,
spentMonthlyCents: 0,
pauseReason: null,
pausedAt: null,
permissions: { canCreateAgents: false },
lastHeartbeatAt: null,
metadata: null,
createdAt: new Date("2026-01-01T00:00:00Z"),
updatedAt: new Date("2026-01-01T00:00:00Z"),
...overrides,
};
}
describe("AgentActionButtons", () => {
let container: HTMLDivElement;
let root: ReturnType<typeof createRoot> | null;
let queryClient: QueryClient;
let invalidateQueries: ReturnType<typeof vi.fn>;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = null;
queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
invalidateQueries = vi.spyOn(queryClient, "invalidateQueries") as unknown as ReturnType<typeof vi.fn>;
mockAgentsApi.clearError.mockResolvedValue(makeAgent({ status: "idle" }));
mockAgentsApi.pause.mockResolvedValue(makeAgent({ status: "paused" }));
mockAgentsApi.resume.mockResolvedValue(makeAgent({ status: "idle" }));
mockAgentsApi.terminate.mockResolvedValue(makeAgent({ status: "terminated" }));
mockAgentsApi.invoke.mockResolvedValue({ id: "run-1" });
mockAgentsApi.resetSession.mockResolvedValue(undefined);
});
afterEach(async () => {
const currentRoot = root;
if (currentRoot) {
await act(async () => {
currentRoot.unmount();
});
}
queryClient.clear();
container.remove();
document.body.innerHTML = "";
vi.clearAllMocks();
});
function render(agent: Agent, props: Partial<ComponentProps<typeof AgentActionButtons>> = {}) {
root ??= createRoot(container);
root.render(
<QueryClientProvider client={queryClient}>
<AgentActionButtons agent={agent} companyId="company-1" runLabel="Run Heartbeat" {...props} />
</QueryClientProvider>,
);
}
it.each(["codex_local", "claude_local", "opencode_local", "pi_local", "paperclip_runner"])("returns unfinished %s agents to their saved runner", async adapterType => {
render(makeAgent({ adapterType, status: "paused", lifecycleState: "paused", pauseReason: "setup" }));
await flushReact();
const finish = [...container.querySelectorAll("button")].find(button => button.textContent === "Finish setup");
expect(finish).toBeTruthy();
expect([...container.querySelectorAll("button")].some(button => button.textContent === "Resume")).toBe(false);
await act(() => finish!.click());
expect(mockNavigate).toHaveBeenCalledWith(expect.stringContaining("setupAgentId=agent-1"));
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" }));
await flushReact();
const buttons = [...container.querySelectorAll("button")];
const finish = buttons.filter(button => button.textContent === "Finish setup");
expect(finish).toHaveLength(1);
expect(buttons.some(button => /Run Heartbeat|^Resume$|^Pause$/.test(button.textContent ?? ""))).toBe(false);
await act(() => finish[0].click());
const target = new URL(mockNavigate.mock.calls[0][0], "https://example.test");
expect(target.pathname).toBe("/agents/new");
expect(Object.fromEntries(target.searchParams)).toMatchObject({ setupAgentId: "agent-1", adapterType: "paperclip_runner", runnerProvider: "claude", runner: "paperclip" });
expect(mockAgentsApi.invoke).not.toHaveBeenCalled();
expect(mockAgentsApi.resume).not.toHaveBeenCalled();
});
it.each(["terminating", "cleaning_up", "terminated", "rejected"] as const)("does not reopen setup during %s", async lifecycleState => {
render(makeAgent({ status: "terminated", lifecycleState, pauseReason: "setup" }));
await flushReact();
expect(container.textContent).not.toContain("Finish setup");
});
it("restores Run after lifecycle refresh completes setup without replacing the editable record", async () => {
const draft = makeAgent({ status: "paused", lifecycleState: "paused", lifecycleVersion: 1, pauseReason: "setup", pausedAt: new Date("2026-01-01T00:00:00Z"), adapterConfig: { model: "saved-model" } });
queryClient.setQueryData(queryKeys.agents.detail("alpha"), draft);
mockAgentsApi.get.mockResolvedValueOnce(draft);
function LiveActions() {
const lifecycle = useAgentLifecycleStatus(draft);
return <AgentActionButtons agent={{ ...draft, ...lifecycle.data }} companyId="company-1" runLabel="Run Heartbeat" />;
}
root = createRoot(container);
root.render(<QueryClientProvider client={queryClient}><LiveActions /></QueryClientProvider>);
await flushReact();
expect(container.textContent).toContain("Finish setup");
mockAgentsApi.get.mockResolvedValue({ ...draft, status: "idle", lifecycleState: "ready", lifecycleVersion: 2, pauseReason: null, pausedAt: null, adapterConfig: { model: "updated-on-server" } });
await act(async () => { await queryClient.invalidateQueries({ queryKey: [...queryKeys.agents.detail(draft.id), "lifecycle", draft.companyId] }); });
await flushReact();
expect(container.textContent).not.toContain("Finish setup");
const run = [...container.querySelectorAll("button")].find(button => button.textContent === "Run Heartbeat");
expect(run?.disabled).toBe(false);
expect(queryClient.getQueryData<Agent>(queryKeys.agents.detail("alpha"))?.adapterConfig).toEqual({ model: "saved-model" });
expect(mockAgentsApi.get).toHaveBeenLastCalledWith("agent-1", "company-1");
await act(() => run!.click());
await flushReact();
expect(mockAgentsApi.invoke).toHaveBeenCalledWith("agent-1", "company-1");
});
it("checks unsaved changes before leaving to finish setup", async () => {
const onBeforeNavigate = vi.fn(() => false);
render(makeAgent({ status: "paused", lifecycleState: "paused", pauseReason: "setup" }), { hasPendingNavigationChanges: true, onBeforeNavigate });
await flushReact();
await act(() => [...container.querySelectorAll("button")].find(button => button.textContent === "Finish setup")!.click());
expect(onBeforeNavigate).toHaveBeenCalledOnce();
expect(mockNavigate).not.toHaveBeenCalled();
expect(mockAgentsApi.invoke).not.toHaveBeenCalled();
});
it("keeps setup available when the caller hides Run or blocks work", async () => {
render(makeAgent({ status: "paused", lifecycleState: "paused", pauseReason: "setup" }), { showRun: false, workActionsDisabled: true });
await flushReact();
expect([...container.querySelectorAll("button")].find(button => button.textContent === "Finish setup")!.disabled).toBe(false);
});
it("offers Run after setup completes without turning a manual pause into setup", async () => {
render(makeAgent({ status: "paused", lifecycleState: "paused", pauseReason: "setup" }));
await flushReact();
render(makeAgent({ status: "paused", lifecycleState: "paused", pauseReason: "manual" }));
await flushReact();
expect(container.textContent).toContain("Resume");
expect(container.textContent).not.toContain("Finish setup");
render(makeAgent({ status: "idle", lifecycleState: "ready", pauseReason: null }));
await flushReact();
const run = [...container.querySelectorAll("button")].find(button => button.textContent === "Run Heartbeat");
expect(run?.disabled).toBe(false);
await act(() => run!.click());
await flushReact();
expect(mockAgentsApi.invoke).toHaveBeenCalledWith("agent-1", "company-1");
});
it.each(["preparing", "verifying", "resuming"] as const)("offers pause rather than resume during %s", async lifecycleState => {
render(makeAgent({ status: "paused", lifecycleState }));
await flushReact();
const buttons = Array.from(container.querySelectorAll("button"));
expect(buttons.some(button => button.textContent === "Resume")).toBe(false);
const pause = buttons.find(button => button.textContent === "Pause")!;
expect(pause.disabled).toBe(false);
await act(async () => pause.click());
await flushReact();
expect(mockAgentsApi.pause).toHaveBeenCalledWith("agent-1", "company-1");
});
it.each(["pausing", "terminating", "cleaning_up", "terminated", "rejected"] as const)("disables pause and resume during %s", async lifecycleState => {
render(makeAgent({ status: lifecycleState === "pausing" ? "paused" : "terminated", lifecycleState }));
await flushReact();
const buttons = Array.from(container.querySelectorAll("button"));
expect(buttons.find(button => button.textContent === "Pause")!.disabled).toBe(true);
if (lifecycleState !== "pausing") {
expect(buttons.find(button => button.textContent === "Run Heartbeat")!.disabled).toBe(true);
expect(buttons.find(button => button.textContent === "Assign Task")!.disabled).toBe(true);
}
});
it("replaces the pause slot with Clear error for error agents", async () => {
render(makeAgent({ status: "error" }));
await flushReact();
expect(container.textContent).toContain("Clear error");
expect(container.textContent).not.toContain("Pause");
expect(container.textContent).toContain("Run Heartbeat");
await act(async () => {
container.querySelector<HTMLButtonElement>('[aria-label="Open actions for Alpha Agent"]')?.click();
});
await flushReact();
expect(document.body.textContent).toContain("Reset Sessions");
});
it("calls clearError and refreshes agent-related queries", async () => {
render(makeAgent({ status: "error" }));
await flushReact();
await act(async () => {
container.querySelector<HTMLButtonElement>('[aria-label="Clear error and return agent to idle"]')?.click();
});
await flushReact();
expect(mockAgentsApi.clearError).toHaveBeenCalledWith("agent-1", "company-1");
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "detail", "agent-1"] });
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "detail", "alpha"] });
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "runtime-state", "agent-1"] });
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "task-sessions", "agent-1"] });
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "company-1"] });
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["live-runs", "company-1"] });
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["heartbeats", "company-1", "agent-1"] });
});
it("keeps the normal pause action for non-error agents", async () => {
render(makeAgent({ status: "active" }));
await flushReact();
expect(container.textContent).toContain("Pause");
expect(container.textContent).not.toContain("Clear error");
});
it.each([false, true])("keeps the normal run action when persistent tracing is %s", async tracingEnabled => {
render(makeAgent({ runtimeConfig: tracingEnabled ? { debug: { providerTrace: "raw" } } : {} }));
await flushReact();
const buttons = Array.from(container.querySelectorAll("button"));
expect(buttons.some(button => button.textContent?.includes("Run with provider trace"))).toBe(false);
expect(container.textContent?.includes("Raw tracing on")).toBe(tracingEnabled);
await act(async () => {
buttons.find(button => button.textContent === "Run Heartbeat")!.click();
});
await flushReact();
expect(mockAgentsApi.invoke).toHaveBeenCalledExactlyOnceWith("agent-1", "company-1");
expect(mockNavigate).toHaveBeenCalledWith("/agents/alpha/runs/run-1");
});
it.each(["terminating", "cleaning_up"] as const)("keeps the detail page open during %s", async lifecycleState => {
mockAgentsApi.terminate.mockResolvedValue(makeAgent({ status: "terminated", lifecycleState }));
const onTerminateSuccess = vi.fn();
render(makeAgent(), { onTerminateSuccess });
await flushReact();
await act(async () => { container.querySelector<HTMLButtonElement>('[aria-label="Open actions for Alpha Agent"]')!.click(); });
await flushReact();
await act(async () => { Array.from(document.body.querySelectorAll("button")).find(button => button.textContent?.includes("Terminate"))!.click(); });
await flushReact();
expect(mockAgentsApi.terminate).toHaveBeenCalledWith("agent-1", "company-1");
expect(onTerminateSuccess).not.toHaveBeenCalled();
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "detail", "agent-1"] });
});
it("calls the terminate success handler after terminating an agent", async () => {
const onTerminateSuccess = vi.fn();
render(makeAgent(), { onTerminateSuccess });
await flushReact();
await act(async () => {
container.querySelector<HTMLButtonElement>('[aria-label="Open actions for Alpha Agent"]')?.click();
});
await flushReact();
const terminateButton = Array.from(document.body.querySelectorAll("button"))
.find((button) => button.textContent?.includes("Terminate"));
expect(terminateButton).toBeTruthy();
await act(async () => {
terminateButton?.click();
});
await flushReact();
expect(mockAgentsApi.terminate).toHaveBeenCalledWith("agent-1", "company-1");
expect(onTerminateSuccess).toHaveBeenCalledWith(expect.objectContaining({
id: "agent-1",
status: "terminated",
}));
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "detail", "agent-1"] });
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "detail", "alpha"] });
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "company-1"] });
});
it("does not terminate when navigation away from a dirty detail page is rejected", async () => {
const onBeforeNavigate = vi.fn().mockReturnValue(false);
render(makeAgent(), { onBeforeNavigate, onTerminateSuccess: vi.fn() });
await flushReact();
await act(async () => {
container.querySelector<HTMLButtonElement>('[aria-label="Open actions for Alpha Agent"]')?.click();
});
await flushReact();
const terminateButton = Array.from(document.body.querySelectorAll("button"))
.find((button) => button.textContent?.includes("Terminate"));
await act(async () => {
terminateButton?.click();
});
await flushReact();
expect(onBeforeNavigate).toHaveBeenCalledOnce();
expect(mockAgentsApi.terminate).not.toHaveBeenCalled();
});
it("rechecks navigation when the form becomes dirty while termination is pending", async () => {
let resolveTermination!: (agent: Agent) => void;
mockAgentsApi.terminate.mockReturnValue(new Promise((resolve) => {
resolveTermination = resolve;
}));
const onBeforeNavigate = vi.fn().mockReturnValueOnce(true).mockReturnValue(false);
const onTerminateSuccess = vi.fn();
const agent = makeAgent();
render(agent, {
hasPendingNavigationChanges: false,
onBeforeNavigate,
onTerminateSuccess,
});
await flushReact();
await act(async () => {
container.querySelector<HTMLButtonElement>('[aria-label="Open actions for Alpha Agent"]')?.click();
});
await flushReact();
const terminateButton = Array.from(document.body.querySelectorAll("button"))
.find((button) => button.textContent?.includes("Terminate"));
await act(async () => {
terminateButton?.click();
});
await flushReact();
render(agent, {
hasPendingNavigationChanges: true,
onBeforeNavigate,
onTerminateSuccess,
});
await flushReact();
resolveTermination(makeAgent({ status: "terminated" }));
await flushReact();
expect(onBeforeNavigate).toHaveBeenCalledTimes(2);
expect(onTerminateSuccess).not.toHaveBeenCalled();
});
});