Files
PaperClipAI/ui/src/components/new-agent/AgentProviderConnection.tsx
T
DottaandPaperclip 57bd302c81 feat(antigravity): add hosted Google loopback-relay sign-in (#22932)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Google Antigravity supports Google account sign-in through Paperclip
Runner's pinned, isolated `agy_acp_server.par` process.
> - On `authenticated + public` deployments (including hosted Cloud
instances), `supportsLocalAiLogin` returns `false`, and the user's
browser cannot directly reach the server's `127.0.0.1:<ephemeral_port>`
loopback callback listener.
> - Because `client_secret` lives only inside `agy_acp_server.par` and
uses PKCE with a one-shot `127.0.0.1` listener, hosted deployments need
an authenticated relay path instead of an anonymous callback route or
extracted secret.
> - This pull request adds an authenticated loopback-relay flow across
Runner, server policy/routes/redaction, and the UI so users on hosted
deployments can sign in with Google, copy the `127.0.0.1` redirect URL
from their address bar, and paste it to complete authentication.
> - The benefit is that Google Antigravity subscription sign-in works on
hosted public deployments while keeping Claude, OpenAI, and Grok
server-host login disabled and preventing SSRF, secret leakage, or
cross-tenant access.

## Linked Issues or Issue Description

Refs #22923

**Subsystem affected**
Cross-cutting (packages/paperclip-runner, packages/shared, server/, ui/)

**Problem or motivation**
Google Antigravity sign-in launches Paperclip's pinned, isolated
`agy_acp_server.par` closure, which opens a one-shot
`127.0.0.1:<ephemeral_port>` OAuth callback listener. On hosted
`authenticated + public` deployments, server-host login routes are
blocked and the user's browser cannot connect to the server's loopback
interface, so users cannot sign in with a Google account on Cloud or
remote instances.

**Proposed solution**
Add an authenticated loopback-relay flow:
1. Runner exposes a single-use `submitRedirect(rawRedirectUrl)` handler
on `AntigravityBrowserLoginState` that validates the pasted URL (length,
printable ASCII, `http://127.0.0.1:<expectedPort>/`, no
credentials/hash, no duplicate `state`/`code`, no `error` param,
`timingSafeEqual` state check, bounded 5-attempt bad-paste cap, SHA-256
reused-code tracking) and issues an SSRF-proof reconstructed `GET` to
`expectedRedirect.origin` with `redirect: "manual"`.
2. Server adds `supportsHostedGoogleAiLogin` (exposed on `/api/health`
as `hostedGoogleAiLoginSupported`), permits Google through the
authenticated `/api/companies/:companyId/ai-connections/local/*` routes
while keeping `anthropic`/`openai`/`xai` blocked on public deployments,
accepts up to 4096-character redirect URLs on `/code` while preserving
Claude's 512-byte limit, runs the loopback relay outside DB
transactions, falls back cleanly when a stack has no active `local`
environment row, and redacts `browserCode`/`redirectUrl` and marks
`/code` secret-sensitive.
3. UI enables Google sign-in for `antigravity_runtime` on non-local
environments when `hostedGoogleAiLoginSupported` is true, renders the
external Google sign-in link plus plain-language `127.0.0.1` copy/paste
instructions with analytics masking/no-capture markers, and triggers an
immediate status check after submission.

**Alternatives considered**
- Adding an anonymous public OAuth callback route on the server:
rejected because it widens the unauthenticated attack surface and cannot
change the loopback `redirect_uri` bound inside `agy_acp_server.par`.
- Extracting Google OAuth `client_secret` out of `agy_acp_server.par`:
rejected by policy; secrets remain owned solely inside the pinned
closure.

## What Changed

- `packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts` &
`packages/paperclip-runner/src/index.ts` &
`server/src/vendor/paperclip-runner/index.ts`: add single-use
`submitRedirect` on `AntigravityBrowserLoginState` with strict
validation, `timingSafeEqual` state verification, 5-attempt cap, bounded
SHA-256 reused-code set, and SSRF-proof loopback relay.
- `packages/shared/src/ai-connections.ts`: add
`LOCAL_AI_LOGIN_CODE_MAX_LENGTH` (4096), `localAiLoginCodeSchema`, and
`submitLocalAiLoginCodeSchema` while preserving Claude's 512-byte
`BROWSER_CODE_MAX_LENGTH` and `browserCodeSchema`.
- `server/src/services/local-ai-login-policy.ts` &
`server/src/routes/health.ts`: add `supportsHostedGoogleAiLogin` and
expose `hostedGoogleAiLoginSupported` on `/api/health`.
- `server/src/services/local-ai-browser-login.ts`,
`server/src/services/local-ai-login.ts`,
`server/src/routes/ai-connections.ts`: permit hosted Google sign-in on
authenticated public deployments while keeping Claude/OpenAI/Grok
blocked; enforce `Cache-Control: no-store`, owner/company/active/expiry
checks, and Claude's 512-byte cap; run Google `submitRedirect` outside
any DB transaction; fall back cleanly to an active environment or
savepoint-wrapped `ensureLocalEnvironment` when no active `local`
environment row exists.
- `server/src/middleware/redact-sensitive.ts`,
`server/src/middleware/http-log-redaction.ts`,
`server/src/middleware/http-log-policy.ts`: redact
`browserCode`/`redirectUrl`/`redirect_url` unconditionally and classify
`/api/companies/:companyId/ai-connections/local/attempts/:sessionId/code`
as secret-sensitive (`local_ai_login_code`).
- `ui/src/api/health.ts`,
`ui/src/components/ai-connections/useLocalAiLogin.ts`,
`ui/src/components/AdapterLoginChrome.tsx`,
`ui/src/components/new-agent/AgentProviderConnection.tsx`,
`ui/src/components/ai-connections/AiConnectionCredentialStep.tsx`,
`ui/src/components/OnboardingWizard.tsx`: enable hosted Google sign-in
for `antigravity_runtime` on hosted/non-local environments, render the
hosted `127.0.0.1` redirect paste flow with `ANALYTICS_MASK_CLASS` and
`ANALYTICS_NO_CAPTURE_CLASS`, preserve retryable paste errors inline,
and trigger immediate status re-check on submit.
- `tests/runner-e2e/source-sdk-public-inputs.json`: refreshed for the
updated `packages/shared/src/ai-connections.ts` schema.
- Unit, integration, and UI tests across `antigravity-auth.test.ts`,
`local-ai-login-policy.test.ts`, `health.test.ts`,
`health-dev-server-token.test.ts`, `redact-sensitive.test.ts`,
`http-log-policy.test.ts`, `antigravity-local-ai-login.test.ts`,
`ai-connections.test.ts`, `AdapterLoginChrome.test.tsx`,
`useLocalAiLogin.test.tsx`, and `AgentProviderConnection.test.tsx`.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter
@paperclipai/paperclip-runner typecheck && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — passed.
- `pnpm --filter @paperclipai/shared exec vitest run
src/validators/claude-setup-token-session.test.ts` — 15/15 passed.
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/drivers/acpx/antigravity-auth.test.ts
src/drivers/acpx/antigravity-auth-stream-order.test.ts` — 33/33 passed
(including real `127.0.0.1` loopback HTTP relay with fake ACP peer,
bad-paste cap, reused-code rejection, single-use, and non-200 failure).
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/local-ai-login-policy.test.ts src/__tests__/health.test.ts
src/__tests__/health-dev-server-token.test.ts
src/__tests__/redact-sensitive.test.ts
src/__tests__/http-log-policy.test.ts
src/__tests__/antigravity-local-ai-login.test.ts` — all passed.
- `pnpm --filter @paperclipai/server exec vitest run
src/__tests__/ai-connections.test.ts` — 167/167 passed against embedded
PostgreSQL (including hosted Google end-to-end route test, redaction of
activity and HTTP logs, and continued blocking of Anthropic/OpenAI/xAI
on hosted public deployments).
- `pnpm --filter @paperclipai/ui exec vitest run
src/components/AdapterLoginChrome.test.tsx
src/components/ai-connections/useLocalAiLogin.test.tsx
src/components/new-agent/AgentProviderConnection.test.tsx` — 30/30
passed.
- `pnpm verify --explain` returned exit 2
(`tests/runner-e2e/source-sdk-public-inputs.json` broad input); required
CI supplies full-repo coverage.
- Note: live end-to-end sign-in against real `agy_acp_server.par` and
Google OAuth on a live Cloud stack was not run in this unit/integration
environment and remains a live-staging verification step.

## Risks

- Low-to-moderate risk. All hosted Google sign-in endpoints stay
authenticated, company-scoped, owner-bound, and `Cache-Control:
no-store`; `localAiLoginSupported` remains `false` on `authenticated +
public` deployments so Claude, OpenAI, and Grok server-host login stay
blocked.
- Loopback relay runs strictly against the validated
`127.0.0.1:<ephemeral_port>` origin printed by `agy_acp_server.par` with
`redirect: "manual"` and a 5-second timeout, outside any database
transaction.
- No database migrations are required.

## Model Used

- Google Gemini (Antigravity agent with tool use and code execution)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-25 07:36:36 -06:00

510 lines
23 KiB
TypeScript

import { healthApi } from "@/api/health";
import { aiConnectionsApi } from "@/api/ai-connections";
import { useLocalAiLogin } from "../ai-connections/useLocalAiLogin";
import type { AiConnectionBinding, AiConnectionLoginIntent } from "@paperclipai/shared";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { Cable } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { motion } from "motion/react";
import {
SavedProviderKeySelect,
useSavedProviderKeys,
} from "../onboarding/SavedProviderKeySelect";
import { agentsApi } from "@/api/agents";
import { queryKeys } from "@/lib/queryKeys";
import { AdapterLoginPanel } from "../AgentConfigForm";
import { AdapterMark } from "./AgentBasicsDialog";
import {
LocalProviderLoginInstructions,
OnboardingCardField,
OnboardingLoginCard,
} from "../AdapterLoginChrome";
import { ModelSourceTiles, type ModelConnectionMode } from "../onboarding/ModelSourceTiles";
import { useQueryView } from "../QueryView";
import { CredentialModeLink } from "../onboarding/CredentialModeLink";
import { FooterNav } from "../onboarding/FooterNav";
import { MAKE_ROOM, CARD_ENTER } from "../onboarding/onboarding-motion";
import { buildFixedClaudeOAuthBinding } from "../environment-variables-editor/model";
import type { EnvBinding } from "@paperclipai/shared";
export type ProviderConnection = {
env: Record<string, EnvBinding>;
aiConnection?: AiConnectionBinding;
/** Kept in memory until the user finishes setup. */
credentials?: Record<string, string>;
storedSessionId?: string;
applyStoredClaudeLogin?: boolean;
};
export function AgentProviderConnection({
companyId,
adapterType,
environmentId,
canLogin,
requiresAgent = false,
agentId,
localEnvironment = false,
onConnected,
onDraftChanged,
onBack,
testConnection,
testError,
managedAccount,
advancedConnection,
}: {
companyId: string;
adapterType: "claude_local" | "codex_local" | "grok_local" | "antigravity_runtime";
environmentId: string | null;
canLogin: boolean;
requiresAgent?: boolean;
agentId?: string;
localEnvironment?: boolean;
onConnected: (connection: ProviderConnection) => void;
onDraftChanged?: () => void;
onBack: () => void;
testConnection: (connection: ProviderConnection) => Promise<boolean>;
testError?: string | null;
advancedConnection?: { content: ReactNode; value?: AiConnectionBinding };
/** Connections supplies its access intent; presentation and login controllers stay shared. */
managedAccount?: {
intent: AiConnectionLoginIntent;
nameForMethod?: (method: "subscription" | "api_key") => string;
initialMethod?: "subscription" | "api_key";
fixedMethod?: boolean;
disabled?: boolean;
onComplete: (result: { connectionId: string; grantId: string; method: "subscription" | "api_key" }) => void;
};
}) {
const needsHealth = localEnvironment || adapterType === "antigravity_runtime";
const health = useQuery({ queryKey: queryKeys.health, queryFn: healthApi.get, enabled: needsHealth });
// Read health through the shared view: a transient failure keeps the saved
// local-login path usable, and a no-data failure shows readable copy.
const healthView = useQueryView(health);
const localAiLoginSupported = Boolean(health.data?.localAiLoginSupported ?? health.data?.deploymentMode === "local_trusted");
const hostedGoogleAiLoginSupported = Boolean(health.data?.hostedGoogleAiLoginSupported);
const canUseLocalLogin = adapterType === "antigravity_runtime"
? (hostedGoogleAiLoginSupported || (localEnvironment && localAiLoginSupported))
: (localEnvironment && localAiLoginSupported);
// Keep the loopback redirect paste option available whenever relay sign-in is
// supported, including private/trusted-host servers where `localAiLoginSupported`
// is true but the user's browser may be on another machine.
const googleHostedRedirect: boolean | "optional" = adapterType === "antigravity_runtime" && hostedGoogleAiLoginSupported
? (localAiLoginSupported ? "optional" : true)
: false;
const epoch = useRef(0);
useEffect(
() => () => {
epoch.current++;
},
[],
);
const cancel = () => {
epoch.current++;
setBusy(false);
setOpened(false);
setAuthorizationUrl(null);
setLoginPhase("preparing");
setLoginRequested(false);
};
const [methodChoice, setMethod] = useState<"subscription" | "api" | null>(managedAccount?.initialMethod === "api_key" ? "api" : managedAccount ? "subscription" : null);
const [advanced, setAdvanced] = useState(false);
// Connections already selected the provider before showing this step.
const [opened, setOpened] = useState(Boolean(advancedConnection || managedAccount));
const [loginRequested, setLoginRequested] = useState(false);
const automaticComputer = requiresAgent && !agentId;
const awaitingLoginRequest = automaticComputer && !loginRequested;
const [authorizationUrl, setAuthorizationUrl] = useState<string | null>(null);
const [loginPhase, setLoginPhase] = useState<"preparing" | "ready" | "waiting" | "connecting">("preparing");
const phaseBeforeSubmit = useRef<"ready" | "waiting">("ready");
const [apiKey, setApiKey] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [storedConnection, setStoredConnection] =
useState<ProviderConnection | null>(null);
const provider = adapterType === "antigravity_runtime" ? "Google" : adapterType === "claude_local" ? "Claude" : adapterType === "grok_local" ? "Grok" : "OpenAI";
const envKey =
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.
const savedKeys = managedAccount
? { ...availableKeys, options: [], subscriptions: [], loading: false }
: availableKeys;
const [subscriptionId, setSubscriptionId] = useState<string | null>(null);
const savedSubscription =
savedKeys.subscriptions.length
? savedKeys.subscriptions.find(
(option) =>
option.id === (subscriptionId ?? savedKeys.subscriptions[0]?.id),
)
: undefined;
const [selectedKeyId, setSelectedKeyId] = useState<string | null>(null);
const selectedKey = savedKeys.options.find(
(option) => option.id === (selectedKeyId ?? savedKeys.options[0]?.id),
);
const storedLogin = managedAccount
? { ...savedKeys.storedLogin, data: undefined, isPending: false, isError: false }
: savedKeys.storedLogin;
// Read the saved-login status through the shared view: cached results stay
// visible during a transient refetch failure,and a no-data failure shows copy.
const storedLoginView = useQueryView(storedLogin);
const savedManagedAccount = useRef<{ connectionId: string; grantId: string } | null>(null);
const method = methodChoice ?? (
(savedKeys.subscriptions.length > 0 || (adapterType === "claude_local" && !savedSubscription && storedLogin.data))
? "subscription" : savedKeys.options.length ? "api" : "subscription"
);
const authMethod = method === "api" ? "api_key" : "subscription";
// Reconnect preserves an account's method. Choosing another method creates
// an account for the same provider; the task host selects it after sign-in.
const reconnecting = managedAccount?.intent.connectionId && (
managedAccount.fixedMethod !== false || managedAccount.initialMethod === authMethod
);
const managedIntent: AiConnectionLoginIntent | undefined = managedAccount ? {
...managedAccount.intent,
connectionId: reconnecting ? managedAccount.intent.connectionId : undefined,
name: reconnecting
? managedAccount.intent.name
: managedAccount.nameForMethod?.(authMethod) ?? managedAccount.intent.name,
} : undefined;
const localLogin = useLocalAiLogin(companyId, managedIntent ?? {
provider: aiProvider, method: "subscription", name: `My ${provider} subscription`,
ownership: "personal", agentIds: [], allAgents: true,
}, !advanced && canUseLocalLogin && method === "subscription" && !savedSubscription && !storedLogin.data,
);
const auth = useQuery({
queryKey: queryKeys.agents.authSignal(
companyId,
adapterType,
environmentId,
),
queryFn: () =>
agentsApi.getAdapterAuthSignal(
companyId,
adapterType,
environmentId ?? undefined,
),
enabled: !managedAccount && !advanced && adapterType !== "antigravity_runtime",
});
async function connect() {
if (busy || managedAccount?.disabled) return;
const run = ++epoch.current;
setBusy(true);
setError(null);
try {
if (managedAccount && managedIntent) {
if (method === "subscription" && !canUseLocalLogin) return;
const result = savedManagedAccount.current ?? await (method === "api"
? aiConnectionsApi.create(companyId, { ...managedIntent, method: "api_key", apiKey: apiKey.trim() })
: localLogin.connect(managedIntent));
savedManagedAccount.current = result;
setApiKey("");
if (run === epoch.current) managedAccount.onComplete({ ...result, method: method === "api" ? "api_key" : "subscription" });
return;
}
let connection: ProviderConnection =
method === "api"
? selectedKey
? selectedKey.aiConnection ? { env: {}, aiConnection: selectedKey.aiConnection } : { env: { [envKey]: selectedKey.binding } }
: (storedConnection ?? {
env: {},
credentials: { [envKey]: apiKey.trim() },
})
: {
...(savedSubscription?.aiConnection ? { aiConnection: savedSubscription.aiConnection } : {}),
env: savedSubscription?.binding
? { CODEX_HOME: savedSubscription.binding }
: {},
...(adapterType === "claude_local" && !savedSubscription && storedLogin.data
? {
env: buildFixedClaudeOAuthBinding(),
applyStoredClaudeLogin: true,
}
: {}),
};
if (method === "subscription" && canUseLocalLogin && !savedSubscription && !storedLogin.data) {
savedManagedAccount.current ??= await localLogin.connect();
connection = { env: {}, aiConnection: { provider: aiProvider, method: "subscription", mode: "responsible_user" } };
}
if (connection.credentials) {
await aiConnectionsApi.create(companyId, { provider: aiProvider, method: "api_key", name: `My ${provider} API`, ownership: "personal", apiKey: connection.credentials[envKey], agentIds: [], allAgents: true });
connection = { env: {}, aiConnection: { provider: aiProvider, method: "api_key", mode: "responsible_user" } };
}
if (run !== epoch.current) return;
if (method === "api") {
setApiKey("");
if (!selectedKey) setStoredConnection(connection);
}
const connected = await testConnection(connection);
if (run !== epoch.current) return;
if (connected) onConnected(connection);
else
setError(
"The provider did not respond. Check the connection and try again.",
);
} catch (cause) {
if (run !== epoch.current) return;
if (managedAccount) setApiKey("");
setError(
cause instanceof Error
? cause.message
: "Could not connect to the provider.",
);
} finally {
if (run === epoch.current) setBusy(false);
}
}
const needsLogin =
method === "subscription" &&
canLogin && adapterType !== "antigravity_runtime" &&
environmentId &&
!savedSubscription &&
!savedKeys.loading &&
!storedLogin.data &&
(Boolean(managedAccount) || auth.data?.status !== "present" || subscriptionId === "");
const switchMode = (next: ModelConnectionMode) => {
if (advancedConnection && next === (advanced ? "advanced" : method)) return;
onDraftChanged?.();
cancel();
setAdvanced(next === "advanced");
setOpened(advancedConnection ? true : opened);
savedManagedAccount.current = null;
if (next !== "advanced") setMethod(next);
setApiKey("");
setStoredConnection(null);
setError(null);
};
return (
<div className="min-w-0 max-w-full">
<ModelSourceTiles
label={advancedConnection ? "Connection type" : "Connect your model provider"}
sources={advancedConnection ? [
{ id: "subscription", label: provider, icon: <AdapterMark type={adapterType} />, credentialMode: "subscription" },
{ id: "api", label: provider, icon: <AdapterMark type={adapterType} />, credentialMode: "api" },
{ id: "advanced", label: "Advanced", icon: <Cable className="size-6 text-muted-foreground" />, credentialMode: "advanced" },
] : [
{
id: adapterType,
label: provider,
icon: <AdapterMark type={adapterType} />,
},
]}
mode={advanced ? "advanced" : method}
selectedId={advancedConnection ? (advanced ? "advanced" : method) : opened ? adapterType : null}
collapsed={!advancedConnection && opened}
onSelect={id => {
if (managedAccount?.disabled) return;
if (advancedConnection) switchMode(id as ModelConnectionMode);
else setOpened(true);
}}
/>
{!advancedConnection && (!opened || managedAccount) && !managedAccount?.fixedMethod && (
<div className="-ml-3 mt-1">
<CredentialModeLink mode={method} onChange={switchMode} />
</div>
)}
{advanced && advancedConnection ? <>
<div className="pt-5">{advancedConnection.content}</div>
<FooterNav
onBack={onBack}
primaryLabel="Use connection"
primaryDisabled={!advancedConnection.value}
onPrimary={() => {
if (advancedConnection.value) onConnected({ env: {}, aiConnection: advancedConnection.value });
}}
/>
</> : <>
{!opened && savedKeys.options.length > 0 && (
<p className="mt-2 text-sm text-muted-foreground">
{savedKeys.options.length} saved API{" "}
{savedKeys.options.length === 1 ? "key available" : "keys available"}.
</p>
)}
{method === "subscription" &&
savedKeys.subscriptions.length > 0 && (
<div className={advancedConnection ? "pt-5" : undefined}>
<SavedProviderKeySelect
options={savedKeys.subscriptions}
value={savedSubscription?.id ?? ""}
onChange={(id) => { onDraftChanged?.(); setSubscriptionId(id); }}
loading={false}
error={false}
kind="subscription"
disabled={busy}
/>
</div>
)}
<motion.div
initial={false}
animate={{ height: opened ? "auto" : 0, opacity: opened ? 1 : 0 }}
transition={{ height: MAKE_ROOM, opacity: CARD_ENTER }}
className="overflow-hidden"
>
{opened && (
<div className="pt-5">
{method === "api" ? (
<OnboardingLoginCard
instruction={
savedKeys.options.length
? "Choose a saved API key or enter a new one"
: `Provide your ${provider} API key to connect`
}
>
<SavedProviderKeySelect
{...savedKeys}
value={selectedKey?.id ?? ""}
disabled={busy}
onChange={(id) => {
onDraftChanged?.();
setSelectedKeyId(id);
setApiKey("");
setStoredConnection(null);
setError(null);
}}
/>
{!selectedKey && (
<OnboardingCardField
label="API key"
masked
autoFocus
value={apiKey}
placeholder={
storedConnection
? "Key entered. Retry the connection."
: "Enter API key here"
}
onChange={(value) => {
onDraftChanged?.();
setSelectedKeyId("");
setApiKey(value);
setStoredConnection(null);
}}
onSubmit={() => void connect()}
disabled={busy}
/>
)}
</OnboardingLoginCard>
) : needsLogin ? !awaitingLoginRequest && (
<AdapterLoginPanel
requiresAgent={requiresAgent}
agentId={agentId}
companyId={companyId}
adapterType={adapterType}
environmentId={environmentId}
chrome="onboarding"
aiConnection={managedIntent ?? { provider: aiProvider, method: "subscription", name: `My ${provider} subscription`, ownership: "personal", agentIds: [], allAgents: true }}
autoStart
onStored={() => {}}
onPromptReady={(url) => {
setAuthorizationUrl(url);
setLoginPhase((phase) => url ? (phase === "preparing" ? "ready" : phase) : "preparing");
}}
onCodeSubmitted={() => {
phaseBeforeSubmit.current = loginPhase === "waiting" ? "waiting" : "ready";
setLoginPhase("connecting");
}}
onSubmitFailed={() => {
setLoginPhase((phase) => phase === "connecting" ? phaseBeforeSubmit.current : phase);
}}
onConnected={(sessionId) => {
if (managedAccount) {
if (!sessionId) { setError("The login did not return a saved connection. Try again."); return; }
const run = epoch.current;
setLoginPhase("connecting");
void aiConnectionsApi.loginResult(companyId, sessionId).then((result) => {
if (run === epoch.current) managedAccount.onComplete({ ...result, method: "subscription" });
}).catch(() => {
if (run !== epoch.current) return;
setLoginPhase("ready");
setError("Could not retrieve the saved connection. Go back and retry.");
});
return;
}
const connection: ProviderConnection = { env: {}, aiConnection: { provider: aiProvider, method: "subscription", mode: "responsible_user" } };
setStoredConnection(connection);
onConnected(connection);
}}
/>
) : savedSubscription ? null : canUseLocalLogin && !storedLogin.data ? (
<LocalProviderLoginInstructions adapterType={adapterType} hostedRedirect={googleHostedRedirect} login={{ ...localLogin, retry: () => { setError(null); localLogin.retry(); } }} />
) : (
<p className="text-sm text-muted-foreground">
{storedLogin.data
? "Use your saved Claude subscription for this agent."
: canLogin
? "Use the existing provider connection for this environment."
: "This environment does not support browser sign-in. Choose a sign-in environment or connect with an API key."}
</p>
)}
</div>
)}
</motion.div>
{!managedAccount && method === "subscription" && storedLoginView.kind === "error" && (
<p role="alert" className="mt-4 text-sm text-destructive">
Could not check your saved Claude subscription. Try again.
</p>
)}
{error && (
<p role="alert" className="mt-4 text-sm text-destructive">
{testError ?? error}
</p>
)}
{needsHealth && healthView.kind === "error" && (
<p role="alert" className="mt-4 text-sm text-destructive">Could not prepare sign-in. Reload this page to try again.</p>
)}
<FooterNav
onBack={() => {
if (opened && !advancedConnection) cancel();
else onBack();
}}
primaryLabel={
opened && needsLogin
? loginPhase === "waiting" ? adapterType === "codex_local" ? "Waiting for auth…" : "Waiting for code"
: loginPhase === "connecting" ? "Connecting"
: automaticComputer && authorizationUrl ? `Continue to ${provider}` : `Sign in to ${provider}`
: busy
? "Connecting"
: method === "subscription" &&
(storedLogin.data || savedSubscription)
? "Use saved subscription"
: method === "api" && selectedKey
? "Use saved API key"
: "Connect"
}
primaryDisabled={
managedAccount?.disabled ||
(Boolean(managedAccount) && method === "subscription" && !canLogin && !canUseLocalLogin) ||
(needsHealth && health.isPending) || localLogin.preparing || Boolean(localLogin.error) ||
(method === "subscription" && canUseLocalLogin && !savedSubscription && !storedLogin.data && localLogin.status !== "ready") ||
(!managedAccount && adapterType !== "antigravity_runtime" && auth.isPending) ||
savedKeys.loading ||
(adapterType === "claude_local" && storedLogin.isPending) ||
// The saved-subscription chooser renders outside the opened section,
// so reusing the visible choice must not wait for a tile click.
(!opened && !(method === "subscription" && savedSubscription)) ||
(Boolean(needsLogin) && !awaitingLoginRequest && (!authorizationUrl || loginPhase !== "ready")) ||
(method === "api" &&
!apiKey.trim() &&
!storedConnection &&
!selectedKey)
}
loading={busy}
primaryIcon={opened && needsLogin && !awaitingLoginRequest ? loginPhase === "ready" ? "none" : "spinner" : undefined}
onPrimary={() => {
if (needsLogin) {
if (awaitingLoginRequest) {
setLoginRequested(true);
return;
}
if (!authorizationUrl || loginPhase !== "ready") return;
window.open(authorizationUrl, "_blank", "noreferrer,noopener");
setLoginPhase("waiting");
} else void connect();
}}
/>
</>}
</div>
);
}