diff --git a/packages/adapters/claude-local/src/server/setup-token-parse.test.ts b/packages/adapters/claude-local/src/server/setup-token-parse.test.ts index 7837b192aa2..35008f48407 100644 --- a/packages/adapters/claude-local/src/server/setup-token-parse.test.ts +++ b/packages/adapters/claude-local/src/server/setup-token-parse.test.ts @@ -283,6 +283,20 @@ describe("parseSetupTokenPrompt", () => { expect(result?.url).toBe(shortCode); }); + it("accepts the claude 2.1.333+ opaque short authorization URL", () => { + const opaqueUrl = "https://claude.ai/oauth/authorize?IQ2RDWoHouqywHRo76dCv-ms1Qxya8PGzuNNvHH1OX8o"; + const result = parseSetupTokenPrompt(completeOutput(opaqueUrl)); + expect(result).not.toBeNull(); + expect(result?.url).toBe(opaqueUrl); + }); + + it("rejects opaque authorization URLs that are too short or contain an API key prefix", () => { + expect(parseSetupTokenPrompt(completeOutput("https://claude.ai/oauth/authorize?tooshort"))).toBeNull(); + expect( + parseSetupTokenPrompt(completeOutput("https://claude.ai/oauth/authorize?sk-ant-api03-1234567890abcdef1234567890")), + ).toBeNull(); + }); + it("returns null for an empty code value", () => { const emptyCode = CLAUDE_COM_URL.replace(`code=${CODE}`, "code="); expect(parseSetupTokenPrompt(completeOutput(emptyCode))).toBeNull(); diff --git a/packages/adapters/claude-local/src/server/setup-token-parse.ts b/packages/adapters/claude-local/src/server/setup-token-parse.ts index b52a472c11f..8b18c28b6cb 100644 --- a/packages/adapters/claude-local/src/server/setup-token-parse.ts +++ b/packages/adapters/claude-local/src/server/setup-token-parse.ts @@ -92,6 +92,10 @@ const CLIENT_ID_RE = /^[A-Za-z0-9._~-]{1,128}$/; const CODE_RE = /^[A-Za-z0-9._~-]{1,1024}$/; const CODE_CHALLENGE_RE = /^[A-Za-z0-9_-]{43,128}$/; const STATE_RE = /^[A-Za-z0-9_-]{16,256}$/; +// `claude` 2.1.333+ emits a short opaque OAuth request token as the entire +// query string (`https://claude.ai/oauth/authorize?`), with no `=` or +// `&` separators. +const OPAQUE_AUTH_QUERY_RE = /^[A-Za-z0-9_-]{24,128}$/; // One `scope` token. The `scope` value is one to eight space-separated tokens. const SCOPE_TOKEN_RE = /^[A-Za-z0-9:._-]{1,64}$/; @@ -278,6 +282,11 @@ function isValidRedirectUri(value: string): boolean { * characters. It rejects an API-key prefix in any decoded value. */ function hasValidQuery(parsed: URL): boolean { + const rawQuery = parsed.search.startsWith("?") ? parsed.search.slice(1) : ""; + if (OPAQUE_AUTH_QUERY_RE.test(rawQuery) && !API_KEY_RE.test(rawQuery)) { + return true; + } + // Collect the values of each key, so the parser can reject a duplicate key and // read the one decoded value of each key. const byKey = new Map(); diff --git a/packages/adapters/claude-local/src/server/setup-token-runner.test.ts b/packages/adapters/claude-local/src/server/setup-token-runner.test.ts index 1c5f267ce2c..1ef39677019 100644 --- a/packages/adapters/claude-local/src/server/setup-token-runner.test.ts +++ b/packages/adapters/claude-local/src/server/setup-token-runner.test.ts @@ -96,6 +96,37 @@ async function flush(): Promise { } describe("runSetupTokenLogin", () => { + it("accepts a code#state paste when the authorization URL uses the claude 2.1.333+ opaque query format", async () => { + const opaqueOutput = PROMPT_OUTPUT.replace( + VALID_URL, + "https://claude.ai/oauth/authorize?IQ2RDWoHouqywHRo76dCv-ms1Qxya8PGzuNNvHH1OX8o", + ); + const fake = createFakeDriver({ chunks: [opaqueOutput] }); + let stream!: (chunk: string) => void; + const start = fake.driver.start.bind(fake.driver); + fake.driver.start = (command, onData) => { stream = onData; return start(command, onData); }; + const write = fake.driver.write.bind(fake.driver); + fake.driver.write = input => { + write(input); + if (input === CODE_SUBMISSION_TERMINATOR) { + stream(SUCCESS_OUTPUT); + fake.resolveExit(0); + } + }; + const onCredential = vi.fn(async () => {}); + const pasted = `${BROWSER_CODE}#opaque-state-value`; + const result = await runSetupTokenLogin(fake.driver, { + onPrompt: () => {}, + provideCode: async () => pasted, + onCredential, + codeSubmitSettleMs: 0, + timeoutMs: 1000, + }); + expect(result).toMatchObject({ outcome: "success", codeSubmitted: true, credentialDelivered: true }); + expect(fake.writes).toContain(pasted); + expect(onCredential).toHaveBeenCalledOnce(); + }); + it("reports a rejected OAuth code immediately even while the CLI waits for Enter to retry", async () => { const fake = createFakeDriver({ chunks: [PROMPT_OUTPUT] }); let stream!: (chunk: string) => void; diff --git a/packages/adapters/claude-local/src/server/setup-token-runner.ts b/packages/adapters/claude-local/src/server/setup-token-runner.ts index ce8e8d43ec0..cf75442888d 100644 --- a/packages/adapters/claude-local/src/server/setup-token-runner.ts +++ b/packages/adapters/claude-local/src/server/setup-token-runner.ts @@ -264,7 +264,8 @@ export async function runSetupTokenLogin( } if (controller.signal.aborted) return; const separator = code.indexOf("#"); - if (separator !== -1 && code.slice(separator + 1) !== new URL(prompt.url).searchParams.get("state")) { + const expectedState = new URL(prompt.url).searchParams.get("state"); + if (separator !== -1 && expectedState !== null && code.slice(separator + 1) !== expectedState) { failureReason = "code_state_mismatch"; controller.abort(); return; diff --git a/server/src/services/device-login-service.ts b/server/src/services/device-login-service.ts index 401ca45af66..3c37ec802ea 100644 --- a/server/src/services/device-login-service.ts +++ b/server/src/services/device-login-service.ts @@ -56,8 +56,8 @@ import type { LoginPtyWorkerManagerLike } from "./setup-token-transport-binding. // The service keeps the one-time login prompt in memory and returns it only // through the owner read path. -/** The host timeout for the sandbox login command. It is exactly five minutes. */ -export const DEVICE_LOGIN_TIMEOUT_MS = 300_000; +/** The host timeout for the sandbox login command (15 minutes, matching provider device-code TTLs). */ +export const DEVICE_LOGIN_TIMEOUT_MS = 15 * 60_000; // The fixed error for a sandbox provider that does not advertise the login // pseudo-terminal capability. The Codex device login runs the login command on a diff --git a/server/src/services/local-ai-browser-login.ts b/server/src/services/local-ai-browser-login.ts index 77ce02bc114..845b783e20e 100644 --- a/server/src/services/local-ai-browser-login.ts +++ b/server/src/services/local-ai-browser-login.ts @@ -111,7 +111,7 @@ export function startLocalBrowserLogin(provider: "anthropic" | "openai" | "googl const codeReady = new Promise((resolve) => { deliverCode = resolve; }); state.submitCode = (code) => { deliverCode?.(code); deliverCode = undefined; }; void runSetupTokenLogin(driver, { - timeoutMs: 300_000, signal: controller.signal, + timeoutMs: 15 * 60_000, signal: controller.signal, onPrompt: (prompt) => { state.authorizationUrl = prompt.url; }, provideCode: (signal) => new Promise((resolve, reject) => { const abort = () => reject(new Error("Local sign-in cancelled")); @@ -141,7 +141,7 @@ export function startLocalBrowserLogin(provider: "anthropic" | "openai" | "googl .catch(() => { state.outcome = "failure"; }); } else { void runDeviceLogin(driver, { - timeoutMs: 300_000, signal: controller.signal, + timeoutMs: 15 * 60_000, signal: controller.signal, onPrompt: (prompt) => { state.authorizationUrl = prompt.url; state.code = prompt.code; }, }).then((result) => { state.outcome = result.outcome === "success" ? "success" : "failure"; }) .catch(() => { state.outcome = "failure"; }); diff --git a/server/src/services/setup-token-session.ts b/server/src/services/setup-token-session.ts index e1e4908cf8f..5cf26c9bf34 100644 --- a/server/src/services/setup-token-session.ts +++ b/server/src/services/setup-token-session.ts @@ -393,7 +393,7 @@ export const DEFAULT_SETUP_TOKEN_SESSION_CAPS: SetupTokenSessionCaps = { }; /** The default host timeout for one login session. */ -export const DEFAULT_SETUP_TOKEN_SESSION_TTL_MS = 5 * 60_000; +export const DEFAULT_SETUP_TOKEN_SESSION_TTL_MS = 15 * 60_000; /** * The default retention window for a completed token. The service releases the diff --git a/ui/src/components/AdapterLoginChrome.test.tsx b/ui/src/components/AdapterLoginChrome.test.tsx index 03a2d577928..175a9ed263d 100644 --- a/ui/src/components/AdapterLoginChrome.test.tsx +++ b/ui/src/components/AdapterLoginChrome.test.tsx @@ -14,6 +14,7 @@ import { OnboardingLoginCodeRow, onboardingCardInputClass, resolveLocalLoginPrimaryAction, + WAITING_HELP_DELAY_MS, } from "./AdapterLoginChrome"; import { isBlockedFromReplay, replayLeaks } from "@/lib/analytics/replay-recording.test-utils"; @@ -96,6 +97,10 @@ describe("the connect step's cards", () => { expect(container.textContent).toContain(waitingLabel); expect(container.querySelector("a")).toBeNull(); expect(container.querySelector("input")?.disabled).toBe(false); + const reopenButton = [...container.querySelectorAll("button")].find((b) => b.textContent === "Open sign-in link again"); + expect(reopenButton).toBeTruthy(); + flushSync(() => reopenButton!.click()); + expect(open).toHaveBeenCalledTimes(2); flushSync(() => root!.render(card("expired"))); expect(container.textContent).toContain("Your setup is saved."); const button = container.querySelector("button")!; @@ -123,6 +128,37 @@ describe("the connect step's cards", () => { } }); + it("shows a recovery action after waiting for WAITING_HELP_DELAY_MS", () => { + vi.useFakeTimers(); + const refresh = vi.fn(); + try { + render( + }> + {}} + onRefresh={refresh} + > + {null} + + , + ); + flushSync(() => container.querySelector("button")!.click()); + expect(container.textContent).not.toContain("Get a new link"); + flushSync(() => { + vi.advanceTimersByTime(WAITING_HELP_DELAY_MS); + }); + const retryButton = [...container.querySelectorAll("button")].find((b) => b.textContent === "Get a new link"); + expect(retryButton).toBeTruthy(); + flushSync(() => retryButton!.click()); + expect(refresh).toHaveBeenCalledOnce(); + } finally { + vi.useRealTimers(); + } + }); + it("gives every card field the same input, from one declaration", () => { // The step asks for three different things in this row — a browser code, a // key — and they sit one toggle apart in the same canvas, so a divergence @@ -393,6 +429,43 @@ describe("session replay", () => { expect(submitCode).toHaveBeenCalledWith("http://127.0.0.1:41234/?state=good&code=xyz"); }); + it("validates and normalizes pasted Claude codes in LocalProviderLoginInstructions", async () => { + const submitCode = vi.fn(async () => {}); + const container = await render( + , + ); + const input = container.querySelector('input[aria-label="Authorization code"]') as HTMLInputElement; + expect(input).not.toBeNull(); + + // Invalid input with spaces shows an inline alert without calling submitCode. + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "not a valid code"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + const submitButton = Array.from(container.querySelectorAll("button")).find(b => b.textContent === "Submit code") as HTMLButtonElement; + await act(async () => { submitButton.click(); }); + expect(submitCode).not.toHaveBeenCalled(); + expect(container.querySelector('[role="alert"]')?.textContent).toContain("doesn’t look like an authorization code"); + + // Pasting a full callback URL normalizes to code#state before submitting. + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call( + input, + "https://platform.claude.com/oauth/code/callback?code=abc123&state=xyz789", + ); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + await act(async () => { submitButton.click(); }); + expect(submitCode).toHaveBeenCalledWith("abc123#xyz789"); + }); + it("keeps the direct local Antigravity prompt without a paste field when hostedRedirect is false", async () => { const container = await render( void) | null>(null); export const OnboardingSignInMark = createContext(null); +/** Delay before showing a "Taking a while?" recovery action while waiting on OAuth. */ +export const WAITING_HELP_DELAY_MS = 60_000; + /** Shared authentication presentation. Hosts retain their existing session lifecycle. */ export function ProviderSubscriptionCard({ providerName, @@ -472,6 +479,7 @@ export function ProviderSubscriptionCard({ failure, failureMessage, onRetry, + onRefresh, children, }: { providerName: string; @@ -481,16 +489,34 @@ export function ProviderSubscriptionCard({ failure?: "expired" | "failed"; failureMessage?: string; onRetry?: () => void; + onRefresh?: () => void; mode: "submitted_code" | "displayed_code" | "browser_redirect" | "hosted_redirect"; loading?: boolean; children: ReactNode; }) { const mark = useContext(OnboardingSignInMark); const retry = useContext(OnboardingSignInRetry) ?? onRetry; + const refresh = onRefresh ?? retry; const [openedUrl, setOpenedUrl] = useState(null); + const [waitingLong, setWaitingLong] = useState(false); + const waiting = authorizationOpened || Boolean(openedUrl && openedUrl === authorizationUrl); useEffect(() => { if (loading || failure) setOpenedUrl(null); }, [loading, failure]); + useEffect(() => { + if (!waiting || loading || failure) { + setWaitingLong(false); + return; + } + const timer = window.setTimeout(() => setWaitingLong(true), WAITING_HELP_DELAY_MS); + return () => window.clearTimeout(timer); + }, [waiting, loading, failure, authorizationUrl]); + const openAuthorizationLink = () => { + if (!authorizationUrl) return; + setOpenedUrl(authorizationUrl); + if (onOpenAuthorization) onOpenAuthorization(); + else window.open(authorizationUrl, "_blank", "noopener,noreferrer"); + }; if (mark && failure) { return ( @@ -507,7 +533,6 @@ export function ProviderSubscriptionCard({ ); } if (mark && (mode === "submitted_code" || mode === "displayed_code")) { - const waiting = authorizationOpened || Boolean(openedUrl && openedUrl === authorizationUrl); const signInInstruction = `Sign into your ${providerName} account`; return ( 2. {mode === "submitted_code" ? "Return to this window and enter the authorization code." : "Enter the code below in the sign-in window."} }> -
- {waiting ? ( - - ) : } -
{children}
+
+
+ {waiting ? ( + + ) : } +
{children}
+
+ {waiting && authorizationUrl && ( +
+ + {waitingLong && refresh && ( + + Taking a while?{" "} + + + )} +
+ )}
); @@ -733,12 +778,21 @@ export function LocalProviderLoginInstructions({ adapterType, login, hostedRedir const optionalHostedGoogleRedirect = adapterType === "antigravity_runtime" && hostedRedirect === "optional"; async function submitBrowserCode(value = browserCode) { if (!value.trim() || !login?.submitCode || codeSubmissionRef.current) return; + let payload = value.trim(); + if (adapterType === "claude_local") { + const validationError = validateSubmittedBrowserCode(value); + if (validationError) { + setSubmitError(validationError); + return; + } + payload = normalizeSubmittedBrowserCode(value); + } const submission = Symbol(); codeSubmissionRef.current = submission; setSubmitting(true); setSubmitError(null); try { - await login.submitCode(value.trim()); + await login.submitCode(payload); if (codeSubmissionRef.current !== submission) return; setBrowserCode(""); setCodeSubmitted(true); @@ -796,16 +850,21 @@ export function LocalProviderLoginInstructions({ adapterType, login, hostedRedir authorizationUrl={safeAuthorizationUrl} authorizationOpened={authorizationOpened} onOpenAuthorization={onOpenAuthorization && (() => onOpenAuthorization(safeAuthorizationUrl))} + onRefresh={login?.retry} mode={hostedGoogleRedirect && !optionalHostedGoogleRedirect ? "hosted_redirect" : adapterType === "antigravity_runtime" ? "browser_redirect" : adapterType === "claude_local" ? "submitted_code" : "displayed_code"} > {adapterType === "claude_local" ?
{ + setSubmitError(null); + setBrowserCode(next); + }} onPaste={pasteBrowserCode} onSubmit={() => void submitBrowserCode()} disabled={submitting} /> + {submitError &&

{submitError}

} {!onboardingSignIn && }
: hostedGoogleRedirect ?

diff --git a/ui/src/components/AgentConfigForm.tsx b/ui/src/components/AgentConfigForm.tsx index b1a59498c3e..f88bc6b2e08 100644 --- a/ui/src/components/AgentConfigForm.tsx +++ b/ui/src/components/AgentConfigForm.tsx @@ -1,4 +1,9 @@ import { environmentLoginRequiresAgent, environmentSupportsLoginPty } from "@paperclipai/shared"; +import { + normalizeSubmittedBrowserCode, + validateSubmittedBrowserCode, +} from "@/lib/onboarding-login-helpers"; +import { useVisibilityLoginRecovery } from "@/lib/use-visibility-login-recovery"; import { matchesAdapterLoginTarget, useAdapterLoginCancellation } from "./useAdapterLoginCancellation"; import { QueryStateConflictError } from "@/lib/query-client"; import { ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS, antigravityModelGroup, isAccountBoundAcpxAgent } from "@/lib/native-model-catalog"; @@ -3261,6 +3266,18 @@ function DisplayedCodeLoginPanel({ return () => onRetryReadyRef.current?.(null); }, [retryReady]); + useVisibilityLoginRecovery({ + active: loginActive, + sessionActive: isActive, + sessionId, + autoRefreshOnExpiry: chrome === "onboarding", + expired: codeExpired || status === "timed_out", + canRetry: retryReady, + retrying: retrying || retryLogin.isPending, + onRefetch: () => statusQuery.refetch(), + onRetry: retryAction, + }); + useReportLoginFailureOnce( isReportableAdapterLoginFailure({ active: loginActive, @@ -3281,6 +3298,7 @@ function DisplayedCodeLoginPanel({ failure={failure} failureMessage={automaticComputer ? startError ?? undefined : undefined} onRetry={!onRetryReady && retryReady ? retryAction : undefined} + onRefresh={!retryLogin.isPending && !startLogin.isPending ? retryAction : undefined} providerName={connectSourceName(adapterType)} authorizationUrl={prompt?.url} onOpenAuthorization={onOpenAuthorization} @@ -3879,12 +3897,15 @@ function SubmittedBrowserCodeLoginPanel({ return () => clearTimeout(timer); }, [isActive, expiresAt, sessionId, releaseServerSession]); - const trimmedCode = browserCode.trim(); + const [codeValidationError, setCodeValidationError] = useState(null); + const [submittedAttemptFailed, setSubmittedAttemptFailed] = useState(false); + + const normalizedCode = normalizeSubmittedBrowserCode(browserCode); const canSubmit = isActive && Boolean(authorizationUrl) && !isCompleting && - isValidBrowserCode(trimmedCode) && + isValidBrowserCode(normalizedCode) && !submitCode.isPending && !codeSubmitted; @@ -3894,13 +3915,22 @@ function SubmittedBrowserCodeLoginPanel({ onSubmitFailedRef.current = onSubmitFailed; const handleSubmit = () => { - if (!canSubmit || codeSubmittedRef.current) return; + if (codeSubmittedRef.current) return; + if (!isValidBrowserCode(normalizedCode)) { + if (browserCode.trim().length > 0) { + setCodeValidationError(validateSubmittedBrowserCode(browserCode)); + } + return; + } + if (!canSubmit) return; codeSubmittedRef.current = true; + setCodeValidationError(null); + setSubmittedAttemptFailed(false); // A new attempt supersedes the last attempt's error, and has to: the // failure report below watches for an error after a submit, and one left // over from before it would end this attempt the moment it began. setStartError(null); - submitCode.mutate(trimmedCode); + submitCode.mutate(normalizedCode); // Reported now, not when the login finishes. A stored login is a poll and a // completion read away, long enough that a button still offering "Waiting // for code" after the paste read as the paste not having registered. @@ -3990,7 +4020,12 @@ function SubmittedBrowserCodeLoginPanel({ useEffect(() => { if (!autoSubmit || !pastedRef.current) return; pastedRef.current = false; - if (!canSubmit) return; + if (!canSubmit) { + if (browserCode.trim().length > 0) { + setCodeValidationError(validateSubmittedBrowserCode(browserCode)); + } + return; + } handleSubmitRef.current(); }, [autoSubmit, canSubmit, browserCode]); @@ -4016,6 +4051,7 @@ function SubmittedBrowserCodeLoginPanel({ if (!startError && !isFailure && !timedOut) return; setCodeSubmitted(false); codeSubmittedRef.current = false; + setSubmittedAttemptFailed(true); onSubmitFailedRef.current?.(); }, [codeSubmitted, startError, isFailure, timedOut]); @@ -4060,6 +4096,8 @@ function SubmittedBrowserCodeLoginPanel({ onMutate: () => { setStartError(null); setAuthorizationUrl(null); + setCodeValidationError(null); + setSubmittedAttemptFailed(false); }, onError: error => setStartError(describeError(error).body), onSettled: () => { @@ -4084,16 +4122,34 @@ function SubmittedBrowserCodeLoginPanel({ return () => onRetryReadyRef.current?.(null); }, [retryReady]); + useVisibilityLoginRecovery({ + active: loginActive, + sessionActive: isActive, + sessionId, + autoRefreshOnExpiry: chrome === "onboarding", + expired: timedOut || status === "timed_out", + canRetry: retryReady, + retrying: retrying || retryLogin.isPending, + onRefetch: () => statusQuery.refetch(), + onRetry: retryAction, + }); + if (chrome === "onboarding") { const failure = !retryLogin.isPending && onboardingFailed ? timedOut || status === "timed_out" ? "expired" : "failed" : undefined; + const onboardingFailureMessage = automaticComputer + ? startError ?? undefined + : submittedAttemptFailed && failure === "failed" + ? "That code wasn’t accepted. Copy the full code from Claude (including any # part) or retry sign-in." + : undefined; return ( )} {!failure && !retryLogin.isPending && ( - { - pastedRef.current = true; - }} - // Dots, not the code. It stays in the field after the paste so the - // customer can see something landed, and that is all they need to - // see of it. - masked - disabled={submitCode.isPending || isCompleting || codeSubmitted} - /> +

+ { + setCodeValidationError(null); + setBrowserCode(next); + }} + onSubmit={handleSubmit} + onPaste={() => { + pastedRef.current = true; + }} + // Dots, not the code. It stays in the field after the paste so the + // customer can see something landed, and that is all they need to + // see of it. + masked + disabled={submitCode.isPending || isCompleting || codeSubmitted} + /> + {codeValidationError && ( +

+ {codeValidationError} +

+ )} +
)} ); diff --git a/ui/src/components/OnboardingWizard.tsx b/ui/src/components/OnboardingWizard.tsx index 7a8b505b1d1..f02175af857 100644 --- a/ui/src/components/OnboardingWizard.tsx +++ b/ui/src/components/OnboardingWizard.tsx @@ -6,6 +6,8 @@ import { useQueryView } from "@/components/QueryView"; import type { AgentRunner, AgentRunnerChoice } from "@paperclipai/shared"; import { needsClaudeSetupQualification, qualifyClaudeSetup } from "../lib/qualify-claude-setup"; import { blocksAgentCreate, runOnboardingConnectionTest } from "../lib/onboarding-connection-test"; +import { normalizeApiKeyInput } from "../lib/onboarding-login-helpers"; +import { OnboardingApiKeyField } from "./onboarding/OnboardingApiKeyField"; import { agentComputerAwaitsHire, agentComputerHostsLogin, useAgentComputerLogin } from "../lib/agent-computer-login"; import { agentHarnessType, agentRunner } from "@paperclipai/shared"; import { adaptersApi, type AdapterInfo } from "../api/adapters"; @@ -627,6 +629,7 @@ function OnboardingWizardInner({ * `localStorage`, and a provider key does not belong there. */ const [apiKey, setApiKey] = useState(""); + const [apiKeyRejected, setApiKeyRejected] = useState(false); // The owner's stored Claude subscription login, read right before the hire // (see handleGiveHeartbeat). Onboarding applies it with no extra control, // so nothing else reads this state yet. @@ -2145,11 +2148,12 @@ function OnboardingWizardInner({ * the only thing left to do with it would be to embed it. */ async function storeApiKeyUserSecret(companyId: string, isCurrent = () => true): Promise { - const key = apiKey.trim(); + const key = normalizeApiKeyInput(apiKey); const envKey = apiKeyEnvKeyFor(adapterType); const stored = apiKeySecretRef.current?.key === key && apiKeySecretRef.current.companyId === companyId && apiKeySecretRef.current.envKey === envKey ? apiKeySecretRef.current : null; if (stored?.binding) return true; + setApiKeyRejected(false); try { if (managedProvider) { const grantId = stored?.grantId ?? (await aiConnectionsApi.create(companyId, { provider: managedProvider, method: "api_key", name: `My ${CONNECT_SOURCE_NAMES[adapterType] ?? managedProvider} API`, ownership: "personal", apiKey: key, agentIds: [], allAgents: true })).grantId; @@ -2170,9 +2174,14 @@ function OnboardingWizardInner({ provider: managedProvider ?? adapterType, method: "api_key", }); + const errorBody = err instanceof Error ? describeError(err).body : ""; + const rejected = + (err instanceof ApiError && err.code === "ai_connection_api_key_rejected") || + errorBody.toLowerCase().includes("rejected this api key"); + setApiKeyRejected(rejected); setError( err instanceof Error - ? `Could not store the API key: ${describeError(err).body}` + ? `Could not store the API key: ${errorBody}` : "Could not store the API key.", ); } @@ -3350,6 +3359,7 @@ function OnboardingWizardInner({ autoConnectStartedRef.current = false; setSourcePicked(true); setAdapterType(id); + setApiKeyRejected(false); if (id !== adapterType) setRunner("auto"); // Older drafts may already pair OpenAI with the Claude // model retained by a previous source switch. @@ -3457,23 +3467,33 @@ function OnboardingWizardInner({ setSelectedSavedKey(createdCompanyId ? { companyId: createdCompanyId, envKey: apiKeyEnvKeyFor(adapterType), id } : null); setApiKey(""); }} />} - {!selectedApiKey && !hasGatewaySelection && !connectionModels && { - setSelectedSavedKey(createdCompanyId ? { companyId: createdCompanyId, envKey: apiKeyEnvKeyFor(adapterType), id: "" } : null); - setApiKey(value); - }} - onSubmit={() => handleConnectStepPrimary()} - />} + {!selectedApiKey && !hasGatewaySelection && !connectionModels && ( + { + setSelectedSavedKey(createdCompanyId ? { companyId: createdCompanyId, envKey: apiKeyEnvKeyFor(adapterType), id: "" } : null); + setApiKeyRejected(false); + setApiKey(value); + }} + onSubmit={() => handleConnectStepPrimary()} + onSwitchProvider={(targetAdapterType) => { + setAdapterType(targetAdapterType); + setRunner("auto"); + setModel(""); + setSelectedSavedKey( + createdCompanyId + ? { companyId: createdCompanyId, envKey: apiKeyEnvKeyFor(targetAdapterType), id: "" } + : null, + ); + setApiKeyRejected(false); + setError(null); + }} + /> + )} {hasGatewaySelection && (gatewayLookupFailed ? <>

Your saved gateway connection could not be loaded. Retry to choose a model and connect your agent.

+

+ )} + {apiKeysHelp && ( +

+ {apiKeysHelp.hint}{" "} + + Open {apiKeysHelp.label} + +

+ )} +
+ ); +} diff --git a/ui/src/lib/onboarding-login-helpers.test.ts b/ui/src/lib/onboarding-login-helpers.test.ts new file mode 100644 index 00000000000..7728346c856 --- /dev/null +++ b/ui/src/lib/onboarding-login-helpers.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from "vitest"; +import { + detectMismatchedApiKeyProvider, + normalizeApiKeyInput, + normalizeSubmittedBrowserCode, + providerApiKeysHelp, + validateSubmittedBrowserCode, +} from "./onboarding-login-helpers"; + +describe("normalizeSubmittedBrowserCode", () => { + it("strips surrounding whitespace, quotes, and embedded line breaks", () => { + expect(normalizeSubmittedBrowserCode(" abc123\r\n#def456 \n")).toBe("abc123#def456"); + expect(normalizeSubmittedBrowserCode("`abc123#def456`")).toBe("abc123#def456"); + expect(normalizeSubmittedBrowserCode('"abc123"')).toBe("abc123"); + }); + + it("extracts code and state when a user pastes the full OAuth callback URL", () => { + expect( + normalizeSubmittedBrowserCode("https://console.anthropic.com/oauth/code/callback?code=mycode123&state=mystate456"), + ).toBe("mycode123#mystate456"); + expect( + normalizeSubmittedBrowserCode("https://console.anthropic.com/oauth/code/callback?code=mycode123#hashstate"), + ).toBe("mycode123#hashstate"); + expect( + normalizeSubmittedBrowserCode("https://console.anthropic.com/oauth/code/callback?code=onlycode"), + ).toBe("onlycode"); + }); + + it("validates normalized browser codes and returns actionable errors for invalid input", () => { + expect(validateSubmittedBrowserCode("abc123#def456")).toBeNull(); + expect(validateSubmittedBrowserCode(" \n ")).toContain("Paste the authorization code"); + expect(validateSubmittedBrowserCode("hello world with spaces")).toContain("doesn’t look like an authorization code"); + }); +}); + +describe("API key helpers", () => { + it("strips whitespace and line breaks from pasted keys", () => { + expect(normalizeApiKeyInput(" sk-proj-abc\n123\t ")).toBe("sk-proj-abc123"); + }); + + it("detects Anthropic keys pasted into OpenAI and OpenAI keys pasted into Anthropic", () => { + expect(detectMismatchedApiKeyProvider("sk-ant-api03-abcdef1234", "codex_local")).toEqual({ + targetAdapterType: "claude_local", + detectedLabel: "Anthropic", + }); + expect(detectMismatchedApiKeyProvider("sk-proj-abcdef123456", "claude_local")).toEqual({ + targetAdapterType: "codex_local", + detectedLabel: "OpenAI", + }); + expect(detectMismatchedApiKeyProvider("sk-ant-api03-abcdef1234", "claude_local")).toBeNull(); + expect(detectMismatchedApiKeyProvider("sk-proj-abcdef123456", "codex_local")).toBeNull(); + expect(detectMismatchedApiKeyProvider("sk-or-v1-abcdef123456", "claude_local")).toBeNull(); + }); + + it("returns provider API key help URLs for OpenAI, Anthropic, and Gemini", () => { + expect(providerApiKeysHelp("codex_local")?.url).toBe("https://platform.openai.com/api-keys"); + expect(providerApiKeysHelp("claude_local")?.url).toBe("https://console.anthropic.com/settings/keys"); + expect(providerApiKeysHelp("gemini_local")?.url).toBe("https://aistudio.google.com/apikey"); + expect(providerApiKeysHelp("unknown_adapter")).toBeNull(); + }); +}); diff --git a/ui/src/lib/onboarding-login-helpers.ts b/ui/src/lib/onboarding-login-helpers.ts new file mode 100644 index 00000000000..ff3247e90a4 --- /dev/null +++ b/ui/src/lib/onboarding-login-helpers.ts @@ -0,0 +1,110 @@ +import { isValidBrowserCode } from "@paperclipai/shared"; + +/** + * Clean up pasted authorization codes from mobile/desktop clipboards: + * - Strip surrounding quotes/backticks and leading/trailing whitespace. + * - Strip embedded line breaks (common when wrapping long codes on mobile). + * - If the user pasted the full OAuth callback URL instead of just the code, + * extract the `code` query parameter (and `#state` if present). + */ +export function normalizeSubmittedBrowserCode(raw: string): string { + const withoutNewlines = raw.replace(/[\r\n]+/g, "").trim(); + const unwrapped = withoutNewlines.replace(/^["'`]+|["'`]+$/g, "").trim(); + if (!unwrapped) return ""; + + if (/^https?:\/\//i.test(unwrapped)) { + try { + const parsed = new URL(unwrapped); + const code = parsed.searchParams.get("code")?.trim(); + if (code) { + const stateFromQuery = parsed.searchParams.get("state")?.trim(); + const stateFromHash = parsed.hash.replace(/^#/, "").trim(); + const state = stateFromQuery || stateFromHash; + return state && !code.includes("#") ? `${code}#${state}` : code; + } + } catch { + // Fall through to raw string so validation reports the bad format. + } + } + + return unwrapped; +} + +/** + * Returns a user-facing inline validation error when a non-empty pasted or + * submitted browser code cannot be sent to the login runner, or null if valid. + */ +export function validateSubmittedBrowserCode(raw: string): string | null { + const normalized = normalizeSubmittedBrowserCode(raw); + if (!normalized) { + return "Paste the authorization code from your sign-in window, then try again."; + } + if (!isValidBrowserCode(normalized)) { + return "That doesn’t look like an authorization code. Copy the code shown after signing in and paste it here."; + } + return null; +} + +/** Strip surrounding whitespace and embedded newlines/tabs from a pasted API key. */ +export function normalizeApiKeyInput(raw: string): string { + return raw.replace(/[\r\n\t]+/g, "").trim(); +} + +export interface MismatchedApiKeyProvider { + targetAdapterType: "claude_local" | "codex_local"; + detectedLabel: string; +} + +/** + * Detect obvious provider mismatches before submitting an API key so users + * pasting an Anthropic key into OpenAI (or vice versa) get a 1-click fix. + */ +export function detectMismatchedApiKeyProvider( + rawKey: string, + currentAdapterType: string, +): MismatchedApiKeyProvider | null { + const key = normalizeApiKeyInput(rawKey); + if (key.length < 10) return null; + + if (key.startsWith("sk-ant-") && currentAdapterType === "codex_local") { + return { targetAdapterType: "claude_local", detectedLabel: "Anthropic" }; + } + if ( + currentAdapterType === "claude_local" && + (key.startsWith("sk-proj-") || (key.startsWith("sk-") && !key.startsWith("sk-ant-") && !key.startsWith("sk-or-"))) + ) { + return { targetAdapterType: "codex_local", detectedLabel: "OpenAI" }; + } + return null; +} + +export interface ProviderApiKeysHelp { + url: string; + label: string; + hint: string; +} + +export function providerApiKeysHelp(adapterType: string): ProviderApiKeysHelp | null { + switch (adapterType) { + case "codex_local": + return { + url: "https://platform.openai.com/api-keys", + label: "OpenAI API keys", + hint: "Check that you copied the full sk-… key, that it hasn’t been revoked, and that project keys have models access.", + }; + case "claude_local": + return { + url: "https://console.anthropic.com/settings/keys", + label: "Anthropic API keys", + hint: "Check that you copied the full sk-ant-… key and that it hasn’t been revoked.", + }; + case "gemini_local": + return { + url: "https://aistudio.google.com/apikey", + label: "Google AI Studio API keys", + hint: "Check that you copied the full API key and that it is active.", + }; + default: + return null; + } +} diff --git a/ui/src/lib/use-visibility-login-recovery.test.tsx b/ui/src/lib/use-visibility-login-recovery.test.tsx new file mode 100644 index 00000000000..a393c62bd01 --- /dev/null +++ b/ui/src/lib/use-visibility-login-recovery.test.tsx @@ -0,0 +1,86 @@ +// @vitest-environment jsdom + +import { createRoot, type Root } from "react-dom/client"; +import { flushSync } from "react-dom"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { useVisibilityLoginRecovery } from "./use-visibility-login-recovery"; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; + +function Harness(props: Parameters[0]) { + useVisibilityLoginRecovery(props); + return null; +} + +describe("useVisibilityLoginRecovery", () => { + let root: Root | null = null; + let container: HTMLDivElement | null = null; + + afterEach(() => { + if (root) flushSync(() => root!.unmount()); + root = null; + container?.remove(); + container = null; + }); + + function mount(props: Parameters[0]) { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + flushSync(() => root!.render()); + } + + function fireVisible() { + Object.defineProperty(document, "visibilityState", { configurable: true, value: "visible" }); + document.dispatchEvent(new Event("visibilitychange")); + } + + it("auto-retries when a suspended tab returns and refetch discovers timed_out", async () => { + const onRetry = vi.fn(); + const onRefetch = vi.fn(async () => ({ data: { status: "timed_out" } })); + mount({ + active: true, + sessionActive: true, + sessionId: "sess-1", + autoRefreshOnExpiry: true, + expired: false, + canRetry: false, + retrying: false, + onRefetch, + onRetry, + }); + + fireVisible(); + await Promise.resolve(); + await Promise.resolve(); + + expect(onRefetch).toHaveBeenCalledOnce(); + expect(onRetry).toHaveBeenCalledOnce(); + + // Second visibility change for the same session does not loop. + fireVisible(); + await Promise.resolve(); + expect(onRetry).toHaveBeenCalledOnce(); + }); + + it("auto-retries immediately when already expired on return", () => { + const onRetry = vi.fn(); + const onRefetch = vi.fn(async () => ({ data: { status: "timed_out" } })); + mount({ + active: true, + sessionActive: false, + sessionId: "sess-2", + autoRefreshOnExpiry: true, + expired: true, + canRetry: true, + retrying: false, + onRefetch, + onRetry, + }); + + fireVisible(); + expect(onRetry).toHaveBeenCalledOnce(); + expect(onRefetch).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/src/lib/use-visibility-login-recovery.ts b/ui/src/lib/use-visibility-login-recovery.ts new file mode 100644 index 00000000000..9c3f3db913a --- /dev/null +++ b/ui/src/lib/use-visibility-login-recovery.ts @@ -0,0 +1,83 @@ +import { useEffect, useRef } from "react"; + +/** + * Polls an active login session as soon as the user returns to the tab, and + * auto-refreshes once in onboarding if the session expired while they were away + * (including when the browser suspended timers and expiry is only discovered by + * the return refetch). + */ +export function useVisibilityLoginRecovery({ + active, + sessionActive, + sessionId, + autoRefreshOnExpiry, + expired, + canRetry, + retrying, + onRefetch, + onRetry, +}: { + active: boolean; + sessionActive: boolean; + sessionId: string | null; + autoRefreshOnExpiry: boolean; + expired: boolean; + canRetry: boolean; + retrying: boolean; + onRefetch: () => Promise<{ data?: { status?: string | null } | null }>; + onRetry: () => void; +}) { + const onRefetchRef = useRef(onRefetch); + onRefetchRef.current = onRefetch; + const onRetryRef = useRef(onRetry); + onRetryRef.current = onRetry; + const retryingRef = useRef(retrying); + retryingRef.current = retrying; + + const autoRefreshedKeyRef = useRef(null); + const pendingReturnRef = useRef(false); + + const tryAutoRefresh = (key: string) => { + if (!autoRefreshOnExpiry || retryingRef.current || autoRefreshedKeyRef.current === key) return false; + autoRefreshedKeyRef.current = key; + pendingReturnRef.current = false; + onRetryRef.current(); + return true; + }; + + useEffect(() => { + if (!active) { + pendingReturnRef.current = false; + return; + } + const onVisibilityChange = () => { + if (document.visibilityState !== "visible") return; + const refreshKey = sessionId ?? "__expired__"; + if (expired && canRetry) { + tryAutoRefresh(refreshKey); + return; + } + if (sessionActive && sessionId) { + pendingReturnRef.current = true; + void onRefetchRef.current().then((result) => { + if (!pendingReturnRef.current) return; + const nextStatus = result.data?.status; + if (nextStatus === "timed_out") { + tryAutoRefresh(refreshKey); + } else if (nextStatus) { + pendingReturnRef.current = false; + } + }).catch(() => { + pendingReturnRef.current = false; + }); + } + }; + document.addEventListener("visibilitychange", onVisibilityChange); + return () => document.removeEventListener("visibilitychange", onVisibilityChange); + }, [active, sessionActive, sessionId, autoRefreshOnExpiry, expired, canRetry]); + + useEffect(() => { + if (!active || !pendingReturnRef.current || !expired || !canRetry) return; + tryAutoRefresh(sessionId ?? "__expired__"); + }, [active, expired, canRetry, sessionId, autoRefreshOnExpiry]); +}