mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-09 07:10:34 +01:00
## Thinking Path > - Paperclip lets people manage agent work through the board. > - The board reads task, agent, settings, plugin, and run data from the server. > - A deploy can interrupt those reads after content is already visible. > - Local error branches can replace that content with an error or show raw codes. > - This pull request moves the remaining reads to the shared recovery behavior. > - The query-error guard prevents new local error patterns from returning. ## Linked Issues or Issue Description **What happened?** Loaded lists, settings, task panels, and manual reads could clear their content or show errors during a server restart. Some reads also disabled the shared retry policy. **Expected behavior** Keep loaded content during a temporary failure. Show the shared connection banner. Retry reads after recovery. Replace content after a real access denial or missing resource, with readable copy. **Steps to reproduce** Open a task, settings page, or run log. Return 503 with `tenant_app_unavailable` from the API. Restore the API and check that content refreshes. Repeat with 403 and 404 to check the failure state. Related merged work: Refs #15754, Refs #15772, Refs #17960. This change covers remaining reads and enforcement. Browser persistence and the outage browser suite follow separately. ## What Changed - Repair an existing PostgreSQL deadline fixture at UTC boundaries. A daily cap defers a heartbeat until both its original interval and the next UTC day allow it. Keep the counted run in its seeded day and cover noon, just before midnight and the first second after midnight with explicit clocks and real PostgreSQL. Production scheduling is unchanged. - Integrate the saved list, settings, shell, task, and manual-read recovery changes against current master. Preserve the current task, Inbox, and run-log structure. - Add `useResilientFetch` for component-local reads. Preserve loaded data, cancel stale requests, and retry through the shared connectivity policy. Keep browser and pairing capabilities in memory. - Retain run log chunks across stream changes and catch up after recovery without duplicate chunks or stalled requests. - Keep genuine authorization and missing-resource failures visible. Translate known single-word codes such as `forbidden`. Show known skills and disconnected-app failures before sibling loading states. Keep Retry bound to its failed request. - Make the query-error guard enforce by default and run it in the CI policy job. Document the narrow exceptions and the read recovery contract. - Invalidate pending OAuth discovery when the operator leaves setup or its context changes. Keep reserved-popup cleanup bound to the current attempt. ## Verification - Current read head `09d1db29dea` is merge-ready: all 59 check runs are completed (54 successful, three skipped, two neutral), the legacy Snyk status is successful, and both required `ci / verify` and `ci / e2e` gates pass. Greptile Apex reviewed this exact head at 5/5 with no unresolved threads; the branch has no merge conflicts. The current CI run is `41748339602`. - Current read head `09d1db29dea` includes master `683fa4725e9`. The latest change touches only the existing server deadline test fixture. Application source remains the previously verified `86376fa751e` revision: all 60 affected skills/disconnected-app tests and both application UI typechecks passed, along with token gates and the enforcing query-error guard. Those UI suites were not repeated for this test-only repair. - The fixture repair passes all seven deadline integration cases and the complete server typecheck, including the server test layer. The old assertion deterministically fails at 23:59:06.888 UTC; its one-second-old run also fails the first-second-of-day probe. The corrected fixture passes noon and both midnight probes. The permanent three-case coverage uses seeded 2099 clocks. - Twelve new regressions fail against the previous implementation. Both skills variants and disconnected-app pages show either request's 403 or 429 while the sibling pauses or remains fetching. Permission failures stay visible. Retry stays usable for its failed request and recovers independently. An initial test-fixture query-key typo was corrected before the passing run. The finding is replied to and resolved. Greptile reviewed prior application revision `86376fa751e` at 5/5 with no new actionable findings or unresolved threads. The current test-only head has now received its own Apex 5/5 review with no unresolved threads, and its CI is successful as recorded above. - The preceding OAuth fix passed all 237 setup tests on both application branches. Its ten regressions prove that Back, Cancel, unmount, or context changes retire initial discovery without creating a connection, caching old identities, navigating an abandoned popup, or closing a newer attempt. - Earlier master integration `e992f770339` passed all 309 tests across eight affected Slack, recovery, retry, submission and task files, plus UI typecheck, token gates, enforcing query-error scan and seven guard tests. The integration preserves Slack workspace reconnect and shared recovery, readable execution errors, source-inspection company scoping, and current submission behavior. Newly inherited retained-file recovery controls keep cached data through transient failures and hide it after definitive denial. - The preceding cache head `97c0bc3966f` passed 1,038 focused cache/write/editor/account/task/API tests. All 22 built-UI outage/write/loading cases passed in 4.7 minutes on exact browser head `b7deaaee5da`, with strict checking of all three specs. The latest skills/app rendering fix is covered by its affected component suites; those broader cases were not repeated for this separate read path. - Historical broader UI, CLI and build results and unresolved aggregate server/DB/adapter failures remain in the PR discussion. Interrupted CI runs were audited and recorded separately; they are not counted as passes. Controlled local outages do not prove hosted authentication or a real Cloud restart/deploy. Real hosted acceptance remains required after merge and deployment. Commands for the latest fix: ```sh pnpm --filter @paperclipai/ui exec vitest run src/pages/CompanySkills.test.tsx src/pages/apps/AppNotConnected.test.tsx pnpm --filter @paperclipai/ui typecheck pnpm check:token-gates node scripts/check-query-error-rendering.mjs --enforce --summary ``` ## Risks This migration touches many read surfaces. The main risks are initial loading, request cancellation, retained authorization state, and run-log paging. The tests cover those states. There are no server, schema, dependency, or API contract changes. The follow-up browser suite and hosted deploy acceptance are required before release acceptance. Recovered commits retain their original authors. If squash-merging, preserve `Co-Authored-By: Bender (Fable) <bender@agents.paperclip.ing>` and the Paperclip trailer. ## Model Used OpenAI `gpt-6.1-sol` through Codex, with xhigh reasoning effort, tool use, and code execution. The context window size is not exposed. Saved source commits keep their original authorship. ## 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 described the issue in-PR following the bug report template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal ticket id - [x] The affected local tests pass; broader limitations are recorded above - [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 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: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Paperclip <noreply@paperclip.ing> Co-authored-by: Bender (Fable) <bender@agents.paperclip.ing> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
485 lines
21 KiB
TypeScript
485 lines
21 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,
|
|
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;
|
|
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 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");
|
|
};
|
|
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 [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 ? (
|
|
<AdapterLoginPanel
|
|
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} 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>
|
|
)}
|
|
{localEnvironment && 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" ? "Waiting for code"
|
|
: loginPhase === "connecting" ? "Connecting"
|
|
: `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) && (!authorizationUrl || loginPhase !== "ready")) ||
|
|
(method === "api" &&
|
|
!apiKey.trim() &&
|
|
!storedConnection &&
|
|
!selectedKey)
|
|
}
|
|
loading={busy}
|
|
primaryIcon={opened && needsLogin ? loginPhase === "ready" ? "none" : "spinner" : undefined}
|
|
onPrimary={() => {
|
|
if (needsLogin) {
|
|
if (!authorizationUrl || loginPhase !== "ready") return;
|
|
window.open(authorizationUrl, "_blank", "noreferrer,noopener");
|
|
setLoginPhase("waiting");
|
|
} else void connect();
|
|
}}
|
|
/>
|
|
</>}
|
|
</div>
|
|
);
|
|
}
|