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; aiConnection?: AiConnectionBinding; /** Kept in memory until the user finishes setup. */ credentials?: Record; 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; 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 health = useQuery({ queryKey: queryKeys.health, queryFn: healthApi.get, enabled: localEnvironment }); // Read health through the shared view: a transient failure keeps the saved // local-login path usable,anda no-data failure shows readable copy. const healthView = useQueryView(health); const canUseLocalLogin = localEnvironment && (health.data?.localAiLoginSupported ?? health.data?.deploymentMode === "local_trusted"); 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(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(null); const [storedConnection, setStoredConnection] = useState(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(null); const savedSubscription = savedKeys.subscriptions.length ? savedKeys.subscriptions.find( (option) => option.id === (subscriptionId ?? savedKeys.subscriptions[0]?.id), ) : undefined; const [selectedKeyId, setSelectedKeyId] = useState(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 (
, credentialMode: "subscription" }, { id: "api", label: provider, icon: , credentialMode: "api" }, { id: "advanced", label: "Advanced", icon: , credentialMode: "advanced" }, ] : [ { id: adapterType, label: provider, icon: , }, ]} 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 && (
)} {advanced && advancedConnection ? <>
{advancedConnection.content}
{ if (advancedConnection.value) onConnected({ env: {}, aiConnection: advancedConnection.value }); }} /> : <> {!opened && savedKeys.options.length > 0 && (

{savedKeys.options.length} saved API{" "} {savedKeys.options.length === 1 ? "key available" : "keys available"}.

)} {method === "subscription" && savedKeys.subscriptions.length > 0 && (
{ onDraftChanged?.(); setSubscriptionId(id); }} loading={false} error={false} kind="subscription" disabled={busy} />
)} {opened && (
{method === "api" ? ( { onDraftChanged?.(); setSelectedKeyId(id); setApiKey(""); setStoredConnection(null); setError(null); }} /> {!selectedKey && ( { onDraftChanged?.(); setSelectedKeyId(""); setApiKey(value); setStoredConnection(null); }} onSubmit={() => void connect()} disabled={busy} /> )} ) : needsLogin ? !awaitingLoginRequest && ( {}} 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 ? ( { setError(null); localLogin.retry(); } }} /> ) : (

{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."}

)}
)}
{!managedAccount && method === "subscription" && storedLoginView.kind === "error" && (

Could not check your saved Claude subscription. Try again.

)} {error && (

{testError ?? error}

)} {localEnvironment && healthView.kind === "error" && (

Could not prepare sign-in. Reload this page to try again.

)} { 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) || (localEnvironment && 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(); }} /> }
); }