diff --git a/doc/onboarding-chat.md b/doc/onboarding-chat.md index 0726699ddc8..6954e5d85d7 100644 --- a/doc/onboarding-chat.md +++ b/doc/onboarding-chat.md @@ -2,7 +2,10 @@ Finishing company onboarding opens the new agent's standing chat. It creates no execution task or project. Chat uses the existing owner-bound conversation record -and is excluded from task collections. Existing onboarding tasks remain readable. +and is excluded from task collections. New chats have no task number or identifier +and do not advance the company's task counter, so the first accepted task is +`-1`. Existing numbered records keep their identifiers. Existing onboarding +tasks remain readable. The wizard prepares the conversation before navigating. After its content paints in a visible tab, the UI requests a live welcome through the normal agent queue. @@ -21,3 +24,8 @@ It proposes scoped work through `suggest_tasks`. Recorded acceptance creates the selected tasks through the existing atomic handoff. An explicit task-creation request can create work directly. Project selection, budgets and hiring gates retain their normal authority. The conversation remains available after handoff. + +Local subscription setup waits for verified sign-in before enabling Connect. +Pasting a Claude authorization code submits it automatically and shows a finishing state; a rejected code +offers a fresh sign-in immediately. Switching providers clears the previous +provider's model so subscription verification uses a compatible model. 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 6028695d16a..96eb42241b1 100644 --- a/packages/adapters/claude-local/src/server/setup-token-parse.ts +++ b/packages/adapters/claude-local/src/server/setup-token-parse.ts @@ -221,6 +221,11 @@ function stripTerminalControls(text: string): string { .replace(ANSI_CSI_RE, ""); } +/** The CLI waits for another Enter after rejecting a code instead of exiting. */ +export function hasSetupTokenOAuthError(text: string): boolean { + return /OAuth\s+error\s*:/.test(stripTerminalControls(text)); +} + /** * Returns true when `value` is a valid `scope` value: one to eight * space-separated tokens, a total length of at most {@link MAX_SCOPE_LENGTH}, 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 ede26a52a74..8482efac1f6 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,31 @@ async function flush(): Promise { } describe("runSetupTokenLogin", () => { + 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; + 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("\r\n\u001b[31mOAuth\u001b[1Cerr"); + stream(`or: Invalid code ${BROWSER_CODE}\u001b[0m\r\nPress Enter to retry\r\n`); + } + }; + const log = vi.fn(); + const onCredential = vi.fn(); + const result = await runSetupTokenLogin(fake.driver, { + onPrompt: () => {}, provideCode: async () => BROWSER_CODE, onCredential, + codeSubmitSettleMs: 0, timeoutMs: 1000, log, + }); + expect(result).toMatchObject({ outcome: "failure", failureReason: "oauth_error", credentialDelivered: false }); + expect(onCredential).not.toHaveBeenCalled(); + expect(fake.stops.count).toBe(1); + expect(JSON.stringify({ result, logs: log.mock.calls })).not.toContain(BROWSER_CODE); + }); + it("sends one login URL through onPrompt", async () => { // A success stream and a resolving sink, so the run reports success after the // runner delivers the credential. 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 076323f7f6b..f1d16644371 100644 --- a/packages/adapters/claude-local/src/server/setup-token-runner.ts +++ b/packages/adapters/claude-local/src/server/setup-token-runner.ts @@ -8,6 +8,7 @@ import { import { parseSetupTokenCredential, parseSetupTokenPrompt, + hasSetupTokenOAuthError, type SetupTokenPrompt, } from "./setup-token-parse.js"; @@ -123,6 +124,7 @@ export type SetupTokenOutcome = LoginRunnerOutcome; * the base result with the two setup-token status fields. */ export interface SetupTokenLoginResult extends LoginRunnerResult { + failureReason?: "oauth_error"; codeSubmitted: boolean; /** True when the runner bound the token and invoked `onCredential` one time. */ credentialDelivered: boolean; @@ -218,6 +220,7 @@ export async function runSetupTokenLogin( let promptSurfaced = false; let codeSubmitted = false; let submitStarted = false; + let oauthError = false; // The runner sets this true one time, only after the mandatory sink resolves. let credentialDelivered = false; // The bound token bytes. The runner binds them from the success record during @@ -329,11 +332,16 @@ export async function runSetupTokenLogin( } return; } - // The prompt already surfaced. Scan the post-prompt stream for the success - // token. The runner scans only when a caller provides an `onCredential` - // sink, so it never holds the secret-bearing stream without a need. - if (!onCredential || tokenBytes) return; + // Observe a rejected code even if the CLI remains open waiting for Enter. + // Retain only the bounded private buffer; return a fixed failure reason. + if (tokenBytes || oauthError) return; tokenBuffer += chunk; + if (hasSetupTokenOAuthError(tokenBuffer)) { + oauthError = true; + tokenBuffer = ""; + controller.abort(); + return; + } captureCredential(); if (!tokenBytes && tokenBuffer.length > CLAUDE_SETUP_TOKEN_MAX_BUFFER_CHARS) { tokenBuffer = tokenBuffer.slice(tokenBuffer.length - CLAUDE_SETUP_TOKEN_MAX_BUFFER_CHARS); @@ -346,6 +354,7 @@ export async function runSetupTokenLogin( promptSurfaced, codeSubmitted, credentialDelivered, + ...(oauthError ? { failureReason: "oauth_error" as const } : {}), }); try { @@ -361,6 +370,11 @@ export async function runSetupTokenLogin( controller.abort(); await submitPromise; + if (oauthError) { + log("[paperclip] Setup-token login: the provider rejected the authorization code."); + return result("failure", null); + } + if (raced.kind === "timeout") { log("[paperclip] Setup-token login timed out; stopping the process."); return result("timeout", null); diff --git a/server/src/services/local-ai-browser-login.test.ts b/server/src/services/local-ai-browser-login.test.ts index 9bfdd7434ab..38a0d55f0a9 100644 --- a/server/src/services/local-ai-browser-login.test.ts +++ b/server/src/services/local-ai-browser-login.test.ts @@ -212,6 +212,27 @@ describe.skipIf(process.platform === "win32")("local browser subscription login" expect((await stat(path.join(home, ".credentials.json"))).mode & 0o777).toBe(0o600); }); + it("reports a rejected Claude code while the CLI waits for a terminal retry", async () => { + const url = "https://claude.com/cai/oauth/authorize?client_id=cid&code=abcdefgh&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&response_type=code&scope=user&state=0123456789abcdef"; + const home = await fakeCli("claude", [ + 'printf "Welcome to Claude Code\\nOpening browser to sign in…\\nBrowser didn\x27t open? Use the url below to sign in (c to copy)\\n"', + `printf '%s\\n' '${url}'`, + 'printf "Paste code here if prompted >\\n"', + 'read -r entered', + 'printf "OAuth error: Invalid code. Press Enter to retry.\\n"', + 'exec sleep 60', + ].join("\n")); + const login = startLocalBrowserLogin("anthropic", home); + try { + await vi.waitFor(() => expect(login.authorizationUrl).toBe(url), { timeout: 5000 }); + login.submitCode?.("fixture-code"); + await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5000 }); + expect(login.error).toContain("Claude rejected the authorization code"); + expect(login.error).not.toContain("fixture-code"); + await expect(readFile(path.join(home, ".credentials.json"))).rejects.toMatchObject({ code: "ENOENT" }); + } finally { login.abort(); } + }); + it("terminates the local provider process when sign-in is cancelled", async () => { const home = await fakeCli("codex", 'echo $$ > "$CODEX_HOME/login.pid"\nexec sleep 60'); const login = startLocalBrowserLogin("openai", home); diff --git a/server/src/services/local-ai-browser-login.ts b/server/src/services/local-ai-browser-login.ts index c657287494d..8ae0a0d54e0 100644 --- a/server/src/services/local-ai-browser-login.ts +++ b/server/src/services/local-ai-browser-login.ts @@ -120,7 +120,10 @@ export function startLocalBrowserLogin(provider: "anthropic" | "openai" | "googl await file.close(); } }, - }).then((result) => { state.outcome = result.outcome === "success" ? "success" : "failure"; }) + }).then((result) => { + state.outcome = result.outcome === "success" ? "success" : "failure"; + if (result.failureReason === "oauth_error") state.error = "Claude rejected the authorization code. Start sign-in again and use the code from the new sign-in tab."; + }) .catch(() => { state.outcome = "failure"; }); } else { void runDeviceLogin(driver, { diff --git a/tests/e2e/conference-room-typing-intro.spec.ts b/tests/e2e/conference-room-typing-intro.spec.ts index f6c8fc6e2d5..b759d5d9a15 100644 --- a/tests/e2e/conference-room-typing-intro.spec.ts +++ b/tests/e2e/conference-room-typing-intro.spec.ts @@ -56,7 +56,7 @@ async function installLaunchIntercepts(page: Page, baseURL?: string) { } /** Drive the wizard from the /onboarding route through to "Get started". */ -async function runOnboardingWizard(page: Page, companyName: string) { +async function runOnboardingWizard(page: Page, companyName: string, signIn?: { source: RegExp; complete: () => Promise }) { await page.goto("/onboarding"); // Launcher card path (existing companies) — enter the wizard if the @@ -84,19 +84,13 @@ async function runOnboardingWizard(page: Page, companyName: string) { // — the row is a question, not a confirmation — so the CTA is disabled until // a tile is pressed. By role rather than by label: which adapters the tiles // offer depends on the registry this environment reports. - const source = page.getByRole("radio").first(); + const source = signIn ? page.getByRole("radio", { name: signIn.source }) : page.getByRole("radio").first(); await source.waitFor({ timeout: 30_000 }); await source.click(); - // "Connect", not "Next": this step's button starts the sign-in where there - // is one to start, so it is named for what it does. This test simulates - // successful local account connection before the environment check and hire. - // - // Waited on for enabled rather than for visible: it is already on screen, - // disabled, and clicking a disabled button raises nothing and does nothing. - const connectNext = page.getByRole("button", { name: /^Connect$/ }); - await expect(connectNext).toBeEnabled({ timeout: 30_000 }); - await connectNext.click(); + // A verified account, or pasting its authorization code, continues + // automatically through the environment check and hire. + if (signIn) await signIn.complete(); // Step 5: review → Get started opens the standing chat. const getStarted = page.getByRole("button", { name: /Get started/ }); @@ -129,6 +123,39 @@ async function assertOnlyChatExists(page: Page, companyName: string) { } test.describe("Chat launch after onboarding wizard", () => { + test("pasting a Claude code connects automatically and continues onboarding", async ({ page, baseURL }) => { + await installLaunchIntercepts(page, baseURL); + let verified = false; + let submissions = 0; + await page.route("**/ai-connections/local/attempts", route => route.fulfill({ status: 201, json: { + sessionId: "00000000-0000-4000-8000-000000000001", expiresAt: "2099-01-01T00:00:00Z", + } })); + await page.route("**/ai-connections/local/check", route => route.fulfill({ json: verified + ? { status: "ready" } + : { status: "sign_in_required", authorizationUrl: "https://claude.ai/oauth/authorize?fixture=auto-paste" }, + })); + await page.route("**/ai-connections/local/attempts/*/code", async route => { + expect(route.request().postDataJSON()).toEqual({ browserCode: "fixture-authorization-code" }); + submissions++; + verified = true; + await route.fulfill({ json: { ok: true } }); + }); + const companyName = `E2E-ClaudePaste-${Date.now()}`; + await runOnboardingWizard(page, companyName, { source: /Claude/, complete: async () => { + const code = page.getByRole("textbox", { name: "Authorization code", exact: true }); + await expect(code).toBeVisible({ timeout: 20_000 }); + await expect(page.getByRole("button", { name: "Connect", exact: true })).toBeDisabled(); + await code.evaluate(input => { + const clipboardData = new DataTransfer(); + clipboardData.setData("text/plain", "fixture-authorization-code"); + input.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true })); + }); + await expect(page.getByRole("status").filter({ hasText: "Finishing sign-in" })).toBeVisible(); + } }); + expect(submissions).toBe(1); + await assertOnlyChatExists(page, companyName); + }); + test("opens chat without creating a task or project", async ({ page, baseURL }) => { await instrumentNavLog(page); await installLaunchIntercepts(page, baseURL); diff --git a/tests/e2e/helpers/onboarding-ai-connection.ts b/tests/e2e/helpers/onboarding-ai-connection.ts index 94c1abaadea..19ded418ea5 100644 --- a/tests/e2e/helpers/onboarding-ai-connection.ts +++ b/tests/e2e/helpers/onboarding-ai-connection.ts @@ -6,6 +6,12 @@ import { expect, type Page } from "@playwright/test"; export async function mockOnboardingLocalAiConnection(page: Page) { const connectionId = randomUUID(); const grantId = randomUUID(); + const sessionId = randomUUID(); + await page.route("**/ai-connections/local/attempts", route => route.fulfill({ status: 201, json: { + sessionId, expiresAt: "2099-01-01T00:00:00Z", + } })); + await page.route("**/ai-connections/local/check", route => route.fulfill({ json: { status: "ready" } })); + await page.route("**/ai-connections/local/attempts/*", route => route.fulfill({ json: { ok: true } })); await page.route("**/ai-connections/local", async (route) => { expect(route.request().method()).toBe("POST"); expect(route.request().postDataJSON()).toMatchObject({ method: "subscription", ownership: "personal" }); diff --git a/tests/e2e/planning-mode-visual-verification.spec.ts b/tests/e2e/planning-mode-visual-verification.spec.ts index 2b2bf18085e..785ae5a2b94 100644 --- a/tests/e2e/planning-mode-visual-verification.spec.ts +++ b/tests/e2e/planning-mode-visual-verification.spec.ts @@ -89,18 +89,10 @@ test("captures planning mode UI for desktop and mobile", async ({ page }) => { // The connect step arrives with no source selected — the tile row is a // question, not a confirmation — so its CTA stays disabled until one is - // pressed. It reads "Connect", not "Next": the button starts the sign-in - // where there is one to start. The test simulates successful local account - // connection, then exercises the real first-task creation flow. - // - // Waited on for enabled rather than visible: it is already on screen, and - // clicking a disabled button raises nothing and does nothing. + // pressed. The simulated verified account then advances automatically. const source = page.getByRole("radio").first(); await source.waitFor({ timeout: 30_000 }); await source.click(); - const connectNext = page.getByRole("button", { name: /^Connect$/ }); - await expect(connectNext).toBeEnabled({ timeout: 30_000 }); - await connectNext.click(); // The review step names the agent rather than the step. await expect( diff --git a/ui/src/components/AdapterLoginChrome.tsx b/ui/src/components/AdapterLoginChrome.tsx index 5d0d7e55d9f..634645eea47 100644 --- a/ui/src/components/AdapterLoginChrome.tsx +++ b/ui/src/components/AdapterLoginChrome.tsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState, type ReactNode } from "react"; +import { useEffect, useRef, useState, type ClipboardEvent, type ReactNode } from "react"; import { AnimatePresence, motion } from "motion/react"; import { Copy, Check, Loader2 } from "lucide-react"; @@ -371,7 +371,7 @@ export function OnboardingCardField({ value: string; onChange: (value: string) => void; onSubmit: () => void; - onPaste?: () => void; + onPaste?: (event: ClipboardEvent) => void; disabled?: boolean; label?: string; placeholder?: string; @@ -404,7 +404,7 @@ export function OnboardingCardField({ value={value} disabled={disabled} onChange={(event) => onChange(event.target.value)} - onPaste={() => onPaste?.()} + onPaste={onPaste} onKeyDown={(event) => { if (event.key === "Enter") { event.preventDefault(); @@ -497,31 +497,57 @@ export function LocalProviderLoginInstructions({ adapterType, login }: { const [showCommand, setShowCommand] = useState(false); const [browserCode, setBrowserCode] = useState(""); const [submitting, setSubmitting] = useState(false); + const [codeSubmitted, setCodeSubmitted] = useState(false); + const codeSubmissionRef = useRef(null); + useEffect(() => { + codeSubmissionRef.current = null; + setBrowserCode(""); + setSubmitting(false); + setCodeSubmitted(false); + }, [login?.authorizationUrl, login?.preparing]); const provider = adapterType === "antigravity_runtime" ? "Google Antigravity" : adapterType === "claude_local" ? "Claude Code" : adapterType === "grok_local" ? "Grok CLI" : "Codex CLI"; const isolated = login?.isolated ?? (adapterType === "codex_local" || adapterType === "grok_local"); const command = login?.command; const browserLogin = adapterType === "claude_local" || adapterType === "codex_local" || adapterType === "antigravity_runtime"; - async function submitBrowserCode() { - if (!browserCode.trim() || !login?.submitCode || submitting) return; + async function submitBrowserCode(value = browserCode) { + if (!value.trim() || !login?.submitCode || codeSubmissionRef.current) return; + const submission = Symbol(); + codeSubmissionRef.current = submission; setSubmitting(true); try { - await login.submitCode(browserCode.trim()); + await login.submitCode(value.trim()); + if (codeSubmissionRef.current !== submission) return; setBrowserCode(""); + setCodeSubmitted(true); } catch { // The login hook presents the request error beside the sign-in card. + if (codeSubmissionRef.current === submission) codeSubmissionRef.current = null; } finally { - setSubmitting(false); + if (codeSubmissionRef.current === submission || codeSubmissionRef.current === null) setSubmitting(false); } } + function pasteBrowserCode(event: ClipboardEvent) { + const pasted = event.clipboardData?.getData("text"); + if (!pasted?.trim()) return; + const input = event.currentTarget; + const start = input.selectionStart ?? input.value.length; + const end = input.selectionEnd ?? start; + const value = input.value.slice(0, start) + pasted + input.value.slice(end); + event.preventDefault(); + setBrowserCode(value); + void submitBrowserCode(value); + } if (login?.preparing) return

Preparing sign-in…

; const ready = login?.status === "ready"; + const awaitingBrowserSignIn = browserLogin && !ready && !login?.authorizationUrl && !login?.error; return
{ready ? <>

{login?.accountLabel ?? provider} is signed in. Click Connect to use this account.

{!showCommand && } : !browserLogin &&

{isolated ? `Sign in to ${provider} for this connection on the machine running Paperclip. Your existing terminal login stays separate.` : `Connect uses your local ${provider} account on the machine running Paperclip.`}

} - {browserLogin && !ready && !login?.authorizationUrl && !login?.error &&

Preparing browser sign-in…

} - {browserLogin && !ready && !login?.error && login?.authorizationUrl && Preparing browser sign-in…

} + {(submitting || codeSubmitted) && !ready && !login?.error &&

Finishing sign-in…

} + {browserLogin && !ready && !submitting && !codeSubmitted && !login?.error && login?.authorizationUrl && void submitBrowserCode()} disabled={submitting} /> @@ -544,6 +571,6 @@ export function LocalProviderLoginInstructions({ adapterType, login }: {
} } {login?.error &&

{login.error}

} - {login && !login.preparing && !ready && (isolated || login.error) && } + {login && !login.preparing && !ready && !awaitingBrowserSignIn && (isolated || login.error) && } ; } diff --git a/ui/src/components/OnboardingWizard.test.tsx b/ui/src/components/OnboardingWizard.test.tsx index 3fb8cf9c712..bc596d08f45 100644 --- a/ui/src/components/OnboardingWizard.test.tsx +++ b/ui/src/components/OnboardingWizard.test.tsx @@ -4548,6 +4548,23 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", ( } finally { await act(async () => root.unmount()); } }); + it.each(["claude_local", "codex_local"])("clears a stale Claude model when choosing an OpenAI subscription from %s", async adapterType => { + mockAdapterBuild.buildAdapterConfig.mockImplementation(values => buildCodexRunnerConfig(values!)); + managedApi.list.mockResolvedValue({ currentUserId: "user-1", connections: [{ + id: "openai-account", grantId: "openai-grant", companyId: "company-new", provider: "openai", + method: "subscription", ownership: "personal", ownerUserId: "user-1", status: "connected", isDefault: true, + }] } as never); + const { root } = await openStep4({ adapterType, model: "claude-opus-5-5" }); + try { + await pickSource(/OpenAI/); + await settle(); + expect(mockAdapterBuild.buildAdapterConfig).toHaveBeenCalledWith(expect.objectContaining({ adapterType: "codex_local", model: "" })); + expect(mockAgentsApi.testEnvironment).toHaveBeenCalledTimes(1); + const tested = mockAgentsApi.testEnvironment.mock.calls[0] as unknown as [string, string, { adapterConfig: Record }]; + expect(tested[2].adapterConfig.model).not.toBe("claude-opus-5-5"); + } finally { await act(async () => root.unmount()); } + }); + it.each(["environments", "settings", "policy"] as const)("does not use warm Claude discovery before %s resolves", async pending => { let finish!: (value: any) => void; const delayed = new Promise(resolve => { finish = resolve; }); @@ -4687,7 +4704,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", ( await pickSource(label); expect(document.body.textContent).toContain("Sign in to"); expect(document.body.textContent).not.toContain("Run this in a terminal"); - expect(button("Connect").disabled).toBe(false); + expect(button("Connect").disabled).toBe(true); await detected(); expectTesting(); // The saved account can become visible while its hello test is pending. @@ -4759,7 +4776,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", ( expect(mockAgentsApi.testEnvironment).not.toHaveBeenCalled(); expect(mockAgentsApi.hire).not.toHaveBeenCalled(); expect(document.body.textContent).toContain("Sign in to"); - expect(button("Connect").disabled).toBe(false); + expect(button("Connect").disabled).toBe(true); } finally { await act(async () => root.unmount()); } }); @@ -4855,12 +4872,17 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", ( } }); - it.each(providers)("keeps Connect usable when %s detection has not completed", async (adapterType, _provider, label) => { + it.each(providers)("waits for %s sign-in before allowing Connect or the keyboard shortcut", async (adapterType, _provider, label) => { const { root } = await openStep4({ adapterType }); try { await pickSource(label); expect(mockAgentsApi.testEnvironment).not.toHaveBeenCalled(); + expect(button("Connect").disabled).toBe(true); await click("Connect"); + await act(async () => document.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", metaKey: true, bubbles: true }))); + expect(managedApi.connectLocal).not.toHaveBeenCalled(); + expect(mockAgentsApi.testEnvironment).not.toHaveBeenCalled(); + await detected(); expect(managedApi.connectLocal).toHaveBeenCalledTimes(1); expect(mockAgentsApi.testEnvironment).toHaveBeenCalledTimes(1); expect(document.body.textContent).toContain("is ready to work!"); @@ -4935,7 +4957,7 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", ( } finally { await act(async () => root.unmount()); } }); - it("shows the Claude browser sign-in card and saves its connection before hiring", async () => { + it("automatically submits a pasted Claude code and saves the verified connection before hiring", async () => { localHealth.get.mockResolvedValue({ deploymentMode: "local_trusted" }); mockEnvironmentsApi.list.mockResolvedValue([LOCAL_ENVIRONMENT]); mockInstanceSettingsApi.get.mockResolvedValue({ defaultEnvironmentId: null }); @@ -4947,7 +4969,18 @@ describe("OnboardingWizard restore-gate (stale localStorage across accounts)", ( expect(mockAgentsApi.startClaudeSetupTokenLogin).not.toHaveBeenCalled(); const connect = [...document.body.querySelectorAll("button")].find(b => b.textContent?.trim().startsWith("Connect")); expect(connect).toBeTruthy(); - await act(async () => connect!.click()); + expect(connect!.disabled).toBe(true); + const code = document.body.querySelector('input[aria-label="Authorization code"]')!; + const paste = new Event("paste", { bubbles: true, cancelable: true }); + Object.defineProperty(paste, "clipboardData", { value: { getData: () => "fixture-authorization-code" } }); + await act(async () => code.dispatchEvent(paste)); + for (let i = 0; i < 4; i++) await flushReact(); + expect(managedApi.submitLocalLoginCode).toHaveBeenCalledWith("company-new", "local-attempt", "fixture-authorization-code"); + expect(managedApi.submitLocalLoginCode).toHaveBeenCalledTimes(1); + expect(document.body.textContent).toContain("Finishing sign-in"); + expect(managedApi.connectLocal).not.toHaveBeenCalled(); + managedApi.checkLocalLogin.mockResolvedValue({ status: "ready" }); + await act(async () => window.dispatchEvent(new Event("focus"))); for (let i = 0; i < 6; i++) await flushReact(); expect(managedApi.connectLocal).toHaveBeenCalledWith("company-new", expect.objectContaining({ provider: "anthropic", method: "subscription", ownership: "personal" })); expect(mockAgentsApi.hire).toHaveBeenCalled(); diff --git a/ui/src/components/OnboardingWizard.tsx b/ui/src/components/OnboardingWizard.tsx index ca2341d7bef..d74842a8279 100644 --- a/ui/src/components/OnboardingWizard.tsx +++ b/ui/src/components/OnboardingWizard.tsx @@ -1432,7 +1432,9 @@ function OnboardingWizardInner({ /** A sign-in is running and has not succeeded. */ const connectStepLoggingIn = - connectStepNeedsLogin && connectPhase !== "idle" && connectPhase !== "connecting"; + (connectStepNeedsLogin && connectPhase !== "idle" && connectPhase !== "connecting") || + (sourcePicked && canUseLocalLogin && credentialMode === "subscription" && !hasSavedSubscription && + !managedBindingForStep() && localLogin.status !== "ready"); // Detecting a credential is enough to start verification once the user has // chosen Claude or Codex. A saved-list refresh during that work is not a new @@ -1547,7 +1549,7 @@ function OnboardingWizardInner({ label: "Connect", icon: "arrow", disabled: - !connectStepReady || (credentialMode === "api" && !apiKey.trim() && !selectedApiKey && !restoredApiCredential && !managedBindingForStep()), + !connectStepReady || connectStepLoggingIn || (credentialMode === "api" && !apiKey.trim() && !selectedApiKey && !restoredApiCredential && !managedBindingForStep()), } : // Nothing is chosen on arrival, and the row is what chooses. Until // it has been answered the button has nothing to do. @@ -3038,9 +3040,11 @@ function OnboardingWizardInner({ setSourcePicked(true); setAdapterType(id); if (id !== adapterType) setRunner("auto"); - if (id !== adapterType) { + // Older drafts may already pair OpenAI with the Claude + // model retained by a previous source switch. + if (id !== adapterType || (id === "codex_local" && credentialMode === "subscription" && model.startsWith("claude-"))) { if (id === "opencode_local") setModel(DEFAULT_OPENCODE_LOCAL_MODEL); - else if (id !== "codex_local") setModel(""); + else setModel(""); } setConnectPhase("collapsing"); }} diff --git a/ui/src/components/ai-connections/useLocalAiLogin.test.tsx b/ui/src/components/ai-connections/useLocalAiLogin.test.tsx index d97385d3e1b..75e459924c5 100644 --- a/ui/src/components/ai-connections/useLocalAiLogin.test.tsx +++ b/ui/src/components/ai-connections/useLocalAiLogin.test.tsx @@ -43,6 +43,29 @@ it("checks once under StrictMode, preserves renaming and navigation, and cancels expect(api.cancelLocalLogin).toHaveBeenCalledTimes(1); expect(api.cancelLocalLogin.mock.invocationCallOrder[0]).toBeLessThan(api.startLocalLogin.mock.invocationCallOrder[1]); }); +it.each(["anthropic", "openai"] as const)("waits for the %s authorization card before offering to restart sign-in", async provider => { + api.checkLocalLogin.mockResolvedValue({ status: "sign_in_required" }); + flushSync(() => root.render()); + await vi.waitFor(() => expect(host.textContent).toContain("Preparing browser sign-in")); + expect(host.textContent).not.toContain("Start sign-in again"); + expect(api.startLocalLogin).toHaveBeenCalledTimes(1); + + api.checkLocalLogin.mockResolvedValue({ status: "sign_in_required", authorizationUrl: "https://example.test/authorize", code: "ABCD-12345" }); + window.dispatchEvent(new Event("focus")); + await vi.waitFor(() => expect(host.querySelector('a[href="https://example.test/authorize"]')).not.toBeNull()); + if (provider === "anthropic") expect(host.querySelector('input[aria-label="Authorization code"]')).not.toBeNull(); + else expect(host.textContent).toContain("ABCD-12345"); + const retry = Array.from(host.querySelectorAll("button")).find(button => button.textContent === "Start sign-in again"); + expect(retry).toBeTruthy(); + + api.checkLocalLogin.mockResolvedValue({ status: "sign_in_required" }); + flushSync(() => retry!.click()); + await vi.waitFor(() => expect(api.startLocalLogin).toHaveBeenCalledTimes(2)); + await vi.waitFor(() => expect(host.textContent).toContain("Preparing browser sign-in")); + expect(host.textContent).not.toContain("Start sign-in again"); + expect(api.cancelLocalLogin).toHaveBeenCalledTimes(1); +}); + it.each(["anthropic", "openai"] as const)("detects an already-signed-in %s account before showing instructions, and does not save it until Connect", async provider => { api.checkLocalLogin.mockResolvedValue({ status: "ready" }); flushSync(() => root.render()); @@ -92,9 +115,41 @@ it("submits a Claude browser code through the owned local attempt", async () => }); flushSync(() => Array.from(host.querySelectorAll("button")).find((button) => button.textContent === "Submit code")?.click()); await vi.waitFor(() => expect(api.submitLocalLoginCode).toHaveBeenCalledWith("company", "attempt-1", "fixture-code")); + await vi.waitFor(() => expect(host.textContent).toContain("Finishing sign-in")); + expect(host.querySelector('input[aria-label="Authorization code"]')).toBeNull(); expect(host.textContent).not.toContain("claude auth login"); }); +it("submits a pasted Claude code once and waits for verification without another click", async () => { + let finishSubmit!: () => void; + api.submitLocalLoginCode.mockReturnValue(new Promise(resolve => { finishSubmit = resolve; })); + api.checkLocalLogin.mockResolvedValue({ status: "sign_in_required", authorizationUrl: "https://claude.ai/oauth/authorize?client_id=test" }); + flushSync(() => root.render()); + await vi.waitFor(() => expect(host.querySelector('input[aria-label="Authorization code"]')).not.toBeNull()); + const input = host.querySelector('input[aria-label="Authorization code"]') as HTMLInputElement; + flushSync(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "old-code"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + expect(api.submitLocalLoginCode).not.toHaveBeenCalled(); + input.select(); + const paste = () => { + const event = new Event("paste", { bubbles: true, cancelable: true }); + Object.defineProperty(event, "clipboardData", { value: { getData: () => " pasted-code#state\n" } }); + input.dispatchEvent(event); + }; + flushSync(() => { paste(); paste(); }); + await vi.waitFor(() => expect(api.submitLocalLoginCode).toHaveBeenCalledWith("company", "attempt-1", "pasted-code#state")); + expect(api.submitLocalLoginCode).toHaveBeenCalledTimes(1); + expect(host.textContent).toContain("Finishing sign-in"); + expect(host.querySelector('input[aria-label="Authorization code"]')).toBeNull(); + expect(api.connectLocal).not.toHaveBeenCalled(); + finishSubmit(); + api.checkLocalLogin.mockResolvedValue({ status: "ready" }); + window.dispatchEvent(new Event("focus")); + await vi.waitFor(() => expect(host.textContent).toContain("is signed in")); +}); + it("hides a failed device prompt and lets the user restart sign-in", async () => { api.checkLocalLogin.mockResolvedValue({ status: "sign_in_required", authorizationUrl: "https://auth.openai.com/codex/device", code: "OLD-CODE", error: "Sign-in ended. Start sign-in again." }); flushSync(() => root.render());