Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
My Cloud pairing: Try again is never held, one failure costs seconds, the VPN line only when it fits; Clear waits longer (#6686)
Milind Soni9dab28531aae
diff --git a/electron/cloud-account.d.mts b/electron/cloud-account.d.mtsindex 9ae915058e..7c4705e5da 100644--- a/electron/cloud-account.d.mts+++ b/electron/cloud-account.d.mts@@ -379,6 +379,8 @@ export interface CloudAccountClient {reload(): Promise<CloudAccountState>;/** Ends a sign-in that waits on this device, at the Admin. */revokeSaved(record: unknown): Promise<void>;+ /** For cloud-accounts.mjs only, never a page: the active sign-in when it is kept in memory only, as its file would hold it. */+ memorySignIn(): unknown;close(): void;}export declare function createCloudAccountClient(options: {@@ -398,6 +400,8 @@ export declare function createCloudAccountClient(options: {/** Files or lending waits for a sleeping Cloud to wake: the session is read every 15 s. */awaitingWake?: () => boolean;t?: (key: string, params?: Record<string, string | number>) => string;+ /** How long Clear waits for a read of the saved sign-in already under way (READ_WAIT_MS). */+ readWaitMs?: number;}): CloudAccountClient;export declare function cloudPlanSnapshot(state: CloudAccountState | null | undefined, extra?: { notice?: import("./cloud-home.mjs").CloudTrialState | null }): CloudPlanSnapshot;/** My Cloud's line under its name in the server menus, or null for none. */diff --git a/electron/cloud-account.mjs b/electron/cloud-account.mjsindex 63e048819d..e29518a2ae 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, failureKind, parseSignInStart, resetOffered, retryAfterSeconds, SIGN_IN_START, SIGN_IN_TRIES, SIGN_IN_VERIFY, signInBlock, signInIdentity, startFailure, verifyFailure } from "./cloud-signin.mjs";+import { cleanCode, cleanEmail, failureKind, parseSignInStart, READ_WAIT_MS, resetOffered, retryAfterSeconds, settledWithin, 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;@@ -98,7 +98,7 @@ function addOffer(result) {export function createCloudAccountClient({ store, openBrowser, platform, deviceName, appVersion,origin = CLOUD_ORIGIN, fixture = false, fetch: fetcher = globalThis.fetch, now = Date.now, onState = () => {},- setTimer = setTimeout, clearTimer = clearTimeout, warn = message => console.warn(message), awaitingWake = () => false, t = englishText.t }) {+ setTimer = setTimeout, clearTimer = clearTimeout, warn = message => console.warn(message), awaitingWake = () => false, t = englishText.t, readWaitMs = READ_WAIT_MS }) {origin = cloudOrigin(origin, fixture);const staging = origin === STAGING_CLOUD_ORIGIN;let grant = null, issued = null, cleanup = null, pending = null, cleanupNeeded = false;@@ -386,7 +386,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN/** 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(() => {});+ if (restoring && reading) await settledWithin(reading, readWaitMs);const reason = signInBlock({ closed, restoring, issued, grant, cleanupNeeded, connecting: connecting && value.status === "connecting" });return reason && { outcome: "blocked", reason, ...(reason === "saved" && value.reset ? { reset: true } : {}) };}@@ -479,7 +479,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNif (!current(stamp)) return state();if (removed) { cleanupNeeded = false; failures = 0; stuckSince = null; return publish({ status: "signed-out", message: "restore-removed" }); }}- failures++; stuckSince ??= now(); const offer = resetOffered({ platform, failures, since: stuckSince, now: now() });+ failures++; stuckSince ??= now(); const offer = resetOffered({ 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();@@ -529,6 +529,8 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN* 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();+ // A read under way may yet open it: then it is kept and signed in, never cleared under that read.+ if (restoring && reading) { await settledWithin(reading, readWaitMs); if (grant) return refresh(); restoring = false; if (closed || issued || clearing || !cleanupNeeded) 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();@@ -698,9 +700,8 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNif (!target || !current) throw new Error(t("native.cloud.notReady"));let result;try { result = await request("pairing", { method: "POST", body: {}, token: current.token }); } catch (error) {- const why = cloudUnreachableText(await refresh().catch(() => state()), target.origin);- throw why ? new Error(why) : error;- }+ const why = error?.status === 429 ? null : cloudUnreachableText(await refresh().catch(() => state()), target.origin); // the Admin's limit: never asked again here+ throw why ? Object.assign(new Error(why), { status: error?.status, opaque: error?.opaque, retryAfter: error?.retryAfter }) : error; }const pairing = parsePairingGrant(result, target.origin, now());if (!pairing) throw new Error("Invalid Cloud pairing response.");return pairing;@@ -967,6 +968,8 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN},/** Ends a sign-in that waits on this device, at the Admin. */revokeSaved: revoke,+ /** For cloud-accounts.mjs only, never a page: the active sign-in when it is kept in memory only, as its file would hold it. */+ memorySignIn: () => (unsaved && grant ? structuredClone(grant) : null),close() { closed = true; reset(); },};}diff --git a/electron/cloud-account.node-test.mjs b/electron/cloud-account.node-test.mjsindex ff69a9ba0c..dfd8a36a78 100644--- a/electron/cloud-account.node-test.mjs+++ b/electron/cloud-account.node-test.mjs@@ -123,6 +123,20 @@ test("a connection that fails while the Admin says My Cloud can't be reached sayawait assert.rejects(f.client.pairHome(), { message: "Cloud request failed." });});+test("a pairing refused while the Admin says why keeps its status; a 429 keeps its Retry-After and doesn't read the session again", async t => {+ const f = await fixture(t); await f.connect();+ const origin = "https://home-7f3k2.fly.dev", since = f.now - 6 * 60_000;+ f.entitlement = { plan: "pro", tier: "pro", status: "active", expiresAt: f.now + 86_400_000, version: 1 };+ f.cloud = { state: "ready", origin, pairingAvailable: true, unreachable: { cause: "host", since } };+ await f.client.refresh();+ f.pairing = { status: 503, body: { error: "unavailable" } };+ await assert.rejects(f.client.pairHome(), (error) => error.status === 503 && /hosting provider/.test(error.message));+ f.pairing = { status: 429, body: { error: "rate_limited" }, headers: { "retry-after": "120" } };+ const reads = f.requests.filter(row => row.route === "/api/cloud/desktop/session").length;+ await assert.rejects(f.client.pairHome(), (error) => error.status === 429 && error.retryAfter === 120);+ assert.equal(f.requests.filter(row => row.route === "/api/cloud/desktop/session").length, reads, "the Admin's limit is not met with another request");+});+test("a free trial and its AI credit come with a verified session, for display only; an Admin without them changes nothing", async t => {const f = await fixture(t); await f.connect();const DAY = 86_400_000, endsAt = f.now + 2 * DAY, origin = "https://home-7f3k2.fly.dev";@@ -609,10 +623,13 @@ test("a locked keychain never removes the saved Cloud sign-in: it is read again,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); }+ // Read again at 0:15, 0:45, 1:45 and 2:45: three failed reads by 0:45, but clearing also waits for two minutes.+ const offered = [];+ for (const delay of [30_000, 60_000, 60_000, 60_000]) { f.now += f.delay; f.tick(); await until(() => f.timer); assert.equal(f.delay, delay); offered.push(f.client.state().reset === true); }+ assert.deepEqual(offered, [false, false, false, true], "offered at the read at 2:45, not the third read at 0:45");assert.ok((await stat(file)).isFile(), "a locked sign-in is never removed");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");+ "said once, then once more when clearing it is offered, 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();@@ -620,6 +637,47 @@ test("a locked keychain never removes the saved Cloud sign-in: it is read again,assert.equal(f.client.state().account.email, "[email protected]");});+test("Clear pressed while a read of the saved sign-in is under way: a read that opens it keeps it, and signs in", async t => {+ const directory = await mkdtemp(join(tmpdir(), "omb-cloud-clear-race-"));+ t.after(() => rm(directory, { recursive: true, force: true }));+ const file = join(directory, "cloud-account.bin"), lock = { locked: true };+ let gate = null;+ const decrypt = async value => { await gate; return { shouldReEncrypt: false, result: Buffer.from(value).map(byte => byte ^ 0x55).toString() }; };+ const f = await fixture(t, { store: electron43Store(file, lock, decrypt) });+ await electron43Store(file).write(savedSignIn(f));+ await f.client.start();+ while (!f.client.state().reset) { f.now += f.delay; f.tick(); await until(() => f.timer); }+ // The keychain is unlocked, and the next read is decrypting as the person presses Clear.+ let release; gate = new Promise(resolve => { release = resolve; });+ lock.locked = false; f.now += f.delay; f.tick();+ const clearing = f.client.resetSaved();+ release();+ assert.equal((await clearing).status, "connected");+ assert.ok((await stat(file)).isFile(), "the saved sign-in that opened is kept");+ assert.ok(!f.requests.some(row => row.method === "DELETE"), "and never revoked");+});++test("Clear pressed while a read never finishes (a keychain prompt nobody answers): it clears after a short wait, and a sign-in can start", async t => {+ const directory = await mkdtemp(join(tmpdir(), "omb-cloud-clear-hung-"));+ t.after(() => rm(directory, { recursive: true, force: true }));+ const file = join(directory, "cloud-account.bin"), lock = { locked: true };+ let hang = null, release = () => {};+ const decrypt = async value => { if (hang) await hang; return { shouldReEncrypt: false, result: Buffer.from(value).map(byte => byte ^ 0x55).toString() }; };+ const f = await fixture(t, { store: electron43Store(file, lock, decrypt), readWaitMs: 50 });+ await electron43Store(file).write(savedSignIn(f));+ await f.client.start();+ while (!f.client.state().reset) { f.now += f.delay; f.tick(); await until(() => f.timer); }+ hang = new Promise(resolve => { release = resolve; }); lock.locked = false; f.now += f.delay; f.tick();+ const outcome = await Promise.race([f.client.resetSaved(), new Promise(resolve => setTimeout(() => resolve("still waiting"), 5_000))]);+ assert.notEqual(outcome, "still waiting", "Clear never waits on a read for ever");+ assert.equal(outcome.status, "signed-out");+ await assert.rejects(stat(file), { code: "ENOENT" });+ assert.equal((await f.client.begin()).status, "connecting", "the sign-in it was cleared for can start");+ // The prompt is answered at last: that late read changes nothing.+ release(); await new Promise(resolve => setTimeout(resolve, 50));+ assert.equal(f.client.state().status, "connecting");+});+test("a decrypt answer in a shape this app does not know is never taken for an unreadable sign-in", async t => {const directory = await mkdtemp(join(tmpdir(), "omb-cloud-shape-"));t.after(() => rm(directory, { recursive: true, force: true }));diff --git a/electron/cloud-accounts.mjs b/electron/cloud-accounts.mjsindex 3d635579c2..06f8b761bd 100644--- a/electron/cloud-accounts.mjs+++ b/electron/cloud-accounts.mjs@@ -20,7 +20,7 @@ const memoryStore = () => { let held = null; return { read: async () => held, wr* @param {{* active: { read(): Promise<any>, write(value: unknown): Promise<void> },* saved: { read(): Promise<any>, write(value: unknown): Promise<void> },- * client(): { state(): any, quiesce(): void, reload(): Promise<any>, signOut(): Promise<any>, revokeSaved(record: unknown): Promise<void> },+ * client(): { state(): any, quiesce(): void, reload(): Promise<any>, signOut(): Promise<any>, revokeSaved(record: unknown): Promise<void>, memorySignIn?(): any },* makeClient(options: { store: any, onState(state: any): void }): any,* origin: string,* holding?(): string | null,@@ -59,6 +59,8 @@ export function createCloudAccounts({ active, saved, client, makeClient, origin,if (raw.v !== VERSION || !Array.isArray(raw.accounts)) throw new Error("These saved sign-ins are from a newer version.");return raw.accounts.filter((record) => usable(record, origin));}+ /** The active sign-in as its file holds it; one kept in memory only (its file couldn't be written) is the client's. */+ const activeRecord = async () => client().memorySignIn?.() ?? await active.read().catch(() => null);const activeId = () => { const state = client().state(); return ["signed-out", "connecting"].includes(state?.status) ? null : state?.account?.id ?? null; };const remember = (list, without = activeId()) => {rows = list.filter((record) => record.account.id !== without).map((record) => ({ id: record.account.id, email: record.account.email, ...(record.expiresAt <= now() ? { signIn: true } : {}) }));@@ -73,7 +75,7 @@ export function createCloudAccounts({ active, saved, client, makeClient, origin,async function become(next, { list, keep = true }) {const leavingId = activeId();await naming(leavingId);- const current = await active.read().catch(() => null);+ const current = await activeRecord();const waiting = keep && usable(current, origin) ? current : null;await saved.write({ v: VERSION, accounts: [...list.filter((record) => record.account.id !== waiting?.account.id), ...(waiting ? [waiting] : [])] });client().quiesce();@@ -120,10 +122,13 @@ export function createCloudAccounts({ active, saved, client, makeClient, origin,const hold = holding();if (hold) return { outcome: hold };const next = list.find((record) => record.account.id !== id && record.expiresAt > now());- const current = await active.read().catch(() => null);+ const memory = client().memorySignIn?.() ?? null, current = memory ?? await active.read().catch(() => null);if (next) {- await become(next, { list: list.filter((record) => record.account.id !== id), keep: false });- if (usable(current, origin)) await client().revokeSaved(current).catch((error) => log(`accounts: signed out here only (${error?.message ?? error})`));+ let switched = false;+ // One kept in memory only ends at the Admin even when the switch fails: a failed switch reads the file again, and that+ // sign-in would be gone from this device with its token still good.+ try { await become(next, { list: list.filter((record) => record.account.id !== id), keep: false }); switched = true; }+ finally { if ((switched || memory) && usable(current, origin)) await client().revokeSaved(current).catch((error) => log(`accounts: signed out here only (${error?.message ?? error})`)); }} else {await naming(id);await leaving(id);diff --git a/electron/cloud-accounts.node-test.mjs b/electron/cloud-accounts.node-test.mjsindex eeb1d4ecc9..e5090e97c4 100644--- a/electron/cloud-accounts.node-test.mjs+++ b/electron/cloud-accounts.node-test.mjs@@ -195,6 +195,40 @@ test("sign out of the active account: gone from this device and ended at the Admassert.ok(!JSON.stringify(w.activeFile).includes(tokenOf("b")));});+/** Account b waiting, and account a in use but kept in memory only, as the client keeps it after Clear and sign in again+ * when the new sign-in couldn't be saved: nothing of it on disk. */+async function inMemory(t) {+ const w = await world(t);+ w.activeFile = w.grant("b");+ await w.boot();+ await w.addByCode("a");+ assert.equal(w.signedInAs(), "acct-a");+ w.activeFile = null; w.client.memorySignIn = () => w.grant("a");+ return w;+}++test("a sign-in kept in memory only: a switch keeps it waiting here, never lost", async (t) => {+ const w = await inMemory(t);+ assert.deepEqual(await w.ring.switchTo("acct-b"), { outcome: "switched" });+ assert.equal(w.signedInAs(), "acct-b");+ assert.deepEqual(ids(w), ["acct-a"]);+ assert.equal(w.savedFile.accounts.find((entry) => entry.account.id === "acct-a")?.token, tokenOf("a"));+});++test("a sign-in kept in memory only: signing out of it ends its token at the Admin", async (t) => {+ const w = await inMemory(t);+ assert.deepEqual(await w.ring.signOut("acct-a"), { outcome: "signed-out" });+ assert.equal(w.signedInAs(), "acct-b");+ assert.deepEqual(w.revoked, [tokenOf("a")], "never left orphaned");+});++test("a sign-in kept in memory only, whose file still can't be written: signing out fails here, and still ends its token", async (t) => {+ const w = await inMemory(t);+ w.failActive = true;+ await assert.rejects(w.ring.signOut("acct-a"), /no keychain/);+ assert.deepEqual(w.revoked, [tokenOf("a")], "the switch failed and the sign-in in memory is gone: its token is not left good");+});+test("sign out of the last account: signed out, with nothing left on this device", async (t) => {const w = await world(t);w.activeFile = w.grant("a");diff --git a/electron/cloud-signin.d.mts b/electron/cloud-signin.d.mtsindex ee0434abaf..2a37b4018d 100644--- a/electron/cloud-signin.d.mts+++ b/electron/cloud-signin.d.mts@@ -16,6 +16,8 @@ export interface CloudSignInBlocked { outcome: "blocked"; reason: CloudSignInBloexport 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 const READ_WAIT_MS: number;+export declare function settledWithin(promise: Promise<unknown>, ms: number): Promise<void>;+export declare function resetOffered(input: { 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 7b987a9ceb..46561ef32d 100644--- a/electron/cloud-signin.mjs+++ b/electron/cloud-signin.mjs@@ -74,10 +74,20 @@ export function signInBlock({ closed, restoring, issued, grant, cleanupNeeded, creturn 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. */+/** A saved sign-in that can't be read is never removed by itself (a keychain or keyring may only be locked or not up yet, a+ * file only held for a moment): clearing it is offered only after RESET_AFTER_TRIES failed reads AND RESET_AFTER_MS, on every+ * platform. A key that can never open it (Windows after a reinstall) is removed by itself already, so this is the rare rest. */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;+export const resetOffered = ({ failures, since, now }) => failures >= RESET_AFTER_TRIES && now - since >= RESET_AFTER_MS;++/** How long Clear waits for a read of the saved sign-in already under way (an unanswered keychain prompt, a keyring that+ * hangs) before it clears anyway. */+export const READ_WAIT_MS = 5_000;+/** Resolves once `promise` settles, or after `ms`, whichever is first; never rejects. */+export const settledWithin = (promise, ms) => new Promise((done) => {+ const timer = setTimeout(done, ms); timer.unref?.();+ Promise.resolve(promise).then(done, done).finally(() => clearTimeout(timer));+});/** 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. */diff --git a/electron/cloud-signin.node-test.mjs b/electron/cloud-signin.node-test.mjsindex 8f4c8d8f66..2d2f4fccdf 100644--- a/electron/cloud-signin.node-test.mjs+++ b/electron/cloud-signin.node-test.mjs@@ -209,37 +209,57 @@ function stuckStore({ unreadable, fails }) {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; } };+const later = { pending: null, delay: 0 };+const timers = { setTimer: (callback, delay) => { later.pending = callback; later.delay = delay; return 1; }, clearTimer: () => { later.pending = null; } };+/** The saved sign-in is read again when its timer falls due, until clearing it is offered: the times those reads came at. */+async function readUntilOffered(f) {+ const at = [];+ while (!f.client.state().reset) {+ assert.ok(later.pending && at.length < 10); f.now += later.delay; at.push(f.now);+ const read = later.pending; later.pending = null; read(); await until(() => later.pending);+ }+ return at;+}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.+ const start = f.now;+ // Nothing is removed by itself, and clearing isn't offered at once: a file held for a moment at launch (an antivirus scan)+ // would read on the next try.+ assert.deepEqual(f.client.state(), { status: "unavailable", message: "restore-failed" });+ assert.deepEqual(await f.client.emailStart("[email protected]"), { outcome: "blocked", reason: "saved" });+ assert.ok(later.pending, "it is read again meanwhile");+ // Three failed reads by 0:45, and two minutes: offered at the read at 2:45.+ assert.deepEqual((await readUntilOffered(f)).map(at => (at - start) / 1000), [15, 45, 105, 165]);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.equal(f.client.memorySignIn()?.token, accessToken, "the account switcher can take it from memory");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.equal(seen.reads, 5);assert.deepEqual(await f.client.signOut(), { status: "signed-out" }, "signing out of it needs nothing on disk");+ assert.equal(f.client.memorySignIn(), null);});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, undefined);+ await readUntilOffered(f);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"]);+ assert.equal(seen.reads, 5);});test("a sign-in under way in the browser: the email code says so, and cancelling it lets the code go", async t => {diff --git a/electron/fixtures/cloud-account.mjs b/electron/fixtures/cloud-account.mjsindex 5f19b680db..6adf6cc33b 100644--- a/electron/fixtures/cloud-account.mjs+++ b/electron/fixtures/cloud-account.mjs@@ -31,6 +31,8 @@ export async function fixture(t, options = {}) {return send(f.disk.status, f.disk.body);}if (req.url === "/api/cloud/desktop/services/x" && req.headers.authorization === `Bearer ${accessToken}`) return send(f.x.status, f.x.body);+ // My Cloud's pairing, only when a test sets an answer (`headers`: e.g. a 429's Retry-After).+ if (f.pairing && req.url === "/api/cloud/desktop/pairing" && req.method === "POST") { res.writeHead(f.pairing.status, { "content-type": "application/json", ...f.pairing.headers }); return res.end(JSON.stringify(f.pairing.body)); }if (/^\/api\/cloud\/desktop\/teams\/[^/]+\/pairing$/.test(req.url) && req.method === "POST" && req.headers.authorization === `Bearer ${accessToken}`) return send(f.teamPairing.status, f.teamPairing.body);if (req.url === "/api/cloud/desktop/services/pages" && req.headers.authorization === `Bearer ${accessToken}`) return send(f.pages.status, f.pages.body);if (req.url === "/api/cloud/desktop/moved" && req.method === "POST" && req.headers.authorization === `Bearer ${accessToken}`) return send(f.moved.status, f.moved.body);diff --git a/electron/home-pairing.mjs b/electron/home-pairing.mjsnew file mode 100644index 0000000000..61f685737c--- /dev/null+++ b/electron/home-pairing.mjs@@ -0,0 +1,84 @@+// When the desktop window asks the Admin for the next sign-in code for My Cloud (home-window.mjs), and when its screen names the+// address this computer couldn't connect to.+//+// Every look once asked for a code at once (the screen mounting, the window coming to the front, each session read), so a page+// that didn't load from here, or an Admin refusing, ran hundreds of requests. A short first wait already stops that loop, so+// one passing failure costs a few seconds, and the waits grow from there.++/** The waits before the next code, after a code whose page didn't load or one the Admin refused. */+export const PAIR_RETRY_MS = Object.freeze([3_000, 10_000, 30_000, 60_000, 120_000, 300_000]);+/** The least time between two codes asked for one Cloud, whatever else happens: Try again, a Cloud that answers again. */+export const PAIR_FLOOR_MS = 3_000;+/** The most an Admin's 429 holds the next code, whatever its Retry-After says. */+export const PAIR_LIMIT_MS = 5 * 60_000;+/** How long My Cloud's page must have kept failing to connect from here (a failed page load at least this long after the+ * first) before the screen names its address. */+export const NETWORK_HINT_MS = 60_000;++/** Chromium's net errors for a name it could not find (net/base/net_error_list.h): NAME_NOT_RESOLVED,+ * NAME_RESOLUTION_FAILED and the DNS range. */+export const nameNotFound = (code) => code === -105 || code === -137 || (code <= -800 && code > -900);+/** TIMED_OUT, CONNECTION_CLOSED, _RESET, _REFUSED, _FAILED, SSL_PROTOCOL_ERROR, ADDRESS_UNREACHABLE,+ * SSL_VERSION_OR_CIPHER_MISMATCH, CONNECTION_TIMED_OUT, PROXY_CONNECTION_FAILED, NETWORK_ACCESS_DENIED. */+const CONNECT_FAILED = new Set([-7, -100, -101, -102, -104, -107, -109, -113, -118, -130, -138]);+/** A page load this computer couldn't connect for (a name, a refused or timed-out connection, TLS or a certificate): what a+ * VPN, firewall or DNS filter does. Not INTERNET_DISCONNECTED or NETWORK_CHANGED: no network here at all is something else. */+export const connectionError = (code) => nameNotFound(code) || CONNECT_FAILED.has(code) || (code <= -200 && code > -300);++const hostOf = (origin) => { try { return new URL(origin).host || null; } catch { return null; } };++/**+ * The window's waits for one Cloud at a time. `hold`: the next code for `origin` waits until `until` (`page`: its page didn't+ * load; `limited`: the Admin answered 429; `down`: a look found it not answering since; `early`: a look that found it answering+ * again already ended a wait in this run of failures, which it does once until a page loads). `asked`: when a code was last+ * asked for, and for which Cloud (PAIR_FLOOR_MS). `unreached`: since when its page has failed to connect from here, and+ * `named` once a page failed so again NETWORK_HINT_MS later, until a page of it loads.+ */+export function createPairWait({ now = Date.now } = {}) {+ let hold = null, unreached = null, asked = null;+ const floor = (origin) => (asked?.origin === origin ? asked.at + PAIR_FLOOR_MS : 0);+ const until = (origin) => Math.max(hold?.origin === origin ? hold.until : 0, floor(origin));+ const held = (origin) => now() < until(origin);+ return {+ held,+ /** When the code for `origin` may be asked for again, while it waits. */+ until: (origin) => (held(origin) ? until(origin) : null),+ /** The Admin's own 429 holds `origin`: the screen says when the app tries again. */+ limited: (origin) => held(origin) && hold?.origin === origin && hold.limited && now() < hold.until,+ /** A code for `origin` is asked for now. */+ asking(origin) { asked = { origin, at: now() }; },+ /** A code for `origin` whose page didn't load (`page`), or one the Admin refused (`error`). */+ hold(origin, { error = null, page = false } = {}) {+ const same = hold?.origin === origin, tries = same ? hold.tries + 1 : 1;+ const limited = error?.status === 429;+ const wait = limited && Number.isFinite(error.retryAfter) ? Math.min(Math.max(error.retryAfter, 0) * 1000, PAIR_LIMIT_MS) : 0;+ hold = { origin, tries, page, limited, down: false, early: same && hold.early,+ until: now() + Math.max(PAIR_RETRY_MS[Math.min(tries, PAIR_RETRY_MS.length) - 1], wait) };+ },+ /** What the window's look at `origin` answered: "yes", "asleep", "failing" (an error, so it connected) or "no" (nothing in+ * time). A page's wait ends once it answers after not answering (it came back), once per run of failures. */+ looked(origin, answer) {+ if (hold?.origin !== origin || !hold.page || hold.limited) return;+ if (answer !== "yes") hold.down = true;+ else if (hold.down && !hold.early) { hold.until = 0; hold.early = true; }+ },+ /** The person pressed Try again: no wait holds them, except the Admin's own 429 and PAIR_FLOOR_MS, after which the screen+ * asks by itself. */+ pressed() { if (hold && !hold.limited) hold.until = 0; },+ /** A page of `origin` loaded: the waits start again. */+ loaded(origin) {+ if (hold?.origin === origin) hold = null;+ if (unreached?.origin === origin) unreached = null;+ },+ /** `origin`'s page failed to load with Chromium's net error `code`: its address is named once a page fails so again+ * NETWORK_HINT_MS after the first. Looks alone never name it. */+ failedLoad(origin, code) {+ if (!connectionError(code)) return;+ if (unreached?.origin !== origin) unreached = { origin, since: now(), named: false };+ else if (now() - unreached.since >= NETWORK_HINT_MS) unreached.named = true;+ },+ /** `origin`'s host once its page has kept failing to connect from here (failedLoad), else null. */+ unreachedHost: (origin) => (unreached?.origin === origin && unreached.named ? hostOf(origin) : null),+ clear() { hold = null; unreached = null; asked = null; },+ };+}diff --git a/electron/home-window-pairing.node-test.mjs b/electron/home-window-pairing.node-test.mjsindex 40c406d640..d114cc55fa 100644--- a/electron/home-window-pairing.node-test.mjs+++ b/electron/home-window-pairing.node-test.mjs@@ -1,25 +1,33 @@-// 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.+// A code from the Admin for My Cloud is never asked for in a loop (home-pairing.mjs PAIR_RETRY_MS): not when its page won't+// load from this computer, and not when the Admin answers 429. One passing failure costs seconds, Try again is never held by+// that wait, and the screen names the address only after its page has failed to connect from here for about a minute.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";+import { connectionError } from "./home-pairing.mjs";+import { NETWORK_HINT_MS, PAIR_FLOOR_MS, PAIR_LIMIT_MS, PAIR_RETRY_MS, RETRY_MS } from "./home-window.mjs";+import { CLOUD, connected, 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 () => {+/** Moves the clock a second at a time (the screen's own timer runs as it falls due) until `check()`: the ms that took, or null. */+async function until(w, check, most = 600_000) {+ for (let t = 1_000; t <= most; t += 1_000) { await w.later(1_000); if (check()) return t; }+ return null;+}+const refused = (status, more = {}) => Object.assign(new Error("Cloud request failed."), { status, ...more });++test("My Cloud's page that doesn't load from here: one code from the Admin, not one per look, and the waits grow", 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.+ // The screen 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" });+ assert.deepEqual(w.home.view(), { screen: "offline" }, "no address named for a page that failed a moment ago");await w.later(PAIR_RETRY_MS[0]);await w.home.retry();- assert.equal(w.pairs, 2, "asked again once the wait is over");+ assert.equal(w.pairs, 2, "asked again once the first 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");@@ -30,21 +38,186 @@ test("My Cloud's page that never loads from here: one code from the Admin, not oassert.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 }) } });+test("one passing failure costs a few seconds, and Try again is never held by the wait", async () => {+ const w = world({ cloud: { signedIn: false } });+ await w.home.show();+ w.home.failed(w.url, -102); await w.later(0);+ const opened = await until(w, () => w.pairs >= 2);+ assert.ok(opened !== null && opened <= PAIR_RETRY_MS[0], `opened ${opened} ms after the failure`);+ assert.ok(PAIR_RETRY_MS[0] <= 5_000);++ // Two failures in a row wait 10 s; the page failed a few seconds after its code.+ const pressed = world({ cloud: { signedIn: false } });+ await pressed.home.show();+ pressed.home.failed(pressed.url, -102); await pressed.later(0);+ assert.notEqual(await until(pressed, () => pressed.pairs >= 2), null);+ await pressed.later(PAIR_FLOOR_MS);+ pressed.home.failed(pressed.url, -102); await pressed.later(0);+ await pressed.home.retry();+ assert.equal(pressed.pairs, 2, "the screen's own look still waits");+ await pressed.home.retry({ pressed: true });+ assert.equal(pressed.pairs, 3, "Try again asks for the code at once");+});++test("Try again is never a loop: codes for one Cloud stay PAIR_FLOOR_MS apart, and a press inside that waits for its end", async () => {+ const w = world({ cloud: { signedIn: false, pairError: refused(502) } });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();+ await w.later(500);+ await w.home.retry({ pressed: true });+ assert.equal(w.pairs, 1, "too soon after the last code");+ assert.equal(await until(w, () => w.pairs >= 2), PAIR_FLOOR_MS - 500 + 500, "asked by itself once that floor ends, no second press needed");+ // A held key, or a page asking in a loop: ten presses a second for a minute.+ const before = w.pairs, start = w.clock;+ for (let t = 0; t < 60_000; t += 100) { await w.home.retry({ pressed: true }); await w.later(100); }+ assert.ok(w.pairs - before <= Math.ceil((w.clock - start) / PAIR_FLOOR_MS) + 1, `${w.pairs - before} codes in a minute`);+});++test("a Cloud whose look flaps between no answer and an answer ends a wait early once, not on every flap", async () => {+ const w = world({ cloud: { signedIn: false } });+ await w.home.show();+ // Every other look at /api/health gets no answer.+ Object.defineProperty(w.cloud, "down", { get() { return w.fetched.filter(([url]) => url === "/api/health").length % 2 === 1; }, set() {} });+ // Every page it is sent to fails to load.+ let went = 0;+ for (let t = 0; t < 40 * 60_000; t += 500) {+ if (w.went.length > went) { went = w.went.length; if (w.url.startsWith("https:")) w.home.failed(w.url, -7); }+ await w.later(500);+ }+ // Main asked 11 times in these 40 minutes; an early end on every flap asked about 400 times.+ assert.ok(w.pairs > 5 && w.pairs <= 16, `${w.pairs} codes in 40 minutes`);+});++test("a Cloud that restarted: the look that finds it answering again opens it, whatever the wait", async () => {+ const w = world({ cloud: { signedIn: false } });+ await w.home.show();+ // Two pages in a row that didn't load: the third failure waits PAIR_RETRY_MS[2].+ for (let i = 1; i <= 2; i++) {+ w.home.failed(w.url, -102); await w.later(0);+ assert.notEqual(await until(w, () => w.pairs > i), null);+ }+ w.home.failed(w.url, -102); w.cloud.down = true; await w.later(0);+ const failedAt = w.clock;+ await w.later(RETRY_MS[0]);+ assert.equal(w.home.view().screen, "offline", "a look finds it not answering");+ w.cloud.down = false;+ const opened = await until(w, () => w.pairs > 3);+ assert.ok(opened !== null && opened <= RETRY_MS[1], `opened ${opened} ms after it answered again`);+ assert.ok(w.clock - failedAt < PAIR_RETRY_MS[2]);+});++test("an Admin that refuses (a restart): Try again asks at once; its 429 holds at most a few minutes and says until when", async () => {+ const w = world({ cloud: { signedIn: false, pairError: refused(502) } });+ await w.home.show();+ assert.equal(w.pairs, 1);+ assert.notEqual(await until(w, () => w.pairs >= 2), null);+ // Refused twice: the next code waits PAIR_RETRY_MS[1].+ await w.later(PAIR_FLOOR_MS);+ await w.home.retry();+ assert.equal(w.pairs, 2, "not every look");+ await w.home.retry({ pressed: true });+ assert.equal(w.pairs, 3, "the person's press");++ const limited = world({ cloud: { signedIn: false, pairError: refused(429, { retryAfter: 7200 }) } });+ await limited.home.show();+ const at = limited.clock;+ assert.equal(limited.pairs, 1);+ assert.deepEqual(limited.home.view(), { screen: "offline", retryAt: at + PAIR_LIMIT_MS }, "the screen says when it tries again");+ assert.ok(PAIR_LIMIT_MS <= 5 * 60_000);+ for (let i = 0; i < 10; i++) { await limited.home.changed(); await limited.home.retry({ pressed: true }); await limited.later(1_000); }+ assert.equal(limited.pairs, 1, "nothing asks again before the Admin's wait, not even Try again");+ limited.cloud.pairError = null;+ const opened = await until(limited, () => limited.pairs >= 2);+ assert.equal(at + PAIR_LIMIT_MS <= limited.clock && limited.clock <= at + PAIR_LIMIT_MS + 1_000, true, `asked again ${opened} ms later`);+});++test("My Cloud opened before it is home: a page of it that loads starts the waits again", async () => {+ const w = world({ journal: null, cloud: { signedIn: false } });+ await w.home.openCloud();+ assert.equal(w.pairs, 1);+ for (let round = 0; round < 3; round++) {+ w.home.failed(w.url, -102); await w.later(0);+ const before = w.pairs;+ const next = await until(w, () => w.pairs > before);+ assert.ok(next !== null && next <= PAIR_RETRY_MS[0], `round ${round}: the next code after ${next} ms`);+ w.home.navigated(`${CLOUD}/`);+ }+});++test("another account taking over, or signing out and in again, drops the wait", async () => {+ const w = world({ cloud: { signedIn: false } });+ await w.home.show();+ w.home.failed(w.url, -102); await w.later(0);+ w.home.accountLeaving();+ await w.home.show();assert.equal(w.pairs, 2);++ const again = world({ cloud: { signedIn: false } });+ await again.home.show();+ // Five pages in a row that didn't load: the next code waits minutes.+ for (let i = 1; i <= 5; i++) { again.home.failed(again.url, -102); await again.later(0); assert.notEqual(await until(again, () => again.pairs > i), null); }+ again.home.failed(again.url, -102); await again.later(PAIR_FLOOR_MS);+ await again.home.retry();+ assert.equal(again.pairs, 6, "held");+ again.state = { status: "signed-out" }; await again.home.changed();+ again.state = connected(); await again.home.changed();+ await again.home.retry();+ assert.equal(again.pairs, 7, "signed in again: asked at once");});-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 } });+const host = (w) => w.home.view().host ?? null;++test("the screen names the address only when the page fails to connect again a minute after it first did", async () => {+ const w = world({ cloud: { signedIn: false } });await w.home.show();+ w.cloud.down = true; w.home.failed(w.url, -102); await w.later(0);+ assert.equal(await until(w, () => host(w) !== null, 3 * NETWORK_HINT_MS), null, "a minute and more of failed looks alone never names it");+ // It answers its look again, and its page still doesn't load: the address is named.+ w.cloud.down = false;+ assert.notEqual(await until(w, () => w.pairs >= 2), null);+ w.home.failed(w.url, -102); await w.later(0);assert.deepEqual(w.home.view(), { screen: "offline", cause: "network", host: "omb-t-1.fly.dev" });- assert.equal(w.pairs, 0);+ // It answers again, while the Admin refuses its code: the screen stays, without the address.+ w.cloud.pairError = refused(502);+ assert.notEqual(await until(w, () => w.pairs >= 3), null);+ assert.equal(w.home.view().screen, "offline");+ assert.equal(host(w), null, "a look that got an answer doesn't name it");+ // A page of it that loads forgets it.+ w.home.navigated(`${CLOUD}/`); w.home.failed(`${CLOUD}/`, -102); await w.later(0);+ assert.equal(host(w), null);++ const soon = world({ cloud: { signedIn: false } });+ await soon.home.show();+ soon.home.failed(soon.url, -102); await soon.later(0);+ assert.notEqual(await until(soon, () => soon.pairs >= 2), null);+ soon.cloud.down = true; soon.home.failed(soon.url, -102); await soon.later(0);+ assert.equal(host(soon), null, "a second failure seconds later is not this computer being blocked");+});++test("no address is named for a Cloud that only fails its look, answers 5xx, or a computer with no network", async () => {+ const quiet = world({ cloud: { down: true } });+ await quiet.home.show();+ await until(quiet, () => false, 3 * NETWORK_HINT_MS);+ assert.equal(quiet.home.view().screen, "offline");+ assert.equal(host(quiet), null, "a look that fails or is slow is not this computer being blocked");++ const failing = world({ cloud: { signedIn: false } });+ await failing.home.show();+ failing.cloud.health = 502; failing.home.failed(failing.url, -102); await failing.later(0);+ await until(failing, () => false, 3 * NETWORK_HINT_MS);+ assert.equal(failing.home.view().screen, "offline");+ assert.equal(host(failing), null, "a Cloud answering 5xx (restarting, updating) was reached");++ for (const code of [-106, -21]) {+ const offline = world({ cloud: { signedIn: false } });+ await offline.home.show();+ offline.cloud.down = true; offline.home.failed(offline.url, code); await offline.later(0);+ await until(offline, () => false, 3 * NETWORK_HINT_MS);+ assert.equal(host(offline), null, `net error ${code}`);+ }+});++test("Chromium's errors that name this computer's connection: names, refused, timed out, TLS and certificates", () => {+ for (const code of [-105, -137, -802, -102, -101, -118, -7, -107, -113, -200, -202, -138, -130]) assert.equal(connectionError(code), true, String(code));+ for (const code of [-106, -21, -3, -2, -300, 0]) assert.equal(connectionError(code), false, String(code));});diff --git a/electron/home-window.d.mts b/electron/home-window.d.mtsindex 05fee28619..522e808f9d 100644--- a/electron/home-window.d.mts+++ b/electron/home-window.d.mts@@ -6,8 +6,9 @@ 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 }- /** `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 }+ /** `network`: My Cloud's page has failed to connect from this computer to its address (`host`) for about a minute while the+ * Admin knows of nothing wrong. `retryAt`: the Admin asked this app to wait (429), and it tries again by itself then. */+ | { screen: "offline"; reason?: string; cause?: "host" | "no_answer" | "network"; host?: string; retryAt?: number }| { 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 }@@ -21,8 +22,9 @@ export interface HomeBridge {/** This computer's screen only. */state(): Promise<HomeView>;onState(callback: (view: HomeView) => void): () => void;- /** This computer's screen only: look again now. */- retry(): Promise<HomeView>;+ /** This computer's screen only: look again now. `pressed`: the person pressed Try again, which no wait for the next+ * sign-in code holds except the Admin's own 429. */+ retry(pressed?: boolean): Promise<HomeView>;/** This computer's screen only, once the person said yes there: the Cloud it shows leaves their list (absent: an older app). */remove?(): Promise<import("./cloud-account.mjs").CloudRemoveOutcome>;/** This device's MausBot Cloud sign-in, again; on My Cloud's page only from the person's click. */@@ -63,6 +65,10 @@ export declare const TEAM_RENEW_RETRY_MS: number;export declare const FRESH_MS: number;export declare const NAME_WAIT_MS: number;export declare const NAME_RETRY_MS: readonly number[];+export declare const PAIR_RETRY_MS: readonly number[];+export declare const PAIR_LIMIT_MS: number;+export declare const PAIR_FLOOR_MS: number;+export declare const NETWORK_HINT_MS: number;export function nameNotFound(code: number): boolean;export function createReadyClock(input?: { store?: { read(): unknown; write(value: unknown): void } | null; now?(): number }): { seen(state: unknown): void; fresh(origin: string | null): boolean };export function splashText(status: "opening" | "waking", name?: string | null, t?: (key: string, params?: Record<string, string | number>) => string): string;@@ -94,7 +100,7 @@ export interface HomeWindow {placeOrigin(): string | null;current(): Home;shown(): HomePlace | null;- retry(): Promise<unknown>;+ retry(input?: { pressed?: boolean }): Promise<unknown>;signIn(): Promise<void>;repair(): Promise<void>;changed(): Promise<void>;diff --git a/electron/home-window.mjs b/electron/home-window.mjsindex db65cee1e6..2537da26b7 100644--- a/electron/home-window.mjs+++ b/electron/home-window.mjs@@ -12,8 +12,11 @@ import { cloudHomeConnectUrl, cloudSetupOf, cloudUnreachableCause, cloudUnreachaimport { cloudMachine, cloudState, myCloudOf, otherOwnClouds, ownCloud } from "./cloud-list.mjs";import { asleepAnswer, BACKGROUND_HEADERS, openSleepingCloud, SIGNED_IN_MS } from "./cloud-power.mjs";import nativeText from "./native-text.cjs";+import { createPairWait, nameNotFound } from "./home-pairing.mjs";import { awayIn, parseJournal, sameCloud } from "./one-home.mjs";+export { nameNotFound, NETWORK_HINT_MS, PAIR_FLOOR_MS, PAIR_LIMIT_MS, PAIR_RETRY_MS } from "./home-pairing.mjs";+export const HOME_SCREEN_PATH = "/home";/** The look at an awake My Cloud before the window moves there: under 3 s, so the offline screen shows within 3 s. */export const LOOK_MS = 2_500;@@ -21,9 +24,6 @@ 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@@ -31,9 +31,6 @@ export const PAIR_RETRY_MS = Object.freeze([15_000, 30_000, 60_000, 120_000, 300export const FRESH_MS = 15 * 60_000;export const NAME_WAIT_MS = 10 * 60_000;export const NAME_RETRY_MS = Object.freeze([5_000, 10_000, 20_000, 40_000, 60_000]);-/** Chromium's net errors for a name it could not find (net/base/net_error_list.h): NAME_NOT_RESOLVED,- * NAME_RESOLUTION_FAILED and the DNS range. */-export const nameNotFound = (code) => code === -105 || code === -137 || (code <= -800 && code > -900);/** A new version of My Cloud's page waits for this long without typing before the window reloads it. */export const QUIET_MS = 30_000;export const VERSION_EVERY_MS = 60_000;@@ -67,7 +64,6 @@ 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. */@@ -251,14 +247,8 @@ 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 next sign-in code's wait, and since when My Cloud's page failed to connect from here (home-pairing.mjs). */+ const waits = createPairWait({ now });/** 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;@@ -283,8 +273,12 @@ export function createHomeWindow(deps) {const still = (place) => shown?.kind === place.kind && shown.id === place.id && shown.origin === place.origin;const clearRenewal = () => { if (renewal) timers.clear(renewal); renewal = null; };+ /** The account the pairing waits were for: signed out, or another account, they start again. */+ let waitsFor = null;async function refresh() {clock.seen(state());+ const who = signedOut() ? null : state()?.account?.id ?? null;+ if (who !== waitsFor) { waits.clear(); waitsFor = who; }const kept = parseJournal(journal());let frozenCloud = null, frozenPlace = null;if (!awayIn(kept)) {@@ -364,17 +358,20 @@ export function createHomeWindow(deps) {}/** 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) {+ * `unreached`: My Cloud's address, named once its page has kept failing to connect from here (home-pairing.mjs) while the+ * Admin knows of nothing wrong. `held`: the origin whose next code waits: the screen looks again when that wait ends,+ * and says when for the Admin's own 429. */+ function offline(token, unreached = null, held = null) {if (!wanted(token)) return;const cause = otherPlace(opening) ? null : cloudUnreachableCause(state(), cloudOrigin());- const host = !cause && unreached && !otherPlace(opening) ? originHost(unreached) : null;- toScreen({ screen: "offline", ...(cause ? { reason: cloudUnreachableText(state(), cloudOrigin()), cause } : host ? { cause: "network", host } : {}) });- later();+ const host = !cause && unreached && !otherPlace(opening) ? waits.unreachedHost(unreached) : null;+ const until = held ? waits.until(held) : null, retryAt = held && waits.limited(held) ? until : null;+ toScreen({ screen: "offline", ...(cause ? { reason: cloudUnreachableText(state(), cloudOrigin()), cause } : host ? { cause: "network", host } : {}), ...(retryAt ? { retryAt } : {}) });+ later(RETRY_MS, undefined, until === null ? Infinity : Math.max(0, until - now()));}- function later(delays = RETRY_MS, count = () => tries++) {+ function later(delays = RETRY_MS, count = () => tries++, atMost = Infinity) {clearRetry();- const ms = delays[Math.min(count(), delays.length - 1)];+ const ms = Math.min(delays[Math.min(count(), delays.length - 1)], atMost);retry = timers.set(() => { retry = null; if (screen) void show(); }, ms);}/** Whether the window's own resolver finds `origin`'s name now, its host cache bypassed. */@@ -426,7 +423,8 @@ export function createHomeWindow(deps) {signal: AbortSignal.timeout(LOOK_MS), headers: { accept: "application/json", ...BACKGROUND_HEADERS } });await response.body?.cancel?.().catch(() => {});if (asleepAnswer(response)) return "asleep";- return response.type === "opaqueredirect" || response.status < 500 ? "yes" : "no";+ // A 5xx is an answer: this computer reached it, and something there is failing (a restart, an update).+ return response.type === "opaqueredirect" || response.status < 500 ? "yes" : "failing";} catch { return "no"; }}/** The window's own session there: `{ expiresAt }` (null when the server names no end), or null when it has none. */@@ -506,7 +504,8 @@ export function createHomeWindow(deps) {if (!asleep) {if (naming) await forgetNames();const look = await answers(origin);- if (look === "no") return unreachable(place, token);+ waits.looked(origin, look);+ if (look === "no" || look === "failing") return unreachable(place, token);if (look === "asleep" && otherPlace(place)) return offline(token);if (look === "asleep") { power.hold(); asleep = true; if (wanted(token)) say("waking"); }}@@ -517,16 +516,17 @@ 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);+ if (waits.held(origin)) return signInNeeded() ? toScreen({ screen: "signin" }) : offline(token, null, origin);+ waits.asking(origin);try { grant = await pair(place); } catch (error) {if (error?.gone && wanted(token)) return gone(place);- holdPairing(origin, { error });+ waits.hold(origin, { error });log(`home: no sign-in code for ${otherPlace(place) ? place.name : "My Cloud"} (${error?.message ?? error})`);}if (!wanted(token)) return;if (!grant) {if (signInNeeded()) return toScreen({ screen: "signin" });- return offline(token);+ return offline(token, null, origin);}}// My Cloud opened before the move made it home is a saved server the window shows, as the Server menu opens one.@@ -743,8 +743,9 @@ export function createHomeWindow(deps) {current: () => home,/** The place the window was last sent to: My Cloud, or a team's or another own Cloud (`{ kind: "team" | "own", id, name, origin }`). */shown: () => shown,- /** The person asked again (the screen's timer, back online, or the window focused). */- retry: () => show(),+ /** The screen asked again (as it opens, back online, or the window focused); `pressed`: the person pressed Try again, which+ * no wait holds except the Admin's own 429. */+ retry: ({ pressed = false } = {}) => { if (pressed) waits.pressed(); return show(); },/** The screen's one button: this device's MausBot Cloud sign-in, again. A sign-in already open in the browser opens* again; one with an account My Cloud isn't (`other`) ends first, so the browser can sign in another; one that is still* good only looks again. */@@ -778,6 +779,7 @@ export function createHomeWindow(deps) {profileShown = null;clearRetry(); clearRenewal();asked = null; naming = null; shown = null; opening = null; screen = null; status = null;+ waits.clear();away = away || !shows(localOrigin());},/** A response the window got (Electron's webRequest): a 401 from the place's API means its session ended. */@@ -792,6 +794,9 @@ export function createHomeWindow(deps) {/** The main frame went somewhere: the place's own sign-in page means its session ended; any other page of it is* the version the window now shows. */navigated(url) {+ // A page of the place, or of My Cloud asked for before it is home, loaded: the waits for its next code start again.+ const page = /^https?:/.test(url) ? originOf(url) : null;+ if (page && (page === placeOrigin() || page === readyCloudOrigin(state()))) waits.loaded(page);// Only a page that loaded counts: an error page (chrome-error:) is the load that failed().if (asked && /^https?:/.test(url)) {const at = originOf(url);@@ -802,7 +807,6 @@ 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;@@ -822,7 +826,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 });+ waits.hold(at, { page: true }); waits.failedLoad(at, code);const token = ++opens;void unreachable(otherPlace(shown) && at === place ? shown : { kind: "cloud", origin: at }, token, nameNotFound(code));return true;@@ -860,7 +864,7 @@ export function installHomeWindowIpc({ ipcMain, homeWindow, cloudPage }) {};const screenPage = (event) => homeWindow.screenPage(event);ipcMain.handle("home:state", from("home:state", screenPage, () => homeWindow.view()));- ipcMain.handle("home:retry", from("home:retry", screenPage, () => homeWindow.retry().then(() => homeWindow.view())));+ ipcMain.handle("home:retry", from("home:retry", screenPage, (pressed) => homeWindow.retry({ pressed: pressed === true }).then(() => homeWindow.view())));ipcMain.handle("home:remove", from("home:remove", screenPage, () => homeWindow.remove()));ipcMain.handle("home:sign-in", from("home:sign-in", (event) => screenPage(event) || cloudPage(event) === "cloud" || (homeWindow.homePage(event) && homeWindow.shown()?.kind === "own"), () => homeWindow.signIn()));ipcMain.handle("home:repair", from("home:repair", (event) => homeWindow.homePage(event), () => homeWindow.repair()));diff --git a/electron/home-window.node-test.mjs b/electron/home-window.node-test.mjsindex 3a4cbde682..ac71ef5f22 100644--- a/electron/home-window.node-test.mjs+++ b/electron/home-window.node-test.mjs@@ -430,6 +430,12 @@ test("the window's IPC: the screen reads and retries, My Cloud's page renews itsawait handlers.get("home:repair")(page);w.url = `${LOCAL}${HOME_SCREEN_PATH}`;assert.deepEqual(handlers.get("home:state")(page), { screen: "opening" });+ // Only Try again's press, as the preload says it, is a press: never any other value a page sends.+ const asked = [], retry = w.home.retry;+ w.home.retry = (input) => { asked.push(input?.pressed ?? false); return retry(input); };+ for (const pressed of [true, "true", 1, undefined]) { w.url = `${LOCAL}${HOME_SCREEN_PATH}`; await handlers.get("home:retry")(page, pressed); }+ assert.deepEqual(asked, [true, false, false, false]);+ w.home.retry = retry; w.url = `${LOCAL}${HOME_SCREEN_PATH}`;assert.throws(() => handlers.get("home:repair")(page), /only available/);w.state = { status: "signed-out" };await handlers.get("home:sign-in")(page);@@ -489,6 +495,9 @@ test("My Cloud's own page, once it is home, gets this app's chat links, diagnostassert.equal(local.bridge.home.updating, false);await local.bridge.home.retry(); await local.bridge.home.state(); await local.bridge.home.signIn();assert.deepEqual(local.invoked.map(([channel]) => channel), ["home:retry", "home:state", "home:sign-in"]);+ // Try again's press is said as such; the screen's own looks never are.+ await local.bridge.home.retry(true); await local.bridge.home.retry("true");+ assert.deepEqual(local.invoked.filter(([channel]) => channel === "home:retry").map(([, pressed]) => pressed), [false, true, false]);});test("only the verified Cloud, open as this window's active server, counts as the Cloud page", () => {diff --git a/electron/preload.cjs b/electron/preload.cjsindex 1b24ddf394..a4a9b4ec32 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -724,7 +724,9 @@ const bridge = {ipcRenderer.on("home:state-changed", handler);return () => ipcRenderer.removeListener("home:state-changed", handler);},- retry: () => ipcRenderer.invoke("home:retry"),+ // `pressed`: Try again's own press (only this computer's screen may ask), never its looks as it opens, comes online or+ // comes to the front.+ retry: pressed => ipcRenderer.invoke("home:retry", pressed === true),remove: () => ipcRenderer.invoke("home:remove"),signIn: () => isLocalPage || navigator.userActivation?.isActive === true? ipcRenderer.invoke("home:sign-in") : Promise.reject(new Error("Choose Sign in to sign in again.")),diff --git a/src/components/CloudAccountSettings.test.ts b/src/components/CloudAccountSettings.test.tsindex c93d9ada2e..85bfb810e5 100644--- a/src/components/CloudAccountSettings.test.ts+++ b/src/components/CloudAccountSettings.test.ts@@ -198,15 +198,21 @@ 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) {+it("a saved sign-in this computer still can't read: what may open it first, then a secondary button that clears it and starts the sign-in", async () => {+ for (const [platform, onSignIn, step] of [["win32", undefined, "Restarting the app may fix it."], ["darwin", vi.fn(), "Unlock your keychain or restart the app"],+ ["linux", vi.fn(), "Unlock your system keyring or restart the app"]] as const) {f.values = []; f.platform = platform;- bridge.resetSaved = vi.fn().mockResolvedValue({ status: "signed-out" }); vi.mocked(bridge.begin).mockClear();+ bridge.resetSaved = vi.fn().mockResolvedValue({ status: "signed-out" }); vi.mocked(bridge.begin).mockClear(); if (onSignIn) onSignIn.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.");+ expect(html, platform).toContain(step);+ expect(html, platform).toContain("If it doesn't, clear it to sign in again.");+ if (platform === "win32") expect(html).not.toMatch(/keychain|keyring|unlock/i);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();+ const clears = render({ onSignIn }).nodes.filter(node => node.type === "button" && node.props.children === "Clear and sign in again");+ expect(clears.length, platform).toBeGreaterThan(0);+ for (const clear of clears) expect(String((clear.props as { className?: string }).className), "never the primary button").not.toContain("ui-button-primary");+ clears[0]!.props.onClick!(); await flush();expect(bridge.resetSaved).toHaveBeenCalledOnce();if (onSignIn) { expect(onSignIn).toHaveBeenCalledOnce(); expect(bridge.begin).not.toHaveBeenCalled(); }else expect(bridge.begin).toHaveBeenCalledOnce();diff --git a/src/components/CloudAccountSettings.tsx b/src/components/CloudAccountSettings.tsxindex 011490b417..a66604df1c 100644--- a/src/components/CloudAccountSettings.tsx+++ b/src/components/CloudAccountSettings.tsx@@ -97,11 +97,17 @@ const RESTORE_RETRY: Partial<Record<DesktopCapabilities["host"]["platform"], Locdarwin: "cloudAccount.restoreRetryKeychain",linux: "cloudAccount.restoreRetryKeyring",};+/** Clear is offered only after a few minutes of failed reads, and still says what may open it first: the keychain or keyring+ * unlocked, or the app restarted (a keyring that wasn't up when the app started). */+const SAVED_STUCK: Partial<Record<DesktopCapabilities["host"]["platform"], LocaleKey>> = {+ darwin: "cloudAccount.savedStuckKeychain",+ linux: "cloudAccount.savedStuckKeyring",+};function 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.reset) return t(SAVED_STUCK[platform] ?? "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");@@ -271,7 +277,8 @@ export function CloudAccountSettings({ linkRequest = 0, cloudHome = false, teamHif (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>;+ // Never the primary button: a saved sign-in that a restart would read is gone once cleared.+ const resetButton = () => resetSaved && <button type="button" disabled={busy} data-cloud-reset="" className="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,@@ -290,7 +297,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")}>- {resetSaved ? resetButton(false) : view.kind === "reauth"+ {resetSaved ? resetButton() : 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>}@@ -311,7 +318,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 = resetSaved ? resetButton(true) : signedOut || (view.kind === "free" && buyOfferAllowed(view))+ const primary = resetSaved ? resetButton() : 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/HomeScreen.dom.test.ts b/src/components/HomeScreen.dom.test.tsindex 08d742da57..333ee4c8e0 100644--- a/src/components/HomeScreen.dom.test.ts+++ b/src/components/HomeScreen.dom.test.ts@@ -49,9 +49,15 @@ it("Remove from list shows only where the Admin says so and the app can; a Cloudawait mount(offline);expect(host.querySelector("[role='status'] span"), "no spinner going on for ever").toBeNull();const retried = offline.retry.mock.calls.length;+ expect(retried, "it looks again as it opens").toBeGreaterThan(0);+ await act(async () => { window.dispatchEvent(new Event("focus")); window.dispatchEvent(new Event("online")); });+ await settle();+ const looks = offline.retry.mock.calls.length;await click("[data-home-action='retry']");expect(host.querySelector("[data-home-action='retry']")?.textContent).toBe("Try again");- expect(offline.retry.mock.calls.length).toBe(retried + 1);+ expect(offline.retry.mock.calls.length).toBe(looks + 1);+ // Only the press says so: the looks (opening, focus, back online) never clear the wait for the next sign-in code.+ expect(offline.retry.mock.calls.map((call: unknown[]) => call[0] === true)).toEqual([...Array(looks).fill(false), true]);});it("a checkout that wasn't finished continues where this app keeps its page, else on the Cloud page", async () => {@@ -64,3 +70,23 @@ it("a checkout that wasn't finished continues where this app keeps its page, elsawait click("[data-home-action='continue']");expect([reopen.mock.calls.length, manage.mock.calls.length]).toEqual([2, 1]);});++it("Try again is pressed once at a time: off while its look runs, so a held key or fast clicks never stack looks", async () => {+ const offline = bridgeOf({ screen: "offline" });+ await mount(offline);+ let finish: (view: HomeView) => void = () => {};+ offline.retry.mockImplementation(() => new Promise<HomeView>((resolve) => { finish = resolve; }));+ const before = offline.retry.mock.calls.length;+ const button = () => host.querySelector<HTMLButtonElement>("[data-home-action='retry']")!;+ await act(async () => { button().click(); button().click(); });+ await settle();+ expect(offline.retry.mock.calls.length).toBe(before + 1);+ expect(button().disabled).toBe(true);+ await click("[data-home-action='retry']");+ expect(offline.retry.mock.calls.length, "a press while it runs does nothing").toBe(before + 1);+ await act(async () => { finish({ screen: "offline" }); });+ await settle();+ expect(button().disabled).toBe(false);+ await click("[data-home-action='retry']");+ expect(offline.retry.mock.calls.length).toBe(before + 2);+});diff --git a/src/components/HomeScreen.test.ts b/src/components/HomeScreen.test.tsindex f9655f32c9..839db0144e 100644--- a/src/components/HomeScreen.test.ts+++ b/src/components/HomeScreen.test.ts@@ -70,3 +70,12 @@ it("My Cloud this computer couldn't connect to names its address and what may bereason: "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.",});});++it("an Admin that asked the app to wait says when it tries again by itself, and nothing once that time has passed", () => {+ const now = new Date(2026, 10, 20, 15, 0).getTime(), at = new Date(2026, 10, 20, 15, 5).getTime();+ const time = new Intl.DateTimeFormat("en", { timeStyle: "short" }).format(new Date(at));+ expect(homeScreenText({ screen: "offline", retryAt: at }, now)).toMatchObject({+ action: "retry", reason: `MausBot Cloud asked this app to wait before it signs in to My Cloud again. The app tries again by itself at ${time}.`,+ });+ expect(homeScreenText({ screen: "offline", retryAt: at }, at + 1).reason).toBeNull();+});diff --git a/src/components/HomeScreen.tsx b/src/components/HomeScreen.tsxindex d0b43cb4d2..ef19ede2eb 100644--- a/src/components/HomeScreen.tsx+++ b/src/components/HomeScreen.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { activeLocale, t } from "@/lib/i18n";import type { LocaleKey } from "@/locales";import type { HomeView, HomeBridge } from "../../electron/home-window.mjs";@@ -28,7 +28,8 @@ export function homeScreenText(view: HomeView | null, now = Date.now()): { titleconst 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"), 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 };+ reason: view.cause === "network" && view.host ? t("homeScreen.offlineNetwork", { host: view.host }) : view.cause && Object.hasOwn(UNREACHABLE, view.cause) ? t(UNREACHABLE[view.cause]!)+ : view.retryAt && view.retryAt > now ? t("homeScreen.offlineWait", { time: new Intl.DateTimeFormat(activeLocale(), { timeStyle: "short" }).format(new Date(view.retryAt)) }) : 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 };@@ -80,6 +81,8 @@ function RemoveFromList({ name, remove }: { name: string; remove: () => Promise<export function HomeScreen({ bridge, manage }: { bridge: HomeBridge; manage?: () => Promise<void> }) {const [view, setView] = useState<HomeView | null>(null);const [failed, setFailed] = useState(false);+ // Try again is pressed once at a time: a held key or fast clicks never stack looks (main also keeps codes apart).+ const [trying, setTrying] = useState(false), pressing = useRef(false);useEffect(() => {let alive = true;const stop = bridge.onState((next) => setView(next));@@ -95,7 +98,11 @@ export function HomeScreen({ bridge, manage }: { bridge: HomeBridge; manage?: ()// Its checkout's page again when this app keeps it (the Cloud it is buying), else the Cloud page, where it can be paid.const reopen = window.ogb?.cloudAdd?.reopen;const run: Partial<Record<HomeAction, () => Promise<unknown>>> = {- retry: () => bridge.retry().then((next) => setView(next)),+ retry: () => {+ if (pressing.current) return Promise.resolve();+ pressing.current = true; setTrying(true);+ return bridge.retry(true).then((next) => setView(next)).finally(() => { pressing.current = false; setTrying(false); });+ },...(manage ? { manage, buy: manage, card: manage, continue: async () => { if (!(reopen && await reopen().catch(() => false))) await manage(); } } : {}),};const button = text.action && text.action !== "sign-in" && text.action !== "manage" ? text.action : null;@@ -113,7 +120,7 @@ export function HomeScreen({ bridge, manage }: { bridge: HomeBridge; manage?: (){text.action === "sign-in" && <button type="button" className="ui-button ui-button-primary mt-2" onClick={() => act(() => bridge.signIn())}>{t("homeScreen.signInButton")}</button>}{text.action === "manage" && manage && <button type="button" className="ui-button mt-2" onClick={() => act(manage)}>{t("cloudAccount.manageInBrowser")}</button>}{button && run[button] && <button type="button" data-home-action={button} className={button === "retry" ? "ui-button mt-2" : "ui-button ui-button-primary mt-2"}- onClick={() => act(run[button]!)}>{t(BUTTON[button])}</button>}+ disabled={button === "retry" && trying} onClick={() => act(run[button]!)}>{t(BUTTON[button])}</button>}{removable && <RemoveFromList name={view.name ?? t("cloudSetup.myCloud")} remove={() => bridge.remove!()} />}{failed && <p role="alert" className="text-[13px] text-danger">{t("cloudAccount.actionFailed")}</p>}</div>diff --git a/src/locales/en.json b/src/locales/en.jsonindex be57fbd767..cff141a5e7 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -1342,7 +1342,9 @@"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.savedStuck": "This computer still can't read its saved MausBot Cloud sign-in. Restarting the app may fix it. If it doesn't, clear it to sign in again. Your plan and My Cloud aren't affected.",+ "cloudAccount.savedStuckKeychain": "This computer still can't open its saved MausBot Cloud sign-in. Unlock your keychain or restart the app, and it may open again. If it doesn't, clear it to sign in again. Your plan and My Cloud aren't affected.",+ "cloudAccount.savedStuckKeyring": "This computer still can't open its saved MausBot Cloud sign-in. Unlock your system keyring or restart the app, and it may open again. If it doesn't, 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.",@@ -7889,6 +7891,7 @@"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.offlineWait": "MausBot Cloud asked this app to wait before it signs in to My Cloud again. The app tries again by itself at {time}.","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 92c3b1eb45..4b464c5a27 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -1264,7 +1264,9 @@"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.savedStuck": "Este computador ainda não consegue ler o login do MausBot Cloud salvo. Reiniciar o app pode resolver. Se não resolver, apague-o para entrar novamente. Seu plano e o My Cloud não são afetados.",+ "cloudAccount.savedStuckKeychain": "Este computador ainda não consegue abrir o login do MausBot Cloud salvo. Desbloqueie o chaveiro ou reinicie o app, e ele pode abrir de novo. Se não abrir, apague-o para entrar novamente. Seu plano e o My Cloud não são afetados.",+ "cloudAccount.savedStuckKeyring": "Este computador ainda não consegue abrir o login do MausBot Cloud salvo. Desbloqueie o chaveiro do sistema ou reinicie o app, e ele pode abrir de novo. Se não abrir, 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.",@@ -7690,6 +7692,7 @@"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.offlineWait": "O MausBot Cloud pediu para este app esperar antes de entrar no My Cloud de novo. O app tenta novamente sozinho às {time}.","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.",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex 9e329ed251..8311441b9c 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -37222,11 +37222,14 @@"cloudBuy.signIn.cancelBrowser": "f014f4b19c08fdfff272f049840c17c7572728af85d9e420f98f517b52e4e083","cloudBuy.signIn.busy": "921e57ca5c227919c8f3999cd40556e2ba071aaefdc86464b4ef00e8f8e12c17","cloudBuy.signIn.signedIn": "a26b31e3757db5a7e29a2814a32cf109b563fca1a8f7f5380e9a0f635dbcfe34",- "cloudAccount.savedStuck": "065a8bb5d861059de5d99b305d28433b92d0e5c25ebd706a340c0440957d58e6",+ "cloudAccount.savedStuck": "5efbddc0309e897b7087a02f66746c693393b24cad3dac3768c44bd3ecdeda72",+ "cloudAccount.savedStuckKeychain": "249c72d715f2ad1758046fbf0cd6e05974494ad9fc2608b74e6a0cbf5b8a9369",+ "cloudAccount.savedStuckKeyring": "f6d3b9e6e946fcc98ce0b64183ae840c5a8a964bf4f5e2c0056a7be48d993e30","cloudAccount.resetSaved": "276fa85bc75786d143b74c11cbbb9abe1b7908f48011c1d799114024e09c903b","cloudAccount.resetKept": "9243efedc1e40bb499acadf970053efa1b7e3a9fc90e3662b3efdd67b89bf453","cloudAccount.unsaved": "69f16bd2ad4856e040d928ce9482507b14e26f66c500287859c8634ef6117149",- "homeScreen.offlineNetwork": "f628e51f2e014252ca9826b7828fb417ad2895267a42716fb41e7140615154c8"+ "homeScreen.offlineNetwork": "f628e51f2e014252ca9826b7828fb417ad2895267a42716fb41e7140615154c8",+ "homeScreen.offlineWait": "7de832bcc189e9fa19b386a0a67d938840772d5500985c835fa1db1afee4d49f"},"zh": {"pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b",