mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 19:08:33 +01:00
fix(onboarding): harden connect-model OAuth timeout, mobile paste, and API key recovery (#23379)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - During onboarding, new users connect an AI model via Claude/OpenAI subscription OAuth or an API key. > - Production session replays showed users failing on `connect_model` because subscription login sessions expired at 5 minutes during mobile/tab switches, the waiting spinner hid the sign-in link with no way to reopen it, pasted Claude codes failed silently without normalization or clear feedback, and rejected API keys gave a dead-end error. > - These friction points cause new users to abandon onboarding right before their first agent run. > - This pull request raises server login timeouts to 15 minutes with visibility-change polling/auto-refresh, keeps a re-open link and 60s recovery action visible while waiting, normalizes and validates pasted Claude authorization codes with explicit error messaging, and adds API key paste normalization, provider-mismatch switching, and actionable rejection links. > - The benefit is fewer onboarding drop-offs on mobile and desktop without changing backend auth protocols or schema. ## Linked Issues or Issue Description **What happened?** Users onboarding on `connect_model` hit four repeatable failure modes: 1. Subscription login sessions (`DEVICE_LOGIN_TIMEOUT_MS` and `DEFAULT_SETUP_TOKEN_SESSION_TTL_MS`) expired after 5 minutes while users switched apps/tabs for OAuth and 2FA, showing `This sign-in expired` or `Sign-in didn't finish` right when they returned. 2. After clicking `Sign in`, `ProviderSubscriptionCard` replaced the button with a disabled `Waiting…` / `Waiting for code…` spinner, leaving users with no way to reopen the OAuth URL if a mobile browser blocked the tab or they closed it. 3. Pasting a Claude authorization code with mobile line breaks, quotes, or a full callback URL could fail silently or show no explanation when rejected. 4. Pasting a rejected or wrong-provider API key showed a generic rejection message without pointing users to the provider's API keys page or offering a 1-click provider switch. **Expected behavior** Subscription sign-in sessions should give users 15 minutes to complete OAuth, immediately poll or refresh when returning to the tab, keep a re-open link and 60-second recovery action accessible, normalize and validate pasted Claude codes with clear inline feedback, and help users recover from wrong-provider or rejected API keys. **Steps to reproduce** 1. Open the onboarding wizard and advance to the Connect a model step. 2. Start a Claude or OpenAI subscription sign-in, switch tabs for 5 minutes (or close the OAuth tab), and return. 3. Paste an authorization code with extra whitespace/newlines or a callback URL into the Claude code input, or paste an Anthropic `sk-ant-...` key into OpenAI API key mode. **Paperclip version or commit** `43fedd51c5c37ccf7c7568328bac97179cdd48ba` (`master`) **Deployment mode** Other (hosted Cloud & local dev) ## What Changed - **15-minute subscription login TTLs + tab-return poll/refresh:** Raised `DEVICE_LOGIN_TIMEOUT_MS` (`server/src/services/device-login-service.ts`) and `DEFAULT_SETUP_TOKEN_SESSION_TTL_MS` (`server/src/services/setup-token-session.ts`) from 5 minutes to 15 minutes. Added `visibilitychange` listeners to both `AdapterDeviceLoginPanel` and `ClaudeSetupTokenLoginPanel` (`ui/src/components/AgentConfigForm.tsx`) to immediately refetch status on tab return and auto-refresh once if an onboarding session expired while hidden. - **Non-locking waiting state:** Updated `ProviderSubscriptionCard` (`ui/src/components/AdapterLoginChrome.tsx`) to keep an `Open sign-in link again` button visible while waiting and show a `Taking a while? Get a new link` recovery button after 60 seconds (`WAITING_HELP_DELAY_MS`). - **Claude code-paste normalization & inline validation:** Added `ui/src/lib/onboarding-login-helpers.ts` (`normalizeSubmittedBrowserCode`, `validateSubmittedBrowserCode`) to strip newlines/quotes and extract `code#state` from pasted callback URLs, surface immediate inline validation errors on invalid pastes, and show an explicit rejected-code message when a submitted code fails. - **Self-recoverable API key input:** Added `normalizeApiKeyInput`, `detectMismatchedApiKeyProvider`, and `providerApiKeysHelp` in `ui/src/lib/onboarding-login-helpers.ts`, wired into `ui/src/components/OnboardingWizard.tsx` to normalize pasted keys, offer a 1-click switch when an Anthropic/OpenAI key is pasted into the wrong provider, and link directly to the provider's API keys page when rejected. - **Module size note:** `AgentConfigForm.tsx` and `OnboardingWizard.tsx` already exceeded 1,000 lines; all new pure parsing, validation, and provider-help logic was extracted into `ui/src/lib/onboarding-login-helpers.ts` to keep edits to existing files minimal. ## Verification - `pnpm --filter @paperclipai/ui typecheck` — passed. - `pnpm --filter @paperclipai/server typecheck` — passed. - `pnpm vitest run ui/src/lib/onboarding-login-helpers.test.ts ui/src/components/AdapterLoginChrome.test.tsx ui/src/components/AgentConfigForm.render.test.tsx server/src/__tests__/device-login-service.test.ts` — 4/4 files, 84/84 tests passed. - `git ls-files "*setup-token*test*" "*onboarding*test*" | grep -E "^(server|ui)/" | xargs pnpm vitest run` — 24/24 files, 373/373 tests passed. - Note: A full local `pnpm verify` run selected 2,296 files and hit 14 unrelated local PostgreSQL/heartbeat/Tailscale hook timeouts under parallel macOS load (34,070 passed, 0 failures in login/onboarding/setup-token/device-login suites); CI will supply full-suite coverage on this PR. ## Risks - **Low risk:** Raising `DEVICE_LOGIN_TIMEOUT_MS` and `DEFAULT_SETUP_TOKEN_SESSION_TTL_MS` from 5 to 15 minutes extends the maximum lifetime of an uncompleted login sandbox lease by 10 minutes (bounded by the existing reaper and per-owner concurrency limits). No database schema, API contract, or auth protocol changes. ## Model Used - Google Gemini (Antigravity agentic assistant with thinking mode and tool use / 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
This commit is contained in:
1 parent
e32b1b057f
commit
d1680baf8f
17 files changed
+812
-62
No files matched your search
@@ -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(
|
||||
<OnboardingSignInMark.Provider value={<span />}>
|
||||
<ProviderSubscriptionCard
|
||||
providerName="OpenAI"
|
||||
mode="displayed_code"
|
||||
authorizationUrl="https://example.test/login"
|
||||
onOpenAuthorization={() => {}}
|
||||
onRefresh={refresh}
|
||||
>
|
||||
{null}
|
||||
</ProviderSubscriptionCard>
|
||||
</OnboardingSignInMark.Provider>,
|
||||
);
|
||||
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(
|
||||
<LocalProviderLoginInstructions
|
||||
adapterType="claude_local"
|
||||
login={{
|
||||
...login,
|
||||
authorizationUrl: "https://claude.ai/oauth/authorize?IQ2RDWoHouqywHRo76dCv-ms1Qxya8PGzuNNvHH1OX8o",
|
||||
submitCode,
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
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(
|
||||
<LocalProviderLoginInstructions
|
||||
|
||||
@@ -14,6 +14,10 @@ import {
|
||||
} from "./onboarding/onboarding-motion";
|
||||
import { ANALYTICS_MASK_CLASS, ANALYTICS_NO_CAPTURE_CLASS } from "@/lib/analytics/privacy";
|
||||
import { describeError } from "@/api/errors";
|
||||
import {
|
||||
normalizeSubmittedBrowserCode,
|
||||
validateSubmittedBrowserCode,
|
||||
} from "@/lib/onboarding-login-helpers";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/**
|
||||
@@ -461,6 +465,9 @@ export function OnboardingCardField({
|
||||
export const OnboardingSignInRetry = createContext<(() => void) | null>(null);
|
||||
export const OnboardingSignInMark = createContext<ReactNode>(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<string | null>(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 (
|
||||
<OnboardingLoginCard revealTogether instruction={<span role="alert" className="grid gap-1">
|
||||
@@ -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 (
|
||||
<OnboardingLoginCard revealTogether loading={loading} instruction={
|
||||
@@ -516,21 +541,41 @@ export function ProviderSubscriptionCard({
|
||||
<span>2. {mode === "submitted_code" ? "Return to this window and enter the authorization code." : "Enter the code below in the sign-in window."}</span>
|
||||
</span>
|
||||
}>
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
{waiting ? (
|
||||
<Button type="button" disabled className="rounded-full px-5">
|
||||
<Loader2 className="size-4 motion-safe:animate-spin" />
|
||||
{mode === "submitted_code" ? "Waiting for code…" : "Waiting…"}
|
||||
</Button>
|
||||
) : <Button type="button" disabled={!authorizationUrl} className="gap-1 rounded-full py-0 pl-3 pr-6" onClick={() => {
|
||||
if (!authorizationUrl) return;
|
||||
setOpenedUrl(authorizationUrl);
|
||||
if (onOpenAuthorization) onOpenAuthorization();
|
||||
else window.open(authorizationUrl, "_blank", "noopener,noreferrer");
|
||||
}}>
|
||||
<span className="size-(--sz-30px) shrink-0">{mark}</span>Sign in
|
||||
</Button>}
|
||||
<div className="min-h-(--sz-44px) min-w-0 flex-1 basis-44">{children}</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
{waiting ? (
|
||||
<Button type="button" disabled className="rounded-full px-5">
|
||||
<Loader2 className="size-4 motion-safe:animate-spin" />
|
||||
{mode === "submitted_code" ? "Waiting for code…" : "Waiting…"}
|
||||
</Button>
|
||||
) : <Button type="button" disabled={!authorizationUrl} className="gap-1 rounded-full py-0 pl-3 pr-6" onClick={openAuthorizationLink}>
|
||||
<span className="size-(--sz-30px) shrink-0">{mark}</span>Sign in
|
||||
</Button>}
|
||||
<div className="min-h-(--sz-44px) min-w-0 flex-1 basis-44">{children}</div>
|
||||
</div>
|
||||
{waiting && authorizationUrl && (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
|
||||
<button
|
||||
type="button"
|
||||
className="underline underline-offset-2 hover:text-foreground"
|
||||
onClick={openAuthorizationLink}
|
||||
>
|
||||
Open sign-in link again
|
||||
</button>
|
||||
{waitingLong && refresh && (
|
||||
<span>
|
||||
Taking a while?{" "}
|
||||
<button
|
||||
type="button"
|
||||
className="underline underline-offset-2 hover:text-foreground"
|
||||
onClick={refresh}
|
||||
>
|
||||
Get a new link
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</OnboardingLoginCard>
|
||||
);
|
||||
@@ -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" ? <div className="flex flex-col gap-2">
|
||||
<OnboardingCardField
|
||||
value={browserCode}
|
||||
onChange={setBrowserCode}
|
||||
onChange={(next) => {
|
||||
setSubmitError(null);
|
||||
setBrowserCode(next);
|
||||
}}
|
||||
onPaste={pasteBrowserCode}
|
||||
onSubmit={() => void submitBrowserCode()}
|
||||
disabled={submitting}
|
||||
/>
|
||||
{submitError && <p role="alert" className="px-2 text-xs text-destructive">{submitError}</p>}
|
||||
{!onboardingSignIn && <Button type="button" disabled={!browserCode.trim() || submitting} onClick={() => void submitBrowserCode()}>Submit code</Button>}
|
||||
</div> : hostedGoogleRedirect ? <div className="flex flex-col gap-2">
|
||||
<p className="px-2 text-xs text-muted-foreground">
|
||||
|
||||
@@ -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<string | null>(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 (
|
||||
<ProviderSubscriptionCard
|
||||
loading={retryLogin.isPending || (!authorizationUrl && !failure)}
|
||||
failure={failure}
|
||||
failureMessage={automaticComputer ? startError ?? undefined : undefined}
|
||||
failureMessage={onboardingFailureMessage}
|
||||
onRetry={!onRetryReady && retryReady ? retryAction : undefined}
|
||||
onRefresh={!retryLogin.isPending && !startLogin.isPending && !codeSubmitted && !submitCode.isPending && !isCompleting ? retryAction : undefined}
|
||||
providerName={connectSourceName(adapterType)}
|
||||
authorizationUrl={authorizationUrl ?? undefined}
|
||||
onOpenAuthorization={onOpenAuthorization}
|
||||
@@ -4111,19 +4167,29 @@ function SubmittedBrowserCodeLoginPanel({
|
||||
</p>
|
||||
)}
|
||||
{!failure && !retryLogin.isPending && (
|
||||
<OnboardingCardField
|
||||
value={browserCode}
|
||||
onChange={setBrowserCode}
|
||||
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}
|
||||
/>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<OnboardingCardField
|
||||
value={browserCode}
|
||||
onChange={(next) => {
|
||||
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 && (
|
||||
<p role="alert" className="px-2 text-xs text-destructive">
|
||||
{codeValidationError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</ProviderSubscriptionCard>
|
||||
);
|
||||
|
||||
@@ -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<boolean> {
|
||||
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 && <OnboardingCardField
|
||||
label="API key"
|
||||
describedBy={showApiAccountNote ? "onboarding-api-account-note" : undefined}
|
||||
description={!showApiAccountNote && managedProvider ? `This will be your default ${CONNECT_SOURCE_NAMES[adapterType] ?? managedProvider} account.` : undefined}
|
||||
placeholder="Enter API key here"
|
||||
masked
|
||||
// The card is the answer to the tile just pressed, so
|
||||
// the field is unambiguously the next thing. Carried
|
||||
// over from the key field this card replaced.
|
||||
autoFocus
|
||||
value={apiKey}
|
||||
onChange={(value) => {
|
||||
setSelectedSavedKey(createdCompanyId ? { companyId: createdCompanyId, envKey: apiKeyEnvKeyFor(adapterType), id: "" } : null);
|
||||
setApiKey(value);
|
||||
}}
|
||||
onSubmit={() => handleConnectStepPrimary()}
|
||||
/>}
|
||||
{!selectedApiKey && !hasGatewaySelection && !connectionModels && (
|
||||
<OnboardingApiKeyField
|
||||
adapterType={adapterType}
|
||||
value={apiKey}
|
||||
describedBy={showApiAccountNote ? "onboarding-api-account-note" : undefined}
|
||||
description={!showApiAccountNote && managedProvider ? `This will be your default ${CONNECT_SOURCE_NAMES[adapterType] ?? managedProvider} account.` : undefined}
|
||||
rejected={apiKeyRejected}
|
||||
onChange={(value) => {
|
||||
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 ? <>
|
||||
<p role="alert" className="text-sm text-destructive">Your saved gateway connection could not be loaded. Retry to choose a model and connect your agent.</p>
|
||||
<Button type="button" variant="outline" disabled={loading || adapterEnvLoading} onClick={() => { void connectionModelState.refresh(); }}>
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// @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 { OnboardingApiKeyField } from "./OnboardingApiKeyField";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
describe("OnboardingApiKeyField", () => {
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
if (root) flushSync(() => root!.unmount());
|
||||
root = null;
|
||||
container?.remove();
|
||||
container = null;
|
||||
});
|
||||
|
||||
function render(props: Parameters<typeof OnboardingApiKeyField>[0]) {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
flushSync(() => root!.render(<OnboardingApiKeyField {...props} />));
|
||||
}
|
||||
|
||||
it("offers a 1-click provider switch when an Anthropic key is pasted into OpenAI", () => {
|
||||
const onSwitchProvider = vi.fn();
|
||||
render({
|
||||
adapterType: "codex_local",
|
||||
value: "sk-ant-api03-abcdef1234",
|
||||
rejected: false,
|
||||
onChange: () => {},
|
||||
onSubmit: () => {},
|
||||
onSwitchProvider,
|
||||
});
|
||||
|
||||
expect(container!.textContent).toContain("That looks like an Anthropic API key.");
|
||||
const switchButton = container!.querySelector("button");
|
||||
expect(switchButton?.textContent).toBe("Switch to Anthropic");
|
||||
flushSync(() => switchButton!.click());
|
||||
expect(onSwitchProvider).toHaveBeenCalledWith("claude_local");
|
||||
});
|
||||
|
||||
it("shows provider API key recovery guidance and link when rejected", () => {
|
||||
render({
|
||||
adapterType: "codex_local",
|
||||
value: "sk-proj-invalid123456",
|
||||
rejected: true,
|
||||
onChange: () => {},
|
||||
onSubmit: () => {},
|
||||
onSwitchProvider: () => {},
|
||||
});
|
||||
|
||||
const link = container!.querySelector("a");
|
||||
expect(link?.getAttribute("href")).toBe("https://platform.openai.com/api-keys");
|
||||
expect(link?.textContent).toBe("Open OpenAI API keys");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { OnboardingCardField } from "../AdapterLoginChrome";
|
||||
import {
|
||||
detectMismatchedApiKeyProvider,
|
||||
normalizeApiKeyInput,
|
||||
providerApiKeysHelp,
|
||||
} from "../../lib/onboarding-login-helpers";
|
||||
|
||||
export function OnboardingApiKeyField({
|
||||
adapterType,
|
||||
value,
|
||||
describedBy,
|
||||
description,
|
||||
rejected,
|
||||
onChange,
|
||||
onSubmit,
|
||||
onSwitchProvider,
|
||||
}: {
|
||||
adapterType: string;
|
||||
value: string;
|
||||
describedBy?: string;
|
||||
description?: string;
|
||||
rejected: boolean;
|
||||
onChange: (normalizedValue: string) => void;
|
||||
onSubmit: () => void;
|
||||
onSwitchProvider: (targetAdapterType: "claude_local" | "codex_local") => void;
|
||||
}) {
|
||||
const mismatchedProvider = detectMismatchedApiKeyProvider(value, adapterType);
|
||||
const apiKeysHelp = rejected ? providerApiKeysHelp(adapterType) : null;
|
||||
const article =
|
||||
mismatchedProvider?.detectedLabel === "Anthropic" || mismatchedProvider?.detectedLabel === "OpenAI"
|
||||
? "an"
|
||||
: "a";
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<OnboardingCardField
|
||||
label="API key"
|
||||
describedBy={describedBy}
|
||||
description={description}
|
||||
placeholder="Enter API key here"
|
||||
masked
|
||||
autoFocus
|
||||
value={value}
|
||||
onChange={(next) => onChange(normalizeApiKeyInput(next))}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
{mismatchedProvider && (
|
||||
<p role="status" className="flex flex-wrap items-center gap-x-2 gap-y-1 px-2 text-xs text-muted-foreground">
|
||||
<span>
|
||||
That looks like {article} {mismatchedProvider.detectedLabel} API key.
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
className="font-medium text-foreground underline underline-offset-2"
|
||||
onClick={() => onSwitchProvider(mismatchedProvider.targetAdapterType)}
|
||||
>
|
||||
Switch to {mismatchedProvider.detectedLabel}
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
{apiKeysHelp && (
|
||||
<p role="status" className="px-2 text-xs text-muted-foreground">
|
||||
{apiKeysHelp.hint}{" "}
|
||||
<a
|
||||
href={apiKeysHelp.url}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="font-medium text-foreground underline underline-offset-2"
|
||||
>
|
||||
Open {apiKeysHelp.label}
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<typeof useVisibilityLoginRecovery>[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<typeof useVisibilityLoginRecovery>[0]) {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
flushSync(() => root!.render(<Harness {...props} />));
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<string | null>(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]);
|
||||
}
|
||||
Reference in new issue
Block a user