Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(spaces): sign-in that never comes back offers a code (CUA-2291) (#5950)

cua-agents[bot]3cc240d9f2f2
diff --git a/apps/cua-spaces-desktop/src/bridge/session.ts b/apps/cua-spaces-desktop/src/bridge/session.ts
index 9a7ac1b64d..a282d42b7c 100644
--- a/apps/cua-spaces-desktop/src/bridge/session.ts
+++ b/apps/cua-spaces-desktop/src/bridge/session.ts
@@ -25,8 +25,9 @@ export function sessionMethods({ model }: BridgeContext): Handlers {
"session.get": () => sessionState(model),
// The browser flow can take minutes: answer now, and `session.changed`
// follows when it ends.
- "session.signIn": () => {
- void model.beginSignIn();
+ "session.signIn": (args) => {
+ // `code`: the page's "Get a code instead" (the browser never got back to the app).
+ void model.beginSignIn(args && (args as { code?: unknown }).code === true ? { code: true } : undefined);
return sessionState(model);
},
"session.signOut": async () => {
diff --git a/apps/cua-spaces-desktop/src/model/app-model.ts b/apps/cua-spaces-desktop/src/model/app-model.ts
index 3c716321c9..2fb9b291e9 100644
--- a/apps/cua-spaces-desktop/src/model/app-model.ts
+++ b/apps/cua-spaces-desktop/src/model/app-model.ts
@@ -47,7 +47,7 @@ import { NotchActivity } from "./activity";
import { createErrorVariant, daemonAnswered, isCancelled, sdkErrorKind, words } from "./errors";
import type { HostModel } from "./host";
import { KeyvaultModel } from "./keyvault";
-import type { AccountRunning, TelemetryRunning } from "./services";
+import type { AccountRunning, SignInOptions, TelemetryRunning } from "./services";
import type { StartupModel } from "./startup";
import { SignInRuns, type SignInEnd } from "./sign-in";
import { SpaceThumbnails } from "./thumbnails";
@@ -908,9 +908,9 @@ export class AppModel {
/** "Sign in": the browser flow (opened by the account), the code while it
* waits. Starting again while it waits is a retry: a new attempt, and
* whichever attempt the browser finishes signs the app in. */
- async beginSignIn(): Promise<void> {
+ async beginSignIn(opts?: SignInOptions): Promise<void> {
if (!this.account || this.signInPhase() === "Starting") return;
- await this.signIns.begin();
+ await this.signIns.begin(opts);
}
/** A session is stored (by a sign-in here or `cua auth login`). */
diff --git a/apps/cua-spaces-desktop/src/model/pending.ts b/apps/cua-spaces-desktop/src/model/pending.ts
index 37fc95d6dc..3133d9bdd8 100644
--- a/apps/cua-spaces-desktop/src/model/pending.ts
+++ b/apps/cua-spaces-desktop/src/model/pending.ts
@@ -18,7 +18,7 @@ import type {
} from "../native/generated/index";
import type { LiveSpacesBackend, SpacesBackend } from "./backend";
import type { AgentSetupRunning } from "./agents";
-import type { AccountProfile, AccountRunning, SignInAttempt } from "./services";
+import type { AccountProfile, AccountRunning, SignInAttempt, SignInOptions } from "./services";
/** A value set once, which callers wait for. */
export class LiveGate<T> {
@@ -143,10 +143,10 @@ export class PendingAccount implements AccountRunning {
return this.gate.current?.account?.profile() ?? null;
}
- async beginSignIn(): Promise<SignInAttempt> {
+ async beginSignIn(opts?: SignInOptions): Promise<SignInAttempt> {
const account = (await this.gate.wait()).account;
if (!account) throw new NotStarted("Signing in");
- return account.beginSignIn();
+ return account.beginSignIn(opts);
}
async signOut(): Promise<void> {
diff --git a/apps/cua-spaces-desktop/src/model/services.ts b/apps/cua-spaces-desktop/src/model/services.ts
index ab23ce1395..9bfe784d77 100644
--- a/apps/cua-spaces-desktop/src/model/services.ts
+++ b/apps/cua-spaces-desktop/src/model/services.ts
@@ -17,6 +17,12 @@ export interface SignInAttempt {
wait(): Promise<string | null>;
}
+/** How a sign-in starts. */
+export interface SignInOptions {
+ /** The code flow: the person enters a code on any device, so it works when the browser cannot reach this app (a blocked loopback, another browser, a phone). */
+ code?: boolean;
+}
+
/** The signed-in account's claims, for the presence name and id. */
export interface AccountProfile {
name?: string;
@@ -30,8 +36,9 @@ export interface AccountRunning {
/** The signed-in identity, read without network access. */
identity(): string | null;
profile(): AccountProfile | null;
- /** Starts a sign-in (opens the browser). */
- beginSignIn(): Promise<SignInAttempt>;
+ /** Starts a sign-in (opens the browser). `code`: with a code to enter on any
+ * device, for when the browser's own way back to the app does not work. */
+ beginSignIn(opts?: SignInOptions): Promise<SignInAttempt>;
signOut(): Promise<void>;
/** The account's token (`force`: refresh it); null when signed out. */
accessToken(force: boolean): Promise<string | null>;
@@ -69,8 +76,8 @@ export class LiveAccount implements AccountRunning {
* box with no browser), the device flow instead, as `cua auth login
* --remote` does: its page opens on any device, with the code the page
* shows. */
- async beginSignIn(): Promise<SignInAttempt> {
- let attempt = await this.auth.beginLogin(undefined);
+ async beginSignIn(opts?: SignInOptions): Promise<SignInAttempt> {
+ let attempt = await this.auth.beginLogin(opts?.code ? "device" : undefined);
const opened = attempt.url() ? await this.openUrl(attempt.url()) : false;
if (!opened && attempt.method() === "browser") attempt = await this.auth.beginLogin("device");
const url = attempt.url();
diff --git a/apps/cua-spaces-desktop/src/model/sign-in.ts b/apps/cua-spaces-desktop/src/model/sign-in.ts
index f5b17cedea..e0076f4eea 100644
--- a/apps/cua-spaces-desktop/src/model/sign-in.ts
+++ b/apps/cua-spaces-desktop/src/model/sign-in.ts
@@ -8,7 +8,7 @@
// finished after all, or another sign-in on this machine (`cua auth login`).
// The account's session is read again while a sign-in waits, so a session
// that appears ends the wait even when no attempt's wait returns.
-import type { AccountRunning, SignInAttempt } from "./services";
+import type { AccountRunning, SignInAttempt, SignInOptions } from "./services";
/** Why a run ended without a session: the error it caught (the core reads
* its case and words), or the browser never confirmed in time. */
@@ -39,7 +39,7 @@ export class SignInRuns {
) {}
/** Starts an attempt (superseding one in progress) and resolves once it ends. */
- async begin(): Promise<void> {
+ async begin(opts?: SignInOptions): Promise<void> {
const account = this.account();
if (!account) return;
const current = ++this.attempt;
@@ -47,7 +47,7 @@ export class SignInRuns {
this.watchStore(account, current);
let attempt: SignInAttempt;
try {
- attempt = await account.beginSignIn();
+ attempt = await account.beginSignIn(opts);
} catch (error) {
if (current === this.attempt) this.fail({ error });
return;
diff --git a/apps/cua-spaces-desktop/test/sign-in-runs.test.ts b/apps/cua-spaces-desktop/test/sign-in-runs.test.ts
index 2c3e15e86d..8c68e9d875 100644
--- a/apps/cua-spaces-desktop/test/sign-in-runs.test.ts
+++ b/apps/cua-spaces-desktop/test/sign-in-runs.test.ts
@@ -7,11 +7,13 @@
// a session stored while it waits ends the wait even when no wait returns.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SignInRuns, type SignInEnd, type SignInView } from "../src/model/sign-in";
-import type { AccountProfile, AccountRunning, SignInAttempt } from "../src/model/services";
+import type { AccountProfile, AccountRunning, SignInAttempt, SignInOptions } from "../src/model/services";
/** Each sign-in is an attempt of its own (a loopback port), finished or failed by the test. */
class RetryAccount implements AccountRunning {
stored: string | null = null;
+ /** The options each start was given. */
+ readonly starts: unknown[] = [];
readonly attempts: { url: string; finish(who: string): void; fail(e: Error): void }[] = [];
identity() {
return this.stored;
@@ -19,7 +21,8 @@ class RetryAccount implements AccountRunning {
profile(): AccountProfile | null {
return null;
}
- async beginSignIn(): Promise<SignInAttempt> {
+ async beginSignIn(opts?: SignInOptions): Promise<SignInAttempt> {
+ this.starts.push(opts);
const url = `http://127.0.0.1:${50000 + this.attempts.length}/callback`;
let finish!: (who: string) => void;
let fail!: (e: Error) => void;
@@ -60,6 +63,20 @@ describe("a retried sign-in", () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
+ it("starts with a code when the page asks for one (the browser never got back), then signs in", async () => {
+ const account = new RetryAccount();
+ const { seen, v } = view();
+ const runs = new SignInRuns(() => account, v);
+ void runs.begin();
+ await flush();
+ const byCode = runs.begin({ code: true });
+ await flush();
+ expect(account.starts).toEqual([undefined, { code: true }]);
+ account.attempts[1]!.finish("[email protected]");
+ await byCode;
+ expect(seen).toMatchObject({ phase: "idle", identity: "[email protected]", signedIn: 1 });
+ });
+
it("finishes on the retry's attempt, and the first attempt's failure stays quiet", async () => {
const account = new RetryAccount();
const { seen, v } = view();
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
index 30f4424651..1de6975fee 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
@@ -123,6 +123,8 @@ public final class AppModel {
public var signInTimeout: Duration = .seconds(600)
/// Tells one sign-in from the next (a timeout of an old one is ignored).
private var signInAttempt = 0
+ /// The attempt in progress asked for a code instead of the browser's way back.
+ private var signInByCode = false
public private(set) var telemetryInput: AppTelemetryInput?
/// The account's Cua Cloud billing (Settings, Billing), once read.
public private(set) var billingStatus: AppBillingStatus?
@@ -1427,11 +1429,19 @@ public final class AppModel {
await runSignIn(current)
}
+ /// "Get a code instead": a code to enter on any device, for when the
+ /// browser never gets back to the app.
+ public func beginSignIn(code: Bool) async {
+ guard let current = startSignIn(code: code) else { return }
+ await runSignIn(current)
+ }
+
/// Marks a sign-in as starting, now (the web page reads it at once), and
/// returns its attempt; nil when one is already starting.
@discardableResult
- public func startSignIn() -> Int? {
+ public func startSignIn(code: Bool = false) -> Int? {
guard account != nil, signIn != .starting else { return nil }
+ signInByCode = code
signIn = .starting
signInURL = nil
signInAttempt += 1
@@ -1443,7 +1453,7 @@ public final class AppModel {
func runSignIn(_ current: Int) async {
guard let account else { return }
do {
- let attempt = try await account.beginSignIn()
+ let attempt = signInByCode ? try await account.beginSignIn(code: true) : try await account.beginSignIn()
// Cancelled, retried or signed in while it started.
guard signInAttempt == current, signIn == .starting else { return }
signIn = .waiting(userCode: attempt.userCode, opened: attempt.opened)
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
index 8257f4c2e8..be9b716f15 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
@@ -303,11 +303,17 @@ public protocol AccountRunning: AnyObject, Sendable {
func profile() -> AccountProfile?
/// Starts a sign-in (opens the browser).
func beginSignIn() async throws -> SignInAttempt
+ /// Starts a sign-in with a code to enter on any device (`code`), for when
+ /// the browser cannot get back to the app. Accounts without a code flow
+ /// start the usual sign-in.
+ func beginSignIn(code: Bool) async throws -> SignInAttempt
/// Signs out.
func signOut() async throws
}
extension AccountRunning {
+ public func beginSignIn(code: Bool) async throws -> SignInAttempt { try await beginSignIn() }
+
/// Accounts that only know a display identity: an email or a username.
public func profile() -> AccountProfile? {
identity().map { $0.contains("@") ? AccountProfile(email: $0) : AccountProfile(username: $0) }
@@ -334,10 +340,12 @@ public final class LiveAccount: AccountRunning, @unchecked Sendable {
return AccountProfile(name: i.name, email: i.email, username: i.username, subject: i.subject)
}
- public func beginSignIn() async throws -> SignInAttempt {
+ public func beginSignIn() async throws -> SignInAttempt { try await beginSignIn(code: false) }
+
+ public func beginSignIn(code: Bool) async throws -> SignInAttempt {
// The browser's sign-in page says where to go back to (the SDK reads it).
setenv("CUA_AUTH_RETURN_TO", "Cua Spaces", 0)
- var attempt = try await auth.beginLogin(flow: nil)
+ var attempt = try await auth.beginLogin(flow: code ? "device" : nil)
var opened = await Self.open(attempt.url())
// No browser opened: the loopback redirect would never come back,
// so use a code that can be confirmed on any device instead.
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift
index ef6e64bcc5..f7d195fa5c 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppStartup.swift
@@ -697,6 +697,10 @@ public final class PendingAccount: AccountRunning, @unchecked Sendable {
guard let account = await gate.wait().account else { throw NotStarted(what: "Signing in") }
return try await account.beginSignIn()
}
+ public func beginSignIn(code: Bool) async throws -> SignInAttempt {
+ guard let account = await gate.wait().account else { throw NotStarted(what: "Signing in") }
+ return try await account.beginSignIn(code: code)
+ }
public func signOut() async throws { try await gate.wait().account?.signOut() }
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
index 8fb5730f7f..48f21dec09 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
@@ -265,7 +265,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
// The browser flow can take minutes: answer now (already
// "starting", so an earlier failure never reads as this one's),
// and `session.changed` follows each step until it ends.
- if let current = model.startSignIn() {
+ // `code`: the page's "Get a code instead" (the browser never got back to the app).
+ if let current = model.startSignIn(code: (args["code"] as? Bool) == true) {
Task { @MainActor in await model.runSignIn(current) }
}
return session()
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
index 2dc3bff168..3d36f7620f 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
@@ -460,6 +460,27 @@ struct ViewModelTests {
#expect(steps(telemetry) == ["signed_in"])
}
+ /// "Get a code instead": a sign-in that never came back from the browser
+ /// restarts with a code, and the account is asked for exactly that.
+ @Test func aSignInThatNeverComesBackCanRestartWithACode() async throws {
+ let account = CodeAskingAccount()
+ let model = makeModel(account: account)
+ let first = Task { await model.beginSignIn() }
+ try await waitUntil { account.starts == [false] }
+ first.cancel()
+ model.cancelSignIn()
+ let byCode = Task { await model.beginSignIn(code: true) }
+ try await waitUntil { account.starts == [false, true] }
+ try await waitUntil { if case .waiting = model.signIn { true } else { false } }
+ guard case let .waiting(userCode, _) = model.signIn else {
+ Issue.record("expected a waiting sign-in, got \(model.signIn)")
+ return
+ }
+ #expect(userCode == "ABCD-EFGH")
+ byCode.cancel()
+ model.cancelSignIn()
+ }
+
/// A sign-in that never finishes: Cancel stops it, a timeout fails it,
/// and each counts by its kind only (never the message).
@Test func aStuckSignInCanBeCancelledAndTimesOut() async throws {
@@ -1569,6 +1590,23 @@ final class StuckAccount: AccountRunning, @unchecked Sendable {
func signOut() async throws {}
}
+/// An account that says which way each sign-in started.
+final class CodeAskingAccount: AccountRunning, @unchecked Sendable {
+ private let lock = NSLock()
+ private var _starts: [Bool] = []
+ var starts: [Bool] { lock.withLock { _starts } }
+ func identity() -> String? { nil }
+ func beginSignIn() async throws -> SignInAttempt { try await beginSignIn(code: false) }
+ func beginSignIn(code: Bool) async throws -> SignInAttempt {
+ lock.withLock { _starts.append(code) }
+ return SignInAttempt(userCode: code ? "ABCD-EFGH" : nil, url: URL(string: "https://cua.ai/device"), opened: true) {
+ try await Task.sleep(for: .seconds(3600))
+ return nil
+ }
+ }
+ func signOut() async throws {}
+}
+
/// An account whose sign-in fails with `error`, while starting or while
/// waiting for the browser.
final class FailingAccount: AccountRunning, @unchecked Sendable {
diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
index 85e16bcd07..9d03ec7778 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
@@ -634,8 +634,8 @@ export function createWebkitAdapter(
const [s, onboarding] = await Promise.all([request<WkSession>("session.get"), request<WkOnboarding>("onboarding.get").catch(() => null)]);
return toSessionSnapshot(s, onboarding);
},
- "session.signIn": async () => {
- const s = await request<WkSession>("session.signIn");
+ "session.signIn": async (args) => {
+ const s = await request<WkSession>("session.signIn", args?.code ? { code: true } : {});
const userCode = typeof s.signIn === "object" ? opt(s.signIn.userCode) : undefined;
return { method: userCode ? "device" : "browser", userCode, verificationUri: opt(s.signInUrl) ?? "" };
},
diff --git a/apps/cua-spaces-web/src/bridge/hooks.ts b/apps/cua-spaces-web/src/bridge/hooks.ts
index 3f9839999c..a7cffd16c1 100644
--- a/apps/cua-spaces-web/src/bridge/hooks.ts
+++ b/apps/cua-spaces-web/src/bridge/hooks.ts
@@ -315,7 +315,7 @@ export interface SessionHook extends Resource<SessionData> {
refresh(): Promise<void>;
/** Starts the browser sign-in; `session.signIn` tracks it until the host
* reports signed in (or failed). */
- signIn(): Promise<SignInStart>;
+ signIn(opts?: { code?: boolean }): Promise<SignInStart>;
/** Stops waiting for the browser. */
cancelSignIn(): void;
signOut(): Promise<void>;
@@ -329,7 +329,7 @@ export function useSession(): SessionHook {
const run = useAction();
return {
...r,
- signIn: () => run((s) => s.signIn()),
+ signIn: (opts) => run((s) => s.signIn(opts)),
cancelSignIn: () => void run((s) => s.cancelSignIn()),
signOut: () => run((s) => s.signOut()),
completeOnboarding: (mode, launchAtLogin) => run((s) => s.completeOnboarding(mode, launchAtLogin)),
diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.ts
index 27b58d3327..00a1ad64b2 100644
--- a/apps/cua-spaces-web/src/bridge/protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/protocol.ts
@@ -259,7 +259,7 @@ export interface HostOperations
"keyvault.revokeGrant": { args: { id: string }; result: number };
"session.get": { args: Record<string, never>; result: SessionSnapshot };
- "session.signIn": { args: Record<string, never>; result: SignInStart };
+ "session.signIn": { args: { code?: boolean }; result: SignInStart };
"session.signOut": { args: Record<string, never>; result: null };
/** `launchAtLogin`: Done's checkbox, where the host draws it (Electron). */
"session.completeOnboarding": { args: { mode: OnboardingMode; launchAtLogin?: boolean }; result: null };
diff --git a/apps/cua-spaces-web/src/bridge/store.ts b/apps/cua-spaces-web/src/bridge/store.ts
index 24d7ecee75..2f151b60c5 100644
--- a/apps/cua-spaces-web/src/bridge/store.ts
+++ b/apps/cua-spaces-web/src/bridge/store.ts
@@ -196,8 +196,9 @@ export interface StoreOptions {
}
/** A device code lives about this long; a sign-in still waiting after it
- * will not finish. */
-const SIGN_IN_TIMEOUT_MS = 10 * 60_000;
+ * will not finish. A native host ends its own wait at 10 minutes and says
+ * why; this safety net comes after it, so one failure is counted once. */
+const SIGN_IN_TIMEOUT_MS = 11 * 60_000;
const CREATE_TICK_MS = 1_000;
/** How often a watched run is read while a turn runs, and while it waits. */
@@ -261,6 +262,8 @@ export class BridgeStore {
private agentsPending: string[] = [];
private signInUrl: string | null = null;
private signInTimer: ReturnType<typeof setTimeout> | undefined;
+ /** The sign-in in progress asked for a code instead of the browser's way back. */
+ private signInByCode = false;
/** Counts `session.signIn` answers: a session read started before the
* latest one says nothing about it (an earlier attempt's failure). */
private signInEpoch = 0;
@@ -961,16 +964,21 @@ export class BridgeStore {
// The host's sign-in failed (the browser never confirmed, the network
// dropped, the keychain refused): say why now, never keep waiting.
if (failure) {
- this.signInFailed({
- kind: "failed",
- reason: (failure.reason as SignInFailure) || "unknown",
- message: failure.message,
- detail: failure.detail,
- });
+ this.signInFailed(
+ {
+ kind: "failed",
+ reason: (failure.reason as SignInFailure) || "unknown",
+ message: failure.message,
+ detail: failure.detail,
+ },
+ true,
+ );
return;
}
if (!waiting) return;
if (waiting.url) this.signInUrl = waiting.url;
+ // The host fell back to a code (no browser, or its way back is blocked).
+ if (waiting.userCode) this.signInByCode = true;
const opened = waiting.opened !== false;
if (this.signInPhase.kind === "waiting" && (this.signInPhase.userCode ?? null) === waiting.userCode && (this.signInPhase.opened ?? true) === opened) return;
this.signInPhase = { kind: "waiting", userCode: waiting.userCode, opened };
@@ -982,15 +990,22 @@ export class BridgeStore {
this.publishSettings();
}
- async signIn(): Promise<SignInStart> {
+ /** `code`: sign in with a code to enter on any device, for when the
+ * browser never gets back to the app. */
+ async signIn(opts: { code?: boolean } = {}): Promise<SignInStart> {
this.stopSignInTimer();
+ this.signInByCode = opts.code === true;
+ if (opts.code) this.trackFeature("sign_in_code_instead");
this.setSignIn({ kind: "starting" });
try {
- const start = await this.adapter.call("session.signIn", {});
+ const start = await this.adapter.call("session.signIn", opts.code ? { code: true } : {});
this.signInEpoch += 1;
// Cancelled while it started: leave it.
if (this.signInPhase.kind !== "starting") return start;
this.signInUrl = start.verificationUri || null;
+ // The way it actually runs: a code when the host gave one (also its own fallback).
+ this.signInByCode = Boolean(start.userCode) || start.method === "device" || opts.code === true;
+ this.trackFeature(this.signInByCode ? "sign_in_started_code" : "sign_in_started_browser");
this.setSignIn({ kind: "waiting", userCode: start.userCode ?? null });
this.signInTimer = setTimeout(() => {
if (this.signInPhase.kind === "waiting") this.signInFailed(signInFailedPhase(this.core, "notConfirmed"));
@@ -1014,12 +1029,19 @@ export class BridgeStore {
/** A sign-in failed: shown with its reason, and counted by its kind
* (never its words). */
- private signInFailed(phase: FailedPhase): void {
+ private signInFailed(phase: FailedPhase, counted = false): void {
this.stopSignInTimer();
- void this.telemetry.track(telemetrySignInFailure(this.core, phase.reason ?? "unknown"));
+ // The reason's kind, and the way it was tried (browser or code). A host
+ // that ran the sign-in has counted the reason itself.
+ if (!counted) void this.telemetry.track(telemetrySignInFailure(this.core, phase.reason ?? "unknown"));
+ this.trackFeature(this.signInByCode ? "sign_in_failed_code" : "sign_in_failed_browser");
this.setSignIn(phase);
}
+ private trackFeature(feature: string): void {
+ void this.telemetry.track([{ type: "feature", feature }]);
+ }
+
private stopSignInTimer(): void {
if (this.signInTimer) clearTimeout(this.signInTimer);
this.signInTimer = undefined;
diff --git a/apps/cua-spaces-web/src/components/__tests__/sidebar-signin.test.tsx b/apps/cua-spaces-web/src/components/__tests__/sidebar-signin.test.tsx
index ea9e8aea70..daf907ac4d 100644
--- a/apps/cua-spaces-web/src/components/__tests__/sidebar-signin.test.tsx
+++ b/apps/cua-spaces-web/src/components/__tests__/sidebar-signin.test.tsx
@@ -1,8 +1,8 @@
// SPDX-License-Identifier: FSL-1.1-MIT
// Copyright (c) 2026 Cua AI, Inc.
-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { afterEach, describe, expect, it } from "vitest";
+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { BridgeProvider } from "@/bridge";
import type { DataAdapter } from "@/bridge/adapter";
@@ -12,7 +12,10 @@ import { AccountFooter } from "@/components/shell/sidebar";
import { ToastProvider } from "@/components/ui/toast";
import { testCore } from "@/bridge/__tests__/testCore";
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
/** A signed-out demo host whose browser sign-in waits (as a real one does). */
function host() {
@@ -156,3 +159,52 @@ describe("a sign-in that fails (it never fails silently)", () => {
expect(who.textContent).toMatch(/^Signed in as \S+/);
});
});
+
+/** A host whose browser sign-in never comes back (another browser, a blocked
+ * connection); a code request is answered with a code. Records every start. */
+function stuckBrowserHost() {
+ const base = createDemoAdapter({ latencyMs: 0, signedIn: false, onboarded: true });
+ const starts: Record<string, unknown>[] = [];
+ const adapter = Object.assign(Object.create(base) as DataAdapter, {
+ call: ((op: string, args: Record<string, unknown>) => {
+ if (op === "session.signIn") {
+ starts.push(args);
+ return Promise.resolve(
+ args.code
+ ? { method: "device", verificationUri: "https://cua.ai/device", userCode: "WXYZ-1234" }
+ : { method: "browser", verificationUri: "https://auth.cua.ai/login" },
+ );
+ }
+ return (base.call as (o: string, a: unknown) => Promise<unknown>).call(base, op, args);
+ }) as DataAdapter["call"],
+ });
+ return { adapter, starts };
+}
+
+describe("a browser sign-in that never comes back", () => {
+ it("offers a code after a while, in plain words, and starts the code sign-in", async () => {
+ const { adapter, starts } = stuckBrowserHost();
+ render(
+ <BridgeProvider adapter={adapter} core={unavailableCore("test: no core")}>
+ <AccountFooter />
+ </BridgeProvider>,
+ );
+ const signInButton = await screen.findByRole("button", { name: "Sign in" });
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ fireEvent.click(signInButton);
+ await screen.findByRole("status");
+ // Not at once: the person may still be signing in.
+ expect(document.querySelector("[data-signin-stuck]")).toBeNull();
+ await act(async () => {
+ vi.advanceTimersByTime(46_000);
+ });
+ vi.useRealTimers();
+ const stuck = (await waitFor(() => document.querySelector("[data-signin-stuck]") ?? Promise.reject(new Error("not yet")))) as Element;
+ expect(stuck.textContent).toContain("Still waiting?");
+ fireEvent.click(screen.getByText("Get a code instead"));
+ await waitFor(() => expect(starts).toEqual([{}, { code: true }]));
+ await waitFor(() => expect(document.querySelector("[data-signin=waiting]")?.textContent).toContain("Code WXYZ-1234"));
+ // With a code on screen there is nothing more to offer.
+ expect(document.querySelector("[data-signin-stuck]")).toBeNull();
+ });
+});
diff --git a/apps/cua-spaces-web/src/components/shell/sidebar.tsx b/apps/cua-spaces-web/src/components/shell/sidebar.tsx
index e22628c3ff..ec001f38c5 100644
--- a/apps/cua-spaces-web/src/components/shell/sidebar.tsx
+++ b/apps/cua-spaces-web/src/components/shell/sidebar.tsx
@@ -9,7 +9,7 @@ import { Loader2Icon, LogOutIcon, TriangleAlertIcon } from "lucide-react";
import type { SignInFooter, Space } from "@/bridge";
import { spokenName } from "@/bridge/space-names";
-import { signInFooter, useBridge, useMachines, useNotifications, useRelayUsageView, useSession, useSpaces, useTrackPlanClick } from "@/bridge";
+import { signInFooter, useBridge, useFeatureRecorded, useMachines, useNotifications, useRelayUsageView, useSession, useSpaces, useTrackPlanClick } from "@/bridge";
import { CuaKey } from "@/components/cua-key";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/ui/toast";
@@ -135,6 +135,13 @@ export function AccountFooter() {
})
: null;
useSignInFailureToast(footer);
+ // A browser sign-in that has not come back for a while: offer a code.
+ const waitingOnBrowser = footer?.state === "waiting" && !footer.code;
+ const stuck = useAfter(waitingOnBrowser, STILL_WAITING_MS);
+ useFeatureRecorded("sign_in_still_waiting", stuck);
+ // The last attempt used a code: another code would not help.
+ const triedCode = useRef(false);
+ if (footer?.state === "waiting" && footer.code) triedCode.current = true;
if (!session || !footer) return <div className="mt-auto h-12 border-t" />;
const unfinished = !session.onboarding.completed;
@@ -143,8 +150,15 @@ export function AccountFooter() {
// A failure is shown here with its reason (and the toast): nothing to add.
const startSignIn = () => {
setDetails(false);
+ triedCode.current = false;
void signIn().catch(() => {});
};
+ // For when the browser never gets back to the app (another browser, a
+ // blocked connection): a code to type on any device.
+ const startWithCode = () => {
+ setDetails(false);
+ void signIn({ code: true }).catch(() => {});
+ };
const identity = footer.identity || (session.signedIn ? "Signed in" : null);
return (
@@ -224,6 +238,14 @@ export function AccountFooter() {
</button>
) : null}
</div>
+ {stuck ? (
+ <div className="mt-1.5 pl-5.5 text-2xs text-muted-foreground" data-signin-stuck="">
+ <p>Still waiting? If the page won&apos;t finish, get a code and sign in from any browser or phone.</p>
+ <button type="button" className="mt-0.5 underline underline-offset-2 hover:text-foreground" onClick={startWithCode} data-signin-code="">
+ Get a code instead
+ </button>
+ </div>
+ ) : null}
{/* No browser opened: the page, to copy to any device. */}
{session.signIn.kind === "waiting" && session.signIn.opened === false && session.signInUrl ? (
<SignInLink url={session.signInUrl} compact />
@@ -239,6 +261,16 @@ export function AccountFooter() {
<Button size="sm" onClick={startSignIn} data-signin-retry="">
{footer.actionLabel}
</Button>
+ {footer.reason === "notConfirmed" && !triedCode.current ? (
+ <button
+ type="button"
+ className="text-2xs text-muted-foreground underline underline-offset-2 hover:text-foreground"
+ onClick={startWithCode}
+ data-signin-code=""
+ >
+ Get a code instead
+ </button>
+ ) : null}
{footer.detail ? (
<button
type="button"
@@ -273,6 +305,23 @@ export function AccountFooter() {
/** A failed sign-in also toasts, once per failure, so it is seen wherever
* the person is looking. */
+/** How long a browser sign-in waits before the page offers a code. */
+const STILL_WAITING_MS = 45_000;
+
+/** True once `active` has stayed true for `ms`; false again when it stops. */
+function useAfter(active: boolean, ms: number): boolean {
+ const [late, setLate] = useState(false);
+ useEffect(() => {
+ if (!active) {
+ setLate(false);
+ return;
+ }
+ const t = setTimeout(() => setLate(true), ms);
+ return () => clearTimeout(t);
+ }, [active, ms]);
+ return late;
+}
+
function useSignInFailureToast(footer: SignInFooter | null) {
const shown = useRef<string | null>(null);
const key = footer?.state === "failed" ? `${footer.reason}:${footer.text}:${footer.detail ?? ""}` : null;
diff --git a/libs/cua/crates/cua-auth/src/lib.rs b/libs/cua/crates/cua-auth/src/lib.rs
index 06792b42f6..7db1b7f00c 100644
--- a/libs/cua/crates/cua-auth/src/lib.rs
+++ b/libs/cua/crates/cua-auth/src/lib.rs
@@ -2055,7 +2055,7 @@ impl PendingLogin {
let secs = std::env::var("CUA_OIDC_LOGIN_TIMEOUT_SECS")
.ok()
.and_then(|s| s.parse::<u64>().ok())
- .unwrap_or(300);
+ .unwrap_or(600);
let to = self.return_to.as_ref();
let (code, mut browser) = tokio::time::timeout(
Duration::from_secs(secs),
diff --git a/libs/cua/crates/cua-telemetry/src/schema.rs b/libs/cua/crates/cua-telemetry/src/schema.rs
index 9196b9e377..3ca2960b52 100644
--- a/libs/cua/crates/cua-telemetry/src/schema.rs
+++ b/libs/cua/crates/cua-telemetry/src/schema.rs
@@ -320,6 +320,15 @@ pub const FEATURES: &[&str] = &[
"upsell_machine_dismiss",
"upsell_plan_card_click",
"upsell_account_menu_click",
+ // Sign-in recovery (CUA-2285): how a sign-in ran and where it got stuck.
+ // The reason a sign-in failed stays in `error_kind`; these add the way
+ // (the browser, or a code to enter on any device).
+ "sign_in_started_browser",
+ "sign_in_started_code",
+ "sign_in_still_waiting",
+ "sign_in_code_instead",
+ "sign_in_failed_browser",
+ "sign_in_failed_code",
];
/// Install steps live in [`INSTALLER_STEPS`] (`cua_installer_step`): the
/// installers send them before any Cua program is on the machine.