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(cua-spaces): sign-in completes after a retried browser sign-in (CUA-1728) (#5268)

Francesco Bonacci5d497f6c3be8
diff --git a/apps/cua-spaces-desktop/src/main.ts b/apps/cua-spaces-desktop/src/main.ts
index bfc4e0ff63..617ee48a5a 100644
--- a/apps/cua-spaces-desktop/src/main.ts
+++ b/apps/cua-spaces-desktop/src/main.ts
@@ -120,6 +120,11 @@ async function startNativeHost(showRoute: (route: string) => void, globalShortcu
appRoot: path.join(__dirname, ".."),
override: process.env.CUA_SPACES_NATIVE_DIR,
});
+ // The browser sign-in's loopback listener lives as long as the app waits
+ // for it (SignInRuns.timeoutMs), not the CLI's 5 minutes: a browser slow to
+ // start (Edge's first run) must not find the port closed while the app
+ // still offers its link.
+ process.env.CUA_OIDC_LOGIN_TIMEOUT_SECS ??= "600";
const native = await loadNative(dir);
// False without a browser here: the sign-in then uses the device flow.
const openUrl = async (url: string) => {
diff --git a/apps/cua-spaces-desktop/src/model/app-model.ts b/apps/cua-spaces-desktop/src/model/app-model.ts
index 2d60e9b973..d0fb806d42 100644
--- a/apps/cua-spaces-desktop/src/model/app-model.ts
+++ b/apps/cua-spaces-desktop/src/model/app-model.ts
@@ -44,6 +44,7 @@ import type { HostModel } from "./host";
import { KeyvaultModel } from "./keyvault";
import type { AccountRunning, TelemetryRunning } from "./services";
import type { StartupModel } from "./startup";
+import { SignInRuns } from "./sign-in";
import { SpaceThumbnails } from "./thumbnails";
import { noLocalRuntimeReason } from "./local-runtime";
import type { RuntimeFix, RuntimeFixAction, WindowsRuntime, WindowsRuntimeAdvice } from "./windows-runtime";
@@ -138,8 +139,8 @@ export class AppModel {
signIn: AppSignInPhase;
/** The page a waiting sign-in finishes on. */
signInUrl: string | null = null;
- /** A sign-in still waiting after this fails (a device code lives about this long). */
- signInTimeoutMs = 600_000;
+ /** Sign-in attempts, a retry's included; the first one to store a session signs the app in. */
+ readonly signIns: SignInRuns;
/** The registry's Spaces (before This machine is added). */
registrySpaces: AppSpace[] = [];
/** Memory and storage use of the Spaces whose detail is showing. */
@@ -177,7 +178,6 @@ export class AppModel {
readonly maxCpus: number;
readonly servicesInNow: () => boolean;
- private signInAttempt = 0;
private listWatchedSince = Date.now();
private rowsInFlight: Promise<import("../native/generated/index").AppSpaceRow[]> | null = null;
private hostInFlight: Promise<void> | null = null;
@@ -238,6 +238,15 @@ export class AppModel {
this.keyvault.subscribe(() => this.changed("keyvault"));
this.roster = d.native.appRosterInitial([]);
this.signIn = new d.native.AppSignInPhase.Idle();
+ this.signIns = new SignInRuns(() => this.account, {
+ starting: () => this.setSignIn(new this.native.AppSignInPhase.Starting()),
+ waiting: (attempt) => {
+ this.signInUrl = attempt.url;
+ this.setSignIn(new this.native.AppSignInPhase.Waiting({ userCode: attempt.userCode ?? undefined }));
+ },
+ signedIn: (who) => this.signedIn(who),
+ failed: (message) => this.signInFailed(message),
+ });
this.identity = d.account?.identity() ?? null;
this.host.identity = this.identity;
this.devices.signedIn = this.identity !== null;
@@ -817,42 +826,27 @@ export class AppModel {
// MARK: Account
- /** "Sign in": the browser flow (opened by the account), the code while it waits. */
+ /** "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> {
if (!this.account || this.signInPhase() === "Starting") return;
- this.setSignIn(new this.native.AppSignInPhase.Starting());
- const current = ++this.signInAttempt;
- try {
- const attempt = await this.account.beginSignIn();
- // Cancelled while it started.
- if (this.signInAttempt !== current || this.signInPhase() !== "Starting") return;
- this.signInUrl = attempt.url;
- this.setSignIn(new this.native.AppSignInPhase.Waiting({ userCode: attempt.userCode ?? undefined }));
- const timeout = setTimeout(() => {
- if (this.signInAttempt === current && this.signInPhase() === "Waiting") this.signInFailed("The sign-in timed out. Try again.");
- }, this.signInTimeoutMs);
- timeout.unref?.();
- let who: string | null;
- try {
- who = await attempt.wait();
- } finally {
- clearTimeout(timeout);
- }
- if (this.signInAttempt !== current || this.signInPhase() !== "Waiting") return;
- this.identity = who ?? this.account.identity();
- this.host.identity = this.identity;
- this.devices.signedIn = this.identity !== null;
- this.teams.reset();
- this.signInUrl = null;
- this.setSignIn(new this.native.AppSignInPhase.Idle());
- // Relay sharing paused while signed out comes back for its owner.
- await this.host.reconcileAccount();
- await this.devices.refresh();
- this.changed("machines");
- } catch (error) {
- if (this.signInAttempt !== current || this.signInPhase() === "Idle") return;
- this.signInFailed(words(error));
- }
+ await this.signIns.begin();
+ }
+
+ /** A session is stored (by a sign-in here or `cua auth login`). */
+ private async signedIn(who: string | null): Promise<void> {
+ if (!this.account) return;
+ this.identity = who ?? this.account.identity();
+ this.host.identity = this.identity;
+ this.devices.signedIn = this.identity !== null;
+ this.teams.reset();
+ this.signInUrl = null;
+ this.setSignIn(new this.native.AppSignInPhase.Idle());
+ // Relay sharing paused while signed out comes back for its owner.
+ await this.host.reconcileAccount();
+ await this.devices.refresh();
+ this.changed("machines");
}
/** The sign-in's phase (`Idle`, `Starting`, `Waiting`, `Failed`). */
@@ -875,7 +869,7 @@ export class AppModel {
/** Stops waiting for the browser (the page can start again). */
cancelSignIn(): void {
if (this.signInPhase() === "Starting" || this.signInPhase() === "Waiting") {
- this.signInAttempt += 1;
+ this.signIns.cancel();
this.telemetry?.record(this.native.appTelemetrySignInFailed(undefined));
}
this.signInUrl = null;
diff --git a/apps/cua-spaces-desktop/src/model/sign-in.ts b/apps/cua-spaces-desktop/src/model/sign-in.ts
new file mode 100644
index 0000000000..faa1b87300
--- /dev/null
+++ b/apps/cua-spaces-desktop/src/model/sign-in.ts
@@ -0,0 +1,114 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// The account's sign-in runs: "Sign in" starts an attempt (its own loopback
+// port or device code), and starting again supersedes the attempt in
+// progress. The app is signed in once a session is stored, whichever way it
+// got there: the latest attempt's wait, an earlier attempt the browser
+// 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 { words } from "./errors";
+import type { AccountRunning, SignInAttempt } from "./services";
+
+/** What a run shows: the AppModel's phase and identity. */
+export interface SignInView {
+ starting(): void;
+ waiting(attempt: SignInAttempt): void;
+ signedIn(who: string | null): Promise<void>;
+ failed(message: string): void;
+}
+
+export const SIGN_IN_TIMED_OUT = "The sign-in timed out. Try again.";
+
+export class SignInRuns {
+ /** How long an attempt waits for the browser (ms). */
+ timeoutMs = 600_000;
+ /** How often the stored session is read while a sign-in waits (ms). */
+ watchMs = 2_000;
+ /** The latest attempt; a retry, Cancel, a failure or a finish moves it on. */
+ private attempt = 0;
+ /** The attempt a sign-in last finished on: a later finish of an older attempt is the same session. */
+ private finishedAt = 0;
+ private watch: ReturnType<typeof setInterval> | null = null;
+
+ constructor(
+ private readonly account: () => AccountRunning | null,
+ private readonly view: SignInView,
+ ) {}
+
+ /** Starts an attempt (superseding one in progress) and resolves once it ends. */
+ async begin(): Promise<void> {
+ const account = this.account();
+ if (!account) return;
+ const current = ++this.attempt;
+ this.view.starting();
+ this.watchStore(account, current);
+ let attempt: SignInAttempt;
+ try {
+ attempt = await account.beginSignIn();
+ } catch (error) {
+ if (current === this.attempt) this.fail(words(error));
+ return;
+ }
+ // Cancelled, retried or signed in while it started.
+ if (current !== this.attempt) return;
+ this.view.waiting(attempt);
+ const timeout = setTimeout(() => {
+ if (current === this.attempt) this.fail(SIGN_IN_TIMED_OUT);
+ }, this.timeoutMs);
+ timeout.unref?.();
+ let who: string | null;
+ try {
+ who = await attempt.wait();
+ } catch (error) {
+ // An attempt a retry or Cancel left behind ends quietly.
+ if (current === this.attempt) this.fail(words(error));
+ return;
+ } finally {
+ clearTimeout(timeout);
+ }
+ // Whichever attempt the browser finished stored the session: take it,
+ // even when a retry superseded this attempt.
+ await this.finish(current, who ?? account.identity());
+ }
+
+ /** Stops waiting (the attempt's own wait ends with its timeout). */
+ cancel(): void {
+ this.attempt += 1;
+ this.stopWatch();
+ }
+
+ private async finish(started: number, who: string | null): Promise<void> {
+ if (this.finishedAt >= started) return;
+ this.finishedAt = ++this.attempt;
+ this.stopWatch();
+ try {
+ await this.view.signedIn(who);
+ } catch (error) {
+ this.view.failed(words(error));
+ }
+ }
+
+ private fail(message: string): void {
+ this.attempt += 1;
+ this.stopWatch();
+ this.view.failed(message);
+ }
+
+ /** A session stored while the sign-in waits ends it. */
+ private watchStore(account: AccountRunning, current: number): void {
+ this.stopWatch();
+ this.watch = setInterval(() => {
+ if (current !== this.attempt) return this.stopWatch();
+ const who = account.identity();
+ if (who !== null) void this.finish(current, who);
+ }, this.watchMs);
+ this.watch.unref?.();
+ }
+
+ private stopWatch(): void {
+ if (this.watch) clearInterval(this.watch);
+ this.watch = null;
+ }
+}
diff --git a/apps/cua-spaces-desktop/test/sign-in-runs.test.ts b/apps/cua-spaces-desktop/test/sign-in-runs.test.ts
new file mode 100644
index 0000000000..262d6f6a45
--- /dev/null
+++ b/apps/cua-spaces-desktop/test/sign-in-runs.test.ts
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// A sign-in retried from the page (CUA-1728): the first attempt's browser
+// came too late, "Open the browser again" started a second attempt, and the
+// browser finished one of them. The app is signed in whichever it was, and
+// a session stored while it waits ends the wait even when no wait returns.
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SIGN_IN_TIMED_OUT, SignInRuns, type SignInView } from "../src/model/sign-in";
+import type { AccountProfile, AccountRunning, SignInAttempt } 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;
+ readonly attempts: { url: string; finish(who: string): void; fail(e: Error): void }[] = [];
+ identity() {
+ return this.stored;
+ }
+ profile(): AccountProfile | null {
+ return null;
+ }
+ async beginSignIn(): Promise<SignInAttempt> {
+ const url = `http://127.0.0.1:${50000 + this.attempts.length}/callback`;
+ let finish!: (who: string) => void;
+ let fail!: (e: Error) => void;
+ const done = new Promise<string>((resolve, reject) => ((finish = resolve), (fail = reject)));
+ this.attempts.push({
+ url,
+ finish: (who) => {
+ // The SDK stores the session before the wait returns.
+ this.stored = who;
+ finish(who);
+ },
+ fail,
+ });
+ return { userCode: null, url, wait: () => done };
+ }
+ async signOut() {
+ this.stored = null;
+ }
+ async accessToken() {
+ return null;
+ }
+}
+
+function view() {
+ const seen = { phase: "idle", url: null as string | null, identity: null as string | null, failed: [] as string[], signedIn: 0 };
+ const v: SignInView = {
+ starting: () => void (seen.phase = "starting"),
+ waiting: (a) => void ((seen.phase = "waiting"), (seen.url = a.url)),
+ signedIn: async (who) => void ((seen.phase = "idle"), (seen.identity = who), (seen.url = null), (seen.signedIn += 1)),
+ failed: (m) => void ((seen.phase = "failed"), seen.failed.push(m)),
+ };
+ return { seen, v };
+}
+
+const flush = () => vi.advanceTimersByTimeAsync(0);
+
+describe("a retried sign-in", () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it("finishes on the retry's attempt, and the first attempt's failure stays quiet", async () => {
+ const account = new RetryAccount();
+ const { seen, v } = view();
+ const runs = new SignInRuns(() => account, v);
+ const first = runs.begin();
+ await flush();
+ expect(seen).toMatchObject({ phase: "waiting", url: "http://127.0.0.1:50000/callback" });
+ const retry = runs.begin();
+ await flush();
+ expect(seen.url).toBe("http://127.0.0.1:50001/callback");
+ account.attempts[1]!.finish("[email protected]");
+ await retry;
+ expect(seen).toMatchObject({ phase: "idle", identity: "[email protected]", signedIn: 1 });
+ // The first attempt's listener times out later: no failure shows.
+ account.attempts[0]!.fail(new Error("browser sign-in was not completed in time"));
+ await first;
+ expect(seen).toMatchObject({ phase: "idle", failed: [], signedIn: 1 });
+ });
+
+ it("finishes when the browser completes the attempt the retry superseded", async () => {
+ const account = new RetryAccount();
+ const { seen, v } = view();
+ const runs = new SignInRuns(() => account, v);
+ const first = runs.begin();
+ await flush();
+ void runs.begin();
+ await flush();
+ account.attempts[0]!.finish("[email protected]");
+ await first;
+ expect(seen).toMatchObject({ phase: "idle", identity: "[email protected]", signedIn: 1 });
+ // The retry's own wait ending afterwards changes nothing.
+ account.attempts[1]!.fail(new Error("timed out"));
+ await flush();
+ expect(seen).toMatchObject({ phase: "idle", failed: [], signedIn: 1 });
+ });
+
+ it("ends the wait once a session is stored, even when no wait returns", async () => {
+ const account = new RetryAccount();
+ const { seen, v } = view();
+ const runs = new SignInRuns(() => account, v);
+ void runs.begin();
+ await flush();
+ void runs.begin();
+ await flush();
+ expect(seen.phase).toBe("waiting");
+ // Signed in, but the attempt's wait is still busy (or never returns).
+ account.stored = "[email protected]";
+ await vi.advanceTimersByTimeAsync(runs.watchMs);
+ expect(seen).toMatchObject({ phase: "idle", identity: "[email protected]", signedIn: 1 });
+ await vi.advanceTimersByTimeAsync(runs.timeoutMs);
+ expect(seen).toMatchObject({ phase: "idle", failed: [], signedIn: 1 });
+ });
+
+ it("still times out, once, when no attempt finishes", async () => {
+ const account = new RetryAccount();
+ const { seen, v } = view();
+ const runs = new SignInRuns(() => account, v);
+ void runs.begin();
+ await flush();
+ void runs.begin();
+ await flush();
+ await vi.advanceTimersByTimeAsync(runs.timeoutMs);
+ expect(seen).toMatchObject({ phase: "failed", failed: [SIGN_IN_TIMED_OUT], signedIn: 0 });
+ });
+});
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/signin.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/signin.test.ts
index c3c870c471..8a8ddb7dc9 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/signin.test.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/signin.test.ts
@@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest";
import type { DataAdapter } from "../adapter";
import { createDemoAdapter } from "../adapters/demo";
import { BridgeStore, SIGN_IN_TIMED_OUT, type SessionData } from "../store";
+import { unavailableCore } from "../core";
import { testCore, until, wasmBuilt } from "./testCore";
/** The demo host, with a browser sign-in that never finishes. */
@@ -43,3 +44,57 @@ describe.skipIf(!wasmBuilt)("a sign-in that never finishes", () => {
store.dispose();
});
});
+
+/** A native host (the Electron app): it runs the sign-in, says when it waits
+ * (a new page per attempt), and only `session.changed` says it finished. */
+function nativeHost() {
+ const demo = createDemoAdapter({ latencyMs: 0, signedIn: false, onboarded: true });
+ const listeners = new Set<(e: { type: string }) => void>();
+ const host = { attempts: 0, identity: null as string | null };
+ const emit = () => listeners.forEach((l) => l({ type: "session.changed" }));
+ const adapter = Object.assign(Object.create(demo) as DataAdapter, {
+ subscribe: (l: (e: { type: string }) => void) => {
+ listeners.add(l);
+ return () => listeners.delete(l);
+ },
+ call: (async (op: string, args: unknown) => {
+ if (op === "session.signIn") {
+ host.attempts += 1;
+ setTimeout(emit, 1);
+ return { method: "browser", verificationUri: "" };
+ }
+ const out = (await demo.call(op as never, args as never)) as Record<string, unknown>;
+ if (op !== "session.get") return out;
+ const fleet = out.fleet as Record<string, unknown>;
+ return host.identity
+ ? { ...out, fleet: { ...fleet, configured: true, authMode: "user", identity: host.identity }, hostSignIn: null }
+ : { ...out, hostSignIn: { userCode: null, url: `http://127.0.0.1:${50000 + host.attempts}/callback` } };
+ }) as DataAdapter["call"],
+ });
+ return { adapter, host, emit };
+}
+
+describe("a sign-in the host finished on a retried attempt (CUA-1728)", () => {
+ it("stops waiting once the host is signed in", async () => {
+ const { adapter, host, emit } = nativeHost();
+ const store = new BridgeStore(adapter, unavailableCore("test: no core"));
+ store.ensure("session");
+ const session = () => store.get<SessionData>("session").data;
+ await until(() => expect(session()).toBeTruthy());
+
+ await store.signIn();
+ await until(() => expect(session()?.signInUrl).toBe("http://127.0.0.1:50001/callback"));
+ // The first attempt's browser came too late: try again, a new port.
+ store.cancelSignIn();
+ await store.signIn();
+ await until(() => expect(session()?.signInUrl).toBe("http://127.0.0.1:50002/callback"));
+ expect(session()?.signIn.kind).toBe("waiting");
+
+ host.identity = "[email protected]";
+ emit();
+ await until(() => expect(session()?.signIn).toEqual({ kind: "idle" }));
+ expect(session()?.signedIn).toBe(true);
+ expect(session()?.signInUrl).toBeNull();
+ store.dispose();
+ });
+});
diff --git a/apps/cua-spaces-web/src/bridge/store.ts b/apps/cua-spaces-web/src/bridge/store.ts
index 8cdd9ae4cf..99e3447c57 100644
--- a/apps/cua-spaces-web/src/bridge/store.ts
+++ b/apps/cua-spaces-web/src/bridge/store.ts
@@ -818,7 +818,16 @@ export class BridgeStore {
* and the page) only after `session.signIn` answered: take them in, so
* the page shows them. */
private followHostSignIn(waiting: HostSignIn | null | undefined): void {
- if (!waiting || (this.signInPhase.kind !== "starting" && this.signInPhase.kind !== "waiting")) return;
+ if (this.signInPhase.kind !== "starting" && this.signInPhase.kind !== "waiting") return;
+ // A native host signed in, whichever attempt (a retry's, or one before
+ // it) finished: the wait is over.
+ const snap = this.sessionSnap;
+ if (snap && snap.hostSignIn !== undefined && snap.fleet.authMode === "user" && snap.fleet.identity) {
+ this.stopSignInTimer();
+ this.signInPhase = { kind: "idle" };
+ return;
+ }
+ if (!waiting) return;
if (waiting.url) this.signInUrl = waiting.url;
if (this.signInPhase.kind === "waiting" && (this.signInPhase.userCode ?? null) === waiting.userCode) return;
this.signInPhase = { kind: "waiting", userCode: waiting.userCode };