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): a sign-in during the first run never fails silently (CUA-3144) (#6408)

Francesco Bonacci7885b58da7df
diff --git a/apps/cua-spaces-web/src/__tests__/first-run-new.test.tsx b/apps/cua-spaces-web/src/__tests__/first-run-new.test.tsx
index 1a07162b7d..4b572040da 100644
--- a/apps/cua-spaces-web/src/__tests__/first-run-new.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/first-run-new.test.tsx
@@ -177,6 +177,16 @@ describe("1b, sign-in", () => {
expect(signInView({ kind: "failed", reason: "offline", message: "You're offline." }, null).line).toBe("You're offline.");
});
+ it("a session that could not be saved says so on 1b, with Try again and Use a code instead", () => {
+ const msg = "Sign-in didn't finish. Cua couldn't save your session on this computer.";
+ const v = signInView({ kind: "failed", reason: "couldNotSave", message: msg }, null);
+ render(<SignInScreen view={v} onTryAgain={noop} onUseCode={noop} onOpen={noop} />);
+ expect(screen.getByRole("heading").textContent).toBe("Sign-in didn't finish");
+ expect(text()).toContain(msg);
+ expect(screen.getByRole("button", { name: "Try again" })).not.toBeNull();
+ expect(screen.getByRole("button", { name: "Use a code instead" })).not.toBeNull();
+ });
+
it("with a code shows the code and the page to enter it on", () => {
const onOpen = vi.fn();
render(<SignInScreen view={signInView({ kind: "waiting", userCode: "WXYZ-1234" }, "https://cua.ai/device")} onTryAgain={noop} onUseCode={noop} onOpen={onOpen} />);
diff --git a/apps/cua-spaces-web/src/__tests__/first-run.test.tsx b/apps/cua-spaces-web/src/__tests__/first-run.test.tsx
index bfd9933d48..5dd1c6f9e6 100644
--- a/apps/cua-spaces-web/src/__tests__/first-run.test.tsx
+++ b/apps/cua-spaces-web/src/__tests__/first-run.test.tsx
@@ -40,7 +40,7 @@ afterEach(() => {
type Calls = { op: string; args: unknown }[];
-async function mount(opts: { signedIn?: boolean; host?: (h: HostStatus) => HostStatus; local?: (l: NonNullable<NewSpaceOptions["local"]>) => NewSpaceOptions["local"]; agents?: (rows: AgentSetupRow[]) => AgentSetupRow[]; cli?: "missing" | "local"; demo?: object } = {}) {
+async function mount(opts: { signedIn?: boolean; host?: (h: HostStatus) => HostStatus; local?: (l: NonNullable<NewSpaceOptions["local"]>) => NewSpaceOptions["local"]; agents?: (rows: AgentSetupRow[]) => AgentSetupRow[]; cli?: "missing" | "local"; demo?: object; intercept?: (op: string, args: unknown) => unknown } = {}) {
await testCore();
const calls: Calls = [];
let lastRows: AgentSetupRow[] | null = null;
@@ -51,7 +51,7 @@ async function mount(opts: { signedIn?: boolean; host?: (h: HostStatus) => HostS
demo: { signedIn: opts.signedIn ?? false, onboarded: false, cli: opts.cli, ...opts.demo },
intercept: (op, args) => {
calls.push({ op, args });
- return undefined;
+ return opts.intercept?.(op, args);
},
answer: (op, out) => {
if (op === "host.status" && opts.host) return opts.host(out as HostStatus);
@@ -357,6 +357,51 @@ describe.skipIf(!wasmBuilt)("the first run (real route, wasm core)", () => {
await waitFor(() => expect(calls.some((c) => c.op === "session.signIn")).toBe(true));
});
+ it("a sign-in that didn't finish says why on the screen, with Try again and a code instead (CUA-3144)", async () => {
+ writeFirstRun({ step: "devices" });
+ // The first try: the browser never confirmed. Then a code that waits.
+ let tries = 0;
+ const calls = await mount({
+ intercept: (op) => {
+ if (op !== "session.signIn") return undefined;
+ tries += 1;
+ if (tries === 1) return Promise.reject(new Error("browser sign-in was not completed in time"));
+ return { method: "device", verificationUri: "https://cua.ai/device", userCode: "4F2-91K" };
+ },
+ });
+ await waitFor(() => expect(heading()).toBe("Add your other computers."));
+ expect(document.querySelector('[data-first-run-status="account"]')).toBeNull();
+ click('[data-first-run-devices-primary="sign-in"]');
+ // Never silent: the reason on the screen itself (the first run has no sidebar), and Try again.
+ await waitFor(() => expect(document.querySelector('[data-first-run-status="account"]')?.getAttribute("data-state")).toBe("fix"));
+ const row = document.querySelector('[data-first-run-status="account"]')!;
+ expect(row.textContent).toMatch(/Sign-in didn't finish/);
+ expect(row.textContent).toMatch(/The browser didn't confirm in time\./);
+ expect(row.textContent).not.toMatch(/not completed in time|error/i);
+ expect(document.querySelector('[data-first-run-devices-primary="sign-in"]')!.textContent).toBe("Try again");
+ // A code works from any browser or phone: for a closed tab, or another browser.
+ click('[data-first-run-action="sign-in-code"]');
+ await waitFor(() => expect(calls.some((c) => c.op === "session.signIn" && (c.args as { code?: boolean }).code === true)).toBe(true));
+ await waitFor(() => expect(document.querySelector('[data-first-run-status="account"]')?.textContent).toMatch(/Enter the code 4F2-91K on the sign-in page\./));
+ expect(document.querySelector('[data-first-run-status="account"]')!.getAttribute("data-state")).toBe("checking");
+ expect(document.querySelector('[data-first-run-action="reopen-sign-in"]')).not.toBeNull();
+ });
+
+ it("while it waits for the browser, it reads the sign-in again when the window is back in front", async () => {
+ writeFirstRun({ step: "devices" });
+ const calls = await mount({
+ intercept: (op) => (op === "session.signIn" ? { method: "browser", verificationUri: "https://cua.ai/signin" } : undefined),
+ });
+ await waitFor(() => expect(heading()).toBe("Add your other computers."));
+ click('[data-first-run-devices-primary="sign-in"]');
+ await waitFor(() => expect(document.querySelector('[data-first-run-action="sign-in-code"]')).not.toBeNull());
+ const before = calls.filter((c) => c.op === "session.get").length;
+ await act(async () => {
+ window.dispatchEvent(new Event("focus"));
+ });
+ await waitFor(() => expect(calls.filter((c) => c.op === "session.get").length).toBeGreaterThan(before));
+ });
+
it("a disk-image install offers the Cua CLI after Pick your agent: the exact file, then Install only when pressed", async () => {
const calls = await mount({ cli: "missing" });
await waitFor(() => expect(heading()).toBe("Your computers, shared by your team and its agents."));
diff --git a/apps/cua-spaces-web/src/bridge/contracts/first-run.ts b/apps/cua-spaces-web/src/bridge/contracts/first-run.ts
index f51b085dd0..66d146dc03 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/first-run.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/first-run.ts
@@ -144,6 +144,10 @@ export interface FirstRunInput {
agentUsedAt: string | null;
signedIn: boolean;
signingIn: boolean;
+ /** While signing in by a code: the code to enter (null: the browser flow). */
+ signInCode?: string | null;
+ /** The last sign-in didn't finish, for this reason (null: it did, or it is running). */
+ signInFailure?: import("./host").SignInFailure | null;
host: FirstRunHost | null;
hostSettingUp: boolean;
offers: FirstRunOffer[];
diff --git a/apps/cua-spaces-web/src/bridge/first-run.ts b/apps/cua-spaces-web/src/bridge/first-run.ts
index 36a109d811..2d825479f8 100644
--- a/apps/cua-spaces-web/src/bridge/first-run.ts
+++ b/apps/cua-spaces-web/src/bridge/first-run.ts
@@ -156,6 +156,18 @@ const rank = (id: string) => {
return i < 0 ? PREFERENCE.length : i;
};
+/** Without the core: screen 3's sign-in line (`first_run::sign_in_row`). */
+function fallbackSignInRow(input: FirstRunInput): FirstRunRow | null {
+ if (input.signingIn) {
+ return input.signInCode
+ ? { id: "account", state: "checking", title: "Signing in", note: `Enter the code ${input.signInCode} on the sign-in page.`, action: { id: "reopen-sign-in", label: "Open the page" }, settingsUrl: null }
+ : { id: "account", state: "checking", title: "Signing in", note: "Finish signing in to Cua in your browser.", action: { id: "sign-in-code", label: "Use a code instead" }, settingsUrl: null };
+ }
+ if (!input.signInFailure) return null;
+ const code = input.signInFailure === "notConfirmed" || input.signInFailure === "codeRejected" || input.signInFailure === "unknown";
+ return { id: "account", state: "fix", title: "Sign-in didn't finish", note: "Try again, or use a code instead.", action: code ? { id: "sign-in-code", label: "Use a code instead" } : null, settingsUrl: null };
+}
+
/** Without the core: the screens in their plainest state. Not the
* product's behaviour; the demo and tests without wasm use it. */
function fallbackView(input: FirstRunInput): FirstRunView {
@@ -236,8 +248,10 @@ function fallbackView(input: FirstRunInput): FirstRunView {
{ title: "Your other computers", note: "Sign in on each one" },
{ title: "Your cloud", note: "Hetzner, AWS, Google Cloud or Modal" },
],
- status: null,
- primary: input.signedIn ? { id: "continue", label: continueLabel("devices") } : { id: "sign-in", label: "Sign in" },
+ status: input.signedIn ? null : fallbackSignInRow(input),
+ primary: input.signedIn
+ ? { id: "continue", label: continueLabel("devices") }
+ : { id: "sign-in", label: input.signInFailure && !input.signingIn ? "Try again" : "Sign in" },
secondary: input.signedIn ? null : { id: "not-now", label: "Not now" },
note: input.signedIn ? null : `Not now keeps Cua on ${place} only. You can sign in later.`,
},
@@ -483,7 +497,7 @@ export interface FirstRunHook {
disconnect(agent: string): Promise<void>;
/** Starts an agent's own sign-in on this computer (`codex login`). */
signIn(agent: string): Promise<void>;
- /** A screen's button: `start`, `continue`, `skip`, `not-now` (next screen), `recheck` (read the agents again), `install` (the CLI), `sign-in`, `set-up`, `open-settings`, `allow` (the app's guide to that System Settings pane), `copy`, `add`. */
+ /** A screen's button: `start`, `continue`, `skip`, `not-now` (next screen), `recheck` (read the agents again), `install` (the CLI), `sign-in`, `sign-in-code` (a code instead of the browser), `reopen-sign-in` (the sign-in page again), `set-up`, `open-settings`, `allow` (the app's guide to that System Settings pane), `copy`, `add`. */
act(id: string, settingsUrl?: string | null): Promise<void>;
/** Copies `text` (the tab shown), else the selected request. */
copyPrompt(text?: string): Promise<void>;
@@ -612,6 +626,11 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS, onFinishe
const signedIn = Boolean(session.data?.signedIn);
const signingIn = session.data?.signIn.kind === "starting" || session.data?.signIn.kind === "waiting";
+ // Every way the sign-in ends shows on the screen (the first run has no sidebar or toast).
+ const signInNow = session.data?.signIn;
+ const signInCode = signInNow?.kind === "waiting" ? (signInNow.userCode ?? null) : null;
+ const signInFailure = signInNow?.kind === "failed" ? (signInNow.reason ?? "unknown") : null;
+ const signInUrl = session.data?.signInUrl ?? null;
// An older saved run may say any step; an unknown one starts over.
const step: FirstRunStep = STEPS.includes(s.step) ? s.step : "welcome";
@@ -652,6 +671,23 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS, onFinishe
};
}, [active, adapter, step, s.finishedLater, tick, pollMs]);
+ // Back from the browser: read the sign-in again at once, so one that
+ // finished (or failed) there shows now, not on the next host push.
+ const refreshSession = useRef(session.refresh);
+ refreshSession.current = session.refresh;
+ useEffect(() => {
+ if (!active || !signingIn) return;
+ const again = () => {
+ if (document.visibilityState !== "hidden") void refreshSession.current().catch(() => {});
+ };
+ window.addEventListener("focus", again);
+ document.addEventListener("visibilitychange", again);
+ return () => {
+ window.removeEventListener("focus", again);
+ document.removeEventListener("visibilitychange", again);
+ };
+ }, [active, signingIn]);
+
const rows: FirstRunAgent[] | null = agents
? agents.map((a) => ({
agent: a.agent,
@@ -722,6 +758,8 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS, onFinishe
agentUsedAt: null,
signedIn,
signingIn,
+ signInCode,
+ signInFailure,
host: host
? {
configured: host.configured,
@@ -1004,6 +1042,13 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS, onFinishe
case "sign-in":
await session.signIn().catch(() => {});
break;
+ case "sign-in-code":
+ // A code to enter on any browser or phone: for a tab that was closed, or opened in another browser.
+ await session.signIn({ code: true }).catch(() => {});
+ break;
+ case "reopen-sign-in":
+ if (signInUrl) await session.openExternal(signInUrl).catch(() => {});
+ break;
case "set-up":
autoSetUp.current = true;
await setUpThisComputer();
diff --git a/apps/cua-spaces-web/src/components/first-run-new/first-run-new.tsx b/apps/cua-spaces-web/src/components/first-run-new/first-run-new.tsx
index 14216d02d0..d57c9e770f 100644
--- a/apps/cua-spaces-web/src/components/first-run-new/first-run-new.tsx
+++ b/apps/cua-spaces-web/src/components/first-run-new/first-run-new.tsx
@@ -513,6 +513,24 @@ export function NewFirstRun() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [s.screen, signedIn, phase.kind]);
+ // Back from the browser: read the sign-in again at once, so one that finished
+ // (or failed) there shows now, not on the next host push.
+ const waitingOnSignIn = s.screen === "signin" && (phase.kind === "starting" || phase.kind === "waiting");
+ const refreshSession = useRef(session.refresh);
+ refreshSession.current = session.refresh;
+ useEffect(() => {
+ if (!waitingOnSignIn) return;
+ const again = () => {
+ if (document.visibilityState !== "hidden") void refreshSession.current().catch(() => {});
+ };
+ window.addEventListener("focus", again);
+ document.addEventListener("visibilitychange", again);
+ return () => {
+ window.removeEventListener("focus", again);
+ document.removeEventListener("visibilitychange", again);
+ };
+ }, [waitingOnSignIn]);
+
// Screen 2, signed in: this computer joins the account (once; the store also does it on sign-in).
const addRun = useRef(0);
const addThis = async () => {
diff --git a/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx b/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx
index 718ccb5eb6..e11a68c321 100644
--- a/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx
+++ b/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx
@@ -26,7 +26,7 @@ Every event carries: `telemetry_schema_version`, `event_version`, `product`
| `cua_keyvault_consent` | `decision` (`requested`, `approved`, `denied`, `expired`) | Consent counts only; nothing about the request. |
| `cua_spaces_feature_used` | `feature` (a fixed Spaces app feature) | Spaces app feature adoption. |
| `cua_stream_stats` | `transport`, `codec`, `decode` (`hw` or `sw`), `fps_bucket`, `latency_bucket`, `resolution`, `duration_bucket` | Streaming performance (50% sampled). |
-| `cua_onboarding_step` | `step`, `outcome`, `onboarding_eligible` (`yes` or `no` on the Spaces app's `app_launched`: its first run was still due; `unknown` otherwise), `error_kind` (a failed `signed_in`: `timeout`, `cancelled`, `permission_denied`, `transport`, `unauthenticated` or `other`, never the message; `none` otherwise) | Install and onboarding funnel. Older Spaces apps also send their getting-started checklist's steps (`checklist_shown`, `checklist_<step>`, `checklist_completed`, `checklist_dismissed`, `checklist_reopened`); current apps have tips instead and send none. |
+| `cua_onboarding_step` | `step`, `outcome`, `onboarding_eligible` (`yes` or `no` on the Spaces app's `app_launched`: its first run was still due; `unknown` otherwise), `error_kind` (a failed `signed_in`: `timeout`, `cancelled`, `permission_denied`, `transport`, `unauthenticated`, `http`, `internal` or `other`, never the message; `none` otherwise), `failed_step` (a failed `signed_in`: the step it stopped at, from its `error_kind`: `reach_service`, `confirm_in_browser`, `exchange_code`, `save_session`, `cancelled` or `unknown`; `none` otherwise) | Install and onboarding funnel, and where sign-ins fail. Older Spaces apps also send their getting-started checklist's steps (`checklist_shown`, `checklist_<step>`, `checklist_completed`, `checklist_dismissed`, `checklist_reopened`); current apps have tips instead and send none. |
| `cua_installer_step` | `step` (`installer_started`, `installer_completed`, `installer_failed`), `outcome`, `install_stage`, `error_kind`, `installer` (`sh` or `ps1`), `items` (what was asked for: `cli`, `spaces`, `cua_driver`, `host` joined with `+`) | Install funnel: how many installs start and finish, and where and why they fail ([values](/cua-sdk/concepts/telemetry-counting#installers)). |
| `cua_agent_used_space` | `tool_group` (`shell`, `files`, `computer`, `services`, `agents` or `other`) | First success and agent retention: an AI agent's tool call acted inside a Space and worked. At most one per install per UTC day. |
| `cua_agent_signin_imported` | `harness` (`hermes`, `claude-code`, `codex` or `other`), `via` (`claude_login_keychain`, `claude_login_file`, `device_code`, `token` or `other`) | One-click Connect: an agent's sign-in was copied into Keyvault on This Mac, and the way it was made. Never the sign-in, the account or the provider. |
diff --git a/libs/cua/crates/cua-auth/src/callback_page.rs b/libs/cua/crates/cua-auth/src/callback_page.rs
index 244455cef4..f7735081a1 100644
--- a/libs/cua/crates/cua-auth/src/callback_page.rs
+++ b/libs/cua/crates/cua-auth/src/callback_page.rs
@@ -40,6 +40,10 @@ pub(crate) enum Outcome {
Stale,
/// The provider would not exchange the code (it expired or was used).
Expired,
+ /// Signed in at the provider, but this computer could not keep the
+ /// session (a locked keychain, a denied prompt, a store that refused the
+ /// write): the app shows the same.
+ NotSaved,
/// Anything else: a provider error, a missing code, a failed exchange.
Failed,
}
@@ -111,6 +115,14 @@ pub(crate) fn render(outcome: &Outcome, to: Option<&ReturnTo>) -> String {
"<p>It took too long to finish, or the link was already used.</p>\n<p>{retry}</p>"
),
),
+ Outcome::NotSaved => (
+ "error",
+ "Sign-in not saved - Cua",
+ "Sign-in couldn't be saved",
+ format!(
+ "<p>Your account is fine, but this computer couldn't save the sign-in. If it asks to use your keychain or saved passwords, allow it.</p>\n<p>{retry}</p>"
+ ),
+ ),
Outcome::Failed => {
let details = match to {
Some(ReturnTo::Terminal) => " The details are in your terminal.".to_string(),
@@ -150,6 +162,7 @@ mod tests {
Outcome::Cancelled,
Outcome::Stale,
Outcome::Expired,
+ Outcome::NotSaved,
Outcome::Failed,
]
}
@@ -185,6 +198,14 @@ mod tests {
assert!(render(&Outcome::Expired, app.as_ref()).contains("sign in from Cua Spaces"));
}
+ #[test]
+ fn a_sign_in_that_was_not_saved_never_reads_as_signed_in() {
+ let app = Some(ReturnTo::App("Cua Spaces".into()));
+ let p = render(&Outcome::NotSaved, app.as_ref());
+ assert!(p.contains("couldn't be saved") && p.contains("sign in from Cua Spaces"));
+ assert!(!p.contains("You're signed in") && !p.contains("window.close()"));
+ }
+
#[test]
fn escapes_the_email_and_app_name() {
let to = ReturnTo::App("<b>".into());
diff --git a/libs/cua/crates/cua-auth/src/lib.rs b/libs/cua/crates/cua-auth/src/lib.rs
index 2f75bccc36..22b29569b9 100644
--- a/libs/cua/crates/cua-auth/src/lib.rs
+++ b/libs/cua/crates/cua-auth/src/lib.rs
@@ -144,6 +144,15 @@ pub const UNREACHABLE: &str = "could not reach the sign-in service";
/// (`access_denied`).
pub const LOGIN_DECLINED: &str = "sign-in was declined in the browser";
+/// How an error starts when a started sign-in was stopped before it
+/// finished ([`LoginCanceller::cancel`]): another attempt finished first, or
+/// the caller stopped waiting. Its loopback listener is closed by then.
+pub const LOGIN_STOPPED: &str = "sign-in was stopped before it finished";
+
+fn stopped() -> Error {
+ Error::Timeout(format!("{LOGIN_STOPPED}; start it again"))
+}
+
/// A request that failed before any answer: [`UNREACHABLE`] for transport
/// failures, the error's own words otherwise.
fn net_err(e: reqwest::Error) -> Error {
@@ -1913,6 +1922,49 @@ pub struct PendingLogin {
oidc: Oidc,
token_endpoint: String,
pending: Pending,
+ cancel: LoginCanceller,
+}
+
+/// Stops a started sign-in from anywhere ([`PendingLogin::canceller`]): a
+/// browser sign-in closes its loopback listener at once (no stale listener
+/// keeps the port or signs in later), a device-code sign-in stops polling.
+/// The wait then ends with an error that starts with [`LOGIN_STOPPED`].
+#[derive(Clone, Debug, Default)]
+pub struct LoginCanceller(Arc<LoginCancel>);
+
+#[derive(Debug, Default)]
+struct LoginCancel {
+ stopped: std::sync::atomic::AtomicBool,
+ notify: tokio::sync::Notify,
+}
+
+impl LoginCanceller {
+ /// Stops the sign-in (once; later calls do nothing).
+ pub fn cancel(&self) {
+ self.0
+ .stopped
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+ self.0.notify.notify_waiters();
+ }
+
+ /// Whether [`cancel`](Self::cancel) was called.
+ pub fn is_cancelled(&self) -> bool {
+ self.0.stopped.load(std::sync::atomic::Ordering::SeqCst)
+ }
+
+ /// Resolves once cancelled (at once when it already was).
+ async fn cancelled(&self) {
+ loop {
+ let notified = self.0.notify.notified();
+ tokio::pin!(notified);
+ // Registered before the check, so a cancel in between is seen.
+ let _ = notified.as_mut().enable();
+ if self.is_cancelled() {
+ return;
+ }
+ notified.await;
+ }
+ }
}
fn b64url(bytes: &[u8]) -> String {
@@ -2014,6 +2066,7 @@ async fn begin_pkce(oidc: &Oidc, d: &Discovery) -> Result<PendingLogin, String>
state,
redirect,
},
+ cancel: LoginCanceller::default(),
})
}
@@ -2060,13 +2113,44 @@ async fn begin_device(oidc: &Oidc, d: &Discovery) -> Result<PendingLogin> {
interval: v["interval"].as_u64().unwrap_or(5).max(1),
expires_in: v["expires_in"].as_u64().unwrap_or(600).clamp(1, 3600),
},
+ cancel: LoginCanceller::default(),
})
}
impl PendingLogin {
+ /// Stops this sign-in from another task (see [`LoginCanceller`]).
+ pub fn canceller(&self) -> LoginCanceller {
+ self.cancel.clone()
+ }
+
/// Waits for the user to finish and returns the tokens (not yet saved).
+ /// Callers that keep the session use [`Session::finish_login`], which
+ /// saves it before the browser page says "You're signed in".
pub async fn complete(self) -> Result<Credentials> {
- match self.pending {
+ self.complete_with(|_| Ok(())).await
+ }
+
+ /// Waits for the user to finish, then runs `save` on the tokens before
+ /// the browser's page is answered: the page says "You're signed in" only
+ /// once the session is kept, and "couldn't save" when `save` fails (a
+ /// locked keychain, a denied prompt), never success for a sign-in the
+ /// app then reports as failed. `save`'s error is returned as is.
+ pub async fn complete_with<F>(self, save: F) -> Result<Credentials>
+ where
+ F: FnOnce(&Credentials) -> Result<()>,
+ {
+ let PendingLogin {
+ oidc,
+ token_endpoint,
+ pending,
+ cancel,
+ return_to,
+ ..
+ } = self;
+ if cancel.is_cancelled() {
+ return Err(stopped());
+ }
+ match pending {
Pending::Pkce {
listener,
verifier,
@@ -2077,27 +2161,32 @@ impl PendingLogin {
.ok()
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(600);
- let to = self.return_to.as_ref();
- let (code, mut browser) = tokio::time::timeout(
- Duration::from_secs(secs),
- await_callback(&listener, &state, to),
- )
- .await
- .map_err(|_| {
+ let to = return_to.as_ref();
+ // Stopped while waiting: the listener closes on return.
+ let waited = tokio::select! {
+ biased;
+ () = cancel.cancelled() => return Err(stopped()),
+ w = tokio::time::timeout(
+ Duration::from_secs(secs),
+ await_callback(&listener, &state, to),
+ ) => w,
+ };
+ let (code, mut browser) = waited.map_err(|_| {
Error::Timeout(
"browser sign-in was not completed in time; try `cua auth login --remote`"
.into(),
)
})??;
- let exchanged = self
- .oidc
+ // The code is here: nothing else may answer on this port.
+ drop(listener);
+ let exchanged = oidc
.form(
- &self.token_endpoint,
+ &token_endpoint,
&[
("grant_type", "authorization_code"),
("code", &code),
("redirect_uri", &redirect),
- ("client_id", &self.oidc.client_id),
+ ("client_id", &oidc.client_id),
("code_verifier", &verifier),
],
)
@@ -2114,13 +2203,16 @@ impl PendingLogin {
)),
Err(e) => Err(e),
};
- let (status, outcome) = match &creds {
+ let exchanged_ok = creds.is_ok();
+ let kept = creds.and_then(|c| save(&c).map(|()| c));
+ let (status, outcome) = match &kept {
Ok(c) => ("200 OK", Outcome::SignedIn(c.identity().email)),
+ Err(_) if exchanged_ok => ("500 Internal Server Error", Outcome::NotSaved),
Err(_) if invalid_grant => ("400 Bad Request", Outcome::Expired),
Err(_) => ("502 Bad Gateway", Outcome::Failed),
};
respond_page(&mut browser, status, &outcome, to).await;
- creds
+ kept
}
Pending::Device {
device_code,
@@ -2139,19 +2231,25 @@ impl PendingLogin {
// is the error then, never a silent "expired".
let mut last: Option<Error> = None;
for _ in 0..(expires_in / interval + 20) {
- let polled = self
- .oidc
+ if cancel.is_cancelled() {
+ return Err(stopped());
+ }
+ let polled = oidc
.form(
- &self.token_endpoint,
+ &token_endpoint,
&[
("grant_type", DEVICE_GRANT),
("device_code", &device_code),
- ("client_id", &self.oidc.client_id),
+ ("client_id", &oidc.client_id),
],
)
.await;
match polled {
- Ok((200, v)) => return Credentials::from_token_response(&v),
+ Ok((200, v)) => {
+ let c = Credentials::from_token_response(&v)?;
+ save(&c)?;
+ return Ok(c);
+ }
Ok((status, v)) => match v["error"].as_str() {
Some("authorization_pending") => last = None,
Some("slow_down") => {
@@ -2187,7 +2285,11 @@ impl PendingLogin {
if tokio::time::Instant::now() >= deadline {
break;
}
- tokio::time::sleep(unit * interval as u32).await;
+ tokio::select! {
+ biased;
+ () = cancel.cancelled() => return Err(stopped()),
+ () = tokio::time::sleep(unit * interval as u32) => {}
+ }
}
Err(last.unwrap_or_else(|| {
Error::Timeout("device authorization expired before it was completed".into())
@@ -2400,6 +2502,17 @@ impl Session {
Ok(id)
}
+ /// Waits for `login`, stores the session, and returns who signed in.
+ /// The session is saved before the browser's page is answered, so a
+ /// store that refuses the write (a locked keychain, a denied prompt)
+ /// shows as "couldn't save" there too, never as "You're signed in".
+ pub async fn finish_login(&self, login: PendingLogin) -> Result<Identity> {
+ let c = login.complete_with(|c| self.store.save(c)).await?;
+ let id = c.identity();
+ *self.cached.lock().await = Some(c);
+ Ok(id)
+ }
+
/// Reads the store (the source of truth: another process may have
/// signed out, or refreshed and rotated the tokens). A store that cannot
/// be read right now (locked keychain, I/O error) falls back to the last
diff --git a/libs/cua/crates/cua-auth/tests/flows.rs b/libs/cua/crates/cua-auth/tests/flows.rs
index 69a185c820..654a4ff9bb 100644
--- a/libs/cua/crates/cua-auth/tests/flows.rs
+++ b/libs/cua/crates/cua-auth/tests/flows.rs
@@ -341,3 +341,139 @@ async fn a_refresh_lost_to_another_process_keeps_its_rotated_session() {
// The other process's session survives.
assert_eq!(store.load().unwrap(), Some(fresh));
}
+
+/// The browser attempt `p`'s redirect URI and state.
+fn redirect_of(p: &cua_auth::PendingLogin) -> (String, String) {
+ let u = url::Url::parse(&p.url).unwrap();
+ let q: std::collections::HashMap<String, String> = u.query_pairs().into_owned().collect();
+ (q["redirect_uri"].clone(), q["state"].clone())
+}
+
+#[tokio::test]
+async fn a_browser_sign_in_that_cannot_be_saved_says_so_on_the_page_too() {
+ let st = Arc::new(Mutex::new(State {
+ pkce_ok: true,
+ ..Default::default()
+ }));
+ let url = issuer(st).await;
+ let d = tempfile::tempdir().unwrap();
+ // The store's directory is a file: every write fails, as a locked
+ // keychain's or a denied prompt's would.
+ let blocker = d.path().join("not-a-directory");
+ std::fs::write(&blocker, b"x").unwrap();
+ let s = Arc::new(Session::new(
+ Oidc::new(&url, "cua-cli"),
+ Store::File(blocker.join("credentials.json")),
+ ));
+ let p = s.begin_login(Flow::Browser).await.unwrap();
+ let (redirect, state) = redirect_of(&p);
+ let s2 = s.clone();
+ let done = tokio::spawn(async move { s2.finish_login(p).await });
+ let r = reqwest::get(format!("{redirect}?code=c&state={state}"))
+ .await
+ .unwrap();
+ let (status, page) = (r.status().as_u16(), r.text().await.unwrap());
+ let e = done.await.unwrap().unwrap_err();
+ assert!(matches!(e, cua_auth::Error::Store(_)), "{e}");
+ // Never "You're signed in" for a session the app then reports as lost.
+ assert_eq!(status, 500);
+ assert!(page.contains("couldn't be saved"), "{page}");
+ assert!(!page.contains("You're signed in"), "{page}");
+ assert!(s.credentials().is_err() || s.credentials().unwrap().is_none());
+}
+
+#[tokio::test]
+async fn a_browser_sign_in_saves_before_the_page_says_signed_in() {
+ let st = Arc::new(Mutex::new(State {
+ pkce_ok: true,
+ ..Default::default()
+ }));
+ let url = issuer(st).await;
+ let d = tempfile::tempdir().unwrap();
+ let s = Arc::new(session(&url, d.path()));
+ let p = s.begin_login(Flow::Browser).await.unwrap();
+ let (redirect, state) = redirect_of(&p);
+ let s2 = s.clone();
+ let done = tokio::spawn(async move { s2.finish_login(p).await });
+ let r = reqwest::get(format!("{redirect}?code=c&state={state}"))
+ .await
+ .unwrap();
+ assert_eq!(r.status().as_u16(), 200);
+ // By the time the page answers, the session is on disk.
+ assert!(s.credentials().unwrap().is_some());
+ let id = done.await.unwrap().unwrap();
+ assert_eq!(id.email.as_deref(), Some("[email protected]"));
+}
+
+#[tokio::test]
+async fn a_stopped_sign_in_closes_its_listener() {
+ let st = Arc::new(Mutex::new(State {
+ pkce_ok: true,
+ ..Default::default()
+ }));
+ let url = issuer(st.clone()).await;
+ let d = tempfile::tempdir().unwrap();
+ let s = session(&url, d.path());
+ let p = s.begin_login(Flow::Browser).await.unwrap();
+ let (redirect, _) = redirect_of(&p);
+ let stop = p.canceller();
+ let done = tokio::spawn(tokio::time::timeout(
+ std::time::Duration::from_secs(20),
+ p.complete(),
+ ));
+ stop.cancel();
+ let e = done.await.unwrap().unwrap().unwrap_err();
+ assert!(matches!(e, cua_auth::Error::Timeout(_)), "{e}");
+ assert!(e.to_string().starts_with(cua_auth::LOGIN_STOPPED), "{e}");
+ // Nothing listens on the old port any more: no stale listener.
+ let port = url::Url::parse(&redirect).unwrap().port().unwrap();
+ assert!(
+ tokio::net::TcpStream::connect(("127.0.0.1", port))
+ .await
+ .is_err(),
+ "the stopped sign-in still listens on {port}"
+ );
+
+ // A code sign-in stopped before it finishes never polls on.
+ let st = Arc::new(Mutex::new(State::default()));
+ let url = issuer(st).await;
+ let p = session(&url, d.path())
+ .begin_login(Flow::Device)
+ .await
+ .unwrap();
+ p.canceller().cancel();
+ let e = p.complete().await.unwrap_err();
+ assert!(e.to_string().starts_with(cua_auth::LOGIN_STOPPED), "{e}");
+}
+
+#[tokio::test]
+async fn an_earlier_tab_still_signs_in_after_a_retry() {
+ let st = Arc::new(Mutex::new(State {
+ pkce_ok: true,
+ ..Default::default()
+ }));
+ let url = issuer(st).await;
+ let d = tempfile::tempdir().unwrap();
+ let s = Arc::new(session(&url, d.path()));
+ // "Sign in", then "Try again" before the first tab finished: each
+ // attempt has its own port, so neither tab reaches the other's listener.
+ let first = s.begin_login(Flow::Browser).await.unwrap();
+ let retry = s.begin_login(Flow::Browser).await.unwrap();
+ let (r1, s1) = redirect_of(&first);
+ let (r2, _) = redirect_of(&retry);
+ assert_ne!(r1, r2);
+ let stop_retry = retry.canceller();
+ let (a, b) = (s.clone(), s.clone());
+ let first_done = tokio::spawn(async move { a.finish_login(first).await });
+ let retry_done = tokio::spawn(async move { b.finish_login(retry).await });
+ let r = reqwest::get(format!("{r1}?code=c&state={s1}"))
+ .await
+ .unwrap();
+ assert_eq!(r.status().as_u16(), 200);
+ assert!(first_done.await.unwrap().is_ok());
+ // The caller stops the other attempt once one signed in.
+ stop_retry.cancel();
+ let e = retry_done.await.unwrap().unwrap_err();
+ assert!(e.to_string().starts_with(cua_auth::LOGIN_STOPPED), "{e}");
+ assert!(s.credentials().unwrap().is_some());
+}
diff --git a/libs/cua/crates/cua-cli/src/auth.rs b/libs/cua/crates/cua-cli/src/auth.rs
index b49207d190..8be3a68660 100644
--- a/libs/cua/crates/cua-cli/src/auth.rs
+++ b/libs/cua/crates/cua-cli/src/auth.rs
@@ -95,8 +95,8 @@ pub async fn login(opts: &LoginOptions, out: &mut dyn Write) -> Result<i32, CuaE
}
}
let _ = out.flush();
- let creds = pending.complete().await.map_err(auth_err)?;
- let id = s.install(creds).await.map_err(auth_err)?;
+ // Saved before the browser's page says "You're signed in".
+ let id = s.finish_login(pending).await.map_err(auth_err)?;
// Activation funnel: a sign-in from the CLI (browser or device code)
// counts like one in the Spaces app's first run.
cua_telemetry::global().capture_step("signed_in", cua_telemetry::Outcome::Ok);
diff --git a/libs/cua/crates/cua-sdk/src/native/auth.rs b/libs/cua/crates/cua-sdk/src/native/auth.rs
index 4dde561695..f8e11ec2af 100644
--- a/libs/cua/crates/cua-sdk/src/native/auth.rs
+++ b/libs/cua/crates/cua-sdk/src/native/auth.rs
@@ -91,6 +91,41 @@ pub struct LoginAttempt {
note: Option<String>,
session: Arc<cua_auth::Session>,
pending: tokio::sync::Mutex<Option<cua_auth::PendingLogin>>,
+ /// Stops this attempt's listener (or its code polling).
+ stop: cua_auth::LoginCanceller,
+ /// Every attempt this `Auth` started that may still be waiting.
+ open: Arc<OpenAttempts>,
+}
+
+/// The sign-ins an [`Auth`] started that may still be waiting. A retry
+/// leaves the attempt before it waiting (its tab may still finish), and
+/// stops any older one; the first to sign in stops the rest. So no loopback
+/// listener outlives its use (CUA-3144).
+#[derive(Default)]
+struct OpenAttempts(std::sync::Mutex<Vec<cua_auth::LoginCanceller>>);
+
+/// How many started sign-ins may wait at once: the newest, and the one a
+/// retry replaced (its browser tab may still be the one finished).
+const OPEN_ATTEMPTS: usize = 2;
+
+impl OpenAttempts {
+ fn add(&self, stop: cua_auth::LoginCanceller) {
+ let mut open = self.0.lock().unwrap_or_else(|e| e.into_inner());
+ open.retain(|c| !c.is_cancelled());
+ open.push(stop);
+ let extra = open.len().saturating_sub(OPEN_ATTEMPTS);
+ for old in open.drain(..extra) {
+ old.cancel();
+ }
+ }
+
+ /// One attempt signed in: the others stop.
+ fn stop_all(&self) {
+ let mut open = self.0.lock().unwrap_or_else(|e| e.into_inner());
+ for c in open.drain(..) {
+ c.cancel();
+ }
+ }
}
#[uniffi::export]
@@ -131,8 +166,20 @@ impl LoginAttempt {
.await
.take()
.ok_or_else(|| CuaError::Closed("this sign-in already finished".into()))?;
- let creds = pending.complete().await?;
- let who = self.session.install(creds).await?;
+ // Saved before the browser's page says "You're signed in".
+ let who = match self.session.finish_login(pending).await {
+ Ok(who) => {
+ self.open.stop_all();
+ who
+ }
+ // Another attempt signed in first and stopped this one:
+ // this one ends signed in too, never as a failure.
+ Err(e) if self.stop.is_cancelled() => match self.session.identity() {
+ Some(who) => return Ok(who.into()),
+ None => return Err(e.into()),
+ },
+ Err(e) => return Err(e.into()),
+ };
enroll_after_sign_in(&self.session).await;
#[cfg(feature = "host")]
super::telemetry::sync_account(&self.session).await;
@@ -197,6 +244,7 @@ async fn enroll_after_sign_in(_session: &Arc<cua_auth::Session>) {}
#[derive(uniffi::Object)]
pub struct Auth {
session: Arc<cua_auth::Session>,
+ open: Arc<OpenAttempts>,
}
impl Auth {
@@ -207,7 +255,10 @@ impl Auth {
// Refresh ahead of expiry in long-lived hosts (the app, the daemon)
// instead of only when a call finds the token expired.
session.spawn_keep_alive();
- Arc::new(Auth { session })
+ Arc::new(Auth {
+ session,
+ open: Arc::default(),
+ })
}
/// The underlying session (Rust hosts).
@@ -242,9 +293,12 @@ impl Auth {
/// code), `browser` or `device`.
pub async fn begin_login(&self, flow: Option<String>) -> Result<Arc<LoginAttempt>> {
let session = self.session.clone();
+ let open = self.open.clone();
run(async move {
let flow = cua_auth::Flow::parse(flow.as_deref().unwrap_or("auto"))?;
let p = session.begin_login(flow).await?;
+ let stop = p.canceller();
+ open.add(stop.clone());
Ok(Arc::new(LoginAttempt {
method: match p.method {
cua_auth::Method::Browser => LoginMethod::Browser,
@@ -255,6 +309,8 @@ impl Auth {
note: p.note.clone(),
session,
pending: tokio::sync::Mutex::new(Some(p)),
+ stop,
+ open,
}))
})
.await
@@ -331,6 +387,27 @@ pub(crate) async fn revoke_connected_agents(devices: Vec<String>) {
mod tests {
use super::*;
+ #[test]
+ fn a_retry_keeps_one_earlier_attempt_and_a_sign_in_stops_the_rest() {
+ let open = OpenAttempts::default();
+ let (a, b, c) = (
+ cua_auth::LoginCanceller::default(),
+ cua_auth::LoginCanceller::default(),
+ cua_auth::LoginCanceller::default(),
+ );
+ open.add(a.clone());
+ open.add(b.clone());
+ // The earlier tab may still be the one finished.
+ assert!(!a.is_cancelled() && !b.is_cancelled());
+ // A third start stops the oldest: its listener closes.
+ open.add(c.clone());
+ assert!(a.is_cancelled() && !b.is_cancelled() && !c.is_cancelled());
+ // One of them signed in: nothing is left listening.
+ open.stop_all();
+ assert!(b.is_cancelled() && c.is_cancelled());
+ assert!(open.0.lock().unwrap().is_empty());
+ }
+
#[tokio::test]
async fn status_and_errors_map_without_touching_the_keychain() {
let d = tempfile::tempdir().unwrap();
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/first-run.json b/libs/cua/crates/cua-spaces-app-core/parity/first-run.json
index 9fcdbf3b94..582969b883 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/first-run.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/first-run.json
@@ -31,6 +31,9 @@
{ "name": "07 pick your agent, still looking", "patch": { "step": "connect", "agents": null } },
{ "name": "08 connect your other devices", "patch": { "step": "devices" } },
{ "name": "09 connect your other devices, signing in", "patch": { "step": "devices", "signingIn": true } },
+ { "name": "09b connect your other devices, signing in with a code", "patch": { "step": "devices", "signingIn": true, "signInCode": "4F2-91K" } },
+ { "name": "09c connect your other devices, the browser never confirmed", "patch": { "step": "devices", "signInFailure": "notConfirmed" } },
+ { "name": "09d connect your other devices, the sign-in couldn't be saved", "patch": { "step": "devices", "signInFailure": "couldNotSave" } },
{ "name": "10 this Mac being added to the account", "patch": { "step": "devices", "signedIn": true, "hostSettingUp": true, "host": { "configured": false, "running": false, "permissions": [] } } },
{ "name": "11 this Mac in the account", "patch": { "step": "devices", "signedIn": true, "host": { "configured": true, "running": true, "online": true, "permissions": [{ "id": "accessibility", "granted": false }] } } },
{ "name": "12 try it in Hermes, waiting", "patch": { "step": "setup", "picked": ["hermes", "claude-code"] } },
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/first-run.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/first-run.json
index 82bbb85900..76106e3307 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/first-run.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/first-run.json
@@ -147,7 +147,58 @@
"Your cloud — Hetzner, AWS, Google Cloud or Modal"
],
"secondary": "not-now:Not now",
- "status": "[checking] Signing in — Finish signing in to Cua in your browser.",
+ "status": "[checking] Signing in — Finish signing in to Cua in your browser. (sign-in-code:Use a code instead)",
+ "title": "Add your other computers."
+ },
+ "step": "devices"
+ },
+ {
+ "art": "hermes on outline",
+ "case": "09b connect your other devices, signing in with a code",
+ "devices": {
+ "lede": "Sign in to Cua here and on your other computers. Then they can all use this Mac's Spaces.",
+ "note": "Not now keeps Cua on this Mac only. You can sign in later.",
+ "primary": "sign-in:Sign in",
+ "rows": [
+ "Your other computers — Sign in with the same account",
+ "Your cloud — Hetzner, AWS, Google Cloud or Modal"
+ ],
+ "secondary": "not-now:Not now",
+ "status": "[checking] Signing in — Enter the code 4F2-91K on the sign-in page. (reopen-sign-in:Open the page)",
+ "title": "Add your other computers."
+ },
+ "step": "devices"
+ },
+ {
+ "art": "hermes on outline",
+ "case": "09c connect your other devices, the browser never confirmed",
+ "devices": {
+ "lede": "Sign in to Cua here and on your other computers. Then they can all use this Mac's Spaces.",
+ "note": "Not now keeps Cua on this Mac only. You can sign in later.",
+ "primary": "sign-in:Try again",
+ "rows": [
+ "Your other computers — Sign in with the same account",
+ "Your cloud — Hetzner, AWS, Google Cloud or Modal"
+ ],
+ "secondary": "not-now:Not now",
+ "status": "[fix] Sign-in didn't finish — The browser didn't confirm in time. (sign-in-code:Use a code instead)",
+ "title": "Add your other computers."
+ },
+ "step": "devices"
+ },
+ {
+ "art": "hermes on outline",
+ "case": "09d connect your other devices, the sign-in couldn't be saved",
+ "devices": {
+ "lede": "Sign in to Cua here and on your other computers. Then they can all use this Mac's Spaces.",
+ "note": "Not now keeps Cua on this Mac only. You can sign in later.",
+ "primary": "sign-in:Try again",
+ "rows": [
+ "Your other computers — Sign in with the same account",
+ "Your cloud — Hetzner, AWS, Google Cloud or Modal"
+ ],
+ "secondary": "not-now:Not now",
+ "status": "[fix] Sign-in didn't finish — This computer couldn't save the sign-in. Unlock your keychain, then try again.",
"title": "Add your other computers."
},
"step": "devices"
diff --git a/libs/cua/crates/cua-spaces-app-core/src/first_run.rs b/libs/cua/crates/cua-spaces-app-core/src/first_run.rs
index 2c78454b2f..d117b1d69c 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/first_run.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/first_run.rs
@@ -324,6 +324,14 @@ pub struct FirstRunInput {
pub signed_in: bool,
/// Sign-in is waiting for the browser.
pub signing_in: bool,
+ /// While signing in by a code: the code to enter on the sign-in page
+ /// (none: the browser flow).
+ pub sign_in_code: Option<String>,
+ /// The last sign-in didn't finish, for this reason (none: it did, it is
+ /// still running, or none was tried). Shown on the screen with what to
+ /// do next, never only in a sidebar the first run does not show
+ /// (CUA-3144).
+ pub sign_in_failure: Option<crate::sign_in::SignInFailure>,
/// `host.status` (none: not read yet).
pub host: Option<FirstRunHost>,
/// The host setup is running (after sign-in).
@@ -530,7 +538,8 @@ pub struct CheckRow {
pub state: RowState,
pub title: String,
pub note: String,
- /// The fix: `restart-check`, `connect`, `sign-in`, `open-settings`,
+ /// The fix: `restart-check`, `connect`, `sign-in`, `sign-in-code`,
+ /// `reopen-sign-in`, `open-settings`,
/// `set-up`.
pub action: Option<FirstRunButton>,
/// The Settings pane `open-settings` opens.
@@ -1180,14 +1189,7 @@ fn account_row(input: &FirstRunInput) -> Option<CheckRow> {
settings_url: None,
};
if !input.signed_in {
- return input.signing_in.then(|| {
- row(
- RowState::Checking,
- "Signing in".into(),
- "Finish signing in to Cua in your browser.".into(),
- None,
- )
- });
+ return sign_in_row(input);
}
let Some(host) = &input.host else {
return Some(row(
@@ -1231,6 +1233,56 @@ fn account_row(input: &FirstRunInput) -> Option<CheckRow> {
))
}
+/// Screen 3's sign-in line before this computer is signed in: waiting
+/// (with the way out when the browser tab was closed or opened in the
+/// wrong browser), or why it didn't finish with the next step. Every way a
+/// sign-in ends shows here: the first run has no sidebar to show it in.
+fn sign_in_row(input: &FirstRunInput) -> Option<CheckRow> {
+ use crate::sign_in::{FAILED_TITLE, SignInFailure, reason_text};
+ let row = |state, title: &str, note: String, action: Option<FirstRunButton>| CheckRow {
+ id: "account".into(),
+ state,
+ title: title.into(),
+ note,
+ action,
+ settings_url: None,
+ };
+ if input.signing_in {
+ let code = input.sign_in_code.as_deref().filter(|c| !c.is_empty());
+ return Some(match code {
+ Some(code) => row(
+ RowState::Checking,
+ "Signing in",
+ format!("Enter the code {code} on the sign-in page."),
+ Some(button("reopen-sign-in", "Open the page")),
+ ),
+ None => row(
+ RowState::Checking,
+ "Signing in",
+ "Finish signing in to Cua in your browser.".into(),
+ Some(button("sign-in-code", "Use a code instead")),
+ ),
+ });
+ }
+ let reason = input.sign_in_failure?;
+ let note = match reason_text(reason) {
+ "" => "Try again, or use a code instead.".to_string(),
+ why => why.to_string(),
+ };
+ // A code helps when the browser can't get back here; not when the
+ // person declined, is offline, or this computer can't save it.
+ let code = matches!(
+ reason,
+ SignInFailure::NotConfirmed | SignInFailure::CodeRejected | SignInFailure::Unknown
+ );
+ Some(row(
+ RowState::Fix,
+ FAILED_TITLE,
+ note,
+ code.then(|| button("sign-in-code", "Use a code instead")),
+ ))
+}
+
fn devices_view(input: &FirstRunInput) -> DevicesView {
let place = this_computer(&input.host_os);
let rows = vec![
@@ -1267,7 +1319,14 @@ fn devices_view(input: &FirstRunInput) -> DevicesView {
),
rows,
status: account_row(input),
- primary: button("sign-in", "Sign in"),
+ primary: button(
+ "sign-in",
+ if input.sign_in_failure.is_some() && !input.signing_in {
+ "Try again"
+ } else {
+ "Sign in"
+ },
+ ),
secondary: Some(button("not-now", "Not now")),
note: Some(format!(
"Not now keeps Cua on {place} only. You can sign in later."
@@ -2512,6 +2571,104 @@ mod tests {
);
}
+ /// Every way a sign-in on screen 3 ends is on the screen with a next
+ /// step, never a silent "Sign in" again (CUA-3144): the first run has no
+ /// sidebar or toast to show it in.
+ #[test]
+ fn every_sign_in_state_shows_on_the_screen_with_a_next_step() {
+ use crate::sign_in::SignInFailure;
+ let mut i = input(FirstRunStep::Devices, vec![]);
+
+ // Waiting for the browser: the way out if the tab was closed or
+ // opened in another browser.
+ i.signing_in = true;
+ let d = view(&i).devices.unwrap();
+ let w = d.status.unwrap();
+ assert_eq!(
+ (w.state, w.title.as_str(), w.note.as_str()),
+ (
+ RowState::Checking,
+ "Signing in",
+ "Finish signing in to Cua in your browser."
+ )
+ );
+ let a = w.action.unwrap();
+ assert_eq!(
+ (a.id.as_str(), a.label.as_str()),
+ ("sign-in-code", "Use a code instead")
+ );
+ assert_eq!(d.primary.label, "Sign in");
+
+ // Waiting for a code: the code, and the page to enter it on.
+ i.sign_in_code = Some("4F2-91K".into());
+ let w = view(&i).devices.unwrap().status.unwrap();
+ assert_eq!(w.note, "Enter the code 4F2-91K on the sign-in page.");
+ assert_eq!(w.action.unwrap().id, "reopen-sign-in");
+
+ // It failed: why, Try again, and a code where a code helps.
+ i.signing_in = false;
+ i.sign_in_code = None;
+ for reason in SignInFailure::ALL {
+ i.sign_in_failure = Some(reason);
+ let d = view(&i).devices.unwrap();
+ let f = d.status.unwrap_or_else(|| panic!("{reason:?} is silent"));
+ assert_eq!(f.state, RowState::Fix, "{reason:?}");
+ assert_eq!(f.title, "Sign-in didn't finish");
+ assert!(!f.note.is_empty(), "{reason:?} has no words");
+ for raw in ["HTTP", "error", "`", "{", "_", "OIDC", "token"] {
+ assert!(!f.note.contains(raw), "{reason:?} shows {raw:?}");
+ }
+ assert_eq!(
+ (d.primary.id.as_str(), d.primary.label.as_str()),
+ ("sign-in", "Try again"),
+ "{reason:?}"
+ );
+ assert_eq!(d.secondary.as_ref().unwrap().id, "not-now");
+ let code = f.action.map(|a| a.id);
+ let helps = matches!(
+ reason,
+ SignInFailure::NotConfirmed | SignInFailure::CodeRejected | SignInFailure::Unknown
+ );
+ assert_eq!(code.as_deref() == Some("sign-in-code"), helps, "{reason:?}");
+ }
+ i.sign_in_failure = Some(SignInFailure::CouldNotSave);
+ assert_eq!(
+ view(&i).devices.unwrap().status.unwrap().note,
+ "This computer couldn't save the sign-in. Unlock your keychain, then try again."
+ );
+
+ // Trying again is waiting again, not the old failure.
+ i.signing_in = true;
+ let d = view(&i).devices.unwrap();
+ assert_eq!(d.status.unwrap().state, RowState::Checking);
+ assert_eq!(d.primary.label, "Sign in");
+
+ // Signed in: the failure is gone.
+ i.signing_in = false;
+ i.signed_in = true;
+ let d = view(&i).devices.unwrap();
+ assert_ne!(d.status.unwrap().title, "Sign-in didn't finish");
+ }
+
+ /// The shells' JSON for the new fields: camelCase, absent in older ones.
+ #[test]
+ fn the_sign_in_fields_read_from_the_page() {
+ let i: FirstRunInput = serde_json::from_value(serde_json::json!({
+ "step": "devices",
+ "hostOs": "macos",
+ "signInFailure": "couldNotSave",
+ "signInCode": null,
+ }))
+ .unwrap();
+ assert_eq!(
+ i.sign_in_failure,
+ Some(crate::sign_in::SignInFailure::CouldNotSave)
+ );
+ let old: FirstRunInput =
+ serde_json::from_value(serde_json::json!({"step": "devices"})).unwrap();
+ assert_eq!(old.sign_in_failure, None);
+ }
+
/// Where Back and Continue go from `v`.
fn nav(v: &FirstRunView) -> (FirstRunStep, FirstRunStep) {
let at = v.current as usize;
diff --git a/libs/cua/crates/cua-spaces-app-core/src/telemetry.rs b/libs/cua/crates/cua-spaces-app-core/src/telemetry.rs
index 13de625c37..cc43beb58c 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/telemetry.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/telemetry.rs
@@ -1810,6 +1810,59 @@ mod tests {
}
}
+ /// A sign-in that failed sends the step it stopped at, from its reason
+ /// only (CUA-3144): a session this computer couldn't save is
+ /// `save_session`, a browser that never came back `confirm_in_browser`.
+ /// Through the usage-data switch: nothing while it is off.
+ #[cfg(feature = "telemetry")]
+ #[test]
+ fn a_failed_sign_in_sends_the_step_it_stopped_at() {
+ use crate::sign_in::SignInFailure;
+ let build = |on: bool| {
+ let home = tempfile::tempdir().unwrap();
+ let sink = std::sync::Arc::new(cua_telemetry::sink::MemorySink::new());
+ let t = cua_telemetry::Telemetry::builder()
+ .env(move |k| match k {
+ "CUA_TELEMETRY_FORBID_NETWORK" => Some("1".into()),
+ "CUA_TELEMETRY" if !on => Some("0".into()),
+ _ => None,
+ })
+ .home(home.path())
+ .sink(sink.clone())
+ .product("spaces_app", "0.2.0")
+ .foreground()
+ .build();
+ t.acknowledge_notice();
+ (home, sink, t)
+ };
+ let (_home, sink, t) = build(true);
+ for (reason, step) in [
+ (Some(SignInFailure::CouldNotSave), "save_session"),
+ (Some(SignInFailure::NotConfirmed), "confirm_in_browser"),
+ (Some(SignInFailure::Offline), "reach_service"),
+ (Some(SignInFailure::CodeRejected), "exchange_code"),
+ (Some(SignInFailure::Unknown), "unknown"),
+ (None, "cancelled"),
+ ] {
+ assert_eq!(record(&t, &sign_in_failure(reason)), 1, "{reason:?}");
+ t.flush(std::time::Duration::from_secs(2));
+ let events = sink.events();
+ let last = events
+ .iter()
+ .rev()
+ .find(|e| e["event"] == "cua_onboarding_step")
+ .expect("cua_onboarding_step was sent");
+ assert_eq!(last["properties"]["step"], "signed_in");
+ assert_eq!(last["properties"]["outcome"], "error");
+ assert_eq!(last["properties"]["failed_step"], step, "{reason:?}");
+ }
+ // Usage data off: nothing leaves.
+ let (_home, sink, t) = build(false);
+ record(&t, &sign_in_failure(Some(SignInFailure::CouldNotSave)));
+ t.flush(std::time::Duration::from_secs(1));
+ assert!(sink.events().is_empty());
+ }
+
/// A Mac that can't run virtual machines is refused by the daemon's
/// preflight with a plain sentence (`MAC_UNSUPPORTED`, or the built-in
/// runtime's identical one). That ends a create like any failure, so it
diff --git a/libs/cua/crates/cua-telemetry/src/events.rs b/libs/cua/crates/cua-telemetry/src/events.rs
index 2faf9621b8..7a1cd47ba5 100644
--- a/libs/cua/crates/cua-telemetry/src/events.rs
+++ b/libs/cua/crates/cua-telemetry/src/events.rs
@@ -649,9 +649,28 @@ pub fn onboarding_step(step: &str, outcome: Outcome) -> Option<Event> {
.s("outcome", outcome.as_str())
.s("onboarding_eligible", "unknown")
.s("error_kind", "none")
+ .s("failed_step", "none")
})
}
+/// The step a failed sign-in stopped at (`schema::SIGN_IN_STEPS`), from its
+/// fixed kind only (`schema::ERROR_KINDS`, as `cua-spaces-app-core`
+/// `sign_in::error_kind` gives it), never from text: reaching Cua's
+/// sign-in service, confirming in the browser (it never came back, or was
+/// declined), the code exchange the service refused, saving the session on
+/// this computer, or stopped by the person. `unknown` when the kind says
+/// nothing about the step.
+pub fn sign_in_failed_step(error_kind: &str) -> &'static str {
+ match error_kind {
+ "transport" | "http" => "reach_service",
+ "timeout" | "permission_denied" => "confirm_in_browser",
+ "unauthenticated" => "exchange_code",
+ "internal" => "save_session",
+ "cancelled" => "cancelled",
+ _ => "unknown",
+ }
+}
+
/// `cua_onboarding_step` `signed_in` with outcome `error`: a sign-in that
/// failed, timed out or was cancelled, as its kind ([`schema::ERROR_KINDS`],
/// else `other`).
@@ -661,6 +680,7 @@ pub fn sign_in_failed(error_kind: &str) -> Event {
.s("outcome", Outcome::Error.as_str())
.s("onboarding_eligible", "unknown")
.s("error_kind", pick(schema::ERROR_KINDS, error_kind, "other"))
+ .s("failed_step", sign_in_failed_step(error_kind))
}
/// `cua_onboarding_step` `app_launched`: the app started, with whether its
@@ -679,6 +699,7 @@ pub fn app_launched(onboarding_eligible: Option<bool>) -> Event {
},
)
.s("error_kind", "none")
+ .s("failed_step", "none")
}
/// Where an agent run was started from ([`schema::AGENT_ENTRIES`]), else
diff --git a/libs/cua/crates/cua-telemetry/src/schema.rs b/libs/cua/crates/cua-telemetry/src/schema.rs
index e6874206d1..b66fbc5dfc 100644
--- a/libs/cua/crates/cua-telemetry/src/schema.rs
+++ b/libs/cua/crates/cua-telemetry/src/schema.rs
@@ -556,6 +556,21 @@ pub const FAILED_STEPS: &[&str] = &[
"connect_services",
"unknown",
];
+/// The step a failed sign-in stopped at (`cua_onboarding_step` `signed_in`
+/// with outcome `error`), derived on device from its fixed `error_kind`,
+/// never from text: reaching Cua's sign-in service, confirming in the
+/// browser, the code exchange, saving the session on this computer, or
+/// stopped by the person. `unknown` when the kind says nothing about it;
+/// `none` for every other step and outcome.
+pub const SIGN_IN_STEPS: &[&str] = &[
+ "none",
+ "reach_service",
+ "confirm_in_browser",
+ "exchange_code",
+ "save_session",
+ "cancelled",
+ "unknown",
+];
/// Time from create to ready (or to the failure), bucketed finely enough
/// for median and p90 estimates.
pub const CREATE_TIMES: &[&str] = &[
@@ -1354,7 +1369,7 @@ pub const EVENTS: &[EventSpec] = &[
},
EventSpec {
name: event::ONBOARDING_STEP,
- version: 3,
+ version: 4,
tier: Tier::Usage,
sample_rate: 1.0,
products: &[
@@ -1381,7 +1396,12 @@ pub const EVENTS: &[EventSpec] = &[
p(
"error_kind",
Kind::Enum(ERROR_KINDS),
- "A failed signed_in: why, as a fixed kind (timeout, cancelled, permission_denied, transport, unauthenticated, other); none otherwise. Never the message.",
+ "A failed signed_in: why, as a fixed kind (timeout, cancelled, permission_denied, transport, unauthenticated, http, internal, other); none otherwise. Never the message.",
+ ),
+ p(
+ "failed_step",
+ Kind::Enum(SIGN_IN_STEPS),
+ "A failed signed_in: the step it stopped at (reach_service, confirm_in_browser, exchange_code, save_session, cancelled), from its error_kind; unknown when the kind does not say; none otherwise.",
),
],
purpose: "Install and onboarding funnel: where people drop off.",
diff --git a/libs/cua/crates/cua-telemetry/tests/privacy.rs b/libs/cua/crates/cua-telemetry/tests/privacy.rs
index f64172f24e..6f97658eaf 100644
--- a/libs/cua/crates/cua-telemetry/tests/privacy.rs
+++ b/libs/cua/crates/cua-telemetry/tests/privacy.rs
@@ -1042,6 +1042,35 @@ fn a_switch_flipped_elsewhere_applies_after_refresh_and_clears_the_spool() {
assert_eq!(t.spooled(), 0);
}
+/// A failed sign-in's `failed_step` comes from its fixed kind only, is
+/// always a word of the schema, and is `none` on every other step.
+#[test]
+fn sign_in_failed_step_keeps_its_vocabulary() {
+ for (kind, want) in [
+ ("transport", "reach_service"),
+ ("http", "reach_service"),
+ ("timeout", "confirm_in_browser"),
+ ("permission_denied", "confirm_in_browser"),
+ ("unauthenticated", "exchange_code"),
+ ("internal", "save_session"),
+ ("cancelled", "cancelled"),
+ ("other", "unknown"),
+ ("[email protected]", "unknown"),
+ ] {
+ let e = events::sign_in_failed(kind);
+ let step = e.props["failed_step"].as_str().unwrap().to_string();
+ assert_eq!(step, want, "{kind}");
+ assert!(schema::SIGN_IN_STEPS.contains(&step.as_str()));
+ assert!(!serde_json::to_string(&e.props).unwrap().contains("ellie"));
+ }
+ let ok = events::onboarding_step("signed_in", Outcome::Ok).unwrap();
+ assert_eq!(ok.props["failed_step"], "none");
+ assert_eq!(
+ events::app_launched(Some(true)).props["failed_step"],
+ "none"
+ );
+}
+
/// The "Telemetry and privacy" pages list every event and every property
/// the schema declares, so nothing is sent that the docs do not name.
/// `failed_step` is derived from the failure's fixed words, never text; it