Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud sign-in: a saved sign-in that can't be used never locks the person out; pairing never loops (#6658)
Milind Soni3c7cb489802d
diff --git a/electron/bridge-contract.json b/electron/bridge-contract.jsonindex a011af7861..639cd1f3b9 100644--- a/electron/bridge-contract.json+++ b/electron/bridge-contract.json@@ -39,6 +39,7 @@"cloudAccount.refresh","cloudAccount.reopen","cloudAccount.reopenCheckout",+ "cloudAccount.resetSaved","cloudAccount.setLook","cloudAccount.sheet","cloudAccount.signInAgain",diff --git a/electron/cloud-account-clouds.node-test.mjs b/electron/cloud-account-clouds.node-test.mjsindex 7d6a395df4..a58388b484 100644--- a/electron/cloud-account-clouds.node-test.mjs+++ b/electron/cloud-account-clouds.node-test.mjs@@ -315,7 +315,8 @@ test("the Admin's word on a Cloud this computer moved to: only a word it knows,test("starting a sign-in over a good one is refused, and goes once that one has ended: what the home screen's Sign in does for another account", async t => {const f = await admin(t);await f.client.start();- await assert.rejects(f.client.begin(), /Sign out before/);+ assert.equal((await f.client.begin()).status, "connected", "refused: the good sign-in stays");+ assert.equal(f.requests.some(row => row.route === "/api/cloud/desktop/authorize"), false);await f.client.signOut();await f.client.begin();assert.equal(f.requests.some(row => row.route === "/api/cloud/desktop/authorize"), true);diff --git a/electron/cloud-account.d.mts b/electron/cloud-account.d.mtsindex c967a6e149..9ae915058e 100644--- a/electron/cloud-account.d.mts+++ b/electron/cloud-account.d.mts@@ -59,6 +59,11 @@ export interface CloudAccountState {checkout?: { plan: string; startedAt: number; signIn?: true; link?: true; done?: true };/** This app talks to the staging Admin (OMB_CLOUD_STAGING=1): test payments, test Clouds. */staging?: true;+ /** Unavailable: the saved sign-in can't be read (`restore-failed`, offered after a few tries) or removed+ * (`signout-storage-failed`); `resetSaved()` clears it so the person can sign in again. */+ reset?: true;+ /** Signed in for this run only: the sign-in couldn't be saved on this computer after the person cleared the old one. */+ unsaved?: true;/** Connected: opening My Cloud waits for it to wake. */waking?: true;/** Connected: the plan's renewal, only while this account pays for a plan that runs: what Cancel and Keep act on (display only). */@@ -81,13 +86,15 @@ export type CloudRenewalResult =* in only in the browser (single sign-on there, or an older Admin). */export type CloudSignInStart =| { outcome: "sent"; email: string; expiresAt: number; resendAt: number; /** False: new accounts are closed, so only an existing one gets a code. */ signupOpen: boolean }- | { outcome: import("./cloud-signin.mjs").CloudSignInStartFailure };+ | { outcome: import("./cloud-signin.mjs").CloudSignInStartFailure }+ | import("./cloud-signin.mjs").CloudSignInBlocked;/** `signed-in`: stored and read like the browser sign-in; `wrong-code` says* the tries left; `expired` needs a new code. */export type CloudSignInVerify =| { outcome: "signed-in"; state: CloudAccountState }| { outcome: "wrong-code"; triesLeft: number }- | { outcome: Exclude<import("./cloud-signin.mjs").CloudSignInVerifyFailure, "wrong-code"> };+ | { outcome: Exclude<import("./cloud-signin.mjs").CloudSignInVerifyFailure, "wrong-code"> }+ | import("./cloud-signin.mjs").CloudSignInBlocked;/** How the Cloud is shown in this app's switcher and Settings → Servers. */export interface CloudHomeLook { name: string; color: import("./cloud-buy.mjs").CloudColor }/** Why the Admin opens no other Cloud's checkout now (contract v1 `addBlocked`). */@@ -147,6 +154,8 @@ export interface CloudAccountBridge {signInStart?(email: string): Promise<CloudSignInStart>;signInVerify?(code: string): Promise<CloudSignInVerify>;signInCancel?(): Promise<void>;+ /** Clears a saved sign-in this computer can't read or remove (state `reset`), so a new one can start. Absent on an older app. */+ resetSaved?(): Promise<CloudAccountState>;/** The checkout this app opened, again (never a new one while main keeps it); the plan and source only when none is kept. */reopenCheckout?(plan: string, source: string): Promise<CloudCheckoutResult>;/** Copies that checkout's page to the clipboard in main; false when none is kept. */@@ -185,7 +194,8 @@ export interface RailOpenResult { outcome: "switched" | "moving" | "sign-in" | "export type AccountAddResult =| { outcome: "switched" | "added" | "already"; email?: string; view: AccountsView }| { outcome: "wrong-code"; triesLeft: number }- | { outcome: Exclude<import("./cloud-signin.mjs").CloudSignInVerifyFailure, "wrong-code"> };+ | { outcome: Exclude<import("./cloud-signin.mjs").CloudSignInVerifyFailure, "wrong-code"> }+ | import("./cloud-signin.mjs").CloudSignInBlocked;/** This app's own pages only: main refuses any other page. Absent on an older app. */export interface AccountsBridge {list(): Promise<AccountsView>;@@ -289,6 +299,7 @@ export interface CloudAccountClient {emailStart(email: string): Promise<CloudSignInStart>;emailVerify(code: string): Promise<CloudSignInVerify>;emailCancel(): void;+ resetSaved(): Promise<CloudAccountState>;reopenCheckout(plan?: string, source?: string): Promise<CloudCheckoutResult>;/** Main only (the clipboard): the kept checkout page, or null. */checkoutLink(): string | null;diff --git a/electron/cloud-account.mjs b/electron/cloud-account.mjsindex cdb70be9ca..63e048819d 100644--- a/electron/cloud-account.mjs+++ b/electron/cloud-account.mjs@@ -2,7 +2,7 @@ import { createManagedDesktopStore, retryDelay, unreadableRecord } from "./managimport { CLOUD_MACHINE_CONNECTABLE, cloudUnreachableText, parseCloudCredit, parseCloudLanding, parseCloudOffer, parseCloudPurchase, parseCloudSummary, parseCloudTeams, parseCloudRoom, parseCloudTrial, parseCloudUsage, parsePairingGrant, parsePublicOffer, withoutTrial } from "./cloud-home.mjs";import { CLOUD_ID, CLOUD_SWATCHES, cleanCloudListName, ORGANIZATION_BLOCKS, otherOwnClouds, ownCloud, parseCloudList, parseCloudRenewal, parseOrganizations, releaseVersion } from "./cloud-list.mjs";import { planTeam, teamPlan } from "./cloud-team-plan.mjs";-import { cleanCode, cleanEmail, parseSignInStart, SIGN_IN_START, SIGN_IN_TRIES, SIGN_IN_VERIFY, signInIdentity, startFailure, verifyFailure } from "./cloud-signin.mjs";+import { cleanCode, cleanEmail, failureKind, parseSignInStart, resetOffered, retryAfterSeconds, SIGN_IN_START, SIGN_IN_TRIES, SIGN_IN_VERIFY, signInBlock, signInIdentity, startFailure, verifyFailure } from "./cloud-signin.mjs";import nativeText from "./native-text.cjs";const { englishText } = nativeText;@@ -102,6 +102,10 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNorigin = cloudOrigin(origin, fixture);const staging = origin === STAGING_CLOUD_ORIGIN;let grant = null, issued = null, cleanup = null, pending = null, cleanupNeeded = false;+ /** `resetUsed`: the person cleared a saved sign-in this computer couldn't use (resetSaved); from then on this run, a new sign-in+ * that can't be saved is kept in memory only (`unsaved`). `stuckSince`: the first failed read of the saved one. */+ let resetUsed = false, unsaved = false, stuckSince = null, reading = null;+ const save = record => (unsaved ? Promise.resolve() : store.write(record));let value = { status: "signed-out", message: "restoring" }, generation = 0, timer = null, closed = false, clearing = null, refreshing = null;let verifiedUntil = 0, restoring = false, controller = new AbortController(), failures = 0;let plan = null, savedHint = null;@@ -126,7 +130,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN? { cloudId: adding.cloudId, name: adding.name, color: adding.color, tier: adding.tier, startedAt: adding.startedAt, ...(adding.url ? { link: true } : {}), ...(adding.done ? { done: true } : {}) } : null;const withCheckout = current => {const open = checkout(), add = buying(), shown = waking && current.status === "connected" ? { ...current, waking: true } : current;- const next = { ...shown, ...(open ? { checkout: open } : {}), ...(add ? { adding: add } : {}) };+ const next = { ...shown, ...(open ? { checkout: open } : {}), ...(add ? { adding: add } : {}), ...(unsaved && grant ? { unsaved: true } : {}) };return staging ? { ...next, staging: true } : next;};const state = () => {@@ -167,12 +171,12 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN}} catch (error) { await reader?.cancel().catch(() => {}); throw error; }finally { reader?.releaseLock(); }- let data;+ let data; const wait = response.ok ? undefined : retryAfterSeconds(response.headers, now()), retryAfter = wait === undefined ? {} : { retryAfter: wait };try { data = JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch {- if (!response.ok) throw Object.assign(new Error("Cloud request failed."), { status: response.status, opaque: true });+ if (!response.ok) throw Object.assign(new Error("Cloud request failed."), { status: response.status, opaque: true, ...retryAfter });throw new Error("Invalid Cloud response.");}- if (!response.ok) throw Object.assign(new Error("Cloud request failed."), { status: response.status, code: data?.error, interval: data?.interval, blocked: data?.addBlocked,+ if (!response.ok) throw Object.assign(new Error("Cloud request failed."), { status: response.status, code: data?.error, interval: data?.interval, blocked: data?.addBlocked, ...retryAfter,...(typeof data?.checkoutUrl === "string" ? { checkoutUrl: data.checkoutUrl } : {}) });return data;}@@ -238,12 +242,14 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNif (clearing) return clearing;const previous = grant ?? issued ?? cleanup, stamp = reset();grant = null; issued = null; cleanup = previous; cleanupNeeded = true; plan = null; savedHint = null; opened = null; adding = null; renewalCloud = null;+ // A sign-in kept in memory only has nothing of its own on disk: one that can't be removed there doesn't block the next.+ const memoryOnly = unsaved; unsaved = false;if (!quiet) publish({ status: "signed-out" });const operation = (async () => {- const [persisted, revoked] = await Promise.allSettled([Promise.resolve().then(() => store.write(null)), previous ? revoke(previous) : Promise.resolve()]);+ const [persisted, revoked] = await Promise.allSettled([Promise.resolve().then(() => store.write(null)).catch(error => { if (!memoryOnly) throw error; }), previous ? revoke(previous) : Promise.resolve()]);if (persisted.status === "fulfilled") { cleanup = null; cleanupNeeded = false; }if (!current(stamp)) return state();- if (persisted.status === "rejected") return publish({ status: "unavailable", message: "signout-storage-failed" });+ if (persisted.status === "rejected") return publish({ status: "unavailable", message: "signout-storage-failed", reset: true });if (quiet) return state();return publish({ status: "signed-out", ...(revoked.status === "rejected" ? { message: "signout-local-only" } : {}) });})().finally(() => { if (clearing === operation) clearing = null; });@@ -271,11 +277,11 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNconst hint = access.plan === "pro" ? { ...(access.tier ? { tier: access.tier } : {}), active: access.status === "active" } : null;if (next.expiresAt !== previous.expiresAt) {const replacement = { ...previous, expiresAt: next.expiresAt };- await store.write(record(replacement, hint));+ await save(record(replacement, hint));if (!current(stamp) || grant !== previous) return state();grant = replacement; savedHint = hint;} else if (!sameHint(savedHint, hint)) {- try { await store.write(record(previous, hint)); savedHint = hint; } catch {}+ try { await save(record(previous, hint)); savedHint = hint; } catch {}if (!current(stamp) || grant !== previous) return state();}plan = hint ? { accountId: grant.account.id, ...hint } : null;@@ -327,7 +333,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNif (!current(stamp) || !wanted()) { await revoke(next).catch(() => {}); return false; }if (next.expiresAt <= now()) throw new Error("Expired Cloud credential.");issued = next;- await store.write(next);+ try { await store.write(next); } catch (error) { if (!resetUsed) throw error; if (current(stamp)) unsaved = true; }if (!current(stamp)) return false;grant = next; issued = null; pending = null; emailed = null; savedHint = null;if (plan?.accountId !== next.account.id) plan = null;@@ -358,7 +364,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN}}async function begin(intent = null) {- if (closed || restoring || clearing || grant || issued || cleanupNeeded) throw new Error("Sign out before starting another Cloud connection.");+ if (closed || restoring || clearing || grant || issued || cleanupNeeded) return state();const stamp = reset();opened = intent ? { plan: intent.plan, source: intent.source, startedAt: now(), signIn: true } : null;publish({ status: "connecting" });@@ -374,13 +380,19 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNpublish({ status: "connecting", enrollment: { userCode: result.userCode, expiresAt: pending.expiresAt } });await openBrowser(pending.verificationUri);if (current(stamp)) schedule(poll, pending.interval);- } catch { if (current(stamp)) { pending = null; opened = null; publish({ status: "signed-out", message: "signin-failed" }); } }+ } catch (error) { if (current(stamp)) { warn(`[cloud] browser sign-in could not start: ${failureKind(error)}`); pending = null; opened = null; publish({ status: "signed-out", message: "signin-failed" }); } }return state();}- const signInBlocked = () => closed || restoring || clearing || grant || issued || cleanupNeeded;+ /** Why a sign-in can't start now (the sheet says so, with the one thing to do), after a sign-out or a read under way ends. */+ async function blocked(connecting = false) {+ if (clearing) await clearing.catch(() => {});+ if (restoring && reading) await reading.catch(() => {});+ const reason = signInBlock({ closed, restoring, issued, grant, cleanupNeeded, connecting: connecting && value.status === "connecting" });+ return reason && { outcome: "blocked", reason, ...(reason === "saved" && value.reset ? { reset: true } : {}) };+ }/** Sends the 8-digit code to `email`. Nothing is signed in yet; the answer says what the sheet shows next. */async function emailStart(email) {- if (signInBlocked() || value.status === "connecting") throw new Error("Sign out before starting another Cloud connection.");+ const stop = await blocked(true); if (stop) return stop;const address = cleanEmail(email), app = signInIdentity({ deviceName, platform, appVersion });if (!address) return { outcome: "invalid-email" };if (!app) return { outcome: "browser" };@@ -394,7 +406,9 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNemailed = { attempt: started.attempt, email: address, expiresAt: now() + started.expiresIn * 1000, wrong: 0 };return { outcome: "sent", email: address, expiresAt: emailed.expiresAt, resendAt: now() + started.resendAfter * 1000, signupOpen: started.signupOpen };} catch (error) {- return current(stamp) ? { outcome: startFailure(error) } : { outcome: "failed" };+ if (!current(stamp)) return { outcome: "failed" };+ const outcome = startFailure(error); if (outcome === "failed") warn(`[cloud] email sign-in could not start: ${failureKind(error)}`);+ return { outcome };}}/** Checks the code; on success the token is stored like the browser sign-in's and the session is read at once. */@@ -402,7 +416,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNconst attempt = emailed, digits = cleanCode(code);if (!attempt || now() >= attempt.expiresAt) { emailed = null; return { outcome: "expired" }; }if (!digits) return { outcome: "wrong-code", triesLeft: SIGN_IN_TRIES - attempt.wrong };- if (signInBlocked()) throw new Error("Sign out before starting another Cloud connection.");+ const stop = await blocked(); if (stop) return stop;const stamp = generation;try {const result = await request(null, { method: "POST", path: SIGN_IN_VERIFY, body: { attempt: attempt.attempt, code: digits } });@@ -463,10 +477,10 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNif (unreadable) {const removed = await store.write(null).then(() => true, () => false);if (!current(stamp)) return state();- if (removed) { cleanupNeeded = false; failures = 0; return publish({ status: "signed-out", message: "restore-removed" }); }+ if (removed) { cleanupNeeded = false; failures = 0; stuckSince = null; return publish({ status: "signed-out", message: "restore-removed" }); }}- failures++;- if (value.message !== "restore-failed") publish({ status: "unavailable", message: "restore-failed" });+ failures++; stuckSince ??= now(); const offer = resetOffered({ platform, failures, since: stuckSince, now: now() });+ if (value.message !== "restore-failed" || (offer && !value.reset)) publish({ status: "unavailable", message: "restore-failed", ...(offer ? { reset: true } : {}) });schedule(start, retryDelay(failures));return state();}@@ -474,12 +488,12 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNconst stamp = generation;restoring = true; verifiedUntil = 0;let saved, restored = null, failed = false, unreadable = false;- try { saved = await store.read(); } catch (error) { failed = true; unreadable = unreadableRecord(error); }+ try { saved = await (reading = store.read()); } catch (error) { failed = true; unreadable = unreadableRecord(error); }if (!failed) try { restored = saved ? validateGrant(saved) : null; } catch { failed = unreadable = true; }restoring = false;if (!current(stamp)) return state();if (failed) return restoreFailed(stamp, unreadable);- grant = restored; cleanupNeeded = false; failures = 0;+ grant = restored; cleanupNeeded = false; failures = 0; stuckSince = null;savedHint = grant ? planHint(saved.planHint) : null;plan = grant && savedHint ? { accountId: grant.account.id, ...savedHint } : null;if (!grant) return ["restoring", "restore-failed"].includes(value.message) ? publish({ status: "signed-out" }) : state();@@ -511,6 +525,16 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN},cancel: () => { if (!pending && value.status !== "connecting") return Promise.resolve(state()); opened = null; return signOut(); },refresh, signOut,+ /** Clear and sign in again: a saved sign-in this computer can't read or remove goes (never a working one), and isn't read again+ * this run. One that still can't be removed stays on disk; this run's next sign-in is kept in memory if it can't be saved. */+ async resetSaved() {+ if (closed || grant || issued || clearing || !cleanupNeeded || !value.reset) return state();+ const stamp = reset(), ended = cleanup; resetUsed = true;+ const [removed] = await Promise.all([store.write(null).then(() => true, () => false), ended ? revoke(ended).catch(() => {}) : null]);+ if (!current(stamp)) return state();+ cleanup = null; cleanupNeeded = false; stuckSince = null;+ return publish({ status: "signed-out", ...(removed ? {} : { message: "reset-kept" }) });+ },async openDashboard() { await openBrowser(`${origin}/cloud`); return state(); },async upgradePreview(plan, source) {if (!UPGRADE_TIERS.includes(plan) || !UPGRADE_SOURCES.includes(source)) throw new Error("Invalid Cloud upgrade.");@@ -935,7 +959,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN/** Reads the sign-in saved in `store` afresh: nothing of the one before stays. Told once, when the Admin has answered. */reload() {quiet = false;- reset();+ reset(); unsaved = false;grant = null; issued = null; cleanup = null; cleanupNeeded = false; plan = null; savedHint = null; opened = null; adding = null; renewalCloud = null; offerCache = null; waking = false;confirmations.clear();value = { status: "signed-out", message: "restoring" };diff --git a/electron/cloud-account.node-test.mjs b/electron/cloud-account.node-test.mjsindex b97e77fb8e..ff69a9ba0c 100644--- a/electron/cloud-account.node-test.mjs+++ b/electron/cloud-account.node-test.mjs@@ -521,14 +521,16 @@ test("sign-out durably forgets personal Cloud and revokes only its credential; otest("failed durable sign-out blocks reconnect until cleanup succeeds", async t => {const f = await fixture(t); await f.connect(); f.failWrite = true;assert.equal((await f.client.signOut()).message, "signout-storage-failed");- await assert.rejects(f.client.begin(), /Sign out/); assert.equal(f.client.state().entitlement, undefined);+ const asked = f.requests.length, blocked = await f.client.begin();+ assert.equal(blocked.status, "unavailable"); assert.equal(blocked.reset, true, "clearing it is offered");+ assert.equal(f.requests.length, asked, "no sign-in starts"); assert.equal(f.client.state().entitlement, undefined);f.failWrite = false; await f.client.signOut(); assert.equal(f.saved, null);});test("startup restoration cannot race a new sign-in, and failed token persistence revokes the issued credential", async t => {let resolveRead;const f = await fixture(t, { store: { read: () => new Promise(resolve => { resolveRead = resolve; }), write: async () => {} } });- const restoring = f.client.start(); await assert.rejects(f.client.begin(), /Sign out/);+ const restoring = f.client.start(); assert.equal((await f.client.begin()).message, "restoring");resolveRead(null); await restoring; assert.deepEqual(f.requests, []);const broken = await fixture(t); broken.failWrite = true; await broken.client.begin(); broken.approved = true; broken.tick();await until(() => broken.revoked); await until(() => broken.client.state().message === "signout-storage-failed");@@ -604,10 +606,15 @@ test("a locked keychain never removes the saved Cloud sign-in: it is read again,lock.locked = true;assert.deepEqual(await f.client.start(), { status: "unavailable", message: "restore-failed" });assert.equal(f.delay, 15_000);- await assert.rejects(f.client.begin(), /Sign out/);+ assert.deepEqual(await f.client.begin(), { status: "unavailable", message: "restore-failed" });+ assert.deepEqual(await f.client.emailStart("[email protected]"), { outcome: "blocked", reason: "saved" }, "no clearing offered yet");+ assert.deepEqual(await f.client.resetSaved(), { status: "unavailable", message: "restore-failed" }, "nothing is cleared before it is offered");for (const delay of [30_000, 60_000, 60_000]) { f.tick(); await until(() => f.timer); assert.equal(f.delay, delay); }assert.ok((await stat(file)).isFile(), "a locked sign-in is never removed");- assert.equal(f.states.filter(state => state.message === "restore-failed").length, 1, "said once, not on every try");+ assert.deepEqual(f.states.filter(state => state.message === "restore-failed").map(state => state.reset ?? false), [false, true],+ "said once, then once more when clearing it is offered (the third read), not on every try");+ assert.deepEqual(await f.client.emailStart("[email protected]"), { outcome: "blocked", reason: "saved", reset: true });+ assert.equal(f.requests.length, 0);lock.locked = false; f.tick();await until(() => f.client.state().status === "connected");assert.equal(f.client.state().account.email, "[email protected]");diff --git a/electron/cloud-signin.d.mts b/electron/cloud-signin.d.mtsindex 888f4a42ec..ee0434abaf 100644--- a/electron/cloud-signin.d.mts+++ b/electron/cloud-signin.d.mts@@ -9,3 +9,13 @@ export type CloudSignInStartFailure = "sso" | "rate-limited" | "browser" | "invaexport type CloudSignInVerifyFailure = "wrong-code" | "expired" | "sso" | "two-factor" | "signup-closed" | "device-limit" | "rate-limited" | "browser" | "failed";export declare function startFailure(error: unknown): CloudSignInStartFailure;export declare function verifyFailure(error: unknown): CloudSignInVerifyFailure;+/** Why a new sign-in can't start now: `busy` (a moment), `signed-in`, `saved` (a saved sign-in this computer can't read or+ * remove; `reset` once clearing it is offered) or `connecting` (one in the browser is under way). */+export type CloudSignInBlockReason = "busy" | "signed-in" | "saved" | "connecting";+export interface CloudSignInBlocked { outcome: "blocked"; reason: CloudSignInBlockReason; reset?: true }+export declare function signInBlock(input: { closed: boolean; restoring: boolean; issued: unknown; grant: unknown; cleanupNeeded: boolean; connecting?: boolean }): CloudSignInBlockReason | null;+export declare const RESET_AFTER_TRIES: number;+export declare const RESET_AFTER_MS: number;+export declare function resetOffered(input: { platform: string; failures: number; since: number; now: number }): boolean;+export declare function failureKind(error: unknown): string;+export declare function retryAfterSeconds(headers: { get(name: string): string | null } | null | undefined, now?: number): number | undefined;diff --git a/electron/cloud-signin.mjs b/electron/cloud-signin.mjsindex be9b40eda9..7b987a9ceb 100644--- a/electron/cloud-signin.mjs+++ b/electron/cloud-signin.mjs@@ -64,3 +64,33 @@ export function verifyFailure(error) {if (noEmailRoute(error)) return "browser";return "failed";}++/** Why a new sign-in can't start now, or null: `busy` (a saved sign-in is being read or saved: a moment), `signed-in`,+ * `saved` (a saved sign-in this computer can't read or remove, until it is cleared) or `connecting` (one in the browser). */+export function signInBlock({ closed, restoring, issued, grant, cleanupNeeded, connecting = false }) {+ if (closed || restoring || issued) return "busy";+ if (grant) return "signed-in";+ if (cleanupNeeded) return "saved";+ return connecting ? "connecting" : null;+}++/** A saved sign-in that can't be read is never removed by itself (a keychain may only be locked): clearing it is offered+ * after RESET_AFTER_TRIES reads or RESET_AFTER_MS, and at once on Windows, which has no keychain to unlock. */+export const RESET_AFTER_TRIES = 3, RESET_AFTER_MS = 2 * 60_000;+export const resetOffered = ({ platform, failures, since, now }) => platform === "win32" || failures >= RESET_AFTER_TRIES || now - since >= RESET_AFTER_MS;++/** A request to the Admin that failed, for the log: its status (and whether the answer was the Admin's own), or the network+ * error's code (a certificate, a name not found, a timeout). Never an address, an email or a token. */+export function failureKind(error) {+ if (Number.isSafeInteger(error?.status)) return `HTTP ${error.status}${error.opaque ? " (not the Admin's own answer)" : /^[a-z_]{1,40}$/.test(error.code ?? "") ? ` ${error.code}` : ""}`;+ const named = [error?.cause?.code, error?.code, error?.cause?.name, error?.name].find(value => typeof value === "string" && /^[A-Za-z_]{1,60}$/.test(value));+ return named ?? "error";+}++/** An answer's Retry-After in whole seconds (seconds or an HTTP date), or undefined. */+export function retryAfterSeconds(headers, now = Date.now()) {+ const value = headers?.get?.("retry-after")?.trim();+ if (!value) return undefined;+ const seconds = /^\d{1,7}$/.test(value) ? Number(value) : Math.ceil((Date.parse(value) - now) / 1000);+ return Number.isFinite(seconds) ? Math.max(0, seconds) : undefined;+}diff --git a/electron/cloud-signin.node-test.mjs b/electron/cloud-signin.node-test.mjsindex 97fb628b70..8f4c8d8f66 100644--- a/electron/cloud-signin.node-test.mjs+++ b/electron/cloud-signin.node-test.mjs@@ -2,7 +2,7 @@ import assert from "node:assert/strict";import test from "node:test";import { createServer } from "node:http";import { createCloudAccountClient } from "./cloud-account.mjs";-import { cleanCode, cleanEmail, parseSignInStart, SIGN_IN_TRIES, signInIdentity, startFailure, verifyFailure } from "./cloud-signin.mjs";+import { cleanCode, cleanEmail, failureKind, parseSignInStart, retryAfterSeconds, SIGN_IN_TRIES, signInIdentity, startFailure, verifyFailure } from "./cloud-signin.mjs";const accessToken = `omc_${"E".repeat(43)}`, ATTEMPT = "a".repeat(43), CODE = "48201937";const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));@@ -87,7 +87,7 @@ test("happy path: the code is sent, the right code signs this computer in with t}assert.deepEqual(f.browsers, [], "no browser at all");assert.equal((await f.client.emailVerify(CODE)).outcome, "expired", "an attempt is used once");- await assert.rejects(f.client.emailStart("[email protected]"), /Sign out before/, "signed in: no second sign-in");+ assert.deepEqual(await f.client.emailStart("[email protected]"), { outcome: "blocked", reason: "signed-in" }, "signed in: no second sign-in");});test("with new accounts closed the Admin still answers \"sent\" (only an existing address gets mail), and the page is told", async t => {@@ -198,3 +198,72 @@ test("a token that cannot be stored is revoked and nothing is signed in; cancellassert.deepEqual(await g.client.emailVerify(CODE), { outcome: "expired" });assert.equal(g.requests.filter(row => row.route.endsWith("/verify")).length, 0);});++/** A saved sign-in this computer can't use, as a store: `read` fails as it would (`unreadable`: the key no longer opens it, else+ * the system store is unavailable), and each write fails where `fails(value)` says (a file Windows won't let go, no encryption). */+function stuckStore({ unreadable, fails }) {+ const seen = { reads: 0, writes: [] };+ const error = message => Object.assign(new Error(message), unreadable ? { code: "unreadable_record" } : {});+ return { seen, store: {+ read: async () => { seen.reads++; throw error("Your company connection could not be read."); },+ write: async value => { seen.writes.push(value === null ? "remove" : "save"); if (fails(value)) throw Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" }); },+ } };+}+const later = { pending: null };+const timers = { setTimer: callback => { later.pending = callback; return 1; }, clearTimer: () => { later.pending = null; } };++test("Windows: a saved sign-in that can be neither read nor removed never locks the person out", async t => {+ const { seen, store } = stuckStore({ unreadable: true, fails: () => true });+ const f = await fixture(t, { store, platform: "win32", ...timers });+ // Windows has no keychain to unlock: clearing it is offered at once, and nothing is removed by itself.+ assert.deepEqual(f.client.state(), { status: "unavailable", message: "restore-failed", reset: true });+ assert.deepEqual(await f.client.emailStart("[email protected]"), { outcome: "blocked", reason: "saved", reset: true });+ assert.equal(f.requests.length, 0, "no code is asked for while it blocks");+ assert.ok(later.pending, "it is read again meanwhile");+ assert.deepEqual(await f.client.resetSaved(), { status: "signed-out", message: "reset-kept" });+ assert.equal(later.pending, null, "nothing reads it again this run");+ assert.equal((await f.client.emailStart("[email protected]")).outcome, "sent");+ const verified = await f.client.emailVerify(CODE);+ assert.equal(verified.outcome, "signed-in"); assert.equal(verified.state.status, "connected"); assert.equal(verified.state.unsaved, true);+ assert.ok(!f.requests.some(row => row.method === "DELETE"), "kept for this run, not revoked");+ assert.equal((await f.client.refresh()).status, "connected", "a sign-in kept in memory is never written again");+ assert.equal(seen.reads, 1);+ assert.deepEqual(await f.client.signOut(), { status: "signed-out" }, "signing out of it needs nothing on disk");+});++test("a system store that can't encrypt: the person clears the saved sign-in and signs in for this run", async t => {+ const { seen, store } = stuckStore({ unreadable: false, fails: value => value !== null });+ const f = await fixture(t, { store, platform: "win32", ...timers });+ assert.equal(f.client.state().reset, true);+ assert.deepEqual(await f.client.resetSaved(), { status: "signed-out" }, "removed");+ await f.client.emailStart("[email protected]");+ const verified = await f.client.emailVerify(CODE);+ assert.equal(verified.outcome, "signed-in"); assert.equal(verified.state.unsaved, true);+ assert.deepEqual(seen.writes, ["remove", "save"]);+});++test("a sign-in under way in the browser: the email code says so, and cancelling it lets the code go", async t => {+ const f = await fixture(t);+ assert.equal((await f.client.begin()).status, "connecting");+ assert.deepEqual(await f.client.emailStart("[email protected]"), { outcome: "blocked", reason: "connecting" });+ await f.client.cancel();+ assert.equal((await f.client.emailStart("[email protected]")).outcome, "sent");+});++test("a sign-in request that fails is logged by its kind only: status, or the network error's code", () => {+ const network = Object.assign(new TypeError("fetch failed"), { cause: Object.assign(new Error("unable to verify the first certificate"), { code: "UNABLE_TO_VERIFY_LEAF_SIGNATURE" }) });+ assert.equal(failureKind(network), "UNABLE_TO_VERIFY_LEAF_SIGNATURE");+ assert.equal(failureKind(Object.assign(new Error("x"), { status: 403, opaque: true })), "HTTP 403 (not the Admin's own answer)");+ assert.equal(failureKind(Object.assign(new Error("x"), { status: 503, code: "unavailable" })), "HTTP 503 unavailable");+ assert.equal(failureKind(Object.assign(new Error("x"), { name: "TimeoutError" })), "TimeoutError");+ assert.equal(failureKind(Object.assign(new Error("x"), { status: 400, code: "[email protected]" })), "HTTP 400", "nothing the answer names is logged as is");+});++test("the Admin's Retry-After reaches whoever asked, in seconds or as a date", async t => {+ const headers = value => new Headers(value === null ? {} : { "retry-after": value });+ assert.equal(retryAfterSeconds(headers("120")), 120);+ assert.equal(retryAfterSeconds(headers(new Date(1_800_000_090_000).toUTCString()), 1_800_000_000_000), 90);+ for (const value of [null, "soon", ""]) assert.equal(retryAfterSeconds(headers(value)), undefined, String(value));+ const f = await fixture(t, { fetch: async () => new Response(JSON.stringify({ error: "rate_limited" }), { status: 429, headers: { "content-type": "application/json", "retry-after": "120" } }) });+ await assert.rejects(f.client.updatesConsentByEmail({ email: "[email protected]", installId: "x", textVersion: 1 }), { status: 429, code: "rate_limited", retryAfter: 120 });+});diff --git a/electron/fixtures/home-window-world.mjs b/electron/fixtures/home-window-world.mjsindex 8a3c0e0ae6..5cb6d40129 100644--- a/electron/fixtures/home-window-world.mjs+++ b/electron/fixtures/home-window-world.mjs@@ -59,6 +59,7 @@ export function world({ clean = null, journal = done(), marker = null, state = creturn { origin: CLIENT, code: "CCCC-LLLL-AAAA", expiresAt: w.clock + 60_000 };}w.pairs++;+ if (w.cloud.pairError) throw w.cloud.pairError;if (w.state?.status !== "connected" || w.cloud.down) throw new Error("My Cloud is not ready to connect yet.");return { origin: CLOUD, code: "AAAA-BBBB-CCCC", expiresAt: w.clock + 60_000 };},diff --git a/electron/home-window-pairing.node-test.mjs b/electron/home-window-pairing.node-test.mjsnew file mode 100644index 0000000000..40c406d640--- /dev/null+++ b/electron/home-window-pairing.node-test.mjs@@ -0,0 +1,50 @@+// A code from the Admin for My Cloud is never asked for in a loop (home-window.mjs PAIR_RETRY_MS): not when its page won't+// load from this computer, and not when the Admin answers 429; and the screen names the address this computer couldn't reach.+import assert from "node:assert/strict";+import test from "node:test";++import { PAIR_RETRY_MS } from "./home-window.mjs";+import { CLOUD, world } from "./fixtures/home-window-world.mjs";++test("My Cloud's page that never loads from here: one code from the Admin, not one per look, and the screen names the address", async () => {+ const w = world({ cloud: { signedIn: false } });+ await w.home.show();+ assert.equal(w.pairs, 1);+ // This computer couldn't load it (a VPN, firewall or DNS filter in the way): the screen, which asks again as it mounts,+ // when the window comes to the front and on each session read.+ w.home.failed(w.url, -102);+ await w.later(0);+ for (let i = 0; i < 10; i++) { await w.home.retry(); await w.home.changed(); }+ assert.equal(w.pairs, 1, "the Admin is not asked for another code at once");+ assert.deepEqual(w.home.view(), { screen: "offline", cause: "network", host: "omb-t-1.fly.dev" });+ await w.later(PAIR_RETRY_MS[0]);+ await w.home.retry();+ assert.equal(w.pairs, 2, "asked again once the wait is over");+ w.home.failed(w.url, -102); await w.later(0);+ await w.later(PAIR_RETRY_MS[0]); await w.home.retry();+ assert.equal(w.pairs, 2, "each failure waits longer");+ await w.later(PAIR_RETRY_MS[1]); await w.home.retry();+ assert.equal(w.pairs, 3);+ w.home.navigated(`${CLOUD}/`); w.home.failed(`${CLOUD}/`, -102); await w.later(0);+ await w.later(PAIR_RETRY_MS[0]); await w.home.retry();+ assert.equal(w.pairs, 4, "a page that loaded starts the waits again");+});++test("the Admin's 429 on a pairing is honoured, Retry-After included, however often the window asks", async () => {+ const w = world({ cloud: { signedIn: false, pairError: Object.assign(new Error("Cloud request failed."), { status: 429, retryAfter: 120 }) } });+ await w.home.show();+ assert.equal(w.pairs, 1);+ for (let i = 0; i < 10; i++) { await w.home.changed(); await w.home.retry(); await w.later(1_000); }+ assert.equal(w.pairs, 1, "nothing asks again before the Admin's Retry-After");+ assert.equal(w.home.view().screen, "offline");+ w.cloud.pairError = null;+ await w.later(120_000); await w.home.retry();+ assert.equal(w.pairs, 2);+});++test("My Cloud that doesn't answer this computer, with no reason from the Admin: the screen names its address", async () => {+ const w = world({ cloud: { down: true } });+ await w.home.show();+ assert.deepEqual(w.home.view(), { screen: "offline", cause: "network", host: "omb-t-1.fly.dev" });+ assert.equal(w.pairs, 0);+});diff --git a/electron/home-window.d.mts b/electron/home-window.d.mtsindex 8dee4626ea..05fee28619 100644--- a/electron/home-window.d.mts+++ b/electron/home-window.d.mts@@ -6,7 +6,8 @@ export type HomeView = { name?: string } & (| { screen: "opening" | "waking" | "moving" }/** The Admin is setting it up (or a brand-new one's name isn't found yet, at `checking`): the step it reports. */| { screen: "setup"; step?: import("./cloud-home.mjs").CloudSetupStep; slow?: true }- | { screen: "offline"; reason?: string; cause?: "host" | "no_answer" }+ /** `network`: this computer couldn't connect to My Cloud's address (`host`) while the Admin knows of nothing wrong. */+ | { screen: "offline"; reason?: string; cause?: "host" | "no_answer" | "network"; host?: string }| { screen: "signin"; other?: true }/** `member`: a team's User, who can't subscribe or pay for it and is sent to its owner. */| { screen: "plan"; machine: "stopped" | "payment-problem" | "failed"; member?: true }diff --git a/electron/home-window.mjs b/electron/home-window.mjsindex 26ff068054..db65cee1e6 100644--- a/electron/home-window.mjs+++ b/electron/home-window.mjs@@ -21,6 +21,9 @@ export const LOOK_MS = 2_500;* offline screen, with Try again: never an endless spinner. */export const OPEN_MS = 30_000;export const RETRY_MS = Object.freeze([2_000, 4_000, 8_000, 15_000, 30_000]);+/** After a code whose page didn't load from here, or one the Admin refused, the next is asked for only after PAIR_RETRY_MS (or+ * the Admin's own Retry-After): every look, session read and focus once asked the Admin for a code about every second. */+export const PAIR_RETRY_MS = Object.freeze([15_000, 30_000, 60_000, 120_000, 300_000]);/** A brand-new Cloud's name can be missing for minutes after the Admin says it is ready: a resolver that was asked while* it was set up keeps that "no such name" (RFC 2308 negative caching; Chromium's own host cache does too). For a Cloud* ready within FRESH_MS, a name not found keeps the setup screen up and the window tries again on NAME_RETRY_MS, with@@ -64,6 +67,7 @@ const DEFAULT_TIMERS = {};const originOf = (url) => { try { return new URL(url).origin; } catch { return null; } };+const originHost = (origin) => { try { return new URL(origin).host || null; } catch { return null; } };/** The Cloud this computer moved to, at the address the verified session gives My Cloud now when My Cloud is that Cloud by* its id or by an address it had before it moved to another provider, for the journal's own account; as kept otherwise. */@@ -247,6 +251,14 @@ export function createHomeWindow(deps) {now = Date.now, timers = DEFAULT_TIMERS, hosts = () => null, readyStore = null, ownMove = () => null, log = () => {}, t = nativeText.englishText.t } = deps;let home = { kind: "computer" }, screen = null, status = null, opens = 0, retry = null, tries = 0, loaded = null, newer = false, repairing = null;let recovering = null;+ /** Pairing held for `origin` until `until` (PAIR_RETRY_MS); `network`: its page didn't load from this computer. */+ let pairHold = null;+ function holdPairing(origin, { error = null, network = false } = {}) {+ const tries = pairHold?.origin === origin ? pairHold.tries + 1 : 1;+ const asked = error?.status === 429 && Number.isFinite(error.retryAfter) ? Math.min(error.retryAfter, 3600) * 1000 : 0;+ pairHold = { origin, tries, network: network || (pairHold?.origin === origin && pairHold.network), until: now() + Math.max(PAIR_RETRY_MS[Math.min(tries, PAIR_RETRY_MS.length) - 1], asked) };+ }+ const pairingHeld = (origin) => pairHold?.origin === origin && now() < pairHold.until;/** The profile (clean-workspace.mjs) the person opened from the rail while My Cloud is home, until they pick a place. */let profileShown = null;/** My Cloud asked for before the move made it home (`{ open }`), until its page loads or the person goes elsewhere;@@ -351,11 +363,13 @@ export function createHomeWindow(deps) {goScreen();}- /** The place didn't answer: this computer's screen says so, with the Admin's reason for My Cloud, and looks again by itself. */- function offline(token) {+ /** The place didn't answer: this computer's screen says so, with the Admin's reason for My Cloud, and looks again by itself.+ * `unreached`: My Cloud's address, which this computer couldn't connect to while the Admin knows of nothing wrong. */+ function offline(token, unreached = null) {if (!wanted(token)) return;const cause = otherPlace(opening) ? null : cloudUnreachableCause(state(), cloudOrigin());- toScreen({ screen: "offline", ...(cause ? { reason: cloudUnreachableText(state(), cloudOrigin()), cause } : {}) });+ const host = !cause && unreached && !otherPlace(opening) ? originHost(unreached) : null;+ toScreen({ screen: "offline", ...(cause ? { reason: cloudUnreachableText(state(), cloudOrigin()), cause } : host ? { cause: "network", host } : {}) });later();}function later(delays = RETRY_MS, count = () => tries++) {@@ -375,10 +389,11 @@ export function createHomeWindow(deps) {/** My Cloud didn't answer: a brand-new one whose name isn't found yet is still settling in (the setup screen, tried* again sooner, for NAME_WAIT_MS); anything else is the offline screen. */async function unreachable(place, token, missing = null) {- if (place.kind !== "cloud" || !(naming || clock.fresh(place.origin)) || (missing ?? !(await found(place.origin))) === false) return offline(token);+ const mine = place.kind === "cloud" ? place.origin : null;+ if (place.kind !== "cloud" || !(naming || clock.fresh(place.origin)) || (missing ?? !(await found(place.origin))) === false) return offline(token, mine);if (!wanted(token)) return;naming ??= { since: now(), tries: 0 };- if (now() - naming.since >= NAME_WAIT_MS) return offline(token);+ if (now() - naming.since >= NAME_WAIT_MS) return offline(token, mine);log(`home: My Cloud's name isn't found yet; trying again (${naming.tries + 1})`);toScreen({ screen: "setup", step: "checking" });later(NAME_RETRY_MS, () => naming.tries++);@@ -502,8 +517,10 @@ export function createHomeWindow(deps) {if (!wanted(token)) return;let grant = null;if (!signedIn) {+ if (pairingHeld(origin)) return signInNeeded() ? toScreen({ screen: "signin" }) : offline(token, place.kind === "cloud" && pairHold.network ? origin : null);try { grant = await pair(place); } catch (error) {if (error?.gone && wanted(token)) return gone(place);+ holdPairing(origin, { error });log(`home: no sign-in code for ${otherPlace(place) ? place.name : "My Cloud"} (${error?.message ?? error})`);}if (!wanted(token)) return;@@ -785,6 +802,7 @@ export function createHomeWindow(deps) {if (otherPlace(shown) && ![shown.origin, localOrigin()].includes(originOf(url))) { shown = null; clearRenewal(); }const origin = placeOrigin();if (!origin || originOf(url) !== origin) return;+ if (pairHold?.origin === origin) pairHold = null;const at = new URL(url);if (at.pathname === "/pair" && !/[#&]code=/.test(at.hash)) { void repair(); return; }newer = false; loaded = null;@@ -804,6 +822,7 @@ export function createHomeWindow(deps) {}if (!at || (at !== place && (home.kind !== "computer" || at !== mine))) return false;if (at !== place) asked ??= { open: null };+ holdPairing(at, { network: true });const token = ++opens;void unreachable(otherPlace(shown) && at === place ? shown : { kind: "cloud", origin: at }, token, nameNotFound(code));return true;diff --git a/electron/main.mjs b/electron/main.mjsindex 40753c488d..9aeec4809a 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -801,7 +801,7 @@ function ensureCloudAccount() {cloudAccount = createCloudAccountClient({store: cloudAccountStore(),platform: process.platform, deviceName: os.hostname().slice(0, 100) || "My computer", appVersion: app.getVersion(), origin: cloudTarget(process.env).origin,- openBrowser: url => shell.openExternal(url), awaitingWake: () => cloudPower.awaiting(),+ openBrowser: url => shell.openExternal(url), awaitingWake: () => cloudPower.awaiting(), warn: slog,onState: state => {cloudSync.accountChanged(state.account?.id ?? null); rememberCloudHome(state);rememberedHome = rememberedCloudHome(rememberedHome, state);@@ -2456,7 +2456,7 @@ const workspaceOnly = (handler) => (event, ...args) => {};const localWorkspaceOnly = (channel, handler) => localOnly(channel, workspaceOnly(handler));// No renderer-supplied address, token, paid flag or callback can choose an account or activate Pro.-for (const method of ["state", "begin", "signInAgain", "reopen", "cancel", "refresh", "signOut", "openDashboard", "offer"]) {+for (const method of ["state", "begin", "signInAgain", "reopen", "cancel", "refresh", "signOut", "openDashboard", "offer", "resetSaved"]) {ipcMain.handle(`cloud-account:${method}`, localWorkspaceOnly(`cloud-account:${method}`, () => (method === "signOut" ? accounts.signOutActive() : ensureCloudAccount()[method]())));}ipcMain.handle("cloud-account:checkout", localWorkspaceOnly("cloud-account:checkout", async (_event, plan, source) => {diff --git a/electron/preload.cjs b/electron/preload.cjsindex d8c0301fd5..1b24ddf394 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -513,6 +513,7 @@ const bridge = {signInStart: email => ipcRenderer.invoke("cloud-account:signInStart", String(email)),signInVerify: code => ipcRenderer.invoke("cloud-account:signInVerify", String(code)),signInCancel: () => ipcRenderer.invoke("cloud-account:signInCancel"),+ resetSaved: () => ipcRenderer.invoke("cloud-account:resetSaved"),reopenCheckout: (plan, source) => ipcRenderer.invoke("cloud-account:reopenCheckout", String(plan), String(source)),copyCheckoutLink: () => ipcRenderer.invoke("cloud-account:copyCheckoutLink"),interest: () => ipcRenderer.invoke("cloud-account:interest"),diff --git a/src/components/AccountMenu.tsx b/src/components/AccountMenu.tsxindex ec7030e75b..bf6e4fdff1 100644--- a/src/components/AccountMenu.tsx+++ b/src/components/AccountMenu.tsx@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from "react";import { Check, LogOut, Plus, UserRound, X } from "lucide-react";import type { AccountsView, AccountSwitchResult, RailOpenResult } from "../../electron/cloud-account.mjs";import { cn } from "@/lib/cn";-import type { CloudSignInPhase } from "@/lib/cloud-plan";+import { blockedProblem, type CloudSignInPhase } from "@/lib/cloud-plan";import { t } from "@/lib/i18n";import { usePlaces } from "@/lib/places";import { CLOSE, Heading, PRIMARY, QUIET, SCREEN, SHEET } from "./cloud-buy/parts";@@ -104,7 +104,7 @@ function AddAccount({ start, onDone, onBack }: { start: string; onDone: (note: ssetBusy(true);void bridge.addStart(email).then((result) => {if (result.outcome === "sent") { setPhase({ step: "code", intent: false, email: result.email, resendAt: result.resendAt, problem: null, triesLeft: null, ...(result.signupOpen === false ? { signupOpen: false } : {}) }); setCode(""); }- else setPhase({ step: "email", intent: false, problem: result.outcome });+ else setPhase({ step: "email", intent: false, problem: result.outcome === "blocked" ? blockedProblem(result) : result.outcome });}, () => setPhase({ step: "email", intent: false, problem: "failed" })).finally(() => setBusy(false));};const verify = (digits: string) => {@@ -115,7 +115,7 @@ function AddAccount({ start, onDone, onBack }: { start: string; onDone: (note: sif (result.outcome === "switched") onDone(null);else if (result.outcome === "added") onDone(t("accounts.added", { email: result.email ?? email }));else if (result.outcome === "already") onDone(t("accounts.already", { email: result.email ?? email }));- else { setCode(""); setPhase({ ...at, problem: result.outcome, triesLeft: result.outcome === "wrong-code" ? result.triesLeft : null }); }+ else { setCode(""); setPhase({ ...at, problem: result.outcome === "blocked" ? blockedProblem(result) : result.outcome, triesLeft: result.outcome === "wrong-code" ? result.triesLeft : null }); }}, () => setPhase({ ...at, problem: "failed", triesLeft: null })).finally(() => setBusy(false));};// The browser's way ends in main, which says how once the list changes: the account in use now, kept for after a move, or thediff --git a/src/components/CloudAccountSettings.test.ts b/src/components/CloudAccountSettings.test.tsindex 8bbe4fe243..c93d9ada2e 100644--- a/src/components/CloudAccountSettings.test.ts+++ b/src/components/CloudAccountSettings.test.ts@@ -198,6 +198,26 @@ it("a saved sign-in that can't be read right now says the app tries again by itsexpect(html).toContain("This computer couldn't open its saved Cloud sign-in. Unlock your keychain, and the app tries again by itself.");none(html, ["could not be read or cleared", "sign out again", "Sign out of MausBot Cloud, then"]);});+it("a saved sign-in this computer can't read or remove: one button clears it and starts the sign-in, whatever the platform", async () => {+ for (const [platform, onSignIn] of [["win32", undefined], ["darwin", vi.fn()]] as const) {+ f.values = []; f.platform = platform;+ bridge.resetSaved = vi.fn().mockResolvedValue({ status: "signed-out" }); vi.mocked(bridge.begin).mockClear();+ await ready({ status: "unavailable", message: "restore-failed", reset: true });+ const html = render({ onSignIn }).html;+ expect(html).toContain("This computer can't read or remove its saved MausBot Cloud sign-in. Clear it to sign in again.");+ none(html, ["tries again by itself", "nothing you need to do"]);+ render({ onSignIn }).nodes.find(node => node.type === "button" && node.props.children === "Clear and sign in again")!.props.onClick!(); await flush();+ expect(bridge.resetSaved).toHaveBeenCalledOnce();+ if (onSignIn) { expect(onSignIn).toHaveBeenCalledOnce(); expect(bridge.begin).not.toHaveBeenCalled(); }+ else expect(bridge.begin).toHaveBeenCalledOnce();+ }+});+it("a saved sign-in that couldn't be removed, and one kept for this run only, each say so", async () => {+ await ready({ status: "signed-out", message: "reset-kept" });+ expect(render().html).toContain("The saved sign-in couldn't be removed from this computer, but you can sign in now.");+ push({ ...free, unsaved: true });+ expect(render().html).toContain("Signed in for now. This computer couldn't save the sign-in");+});it("a sign-out that could not clear the saved sign-in still asks for it", async () => {await ready({ status: "unavailable", message: "signout-storage-failed" });const html = render().html;diff --git a/src/components/CloudAccountSettings.tsx b/src/components/CloudAccountSettings.tsxindex 5aa7036658..011490b417 100644--- a/src/components/CloudAccountSettings.tsx+++ b/src/components/CloudAccountSettings.tsx@@ -100,6 +100,8 @@ const RESTORE_RETRY: Partial<Record<DesktopCapabilities["host"]["platform"], Locfunction accountMessage(account: CloudAccountState | null, view: CloudPlanView, platform: DesktopCapabilities["host"]["platform"]): string | null {if (!account) return null;+ // A saved sign-in this computer can't read or remove: Clear and sign in again is the way on (main offers it after a few tries).+ if (account.reset) return t("cloudAccount.savedStuck");if (account.message === "signout-local-only") return t("cloudAccount.signoutLocalOnly");if (account.message === "signout-storage-failed") return t("cloudAccount.storageFailed");if (account.message === "restore-failed") return t(RESTORE_RETRY[platform] ?? "cloudAccount.restoreRetry");@@ -109,8 +111,9 @@ function accountMessage(account: CloudAccountState | null, view: CloudPlanView,if (view.kind === "attention" && !account.machine && !account.trial) return t("cloudAccount.attention");if (account.status === "signed-out" && account.message === "enrollment-expired") return t("cloudAccount.codeExpired");if (account.status === "signed-out" && account.message === "restore-removed") return t("cloudAccount.restoreRemoved");+ if (account.status === "signed-out" && account.message === "reset-kept") return t("cloudAccount.resetKept");if (account.status === "signed-out" && account.message && account.message !== "restoring") return t("cloudAccount.signinFailed");- return null;+ return account.unsaved ? t("cloudAccount.unsaved") : null;}function dashboardLabel(account: CloudAccountState, view: CloudPlanView): string {@@ -261,6 +264,14 @@ export function CloudAccountSettings({ linkRequest = 0, cloudHome = false, teamHconst signedOut = view.kind === "signed-out" || view.kind === "removed";const startLabel = t(offerTrialDays(offer) !== null ? "cloudIntro.start" : "cloudAccount.upgrade");const errorLine = error && <p role="alert" className="px-4 text-[12px] leading-4 text-danger">{t("cloudAccount.actionFailed")}</p>;+ // Clear and sign in again: the saved sign-in goes, then the sign-in starts as Sign in's does.+ const resetSaved = bridge.resetSaved && account?.reset ? () => void perform(async () => {+ const next = await bridge.resetSaved!();+ if (next.status !== "signed-out") return next;+ if (onSignIn) { onSignIn(); return next; }+ return bridge.begin();+ }) : null;+ const resetButton = (primary: boolean) => resetSaved && <button type="button" disabled={busy} data-cloud-reset="" className={primary ? "ui-button ui-button-primary" : "ui-button"} onClick={resetSaved}>{t("cloudAccount.resetSaved")}</button>;if (part === "account") {// One layout on every rail (§1.6): an icon card with the person's picture in the first row's slot, who is signed in,@@ -279,7 +290,7 @@ export function CloudAccountSettings({ linkRequest = 0, cloudHome = false, teamH<button type="button" disabled={busy} className="settings-quiet cursor-pointer" onClick={() => void perform(() => bridge.cancel())}>{t("organization.cancel")}</button></SettingRow>}{signed && <SettingRow title={account.account?.email ?? t("settings.account.signedIn")} leading={avatar ?? blank} subtitle={message ? <p role="status">{message}</p> : t("settings.account.signedIn")}>- {view.kind === "reauth"+ {resetSaved ? resetButton(false) : view.kind === "reauth"? <button type="button" disabled={busy} className="ui-button" onClick={() => void perform(() => bridge.signInAgain())}>{t("cloudAccount.signInAgain")}</button>: advanced && <button type="button" disabled={busy} className="settings-quiet cursor-pointer" onClick={() => void perform(() => bridge.refresh())}>{t("organization.refresh")}</button>}</SettingRow>}@@ -300,7 +311,7 @@ export function CloudAccountSettings({ linkRequest = 0, cloudHome = false, teamHif (part === "sign-out") return null;const cancelled = account?.status === "connected" && account.renewal?.cancelled === true;- const primary = signedOut || (view.kind === "free" && buyOfferAllowed(view))+ const primary = resetSaved ? resetButton(true) : signedOut || (view.kind === "free" && buyOfferAllowed(view))? onAddCloud && buyOfferAllowed(view) && <button type="button" disabled={busy} className="ui-button ui-button-primary" data-plan-add="" onClick={onAddCloud}>{startLabel}</button>: view.kind === "reauth"? <button type="button" disabled={busy} className="ui-button ui-button-primary" onClick={() => void perform(() => bridge.signInAgain())}>{t("cloudAccount.signInAgain")}</button>diff --git a/src/components/CloudAddDialog.test.ts b/src/components/CloudAddDialog.test.tsindex 3a52965ffd..e3fe8f1d12 100644--- a/src/components/CloudAddDialog.test.ts+++ b/src/components/CloudAddDialog.test.ts@@ -54,7 +54,7 @@ const nodes = (value: ReactNode): Node[] => {const text = (html: string) => html.replace(/<[^>]+>/g, " ").replace(/'/g, "'").replace(/&/g, "&").replace(/\s+/g, " ").trim();const label = (node: Node) => text(renderToStaticMarkup(node));const button = (tree: Node[], name: string) => tree.find(node => node.type === "button" && (label(node) === name || label(node).startsWith(name) || node.props["aria-label"] === name));-const actions = (): CloudAddActions => Object.fromEntries(["start", "signIn", "back", "email", "sendCode", "changeEmail", "code", "resend", "browser", "reopenBrowser",+const actions = (): CloudAddActions => Object.fromEntries(["start", "signIn", "back", "email", "sendCode", "resetSaved", "cancelBrowser", "changeEmail", "code", "resend", "browser", "reopenBrowser","cancelSignIn", "reopenCheckout", "copyLink", "changePlan", "retry", "name", "color", "openCloud", "openTeam", "notNow", "interest", "close"].map(name => [name, vi.fn()])) as unknown as CloudAddActions;const baseUi = (extra: Partial<CloudAddUi> = {}): CloudAddUi => ({ chosen: null, current: null, offerShown: TRIAL, now: NOW, busy: false, openFailed: false, email: EMAIL, code: "", profileEmail: EMAIL,look: { typed: "Studio", name: "Studio", color: "teal" }, counting: null, copied: false, payFailed: false, interest: null, ...extra });@@ -217,6 +217,20 @@ describe("each screen of the sheet says one thing and offers one next step", ()expect(text(panel({ kind: "sign-in", phase }).html)).not.toContain("aren't open yet");});+ it("a sign-in that can't start says why truthfully, never 'couldn't reach', with its one way on", () => {+ const email = (problem: any): CloudAddView => ({ kind: "sign-in", phase: { step: "email", intent: false, problem } });+ const saved = panel(email("saved"));+ expect(text(saved.html)).toContain("This computer has a saved MausBot Cloud sign-in that it can't read, so a new sign-in can't start.");+ expect(text(saved.html)).not.toContain("Couldn't reach");+ button(saved.tree, "Clear it and send the code")!.props.onClick(); expect(saved.handlers.resetSaved).toHaveBeenCalledOnce();+ const waiting = panel(email("saved-wait"));+ expect(text(waiting.html)).toContain("The app tries again by itself"); expect(button(waiting.tree, "Clear it and send the code")).toBeUndefined();+ const browser = panel(email("connecting"));+ expect(text(browser.html)).toContain("A sign-in is still under way in your browser.");+ button(browser.tree, "Cancel it and send the code")!.props.onClick(); expect(browser.handlers.cancelBrowser).toHaveBeenCalledOnce();+ expect(text(panel(email("busy")).html)).toContain("Try again in a moment.");+ });+it("Sign in: the Admin's answers in plain words, with the one way on", () => {const code = (problem: any, triesLeft: number | null = null): CloudAddView => ({ kind: "sign-in", phase: { step: "code", intent: true, email: EMAIL, resendAt: NOW - 1, problem, triesLeft } });expect(text(panel(code("wrong-code", 3)).html)).toContain("That code isn't right. 3 tries left.");@@ -422,6 +436,19 @@ describe("the sheet", () => {expect(render()).toContain('data-add-cloud-flow="app_whats_new_team"');});+ it("Send code with a saved sign-in this computer can't read: one click clears it and sends the code", async () => {+ await settle(); await buy("pro");+ bridge.signInStart.mockResolvedValueOnce({ outcome: "blocked", reason: "saved", reset: true });+ bridge.resetSaved = vi.fn(async () => ({ status: "signed-out" }));+ tree().find(node => node.type === "form")!.props.onSubmit({ preventDefault() {} }); await flush();+ const html = await settle();+ expect(html).toContain("saved MausBot Cloud sign-in that it can't read"); expect(html).not.toContain("Couldn't reach");+ await press("Clear it and send the code");+ expect(bridge.resetSaved).toHaveBeenCalledOnce();+ expect(bridge.signInStart).toHaveBeenCalledTimes(2);+ expect(await settle()).toContain(`Enter the 8-digit code sent to ${EMAIL}`);+ });+it("the Admin's word that new accounts are closed reaches the code step", async () => {bridge.signInStart.mockResolvedValueOnce({ outcome: "sent", email: EMAIL, expiresAt: NOW + 600_000, resendAt: NOW + 30_000, signupOpen: false });await settle(); await buy("pro");diff --git a/src/components/CloudAddDialog.tsx b/src/components/CloudAddDialog.tsxindex ed7f7a20a7..beb142bd2c 100644--- a/src/components/CloudAddDialog.tsx+++ b/src/components/CloudAddDialog.tsx@@ -9,7 +9,7 @@ import { track } from "@/lib/analytics";import { cloudAccountBridge } from "@/lib/cloud-add-web";import { cn } from "@/lib/cn";import { cloudColor, cloudNameShown, DEFAULT_CLOUD_COLOR } from "@/lib/cloud-look";-import { cloudAddView, offerPlan, sameTerms, startedSleeps, type CloudAddView, type CloudSignInPhase } from "@/lib/cloud-plan";+import { blockedProblem, cloudAddView, offerPlan, sameTerms, startedSleeps, type CloudAddView, type CloudSignInPhase } from "@/lib/cloud-plan";import { t } from "@/lib/i18n";import { welcomeOnScreen } from "@/lib/onboarding";import { useStore } from "@/state/store";@@ -28,6 +28,10 @@ export interface CloudAddActions {back(): void;email(value: string): void;sendCode(): void;+ /** Clears a saved sign-in this computer can't read, then sends the code. */+ resetSaved(): void;+ /** Ends the sign-in under way in the browser, then sends the code. */+ cancelBrowser(): void;changeEmail(): void;code(value: string): void;resend(): void;@@ -70,7 +74,7 @@ export function CloudAddPanel({ view, ui, actions }: { view: CloudAddView; ui: ConStart={actions.start} onSignIn={actions.signIn} />;case "sign-in": return <SignInScreen phase={view.phase} email={ui.email} code={ui.code} profileEmail={ui.profileEmail} busy={ui.busy} now={ui.now}onBack={actions.back} onEmail={actions.email} onSend={actions.sendCode} onChangeEmail={actions.changeEmail} onCode={actions.code}- onResend={actions.resend} onBrowser={actions.browser} />;+ onResend={actions.resend} onBrowser={actions.browser} onReset={actions.resetSaved} onCancelBrowser={actions.cancelBrowser} />;case "signing-in": return <BrowserSignInScreen code={view.code} checkout={view.checkout} busy={ui.busy}trial={ui.offerShown ? Boolean(offerPlan(ui.offerShown, ui.chosen).trialDays) : false} onReopen={actions.reopenBrowser} onCancel={actions.cancelSignIn} />;case "waiting": return <PayScreen plan={view.plan} offer={ui.offerShown} browser={view.browser} late={view.late} link={view.link} email={view.email}@@ -292,19 +296,21 @@ export function CloudAddDialog({ now = Date.now }: { now?: () => number }) {setSignIn({ step: "email", intent, problem: null });setForm({ email: form.email || profileEmail || "", code: "" });};- const sendCode = () => {+ /** `before`: what clears the way first (a saved sign-in cleared, the browser's ended), as one step with the send. */+ const send = (before: () => Promise<unknown> = async () => {}) => {if (busy || !bridge.signInStart || !signIn || signIn.step === "done") return;const phase = signIn;setBusy(true);- void bridge.signInStart(form.email).then(result => {+ void before().then(() => bridge.signInStart!(form.email)).then(result => {if (result.outcome === "sent") {setSignIn({ step: "code", intent: phase.intent, email: result.email, resendAt: result.resendAt, problem: null, triesLeft: null,...(result.signupOpen === false ? { signupOpen: false } : {}) });setForm({ email: result.email, code: "" });track("cloud_signin", { step: "code_sent", source: request.source });- } else setSignIn({ ...phase, problem: result.outcome });+ } else setSignIn({ ...phase, problem: result.outcome === "blocked" ? blockedProblem(result) : result.outcome });}, () => setSignIn({ ...phase, problem: "failed" })).finally(() => setBusy(false));};+ const sendCode = () => send();const verify = (code: string) => {if (!bridge.signInVerify || signIn?.step !== "code") return;const phase = signIn, plan = phase.intent ? planNow() : null;@@ -314,7 +320,7 @@ export function CloudAddDialog({ now = Date.now }: { now?: () => number }) {const result = await bridge.signInVerify!(code);if (result.outcome !== "signed-in") {setForm({ email: form.email, code: "" });- setSignIn({ ...phase, problem: result.outcome, triesLeft: result.outcome === "wrong-code" ? result.triesLeft : null });+ setSignIn({ ...phase, problem: result.outcome === "blocked" ? blockedProblem(result) : result.outcome, triesLeft: result.outcome === "wrong-code" ? result.triesLeft : null });return;}setAccount(result.state); setArrived(true);@@ -339,6 +345,8 @@ export function CloudAddDialog({ now = Date.now }: { now?: () => number }) {back: () => { setSignIn(null); void bridge.signInCancel?.().catch(() => {}); },email: value => setForm({ email: value, code: form.code }),sendCode,+ resetSaved: () => { if (bridge.resetSaved) send(async () => setAccount(await bridge.resetSaved!())); },+ cancelBrowser: () => send(async () => setAccount(await bridge.cancel())),changeEmail: () => { if (signIn) { setSignIn({ step: "email", intent: signIn.intent, problem: null }); void bridge.signInCancel?.().catch(() => {}); } },code: value => {const digits = codeDigits(value);diff --git a/src/components/HomeScreen.test.ts b/src/components/HomeScreen.test.tsindex 190004945e..f9655f32c9 100644--- a/src/components/HomeScreen.test.ts+++ b/src/components/HomeScreen.test.ts@@ -63,3 +63,10 @@ it("a Cloud that isn't running says what it is in plain words with its one actiofor (const words of Object.values(homeScreenText({ screen, name: "Client B", deleteAt: day }, now))) expect(String(words)).not.toMatch(/—|\bVM\b|engine|ctx|server/i);}});++it("My Cloud this computer couldn't connect to names its address and what may be in the way, with Try again", () => {+ expect(homeScreenText({ screen: "offline", cause: "network", host: "omb-t-1.fly.dev" })).toMatchObject({+ title: "Can't reach My Cloud right now.", action: "retry",+ reason: "This computer couldn't connect to omb-t-1.fly.dev. If My Cloud opens on another device or network, check whether a VPN, firewall or DNS filter here blocks that address.",+ });+});diff --git a/src/components/HomeScreen.tsx b/src/components/HomeScreen.tsxindex d8b1354f42..d0b43cb4d2 100644--- a/src/components/HomeScreen.tsx+++ b/src/components/HomeScreen.tsx@@ -27,7 +27,8 @@ export function homeScreenText(view: HomeView | null, now = Date.now()): { titleconst name = view?.name ?? null;const named = (plain: LocaleKey, withName: LocaleKey) => (name ? t(withName, { name }) : t(plain));if (view?.screen === "setup") return { title: named("homeScreen.setup", "homeScreen.setupNamed"), body: t(view.slow ? "cloudHome.slow" : "homeScreen.setupBody"), reason: null, action: null, busy: true };- if (view?.screen === "offline") return { title: named("homeScreen.offline", "homeScreen.offlineNamed"), body: t("homeScreen.offlineBack"), reason: view.cause && Object.hasOwn(UNREACHABLE, view.cause) ? t(UNREACHABLE[view.cause]!) : view.reason ?? null, action: "retry", busy: false };+ if (view?.screen === "offline") return { title: named("homeScreen.offline", "homeScreen.offlineNamed"), body: t("homeScreen.offlineBack"), action: "retry", busy: false,+ reason: view.cause === "network" && view.host ? t("homeScreen.offlineNetwork", { host: view.host }) : view.cause && Object.hasOwn(UNREACHABLE, view.cause) ? t(UNREACHABLE[view.cause]!) : view.reason ?? null };if (view?.screen === "signin") return { title: named("homeScreen.signIn", "homeScreen.signInNamed"), body: t(view.other ? "homeScreen.signInOther" : "homeScreen.signInEnded"), reason: null, action: "sign-in", busy: false };if (view?.screen === "plan" && view.member && view.machine !== "failed") return { title: named("homeScreen.plan", "homeScreen.planNamed"), body: t("cloudHome.stoppedMember"), reason: null, action: null, busy: false };if (view?.screen === "plan") return { title: named("homeScreen.plan", "homeScreen.planNamed"), body: t(MACHINE[view.machine] ?? "cloudHome.failed"), reason: null, action: view.machine === "failed" ? null : "manage", busy: false };diff --git a/src/components/cloud-buy/SignInScreen.tsx b/src/components/cloud-buy/SignInScreen.tsxindex b175f6aafd..3f4e5c6cf0 100644--- a/src/components/cloud-buy/SignInScreen.tsx+++ b/src/components/cloud-buy/SignInScreen.tsx@@ -21,6 +21,11 @@ export function problemLine(problem: CloudSignInProblem, triesLeft: number | nulcase "two-factor": return t("cloudBuy.signIn.twoFactor");case "browser": return t("cloudBuy.signIn.browser");case "failed": return t("cloudBuy.signIn.failed");+ case "saved": return t("cloudBuy.signIn.saved");+ case "saved-wait": return t("cloudBuy.signIn.savedWait");+ case "connecting": return t("cloudBuy.signIn.connecting");+ case "busy": return t("cloudBuy.signIn.busy");+ case "signed-in": return t("cloudBuy.signIn.signedIn");}}@@ -30,10 +35,12 @@ export function codeDigits(value: string): string {}const clock = (ms: number) => { const seconds = Math.max(0, Math.ceil(ms / 1000)); return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; };-export function SignInScreen({ phase, email, code, profileEmail, busy, now, onBack, onEmail, onSend, onChangeEmail, onCode, onResend, onBrowser }: {+/** `onReset`: a saved sign-in this computer can't read is cleared and a code sent; `onCancelBrowser`: the sign-in under way in+ * the browser ends and a code is sent instead. Each is the problem's one action, where the page offers it. */+export function SignInScreen({ phase, email, code, profileEmail, busy, now, onBack, onEmail, onSend, onChangeEmail, onCode, onResend, onBrowser, onReset, onCancelBrowser }: {phase: CloudSignInPhase; email: string; code: string; profileEmail: string | null; busy: boolean; now: number;onBack: () => void; onEmail: (email: string) => void; onSend: () => void; onChangeEmail: () => void;- onCode: (code: string) => void; onResend: () => void; onBrowser: () => void;+ onCode: (code: string) => void; onResend: () => void; onBrowser: () => void; onReset?: () => void; onCancelBrowser?: () => void;}) {const problem = phase.step === "done" ? null : phase.problem;const browser = problem !== null && BROWSER_PROBLEMS.has(problem);@@ -102,6 +109,8 @@ export function SignInScreen({ phase, email, code, profileEmail, busy, now, onBa<p>{problemLine(problem, phase.step === "code" ? phase.triesLeft : null)}</p>{browser && <button type="button" className={PRIMARY} onClick={onBrowser}>{t("cloudBuy.signIn.continueBrowser")}<ExternalLink size={14} aria-hidden="true" /></button>}{problem === "expired" && phase.step === "code" && <button type="button" className={QUIET} disabled={busy} onClick={onResend}>{t("cloudBuy.signIn.newCode")}</button>}+ {problem === "saved" && onReset && <button type="button" data-cloud-reset className={PRIMARY} disabled={busy} onClick={onReset}>{t("cloudBuy.signIn.reset")}</button>}+ {problem === "connecting" && onCancelBrowser && <button type="button" data-cloud-cancel-browser className={QUIET} disabled={busy} onClick={onCancelBrowser}>{t("cloudBuy.signIn.cancelBrowser")}</button>}</div>}{phase.step !== "done" && !browser && <p className="text-[13px] leading-[18px] text-ink-tertiary">{t("cloudBuy.signIn.ssoHint")}{" "}<button type="button" className={LINK} onClick={onBrowser}>{t("cloudBuy.signIn.continueBrowser")}</button></p>}diff --git a/src/lib/cloud-plan.ts b/src/lib/cloud-plan.tsindex 23245001a8..0e81f29013 100644--- a/src/lib/cloud-plan.ts+++ b/src/lib/cloud-plan.ts@@ -1,4 +1,5 @@import type { CloudAccountState, CloudPlanSnapshot } from "../../electron/cloud-account.mjs";+import type { CloudSignInBlocked } from "../../electron/cloud-signin.mjs";import type { CloudCredit, CloudOffer, CloudOfferPlan, CloudPlanAllowances, CloudSetupStep, CloudTrial, CloudTrialState } from "../../electron/cloud-home.mjs";import { planTeam, teamPlan } from "../../electron/cloud-team-plan.mjs";import { activeLocale, t } from "@/lib/i18n";@@ -272,7 +273,13 @@ export function cloudIntroView(offer: CloudOffer | null | undefined): { badge: sexport const CHECKOUT_WAIT_MS = 30 * 60_000;/** The in-app sign-in's step, kept by the sheet: where it is and what the Admin last said, never a code or token. */-export type CloudSignInProblem = "invalid-email" | "rate-limited" | "failed" | "wrong-code" | "expired" | "signup-closed" | "device-limit" | "sso" | "two-factor" | "browser";+export type CloudSignInProblem = "invalid-email" | "rate-limited" | "failed" | "wrong-code" | "expired" | "signup-closed" | "device-limit" | "sso" | "two-factor" | "browser"+ | "saved" | "saved-wait" | "connecting" | "busy" | "signed-in";+/** A sign-in that couldn't start, as the sheet says it: a saved sign-in this computer can't read (`saved` once clearing it is+ * offered, `saved-wait` while the app still tries to read it), one in the browser (`connecting`), or a moment's wait. */+export function blockedProblem(result: CloudSignInBlocked): CloudSignInProblem {+ return result.reason === "saved" ? (result.reset ? "saved" : "saved-wait") : result.reason;+}export type CloudSignInPhase =| { step: "email"; intent: boolean; problem: CloudSignInProblem | null }| { step: "code"; intent: boolean; email: string; resendAt: number; problem: CloudSignInProblem | null; triesLeft: number | null; signupOpen?: boolean }diff --git a/src/locales/en.json b/src/locales/en.jsonindex 0d6d584246..be57fbd767 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -695,6 +695,13 @@"cloudBuy.signIn.invalidEmail": "Enter an email address like [email protected].","cloudBuy.signIn.rateLimited": "Too many codes were asked for just now. Wait a minute, then try again.","cloudBuy.signIn.failed": "Couldn't reach MausBot Cloud. Check your connection and try again.",+ "cloudBuy.signIn.saved": "This computer has a saved MausBot Cloud sign-in that it can't read, so a new sign-in can't start.",+ "cloudBuy.signIn.reset": "Clear it and send the code",+ "cloudBuy.signIn.savedWait": "This computer couldn't open its saved MausBot Cloud sign-in yet. If your system asks you to unlock your keychain, unlock it. The app tries again by itself, and offers to clear it if it still can't.",+ "cloudBuy.signIn.connecting": "A sign-in is still under way in your browser.",+ "cloudBuy.signIn.cancelBrowser": "Cancel it and send the code",+ "cloudBuy.signIn.busy": "This app is still opening its MausBot Cloud sign-in. Try again in a moment.",+ "cloudBuy.signIn.signedIn": "This computer is already signed in to MausBot Cloud.","cloudBuy.signIn.wrongCode": "That code isn't right. {count} tries left.","cloudBuy.signIn.wrongCodeOne": "That code isn't right. 1 try left.","cloudBuy.signIn.expired": "That code can't be used any more. Send a new one.",@@ -1335,6 +1342,10 @@"cloudAccount.restoreRetryKeyring": "This computer couldn't open its saved Cloud sign-in. Unlock your system keyring, and the app tries again by itself.","cloudAccount.restoreRemoved": "This computer's Cloud sign-in couldn't be read, so it was removed. Sign in again.","cloudAccount.signinFailed": "Cloud sign-in ended or could not be completed. Start again on this computer.",+ "cloudAccount.savedStuck": "This computer can't read or remove its saved MausBot Cloud sign-in. Clear it to sign in again. Your plan and My Cloud aren't affected.",+ "cloudAccount.resetSaved": "Clear and sign in again",+ "cloudAccount.resetKept": "The saved sign-in couldn't be removed from this computer, but you can sign in now. After the app restarts, it may ask you to clear it again.",+ "cloudAccount.unsaved": "Signed in for now. This computer couldn't save the sign-in, so the app asks you to sign in again after it restarts.","cloudAccount.actionFailed": "Could not complete this Cloud action. Check your connection and try again.","cloudAccount.keepHere.title": "Keep this computer's bots on this computer","cloudAccount.keepHere.line": "This computer's bots, chats and automations stay here instead of moving to My Cloud.",@@ -7877,6 +7888,7 @@"homeScreen.setup": "Setting up My Cloud…","homeScreen.setupBody": "This takes about a minute. It opens by itself when it's ready.","homeScreen.offline": "Can't reach My Cloud right now.",+ "homeScreen.offlineNetwork": "This computer couldn't connect to {host}. If My Cloud opens on another device or network, check whether a VPN, firewall or DNS filter here blocks that address.","homeScreen.offlineBack": "It comes back by itself when it answers.","homeScreen.signIn": "Sign in to open My Cloud","homeScreen.signInEnded": "This computer's sign-in to MausBot Cloud has ended. Your bots and chats are safe on My Cloud.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex bc9e871815..92c3b1eb45 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -669,6 +669,13 @@"cloudBuy.signIn.invalidEmail": "Digite um endereço de e-mail como [email protected].","cloudBuy.signIn.rateLimited": "Muitos códigos foram pedidos agora há pouco. Aguarde um minuto e tente novamente.","cloudBuy.signIn.failed": "Não foi possível acessar o MausBot Cloud. Verifique sua conexão e tente novamente.",+ "cloudBuy.signIn.saved": "Este computador tem um login do MausBot Cloud salvo que não consegue ler, então não é possível começar um novo login.",+ "cloudBuy.signIn.reset": "Apagar e enviar o código",+ "cloudBuy.signIn.savedWait": "Este computador ainda não conseguiu abrir o login do MausBot Cloud salvo. Se o sistema pedir para desbloquear o chaveiro, desbloqueie. O app tenta novamente sozinho e oferece apagar o login se ainda não conseguir.",+ "cloudBuy.signIn.connecting": "Um login ainda está em andamento no seu navegador.",+ "cloudBuy.signIn.cancelBrowser": "Cancelar e enviar o código",+ "cloudBuy.signIn.busy": "Este app ainda está abrindo o login do MausBot Cloud. Tente novamente em instantes.",+ "cloudBuy.signIn.signedIn": "Este computador já está conectado ao MausBot Cloud.","cloudBuy.signIn.wrongCode": "Código incorreto. Restam {count} tentativas.","cloudBuy.signIn.wrongCodeOne": "Código incorreto. Resta 1 tentativa.","cloudBuy.signIn.expired": "Esse código não pode mais ser usado. Envie um novo.",@@ -1257,6 +1264,10 @@"cloudAccount.restoreRetryKeyring": "Não foi possível acessar os dados de login do Cloud salvos neste computador. Desbloqueie o chaveiro do sistema e o app tenta novamente sozinho.","cloudAccount.restoreRemoved": "Não foi possível ler o login do Cloud salvo neste computador, então esse login foi removido. Entre novamente.","cloudAccount.signinFailed": "O login no Cloud terminou ou não pôde ser concluído. Comece novamente neste computador.",+ "cloudAccount.savedStuck": "Este computador não consegue ler nem apagar o login do MausBot Cloud salvo. Apague-o para entrar novamente. Seu plano e o My Cloud não são afetados.",+ "cloudAccount.resetSaved": "Apagar e entrar novamente",+ "cloudAccount.resetKept": "Não foi possível apagar o login salvo deste computador, mas você já pode entrar. Depois que o app reiniciar, ele pode pedir para apagá-lo novamente.",+ "cloudAccount.unsaved": "Login feito por enquanto. Este computador não conseguiu salvar o login, então o app pede para entrar novamente depois que reiniciar.","cloudAccount.actionFailed": "Não foi possível concluir esta ação do Cloud. Verifique sua conexão e tente novamente.","cloudAccount.keepHere.title": "Manter aqui os bots deste computador","cloudAccount.keepHere.line": "Os bots, as conversas e as automações deste computador ficam aqui em vez de ir para o Cloud.",@@ -7678,6 +7689,7 @@"homeScreen.setup": "Configurando o Cloud…","homeScreen.setupBody": "Isso leva cerca de um minuto. Ele abre sozinho assim que estiver pronto.","homeScreen.offline": "Não foi possível acessar o Cloud agora.",+ "homeScreen.offlineNetwork": "Este computador não conseguiu se conectar a {host}. Se o My Cloud abrir em outro dispositivo ou rede, verifique se uma VPN, um firewall ou um filtro de DNS daqui está bloqueando esse endereço.","homeScreen.offlineBack": "Ele volta sozinho assim que responder.","homeScreen.signIn": "Entre para abrir o Cloud","homeScreen.signInEnded": "Seu login no MausBot Cloud não está mais ativo neste computador. Seus bots e conversas estão seguros no Cloud.",