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): show every sign-in state, with a reason and Try again (#5708)

ddupontc2a21e764e2c
diff --git a/apps/cua-spaces-desktop/src/model/app-model.ts b/apps/cua-spaces-desktop/src/model/app-model.ts
index 4a23e7db08..fe8d5bc3b9 100644
--- a/apps/cua-spaces-desktop/src/model/app-model.ts
+++ b/apps/cua-spaces-desktop/src/model/app-model.ts
@@ -43,12 +43,12 @@ import type { CloudModel } from "./cloud";
import type { DevicesModel } from "./devices";
import { TeamsModel } from "./teams";
import { NotchActivity } from "./activity";
-import { createErrorVariant, daemonAnswered, isCancelled, words } from "./errors";
+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 { StartupModel } from "./startup";
-import { SignInRuns } from "./sign-in";
+import { SignInRuns, type SignInEnd } from "./sign-in";
import { SpaceThumbnails } from "./thumbnails";
import { noLocalRuntimeReason } from "./local-runtime";
import type { LinuxRuntime } from "./linux-runtime";
@@ -256,10 +256,10 @@ export class AppModel {
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 }));
+ this.setSignIn(new this.native.AppSignInPhase.Waiting({ userCode: attempt.userCode ?? undefined, opened: attempt.opened !== false }));
},
signedIn: (who) => this.signedIn(who),
- failed: (message) => this.signInFailed(message),
+ failed: (end) => this.signInFailed(end),
});
this.identity = d.account?.identity() ?? null;
this.host.identity = this.identity;
@@ -915,18 +915,25 @@ export class AppModel {
this.changed("session");
}
- /** Shown where the sign-in was started; counted by its kind only. */
- private signInFailed(message: string): void {
+ /** Shown with its reason in the sidebar's foot (and a toast there);
+ * counted by its kind only (the core keeps the words). */
+ private signInFailed(end: SignInEnd): void {
+ const n = this.native;
+ const phase =
+ "timedOut" in end
+ ? n.appSignInFailed(n.AppSignInFailure.NotConfirmed, undefined)
+ : n.appSignInFailedFromError(sdkErrorKind(end.error) ?? "", words(end.error));
this.signInUrl = null;
- this.setSignIn(new this.native.AppSignInPhase.Failed({ message }));
- this.telemetry?.record(this.native.appTelemetrySignInFailed(message));
+ this.setSignIn(phase);
+ const reason = phase.tag === "Failed" ? phase.inner.reason : n.AppSignInFailure.Unknown;
+ this.telemetry?.record(n.appTelemetrySignInFailure(reason));
}
/** Stops waiting for the browser (the page can start again). */
cancelSignIn(): void {
if (this.signInPhase() === "Starting" || this.signInPhase() === "Waiting") {
this.signIns.cancel();
- this.telemetry?.record(this.native.appTelemetrySignInFailed(undefined));
+ this.telemetry?.record(this.native.appTelemetrySignInFailure(undefined));
}
this.signInUrl = null;
this.setSignIn(new this.native.AppSignInPhase.Idle());
diff --git a/apps/cua-spaces-desktop/src/model/services.ts b/apps/cua-spaces-desktop/src/model/services.ts
index 8b68301977..ab23ce1395 100644
--- a/apps/cua-spaces-desktop/src/model/services.ts
+++ b/apps/cua-spaces-desktop/src/model/services.ts
@@ -12,6 +12,8 @@ export interface SignInAttempt {
userCode: string | null;
/** The page the sign-in finishes on (to open it again). */
url: string | null;
+ /** A browser opened on this machine (false: the page is to be opened by hand, on any device). */
+ opened?: boolean;
wait(): Promise<string | null>;
}
@@ -75,6 +77,7 @@ export class LiveAccount implements AccountRunning {
return {
userCode: attempt.userCode() ?? null,
url: url || null,
+ opened,
wait: async () => display(await attempt.wait()),
};
}
diff --git a/apps/cua-spaces-desktop/src/model/sign-in.ts b/apps/cua-spaces-desktop/src/model/sign-in.ts
index faa1b87300..f5b17cedea 100644
--- a/apps/cua-spaces-desktop/src/model/sign-in.ts
+++ b/apps/cua-spaces-desktop/src/model/sign-in.ts
@@ -8,19 +8,20 @@
// 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";
+/** 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. */
+export type SignInEnd = { error: unknown } | { timedOut: true };
+
/** 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;
+ failed(end: SignInEnd): 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;
@@ -48,14 +49,14 @@ export class SignInRuns {
try {
attempt = await account.beginSignIn();
} catch (error) {
- if (current === this.attempt) this.fail(words(error));
+ if (current === this.attempt) this.fail({ 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);
+ if (current === this.attempt) this.fail({ timedOut: true });
}, this.timeoutMs);
timeout.unref?.();
let who: string | null;
@@ -63,7 +64,7 @@ export class SignInRuns {
who = await attempt.wait();
} catch (error) {
// An attempt a retry or Cancel left behind ends quietly.
- if (current === this.attempt) this.fail(words(error));
+ if (current === this.attempt) this.fail({ error });
return;
} finally {
clearTimeout(timeout);
@@ -86,14 +87,14 @@ export class SignInRuns {
try {
await this.view.signedIn(who);
} catch (error) {
- this.view.failed(words(error));
+ this.view.failed({ error });
}
}
- private fail(message: string): void {
+ private fail(end: SignInEnd): void {
this.attempt += 1;
this.stopWatch();
- this.view.failed(message);
+ this.view.failed(end);
}
/** A session stored while the sign-in waits ends it. */
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts
index bb760be45f..5183425c68 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi-ffi.ts
@@ -1447,6 +1447,21 @@ const DEFINITIONS = {
ret: FfiType.RustBuffer,
hasRustCallStatus: true,
},
+ "uniffi_cua_spaces_ffi_fn_func_app_sign_in_failed": {
+ args: [FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_spaces_ffi_fn_func_app_sign_in_failed_from_error": {
+ args: [FfiType.RustBuffer, FfiType.RustBuffer],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
+ "uniffi_cua_spaces_ffi_fn_func_app_sign_in_footer": {
+ args: [FfiType.RustBuffer],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
"uniffi_cua_spaces_ffi_fn_func_app_space_accepts_drop": {
args: [FfiType.RustBuffer],
ret: FfiType.Int8,
@@ -1632,6 +1647,11 @@ const DEFINITIONS = {
ret: FfiType.RustBuffer,
hasRustCallStatus: true,
},
+ "uniffi_cua_spaces_ffi_fn_func_app_telemetry_sign_in_failure": {
+ args: [FfiType.RustBuffer],
+ ret: FfiType.RustBuffer,
+ hasRustCallStatus: true,
+ },
"uniffi_cua_spaces_ffi_fn_func_app_telemetry_start": {
args: [FfiType.RustBuffer, FfiType.RustBuffer],
ret: FfiType.Int8,
@@ -3202,6 +3222,21 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_spaces_ffi_checksum_func_app_sign_in_failed": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_spaces_ffi_checksum_func_app_sign_in_failed_from_error": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
+ "uniffi_cua_spaces_ffi_checksum_func_app_sign_in_footer": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_spaces_ffi_checksum_func_app_space_accepts_drop": {
args: [],
ret: FfiType.UInt16,
@@ -3387,6 +3422,11 @@ const DEFINITIONS = {
ret: FfiType.UInt16,
hasRustCallStatus: false,
},
+ "uniffi_cua_spaces_ffi_checksum_func_app_telemetry_sign_in_failure": {
+ args: [],
+ ret: FfiType.UInt16,
+ hasRustCallStatus: false,
+ },
"uniffi_cua_spaces_ffi_checksum_func_app_telemetry_start": {
args: [],
ret: FfiType.UInt16,
@@ -4305,6 +4345,9 @@ interface NativeModuleInterface {
uniffi_cua_spaces_ffi_fn_func_app_share_state_from_json(json: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_share_view(input: Uint8Array, state: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_sidebar(spaces: Uint8Array, query: Uint8Array, selectedId: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_spaces_ffi_fn_func_app_sign_in_failed(reason: Uint8Array, detail: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_spaces_ffi_fn_func_app_sign_in_failed_from_error(variant: Uint8Array, message: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_spaces_ffi_fn_func_app_sign_in_footer(input: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_space_accepts_drop(space: Uint8Array, uniffi_out_err: UniffiRustCallStatus): number;
uniffi_cua_spaces_ffi_fn_func_app_space_detail(space: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_space_detail_copy(uniffi_out_err: UniffiRustCallStatus): Uint8Array;
@@ -4342,6 +4385,7 @@ interface NativeModuleInterface {
uniffi_cua_spaces_ffi_fn_func_app_telemetry_record(signals: Uint8Array, uniffi_out_err: UniffiRustCallStatus): number;
uniffi_cua_spaces_ffi_fn_func_app_telemetry_share(input: Uint8Array, state: Uint8Array, action: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_telemetry_sign_in_failed(message: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
+ uniffi_cua_spaces_ffi_fn_func_app_telemetry_sign_in_failure(reason: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_telemetry_start(version: Uint8Array, onboardingEligible: Uint8Array, uniffi_out_err: UniffiRustCallStatus): number;
uniffi_cua_spaces_ffi_fn_func_app_telemetry_storage(input: Uint8Array, state: Uint8Array, action: Uint8Array, uniffi_out_err: UniffiRustCallStatus): Uint8Array;
uniffi_cua_spaces_ffi_fn_func_app_telemetry_welcome_left(on: number, uniffi_out_err: UniffiRustCallStatus): void;
@@ -4656,6 +4700,9 @@ interface NativeModuleInterface {
uniffi_cua_spaces_ffi_checksum_func_app_share_state_from_json(): number;
uniffi_cua_spaces_ffi_checksum_func_app_share_view(): number;
uniffi_cua_spaces_ffi_checksum_func_app_sidebar(): number;
+ uniffi_cua_spaces_ffi_checksum_func_app_sign_in_failed(): number;
+ uniffi_cua_spaces_ffi_checksum_func_app_sign_in_failed_from_error(): number;
+ uniffi_cua_spaces_ffi_checksum_func_app_sign_in_footer(): number;
uniffi_cua_spaces_ffi_checksum_func_app_space_accepts_drop(): number;
uniffi_cua_spaces_ffi_checksum_func_app_space_detail(): number;
uniffi_cua_spaces_ffi_checksum_func_app_space_detail_copy(): number;
@@ -4693,6 +4740,7 @@ interface NativeModuleInterface {
uniffi_cua_spaces_ffi_checksum_func_app_telemetry_record(): number;
uniffi_cua_spaces_ffi_checksum_func_app_telemetry_share(): number;
uniffi_cua_spaces_ffi_checksum_func_app_telemetry_sign_in_failed(): number;
+ uniffi_cua_spaces_ffi_checksum_func_app_telemetry_sign_in_failure(): number;
uniffi_cua_spaces_ffi_checksum_func_app_telemetry_start(): number;
uniffi_cua_spaces_ffi_checksum_func_app_telemetry_storage(): number;
uniffi_cua_spaces_ffi_checksum_func_app_telemetry_welcome_left(): number;
diff --git a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
index abaa9dcc9c..feb81ec200 100644
--- a/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
+++ b/apps/cua-spaces-desktop/src/native/generated/cua_spaces_ffi.ts
@@ -4471,6 +4471,69 @@ export function appSidebar(spaces: Array<AppSpace>, query: string, selectedId: s
));
}
+/**
+ * The failed phase for a known reason, with the error's words for Details.
+ */
+export function appSignInFailed(reason: AppSignInFailure, detail: string | undefined): AppSignInPhase {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterTypeAppSignInPhase.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_spaces_ffi_fn_func_app_sign_in_failed(
+ FfiConverterTypeAppSignInFailure.lower(reason, nativeModule().rustbuffer_alloc),
+ FfiConverterOptionalString.lower(detail, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * The failed phase for an error the shell caught: the SDK error's case
+ * (`Timeout`, `Http`, ...; empty for another error) and its words.
+ */
+export function appSignInFailedFromError(variant: string, message: string): AppSignInPhase {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterTypeAppSignInPhase.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_spaces_ffi_fn_func_app_sign_in_failed_from_error(
+ FfiConverterString.lower(variant, nativeModule().rustbuffer_alloc),
+ FfiConverterString.lower(message, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
+/**
+ * The sidebar's foot: every sign-in state in one place.
+ */
+export function appSignInFooter(input: AppSignInFooterInput): AppSignInFooter {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterTypeAppSignInFooter.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_spaces_ffi_fn_func_app_sign_in_footer(
+ FfiConverterTypeAppSignInFooterInput.lower(input, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
/**
* Whether a Space takes a teleport drop (the notch tiles' and the Space
* rows' rule).
@@ -5259,6 +5322,26 @@ export function appTelemetrySignInFailed(message: string | undefined): Array<App
));
}
+/**
+ * A sign-in failed for `reason` or was cancelled (none): its kind only.
+ */
+export function appTelemetrySignInFailure(reason: AppSignInFailure | undefined): Array<AppTelemetrySignal> {
+ return ((__rb: Uint8Array) => {
+ try {
+ return FfiConverterSequenceTypeAppTelemetrySignal.lift(__rb);
+ } finally {
+ nativeModule().rustbuffer_free(__rb);
+ }
+ })(uniffiCaller.rustCall(
+ /*caller:*/ (callStatus) => {
+ return nativeModule().uniffi_cua_spaces_ffi_fn_func_app_telemetry_sign_in_failure(
+ FfiConverterOptionalTypeAppSignInFailure.lower(reason, nativeModule().rustbuffer_alloc),
+ callStatus);
+ },
+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),
+ ));
+ }
+
/**
* The app started: attributes this process's events to `spaces_app` at
* `version`, links usage data to the signed-in account in the background
@@ -35885,6 +35968,73 @@ const FfiConverterTypeAppSettings = (() => {
return new FFIConverter();
})();
+export enum AppSignInFailure {
+ /**
+ * The browser never confirmed: the wait ran out, or the code expired
+ * before it was confirmed.
+ */
+ NotConfirmed = "notConfirmed",
+ /**
+ * The person declined it in the browser.
+ */
+ Declined = "declined",
+ /**
+ * The sign-in service refused the code (expired or already used).
+ */
+ CodeRejected = "codeRejected",
+ /**
+ * This computer could not reach the sign-in service.
+ */
+ Offline = "offline",
+ /**
+ * The sign-in service answered with its own error.
+ */
+ ServiceUnavailable = "serviceUnavailable",
+ /**
+ * Signed in, but the session could not be stored on this computer (a
+ * locked keychain, a credential store that refused the write).
+ */
+ CouldNotSave = "couldNotSave",
+ /**
+ * Anything else (the words are behind Details).
+ */
+ Unknown = "unknown"
+}
+
+const FfiConverterTypeAppSignInFailure = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = AppSignInFailure;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return AppSignInFailure.NotConfirmed;
+ case 2: return AppSignInFailure.Declined;
+ case 3: return AppSignInFailure.CodeRejected;
+ case 4: return AppSignInFailure.Offline;
+ case 5: return AppSignInFailure.ServiceUnavailable;
+ case 6: return AppSignInFailure.CouldNotSave;
+ case 7: return AppSignInFailure.Unknown;
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value) {
+ case AppSignInFailure.NotConfirmed: return ordinalConverter.write(1, into);
+ case AppSignInFailure.Declined: return ordinalConverter.write(2, into);
+ case AppSignInFailure.CodeRejected: return ordinalConverter.write(3, into);
+ case AppSignInFailure.Offline: return ordinalConverter.write(4, into);
+ case AppSignInFailure.ServiceUnavailable: return ordinalConverter.write(5, into);
+ case AppSignInFailure.CouldNotSave: return ordinalConverter.write(6, into);
+ case AppSignInFailure.Unknown: return ordinalConverter.write(7, into);
+ }
+ }
+ allocationSize(value: TypeName): number {
+ return ordinalConverter.allocationSize(0);
+ }
+ }
+ return new FFIConverter();
+})();
+
// Enum: AppSignInPhase
export enum AppSignInPhase_Tags {
@@ -35952,7 +36102,7 @@ export const AppSignInPhase = (() => {
type Waiting__interface = {
tag: AppSignInPhase_Tags.Waiting;
inner:
-Readonly<{userCode?: string}>
+Readonly<{userCode?: string; opened: boolean}>
};
/**
* The browser is open.
@@ -35965,15 +36115,15 @@ Readonly<{userCode?: string}>
readonly [uniffiTypeNameSymbol] = "AppSignInPhase";
readonly tag = AppSignInPhase_Tags.Waiting;
readonly inner:
-Readonly<{userCode?: string}>;
+Readonly<{userCode?: string; opened: boolean}>;
constructor(
-inner: {userCode?: string }) {
+inner: {userCode?: string; opened: boolean }) {
super("AppSignInPhase", "Waiting");
this.inner = Object.freeze(inner);
}
static new(
-inner: {userCode?: string }): Waiting_ {
+inner: {userCode?: string; opened: boolean }): Waiting_ {
return new Waiting_(inner);
}
@@ -35986,10 +36136,10 @@ inner: {userCode?: string }): Waiting_ {
type Failed__interface = {
tag: AppSignInPhase_Tags.Failed;
inner:
-Readonly<{message: string}>
+Readonly<{reason: AppSignInFailure; message: string; detail?: string}>
};
/**
- * It failed.
+ * It failed ([`crate::sign_in::failed`] makes it).
*/
class Failed_ extends UniffiEnum implements Failed__interface {
/**
@@ -35999,15 +36149,15 @@ Readonly<{message: string}>
readonly [uniffiTypeNameSymbol] = "AppSignInPhase";
readonly tag = AppSignInPhase_Tags.Failed;
readonly inner:
-Readonly<{message: string}>;
+Readonly<{reason: AppSignInFailure; message: string; detail?: string}>;
constructor(
-inner: {message: string }) {
+inner: {reason: AppSignInFailure; message: string; detail?: string }) {
super("AppSignInPhase", "Failed");
this.inner = Object.freeze(inner);
}
static new(
-inner: {message: string }): Failed_ {
+inner: {reason: AppSignInFailure; message: string; detail?: string }): Failed_ {
return new Failed_(inner);
}
@@ -36043,8 +36193,8 @@ const FfiConverterTypeAppSignInPhase = (() => {
switch (ordinalConverter.read(from)) {
case 1: return new AppSignInPhase.Idle();
case 2: return new AppSignInPhase.Starting();
- case 3: return new AppSignInPhase.Waiting({userCode: FfiConverterOptionalString.read(from) });
- case 4: return new AppSignInPhase.Failed({message: FfiConverterString.read(from) });
+ case 3: return new AppSignInPhase.Waiting({userCode: FfiConverterOptionalString.read(from), opened: FfiConverterBool.read(from) });
+ case 4: return new AppSignInPhase.Failed({reason: FfiConverterTypeAppSignInFailure.read(from), message: FfiConverterString.read(from), detail: FfiConverterOptionalString.read(from) });
default: throw new UniffiInternalError.UnexpectedEnumCase();
}
}
@@ -36062,12 +36212,15 @@ const FfiConverterTypeAppSignInPhase = (() => {
ordinalConverter.write(3, into);
const inner = value.inner;
FfiConverterOptionalString.write(inner.userCode, into);
+ FfiConverterBool.write(inner.opened, into);
return;
}
case AppSignInPhase_Tags.Failed: {
ordinalConverter.write(4, into);
const inner = value.inner;
+ FfiConverterTypeAppSignInFailure.write(inner.reason, into);
FfiConverterString.write(inner.message, into);
+ FfiConverterOptionalString.write(inner.detail, into);
return;
}
default:
@@ -36087,12 +36240,15 @@ const FfiConverterTypeAppSignInPhase = (() => {
const inner = value.inner;
let size = ordinalConverter.allocationSize(3);
size += FfiConverterOptionalString.allocationSize(inner.userCode);
+ size += FfiConverterBool.allocationSize(inner.opened);
return size;
}
case AppSignInPhase_Tags.Failed: {
const inner = value.inner;
let size = ordinalConverter.allocationSize(4);
+ size += FfiConverterTypeAppSignInFailure.allocationSize(inner.reason);
size += FfiConverterString.allocationSize(inner.message);
+ size += FfiConverterOptionalString.allocationSize(inner.detail);
return size;
}
default: throw new UniffiInternalError.UnexpectedEnumCase();
@@ -37877,6 +38033,298 @@ const FfiConverterTypeAppSidebarView = (() => {
return new FFIConverter();
})();
+export enum AppSignInFooterState {
+ /**
+ * Not signed in: "Sign in".
+ */
+ SignedOut = "signedOut",
+ /**
+ * Asking for a code / opening the browser.
+ */
+ Starting = "starting",
+ /**
+ * The browser is open.
+ */
+ Waiting = "waiting",
+ /**
+ * It failed: the reason and Try again.
+ */
+ Failed = "failed",
+ /**
+ * Signed in.
+ */
+ SignedIn = "signedIn"
+}
+
+const FfiConverterTypeAppSignInFooterState = (() => {
+ const ordinalConverter = FfiConverterInt32;
+ type TypeName = AppSignInFooterState;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ switch (ordinalConverter.read(from)) {
+ case 1: return AppSignInFooterState.SignedOut;
+ case 2: return AppSignInFooterState.Starting;
+ case 3: return AppSignInFooterState.Waiting;
+ case 4: return AppSignInFooterState.Failed;
+ case 5: return AppSignInFooterState.SignedIn;
+ default: throw new UniffiInternalError.UnexpectedEnumCase();
+ }
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ switch (value) {
+ case AppSignInFooterState.SignedOut: return ordinalConverter.write(1, into);
+ case AppSignInFooterState.Starting: return ordinalConverter.write(2, into);
+ case AppSignInFooterState.Waiting: return ordinalConverter.write(3, into);
+ case AppSignInFooterState.Failed: return ordinalConverter.write(4, into);
+ case AppSignInFooterState.SignedIn: return ordinalConverter.write(5, into);
+ }
+ }
+ allocationSize(value: TypeName): number {
+ return ordinalConverter.allocationSize(0);
+ }
+ }
+ return new FFIConverter();
+})();
+
+export type AppSignInToast = {
+ /**
+ * "Sign-in didn't finish".
+ */
+ title: string,
+ /**
+ * The reason (none for an unknown one).
+ */
+ body?: string
+}
+
+/**
+ * Generated factory for {@link AppSignInToast} record objects.
+ */
+export const AppSignInToast = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<AppSignInToast, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<AppSignInToast>,
+ });
+})();
+
+const FfiConverterTypeAppSignInToast = (() => {
+ type TypeName = AppSignInToast;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ title: FfiConverterString.read(from),
+ body: FfiConverterOptionalString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.title, into);
+ FfiConverterOptionalString.write(value.body, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.title) +
+ FfiConverterOptionalString.allocationSize(value.body);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type AppSignInFooter = {
+ /**
+ * Which state.
+ */
+ state: AppSignInFooterState,
+ /**
+ * The line: "Signed in as …", "Waiting for your browser…", "Sign-in
+ * didn't finish. …", "Not signed in".
+ */
+ text: string,
+ /**
+ * The signed-in account (state `SignedIn`).
+ */
+ identity?: string,
+ /**
+ * Waiting: the code to confirm in the browser.
+ */
+ code?: string,
+ /**
+ * "Code".
+ */
+ codeLabel: string,
+ /**
+ * Waiting with a page: "Open again".
+ */
+ reopenLabel?: string,
+ /**
+ * Starting or waiting: "Cancel".
+ */
+ cancelLabel?: string,
+ /**
+ * "Sign in" or "Try again" (none while signed in or waiting).
+ */
+ actionLabel?: string,
+ /**
+ * Failed: why.
+ */
+ reason?: AppSignInFailure,
+ /**
+ * Failed: the error's own words, behind "Details".
+ */
+ detail?: string,
+ /**
+ * "Details".
+ */
+ detailsLabel: string,
+ /**
+ * Failed: the toast the shell shows once, when it fails.
+ */
+ toast?: AppSignInToast
+}
+
+/**
+ * Generated factory for {@link AppSignInFooter} record objects.
+ */
+export const AppSignInFooter = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<AppSignInFooter, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<AppSignInFooter>,
+ });
+})();
+
+const FfiConverterTypeAppSignInFooter = (() => {
+ type TypeName = AppSignInFooter;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ state: FfiConverterTypeAppSignInFooterState.read(from),
+ text: FfiConverterString.read(from),
+ identity: FfiConverterOptionalString.read(from),
+ code: FfiConverterOptionalString.read(from),
+ codeLabel: FfiConverterString.read(from),
+ reopenLabel: FfiConverterOptionalString.read(from),
+ cancelLabel: FfiConverterOptionalString.read(from),
+ actionLabel: FfiConverterOptionalString.read(from),
+ reason: FfiConverterOptionalTypeAppSignInFailure.read(from),
+ detail: FfiConverterOptionalString.read(from),
+ detailsLabel: FfiConverterString.read(from),
+ toast: FfiConverterOptionalTypeAppSignInToast.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterTypeAppSignInFooterState.write(value.state, into);
+ FfiConverterString.write(value.text, into);
+ FfiConverterOptionalString.write(value.identity, into);
+ FfiConverterOptionalString.write(value.code, into);
+ FfiConverterString.write(value.codeLabel, into);
+ FfiConverterOptionalString.write(value.reopenLabel, into);
+ FfiConverterOptionalString.write(value.cancelLabel, into);
+ FfiConverterOptionalString.write(value.actionLabel, into);
+ FfiConverterOptionalTypeAppSignInFailure.write(value.reason, into);
+ FfiConverterOptionalString.write(value.detail, into);
+ FfiConverterString.write(value.detailsLabel, into);
+ FfiConverterOptionalTypeAppSignInToast.write(value.toast, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterTypeAppSignInFooterState.allocationSize(value.state) +
+ FfiConverterString.allocationSize(value.text) +
+ FfiConverterOptionalString.allocationSize(value.identity) +
+ FfiConverterOptionalString.allocationSize(value.code) +
+ FfiConverterString.allocationSize(value.codeLabel) +
+ FfiConverterOptionalString.allocationSize(value.reopenLabel) +
+ FfiConverterOptionalString.allocationSize(value.cancelLabel) +
+ FfiConverterOptionalString.allocationSize(value.actionLabel) +
+ FfiConverterOptionalTypeAppSignInFailure.allocationSize(value.reason) +
+ FfiConverterOptionalString.allocationSize(value.detail) +
+ FfiConverterString.allocationSize(value.detailsLabel) +
+ FfiConverterOptionalTypeAppSignInToast.allocationSize(value.toast);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
+export type AppSignInFooterInput = {
+ /**
+ * The signed-in account.
+ */
+ identity?: string,
+ /**
+ * Cua Cloud works through client credentials (an API key).
+ */
+ cloudConfigured: boolean,
+ /**
+ * Signing in is possible here.
+ */
+ canSignIn: boolean,
+ /**
+ * The sign-in in progress.
+ */
+ signIn: AppSignInPhase,
+ /**
+ * The page the sign-in finishes on is known (Open again).
+ */
+ hasUrl: boolean
+}
+
+/**
+ * Generated factory for {@link AppSignInFooterInput} record objects.
+ */
+export const AppSignInFooterInput = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<AppSignInFooterInput, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<AppSignInFooterInput>,
+ });
+})();
+
+const FfiConverterTypeAppSignInFooterInput = (() => {
+ type TypeName = AppSignInFooterInput;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ identity: FfiConverterOptionalString.read(from),
+ cloudConfigured: FfiConverterBool.read(from),
+ canSignIn: FfiConverterBool.read(from),
+ signIn: FfiConverterTypeAppSignInPhase.read(from),
+ hasUrl: FfiConverterBool.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterOptionalString.write(value.identity, into);
+ FfiConverterBool.write(value.cloudConfigured, into);
+ FfiConverterBool.write(value.canSignIn, into);
+ FfiConverterTypeAppSignInPhase.write(value.signIn, into);
+ FfiConverterBool.write(value.hasUrl, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterOptionalString.allocationSize(value.identity) +
+ FfiConverterBool.allocationSize(value.cloudConfigured) +
+ FfiConverterBool.allocationSize(value.canSignIn) +
+ FfiConverterTypeAppSignInPhase.allocationSize(value.signIn) +
+ FfiConverterBool.allocationSize(value.hasUrl);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export enum AppAgentStatus {
/**
* A turn is running.
@@ -63509,6 +63957,12 @@ const FfiConverterSequenceTypeAppSidebarSection = new FfiConverterArray(FfiConve
// FfiConverter for AppMsg | undefined
const FfiConverterOptionalTypeAppMsg = new FfiConverterOptional(FfiConverterTypeAppMsg);
+// FfiConverter for AppSignInFailure | undefined
+const FfiConverterOptionalTypeAppSignInFailure = new FfiConverterOptional(FfiConverterTypeAppSignInFailure);
+
+// FfiConverter for AppSignInToast | undefined
+const FfiConverterOptionalTypeAppSignInToast = new FfiConverterOptional(FfiConverterTypeAppSignInToast);
+
// FfiConverter for Array<AppDetailAction>
const FfiConverterSequenceTypeAppDetailAction = new FfiConverterArray(FfiConverterTypeAppDetailAction);
@@ -64467,6 +64921,15 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_sidebar() !== 2197) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_sidebar");
}
+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_sign_in_failed() !== 6165) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_sign_in_failed");
+ }
+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_sign_in_failed_from_error() !== 6411) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_sign_in_failed_from_error");
+ }
+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_sign_in_footer() !== 8779) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_sign_in_footer");
+ }
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_space_accepts_drop() !== 51121) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_space_accepts_drop");
}
@@ -64578,6 +65041,9 @@ function uniffiEnsureInitialized() {
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_telemetry_sign_in_failed() !== 34262) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_telemetry_sign_in_failed");
}
+ if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_telemetry_sign_in_failure() !== 23014) {
+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_telemetry_sign_in_failure");
+ }
if (nativeModule().uniffi_cua_spaces_ffi_checksum_func_app_telemetry_start() !== 30125) {
throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_spaces_ffi_checksum_func_app_telemetry_start");
}
@@ -65243,7 +65709,12 @@ export default Object.freeze({
FfiConverterTypeAppSidebarRow,
FfiConverterTypeAppSidebarSection,
FfiConverterTypeAppSidebarView,
+ FfiConverterTypeAppSignInFailure,
+ FfiConverterTypeAppSignInFooter,
+ FfiConverterTypeAppSignInFooterInput,
+ FfiConverterTypeAppSignInFooterState,
FfiConverterTypeAppSignInPhase,
+ FfiConverterTypeAppSignInToast,
FfiConverterTypeAppSpace,
FfiConverterTypeAppSpaceAgentRun,
FfiConverterTypeAppSpaceDetail,
diff --git a/apps/cua-spaces-desktop/test/bridge-native.test.ts b/apps/cua-spaces-desktop/test/bridge-native.test.ts
index 239552a4ca..869680d3f0 100644
--- a/apps/cua-spaces-desktop/test/bridge-native.test.ts
+++ b/apps/cua-spaces-desktop/test/bridge-native.test.ts
@@ -319,6 +319,25 @@ describe.skipIf(!built)("the bridge on the app core", () => {
expect(sessionEvents()).toBe(2);
});
+ it("says why a sign-in failed, typed, so the page never keeps waiting", async () => {
+ await call("session.signOut");
+ await call("session.signIn");
+ await until(() => model.signIn.tag === "Waiting");
+ account.failSignIn(new Error("could not reach the sign-in service: error sending request"));
+ await until(() => model.signIn.tag === "Failed");
+ expect(await call("session.get")).toMatchObject({
+ signIn: {
+ type: "failed",
+ reason: "offline",
+ message: "Sign-in didn't finish. Can't reach Cua. Check your connection.",
+ detail: "could not reach the sign-in service: error sending request",
+ },
+ signInUrl: null,
+ });
+ const kinds = telemetry.recorded.flatMap((s) => (s.tag === "SignInFailed" ? [s.inner.errorKind] : []));
+ expect(kinds.at(-1)).toBe("transport");
+ });
+
it("answers the Machines page from the host and the relay's devices", async () => {
const m = (await call("machines.list")) as Record<string, unknown>;
expect(m.signedIn).toBe(true);
diff --git a/apps/cua-spaces-desktop/test/fixtures.ts b/apps/cua-spaces-desktop/test/fixtures.ts
index 4d41acc22e..d05d3b48b8 100644
--- a/apps/cua-spaces-desktop/test/fixtures.ts
+++ b/apps/cua-spaces-desktop/test/fixtures.ts
@@ -358,6 +358,7 @@ export function fixtureDevices(now = BigInt(Math.floor(Date.now() / 1000))): Dev
export class FixtureAccount implements AccountRunning {
current: string | null;
private finish: ((who: string) => void) | null = null;
+ private fail: ((e: Error) => void) | null = null;
constructor(identity: string | null = null) {
this.current = identity;
}
@@ -368,7 +369,7 @@ export class FixtureAccount implements AccountRunning {
return this.current ? { email: this.current } : null;
}
async beginSignIn(): Promise<SignInAttempt> {
- const done = new Promise<string>((resolve) => (this.finish = resolve));
+ const done = new Promise<string>((resolve, reject) => ((this.finish = resolve), (this.fail = reject)));
return {
userCode: "ABCD-1234",
url: "https://cua.ai/device",
@@ -381,6 +382,10 @@ export class FixtureAccount implements AccountRunning {
completeSignIn(who: string) {
this.finish?.(who);
}
+ /** The sign-in fails (the network dropped, the code expired). */
+ failSignIn(error: Error) {
+ this.fail?.(error);
+ }
async signOut() {
this.current = null;
}
diff --git a/apps/cua-spaces-desktop/test/sign-in-browser.test.ts b/apps/cua-spaces-desktop/test/sign-in-browser.test.ts
index 78115c0ac1..10bcb60622 100644
--- a/apps/cua-spaces-desktop/test/sign-in-browser.test.ts
+++ b/apps/cua-spaces-desktop/test/sign-in-browser.test.ts
@@ -60,14 +60,15 @@ describe("the account's sign-in", () => {
const a = await new LiveAccount(auth, async (url) => (opened.push(url), true)).beginSignIn();
expect(flows).toEqual([undefined]);
expect(opened).toEqual(["https://auth.cua.ai/authorize?x=1"]);
- expect([a.url, a.userCode]).toEqual(["https://auth.cua.ai/authorize?x=1", null]);
+ expect([a.url, a.userCode, a.opened]).toEqual(["https://auth.cua.ai/authorize?x=1", null, true]);
});
it("uses the device flow without a browser: a page for any device and its code", async () => {
const { auth, flows } = fakeAuth();
const a = await new LiveAccount(auth, async () => false).beginSignIn();
expect(flows).toEqual([undefined, "device"]);
- expect([a.url, a.userCode]).toEqual(["https://auth.cua.ai/device", "WDJB-MJHT"]);
+ // The foot says to open the page (no browser to wait on).
+ expect([a.url, a.userCode, a.opened]).toEqual(["https://auth.cua.ai/device", "WDJB-MJHT", false]);
expect(await a.wait()).toBe("[email protected]");
});
});
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 262d6f6a45..2c3e15e86d 100644
--- a/apps/cua-spaces-desktop/test/sign-in-runs.test.ts
+++ b/apps/cua-spaces-desktop/test/sign-in-runs.test.ts
@@ -6,7 +6,7 @@
// 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 { SignInRuns, type SignInEnd, 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. */
@@ -44,7 +44,7 @@ class RetryAccount implements AccountRunning {
}
function view() {
- const seen = { phase: "idle", url: null as string | null, identity: null as string | null, failed: [] as string[], signedIn: 0 };
+ const seen = { phase: "idle", url: null as string | null, identity: null as string | null, failed: [] as SignInEnd[], signedIn: 0 };
const v: SignInView = {
starting: () => void (seen.phase = "starting"),
waiting: (a) => void ((seen.phase = "waiting"), (seen.url = a.url)),
@@ -122,6 +122,18 @@ describe("a retried sign-in", () => {
void runs.begin();
await flush();
await vi.advanceTimersByTimeAsync(runs.timeoutMs);
- expect(seen).toMatchObject({ phase: "failed", failed: [SIGN_IN_TIMED_OUT], signedIn: 0 });
+ expect(seen).toMatchObject({ phase: "failed", failed: [{ timedOut: true }], signedIn: 0 });
+ });
+
+ it("fails with the error it caught (the core reads its reason), never silently", async () => {
+ const account = new RetryAccount();
+ const { seen, v } = view();
+ const runs = new SignInRuns(() => account, v);
+ const run = runs.begin();
+ await flush();
+ const offline = new Error("could not reach the sign-in service: error sending request");
+ account.attempts[0]!.fail(offline);
+ await run;
+ expect(seen).toMatchObject({ phase: "failed", failed: [{ error: offline }], signedIn: 0 });
});
});
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
index 006745dc27..b537d2c8fd 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
@@ -114,6 +114,8 @@ public final class AppModel {
public private(set) var signIn: AppSignInPhase = .idle
/// The page a waiting sign-in finishes on ("Open the browser again").
public private(set) var signInURL: URL?
+ /// A failed sign-in's toast (the classic window shows it for a while).
+ public var signInToast: AppSignInToast?
/// A sign-in still waiting after this fails (a device code lives
/// about this long).
public var signInTimeout: Duration = .seconds(600)
@@ -1290,24 +1292,44 @@ public final class AppModel {
/// "Sign in" / "Sign in to Cua": the browser flow, the code while it waits.
public func beginSignIn() async {
- guard let account, signIn != .starting else { return }
+ guard let current = startSignIn() 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? {
+ guard account != nil, signIn != .starting else { return nil }
signIn = .starting
+ signInURL = nil
signInAttempt += 1
- let current = signInAttempt
+ return signInAttempt
+ }
+
+ /// Runs attempt `current`: every way it ends is shown (`signIn`), never
+ /// a silent stop.
+ func runSignIn(_ current: Int) async {
+ guard let account else { return }
do {
let attempt = try await account.beginSignIn()
- // Cancelled while it started.
+ // Cancelled, retried or signed in while it started.
guard signInAttempt == current, signIn == .starting else { return }
- signIn = .waiting(userCode: attempt.userCode)
+ signIn = .waiting(userCode: attempt.userCode, opened: attempt.opened)
signInURL = attempt.url
let timeout = signInTimeout
Task { @MainActor [weak self] in
try? await Task.sleep(for: timeout)
guard let self, self.signInAttempt == current, case .waiting = self.signIn else { return }
- self.signInFailed("The sign-in timed out. Try again.")
+ self.signInFailed(appSignInFailed(reason: .notConfirmed, detail: nil))
}
let who = try await attempt.wait()
- guard signInAttempt == current, case .waiting = signIn else { return }
+ // Whichever attempt the browser finished stored the session:
+ // take it, even when a retry or Cancel superseded this one (an
+ // earlier tab confirmed after all). Only a sign-out since then
+ // leaves it.
+ guard signInAttempt == current || identity == nil else { return }
+ signInAttempt += 1
let previous = identity
identity = who ?? account.identity()
host.identity = identity
@@ -1326,17 +1348,22 @@ public final class AppModel {
await reloadTeams()
await reloadShareRemovals()
} catch {
+ // A superseded attempt (a retry, Cancel) ends quietly; the one
+ // shown fails with its reason.
guard signInAttempt == current, signIn != .idle else { return }
- signInFailed(LiveSpacesBackend.words(error))
+ let variant = (error as? CuaError).flatMap { Mirror(reflecting: $0).children.first?.label } ?? ""
+ signInFailed(appSignInFailedFromError(variant: variant, message: LiveSpacesBackend.words(error)))
}
}
- /// Shown where the sign-in was started; counted by its kind only (the
- /// core keeps the words).
- private func signInFailed(_ message: String) {
- signIn = .failed(message: message)
+ /// Shown where the sign-in was started and in the sidebar's foot, with
+ /// a toast; counted by its kind only (the core keeps the words).
+ private func signInFailed(_ phase: AppSignInPhase) {
+ signIn = phase
signInURL = nil
- telemetry?.record(appTelemetrySignInFailed(message: message))
+ guard case let .failed(reason, _, _) = phase else { return }
+ signInToast = signInFooter.toast
+ telemetry?.record(appTelemetrySignInFailure(reason: reason))
}
/// Stops waiting for the browser (the page can start again).
@@ -1344,13 +1371,26 @@ public final class AppModel {
switch signIn {
case .starting, .waiting:
signInAttempt += 1
- telemetry?.record(appTelemetrySignInFailed(message: nil))
+ telemetry?.record(appTelemetrySignInFailure(reason: nil))
default: break
}
signIn = .idle
signInURL = nil
}
+ /// Opens the sign-in page again (the tab was closed).
+ public func reopenSignIn() {
+ guard let signInURL else { return }
+ NSWorkspace.shared.open(signInURL)
+ }
+
+ /// The sidebar's foot: every sign-in state in one place.
+ public var signInFooter: AppSignInFooter {
+ appSignInFooter(input: AppSignInFooterInput(identity: identity, cloudConfigured: cloudConfigured,
+ canSignIn: account != nil, signIn: signIn,
+ hasUrl: signInURL != nil))
+ }
+
public func signOut() async {
try? await account?.signOut()
identity = nil
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
index 4b9ec31d34..bcc3034d94 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppServices.swift
@@ -247,11 +247,16 @@ public struct SignInAttempt: Sendable {
public var userCode: String?
/// The page the sign-in finishes on (to open it again).
public var url: URL?
+ /// A browser opened on this Mac (false: the page is to be opened by
+ /// hand, here or on another device).
+ public var opened: Bool
public var wait: @Sendable () async throws -> String?
- public init(userCode: String?, url: URL? = nil, wait: @escaping @Sendable () async throws -> String?) {
+ public init(userCode: String?, url: URL? = nil, opened: Bool = true,
+ wait: @escaping @Sendable () async throws -> String?) {
self.userCode = userCode
self.url = url
+ self.opened = opened
self.wait = wait
}
}
@@ -312,16 +317,26 @@ public final class LiveAccount: AccountRunning, @unchecked Sendable {
public func beginSignIn() 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)
- let attempt = try await auth.beginLogin(flow: nil)
- let url = URL(string: attempt.url())
- if let url {
- await MainActor.run { _ = NSWorkspace.shared.open(url) }
+ var attempt = try await auth.beginLogin(flow: 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.
+ if !opened, attempt.method() == .browser {
+ attempt = try await auth.beginLogin(flow: "device")
+ opened = await Self.open(attempt.url())
}
- return SignInAttempt(userCode: attempt.userCode(), url: url) {
- Self.display(try await attempt.wait())
+ let started = attempt
+ return SignInAttempt(userCode: started.userCode(), url: URL(string: started.url()), opened: opened) {
+ Self.display(try await started.wait())
}
}
+ /// Opens `link` in the default browser; false when nothing opened it.
+ static func open(_ link: String) async -> Bool {
+ guard let url = URL(string: link), !link.isEmpty else { return false }
+ return await MainActor.run { NSWorkspace.shared.open(url) }
+ }
+
public func signOut() async throws { _ = try await auth.logout() }
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift
index 3dc7badfc6..7f3a088014 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/MainWindow.swift
@@ -35,6 +35,7 @@ public struct MainWindow: View {
}
}
}
+ .overlay(alignment: .bottomTrailing) { SignInToastView(model: model) }
.background(WindowReader { model.dropTargets.window = $0 })
.searchable(text: $model.query, placement: .sidebar, prompt: chrome.searchPlaceholder)
.toolbar {
@@ -232,29 +233,115 @@ struct Sidebar: View {
private func badge(_ row: KvCategoryRow) -> Int { Int(row.badge ?? 0) }
}
-/// The sidebar's foot: the account line, Sign in when offered, Settings.
+/// The sidebar's foot: every sign-in state in one place (the core's
+/// `appSignInFooter`): signed in as, waiting for the browser with the code,
+/// Open again and Cancel, or why it failed with Try again; and Settings.
struct SidebarFooter: View {
let model: AppModel
+ @State private var showingDetails = false
var body: some View {
- let chrome = model.chrome
- HStack(spacing: 8) {
- Text(chrome.account)
- .lineLimit(1)
- .truncationMode(.middle)
- .foregroundStyle(.secondary)
- .accessibilityIdentifier("sidebar-account")
- Spacer(minLength: 4)
- if let label = chrome.signInLabel {
- Button(label) { Task { await model.beginSignIn() } }
- .controlSize(.small)
+ let f = model.signInFooter
+ HStack(alignment: .top, spacing: 8) {
+ VStack(alignment: .leading, spacing: 4) {
+ switch f.state {
+ case .starting, .waiting:
+ HStack(spacing: 6) {
+ ProgressView().controlSize(.mini)
+ Text(f.text).lineLimit(2)
+ }
+ .accessibilityElement(children: .combine)
+ .accessibilityIdentifier("sidebar-signin-waiting")
+ // The code on its own line (it never wraps), then
+ // Open again and Cancel.
+ if let code = f.code {
+ Text("\(f.codeLabel) \(Text(code).font(.callout.monospaced().weight(.semibold)).foregroundStyle(.primary))")
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ .textSelection(.enabled)
+ .lineLimit(1)
+ .fixedSize()
+ .padding(.leading, 20)
+ }
+ HStack(spacing: 4) {
+ if let reopen = f.reopenLabel {
+ Button(reopen) { model.reopenSignIn() }
+ .buttonStyle(.link)
+ .accessibilityIdentifier("sidebar-signin-reopen")
+ Text("\u{b7}")
+ }
+ if let cancel = f.cancelLabel {
+ Button(cancel) { model.cancelSignIn() }
+ .buttonStyle(.link)
+ .accessibilityIdentifier("sidebar-signin-cancel")
+ }
+ }
+ .lineLimit(1)
+ .fixedSize()
+ .padding(.leading, 20)
+ .font(.callout)
+ .foregroundStyle(.secondary)
+ case .failed:
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ Image(systemName: "exclamationmark.triangle")
+ .foregroundStyle(.red)
+ Text(f.text)
+ .lineLimit(4)
+ .accessibilityIdentifier("sidebar-signin-failed")
+ }
+ HStack(spacing: 8) {
+ if let retry = f.actionLabel {
+ Button(retry) { Task { await model.beginSignIn() } }
+ .controlSize(.small)
+ .accessibilityIdentifier("sidebar-signin-retry")
+ }
+ if let detail = f.detail {
+ Button(f.detailsLabel) { showingDetails.toggle() }
+ .buttonStyle(.link)
+ .font(.callout)
+ .popover(isPresented: $showingDetails) {
+ Text(detail)
+ .font(.callout.monospaced())
+ .textSelection(.enabled)
+ .frame(width: 280, alignment: .leading)
+ .padding(12)
+ }
+ }
+ }
+ .padding(.leading, 20)
+ case .signedIn:
+ // "Signed in as", then the whole address on its own line.
+ VStack(alignment: .leading, spacing: 1) {
+ Text("Signed in as").font(.caption).foregroundStyle(.secondary)
+ Text(f.identity ?? f.text)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ }
+ .help(f.text)
+ .accessibilityElement(children: .combine)
+ .accessibilityIdentifier("sidebar-account")
+ case .signedOut:
+ HStack(spacing: 8) {
+ Text(f.text)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .foregroundStyle(.secondary)
+ .accessibilityIdentifier("sidebar-account")
+ Spacer(minLength: 4)
+ if let label = f.actionLabel {
+ Button(label) { Task { await model.beginSignIn() } }
+ .controlSize(.small)
+ }
+ }
+ }
}
+ .frame(maxWidth: .infinity, alignment: .leading)
SettingsLink {
Image(systemName: "gearshape")
}
.buttonStyle(.borderless)
- .help(chrome.settingsLabel)
- .accessibilityLabel(chrome.settingsLabel)
+ .help(model.chrome.settingsLabel)
+ .accessibilityLabel(model.chrome.settingsLabel)
}
.padding(.horizontal, 12)
.padding(.vertical, 8)
@@ -262,6 +349,44 @@ struct SidebarFooter: View {
}
}
+/// A failed sign-in's toast: seen wherever the window is, then gone (the
+/// sidebar's foot keeps the reason and Try again).
+struct SignInToastView: View {
+ let model: AppModel
+
+ var body: some View {
+ if let toast = model.signInToast {
+ HStack(alignment: .top, spacing: 8) {
+ Image(systemName: "exclamationmark.circle.fill").foregroundStyle(.red)
+ VStack(alignment: .leading, spacing: 2) {
+ Text(toast.title).font(.headline)
+ if let body = toast.body {
+ Text(body).font(.callout).foregroundStyle(.secondary)
+ }
+ }
+ Button {
+ model.signInToast = nil
+ } label: {
+ Image(systemName: "xmark").font(.caption)
+ }
+ .buttonStyle(.borderless)
+ .accessibilityLabel("Dismiss")
+ }
+ .padding(12)
+ .frame(width: 300, alignment: .leading)
+ .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12))
+ .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(.separator))
+ .shadow(radius: 8, y: 2)
+ .padding(16)
+ .accessibilityIdentifier("signin-toast")
+ .task(id: toast) {
+ try? await Task.sleep(for: .seconds(15))
+ if model.signInToast == toast { model.signInToast = nil }
+ }
+ }
+ }
+}
+
/// One Space row: its OS icon, the name and a status dot, dimmed when not
/// live, and outlined while a dragged window is over it. A Space that turns
/// off and on has a power button before its dot, shown on hover and on the
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
index 19a241a2cc..3e7057089e 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
@@ -251,9 +251,12 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
case "session.get": return session()
case "session.signIn":
- // The browser flow can take minutes: answer now, and
- // `session.changed` follows when it ends.
- Task { @MainActor in await model.beginSignIn() }
+ // 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() {
+ Task { @MainActor in await model.runSignIn(current) }
+ }
return session()
case "session.signOut":
await model.signOut()
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
index 052ce93851..2b6e2dcdc8 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/ViewModelTests.swift
@@ -457,7 +457,14 @@ struct ViewModelTests {
let model = makeModel(account: account, telemetry: telemetry)
let first = Task { await model.beginSignIn() }
try await waitUntil { if case .waiting = model.signIn { true } else { false } }
- #expect(model.signIn == .waiting(userCode: "ABCD-EFGH"))
+ #expect(model.signIn == .waiting(userCode: "ABCD-EFGH", opened: true))
+ // The sidebar's foot: the spinner line, the code, Open again, Cancel.
+ let waiting = model.signInFooter
+ #expect(waiting.state == .waiting)
+ #expect(waiting.text == "Waiting for your browser\u{2026}")
+ #expect(waiting.code == "ABCD-EFGH")
+ #expect(waiting.reopenLabel == "Open again")
+ #expect(waiting.cancelLabel == "Cancel")
#expect(model.signInURL?.absoluteString == "https://cua.ai/device")
model.cancelSignIn()
#expect(model.signIn == .idle)
@@ -467,7 +474,11 @@ struct ViewModelTests {
model.signInTimeout = .milliseconds(50)
let second = Task { await model.beginSignIn() }
try await waitUntil { if case .failed = model.signIn { true } else { false } }
- #expect(model.signIn == .failed(message: "The sign-in timed out. Try again."))
+ #expect(model.signIn == .failed(reason: .notConfirmed,
+ message: "Sign-in didn't finish. The browser didn't confirm in time.",
+ detail: nil))
+ #expect(model.signInFooter.actionLabel == "Try again")
+ #expect(model.signInToast?.title == "Sign-in didn't finish")
second.cancel()
let kinds = telemetry.recorded.compactMap { s -> String? in
if case let .signInFailed(kind) = s { return kind }
@@ -476,6 +487,76 @@ struct ViewModelTests {
#expect(kinds == ["cancelled", "timeout"])
}
+ /// Every way the account's sign-in fails is shown in the sidebar's
+ /// foot with its reason, Try again and a toast; never a silent stop.
+ @Test func everySignInFailureIsShownWithItsReason() async throws {
+ let cases: [(Error, AppSignInFailure, String)] = [
+ (CuaError.Http(message: "could not reach the sign-in service: error sending request"), .offline, "transport"),
+ (CuaError.Timeout(message: "device authorization expired before it was completed"), .notConfirmed, "timeout"),
+ (CuaError.Unauthenticated(message: "sign-in was declined in the browser: access_denied"), .declined, "permission_denied"),
+ (CuaError.Unauthenticated(message: "Code not valid"), .codeRejected, "unauthenticated"),
+ (CuaError.Http(message: "the sign-in service answered HTTP 503: down"), .serviceUnavailable, "http"),
+ (CuaError.Internal(message: "credential store: User interaction is not allowed."), .couldNotSave, "internal"),
+ ]
+ for (error, reason, kind) in cases {
+ for whileStarting in [true, false] {
+ let telemetry = FixtureTelemetry()
+ let account = FailingAccount(error: error, whileStarting: whileStarting)
+ let model = makeModel(account: account, telemetry: telemetry)
+ await model.beginSignIn()
+ guard case let .failed(got, message, detail) = model.signIn else {
+ Issue.record("\(error): \(model.signIn)")
+ continue
+ }
+ #expect(got == reason, "\(error)")
+ #expect(message.hasPrefix("Sign-in didn't finish. "))
+ #expect(detail == LiveSpacesBackend.words(error), "the words stay behind Details")
+ let footer = model.signInFooter
+ #expect(footer.state == .failed)
+ #expect(footer.actionLabel == "Try again")
+ #expect(footer.detail == detail)
+ #expect(model.signInToast != nil, "a failure toasts")
+ let kinds = telemetry.recorded.compactMap { s -> String? in
+ if case let .signInFailed(kind) = s { return kind }
+ return nil
+ }
+ #expect(kinds == [kind])
+ }
+ }
+ }
+
+ /// Open again or Try again starts a new attempt; when the person then
+ /// confirms the first tab, the app is signed in all the same.
+ @Test func anEarlierTabThatConfirmsStillSignsIn() async throws {
+ let account = TwoTabAccount()
+ let model = makeModel(account: account)
+ let first = Task { await model.beginSignIn() }
+ try await waitUntil { model.signIn == .waiting(userCode: "TAB-1", opened: true) }
+ model.cancelSignIn()
+ let second = Task { await model.beginSignIn() }
+ try await waitUntil { model.signIn == .waiting(userCode: "TAB-2", opened: true) }
+ account.confirm(tab: 1)
+ await first.value
+ #expect(model.identity == "[email protected]")
+ #expect(model.signIn == .idle)
+ #expect(model.signInFooter.text == "Signed in as [email protected]")
+ // The second attempt's own end is no longer shown.
+ account.fail(tab: 2)
+ await second.value
+ #expect(model.signIn == .idle)
+ }
+
+ /// No browser opened: the foot says to open the page instead of
+ /// waiting on a browser that is not there.
+ @Test func noBrowserSaysToOpenThePage() async throws {
+ let model = makeModel(account: StuckAccount(opened: false))
+ let task = Task { await model.beginSignIn() }
+ try await waitUntil { if case .waiting = model.signIn { true } else { false } }
+ #expect(model.signInFooter.text == "Open the sign-in page to continue.")
+ #expect(model.signInFooter.code == "ABCD-EFGH")
+ task.cancel()
+ }
+
func waitUntil(_ done: @MainActor () -> Bool) async throws {
for _ in 0..<200 where !done() { try await Task.sleep(for: .milliseconds(10)) }
#expect(done())
@@ -1412,12 +1493,57 @@ struct ViewModelTests {
/// An account whose browser sign-in never finishes.
final class StuckAccount: AccountRunning, @unchecked Sendable {
+ let opened: Bool
+ init(opened: Bool = true) { self.opened = opened }
func identity() -> String? { nil }
func beginSignIn() async throws -> SignInAttempt {
- SignInAttempt(userCode: "ABCD-EFGH", url: URL(string: "https://cua.ai/device")) {
+ SignInAttempt(userCode: "ABCD-EFGH", url: URL(string: "https://cua.ai/device"), opened: opened) {
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 {
+ let error: Error
+ let whileStarting: Bool
+ init(error: Error, whileStarting: Bool) {
+ self.error = error
+ self.whileStarting = whileStarting
+ }
+ func identity() -> String? { nil }
+ func beginSignIn() async throws -> SignInAttempt {
+ if whileStarting { throw error }
+ let error = error
+ return SignInAttempt(userCode: "ABCD-EFGH", url: URL(string: "https://cua.ai/device")) { throw error }
+ }
+ func signOut() async throws {}
+}
+
+/// An account with two browser tabs (two attempts) the test confirms or
+/// fails by hand.
+final class TwoTabAccount: AccountRunning, @unchecked Sendable {
+ private let lock = NSLock()
+ private var tabs: [Int: CheckedContinuation<String?, Error>] = [:]
+ private var started = 0
+ private var signedIn: String?
+
+ func identity() -> String? { lock.withLock { signedIn } }
+ func beginSignIn() async throws -> SignInAttempt {
+ let tab = lock.withLock { started += 1; return started }
+ return SignInAttempt(userCode: "TAB-\(tab)", url: URL(string: "https://cua.ai/device")) { [self] in
+ try await withCheckedThrowingContinuation { c in lock.withLock { tabs[tab] = c } }
+ }
+ }
+ func confirm(tab: Int) {
+ let c = lock.withLock { signedIn = "[email protected]"; return tabs.removeValue(forKey: tab) }
+ c?.resume(returning: "[email protected]")
+ }
+ func fail(tab: Int) {
+ lock.withLock { tabs.removeValue(forKey: tab) }?.resume(throwing: CuaError.Timeout(message: "expired"))
+ }
+ func signOut() async throws {}
+}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
index 576a3bf718..c1149b28d1 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/WebUIHostTests.swift
@@ -3,6 +3,7 @@
import AppKit
@testable import CuaSpacesMacKit
+import CuaSDK
import CuaSpacesFFI
import Foundation
import Testing
@@ -40,9 +41,40 @@ struct WebUIHostTests {
#expect(BridgeValue.encode(Optional<String>.none) is NSNull)
#expect(BridgeValue.encode([1, 2]) as? [Int] == [1, 2])
#expect(BridgeValue.encode(AppSignInPhase.idle) as? String == "idle")
- let waiting = BridgeValue.encode(AppSignInPhase.waiting(userCode: "AB-12")) as? [String: Any]
+ let waiting = BridgeValue.encode(AppSignInPhase.waiting(userCode: "AB-12", opened: true)) as? [String: Any]
#expect(waiting?["type"] as? String == "waiting")
#expect(waiting?["userCode"] as? String == "AB-12")
+ #expect(waiting?["opened"] as? Bool == true)
+ // A failure reaches the page typed (its reason, the line, Details).
+ let failed = BridgeValue.encode(appSignInFailed(reason: .offline, detail: "dns")) as? [String: Any]
+ #expect(failed?["type"] as? String == "failed")
+ #expect(failed?["reason"] as? String == "offline")
+ #expect(failed?["message"] as? String == "Sign-in didn't finish. Can't reach Cua. Check your connection.")
+ #expect(failed?["detail"] as? String == "dns")
+ }
+
+ /// `session.signIn` answers "starting" at once: an earlier attempt's
+ /// failure never reads as this one's, and the page then follows the
+ /// host to its end (`session.changed`), failure included.
+ @Test func signInAnswersStartingThenTheFailureReachesThePage() async throws {
+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cua-webui-\(UUID().uuidString)")
+ let model = AppModel(backend: FixtureSpacesBackend(), keyvault: KeyvaultModel(client: nil),
+ onboarding: OnboardingModel(statePath: dir.appendingPathComponent("onboarding.json").path),
+ settingsPath: dir.appendingPathComponent("settings.json").path,
+ account: FailingAccount(error: CuaError.Http(message: "could not reach the sign-in service: x"),
+ whileStarting: false),
+ telemetry: FixtureTelemetry())
+ let bridge = WebUIBridge(model: model, allowedOrigins: [])
+ let started = try await bridge.handle("session.signIn", [:]) as? [String: Any]
+ #expect(started?["signIn"] as? String == "starting")
+ for _ in 0..<200 {
+ if case .failed = model.signIn { break }
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ let after = try await bridge.handle("session.get", [:]) as? [String: Any]
+ let failed = after?["signIn"] as? [String: Any]
+ #expect(failed?["type"] as? String == "failed")
+ #expect(failed?["reason"] as? String == "offline")
}
@Test func anUnknownMethodIsUnimplemented() async {
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 8a8ddb7dc9..9b77f05cf0 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/signin.test.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/signin.test.ts
@@ -4,7 +4,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 { BridgeStore, type SessionData } from "../store";
import { unavailableCore } from "../core";
import { testCore, until, wasmBuilt } from "./testCore";
@@ -37,7 +37,14 @@ describe.skipIf(!wasmBuilt)("a sign-in that never finishes", () => {
expect(session()?.signInUrl).toBeNull();
await store.signIn();
- await until(() => expect(session()?.signIn).toEqual({ kind: "failed", message: SIGN_IN_TIMED_OUT }));
+ await until(() =>
+ expect(session()?.signIn).toEqual({
+ kind: "failed",
+ reason: "notConfirmed",
+ message: "Sign-in didn't finish. The browser didn't confirm in time.",
+ detail: null,
+ }),
+ );
await store.telemetry.flush();
const kinds = adapter.state.telemetry.flatMap((s) => (s.type === "sign-in-failed" ? [s.errorKind] : []));
expect(kinds).toEqual(["cancelled", "timeout"]);
@@ -50,7 +57,13 @@ describe.skipIf(!wasmBuilt)("a sign-in that never finishes", () => {
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 host = {
+ attempts: 0,
+ identity: null as string | null,
+ failure: null as { reason: string; message: string; detail: string | null } | null,
+ /** How long `session.get` takes to answer (ms). */
+ getDelay: 0,
+ };
const emit = () => listeners.forEach((l) => l({ type: "session.changed" }));
const adapter = Object.assign(Object.create(demo) as DataAdapter, {
subscribe: (l: (e: { type: string }) => void) => {
@@ -65,10 +78,15 @@ function nativeHost() {
}
const out = (await demo.call(op as never, args as never)) as Record<string, unknown>;
if (op !== "session.get") return out;
+ // What the host says now; it answers after `getDelay`.
+ const failure = host.failure;
+ if (host.getDelay) await new Promise((r) => setTimeout(r, host.getDelay));
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` } };
+ : failure
+ ? { ...out, hostSignIn: null, hostSignInFailure: failure }
+ : { ...out, hostSignIn: { userCode: null, url: `http://127.0.0.1:${50000 + host.attempts}/callback` } };
}) as DataAdapter["call"],
});
return { adapter, host, emit };
@@ -98,3 +116,51 @@ describe("a sign-in the host finished on a retried attempt (CUA-1728)", () => {
store.dispose();
});
});
+
+describe("a sign-in that fails in the host (Ellie: it silently failed)", () => {
+ it("shows the host's reason at once instead of waiting on", 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()?.signIn.kind).toBe("waiting"));
+ // The network dropped while the browser was open: the host gave up.
+ host.failure = { reason: "offline", message: "Sign-in didn't finish. Can't reach Cua. Check your connection.", detail: "dns error" };
+ emit();
+ await until(() =>
+ expect(session()?.signIn).toEqual({
+ kind: "failed",
+ reason: "offline",
+ message: "Sign-in didn't finish. Can't reach Cua. Check your connection.",
+ detail: "dns error",
+ }),
+ );
+ expect(session()?.signInUrl).toBeNull();
+ await store.telemetry.flush();
+ store.dispose();
+ });
+
+ it("never reads an earlier attempt's failure as the new one's", 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());
+ // The last attempt failed on the host; a session read starts (slow)...
+ host.failure = { reason: "notConfirmed", message: "Sign-in didn't finish. The browser didn't confirm in time.", detail: null };
+ host.getDelay = 30;
+ emit();
+ await new Promise((r) => setTimeout(r, 5));
+ // ...and Try again is pressed before it answers.
+ host.failure = null;
+ await store.signIn();
+ expect(session()?.signIn.kind).toBe("waiting");
+ // The slow read lands with the old failure: not this attempt's.
+ await new Promise((r) => setTimeout(r, 60));
+ expect(session()?.signIn.kind).toBe("waiting");
+ store.dispose();
+ });
+});
diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
index 4fed2d1e08..f1f7dc4b38 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts
@@ -330,8 +330,16 @@ export function toSessionSnapshot(s: WkSession, onboarding: WkOnboarding | null
// The SwiftUI app's first run is its own window; Electron's is the page's.
onboarding: onboarding ? { completed: onboarding.completed, mode: onboarding.mode } : { completed: true, mode: "client" },
daemon: null,
- // The host runs the sign-in: while it waits, its code and page.
- hostSignIn: typeof s.signIn === "object" && s.signIn.type === "waiting" ? { userCode: opt(s.signIn.userCode) ?? null, url: opt(s.signInUrl) ?? null } : null,
+ // The host runs the sign-in: while it waits, its code and page; when
+ // it failed, why (the page shows it instead of waiting on).
+ hostSignIn:
+ typeof s.signIn === "object" && s.signIn.type === "waiting"
+ ? { userCode: opt(s.signIn.userCode) ?? null, url: opt(s.signInUrl) ?? null, opened: s.signIn.opened !== false }
+ : null,
+ hostSignInFailure:
+ typeof s.signIn === "object" && s.signIn.type === "failed"
+ ? { reason: s.signIn.reason ?? "unknown", message: s.signIn.message ?? "", detail: opt(s.signIn.detail) ?? null }
+ : null,
};
}
diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
index e78506c632..de08b8238a 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
@@ -2746,12 +2746,40 @@
"string",
"null"
]
+ },
+ "opened": {
+ "type": "boolean"
}
},
"required": [
"userCode",
"url"
]
+ },
+ "hostSignInFailure": {
+ "type": [
+ "object",
+ "null"
+ ],
+ "properties": {
+ "reason": {
+ "type": "string"
+ },
+ "message": {
+ "type": "string"
+ },
+ "detail": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "reason",
+ "message",
+ "detail"
+ ]
}
},
"required": [
@@ -4482,8 +4510,20 @@
"null"
]
},
+ "opened": {
+ "type": "boolean"
+ },
+ "reason": {
+ "type": "string"
+ },
"message": {
"type": "string"
+ },
+ "detail": {
+ "type": [
+ "string",
+ "null"
+ ]
}
},
"required": [
diff --git a/apps/cua-spaces-web/src/bridge/contracts/host.ts b/apps/cua-spaces-web/src/bridge/contracts/host.ts
index cecff290f7..2f961225c4 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/host.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/host.ts
@@ -597,12 +597,32 @@ export interface TelemetryView {
/* ---- Settings page (app core `settings::page`) --------------------------- */
+/** Why a sign-in did not finish (`sign_in::SignInFailure`). */
+export type SignInFailure = "notConfirmed" | "declined" | "codeRejected" | "offline" | "serviceUnavailable" | "couldNotSave" | "unknown";
+
/** Where the Account section's sign-in stands (`settings::SignInPhase`). */
export type SignInPhase =
| { kind: "idle" }
| { kind: "starting" }
- | { kind: "waiting"; userCode?: string | null }
- | { kind: "failed"; message: string };
+ | { kind: "waiting"; userCode?: string | null; opened?: boolean }
+ /** `message` is the core's line; `detail` the error's own words (Details). */
+ | { kind: "failed"; reason?: SignInFailure; message: string; detail?: string | null };
+
+/** The sidebar's foot (`sign_in::SignInFooter`): every sign-in state in one place. */
+export interface SignInFooter {
+ state: "signedOut" | "starting" | "waiting" | "failed" | "signedIn";
+ text: string;
+ identity: string | null;
+ code: string | null;
+ codeLabel: string;
+ reopenLabel: string | null;
+ cancelLabel: string | null;
+ actionLabel: string | null;
+ reason: SignInFailure | null;
+ detail: string | null;
+ detailsLabel: string;
+ toast: { title: string; body: string | null } | null;
+}
/** `settings::SettingsInput` (the fields the bridge fills; the rest default). */
export interface SettingsInput {
diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
index a171073207..5a259b7fe9 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
@@ -67,7 +67,7 @@ import type { HostChecklistState } from "../ops/checklist";
import type { PresenceCursorWire, PresenceJoinInfo, PresenceParticipantWire } from "../ops/presence";
import type { StartupState } from "../ops/startup";
import type { StreamTicket } from "../ops/stream";
-import type { GlobalShortcut, HostSettings, HostSignIn, OpName, SessionSnapshot, SettingsSnapshot, SettingsValues } from "../protocol";
+import type { GlobalShortcut, HostSettings, HostSignIn, HostSignInFailure, OpName, SessionSnapshot, SettingsSnapshot, SettingsValues } from "../protocol";
import type { WebkitMethod, WkHostState, WkMachines, WkOnboarding, WkSession, WkSettings, WkSettingsRow, WkSpace, WkSpaces } from "../webkit-protocol";
import { Defs, any, bool, dict, list, nul, nullable, num, obj, object, oneOf, opt, optNull, str, union, type Schema } from "./schema";
@@ -233,7 +233,8 @@ const SessionShape = ref(
daemon: nullable(
obj<DaemonStatus>()({ connected: bool, version: opt(str), socketPath: opt(str), loopbackUrl: opt(str), error: opt(str) }),
),
- hostSignIn: optNull(obj<HostSignIn>()({ userCode: nullable(str), url: nullable(str) })),
+ hostSignIn: optNull(obj<HostSignIn>()({ userCode: nullable(str), url: nullable(str), opened: opt(bool) })),
+ hostSignInFailure: optNull(obj<HostSignInFailure>()({ reason: str, message: str, detail: nullable(str) })),
}),
);
@@ -1148,7 +1149,10 @@ const WkSessionShape = ref(
identity: nullable(str),
signedIn: bool,
cloudConfigured: bool,
- signIn: union(oneOf("idle", "starting"), object({ type: str, userCode: optNull(str), message: opt(str) })),
+ signIn: union(
+ oneOf("idle", "starting"),
+ object({ type: str, userCode: optNull(str), opened: opt(bool), reason: opt(str), message: opt(str), detail: optNull(str) }),
+ ),
signInUrl: optNull(str),
}),
);
diff --git a/apps/cua-spaces-web/src/bridge/index.ts b/apps/cua-spaces-web/src/bridge/index.ts
index d418fafe20..e013516ed2 100644
--- a/apps/cua-spaces-web/src/bridge/index.ts
+++ b/apps/cua-spaces-web/src/bridge/index.ts
@@ -96,6 +96,7 @@ export type * from "./contracts/devices";
export type * from "./contracts/notifications";
export * from "./settings-hooks";
export { hasNotch, passedSteps, signInCodeText, type SavedOnboarding } from "./onboarding";
+export { signInFailedFromError, signInFailedPhase, signInFooter, type FailedPhase, type SignInFooterInput } from "./sign-in";
export {
useConnectCloud,
useFirstSpaceOffers,
diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.ts
index 9e2105bb68..5849c5db30 100644
--- a/apps/cua-spaces-web/src/bridge/protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/protocol.ts
@@ -163,12 +163,25 @@ export interface SessionSnapshot {
/** A native host's sign-in waiting for the browser (it runs the flow
* itself): the code to confirm and the page it finishes on. */
hostSignIn?: HostSignIn | null;
+ /** A native host's sign-in that failed (its reason, the core's line and
+ * the error's words for Details): the page shows it, never a wait that
+ * goes on. Absent from an older host. */
+ hostSignInFailure?: HostSignInFailure | null;
}
/** A sign-in the host waits on (`SessionSnapshot.hostSignIn`). */
export interface HostSignIn {
userCode: string | null;
url: string | null;
+ /** A browser opened on the host (false: open the page by hand). */
+ opened?: boolean;
+}
+
+/** A host sign-in that failed (`SessionSnapshot.hostSignInFailure`). */
+export interface HostSignInFailure {
+ reason: string;
+ message: string;
+ detail: string | null;
}
/* ---- Operations ---------------------------------------------------------- */
diff --git a/apps/cua-spaces-web/src/bridge/sign-in.ts b/apps/cua-spaces-web/src/bridge/sign-in.ts
new file mode 100644
index 0000000000..697a3fb2c1
--- /dev/null
+++ b/apps/cua-spaces-web/src/bridge/sign-in.ts
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * Sign-in you can see (the core's `sign_in`): the failed phase for a reason
+ * or a caught error, and the sidebar's foot for every state. The words are
+ * the core's; the fallbacks only keep the page usable before the wasm core
+ * loads (tests, a dev build without it).
+ */
+
+import type { CoreClient } from "./core";
+import type { SignInFailure, SignInFooter, SignInPhase } from "./contracts/host";
+
+export type FailedPhase = Extract<SignInPhase, { kind: "failed" }>;
+
+const FAILED = "Sign-in didn't finish";
+
+/** The failed phase for `reason`, with the error's words for Details. */
+export function signInFailedPhase(core: CoreClient, reason: SignInFailure, detail: string | null = null): FailedPhase {
+ return core.tryCall<FailedPhase>("signIn.failed", { reason, detail }) ?? { kind: "failed", reason, message: `${FAILED}.`, detail };
+}
+
+/** The failed phase for an error the page or a host caught: its case
+ * (`Timeout`, `Http`, ...: a UniFFI error's `tag`), if any, and its words. */
+export function signInFailedFromError(core: CoreClient, error: unknown): FailedPhase {
+ const message = error instanceof Error ? error.message : String(error);
+ const tag = typeof (error as { tag?: unknown } | null)?.tag === "string" ? (error as { tag: string }).tag : null;
+ return (
+ core.tryCall<FailedPhase>("signIn.failedFromError", { variant: tag, message }) ?? {
+ kind: "failed",
+ reason: "unknown",
+ message: `${FAILED}.`,
+ detail: message || null,
+ }
+ );
+}
+
+/** What the sidebar's foot shows. */
+export interface SignInFooterInput {
+ identity: string | null;
+ cloudConfigured: boolean;
+ canSignIn: boolean;
+ signIn: SignInPhase;
+ hasUrl: boolean;
+}
+
+/** The sidebar's foot: signed in as, waiting with the code, Open again and
+ * Cancel, or why it failed with Try again (and the toast to show once). */
+export function signInFooter(core: CoreClient, input: SignInFooterInput): SignInFooter {
+ return core.tryCall<SignInFooter>("signIn.footer", { input }) ?? fallbackFooter(input);
+}
+
+function fallbackFooter(input: SignInFooterInput): SignInFooter {
+ const base: SignInFooter = {
+ state: "signedOut",
+ text: input.cloudConfigured ? "Signed in with an API key" : "Not signed in",
+ identity: null,
+ code: null,
+ codeLabel: "Code",
+ reopenLabel: null,
+ cancelLabel: null,
+ actionLabel: input.canSignIn ? "Sign in" : null,
+ reason: null,
+ detail: null,
+ detailsLabel: "Details",
+ toast: null,
+ };
+ if (input.identity) return { ...base, state: "signedIn", text: `Signed in as ${input.identity}`, identity: input.identity, actionLabel: null };
+ const p = input.signIn;
+ switch (p.kind) {
+ case "starting":
+ return { ...base, state: "starting", text: "Opening your browser…", cancelLabel: "Cancel", actionLabel: null };
+ case "waiting":
+ return {
+ ...base,
+ state: "waiting",
+ text: p.opened === false ? "Open the sign-in page to continue." : "Waiting for your browser…",
+ code: p.userCode ?? null,
+ reopenLabel: input.hasUrl ? "Open again" : null,
+ cancelLabel: "Cancel",
+ actionLabel: null,
+ };
+ case "failed":
+ return {
+ ...base,
+ state: "failed",
+ text: p.message || `${FAILED}.`,
+ reason: p.reason ?? "unknown",
+ detail: p.detail ?? null,
+ actionLabel: "Try again",
+ toast: { title: FAILED, body: null },
+ };
+ default:
+ return base;
+ }
+}
diff --git a/apps/cua-spaces-web/src/bridge/store.ts b/apps/cua-spaces-web/src/bridge/store.ts
index ef5b98697d..745852c04d 100644
--- a/apps/cua-spaces-web/src/bridge/store.ts
+++ b/apps/cua-spaces-web/src/bridge/store.ts
@@ -18,7 +18,7 @@ import { withCreateContext } from "./create-context";
import { createReport, reportMailto, type CreateReport, type ReportSend } from "./diagnostic-report";
import type { AboutInput } from "./contracts/settings";
import { passedSteps } from "./onboarding";
-import type { MachineRow, MachinesView, OnboardingMode, SettingsPage, SignInPhase, SignInStart, SpaceCreateConfig, TelemetryView } from "./contracts/host";
+import type { MachineRow, MachinesView, OnboardingMode, SettingsPage, SignInFailure, SignInPhase, SignInStart, SpaceCreateConfig, TelemetryView } from "./contracts/host";
import type { OnboardingAction, OnboardingFlowState } from "./contracts/onboarding";
import type { KeyvaultOverview, KvGrant, KvListView, KvSelection, VaultAction, VaultState } from "./contracts/keyvault";
import type { KvAccessCommand } from "./ops/keyvault-manage";
@@ -46,7 +46,8 @@ import {
type KeyvaultViews,
type Machine,
} from "./derive";
-import type { HostEvent, HostSignIn, SessionSnapshot, SettingKey, SettingsSnapshot, SettingsValues } from "./protocol";
+import type { HostEvent, HostSignIn, HostSignInFailure, SessionSnapshot, SettingKey, SettingsSnapshot, SettingsValues } from "./protocol";
+import { signInFailedFromError, signInFailedPhase, type FailedPhase } from "./sign-in";
import { createSettingsFeature, type SettingsFeature } from "./settings-feature";
import { SpaceDetailStore } from "./space-detail";
import {
@@ -57,7 +58,7 @@ import {
telemetryOnboarding,
telemetryOnboardingFinished,
telemetryOnboardingSkipped,
- telemetrySignInFailed,
+ telemetrySignInFailure,
} from "./telemetry";
import { ThisMachineStore } from "./this-machine";
import { Transcript, type TranscriptItem } from "./transcript";
@@ -196,7 +197,6 @@ 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;
-export const SIGN_IN_TIMED_OUT = "The sign-in timed out. Try again.";
const CREATE_TICK_MS = 1_000;
/** How often a watched run is read while a turn runs, and while it waits. */
@@ -260,6 +260,9 @@ export class BridgeStore {
private agentsPending: string[] = [];
private signInUrl: string | null = null;
private signInTimer: ReturnType<typeof setTimeout> | undefined;
+ /** Counts `session.signIn` answers: a session read started before the
+ * latest one says nothing about it (an earlier attempt's failure). */
+ private signInEpoch = 0;
private readonly signInTimeoutMs: number;
private overview: KeyvaultOverview | undefined;
private vaultState: VaultState = INITIAL_VAULT_STATE;
@@ -456,8 +459,9 @@ export class BridgeStore {
break;
}
case "session": {
+ const epoch = this.signInEpoch;
this.sessionSnap = await this.adapter.call("session.get", {});
- this.followHostSignIn(this.sessionSnap.hostSignIn);
+ this.followHostSignIn(this.sessionSnap.hostSignIn, epoch === this.signInEpoch ? this.sessionSnap.hostSignInFailure : null);
this.publishSession();
if (this.settingsSnap) this.publishSettings();
break;
@@ -919,7 +923,7 @@ export class BridgeStore {
/** A native host runs the sign-in and says when it waits (with the code
* and the page) only after `session.signIn` answered: take them in, so
* the page shows them. */
- private followHostSignIn(waiting: HostSignIn | null | undefined): void {
+ private followHostSignIn(waiting: HostSignIn | null | undefined, failure?: HostSignInFailure | null): void {
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.
@@ -929,10 +933,22 @@ export class BridgeStore {
this.signInPhase = { kind: "idle" };
return;
}
+ // 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,
+ });
+ 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 };
+ 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 };
}
private setSignIn(phase: SignInPhase): void {
@@ -946,16 +962,19 @@ export class BridgeStore {
this.setSignIn({ kind: "starting" });
try {
const start = await this.adapter.call("session.signIn", {});
+ this.signInEpoch += 1;
// Cancelled while it started: leave it.
if (this.signInPhase.kind !== "starting") return start;
this.signInUrl = start.verificationUri || null;
this.setSignIn({ kind: "waiting", userCode: start.userCode ?? null });
this.signInTimer = setTimeout(() => {
- if (this.signInPhase.kind === "waiting") this.signInFailed(SIGN_IN_TIMED_OUT);
+ if (this.signInPhase.kind === "waiting") this.signInFailed(signInFailedPhase(this.core, "notConfirmed"));
}, this.signInTimeoutMs);
return start;
} catch (e) {
- this.signInFailed(toError(e).message);
+ // Shown in the sidebar's foot with its reason (and a toast there),
+ // so callers need not say it again.
+ this.signInFailed(signInFailedFromError(this.core, e));
throw toError(e);
}
}
@@ -964,15 +983,16 @@ export class BridgeStore {
cancelSignIn(): void {
if (this.signInPhase.kind !== "starting" && this.signInPhase.kind !== "waiting") return;
this.stopSignInTimer();
- void this.telemetry.track(telemetrySignInFailed(this.core, null));
+ void this.telemetry.track(telemetrySignInFailure(this.core, null));
this.setSignIn({ kind: "idle" });
}
- /** A sign-in failed: shown, and counted by its kind (never its words). */
- private signInFailed(message: string): void {
+ /** A sign-in failed: shown with its reason, and counted by its kind
+ * (never its words). */
+ private signInFailed(phase: FailedPhase): void {
this.stopSignInTimer();
- void this.telemetry.track(telemetrySignInFailed(this.core, message));
- this.setSignIn({ kind: "failed", message });
+ void this.telemetry.track(telemetrySignInFailure(this.core, phase.reason ?? "unknown"));
+ this.setSignIn(phase);
}
private stopSignInTimer(): void {
@@ -1358,7 +1378,8 @@ export class BridgeStore {
reload("machines");
break;
case "session.signInFailed":
- this.signInFailed(e.reason);
+ // A host that only has words (the Tauri app): the core reads them.
+ this.signInFailed(signInFailedFromError(this.core, new Error(e.reason)));
break;
case "session.signedOut":
this.signInPhase = { kind: "idle" };
diff --git a/apps/cua-spaces-web/src/bridge/telemetry.ts b/apps/cua-spaces-web/src/bridge/telemetry.ts
index 4ca33c701a..864513cb7e 100644
--- a/apps/cua-spaces-web/src/bridge/telemetry.ts
+++ b/apps/cua-spaces-web/src/bridge/telemetry.ts
@@ -16,7 +16,7 @@
import { isUnsupported, type BridgeMode, type DataAdapter } from "./adapter";
import type { CoreClient } from "./core";
-import type { TelemetryView } from "./contracts/host";
+import type { SignInFailure, TelemetryView } from "./contracts/host";
import type { OnboardingAction, OnboardingFlowState } from "./contracts/onboarding";
import type { CreateAction, CreatesState } from "./contracts/spaces";
import { sanitizeSignals, type TelemetrySignal } from "./ops/telemetry";
@@ -54,6 +54,11 @@ export function telemetrySignInFailed(core: CoreClient, message: string | null):
return signals(core.tryCall("telemetry.signInFailed", { message }));
}
+/** A sign-in failed for `reason` or was cancelled (null): its kind only. */
+export function telemetrySignInFailure(core: CoreClient, reason: SignInFailure | null): TelemetrySignal[] {
+ return signals(core.tryCall("telemetry.signInFailure", { reason }));
+}
+
/** What a create, power or delete step means (`telemetry.creates`). */
export function telemetryCreates(core: CoreClient, state: CreatesState | null, action: CreateAction, now: number): TelemetrySignal[] {
return signals(core.tryCall("telemetry.creates", { state, action, now }));
diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
index 4e65eaf1d2..57553416ac 100644
--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
@@ -306,8 +306,8 @@ export interface WkSession {
identity: string | null;
signedIn: boolean;
cloudConfigured: boolean;
- /** `idle`, `starting`, `{type: "waiting", userCode}`, `{type: "failed", message}`. */
- signIn: string | { type: string; userCode?: string | null; message?: string };
+ /** `idle`, `starting`, `{type: "waiting", userCode, opened}`, `{type: "failed", reason, message, detail}`. */
+ signIn: string | { type: string; userCode?: string | null; opened?: boolean; reason?: string; message?: string; detail?: string | null };
/** The page a waiting sign-in finishes on (null otherwise), to show and copy. */
signInUrl?: string | null;
}
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 14363aff6e..ea9e8aea70 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
@@ -9,6 +9,8 @@ import type { DataAdapter } from "@/bridge/adapter";
import { createDemoAdapter } from "@/bridge/adapters/demo";
import { unavailableCore } from "@/bridge/core";
import { AccountFooter } from "@/components/shell/sidebar";
+import { ToastProvider } from "@/components/ui/toast";
+import { testCore } from "@/bridge/__tests__/testCore";
afterEach(cleanup);
@@ -41,12 +43,13 @@ describe("the sidebar's sign-in", () => {
);
fireEvent.click(await screen.findByRole("button", { name: "Sign in" }));
const status = await screen.findByRole("status");
- await waitFor(() => expect(status.textContent).toContain("WXYZ-1234"));
- fireEvent.click(screen.getByText("Open the browser again"));
+ expect(status.textContent).toContain("Waiting for your browser");
+ await waitFor(() => expect(document.querySelector("[data-signin=waiting]")?.textContent).toContain("Code WXYZ-1234"));
+ fireEvent.click(screen.getByText("Open again"));
await waitFor(() => expect(opened).toEqual(["https://cua.ai/device"]));
fireEvent.click(screen.getByText("Cancel"));
expect(await screen.findByRole("button", { name: "Sign in" })).toBeTruthy();
- expect(screen.queryByText("Open the browser again")).toBeNull();
+ expect(screen.queryByText("Open again")).toBeNull();
});
});
@@ -75,7 +78,10 @@ function nativeHost() {
return { method: "browser", verificationUri: "" };
}
const out = await (base.call as (o: string, a: unknown) => Promise<unknown>).call(base, op, args);
- return op === "session.get" && waiting ? { ...(out as object), hostSignIn: { userCode: "WDJB-MJHT", url: "https://auth.cua.ai/device" } } : out;
+ // No browser on this box: the page is to be opened on any device.
+ return op === "session.get" && waiting
+ ? { ...(out as object), hostSignIn: { userCode: "WDJB-MJHT", url: "https://auth.cua.ai/device", opened: false } }
+ : out;
}) as DataAdapter["call"],
});
return adapter;
@@ -89,8 +95,8 @@ describe("a sign-in the host runs", () => {
</BridgeProvider>,
);
fireEvent.click(await screen.findByRole("button", { name: "Sign in" }));
- const status = await screen.findByRole("status");
- await waitFor(() => expect(status.textContent).toContain("WDJB-MJHT"));
+ await waitFor(() => expect(document.querySelector("[data-signin=waiting]")?.textContent).toContain("WDJB-MJHT"));
+ expect((await screen.findByRole("status")).textContent).toContain("Open the sign-in page to continue.");
const link = await waitFor(() => {
const l = document.querySelector<HTMLElement>("[data-signin-link]");
if (!l) throw new Error("no link");
@@ -100,3 +106,53 @@ describe("a sign-in the host runs", () => {
expect(screen.getByRole("button", { name: "Copy the sign-in link" })).toBeTruthy();
});
});
+
+/** A host whose sign-in fails, with the error a real one gives. */
+function failingHost(error: Error) {
+ const base = createDemoAdapter({ latencyMs: 0, signedIn: false, onboarded: true });
+ return Object.assign(Object.create(base) as DataAdapter, {
+ call: ((op: string, args: Record<string, unknown>) =>
+ op === "session.signIn"
+ ? Promise.reject(error)
+ : (base.call as (o: string, a: unknown) => Promise<unknown>).call(base, op, args)) as DataAdapter["call"],
+ });
+}
+
+describe("a sign-in that fails (it never fails silently)", () => {
+ it("says why in the foot, with Try again, Details and a toast", async () => {
+ render(
+ <ToastProvider>
+ <BridgeProvider adapter={failingHost(new Error("could not reach the sign-in service: error sending request"))} core={await testCore()}>
+ <AccountFooter />
+ </BridgeProvider>
+ </ToastProvider>,
+ );
+ fireEvent.click(await screen.findByRole("button", { name: "Sign in" }));
+ const alert = await screen.findByRole("alert");
+ // The core's words (or, without the wasm core, the plain fallback line).
+ expect(alert.textContent).toMatch(/^Sign-in didn't finish\./);
+ expect(screen.getByRole("button", { name: "Try again" })).toBeTruthy();
+ // The raw error stays behind Details.
+ expect(alert.textContent).not.toContain("error sending request");
+ fireEvent.click(screen.getByText("Details"));
+ expect(alert.textContent).toContain("error sending request");
+ // And a toast (its title is exactly the line's start), once.
+ const toasts = await screen.findAllByText("Sign-in didn't finish");
+ expect(toasts).toHaveLength(1);
+ });
+
+ it("shows who is signed in", async () => {
+ const base = createDemoAdapter({ latencyMs: 0, signedIn: true, onboarded: true });
+ render(
+ <BridgeProvider adapter={base} core={await testCore()}>
+ <AccountFooter />
+ </BridgeProvider>,
+ );
+ const who = await waitFor(() => {
+ const el = document.querySelector<HTMLElement>("[data-signin-identity]");
+ if (!el) throw new Error("not signed in yet");
+ return el;
+ });
+ expect(who.textContent).toMatch(/^Signed in as \S+/);
+ });
+});
diff --git a/apps/cua-spaces-web/src/components/shell/sidebar.tsx b/apps/cua-spaces-web/src/components/shell/sidebar.tsx
index 088a8384ea..3b25fcdd48 100644
--- a/apps/cua-spaces-web/src/components/shell/sidebar.tsx
+++ b/apps/cua-spaces-web/src/components/shell/sidebar.tsx
@@ -2,14 +2,14 @@
// Copyright (c) 2026 Cua AI, Inc.
import { Link } from "@tanstack/react-router";
-import { useRef, type PointerEvent } from "react";
+import { useEffect, useRef, useState, type PointerEvent } from "react";
-import { LogOutIcon } from "lucide-react";
+import { Loader2Icon, LogOutIcon, TriangleAlertIcon } from "lucide-react";
-import type { Space } from "@/bridge";
+import type { SignInFooter, Space } from "@/bridge";
import { spokenName } from "@/bridge/space-names";
-import { signInCodeText, useBridge, useMachines, useNotifications, useRelayUsageView, useSession, useSpaces, useTrackPlanClick } from "@/bridge";
+import { signInFooter, useBridge, 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";
@@ -113,35 +113,55 @@ function SidebarCreating({ spaces }: { spaces: Space[] }) {
);
}
-/** The account, or "Sign in"; and a way back into a first run left halfway. */
+/** The account and its sign-in, every state in one place (the core's
+ * `signIn.footer`): signed in as, waiting for the browser with the code,
+ * Open again and Cancel, or why it failed with Try again and a toast. And a
+ * way back into a first run left halfway. */
export function AccountFooter() {
const { core } = useBridge();
const { data: session, signIn, signOut, cancelSignIn, openExternal } = useSession();
const plan = useRelayUsageView()?.planCard;
const trackPlanClick = useTrackPlanClick();
- if (!session) return <div className="mt-auto h-12 border-t" />;
+ const [details, setDetails] = useState(false);
+ const footer = session
+ ? signInFooter(core, {
+ identity: session.signedIn ? (session.identity ?? "") : null,
+ cloudConfigured: session.fleet.configured,
+ canSignIn: true,
+ signIn: session.signIn,
+ hasUrl: Boolean(session.signInUrl),
+ })
+ : null;
+ useSignInFailureToast(footer);
+ if (!session || !footer) return <div className="mt-auto h-12 border-t" />;
- const identity = session.signedIn ? (session.identity ?? "Signed in") : null;
- const phase = session.signIn.kind;
- const waiting = phase === "starting" || phase === "waiting";
const unfinished = !session.onboarding.completed;
const run = (f: () => Promise<unknown>, what: string) =>
f().catch((e: unknown) => toast(what, { description: e instanceof Error ? e.message : String(e) }));
+ // A failure is shown here with its reason (and the toast): nothing to add.
+ const startSignIn = () => {
+ setDetails(false);
+ void signIn().catch(() => {});
+ };
+ const identity = footer.identity || (session.signedIn ? "Signed in" : null);
return (
- <div className="mt-auto border-t px-3 py-2.5">
+ <div className="mt-auto border-t px-3 py-2.5" data-signin={footer.state}>
{unfinished ? (
<Link to="/onboarding" className="mb-2 block text-xs text-muted-foreground hover:text-foreground">
Finish setting up
</Link>
) : null}
- {identity ? (
+ {footer.state === "signedIn" && identity ? (
<div className="flex items-center gap-2.5">
<div className="flex size-6 shrink-0 items-center justify-center rounded-full bg-muted text-2xs font-semibold text-muted-foreground uppercase">
{identity.slice(0, 1)}
</div>
<div className="min-w-0 flex-1 leading-tight">
- <div className="truncate text-xs font-medium">{identity}</div>
+ <div className="truncate text-xs" title={footer.text} data-signin-identity="">
+ <span className="block text-2xs text-muted-foreground">Signed in as </span>
+ <span className="block truncate font-medium">{identity}</span>
+ </div>
{plan?.primary ? (
// The current plan, always visible; on Free it opens Pro's checkout.
<button
@@ -156,9 +176,7 @@ export function AccountFooter() {
{plan.label}
{plan.plan === "free" ? " · Upgrade" : ""}
</button>
- ) : (
- <div className="truncate text-2xs text-muted-foreground">Cua account</div>
- )}
+ ) : null}
</div>
{session.fleet.authMode === "user" ? (
<Tooltip content="Sign out" side="top">
@@ -168,49 +186,105 @@ export function AccountFooter() {
</Tooltip>
) : null}
</div>
- ) : waiting ? (
- // As in the first run: the code to confirm, the page to open again
- // if the tab was closed, and a way out (it also times out).
- <div data-signin="waiting">
- <p className="text-xs text-muted-foreground select-text" role="status">
- {phase === "waiting" && session.signIn.kind === "waiting"
- ? signInCodeText(core, session.signIn.userCode)
- : "Waiting for the browser…"}
+ ) : footer.state === "starting" || footer.state === "waiting" ? (
+ // The code to confirm, the page to open again if the tab was
+ // closed, and a way out (it also ends by itself, with a reason).
+ <div>
+ <p className="flex items-center gap-2 text-xs" role="status">
+ <Loader2Icon className="size-3.5 shrink-0 animate-spin text-muted-foreground" aria-hidden />
+ <span className="truncate">{footer.text}</span>
+ </p>
+ <div className="mt-1 flex flex-wrap items-center gap-x-1 pl-5.5 text-2xs text-muted-foreground">
+ {footer.code ? (
+ <>
+ <span className="select-text">
+ {footer.codeLabel} <span className="font-mono font-semibold text-foreground">{footer.code}</span>
+ </span>
+ <span aria-hidden>·</span>
+ </>
+ ) : null}
+ {footer.reopenLabel && session.signInUrl ? (
+ <>
+ <button
+ type="button"
+ className="underline underline-offset-2 hover:text-foreground"
+ onClick={() => void openExternal(session.signInUrl!).catch(() => {})}
+ data-signin-reopen=""
+ >
+ {footer.reopenLabel}
+ </button>
+ <span aria-hidden>·</span>
+ </>
+ ) : null}
+ {footer.cancelLabel ? (
+ <button type="button" className="underline underline-offset-2 hover:text-foreground" onClick={() => cancelSignIn()} data-signin-cancel="">
+ {footer.cancelLabel}
+ </button>
+ ) : null}
+ </div>
+ {/* 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 />
+ ) : null}
+ </div>
+ ) : footer.state === "failed" ? (
+ <div role="alert">
+ <p className="flex items-start gap-2 text-xs">
+ <TriangleAlertIcon className="mt-px size-3.5 shrink-0 text-destructive" aria-hidden />
+ <span data-signin-reason={footer.reason ?? "unknown"}>{footer.text}</span>
</p>
- {session.signInUrl ? <SignInLink url={session.signInUrl} compact /> : null}
- <div className="mt-1.5 flex items-center gap-3 text-2xs">
- {session.signInUrl ? (
+ <div className="mt-2 flex items-center gap-3 pl-5.5">
+ <Button size="sm" onClick={startSignIn} data-signin-retry="">
+ {footer.actionLabel}
+ </Button>
+ {footer.detail ? (
<button
type="button"
- className="text-foreground underline-offset-2 hover:underline"
- onClick={() => void openExternal(session.signInUrl!)}
- data-signin-reopen=""
+ className="text-2xs text-muted-foreground underline underline-offset-2 hover:text-foreground"
+ aria-expanded={details}
+ onClick={() => setDetails((d) => !d)}
+ data-signin-details=""
>
- Open the browser again
+ {footer.detailsLabel}
</button>
) : null}
- <button
- type="button"
- className="text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
- onClick={() => cancelSignIn()}
- data-signin-cancel=""
- >
- Cancel
- </button>
</div>
+ {details && footer.detail ? (
+ <pre className="mt-2 max-h-28 overflow-auto rounded-md bg-muted px-2 py-1.5 font-mono text-2xs break-words whitespace-pre-wrap text-muted-foreground select-text">
+ {footer.detail}
+ </pre>
+ ) : null}
</div>
) : (
<div className="flex items-center justify-between gap-2">
- <Button variant="outline" size="sm" onClick={() => void run(signIn, "Couldn't sign in")}>
- {phase === "failed" ? "Try again" : "Sign in"}
- </Button>
- {phase === "failed" ? <span className="truncate text-2xs text-destructive">{session.signIn.message}</span> : null}
+ <span className="truncate text-xs text-muted-foreground">{footer.text}</span>
+ {footer.actionLabel ? (
+ <Button variant="outline" size="sm" onClick={startSignIn}>
+ {footer.actionLabel}
+ </Button>
+ ) : null}
</div>
)}
</div>
);
}
+/** A failed sign-in also toasts, once per failure, so it is seen wherever
+ * the person is looking. */
+function useSignInFailureToast(footer: SignInFooter | null) {
+ const shown = useRef<string | null>(null);
+ const key = footer?.state === "failed" ? `${footer.reason}:${footer.text}:${footer.detail ?? ""}` : null;
+ useEffect(() => {
+ if (!key || !footer?.toast) {
+ shown.current = key;
+ return;
+ }
+ if (shown.current === key) return;
+ shown.current = key;
+ toast(footer.toast.title, { description: footer.toast.body ?? undefined, type: "error", group: "sign-in" });
+ }, [key, footer]);
+}
+
function ResizeHandle() {
const setWidth = useUiStore((s) => s.setSidebarWidth);
const start = useRef<{ x: number; width: number } | null>(null);
diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lock
index 92cef75354..a629399744 100644
--- a/libs/cua/Cargo.lock
+++ b/libs/cua/Cargo.lock
@@ -2892,6 +2892,8 @@ name = "cua-spaces-app-core"
version = "0.7.0"
dependencies = [
"async-trait",
+ "base64 0.22.1",
+ "cua-auth",
"cua-create-failure",
"cua-home",
"cua-keyvault",
@@ -2900,6 +2902,7 @@ dependencies = [
"serde_json",
"tempfile",
"tokio",
+ "url",
]
[[package]]
diff --git a/libs/cua/crates/cua-auth/src/lib.rs b/libs/cua/crates/cua-auth/src/lib.rs
index e3e099881d..44835a5d4f 100644
--- a/libs/cua/crates/cua-auth/src/lib.rs
+++ b/libs/cua/crates/cua-auth/src/lib.rs
@@ -123,6 +123,43 @@ fn http_err(e: impl std::fmt::Display) -> Error {
Error::Http(e.to_string())
}
+/// How an error starts when the identity provider could not be reached at
+/// all (no network, DNS, refused, timed out). The Spaces app core reads it
+/// to say "can't reach Cua" instead of showing the transport's words.
+pub const UNREACHABLE: &str = "could not reach the sign-in service";
+
+/// How an error starts when the person declined the sign-in in the browser
+/// (`access_denied`).
+pub const LOGIN_DECLINED: &str = "sign-in was declined in the browser";
+
+/// A request that failed before any answer: [`UNREACHABLE`] for transport
+/// failures, the error's own words otherwise.
+fn net_err(e: reqwest::Error) -> Error {
+ if e.is_connect() || e.is_timeout() || e.is_request() {
+ Error::Http(format!("{UNREACHABLE}: {e}"))
+ } else {
+ Error::Http(e.to_string())
+ }
+}
+
+/// Whether `e` is [`UNREACHABLE`] (worth another poll).
+fn is_unreachable(e: &Error) -> bool {
+ matches!(e, Error::Http(m) if m.starts_with(UNREACHABLE))
+}
+
+/// A non-200 answer from the token or device endpoint: the provider's own
+/// trouble (5xx) is [`Error::Http`], a refusal [`Error::Unauthenticated`].
+fn token_refusal(status: u16, v: &serde_json::Value, fallback: &str) -> Error {
+ if status >= 500 {
+ Error::Http(format!(
+ "the sign-in service answered HTTP {status}: {}",
+ describe(v, fallback)
+ ))
+ } else {
+ Error::Unauthenticated(describe(v, fallback))
+ }
+}
+
fn store_err(e: impl std::fmt::Display) -> Error {
Error::Store(e.to_string())
}
@@ -1671,7 +1708,7 @@ impl Oidc {
.form(form)
.send()
.await
- .map_err(http_err)?;
+ .map_err(net_err)?;
let status = r.status().as_u16();
let text = r.text().await.map_err(http_err)?;
let v = serde_json::from_str(&text)
@@ -1682,7 +1719,7 @@ impl Oidc {
/// Fetches the discovery document.
pub async fn discover(&self) -> Result<Discovery> {
let url = format!("{}/.well-known/openid-configuration", self.issuer);
- let r = self.http.get(&url).send().await.map_err(http_err)?;
+ let r = self.http.get(&url).send().await.map_err(net_err)?;
if !r.status().is_success() {
return Err(Error::Http(format!(
"OIDC discovery failed (HTTP {})",
@@ -1953,10 +1990,12 @@ async fn begin_device(oidc: &Oidc, d: &Discovery) -> Result<PendingLogin> {
)
.await?;
if status != 200 {
- return Err(Error::Unauthenticated(describe(
- &v,
- "could not start device authorization",
- )));
+ return Err(match token_refusal(status, &v, "refused") {
+ Error::Unauthenticated(why) => {
+ Error::Unauthenticated(format!("could not start the sign-in: {why}"))
+ }
+ other => other,
+ });
}
let device_code = v["device_code"].as_str().unwrap_or_default().to_string();
let user_code = v["user_code"].as_str().unwrap_or_default().to_string();
@@ -2030,10 +2069,11 @@ impl PendingLogin {
matches!(&exchanged, Ok((_, v)) if v["error"] == "invalid_grant");
let creds = match exchanged {
Ok((200, v)) => Credentials::from_token_response(&v),
- Ok((status, v)) => Err(Error::Unauthenticated(describe(
+ Ok((status, v)) => Err(token_refusal(
+ status,
&v,
&format!("token request failed (HTTP {status})"),
- ))),
+ )),
Err(e) => Err(e),
};
let (status, outcome) = match &creds {
@@ -2056,8 +2096,12 @@ impl PendingLogin {
.unwrap_or(Duration::from_secs(1));
let deadline = tokio::time::Instant::now() + unit * expires_in as u32;
// Hard bound on iterations, independent of the clock.
+ // A network drop or the provider's own trouble (5xx) while
+ // the person confirms is retried until the code expires; it
+ // is the error then, never a silent "expired".
+ let mut last: Option<Error> = None;
for _ in 0..(expires_in / interval + 20) {
- let (status, v) = self
+ let polled = self
.oidc
.form(
&self.token_endpoint,
@@ -2067,28 +2111,49 @@ impl PendingLogin {
("client_id", &self.oidc.client_id),
],
)
- .await?;
- if status == 200 {
- return Credentials::from_token_response(&v);
- }
- match v["error"].as_str() {
- Some("authorization_pending") => {}
- Some("slow_down") => interval += 5,
- _ => {
- return Err(Error::Unauthenticated(describe(
- &v,
- &format!("token request failed (HTTP {status})"),
- )));
- }
+ .await;
+ match polled {
+ Ok((200, v)) => return Credentials::from_token_response(&v),
+ Ok((status, v)) => match v["error"].as_str() {
+ Some("authorization_pending") => last = None,
+ Some("slow_down") => {
+ interval += 5;
+ last = None;
+ }
+ Some("expired_token") => {
+ return Err(Error::Timeout(
+ "the sign-in code expired before it was confirmed (expired_token)"
+ .into(),
+ ));
+ }
+ Some("access_denied") => {
+ return Err(Error::Unauthenticated(format!(
+ "{LOGIN_DECLINED}: {}",
+ describe(&v, "access_denied")
+ )));
+ }
+ _ if status >= 500 => {
+ last = Some(token_refusal(status, &v, "token request failed"));
+ }
+ _ => {
+ return Err(token_refusal(
+ status,
+ &v,
+ &format!("token request failed (HTTP {status})"),
+ ));
+ }
+ },
+ Err(e) if is_unreachable(&e) => last = Some(e),
+ Err(e) => return Err(e),
}
if tokio::time::Instant::now() >= deadline {
break;
}
tokio::time::sleep(unit * interval as u32).await;
}
- Err(Error::Timeout(
- "device authorization expired before it was completed".into(),
- ))
+ Err(last.unwrap_or_else(|| {
+ Error::Timeout("device authorization expired before it was completed".into())
+ }))
}
}
}
@@ -2161,6 +2226,9 @@ async fn await_callback(
Outcome::Failed
};
respond_page(&mut sock, "400 Bad Request", &outcome, to).await;
+ if e == "access_denied" {
+ return Err(Error::Unauthenticated(format!("{LOGIN_DECLINED}: {msg}")));
+ }
return Err(Error::Unauthenticated(format!("sign-in failed: {msg}")));
}
let Some(code) = q.get("code").filter(|c| !c.is_empty()).cloned() else {
diff --git a/libs/cua/crates/cua-spaces-app-core/Cargo.toml b/libs/cua/crates/cua-spaces-app-core/Cargo.toml
index 321b324746..4858bda7e9 100644
--- a/libs/cua/crates/cua-spaces-app-core/Cargo.toml
+++ b/libs/cua/crates/cua-spaces-app-core/Cargo.toml
@@ -35,6 +35,11 @@ async-trait = { workspace = true, optional = true }
tokio = { workspace = true, optional = true, features = ["sync"] }
[dev-dependencies]
+# Sign-in drift test (`tests/sign_in_failures.rs`): every real cua-auth
+# sign-in failure maps to a reason with words.
+cua-auth.workspace = true
+url.workspace = true
+base64.workspace = true
# Wire-drift tests: the core's Keyvault mirror types decode the broker's
# real serde output.
cua-keyvault.workspace = true
diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
index cbb452920c..0ffb759374 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs
@@ -17,8 +17,8 @@ use crate::{
CoreError, about, agent_keys, agents, checklist, cloud_connect, devices, diagnostics,
drive_mount_preview, drive_page, drive_settings, driver_preview, experiments, host, login_item,
machines, notch, notifications, nudges, onboarding, onboarding_preview, palette, paths,
- persistent, presence, relay_usage, resources, settings, share, telemetry, upsell, window,
- wizard,
+ persistent, presence, relay_usage, resources, settings, share, sign_in, telemetry, upsell,
+ window, wizard,
};
use serde::Serialize;
use serde::de::DeserializeOwned;
@@ -159,6 +159,11 @@ pub const METHODS: &[&str] = &[
"onboarding.copy",
"onboarding.signedInText",
"onboarding.signInCodeText",
+ "signIn.footer",
+ "signIn.failed",
+ "signIn.failedFromError",
+ "signIn.failureOf",
+ "signIn.reasonText",
"onboarding.replacesText",
"onboarding.installedAtText",
"onboarding.preview",
@@ -277,6 +282,7 @@ pub const METHODS: &[&str] = &[
"telemetry.onboardingFinished",
"telemetry.onboardingSkipped",
"telemetry.signInFailed",
+ "telemetry.signInFailure",
"telemetry.creates",
"telemetry.storage",
"telemetry.share",
@@ -780,6 +786,20 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {
"onboarding.signInCodeText" => out(onboarding::sign_in_code_text(
a.get::<Option<String>>("userCode")?.as_deref(),
)),
+ "signIn.footer" => out(sign_in::footer(&a.get("input")?)),
+ "signIn.failed" => out(sign_in::failed(
+ a.get("reason")?,
+ a.get::<Option<String>>("detail")?.as_deref(),
+ )),
+ "signIn.failedFromError" => out(sign_in::failed_from_error(
+ &a.get::<Option<String>>("variant")?.unwrap_or_default(),
+ &a.get::<String>("message")?,
+ )),
+ "signIn.failureOf" => out(sign_in::failure_of(
+ &a.get::<Option<String>>("variant")?.unwrap_or_default(),
+ &a.get::<String>("message")?,
+ )),
+ "signIn.reasonText" => out(sign_in::reason_text(a.get("reason")?)),
"onboarding.replacesText" => out(onboarding::replaces_text(
a.get::<Option<String>>("installedVersion")?.as_deref(),
)),
@@ -1143,6 +1163,7 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {
"telemetry.signInFailed" => out(telemetry::sign_in_failed(
a.get::<Option<String>>("message")?.as_deref(),
)),
+ "telemetry.signInFailure" => out(telemetry::sign_in_failure(a.get("reason")?)),
"telemetry.creates" => out(telemetry::creates(
&a.get::<Option<creating::CreatesState>>("state")?
.unwrap_or_default(),
diff --git a/libs/cua/crates/cua-spaces-app-core/src/lib.rs b/libs/cua/crates/cua-spaces-app-core/src/lib.rs
index f8648145c0..3f6494aa53 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/lib.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/lib.rs
@@ -93,6 +93,7 @@ pub mod relay_usage;
pub mod resources;
pub mod settings;
pub mod share;
+pub mod sign_in;
pub mod spaces;
pub mod teams;
pub mod telemetry;
diff --git a/libs/cua/crates/cua-spaces-app-core/src/settings.rs b/libs/cua/crates/cua-spaces-app-core/src/settings.rs
index 865a1874a1..884979c886 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/settings.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/settings.rs
@@ -13,6 +13,7 @@ use crate::CoreError;
use crate::about::UpdateChannel;
use crate::experiments::{Experiment, Experiments};
use crate::model::Location;
+use crate::sign_in::SignInFailure;
use serde::{Deserialize, Serialize};
use std::path::Path;
@@ -300,14 +301,28 @@ pub enum SignInPhase {
/// The code to confirm there, when the flow has one.
#[serde(default)]
user_code: Option<String>,
+ /// A browser opened on this computer (false: the page is to be
+ /// opened by hand, here or on another device).
+ #[serde(default = "yes")]
+ opened: bool,
},
- /// It failed.
+ /// It failed ([`crate::sign_in::failed`] makes it).
Failed {
- /// Why.
+ /// Why ([`crate::sign_in::SignInFailure`]).
+ #[serde(default)]
+ reason: SignInFailure,
+ /// The line shown: "Sign-in didn't finish." and the reason.
message: String,
+ /// The error's own words, behind Details (never shown by default).
+ #[serde(default)]
+ detail: Option<String>,
},
}
+fn yes() -> bool {
+ true
+}
+
/// The usage-telemetry switch's state.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
@@ -675,7 +690,7 @@ pub fn page(input: &SettingsInput) -> SettingsPage {
r.enabled = true;
account.push(r);
}
- } else if let SignInPhase::Waiting { user_code } = &input.sign_in {
+ } else if let SignInPhase::Waiting { user_code, .. } = &input.sign_in {
let mut r = row(
"sign-in-code",
Text,
@@ -705,7 +720,7 @@ pub fn page(input: &SettingsInput) -> SettingsPage {
);
r.enabled = input.sign_in != SignInPhase::Starting;
account.push(r);
- if let SignInPhase::Failed { message } = &input.sign_in {
+ if let SignInPhase::Failed { message, .. } = &input.sign_in {
account.push(row("sign-in-error", Error, message));
}
}
@@ -1079,7 +1094,8 @@ mod tests {
assert_eq!(
sign_in,
SignInPhase::Waiting {
- user_code: Some("AB-CD".into())
+ user_code: Some("AB-CD".into()),
+ opened: true,
}
);
}
diff --git a/libs/cua/crates/cua-spaces-app-core/src/sign_in.rs b/libs/cua/crates/cua-spaces-app-core/src/sign_in.rs
new file mode 100644
index 0000000000..12987d9d5c
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/src/sign_in.rs
@@ -0,0 +1,589 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Sign-in you can see: every state of the account's sign-in, in one place
+//! (the sidebar's foot), in both shells.
+//!
+//! - Waiting: a spinner, "Waiting for your browser…", the code to confirm,
+//! "Open again" and "Cancel".
+//! - Failed: "Sign-in didn't finish." with a short reason, "Try again", the
+//! error's own words behind "Details", and a toast, so it never fails
+//! silently.
+//! - Signed in: "Signed in as <email>".
+//!
+//! A failure is typed ([`SignInFailure`]): the shells hand the core what
+//! they caught (the SDK error's case and its words, [`failure_of`]) or the
+//! reason they know ([`failed`]: the wait ran out), and the core picks the
+//! words ([`reason_text`]). Every reason has words; a test fails if one is
+//! added without them.
+
+use serde::{Deserialize, Serialize};
+
+use crate::settings::SignInPhase;
+
+/// Why a sign-in did not finish.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum SignInFailure {
+ /// The browser never confirmed: the wait ran out, or the code expired
+ /// before it was confirmed.
+ NotConfirmed,
+ /// The person declined it in the browser.
+ Declined,
+ /// The sign-in service refused the code (expired or already used).
+ CodeRejected,
+ /// This computer could not reach the sign-in service.
+ Offline,
+ /// The sign-in service answered with its own error.
+ ServiceUnavailable,
+ /// Signed in, but the session could not be stored on this computer (a
+ /// locked keychain, a credential store that refused the write).
+ CouldNotSave,
+ /// Anything else (the words are behind Details).
+ #[default]
+ Unknown,
+}
+
+impl SignInFailure {
+ /// Every reason, for the words test and the shells' own tests.
+ pub const ALL: [SignInFailure; 7] = [
+ SignInFailure::NotConfirmed,
+ SignInFailure::Declined,
+ SignInFailure::CodeRejected,
+ SignInFailure::Offline,
+ SignInFailure::ServiceUnavailable,
+ SignInFailure::CouldNotSave,
+ SignInFailure::Unknown,
+ ];
+}
+
+/// The line every failure starts with (also the toast's title).
+pub const FAILED_TITLE: &str = "Sign-in didn't finish";
+
+/// What the person can do about `reason`, in a few plain words (empty when
+/// there is nothing to add to "Try again").
+pub fn reason_text(reason: SignInFailure) -> &'static str {
+ // Exhaustive on purpose: a new reason does not build without its words.
+ match reason {
+ SignInFailure::NotConfirmed => "The browser didn't confirm in time.",
+ SignInFailure::Declined => "It was declined in the browser.",
+ SignInFailure::CodeRejected => "The sign-in code expired or was already used.",
+ SignInFailure::Offline => "Can't reach Cua. Check your connection.",
+ SignInFailure::ServiceUnavailable => {
+ "Cua's sign-in service had a problem. Try again in a minute."
+ }
+ SignInFailure::CouldNotSave => {
+ "This computer couldn't save the sign-in. Unlock your keychain, then try again."
+ }
+ SignInFailure::Unknown => "",
+ }
+}
+
+/// The failure's whole line: "Sign-in didn't finish." and the reason.
+pub fn failure_line(reason: SignInFailure) -> String {
+ match reason_text(reason) {
+ "" => format!("{FAILED_TITLE}."),
+ why => format!("{FAILED_TITLE}. {why}"),
+ }
+}
+
+/// The fixed word usage data records for `reason` (`schema::ERROR_KINDS`).
+pub fn error_kind(reason: SignInFailure) -> &'static str {
+ match reason {
+ SignInFailure::NotConfirmed => "timeout",
+ SignInFailure::Declined => "permission_denied",
+ SignInFailure::CodeRejected => "unauthenticated",
+ SignInFailure::Offline => "transport",
+ SignInFailure::ServiceUnavailable => "http",
+ SignInFailure::CouldNotSave => "internal",
+ SignInFailure::Unknown => "other",
+ }
+}
+
+/// Longest Details text kept (the error's words, never shown by default).
+const DETAIL_MAX: usize = 400;
+
+/// The failed phase for `reason`, with the error's own words (`detail`) for
+/// Details.
+pub fn failed(reason: SignInFailure, detail: Option<&str>) -> SignInPhase {
+ let detail = detail.map(str::trim).filter(|d| !d.is_empty()).map(|d| {
+ if d.chars().count() > DETAIL_MAX {
+ let cut: String = d.chars().take(DETAIL_MAX).collect();
+ format!("{cut}\u{2026}")
+ } else {
+ d.to_string()
+ }
+ });
+ SignInPhase::Failed {
+ reason,
+ message: failure_line(reason),
+ detail,
+ }
+}
+
+/// The failed phase for an error the shell caught: `variant` is the SDK
+/// error's case (`Timeout`, `Unauthenticated`, `Http`, `Internal`, ...; empty
+/// for any other error) and `message` its words.
+pub fn failed_from_error(variant: &str, message: &str) -> SignInPhase {
+ failed(failure_of(variant, message), Some(message))
+}
+
+/// The reason for an error from a sign-in (`cua_auth` through the SDK).
+///
+/// The SDK maps the sign-in's errors to its cases (`cua_auth::Error` ->
+/// `CuaError`): `Timeout` (the browser did not confirm, the code expired),
+/// `Unauthenticated` (the provider refused, or the person declined:
+/// `cua_auth::LOGIN_DECLINED`), `Http` (unreachable:
+/// `cua_auth::UNREACHABLE`, or the provider's own error), `Internal` (the
+/// credential store: "credential store: ..."). The words decide only where
+/// one case covers two reasons. `cua-auth`'s `sign_in_failures` test runs
+/// every real failure through this and fails when they drift apart.
+pub fn failure_of(variant: &str, message: &str) -> SignInFailure {
+ let v: String = variant
+ .chars()
+ .filter(|c| *c != '_')
+ .map(|c| c.to_ascii_lowercase())
+ .collect();
+ let m = message.to_ascii_lowercase();
+ let has = |words: &[&str]| words.iter().any(|w| m.contains(w));
+ if has(&["declined", "access_denied"]) || v == "cancelled" {
+ return SignInFailure::Declined;
+ }
+ if has(&["credential store", "keychain", "credential vault"]) {
+ return SignInFailure::CouldNotSave;
+ }
+ if v == "transport"
+ || has(&[
+ "could not reach",
+ "error sending request",
+ "connection refused",
+ "network",
+ "offline",
+ "dns",
+ "unreachable",
+ ])
+ {
+ return SignInFailure::Offline;
+ }
+ if v == "timeout" || has(&["expired before", "not completed in time", "timed out"]) {
+ return SignInFailure::NotConfirmed;
+ }
+ if has(&["could not start"]) {
+ return SignInFailure::ServiceUnavailable;
+ }
+ if v == "unauthenticated" || has(&["invalid_grant", "expired_token"]) {
+ return SignInFailure::CodeRejected;
+ }
+ if matches!(v.as_str(), "http" | "unsupported") || has(&["http 5", "discovery"]) {
+ return SignInFailure::ServiceUnavailable;
+ }
+ SignInFailure::Unknown
+}
+
+/// What the sidebar's foot shows.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum SignInFooterState {
+ /// Not signed in: "Sign in".
+ SignedOut,
+ /// Asking for a code / opening the browser.
+ Starting,
+ /// The browser is open.
+ Waiting,
+ /// It failed: the reason and Try again.
+ Failed,
+ /// Signed in.
+ SignedIn,
+}
+
+/// What the foot depends on.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct SignInFooterInput {
+ /// The signed-in account.
+ pub identity: Option<String>,
+ /// Cua Cloud works through client credentials (an API key).
+ pub cloud_configured: bool,
+ /// Signing in is possible here.
+ pub can_sign_in: bool,
+ /// The sign-in in progress.
+ pub sign_in: SignInPhase,
+ /// The page the sign-in finishes on is known (Open again).
+ pub has_url: bool,
+}
+
+/// A toast for a failure, so it is seen wherever the person is.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SignInToast {
+ /// "Sign-in didn't finish".
+ pub title: String,
+ /// The reason (none for an unknown one).
+ pub body: Option<String>,
+}
+
+/// The sidebar's foot: one place for every sign-in state.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SignInFooter {
+ /// Which state.
+ pub state: SignInFooterState,
+ /// The line: "Signed in as …", "Waiting for your browser…", "Sign-in
+ /// didn't finish. …", "Not signed in".
+ pub text: String,
+ /// The signed-in account (state `SignedIn`).
+ pub identity: Option<String>,
+ /// Waiting: the code to confirm in the browser.
+ pub code: Option<String>,
+ /// "Code".
+ pub code_label: String,
+ /// Waiting with a page: "Open again".
+ pub reopen_label: Option<String>,
+ /// Starting or waiting: "Cancel".
+ pub cancel_label: Option<String>,
+ /// "Sign in" or "Try again" (none while signed in or waiting).
+ pub action_label: Option<String>,
+ /// Failed: why.
+ pub reason: Option<SignInFailure>,
+ /// Failed: the error's own words, behind "Details".
+ pub detail: Option<String>,
+ /// "Details".
+ pub details_label: String,
+ /// Failed: the toast the shell shows once, when it fails.
+ pub toast: Option<SignInToast>,
+}
+
+/// The sidebar's foot for `input`.
+pub fn footer(input: &SignInFooterInput) -> SignInFooter {
+ let mut f = SignInFooter {
+ state: SignInFooterState::SignedOut,
+ text: String::new(),
+ identity: None,
+ code: None,
+ code_label: "Code".into(),
+ reopen_label: None,
+ cancel_label: None,
+ action_label: None,
+ reason: None,
+ detail: None,
+ details_label: "Details".into(),
+ toast: None,
+ };
+ if let Some(id) = input.identity.clone().filter(|i| !i.is_empty()) {
+ f.state = SignInFooterState::SignedIn;
+ f.text = format!("Signed in as {id}");
+ f.identity = Some(id);
+ return f;
+ }
+ match &input.sign_in {
+ SignInPhase::Starting => {
+ f.state = SignInFooterState::Starting;
+ f.text = "Opening your browser\u{2026}".into();
+ f.cancel_label = Some("Cancel".into());
+ }
+ SignInPhase::Waiting { user_code, opened } => {
+ f.state = SignInFooterState::Waiting;
+ f.text = if *opened {
+ "Waiting for your browser\u{2026}".into()
+ } else {
+ // No browser opened here: the page can be opened anywhere.
+ "Open the sign-in page to continue.".into()
+ };
+ f.code = user_code.clone().filter(|c| !c.is_empty());
+ f.reopen_label = input.has_url.then(|| "Open again".into());
+ f.cancel_label = Some("Cancel".into());
+ }
+ SignInPhase::Failed {
+ reason,
+ message,
+ detail,
+ } => {
+ f.state = SignInFooterState::Failed;
+ f.text = if message.is_empty() {
+ failure_line(*reason)
+ } else {
+ message.clone()
+ };
+ f.reason = Some(*reason);
+ f.detail = detail.clone();
+ f.action_label = Some("Try again".into());
+ let why = reason_text(*reason);
+ f.toast = Some(SignInToast {
+ title: FAILED_TITLE.into(),
+ body: (!why.is_empty()).then(|| why.into()),
+ });
+ }
+ SignInPhase::Idle => {
+ f.text = if input.cloud_configured {
+ "Signed in with an API key".into()
+ } else {
+ "Not signed in".into()
+ };
+ f.action_label = input.can_sign_in.then(|| "Sign in".into());
+ }
+ }
+ f
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn every_reason_has_plain_short_words_and_a_telemetry_kind() {
+ for r in SignInFailure::ALL {
+ let line = failure_line(r);
+ assert!(line.starts_with("Sign-in didn't finish."), "{r:?}: {line}");
+ assert!(line.len() <= 120, "{r:?} is too long: {line}");
+ // Never a raw error: no protocol words, codes or quoting.
+ for raw in ["HTTP", "error", "Error", "`", "{", "_", "OIDC", "token"] {
+ assert!(!line.contains(raw), "{r:?} shows {raw:?}: {line}");
+ }
+ if r != SignInFailure::Unknown {
+ assert!(!reason_text(r).is_empty(), "{r:?} has no reason");
+ }
+ let kind = error_kind(r);
+ assert!(
+ [
+ "timeout",
+ "permission_denied",
+ "unauthenticated",
+ "transport",
+ "http",
+ "internal",
+ "other"
+ ]
+ .contains(&kind),
+ "{r:?}: {kind}"
+ );
+ }
+ // Every reason is in ALL (the words test covers them all): the
+ // match below does not build without a new one.
+ for r in SignInFailure::ALL {
+ let i = match r {
+ SignInFailure::NotConfirmed => 0,
+ SignInFailure::Declined => 1,
+ SignInFailure::CodeRejected => 2,
+ SignInFailure::Offline => 3,
+ SignInFailure::ServiceUnavailable => 4,
+ SignInFailure::CouldNotSave => 5,
+ SignInFailure::Unknown => 6,
+ };
+ assert_eq!(SignInFailure::ALL[i], r);
+ }
+ }
+
+ #[test]
+ fn errors_map_to_reasons() {
+ let cases = [
+ (
+ "Timeout",
+ "device authorization expired before it was completed",
+ SignInFailure::NotConfirmed,
+ ),
+ (
+ "Timeout",
+ "browser sign-in was not completed in time; try `cua auth login --remote`",
+ SignInFailure::NotConfirmed,
+ ),
+ (
+ "Timeout",
+ "the sign-in code expired before it was confirmed",
+ SignInFailure::NotConfirmed,
+ ),
+ (
+ "Unauthenticated",
+ "sign-in was declined in the browser: User denied",
+ SignInFailure::Declined,
+ ),
+ (
+ "Unauthenticated",
+ "Code not valid",
+ SignInFailure::CodeRejected,
+ ),
+ (
+ "Unauthenticated",
+ "invalid_grant",
+ SignInFailure::CodeRejected,
+ ),
+ (
+ "Http",
+ "could not reach the sign-in service: error sending request for url (http://x)",
+ SignInFailure::Offline,
+ ),
+ (
+ "Http",
+ "the sign-in service answered HTTP 503: unavailable",
+ SignInFailure::ServiceUnavailable,
+ ),
+ (
+ "Http",
+ "OIDC discovery failed (HTTP 502)",
+ SignInFailure::ServiceUnavailable,
+ ),
+ (
+ "Unsupported",
+ "browser sign-in is unavailable: x",
+ SignInFailure::ServiceUnavailable,
+ ),
+ (
+ "Internal",
+ "credential store: User interaction is not allowed.",
+ SignInFailure::CouldNotSave,
+ ),
+ ("Transport", "connection reset", SignInFailure::Offline),
+ (
+ "Closed",
+ "this sign-in already finished",
+ SignInFailure::Unknown,
+ ),
+ (
+ "",
+ "The sign-in timed out. Try again.",
+ SignInFailure::NotConfirmed,
+ ),
+ ("", "something odd", SignInFailure::Unknown),
+ ];
+ for (variant, message, want) in cases {
+ assert_eq!(failure_of(variant, message), want, "{variant}: {message}");
+ }
+ }
+
+ #[test]
+ fn the_failed_phase_keeps_the_words_for_details_only() {
+ let p = failed_from_error("Http", "could not reach the sign-in service: dns error");
+ let SignInPhase::Failed {
+ reason,
+ message,
+ detail,
+ } = p
+ else {
+ panic!()
+ };
+ assert_eq!(reason, SignInFailure::Offline);
+ assert_eq!(
+ message,
+ "Sign-in didn't finish. Can't reach Cua. Check your connection."
+ );
+ assert_eq!(
+ detail.as_deref(),
+ Some("could not reach the sign-in service: dns error")
+ );
+ let long = "x".repeat(1000);
+ let SignInPhase::Failed { detail, .. } = failed(SignInFailure::Unknown, Some(&long)) else {
+ panic!()
+ };
+ assert_eq!(detail.unwrap().chars().count(), DETAIL_MAX + 1);
+ let SignInPhase::Failed { detail, .. } = failed(SignInFailure::Unknown, Some(" ")) else {
+ panic!()
+ };
+ assert_eq!(detail, None);
+ }
+
+ #[test]
+ fn the_footer_shows_every_state_in_one_place() {
+ let signed_out = footer(&SignInFooterInput {
+ can_sign_in: true,
+ ..Default::default()
+ });
+ assert_eq!(signed_out.state, SignInFooterState::SignedOut);
+ assert_eq!(signed_out.text, "Not signed in");
+ assert_eq!(signed_out.action_label.as_deref(), Some("Sign in"));
+ assert!(signed_out.toast.is_none());
+
+ let waiting = footer(&SignInFooterInput {
+ sign_in: SignInPhase::Waiting {
+ user_code: Some("4F2-91K".into()),
+ opened: true,
+ },
+ has_url: true,
+ can_sign_in: true,
+ ..Default::default()
+ });
+ assert_eq!(waiting.state, SignInFooterState::Waiting);
+ assert_eq!(waiting.text, "Waiting for your browser\u{2026}");
+ assert_eq!(waiting.code.as_deref(), Some("4F2-91K"));
+ assert_eq!(waiting.reopen_label.as_deref(), Some("Open again"));
+ assert_eq!(waiting.cancel_label.as_deref(), Some("Cancel"));
+ assert_eq!(waiting.action_label, None);
+
+ let not_opened = footer(&SignInFooterInput {
+ sign_in: SignInPhase::Waiting {
+ user_code: None,
+ opened: false,
+ },
+ has_url: true,
+ ..Default::default()
+ });
+ assert_eq!(not_opened.text, "Open the sign-in page to continue.");
+ assert_eq!(not_opened.code, None);
+
+ let failed = footer(&SignInFooterInput {
+ sign_in: failed(
+ SignInFailure::NotConfirmed,
+ Some("device authorization expired"),
+ ),
+ can_sign_in: true,
+ ..Default::default()
+ });
+ assert_eq!(failed.state, SignInFooterState::Failed);
+ assert_eq!(
+ failed.text,
+ "Sign-in didn't finish. The browser didn't confirm in time."
+ );
+ assert_eq!(failed.action_label.as_deref(), Some("Try again"));
+ assert_eq!(
+ failed.detail.as_deref(),
+ Some("device authorization expired")
+ );
+ assert_eq!(
+ failed.toast,
+ Some(SignInToast {
+ title: "Sign-in didn't finish".into(),
+ body: Some("The browser didn't confirm in time.".into()),
+ })
+ );
+
+ let signed_in = footer(&SignInFooterInput {
+ identity: Some("[email protected]".into()),
+ sign_in: failed.reason.map(|r| self::failed(r, None)).unwrap(),
+ ..Default::default()
+ });
+ assert_eq!(signed_in.state, SignInFooterState::SignedIn);
+ assert_eq!(signed_in.text, "Signed in as [email protected]");
+ assert!(signed_in.toast.is_none());
+ }
+
+ #[test]
+ fn a_failed_phase_from_an_older_shell_still_reads() {
+ // A shell that only has words (no reason, no detail).
+ let p: SignInPhase = serde_json::from_str(
+ r#"{"kind":"failed","message":"The sign-in timed out. Try again."}"#,
+ )
+ .unwrap();
+ assert_eq!(
+ p,
+ SignInPhase::Failed {
+ reason: SignInFailure::Unknown,
+ message: "The sign-in timed out. Try again.".into(),
+ detail: None
+ }
+ );
+ let w: SignInPhase = serde_json::from_str(r#"{"kind":"waiting","userCode":"AB"}"#).unwrap();
+ assert_eq!(
+ w,
+ SignInPhase::Waiting {
+ user_code: Some("AB".into()),
+ opened: true
+ }
+ );
+ let f = serde_json::to_value(failed(
+ SignInFailure::CouldNotSave,
+ Some("credential store: x"),
+ ))
+ .unwrap();
+ assert_eq!(f["kind"], "failed");
+ assert_eq!(f["reason"], "couldNotSave");
+ assert_eq!(f["detail"], "credential store: x");
+ }
+}
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 9114df1c83..c098072529 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/telemetry.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/telemetry.rs
@@ -342,6 +342,17 @@ pub fn sign_in_failed(message: Option<&str>) -> Vec<TelemetrySignal> {
}]
}
+/// A sign-in failed for `reason` or was cancelled (`None`): its fixed
+/// word only ([`crate::sign_in::error_kind`]).
+pub fn sign_in_failure(reason: Option<crate::sign_in::SignInFailure>) -> Vec<TelemetrySignal> {
+ vec![TelemetrySignal::SignInFailed {
+ error_kind: reason
+ .map(crate::sign_in::error_kind)
+ .unwrap_or("cancelled")
+ .into(),
+ }]
+}
+
/// "Start using Cua Spaces" on Done (nothing while usage data is off).
pub fn onboarding_finished(s: &OnboardingState) -> Vec<TelemetrySignal> {
if !s.shares_usage() {
diff --git a/libs/cua/crates/cua-spaces-app-core/tests/sign_in_browser_timeout.rs b/libs/cua/crates/cua-spaces-app-core/tests/sign_in_browser_timeout.rs
new file mode 100644
index 0000000000..01a2535abf
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/tests/sign_in_browser_timeout.rs
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! A browser sign-in nobody finishes (the tab was closed, the browser never
+//! opened) ends with "the browser didn't confirm", not a wait without end.
+//! Its own test binary: it sets the process-wide wait
+//! (`CUA_OIDC_LOGIN_TIMEOUT_SECS`).
+
+use cua_auth::{Flow, Method, Oidc, Session, Store};
+use cua_spaces_app_core::sign_in::{self, SignInFailure};
+use std::time::Duration;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+/// An issuer that accepts browser sign-in and nothing else.
+async fn issuer() -> String {
+ let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", l.local_addr().unwrap());
+ let b = base.clone();
+ tokio::spawn(async move {
+ while let Ok((mut s, _)) = l.accept().await {
+ let base = b.clone();
+ tokio::spawn(async move {
+ let mut buf = vec![0u8; 8192];
+ let n = s.read(&mut buf).await.unwrap_or(0);
+ let head = String::from_utf8_lossy(&buf[..n]).to_string();
+ let body = if head.starts_with("GET /.well-known/openid-configuration") {
+ format!(
+ r#"{{"authorization_endpoint":"{base}/auth","token_endpoint":"{base}/token"}}"#
+ )
+ } else {
+ "{}".into()
+ };
+ let resp = format!(
+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = s.write_all(resp.as_bytes()).await;
+ });
+ }
+ });
+ base
+}
+
+#[tokio::test]
+async fn a_browser_sign_in_nobody_finishes_is_not_confirmed() {
+ // SAFETY: the only test in this binary; nothing else reads the env.
+ unsafe { std::env::set_var("CUA_OIDC_LOGIN_TIMEOUT_SECS", "1") };
+ let url = issuer().await;
+ let d = tempfile::tempdir().unwrap();
+ let s = Session::new(
+ Oidc::new(&url, "cua-cli"),
+ Store::File(d.path().join("credentials.json")),
+ );
+ let p = s.begin_login(Flow::Browser).await.unwrap();
+ assert_eq!(p.method, Method::Browser);
+ let e = tokio::time::timeout(Duration::from_secs(20), p.complete())
+ .await
+ .unwrap()
+ .unwrap_err();
+ assert!(matches!(e, cua_auth::Error::Timeout(_)), "{e}");
+ assert_eq!(
+ sign_in::failure_of("Timeout", &e.to_string()),
+ SignInFailure::NotConfirmed
+ );
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/tests/sign_in_failures.rs b/libs/cua/crates/cua-spaces-app-core/tests/sign_in_failures.rs
new file mode 100644
index 0000000000..c893fef45f
--- /dev/null
+++ b/libs/cua/crates/cua-spaces-app-core/tests/sign_in_failures.rs
@@ -0,0 +1,428 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Drift guard: every way a real sign-in (`cua-auth`, against a loopback
+//! issuer, with a file store in a temporary directory, never the keychain)
+//! fails reaches the shells as a typed reason with words, never silently
+//! and never as "Unknown".
+//!
+//! The shells see a sign-in error as the SDK's `CuaError` case and its
+//! words; [`sdk_case`] is the SDK's mapping (`cua-sdk/src/native/auth.rs`,
+//! `impl From<cua_auth::Error> for CuaError`), exhaustive so a new
+//! `cua_auth::Error` case does not build here until it has a reason.
+
+use cua_auth::{Credentials, Flow, Method, Oidc, Session, Store};
+use cua_spaces_app_core::settings::SignInPhase;
+use cua_spaces_app_core::sign_in::{self, SignInFailure};
+use serde_json::{Value, json};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+
+/// The SDK's case for a sign-in error, as the shells receive it.
+fn sdk_case(e: &cua_auth::Error) -> &'static str {
+ use cua_auth::Error as E;
+ match e {
+ E::NotLoggedIn | E::Unauthenticated(_) => "Unauthenticated",
+ E::Http(_) => "Http",
+ E::Timeout(_) => "Timeout",
+ E::Unsupported(_) => "Unsupported",
+ E::InvalidArgument(_) => "InvalidArgument",
+ E::Store(_) => "Internal",
+ }
+}
+
+/// The reason a shell shows for `e`, and checks it is shown with words.
+fn shown(e: &cua_auth::Error) -> SignInFailure {
+ let phase = sign_in::failed_from_error(sdk_case(e), &e.to_string());
+ let SignInPhase::Failed {
+ reason,
+ message,
+ detail,
+ } = &phase
+ else {
+ panic!("{phase:?}")
+ };
+ assert!(message.starts_with("Sign-in didn't finish."), "{message}");
+ assert_eq!(detail.as_deref(), Some(e.to_string().trim()));
+ let footer = sign_in::footer(&sign_in::SignInFooterInput {
+ sign_in: phase.clone(),
+ can_sign_in: true,
+ ..Default::default()
+ });
+ assert_eq!(footer.action_label.as_deref(), Some("Try again"));
+ assert!(footer.toast.is_some(), "a failure always toasts");
+ *reason
+}
+
+/// What the loopback issuer answers.
+#[derive(Clone)]
+struct Script {
+ discovery_status: u16,
+ /// The token endpoint discovery names (none: this issuer's).
+ token_endpoint: Option<String>,
+ /// Browser + PKCE accepted (the preflight answers 200).
+ pkce_ok: bool,
+ device_start: (u16, Value),
+ /// The device grant's answers in order (the last one repeats).
+ device_polls: Vec<(u16, Value)>,
+ device_expires_in: u64,
+ /// The authorization code exchange.
+ exchange: (u16, Value),
+}
+
+impl Default for Script {
+ fn default() -> Self {
+ Script {
+ discovery_status: 200,
+ token_endpoint: None,
+ pkce_ok: false,
+ device_start: (200, Value::Null),
+ device_polls: vec![(400, json!({"error": "authorization_pending"}))],
+ device_expires_in: 2,
+ exchange: (200, tokens()),
+ }
+ }
+}
+
+fn tokens() -> Value {
+ use base64::Engine;
+ let e = |v: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(v);
+ let claims = json!({"preferred_username": "ellie", "email": "[email protected]"});
+ json!({
+ "access_token": format!("{}.{}.sig", e(br#"{"alg":"none"}"#), e(claims.to_string().as_bytes())),
+ "refresh_token": "rt", "expires_in": 3600
+ })
+}
+
+/// A loopback issuer that follows `script`; returns its URL.
+async fn issuer(script: Script) -> String {
+ let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", l.local_addr().unwrap());
+ let polls = Arc::new(Mutex::new(0usize));
+ let b = base.clone();
+ tokio::spawn(async move {
+ while let Ok((mut s, _)) = l.accept().await {
+ let (script, base, polls) = (script.clone(), b.clone(), polls.clone());
+ tokio::spawn(async move {
+ let mut buf = Vec::new();
+ let mut tmp = [0u8; 4096];
+ let head_end = loop {
+ match s.read(&mut tmp).await {
+ Ok(0) | Err(_) => return,
+ Ok(n) => buf.extend_from_slice(&tmp[..n]),
+ }
+ if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
+ break i + 4;
+ }
+ if buf.len() > 1 << 16 {
+ return;
+ }
+ };
+ let head = String::from_utf8_lossy(&buf[..head_end]).to_string();
+ let len: usize = head
+ .lines()
+ .find_map(|l| {
+ l.to_ascii_lowercase()
+ .strip_prefix("content-length:")
+ .map(|v| v.trim().parse().unwrap_or(0))
+ })
+ .unwrap_or(0)
+ .min(1 << 16);
+ while buf.len() < head_end + len {
+ match s.read(&mut tmp).await {
+ Ok(0) | Err(_) => break,
+ Ok(n) => buf.extend_from_slice(&tmp[..n]),
+ }
+ }
+ let body = String::from_utf8_lossy(&buf[head_end..]).to_string();
+ let mut first = head.lines().next().unwrap_or_default().split_whitespace();
+ let method = first.next().unwrap_or_default().to_string();
+ let path = first
+ .next()
+ .unwrap_or_default()
+ .split('?')
+ .next()
+ .unwrap_or_default()
+ .to_string();
+ let grant = url::form_urlencoded::parse(body.as_bytes())
+ .find(|(k, _)| k == "grant_type")
+ .map(|(_, v)| v.into_owned());
+ let (status, v) = match (method.as_str(), path.as_str()) {
+ ("GET", "/.well-known/openid-configuration") => (
+ script.discovery_status,
+ json!({
+ "authorization_endpoint": format!("{base}/auth"),
+ "token_endpoint": script.token_endpoint.clone().unwrap_or(format!("{base}/token")),
+ "device_authorization_endpoint": format!("{base}/device"),
+ }),
+ ),
+ ("GET", "/auth") if script.pkce_ok => (200, json!({})),
+ ("GET", "/auth") => (400, json!({"error": "Invalid parameter: redirect_uri"})),
+ ("POST", "/device") if script.device_start.0 == 200 => (
+ 200,
+ json!({"device_code": "dc", "user_code": "4F2-91K",
+ "verification_uri": "https://login.test/device",
+ "expires_in": script.device_expires_in, "interval": 1}),
+ ),
+ ("POST", "/device") => script.device_start.clone(),
+ ("POST", "/token") if grant.as_deref() == Some("authorization_code") => {
+ script.exchange.clone()
+ }
+ ("POST", "/token") => {
+ let mut n = polls.lock().unwrap();
+ let i = (*n).min(script.device_polls.len() - 1);
+ *n += 1;
+ script.device_polls[i].clone()
+ }
+ _ => (404, json!({})),
+ };
+ let body = v.to_string();
+ let resp = format!(
+ "HTTP/1.1 {status} X\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = s.write_all(resp.as_bytes()).await;
+ let _ = s.shutdown().await;
+ });
+ }
+ });
+ base
+}
+
+fn session(url: &str, dir: &std::path::Path) -> Session {
+ Session::new(
+ Oidc::new(url, "cua-cli"),
+ Store::File(dir.join("credentials.json")),
+ )
+}
+
+/// A port nothing listens on (bound, then closed).
+async fn closed_port() -> u16 {
+ let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ l.local_addr().unwrap().port()
+}
+
+/// Runs a device-code sign-in to its end.
+async fn device(script: Script) -> Result<Credentials, cua_auth::Error> {
+ let url = issuer(script).await;
+ let d = tempfile::tempdir().unwrap();
+ let p = session(&url, d.path()).begin_login(Flow::Device).await?;
+ assert_eq!(p.method, Method::Device);
+ tokio::time::timeout(Duration::from_secs(30), p.complete())
+ .await
+ .expect("the device flow ends by itself")
+}
+
+/// Starts a browser sign-in and answers its redirect with `query`.
+async fn browser(script: Script, query: impl Fn(&str) -> String) -> cua_auth::Error {
+ let url = issuer(Script {
+ pkce_ok: true,
+ ..script
+ })
+ .await;
+ let d = tempfile::tempdir().unwrap();
+ let p = session(&url, d.path())
+ .begin_login(Flow::Browser)
+ .await
+ .unwrap();
+ let u = url::Url::parse(&p.url).unwrap();
+ let q: std::collections::HashMap<String, String> = u.query_pairs().into_owned().collect();
+ let redirect = url::Url::parse(&q["redirect_uri"]).unwrap();
+ let done = tokio::spawn(tokio::time::timeout(Duration::from_secs(20), p.complete()));
+ let mut s =
+ tokio::net::TcpStream::connect((redirect.host_str().unwrap(), redirect.port().unwrap()))
+ .await
+ .unwrap();
+ let req = format!(
+ "GET /callback?{} HTTP/1.1\r\nhost: 127.0.0.1\r\nconnection: close\r\n\r\n",
+ query(&q["state"])
+ );
+ s.write_all(req.as_bytes()).await.unwrap();
+ let mut page = String::new();
+ let _ = s.read_to_string(&mut page).await;
+ done.await.unwrap().unwrap().unwrap_err()
+}
+
+#[tokio::test]
+async fn an_unreachable_sign_in_service_is_offline() {
+ let port = closed_port().await;
+ let d = tempfile::tempdir().unwrap();
+ let e = session(&format!("http://127.0.0.1:{port}"), d.path())
+ .begin_login(Flow::Auto)
+ .await
+ .err()
+ .unwrap();
+ assert!(e.to_string().starts_with(cua_auth::UNREACHABLE), "{e}");
+ assert_eq!(shown(&e), SignInFailure::Offline);
+}
+
+#[tokio::test]
+async fn a_broken_sign_in_service_is_its_problem() {
+ let url = issuer(Script {
+ discovery_status: 502,
+ ..Default::default()
+ })
+ .await;
+ let d = tempfile::tempdir().unwrap();
+ let e = session(&url, d.path())
+ .begin_login(Flow::Auto)
+ .await
+ .err()
+ .unwrap();
+ assert_eq!(shown(&e), SignInFailure::ServiceUnavailable, "{e}");
+
+ // The device code is refused at the start (a client the provider
+ // does not allow): the service's problem, not the person's code.
+ let e = device(Script {
+ device_start: (400, json!({"error": "unauthorized_client"})),
+ ..Default::default()
+ })
+ .await
+ .unwrap_err();
+ assert_eq!(shown(&e), SignInFailure::ServiceUnavailable, "{e}");
+}
+
+#[tokio::test]
+async fn a_code_never_confirmed_is_not_confirmed() {
+ // Pending until the code expires.
+ let e = device(Script::default()).await.unwrap_err();
+ assert!(matches!(e, cua_auth::Error::Timeout(_)), "{e}");
+ assert_eq!(shown(&e), SignInFailure::NotConfirmed);
+ // The provider says the code expired.
+ let e = device(Script {
+ device_polls: vec![(400, json!({"error": "expired_token"}))],
+ device_expires_in: 60,
+ ..Default::default()
+ })
+ .await
+ .unwrap_err();
+ assert!(matches!(e, cua_auth::Error::Timeout(_)), "{e}");
+ assert_eq!(shown(&e), SignInFailure::NotConfirmed);
+}
+
+#[tokio::test]
+async fn declining_in_the_browser_is_declined() {
+ let e = device(Script {
+ device_polls: vec![(400, json!({"error": "access_denied"}))],
+ ..Default::default()
+ })
+ .await
+ .unwrap_err();
+ assert!(e.to_string().starts_with(cua_auth::LOGIN_DECLINED), "{e}");
+ assert_eq!(shown(&e), SignInFailure::Declined);
+
+ let e = browser(Script::default(), |state| {
+ format!("error=access_denied&error_description=User+denied&state={state}")
+ })
+ .await;
+ assert!(e.to_string().starts_with(cua_auth::LOGIN_DECLINED), "{e}");
+ assert_eq!(shown(&e), SignInFailure::Declined);
+}
+
+#[tokio::test]
+async fn a_refused_code_is_rejected_and_a_broken_exchange_is_the_service() {
+ let e = browser(
+ Script {
+ exchange: (
+ 400,
+ json!({"error": "invalid_grant", "error_description": "Code not valid"}),
+ ),
+ ..Default::default()
+ },
+ |state| format!("code=c&state={state}"),
+ )
+ .await;
+ assert_eq!(shown(&e), SignInFailure::CodeRejected, "{e}");
+
+ let e = browser(
+ Script {
+ exchange: (500, json!({"error": "server_error"})),
+ ..Default::default()
+ },
+ |state| format!("code=c&state={state}"),
+ )
+ .await;
+ assert_eq!(shown(&e), SignInFailure::ServiceUnavailable, "{e}");
+}
+
+#[tokio::test]
+async fn a_network_drop_while_waiting_is_retried_then_offline() {
+ // The provider stumbles once, then the person confirms: signed in.
+ let c = device(Script {
+ device_polls: vec![
+ (503, json!({"error": "temporarily_unavailable"})),
+ (200, tokens()),
+ ],
+ device_expires_in: 30,
+ ..Default::default()
+ })
+ .await
+ .unwrap();
+ assert!(c.access_token.contains('.'));
+
+ // The token endpoint stays unreachable until the code expires: that,
+ // not "expired", is what the person sees.
+ let port = closed_port().await;
+ let e = device(Script {
+ token_endpoint: Some(format!("http://127.0.0.1:{port}/token")),
+ ..Default::default()
+ })
+ .await
+ .unwrap_err();
+ assert!(e.to_string().starts_with(cua_auth::UNREACHABLE), "{e}");
+ assert_eq!(shown(&e), SignInFailure::Offline);
+
+ // The provider keeps failing until the code expires.
+ let e = device(Script {
+ device_polls: vec![(503, json!({"error": "temporarily_unavailable"}))],
+ ..Default::default()
+ })
+ .await
+ .unwrap_err();
+ assert_eq!(shown(&e), SignInFailure::ServiceUnavailable, "{e}");
+}
+
+#[tokio::test]
+async fn a_session_that_cannot_be_saved_says_so() {
+ let url = issuer(Script {
+ device_polls: vec![(200, tokens())],
+ ..Default::default()
+ })
+ .await;
+ let d = tempfile::tempdir().unwrap();
+ // The store's directory is a file: every write fails, as a locked
+ // keychain's would.
+ let blocker = d.path().join("not-a-directory");
+ std::fs::write(&blocker, b"x").unwrap();
+ let s = Session::new(
+ Oidc::new(&url, "cua-cli"),
+ Store::File(blocker.join("credentials.json")),
+ );
+ let p = s.begin_login(Flow::Device).await.unwrap();
+ let c = p.complete().await.unwrap();
+ let e = s.install(c).await.unwrap_err();
+ assert!(matches!(e, cua_auth::Error::Store(_)), "{e}");
+ assert_eq!(shown(&e), SignInFailure::CouldNotSave);
+}
+
+#[test]
+fn every_sdk_case_a_sign_in_can_fail_with_has_a_reason() {
+ // The cases `sdk_case` can give, with representative words.
+ for (case, words) in [
+ ("Unauthenticated", "Code not valid"),
+ ("Http", "OIDC discovery failed (HTTP 500)"),
+ (
+ "Timeout",
+ "device authorization expired before it was completed",
+ ),
+ ("Unsupported", "browser sign-in is unavailable: no endpoint"),
+ ("Internal", "credential store: denied"),
+ ] {
+ assert_ne!(
+ sign_in::failure_of(case, words),
+ SignInFailure::Unknown,
+ "{case}: {words}"
+ );
+ }
+}
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
index a8b8cec55b..17109b4f86 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
@@ -2594,6 +2594,31 @@ pub fn app_telemetry_sign_in_failed(message: Option<String>) -> Vec<AppTelemetry
core::telemetry::sign_in_failed(message.as_deref())
}
+/// A sign-in failed for `reason` or was cancelled (none): its kind only.
+#[uniffi::export]
+pub fn app_telemetry_sign_in_failure(reason: Option<AppSignInFailure>) -> Vec<AppTelemetrySignal> {
+ core::telemetry::sign_in_failure(reason)
+}
+
+/// The sidebar's foot: every sign-in state in one place.
+#[uniffi::export]
+pub fn app_sign_in_footer(input: AppSignInFooterInput) -> AppSignInFooter {
+ core::sign_in::footer(&input)
+}
+
+/// The failed phase for a known reason, with the error's words for Details.
+#[uniffi::export]
+pub fn app_sign_in_failed(reason: AppSignInFailure, detail: Option<String>) -> AppSignInPhase {
+ core::sign_in::failed(reason, detail.as_deref())
+}
+
+/// The failed phase for an error the shell caught: the SDK error's case
+/// (`Timeout`, `Http`, ...; empty for another error) and its words.
+#[uniffi::export]
+pub fn app_sign_in_failed_from_error(variant: String, message: String) -> AppSignInPhase {
+ core::sign_in::failed_from_error(&variant, &message)
+}
+
/// "Start using Cua Spaces".
#[uniffi::export]
pub fn app_telemetry_onboarding_finished(state: AppOnboardingState) -> Vec<AppTelemetrySignal> {
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
index 5b286b9cdb..92aa1efd3c 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core_types.rs
@@ -6699,11 +6699,18 @@ pub enum AppSignInPhase {
Waiting {
/// The code to confirm there, when the flow has one.
user_code: Option<String>,
+ /// A browser opened on this computer (false: the page is to be
+ /// opened by hand, here or on another device).
+ opened: bool,
},
- /// It failed.
+ /// It failed ([`crate::sign_in::failed`] makes it).
Failed {
- /// Why.
+ /// Why ([`crate::sign_in::SignInFailure`]).
+ reason: AppSignInFailure,
+ /// The line shown: "Sign-in didn't finish." and the reason.
message: String,
+ /// The error's own words, behind Details (never shown by default).
+ detail: Option<String>,
},
}
@@ -6874,6 +6881,101 @@ pub struct AppSettingsPage {
pub sections: Vec<AppSettingsSection>,
}
+/// Why a sign-in did not finish.
+pub type AppSignInFailure = core::sign_in::SignInFailure;
+#[uniffi::remote(Enum)]
+pub enum AppSignInFailure {
+ /// The browser never confirmed: the wait ran out, or the code expired
+ /// before it was confirmed.
+ NotConfirmed,
+ /// The person declined it in the browser.
+ Declined,
+ /// The sign-in service refused the code (expired or already used).
+ CodeRejected,
+ /// This computer could not reach the sign-in service.
+ Offline,
+ /// The sign-in service answered with its own error.
+ ServiceUnavailable,
+ /// Signed in, but the session could not be stored on this computer (a
+ /// locked keychain, a credential store that refused the write).
+ CouldNotSave,
+ /// Anything else (the words are behind Details).
+ Unknown,
+}
+
+/// What the sidebar's foot shows.
+pub type AppSignInFooterState = core::sign_in::SignInFooterState;
+#[uniffi::remote(Enum)]
+pub enum AppSignInFooterState {
+ /// Not signed in: "Sign in".
+ SignedOut,
+ /// Asking for a code / opening the browser.
+ Starting,
+ /// The browser is open.
+ Waiting,
+ /// It failed: the reason and Try again.
+ Failed,
+ /// Signed in.
+ SignedIn,
+}
+
+/// What the foot depends on.
+pub type AppSignInFooterInput = core::sign_in::SignInFooterInput;
+#[uniffi::remote(Record)]
+pub struct AppSignInFooterInput {
+ /// The signed-in account.
+ pub identity: Option<String>,
+ /// Cua Cloud works through client credentials (an API key).
+ pub cloud_configured: bool,
+ /// Signing in is possible here.
+ pub can_sign_in: bool,
+ /// The sign-in in progress.
+ pub sign_in: AppSignInPhase,
+ /// The page the sign-in finishes on is known (Open again).
+ pub has_url: bool,
+}
+
+/// A toast for a failure, so it is seen wherever the person is.
+pub type AppSignInToast = core::sign_in::SignInToast;
+#[uniffi::remote(Record)]
+pub struct AppSignInToast {
+ /// "Sign-in didn't finish".
+ pub title: String,
+ /// The reason (none for an unknown one).
+ pub body: Option<String>,
+}
+
+/// The sidebar's foot: one place for every sign-in state.
+pub type AppSignInFooter = core::sign_in::SignInFooter;
+#[uniffi::remote(Record)]
+pub struct AppSignInFooter {
+ /// Which state.
+ pub state: AppSignInFooterState,
+ /// The line: "Signed in as …", "Waiting for your browser…", "Sign-in
+ /// didn't finish. …", "Not signed in".
+ pub text: String,
+ /// The signed-in account (state `SignedIn`).
+ pub identity: Option<String>,
+ /// Waiting: the code to confirm in the browser.
+ pub code: Option<String>,
+ /// "Code".
+ pub code_label: String,
+ /// Waiting with a page: "Open again".
+ pub reopen_label: Option<String>,
+ /// Starting or waiting: "Cancel".
+ pub cancel_label: Option<String>,
+ /// "Sign in" or "Try again" (none while signed in or waiting).
+ pub action_label: Option<String>,
+ /// Failed: why.
+ pub reason: Option<AppSignInFailure>,
+ /// Failed: the error's own words, behind "Details".
+ pub detail: Option<String>,
+ /// "Details".
+ pub details_label: String,
+ /// Failed: the toast the shell shows once, when it fails.
+ pub toast: Option<AppSignInToast>,
+}
+
/// What the chrome depends on.
pub type AppChromeInput = core::window::ChromeInput;
#[uniffi::remote(Record)]
diff --git a/libs/cua/scripts/generate-app-core-ffi.py b/libs/cua/scripts/generate-app-core-ffi.py
index 8cf3269bf8..fb0d6f4cf7 100644
--- a/libs/cua/scripts/generate-app-core-ffi.py
+++ b/libs/cua/scripts/generate-app-core-ffi.py
@@ -55,6 +55,7 @@ TYPES = [
("login_item.rs", "login_item", ["LoginItemStatus", "LoginItemInput", "LoginItemPlan"]),
("experiments.rs", "experiments", ["Experiments"]),
("settings.rs", "settings", ["SwitcherTheme", "AppSettings", "KeyCombo", "SignInPhase", "TelemetryInput", "SettingsInput", "SettingsRowKind", "SettingsOption", "SettingsRow", "SettingsSection", "SettingsPage"]),
+ ("sign_in.rs", "sign_in", ["SignInFailure", "SignInFooterState", "SignInFooterInput", "SignInToast", "SignInFooter"]),
("window.rs", "window", ["ChromeInput", "MainChrome", "MenuItemId", "MenuItem", "MenuInput"]),
("host.rs", "host", ["HostSummaryInput", "HostSetupRequest", "HostClient", "HostAccess", "HostPermissionInput", "HostProvidedSpace", "HostSpacesAudit", "HostState", "HostAccount", "HostAccountStep", "HostActionId", "HostSettingChange", "HostToggle", "HostConfirm", "HostAction", "HostAccessRow", "PermissionRow", "HostSetupChoice", "HostPanelView", "HostFormState", "HostFormAction", "HostFormChoice", "HostFormField", "HostFormView"]),
("installer.rs", "installer", ["InstallMethod", "CliInstallPlan", "CliInstallRequest"]),
diff --git a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
index 7616b4e42b..11479cde76 100644
--- a/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
+++ b/libs/spaces-app-swift/Sources/CuaSpacesFFI/CuaSpacesFFI.swift
@@ -33490,6 +33490,336 @@ public func FfiConverterTypeAppSidebarView_lower(_ value: AppSidebarView) -> Rus
}
+public struct AppSignInFooter: Equatable, Hashable {
+ /**
+ * Which state.
+ */
+ public var state: AppSignInFooterState
+ /**
+ * The line: "Signed in as …", "Waiting for your browser…", "Sign-in
+ * didn't finish. …", "Not signed in".
+ */
+ public var text: String
+ /**
+ * The signed-in account (state `SignedIn`).
+ */
+ public var identity: String?
+ /**
+ * Waiting: the code to confirm in the browser.
+ */
+ public var code: String?
+ /**
+ * "Code".
+ */
+ public var codeLabel: String
+ /**
+ * Waiting with a page: "Open again".
+ */
+ public var reopenLabel: String?
+ /**
+ * Starting or waiting: "Cancel".
+ */
+ public var cancelLabel: String?
+ /**
+ * "Sign in" or "Try again" (none while signed in or waiting).
+ */
+ public var actionLabel: String?
+ /**
+ * Failed: why.
+ */
+ public var reason: AppSignInFailure?
+ /**
+ * Failed: the error's own words, behind "Details".
+ */
+ public var detail: String?
+ /**
+ * "Details".
+ */
+ public var detailsLabel: String
+ /**
+ * Failed: the toast the shell shows once, when it fails.
+ */
+ public var toast: AppSignInToast?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * Which state.
+ */state: AppSignInFooterState,
+ /**
+ * The line: "Signed in as …", "Waiting for your browser…", "Sign-in
+ * didn't finish. …", "Not signed in".
+ */text: String,
+ /**
+ * The signed-in account (state `SignedIn`).
+ */identity: String?,
+ /**
+ * Waiting: the code to confirm in the browser.
+ */code: String?,
+ /**
+ * "Code".
+ */codeLabel: String,
+ /**
+ * Waiting with a page: "Open again".
+ */reopenLabel: String?,
+ /**
+ * Starting or waiting: "Cancel".
+ */cancelLabel: String?,
+ /**
+ * "Sign in" or "Try again" (none while signed in or waiting).
+ */actionLabel: String?,
+ /**
+ * Failed: why.
+ */reason: AppSignInFailure?,
+ /**
+ * Failed: the error's own words, behind "Details".
+ */detail: String?,
+ /**
+ * "Details".
+ */detailsLabel: String,
+ /**
+ * Failed: the toast the shell shows once, when it fails.
+ */toast: AppSignInToast?) {
+ self.state = state
+ self.text = text
+ self.identity = identity
+ self.code = code
+ self.codeLabel = codeLabel
+ self.reopenLabel = reopenLabel
+ self.cancelLabel = cancelLabel
+ self.actionLabel = actionLabel
+ self.reason = reason
+ self.detail = detail
+ self.detailsLabel = detailsLabel
+ self.toast = toast
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppSignInFooter: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppSignInFooter: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppSignInFooter {
+ return
+ try AppSignInFooter(
+ state: FfiConverterTypeAppSignInFooterState.read(from: &buf),
+ text: FfiConverterString.read(from: &buf),
+ identity: FfiConverterOptionString.read(from: &buf),
+ code: FfiConverterOptionString.read(from: &buf),
+ codeLabel: FfiConverterString.read(from: &buf),
+ reopenLabel: FfiConverterOptionString.read(from: &buf),
+ cancelLabel: FfiConverterOptionString.read(from: &buf),
+ actionLabel: FfiConverterOptionString.read(from: &buf),
+ reason: FfiConverterOptionTypeAppSignInFailure.read(from: &buf),
+ detail: FfiConverterOptionString.read(from: &buf),
+ detailsLabel: FfiConverterString.read(from: &buf),
+ toast: FfiConverterOptionTypeAppSignInToast.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppSignInFooter, into buf: inout [UInt8]) {
+ FfiConverterTypeAppSignInFooterState.write(value.state, into: &buf)
+ FfiConverterString.write(value.text, into: &buf)
+ FfiConverterOptionString.write(value.identity, into: &buf)
+ FfiConverterOptionString.write(value.code, into: &buf)
+ FfiConverterString.write(value.codeLabel, into: &buf)
+ FfiConverterOptionString.write(value.reopenLabel, into: &buf)
+ FfiConverterOptionString.write(value.cancelLabel, into: &buf)
+ FfiConverterOptionString.write(value.actionLabel, into: &buf)
+ FfiConverterOptionTypeAppSignInFailure.write(value.reason, into: &buf)
+ FfiConverterOptionString.write(value.detail, into: &buf)
+ FfiConverterString.write(value.detailsLabel, into: &buf)
+ FfiConverterOptionTypeAppSignInToast.write(value.toast, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppSignInFooter_lift(_ buf: RustBuffer) throws -> AppSignInFooter {
+ return try FfiConverterTypeAppSignInFooter.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppSignInFooter_lower(_ value: AppSignInFooter) -> RustBuffer {
+ return FfiConverterTypeAppSignInFooter.lower(value)
+}
+
+
+public struct AppSignInFooterInput: Equatable, Hashable {
+ /**
+ * The signed-in account.
+ */
+ public var identity: String?
+ /**
+ * Cua Cloud works through client credentials (an API key).
+ */
+ public var cloudConfigured: Bool
+ /**
+ * Signing in is possible here.
+ */
+ public var canSignIn: Bool
+ /**
+ * The sign-in in progress.
+ */
+ public var signIn: AppSignInPhase
+ /**
+ * The page the sign-in finishes on is known (Open again).
+ */
+ public var hasUrl: Bool
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * The signed-in account.
+ */identity: String?,
+ /**
+ * Cua Cloud works through client credentials (an API key).
+ */cloudConfigured: Bool,
+ /**
+ * Signing in is possible here.
+ */canSignIn: Bool,
+ /**
+ * The sign-in in progress.
+ */signIn: AppSignInPhase,
+ /**
+ * The page the sign-in finishes on is known (Open again).
+ */hasUrl: Bool) {
+ self.identity = identity
+ self.cloudConfigured = cloudConfigured
+ self.canSignIn = canSignIn
+ self.signIn = signIn
+ self.hasUrl = hasUrl
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppSignInFooterInput: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppSignInFooterInput: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppSignInFooterInput {
+ return
+ try AppSignInFooterInput(
+ identity: FfiConverterOptionString.read(from: &buf),
+ cloudConfigured: FfiConverterBool.read(from: &buf),
+ canSignIn: FfiConverterBool.read(from: &buf),
+ signIn: FfiConverterTypeAppSignInPhase.read(from: &buf),
+ hasUrl: FfiConverterBool.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppSignInFooterInput, into buf: inout [UInt8]) {
+ FfiConverterOptionString.write(value.identity, into: &buf)
+ FfiConverterBool.write(value.cloudConfigured, into: &buf)
+ FfiConverterBool.write(value.canSignIn, into: &buf)
+ FfiConverterTypeAppSignInPhase.write(value.signIn, into: &buf)
+ FfiConverterBool.write(value.hasUrl, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppSignInFooterInput_lift(_ buf: RustBuffer) throws -> AppSignInFooterInput {
+ return try FfiConverterTypeAppSignInFooterInput.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppSignInFooterInput_lower(_ value: AppSignInFooterInput) -> RustBuffer {
+ return FfiConverterTypeAppSignInFooterInput.lower(value)
+}
+
+
+public struct AppSignInToast: Equatable, Hashable {
+ /**
+ * "Sign-in didn't finish".
+ */
+ public var title: String
+ /**
+ * The reason (none for an unknown one).
+ */
+ public var body: String?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(
+ /**
+ * "Sign-in didn't finish".
+ */title: String,
+ /**
+ * The reason (none for an unknown one).
+ */body: String?) {
+ self.title = title
+ self.body = body
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppSignInToast: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppSignInToast: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppSignInToast {
+ return
+ try AppSignInToast(
+ title: FfiConverterString.read(from: &buf),
+ body: FfiConverterOptionString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: AppSignInToast, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.title, into: &buf)
+ FfiConverterOptionString.write(value.body, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppSignInToast_lift(_ buf: RustBuffer) throws -> AppSignInToast {
+ return try FfiConverterTypeAppSignInToast.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppSignInToast_lower(_ value: AppSignInToast) -> RustBuffer {
+ return FfiConverterTypeAppSignInToast.lower(value)
+}
+
+
public struct AppSpace: Equatable, Hashable {
/**
* Sandbox ref (`cloud:<name>`, `local:<name>`, `direct:<host:port>`, ...).
@@ -55874,6 +56204,234 @@ public func FfiConverterTypeAppShareSheetAction_lower(_ value: AppShareSheetActi
}
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum AppSignInFailure: Equatable, Hashable {
+
+ /**
+ * The browser never confirmed: the wait ran out, or the code expired
+ * before it was confirmed.
+ */
+ case notConfirmed
+ /**
+ * The person declined it in the browser.
+ */
+ case declined
+ /**
+ * The sign-in service refused the code (expired or already used).
+ */
+ case codeRejected
+ /**
+ * This computer could not reach the sign-in service.
+ */
+ case offline
+ /**
+ * The sign-in service answered with its own error.
+ */
+ case serviceUnavailable
+ /**
+ * Signed in, but the session could not be stored on this computer (a
+ * locked keychain, a credential store that refused the write).
+ */
+ case couldNotSave
+ /**
+ * Anything else (the words are behind Details).
+ */
+ case unknown
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppSignInFailure: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppSignInFailure: FfiConverterRustBuffer {
+ typealias SwiftType = AppSignInFailure
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppSignInFailure {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .notConfirmed
+
+ case 2: return .declined
+
+ case 3: return .codeRejected
+
+ case 4: return .offline
+
+ case 5: return .serviceUnavailable
+
+ case 6: return .couldNotSave
+
+ case 7: return .unknown
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: AppSignInFailure, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .notConfirmed:
+ writeInt(&buf, Int32(1))
+
+
+ case .declined:
+ writeInt(&buf, Int32(2))
+
+
+ case .codeRejected:
+ writeInt(&buf, Int32(3))
+
+
+ case .offline:
+ writeInt(&buf, Int32(4))
+
+
+ case .serviceUnavailable:
+ writeInt(&buf, Int32(5))
+
+
+ case .couldNotSave:
+ writeInt(&buf, Int32(6))
+
+
+ case .unknown:
+ writeInt(&buf, Int32(7))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppSignInFailure_lift(_ buf: RustBuffer) throws -> AppSignInFailure {
+ return try FfiConverterTypeAppSignInFailure.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppSignInFailure_lower(_ value: AppSignInFailure) -> RustBuffer {
+ return FfiConverterTypeAppSignInFailure.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum AppSignInFooterState: Equatable, Hashable {
+
+ /**
+ * Not signed in: "Sign in".
+ */
+ case signedOut
+ /**
+ * Asking for a code / opening the browser.
+ */
+ case starting
+ /**
+ * The browser is open.
+ */
+ case waiting
+ /**
+ * It failed: the reason and Try again.
+ */
+ case failed
+ /**
+ * Signed in.
+ */
+ case signedIn
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension AppSignInFooterState: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeAppSignInFooterState: FfiConverterRustBuffer {
+ typealias SwiftType = AppSignInFooterState
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> AppSignInFooterState {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .signedOut
+
+ case 2: return .starting
+
+ case 3: return .waiting
+
+ case 4: return .failed
+
+ case 5: return .signedIn
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: AppSignInFooterState, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .signedOut:
+ writeInt(&buf, Int32(1))
+
+
+ case .starting:
+ writeInt(&buf, Int32(2))
+
+
+ case .waiting:
+ writeInt(&buf, Int32(3))
+
+
+ case .failed:
+ writeInt(&buf, Int32(4))
+
+
+ case .signedIn:
+ writeInt(&buf, Int32(5))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppSignInFooterState_lift(_ buf: RustBuffer) throws -> AppSignInFooterState {
+ return try FfiConverterTypeAppSignInFooterState.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeAppSignInFooterState_lower(_ value: AppSignInFooterState) -> RustBuffer {
+ return FfiConverterTypeAppSignInFooterState.lower(value)
+}
+
+
// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
@@ -55893,15 +56451,25 @@ public enum AppSignInPhase: Equatable, Hashable {
case waiting(
/**
* The code to confirm there, when the flow has one.
- */userCode: String?
+ */userCode: String?,
+ /**
+ * A browser opened on this computer (false: the page is to be
+ * opened by hand, here or on another device).
+ */opened: Bool
)
/**
- * It failed.
+ * It failed ([`crate::sign_in::failed`] makes it).
*/
case failed(
/**
- * Why.
- */message: String
+ * Why ([`crate::sign_in::SignInFailure`]).
+ */reason: AppSignInFailure,
+ /**
+ * The line shown: "Sign-in didn't finish." and the reason.
+ */message: String,
+ /**
+ * The error's own words, behind Details (never shown by default).
+ */detail: String?
)
@@ -55928,10 +56496,10 @@ public struct FfiConverterTypeAppSignInPhase: FfiConverterRustBuffer {
case 2: return .starting
- case 3: return .waiting(userCode: try FfiConverterOptionString.read(from: &buf)
+ case 3: return .waiting(userCode: try FfiConverterOptionString.read(from: &buf), opened: try FfiConverterBool.read(from: &buf)
)
- case 4: return .failed(message: try FfiConverterString.read(from: &buf)
+ case 4: return .failed(reason: try FfiConverterTypeAppSignInFailure.read(from: &buf), message: try FfiConverterString.read(from: &buf), detail: try FfiConverterOptionString.read(from: &buf)
)
default: throw UniffiInternalError.unexpectedEnumCase
@@ -55950,14 +56518,17 @@ public struct FfiConverterTypeAppSignInPhase: FfiConverterRustBuffer {
writeInt(&buf, Int32(2))
- case let .waiting(userCode):
+ case let .waiting(userCode,opened):
writeInt(&buf, Int32(3))
FfiConverterOptionString.write(userCode, into: &buf)
+ FfiConverterBool.write(opened, into: &buf)
- case let .failed(message):
+ case let .failed(reason,message,detail):
writeInt(&buf, Int32(4))
+ FfiConverterTypeAppSignInFailure.write(reason, into: &buf)
FfiConverterString.write(message, into: &buf)
+ FfiConverterOptionString.write(detail, into: &buf)
}
}
@@ -63622,6 +64193,30 @@ fileprivate struct FfiConverterOptionTypeAppSidebarRow: FfiConverterRustBuffer {
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeAppSignInToast: FfiConverterRustBuffer {
+ typealias SwiftType = AppSignInToast?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeAppSignInToast.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeAppSignInToast.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -64510,6 +65105,30 @@ fileprivate struct FfiConverterOptionTypeAppShareRequest: FfiConverterRustBuffer
}
}
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeAppSignInFailure: FfiConverterRustBuffer {
+ typealias SwiftType = AppSignInFailure?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeAppSignInFailure.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeAppSignInFailure.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
#if swift(>=5.8)
@_documentation(visibility: private)
#endif
@@ -71672,6 +72291,39 @@ public func appSidebar(spaces: [AppSpace], query: String, selectedId: String) ->
)
})
}
+/**
+ * The failed phase for a known reason, with the error's words for Details.
+ */
+public func appSignInFailed(reason: AppSignInFailure, detail: String?) -> AppSignInPhase {
+ return try! FfiConverterTypeAppSignInPhase_lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_app_sign_in_failed(
+ FfiConverterTypeAppSignInFailure_lower(reason),
+ FfiConverterOptionString.lower(detail),$0
+ )
+})
+}
+/**
+ * The failed phase for an error the shell caught: the SDK error's case
+ * (`Timeout`, `Http`, ...; empty for another error) and its words.
+ */
+public func appSignInFailedFromError(variant: String, message: String) -> AppSignInPhase {
+ return try! FfiConverterTypeAppSignInPhase_lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_app_sign_in_failed_from_error(
+ FfiConverterString.lower(variant),
+ FfiConverterString.lower(message),$0
+ )
+})
+}
+/**
+ * The sidebar's foot: every sign-in state in one place.
+ */
+public func appSignInFooter(input: AppSignInFooterInput) -> AppSignInFooter {
+ return try! FfiConverterTypeAppSignInFooter_lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_app_sign_in_footer(
+ FfiConverterTypeAppSignInFooterInput_lower(input),$0
+ )
+})
+}
/**
* Whether a Space takes a teleport drop (the notch tiles' and the Space
* rows' rule).
@@ -72090,6 +72742,16 @@ public func appTelemetrySignInFailed(message: String?) -> [AppTelemetrySignal]
)
})
}
+/**
+ * A sign-in failed for `reason` or was cancelled (none): its kind only.
+ */
+public func appTelemetrySignInFailure(reason: AppSignInFailure?) -> [AppTelemetrySignal] {
+ return try! FfiConverterSequenceTypeAppTelemetrySignal.lift(try! rustCall() {
+ uniffi_cua_spaces_ffi_fn_func_app_telemetry_sign_in_failure(
+ FfiConverterOptionTypeAppSignInFailure.lower(reason),$0
+ )
+})
+}
/**
* The app started: attributes this process's events to `spaces_app` at
* `version`, links usage data to the signed-in account in the background
@@ -73426,6 +74088,15 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_spaces_ffi_checksum_func_app_sidebar() != 2197) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_spaces_ffi_checksum_func_app_sign_in_failed() != 6165) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_spaces_ffi_checksum_func_app_sign_in_failed_from_error() != 6411) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_cua_spaces_ffi_checksum_func_app_sign_in_footer() != 8779) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_spaces_ffi_checksum_func_app_space_accepts_drop() != 51121) {
return InitializationResult.apiChecksumMismatch
}
@@ -73537,6 +74208,9 @@ private let initializationResult: InitializationResult = {
if (uniffi_cua_spaces_ffi_checksum_func_app_telemetry_sign_in_failed() != 34262) {
return InitializationResult.apiChecksumMismatch
}
+ if (uniffi_cua_spaces_ffi_checksum_func_app_telemetry_sign_in_failure() != 23014) {
+ return InitializationResult.apiChecksumMismatch
+ }
if (uniffi_cua_spaces_ffi_checksum_func_app_telemetry_start() != 30125) {
return InitializationResult.apiChecksumMismatch
}
diff --git a/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h b/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
index 07bf0ad5c2..4deaf8b329 100644
--- a/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
+++ b/libs/spaces-app-swift/Sources/cua_spaces_ffiFFI/include/cua_spaces_ffiFFI.h
@@ -1738,6 +1738,21 @@ RustBuffer uniffi_cua_spaces_ffi_fn_func_app_share_view(RustBuffer input, RustBu
RustBuffer uniffi_cua_spaces_ffi_fn_func_app_sidebar(RustBuffer spaces, RustBuffer query, RustBuffer selected_id, RustCallStatus *_Nonnull out_status
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SIGN_IN_FAILED
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SIGN_IN_FAILED
+RustBuffer uniffi_cua_spaces_ffi_fn_func_app_sign_in_failed(RustBuffer reason, RustBuffer detail, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SIGN_IN_FAILED_FROM_ERROR
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SIGN_IN_FAILED_FROM_ERROR
+RustBuffer uniffi_cua_spaces_ffi_fn_func_app_sign_in_failed_from_error(RustBuffer variant, RustBuffer message, RustCallStatus *_Nonnull out_status
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SIGN_IN_FOOTER
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SIGN_IN_FOOTER
+RustBuffer uniffi_cua_spaces_ffi_fn_func_app_sign_in_footer(RustBuffer input, RustCallStatus *_Nonnull out_status
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SPACE_ACCEPTS_DROP
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_SPACE_ACCEPTS_DROP
int8_t uniffi_cua_spaces_ffi_fn_func_app_space_accepts_drop(RustBuffer space, RustCallStatus *_Nonnull out_status
@@ -1926,6 +1941,11 @@ RustBuffer uniffi_cua_spaces_ffi_fn_func_app_telemetry_share(RustBuffer input, R
RustBuffer uniffi_cua_spaces_ffi_fn_func_app_telemetry_sign_in_failed(RustBuffer message, RustCallStatus *_Nonnull out_status
);
#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_TELEMETRY_SIGN_IN_FAILURE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_TELEMETRY_SIGN_IN_FAILURE
+RustBuffer uniffi_cua_spaces_ffi_fn_func_app_telemetry_sign_in_failure(RustBuffer reason, RustCallStatus *_Nonnull out_status
+);
+#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_TELEMETRY_START
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_FN_FUNC_APP_TELEMETRY_START
int8_t uniffi_cua_spaces_ffi_fn_func_app_telemetry_start(RustBuffer version, RustBuffer onboarding_eligible, RustCallStatus *_Nonnull out_status
@@ -3760,6 +3780,24 @@ uint16_t uniffi_cua_spaces_ffi_checksum_func_app_share_view(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SIDEBAR
uint16_t uniffi_cua_spaces_ffi_checksum_func_app_sidebar(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SIGN_IN_FAILED
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SIGN_IN_FAILED
+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_sign_in_failed(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SIGN_IN_FAILED_FROM_ERROR
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SIGN_IN_FAILED_FROM_ERROR
+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_sign_in_failed_from_error(void
+
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SIGN_IN_FOOTER
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SIGN_IN_FOOTER
+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_sign_in_footer(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_SPACE_ACCEPTS_DROP
@@ -3982,6 +4020,12 @@ uint16_t uniffi_cua_spaces_ffi_checksum_func_app_telemetry_share(void
#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_TELEMETRY_SIGN_IN_FAILED
uint16_t uniffi_cua_spaces_ffi_checksum_func_app_telemetry_sign_in_failed(void
+);
+#endif
+#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_TELEMETRY_SIGN_IN_FAILURE
+#define UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_TELEMETRY_SIGN_IN_FAILURE
+uint16_t uniffi_cua_spaces_ffi_checksum_func_app_telemetry_sign_in_failure(void
+
);
#endif
#ifndef UNIFFI_FFIDEF_UNIFFI_CUA_SPACES_FFI_CHECKSUM_FUNC_APP_TELEMETRY_START