Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Keep the account state as fresh as before whenever someone is looking

milind-soniffcc35816db2
diff --git a/electron/cloud-account.d.mts b/electron/cloud-account.d.mts
index 6b9ee92979..ac26f5fa16 100644
--- a/electron/cloud-account.d.mts
+++ b/electron/cloud-account.d.mts
@@ -294,8 +294,12 @@ export interface CloudAccountClient {
refresh(): Promise<CloudAccountState>;
/** While the Admin's session read keeps failing, when this client tries it again by itself (epoch ms); 0 otherwise. */
failingUntil?(): number;
- /** The window came to the front: the session is read now if its last answer is a minute old (never inside a failure's wait), at once while a checkout is watched. */
- freshen(): void;
+ /** The window came to the front, the computer woke, or the person pressed Try again: the session is read now (that read) when
+ * the last read began a minute ago or more, a failure's wait or not, and at once while a checkout is watched; otherwise null,
+ * and the next read comes a minute after the last at the latest. */
+ freshen(): Promise<CloudAccountState> | null;
+ /** When the last session read began (epoch ms); 0 before the first. */
+ lastAttemptAt?(): number;
signOut(): Promise<CloudAccountState>;
openDashboard(): Promise<CloudAccountState>;
offer(): Promise<import("./cloud-home.mjs").CloudOffer | null>;
@@ -408,7 +412,7 @@ export declare function createCloudAccountClient(options: {
readWaitMs?: number;
/** Spreads each wait between session reads (Math.random). */
random?: () => number;
- /** Someone is looking (main's window in front) or a move is under way: the session is read every minute instead of every five. Default true. */
+ /** Someone is looking (main's window in front or visible) or a move is under way: the session is read every minute instead of every five, and a failed read retried within the minute. Default true. */
attended?: () => boolean;
}): CloudAccountClient;
export declare function cloudPlanSnapshot(state: CloudAccountState | null | undefined, extra?: { notice?: import("./cloud-home.mjs").CloudTrialState | null }): CloudPlanSnapshot;
diff --git a/electron/cloud-account.mjs b/electron/cloud-account.mjs
index 2c2ebac4b4..9e6d27f9a9 100644
--- a/electron/cloud-account.mjs
+++ b/electron/cloud-account.mjs
@@ -107,7 +107,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
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, failingUntil = 0;
+ let verifiedUntil = 0, restoring = false, controller = new AbortController(), failures = 0, failingUntil = 0, lastAttemptAt = 0, timerAt = Infinity, timerFor = null; // the last session read's start; the timer's due time and work
let plan = null, savedHint = null;
/** The plan's own Cloud that Cancel and Keep act on, as the last verified session names it. */
let renewalCloud = null;
@@ -145,10 +145,10 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
const watchingAdd = () => Boolean(adding && !adding.done && now() - adding.startedAt < CHECKOUT_WATCH_MS);
const publish = next => { value = next; onState(state()); return state(); };
const record = (saved, hint) => ({ ...saved, ...(hint ? { planHint: hint } : {}) });
- const stopTimer = () => { if (timer !== null) clearTimer(timer); timer = null; };
+ const stopTimer = () => { if (timer !== null) clearTimer(timer); timer = null; timerAt = Infinity; timerFor = null; };
const schedule = (work, delay) => {
stopTimer();
- if (!closed) { timer = setTimer(() => { timer = null; void work().catch(() => {}); }, Math.max(1, delay)); timer?.unref?.(); }
+ if (!closed) { timerAt = now() + Math.max(1, delay); timerFor = work; timer = setTimer(() => { timer = null; timerAt = Infinity; timerFor = null; void work().catch(() => {}); }, Math.max(1, delay)); timer?.unref?.(); }
};
const reset = () => { generation++; stopTimer(); controller.abort(); controller = new AbortController(); pending = null; emailed = null; verifiedUntil = 0; failures = 0; failingUntil = 0; return generation; };
// `quiet`: another account is taking over (quiesce to reload): this sign-in's grant is still in memory, and nothing may ask for
@@ -260,7 +260,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
if (!grant || !current(stamp)) return state();
if (grant.expiresAt <= now()) { stopTimer(); return publish(view("reauth-required", "expired")); }
try {
- const previous = grant, result = await request("session", { token: previous.token });
+ lastAttemptAt = now(); const previous = grant, result = await request("session", { token: previous.token });
if (!current(stamp) || grant !== previous) return state();
const next = identity(result);
if (next.device.id !== previous.device.id || next.account.id !== previous.account.id || next.account.email !== previous.account.email || next.expiresAt <= now()) {
@@ -312,7 +312,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
} catch (error) {
if (!current(stamp)) return state();
if (signInEnded(error)) { verifiedUntil = 0; failures = 0; stopTimer(); return publish(view("reauth-required", "access-ended")); }
- failures++; const wait = sessionRetryWait(failures, { retryAfter: error?.retryAfter, expiresIn: grant.expiresAt - now(), verifiedIn: verifiedUntil - now(), random }); failingUntil = now() + Math.max(0, wait); // `failingUntil` below
+ failures++; const wait = sessionRetryWait(failures, { retryAfter: error?.retryAfter, expiresIn: grant.expiresAt - now(), verifiedIn: verifiedUntil - now(), attended: attended(), waking: awaitingWake(), random }); failingUntil = now() + Math.max(0, wait); // `failingUntil` below
if (value.status === "connected") publish(value);
else publish(view("unavailable", "unreachable"));
schedule(refresh, wait);
@@ -524,8 +524,10 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
return state();
},
cancel: () => { if (!pending && value.status !== "connecting") return Promise.resolve(state()); opened = null; return signOut(); },
- refresh, signOut, failingUntil: () => (failures > 0 ? failingUntil : 0), // a failing session read's next try: a caller waits for it
- freshen() { if (grant && value.status !== "reauth-required" && (watching() || (now() - (value.verifiedAt ?? 0) >= REFRESH_MS && !(failures > 0 && failingUntil > now())))) void refresh().catch(() => {}); }, // the window came to the front: read now when the last answer is a minute old (never inside a failure's wait), at once while a checkout is watched
+ refresh, signOut, lastAttemptAt: () => lastAttemptAt, failingUntil: () => (failures > 0 ? failingUntil : 0), // when the last session read began; a failing one's next try
+ freshen() { // the window came to the front, the computer woke, or the person pressed Try again: read now when the last read began a minute ago or more (inside a failure's wait too), at once while a checkout is watched; else the next read comes a minute after the last
+ if (!grant || quiet || closed || value.status === "reauth-required") return null; if (watching() || now() - lastAttemptAt >= REFRESH_MS) return refresh().catch(() => state());
+ if (timerFor === refresh && timerAt > lastAttemptAt + REFRESH_MS) schedule(refresh, lastAttemptAt + REFRESH_MS - now()); return null; },
/** 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() {
@@ -906,8 +908,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
* it does not offer X research (404). Never kept on disk. The relay must
* be on the Cloud's own origin: the token goes nowhere else. */
async xResearchAccess() {
- const current = grant;
- if (!current) return null;
+ const current = grant; if (quiet) throw new Error("Another account is taking over."); if (!current) return null; // never the account before's sign-in
let result;
try { result = await request("services/x", { method: "POST", body: {}, token: current.token }); }
catch (error) { if (error?.status === 402 || error?.status === 404) return null; throw error; }
@@ -922,8 +923,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
* or null when there is no sign-in or the Admin does not offer pages yet (404). Never kept on disk. The token route
* must be on the Cloud's own origin: the token goes nowhere else. */
async pagesAccess() {
- const current = grant;
- if (!current) return null;
+ const current = grant; if (quiet) throw new Error("Another account is taking over."); if (!current) return null; // never the account before's sign-in
let result;
try { result = await request("services/pages", { method: "POST", body: {}, token: current.token }); }
catch (error) { if (error?.status === 404) return null; throw error; }
diff --git a/electron/cloud-account.node-test.mjs b/electron/cloud-account.node-test.mjs
index 8ce17cedd1..855d52863b 100644
--- a/electron/cloud-account.node-test.mjs
+++ b/electron/cloud-account.node-test.mjs
@@ -57,8 +57,8 @@ test("a failed check keeps the last verified answer (never a malformed one), say
assert.deepEqual(state.lastPlan, { tier: "max", active: true });
});
-test("a check that fails is asked again after 15 s, 30 s, 1, 2 and 4 minutes, then every 5", async t => {
- const f = await fixture(t); await f.connect();
+test("a check that fails while nobody looks is asked again after 15 s, 30 s, 1, 2 and 4 minutes, then every 5", async t => {
+ const f = await fixture(t, { attended: () => false }); await f.connect();
assert.equal(f.client.failingUntil(), 0); f.sessionStatus = 503; await f.client.refresh(); assert.equal(f.delay, 15_000);
assert.equal(f.client.failingUntil(), f.now + 15_000, "a caller that would read it sooner (the Cloud's page) is told when it is tried again");
for (const delay of [30_000, 60_000, 120_000, 240_000, 300_000, 300_000]) { f.tick(); await until(() => f.timer); assert.equal(f.delay, delay); }
diff --git a/electron/cloud-background.node-test.mjs b/electron/cloud-background.node-test.mjs
index f1994c62e9..60209fd889 100644
--- a/electron/cloud-background.node-test.mjs
+++ b/electron/cloud-background.node-test.mjs
@@ -124,14 +124,20 @@ test("the same app with its window in front reads the session every minute, as b
assert.deepEqual(counts, { "GET session": 60, "POST move-status": 0, "POST services/pages": 0, "POST services/x": 0, "GET updates-consent": 0 });
});
-test("an Admin failing everything but the session: each other ask waits longer each time, 2 an hour, instead of going with every session read (was 60 an hour each)", async () => {
+test("an Admin failing everything but the session: the move's report backs off to 2 an hour, the tokens to every 5 minutes, instead of going with every session read (was 60 an hour each)", async () => {
for (const [name, answer] of Object.entries(failing)) {
const counts = await hour({ paid: true, admin: (key) => (key === "GET session" ? undefined : answer()) });
- // After the launch's try and the first ten minutes' (1, 2 and 5 minutes on), the hour holds the 10-minute one and the first 30-minute one.
- assert.deepEqual(counts, { "GET session": 12, "POST move-status": 2, "POST services/pages": 2, "POST services/x": 2, "GET updates-consent": 0 }, name);
+ // The report: after the launch's try and the first ten minutes' (1, 2 and 5 minutes on), the 10-minute one and the first
+ // 30-minute one. The tokens: 1, 2 and 5 minutes on, then every 5 minutes. (A Retry-After of 60 s changes neither.)
+ assert.deepEqual(counts, { "GET session": 12, "POST move-status": 2, "POST services/pages": 12, "POST services/x": 12, "GET updates-consent": 0 }, name);
}
});
+test("someone looking (window in front or visible) with a failing Admin: the session is tried within the minute, as before", async () => {
+ const counts = await hour({ paid: true, attended: () => true, admin: (key) => (key === "GET session" ? json({ error: "unavailable" }, 503) : undefined) });
+ assert.equal(counts["GET session"], 60, "15 s, 30 s, then every minute: as many as before, never fewer");
+});
+
test("an Admin failing everything: the session is tried after 15 s, 30 s, 1, 2, 4 minutes and then every 5 (was every minute), and the move's report twice an hour (was 60)", async () => {
for (const [name, answer] of Object.entries(failing)) {
const counts = await hour({ paid: true, admin: () => answer() });
@@ -139,14 +145,14 @@ test("an Admin failing everything: the session is tried after 15 s, 30 s, 1, 2,
}
});
-test("pages asking for the updates answer are answered from this run once the account's answer is in step (each look asked the Admin before)", async () => {
+test("pages asking for the updates answer are answered from this run, read again only once the last read is 10 minutes old (each look asked the Admin before)", async () => {
const counts = await hour({ paid: false }, async (a) => {
for (let look = 0; look < 10; look++) { await a.updates.state(); await a.pass(5 * 60_000); }
});
- assert.equal(counts["GET updates-consent"], 0);
+ assert.equal(counts["GET updates-consent"], 5, "10 looks 5 minutes apart: every other one reads (was 10)");
});
-test("the Admin unreachable for 20 minutes, then back: the same sign-in gets its tokens back without new ones, and its updates answer is not read again", async () => {
+test("the Admin unreachable for 20 minutes, then back: the same sign-in gets its tokens back without new ones, and its updates answer is read once", async () => {
let down = false;
const counts = await hour({ paid: true, admin: () => (down ? json({ error: "unavailable" }, 503) : undefined) }, async (a) => {
down = true;
@@ -159,7 +165,7 @@ test("the Admin unreachable for 20 minutes, then back: the same sign-in gets its
// Was: 1 new pages token, 1 new research relay token and 1 updates read on the way back, and a move report each minute meanwhile (19).
assert.equal(counts["POST services/pages"], 0);
assert.equal(counts["POST services/x"], 0);
- assert.equal(counts["GET updates-consent"], 0);
+ assert.equal(counts["GET updates-consent"], 1, "the sign-in verified again, and its last read over 10 minutes old");
assert.equal(counts["POST move-status"], 3, "the report says it is unverified, and verified again, as each changes");
});
@@ -183,20 +189,58 @@ test("coming to the front reads the session at once when its answer is a minute
});
// The session's own waits, against the loopback fixture (fixtures/cloud-account.mjs).
-test("a failing check never asks before the Admin's Retry-After", async t => {
- const f = await fixture(t); await f.connect();
- f.sessionError = { status: 429, body: { error: "rate_limited" }, headers: { "retry-after": "600" } };
+test("a failing check never asks before the Admin's Retry-After, held to five minutes and spread only later, with a last try before the answer stops counting", async t => {
+ let draw = 0.5;
+ const f = await fixture(t, { random: () => draw }); await f.connect();
+ f.sessionError = { status: 429, body: { error: "rate_limited" }, headers: { "retry-after": "60" } };
+ for (const [drawn, delay] of [[0, 60_000], [0.5, 66_000], [1, 72_000]]) { draw = drawn; await f.client.refresh(); assert.equal(f.delay, delay, "the Admin's own wait, not 15 s, spread up to a fifth later"); }
+ f.sessionError.headers["retry-after"] = "3600"; draw = 0;
await f.client.refresh();
- assert.equal(f.delay, 600_000, "the Admin's own wait, not 15 s");
+ assert.equal(f.delay, 300_000, "an hour asked for is held to five minutes");
+ f.now = f.client.state().verifiedUntil - 140_000;
+ await f.client.refresh();
+ assert.equal(f.delay, 120_000, "and never past 20 s before the verified answer stops counting");
assert.equal(f.client.state().status, "connected");
});
+test("a failing check while someone looks: 15 s, 30 s, then each minute, as before; while a sleeping Cloud is awaited: every 15 s", async t => {
+ let front = true, waking = false;
+ const f = await fixture(t, { attended: () => front, awaitingWake: () => waking }); await f.connect();
+ f.sessionStatus = 503;
+ const waits = [];
+ for (let i = 0; i < 6; i++) { await f.client.refresh(); waits.push(f.delay); }
+ assert.deepEqual(waits, [15_000, 30_000, 60_000, 60_000, 60_000, 60_000]);
+ waking = true;
+ await f.client.refresh();
+ assert.equal(f.delay, 15_000);
+ waking = false; front = false;
+ await f.client.refresh();
+ assert.equal(f.delay, 300_000, "nobody looking: the eighth failure waits 5 minutes");
+});
+
+test("coming to the front inside a failure's wait reads at once when the last read began a minute ago; under a minute, the next read moves up to a minute after the last", async t => {
+ let front = false;
+ const f = await fixture(t, { attended: () => front }); await f.connect();
+ assert.equal(f.delay, 300_000, "in the back: 5 minutes");
+ f.now += 20_000; front = true;
+ const before = f.requests.length;
+ assert.equal(f.client.freshen(), null, "the answer is 20 s old: not read again now");
+ assert.equal(f.delay, 40_000, "the 5-minute read moves up to a minute after the last");
+ f.sessionStatus = 503; front = false;
+ for (let i = 0; i < 5; i++) await f.client.refresh();
+ assert.equal(f.delay, 240_000, "in the back, failing: 4 minutes");
+ f.now += 61_000; front = true;
+ await f.client.freshen();
+ assert.equal(f.requests.length, before + 6, "a minute after the last try: read now, inside the failure's wait");
+ assert.equal(f.delay, 60_000, "and, in front, every minute from then on");
+});
+
test("a failing check gets one last try before the verified answer stops counting, so a short outage never shows", async t => {
- const f = await fixture(t); await f.connect();
+ const f = await fixture(t, { attended: () => false }); await f.connect();
const counted = f.client.state().verifiedUntil;
f.sessionStatus = 503;
- for (let i = 0; i < 7; i++) { f.now += f.delay; await f.client.refresh(); }
- assert.equal(f.now + f.delay, counted - 20_000, "after 1, 15 s, 30 s, 1, 2, 4 and 5 minutes, the next try is 20 s before the answer stops counting, not 5 minutes on");
+ for (let i = 0; i < 6; i++) { f.now += f.delay; await f.client.refresh(); }
+ assert.equal(f.now + f.delay, counted - 20_000, "after 5 minutes, then 15 s, 30 s, 1, 2 and 4 minutes, the next try is 20 s before the answer stops counting, not 5 minutes on");
assert.equal(f.client.state().status, "connected");
f.now += f.delay; f.sessionStatus = 200; await f.client.refresh();
assert.equal(f.client.state().status, "connected");
diff --git a/electron/cloud-cadence.mjs b/electron/cloud-cadence.mjs
index 9e9f70e723..91d45cc51a 100644
--- a/electron/cloud-cadence.mjs
+++ b/electron/cloud-cadence.mjs
@@ -6,8 +6,16 @@
export const REFRESH_MS = 60_000;
/** The same while nobody is looking and nothing is under way: coming to the front reads it again at once (cloud-account.mjs `freshen`). */
export const IDLE_REFRESH_MS = 5 * 60_000;
-/** A failed session read is tried again after each of these in turn, then the last from then on. */
+/** A failed session read is tried again after each of these in turn, then the last from then on, while nobody is looking. */
export const SESSION_RETRY_MS = Object.freeze([15_000, 30_000, 60_000, 120_000, 240_000, 300_000]);
+/** The same while someone is looking (the window in front or visible, or a move under way): never longer than a minute, as before. */
+export const ATTENDED_RETRY_MS = Object.freeze([15_000, 30_000, 60_000]);
+/** The same while Files or lending waits for a sleeping Cloud to wake: every 15 s, as its steady read. */
+export const WAKE_RETRY_MS = Object.freeze([15_000]);
+/** The session's Retry-After is held to this: the Admin can slow the app, never leave it unverified for long. */
+export const SESSION_RETRY_AFTER_MAX_MS = 5 * 60_000;
+/** The pages and research relay tokens: tried again after each of these, then every 5 minutes. */
+export const TOKEN_RETRY_MS = Object.freeze([60_000, 120_000, 300_000]);
/** Any other background ask that failed (the pages and research relay tokens, the move's report, the updates answer). */
export const ASK_RETRY_MS = Object.freeze([60_000, 120_000, 300_000, 600_000, 1_800_000]);
/** A Retry-After longer than this is held to it. */
@@ -29,20 +37,28 @@ export function jitteredBelow(ms, random = Math.random) {
return Math.max(1, Math.round(ms * (1 - spread * SPREAD)));
}
+/** `ms` spread up by up to 20%, never sooner: an Admin's Retry-After, so the apps it slowed don't all come back together. */
+export function jitteredAbove(ms, random = Math.random) {
+ const drawn = Number(random());
+ return Math.max(1, Math.round(ms * (1 + (Number.isFinite(drawn) ? Math.min(1, Math.max(0, drawn)) : 0) * SPREAD)));
+}
+
/** The wait after `failures` failed asks in a row (1 or more), from `steps`, spread; never shorter than `retryAfter`, the
- * Admin's own Retry-After in seconds (cloud-account.mjs puts it on a failed request's error). */
-export function retryWait(failures, { steps = ASK_RETRY_MS, retryAfter, random = Math.random } = {}) {
+ * Admin's own Retry-After in seconds (cloud-account.mjs puts it on a failed request's error), held to `retryAfterMax` and
+ * spread only longer. `below`: the steps are spread only sooner (a wait someone may be watching). */
+export function retryWait(failures, { steps = ASK_RETRY_MS, retryAfter, retryAfterMax = RETRY_AFTER_MAX_MS, below = false, random = Math.random } = {}) {
const step = steps[Math.min(Math.max(1, Math.floor(failures) || 1), steps.length) - 1];
- const asked = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter * 1000, RETRY_AFTER_MAX_MS) : 0;
- return Math.max(jittered(step, random), asked);
+ const asked = Number.isFinite(retryAfter) && retryAfter > 0 ? jitteredAbove(Math.min(retryAfter * 1000, retryAfterMax), random) : 0;
+ return Math.max(below ? jitteredBelow(step, random) : jittered(step, random), asked);
}
-/** The wait before a failed session read is tried again: longer each time up to five minutes, never before the Admin's
- * Retry-After, never past the sign-in's expiry (`expiresIn`), and with a last try 20 s before the verified answer stops
- * counting (`verifiedIn`) unless the Admin said when to come back. */
-export function sessionRetryWait(failures, { retryAfter, expiresIn = Infinity, verifiedIn = 0, random = Math.random } = {}) {
- const left = verifiedIn - 20_000;
- return Math.min(retryWait(failures, { steps: SESSION_RETRY_MS, retryAfter, random }), expiresIn, left > 0 && !(retryAfter > 0) ? left : Infinity);
+/** The wait before a failed session read is tried again: 15 s, 30 s, then each minute while someone is looking (`attended`),
+ * every 15 s while a sleeping Cloud is awaited (`waking`), else longer each time up to five minutes. Never before the Admin's
+ * Retry-After (held to five minutes), never past the sign-in's expiry (`expiresIn`), and always with a last try 20 s before
+ * the verified answer stops counting (`verifiedIn`). */
+export function sessionRetryWait(failures, { retryAfter, expiresIn = Infinity, verifiedIn = 0, attended = false, waking = false, random = Math.random } = {}) {
+ const left = verifiedIn - 20_000, steps = waking ? WAKE_RETRY_MS : attended ? ATTENDED_RETRY_MS : SESSION_RETRY_MS;
+ return Math.min(retryWait(failures, { steps, retryAfter, retryAfterMax: SESSION_RETRY_AFTER_MAX_MS, below: waking || attended, random }), expiresIn, left > 0 ? left : Infinity);
}
/**
diff --git a/electron/cloud-cadence.node-test.mjs b/electron/cloud-cadence.node-test.mjs
new file mode 100644
index 0000000000..fd344d8a6e
--- /dev/null
+++ b/electron/cloud-cadence.node-test.mjs
@@ -0,0 +1,50 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { createBackoff, jittered, jitteredAbove, jitteredBelow, retryWait, SESSION_RETRY_AFTER_MAX_MS, sessionRetryWait } from "./cloud-cadence.mjs";
+
+test("spreads: ±20% around, only sooner, only later; a draw of 0.5 leaves a wait as it is (only later: +10%)", () => {
+ for (const [drawn, around, sooner, later] of [[0, 80, 80, 100], [0.5, 100, 100, 110], [1, 120, 80, 120], [Number.NaN, 100, 100, 100], [7, 120, 80, 120]]) {
+ assert.equal(jittered(100_000, () => drawn), around * 1_000, `around ${drawn}`);
+ assert.equal(jitteredBelow(100_000, () => drawn), sooner * 1_000, `sooner ${drawn}`);
+ assert.equal(jitteredAbove(100_000, () => drawn), later * 1_000, `later ${drawn}`);
+ }
+});
+
+test("a Retry-After is kept, spread only later, and held to its cap (an hour, five minutes for the session)", () => {
+ const low = () => 0;
+ assert.equal(retryWait(1, { retryAfter: 600, random: low }), 600_000, "longer than the 1-minute step");
+ assert.equal(retryWait(1, { retryAfter: 600, random: () => 1 }), 720_000);
+ assert.equal(retryWait(1, { retryAfter: 30, random: low }), 48_000, "shorter than the step: the step");
+ assert.equal(retryWait(1, { retryAfter: 86_400, random: low }), 3_600_000, "a day asked for: an hour");
+ assert.equal(retryWait(1, { retryAfter: 86_400, retryAfterMax: 300_000, random: low }), 300_000);
+ for (const bad of [0, -5, Number.NaN, undefined, "600"]) assert.equal(retryWait(1, { retryAfter: bad, random: () => 0.5 }), 60_000, String(bad));
+ assert.equal(sessionRetryWait(1, { retryAfter: 3_600, verifiedIn: 900_000, random: low }), SESSION_RETRY_AFTER_MAX_MS, "the session's is held to five minutes");
+ assert.equal(sessionRetryWait(1, { retryAfter: 3_600, verifiedIn: 140_000, random: low }), 120_000, "and never past 20 s before the verified answer stops counting");
+});
+
+test("the session's failure waits: who is looking decides how long", () => {
+ const steps = (options) => [1, 2, 3, 4, 5, 6, 7].map((failures) => sessionRetryWait(failures, { verifiedIn: 3_600_000, random: () => 0.5, ...options }));
+ assert.deepEqual(steps({}), [15_000, 30_000, 60_000, 120_000, 240_000, 300_000, 300_000]);
+ assert.deepEqual(steps({ attended: true }), [15_000, 30_000, 60_000, 60_000, 60_000, 60_000, 60_000]);
+ assert.deepEqual(steps({ waking: true }), Array(7).fill(15_000));
+ assert.ok(steps({ attended: true, random: () => 1 }).every((wait) => wait <= 60_000), "looking: never longer than a minute, whatever the draw");
+ assert.equal(sessionRetryWait(3, { expiresIn: 5_000, verifiedIn: 3_600_000, random: () => 0.5 }), 5_000, "never past the sign-in's expiry");
+});
+
+test("a backoff grows with each failure, and an answer starts it again", () => {
+ let clock = 0;
+ const backoff = createBackoff({ steps: [60_000, 120_000, 300_000], now: () => clock, random: () => 0.5 });
+ assert.equal(backoff.waiting(), false);
+ assert.equal(backoff.failed(), 60_000);
+ assert.equal(backoff.waiting(), true);
+ assert.equal(backoff.failed(), 120_000);
+ assert.equal(backoff.failed(), 300_000);
+ assert.equal(backoff.failed(), 300_000, "the last step from then on");
+ clock = 299_999; assert.equal(backoff.waiting(), true);
+ clock = 300_000; assert.equal(backoff.waiting(), false);
+ backoff.ok();
+ assert.equal(backoff.until(), 0);
+ assert.equal(backoff.failed() - clock, 60_000, "an answer starts the count again");
+ assert.equal(backoff.failed({ retryAfter: 900 }) - clock, 990_000, "and a Retry-After counts");
+});
diff --git a/electron/cloud-operation.node-test.mjs b/electron/cloud-operation.node-test.mjs
index 9ea0d95275..f89265c343 100644
--- a/electron/cloud-operation.node-test.mjs
+++ b/electron/cloud-operation.node-test.mjs
@@ -110,7 +110,7 @@ test("another Cloud of the person's own being moved: its screen names it", async
assert.deepEqual(w.home.view(), { screen: "working", operation: move, name: "Client A" });
});
-test("the Cloud's own page asks what has it down: the Admin's word for the place on screen only, read again when it is old, never while the Admin is failing", async () => {
+test("the Cloud's own page asks what has it down: the Admin's word for the place on screen only, read again when it is old, while the Admin fails at most each minute", async () => {
const w = world({ state: { ...connected({ operation: UPDATE }), verifiedAt: 1_000_000 } });
await w.home.refresh();
assert.deepEqual(await w.home.operation(), UPDATE);
@@ -123,15 +123,21 @@ test("the Cloud's own page asks what has it down: the Admin's word for the place
stale.refreshed = { ...connected({ operation: UPDATE }), verifiedAt: stale.clock };
assert.deepEqual(await stale.home.operation(), UPDATE);
assert.equal(stale.refreshes, 1);
- // The Admin itself failing: the account's own retry wait is kept, however often the page asks.
+ // The Admin itself failing: within a minute of the account's last try, its retry wait is kept, however often the page asks.
const failing = world({ state: { ...connected(), verifiedAt: 1 } });
await failing.home.refresh();
- failing.failingUntil = failing.clock + 30_000;
+ failing.failingUntil = failing.clock + 300_000; failing.lastAttemptAt = failing.clock;
for (let i = 0; i < 3; i++) assert.equal(await failing.home.operation(), null);
assert.equal(failing.refreshes, 0);
- failing.clock += 30_000;
+ failing.clock += 60_000;
await failing.home.operation();
- assert.equal(failing.refreshes, 1, "read again once its wait is over");
+ assert.equal(failing.refreshes, 1, "a minute after the last try: read again, inside a 5-minute wait");
+ failing.lastAttemptAt = failing.clock; failing.clock += 30_000;
+ await failing.home.operation();
+ assert.equal(failing.refreshes, 1);
+ failing.failingUntil = 0;
+ await failing.home.operation();
+ assert.equal(failing.refreshes, 2, "read again once its wait is over");
const signedOut = world({ state: { status: "signed-out" } });
assert.equal(await signedOut.home.operation(), null);
});
diff --git a/electron/fixtures/home-window-world.mjs b/electron/fixtures/home-window-world.mjs
index d9842baac0..9551ea027f 100644
--- a/electron/fixtures/home-window-world.mjs
+++ b/electron/fixtures/home-window-world.mjs
@@ -51,6 +51,9 @@ export function world({ clean = null, journal = done(), marker = null, state = c
refresh: async () => { w.refreshes++; if (w.refreshed) w.state = w.refreshed; return w.state; },
/** While the Admin's session read keeps failing (`w.failingUntil`), when the account tries it again by itself. */
failingUntil: () => w.failingUntil ?? 0,
+ /** When the last session read began (`w.lastAttemptAt`); `freshen`, as the account's: read when that is a minute old. */
+ lastAttemptAt: () => w.lastAttemptAt ?? 0,
+ freshen: () => { w.freshens = (w.freshens ?? 0) + 1; return null; },
power: () => w.power,
powerOf: (origin) => (origin === CLOUD ? w.power : (w.state?.clouds ?? []).find((cloud) => cloud.origin === origin)?.power ?? null),
async wakeHome() { w.wakes++; await w.cloud.wakeGate; if (w.cloud.wakes) w.power = { ...w.power, state: "awake" }; return "awake"; },
diff --git a/electron/home-window.mjs b/electron/home-window.mjs
index 1b34714ed9..ccf7154762 100644
--- a/electron/home-window.mjs
+++ b/electron/home-window.mjs
@@ -8,6 +8,7 @@
// signed-out app (its automations would run twice). The page that counts as home is the main window's main frame at the
// shown place's verified origin, nothing else. A team is only ever one the Admin's session lists, paired through the
// Admin's team pairing (its claims are the Admin's), never an address a page supplied.
+import { REFRESH_MS } from "./cloud-cadence.mjs";
import { cloudHomeConnectUrl, cloudSetupOf, cloudUnreachableCause, cloudUnreachableText, machineSetup, readyCloudOrigin } from "./cloud-home.mjs";
import { cloudMachine, cloudState, myCloudOf, otherOwnClouds, ownCloud } from "./cloud-list.mjs";
import { cloudOperationAt, createOperationOutages, OPERATION_FRESH_MS, OPERATION_REFRESH_MS } from "./cloud-operation.mjs";
@@ -767,8 +768,11 @@ export function createHomeWindow(deps) {
/** 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 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(); },
+ * no wait holds except the Admin's own 429, and which reads the session again first when its last read began a minute ago. */
+ async retry({ pressed = false } = {}) {
+ if (pressed) { waits.pressed(); await Promise.resolve(account()?.freshen?.()).catch(() => {}); }
+ 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. */
@@ -859,13 +863,14 @@ export function createHomeWindow(deps) {
/** The operation the Admin says has the place on screen down now (cloud-operation.mjs), with a team's or other Cloud's
* `name`, else null: its own page asks while its live stream is down (backing off by itself), so it can say "Updating My
* Cloud" instead of "unable to connect"; the page keeps its own hard end. The session is read again first when the last
- * read is OPERATION_FRESH_MS old or more (the Admin is the one that knows; the place doesn't answer), never while the Admin
- * itself is failing: the account's own retry wait is kept then (cloud-account.mjs `failingUntil`). */
+ * read is OPERATION_FRESH_MS old or more (the Admin is the one that knows; the place doesn't answer); while the Admin itself
+ * is failing, only once its last read began a minute ago (cloud-account.mjs `failingUntil`, `lastAttemptAt`). */
async operation() {
const origin = placeOrigin(), current = state();
if (!origin || current?.status !== "connected") return null;
const client = account(), failing = Number(client?.failingUntil?.() ?? 0);
- if (!(now() - (current.verifiedAt ?? 0) < OPERATION_FRESH_MS) && !(failing > now())) await Promise.resolve(client?.refresh?.()).catch(() => {});
+ const tried = Number(client?.lastAttemptAt?.() ?? 0);
+ if (!(now() - (current.verifiedAt ?? 0) < OPERATION_FRESH_MS) && (!(failing > now()) || now() - tried >= REFRESH_MS)) await Promise.resolve(client?.refresh?.()).catch(() => {});
const operation = cloudOperationAt(state(), origin), name = otherPlace(shown) && shown.origin === origin ? shown.name : null;
return operation ? { ...operation, ...(name ? { name } : {}) } : null;
},
diff --git a/electron/home-window.node-test.mjs b/electron/home-window.node-test.mjs
index ac71ef5f22..5e521c6db9 100644
--- a/electron/home-window.node-test.mjs
+++ b/electron/home-window.node-test.mjs
@@ -435,6 +435,7 @@ test("the window's IPC: the screen reads and retries, My Cloud's page renews its
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]);
+ assert.equal(w.freshens, 1, "only a press reads the sign-in again first (when its last read began a minute ago)");
w.home.retry = retry; w.url = `${LOCAL}${HOME_SCREEN_PATH}`;
assert.throws(() => handlers.get("home:repair")(page), /only available/);
w.state = { status: "signed-out" };
diff --git a/electron/included-x.mjs b/electron/included-x.mjs
index 9e2450a610..63ac645485 100644
--- a/electron/included-x.mjs
+++ b/electron/included-x.mjs
@@ -13,8 +13,10 @@
// the sign-in's answer is only unverified for a while (the Admin unreachable),
// the server holds nothing, and the same sign-in verified again gets the same
// token back without asking. An ask that fails is asked again later, longer
-// each time (cloud-cadence.mjs), never on each state the sign-in publishes.
-import { createBackoff } from "./cloud-cadence.mjs";
+// each time up to 5 minutes (cloud-cadence.mjs), never on each state the
+// sign-in publishes; at once when the window comes to the front (`retryNow`) or
+// the sign-in is verified again after its reads failed.
+import { createBackoff, TOKEN_RETRY_MS } from "./cloud-cadence.mjs";
const paidDevice = (state) =>
state?.status === "connected" && state.entitlement?.plan === "pro" && state.entitlement.status === "active" && typeof state.deviceId === "string"
@@ -44,8 +46,8 @@ export function createIncludedXSync({ fetchAccess, send, device = paidDevice, no
/** The token held when the same sign-in's answer stopped being verified for a while (state "unavailable"). */
let parked = null;
/** Failed asks in a row for the plan key `failingKey`: none again before `failing.until()`, when `retry` asks. */
- const failing = createBackoff({ now, random });
- let failingKey = null, retry = null;
+ const failing = createBackoff({ steps: TOKEN_RETRY_MS, now, random });
+ let failingKey = null, retry = null, healthy = true;
const askLater = (ms) => {
if (retry) timers.clear(retry);
retry = timers.set(() => { retry = null; if (latest) void onState(latest); }, Math.max(1, ms));
@@ -53,6 +55,10 @@ export function createIncludedXSync({ fetchAccess, send, device = paidDevice, no
const unverified = (state, entry) => Boolean(entry) && state?.status === "unavailable" && state.deviceId === entry.deviceId;
const onState = async (state) => {
latest = state;
+ // The sign-in verified again after its reads failed (the Admin is back): a failed ask goes again now.
+ const verified = state?.status === "connected" && !state.checking;
+ if (verified && !healthy) failing.ok();
+ healthy = verified;
const deviceId = device(state);
if (!deviceId) {
if (unverified(state, held)) parked = held;
@@ -93,6 +99,13 @@ export function createIncludedXSync({ fetchAccess, send, device = paidDevice, no
return {
/** Every Cloud account state the desktop publishes. */
onState,
+ /** The window came to the front: an ask that failed goes again now, not at the end of its wait. */
+ retryNow() {
+ if (!failing.waiting()) return;
+ failing.ok();
+ if (retry) { timers.clear(retry); retry = null; }
+ if (latest) void onState(latest);
+ },
/** The local server (re)started and holds nothing yet. */
serverStarted() {
if (held) send(held.access);
diff --git a/electron/included-x.test.mjs b/electron/included-x.test.mjs
index da8cf1e544..a337d16952 100644
--- a/electron/included-x.test.mjs
+++ b/electron/included-x.test.mjs
@@ -89,8 +89,8 @@ describe("included X research access on the desktop", () => {
expect(waits.map((timer) => timer.ms), "then after two minutes").toEqual([120_000]);
await pass(120_000);
expect(fetchAccess).toHaveBeenCalledTimes(3);
- expect(waits.map((timer) => timer.ms), "the Admin's own Retry-After, longer than the next step, is kept").toEqual([900_000]);
- await pass(899_000); await x.onState(paid());
+ expect(waits.map((timer) => timer.ms), "the Admin's own Retry-After, longer than the next step, is kept (spread only later)").toEqual([990_000]);
+ await pass(989_000); await x.onState(paid());
expect(fetchAccess).toHaveBeenCalledTimes(3);
await pass(1_000);
expect(fetchAccess).toHaveBeenCalledTimes(4);
@@ -98,6 +98,24 @@ describe("included X research access on the desktop", () => {
expect(waits).toEqual([]);
});
+ it("never waits more than 5 minutes between asks, and asks at once when the window comes to the front or the sign-in is verified again", async () => {
+ const fetchAccess = vi.fn(async () => { throw new Error("offline"); });
+ const { x, waits, pass } = sync(fetchAccess);
+ await x.onState(paid());
+ for (const ms of [60_000, 120_000, 300_000]) { expect(waits.map((timer) => timer.ms)).toEqual([ms]); await pass(ms); }
+ expect(waits.map((timer) => timer.ms)).toEqual([300_000]);
+ expect(fetchAccess).toHaveBeenCalledTimes(4);
+ x.retryNow(); await pass(0);
+ expect(fetchAccess, "the window came to the front").toHaveBeenCalledTimes(5);
+ expect(waits.map((timer) => timer.ms), "and the count starts again").toEqual([60_000]);
+ x.retryNow(); await pass(0);
+ expect(fetchAccess).toHaveBeenCalledTimes(6);
+ await x.onState({ ...paid(), checking: true }); await x.onState(paid());
+ expect(fetchAccess, "verified again after failed reads").toHaveBeenCalledTimes(7);
+ await x.onState(paid());
+ expect(fetchAccess, "an ordinary refresh asks nothing").toHaveBeenCalledTimes(7);
+ });
+
it("a sign-in unverified for a while gets its token back once verified again, without asking the Admin for a new one", async () => {
const { x, sent, fetchAccess } = sync();
await x.onState(paid());
diff --git a/electron/main.mjs b/electron/main.mjs
index f7efe5f980..c8eb91359e 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(), warn: slog, attended: () => { try { return BrowserWindow.getFocusedWindow() !== null || oneHome.underWay(); } catch { return true; } },
+ openBrowser: url => shell.openExternal(url), awaitingWake: () => cloudPower.awaiting(), warn: slog, attended: () => { try { const win = mainWindow; return BrowserWindow.getFocusedWindow() !== null || Boolean(win && !win.isDestroyed() && win.isVisible() && !win.isMinimized()) || oneHome.underWay(); } catch { return true; } }, // in front or visible (an inactive app's window too), or a move under way
onState: state => {
cloudSync.accountChanged(state.account?.id ?? null); rememberCloudHome(state);
rememberedHome = rememberedCloudHome(rememberedHome, state);
@@ -1951,8 +1951,8 @@ function createWindow({ deferNavigation = false } = {}) {
},
});
mainWindow = win; hiddenStart = false; chromeRail.attach(win);
- win.on("show", () => desktopTray?.windowShown(win));
- win.on("focus", () => { cloudAccount?.freshen(); cloudFocusWake.focused({ shown: !desktopRemoteAccess && win.isVisible() && !win.isMinimized(), showingCloud: placeShown() === "cloud" }); }); win.on("blur", () => cloudFocusWake.blurred({ showingCloud: placeShown() === "cloud" }));
+ win.on("show", () => { desktopTray?.windowShown(win); cloudAccount?.freshen(); }); win.on("restore", () => cloudAccount?.freshen());
+ win.on("focus", () => { cloudAccount?.freshen(); includedX.retryNow(); includedPages.retryNow(); cloudFocusWake.focused({ shown: !desktopRemoteAccess && win.isVisible() && !win.isMinimized(), showingCloud: placeShown() === "cloud" }); }); win.on("blur", () => cloudFocusWake.blurred({ showingCloud: placeShown() === "cloud" }));
win.on("close", (event) => {
if (process.platform === "win32" && !desktopShutdownStarted && desktopTray) {
event.preventDefault();
@@ -2669,7 +2669,7 @@ ipcMain.handle("environments:add-from-link", localWorkspaceOnly("environments:ad
ipcMain.handle("environments:forget", localWorkspaceOnly("environments:forget", (_event, id, purge) => forgetEnvironment(typeof id === "string" ? id : "", purge === true)));
const savedServerStatus = createServerStatus({ entries: () => environmentsState.environments.filter((e) => e.kind === "remote" && !e.home && !e.team && !e.cloud), check: (origin) => checkServer(origin, (...args) => session.defaultSession.fetch(...args)),
appVersion: app.getVersion(), onChange: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("environments:status-changed"); } });
-installServerStatus({ ipcMain, guard: localWorkspaceOnly, status: savedServerStatus, app, powerMonitor, online: () => net.isOnline() }); installUpdateAll({ ipcMain, guard: localWorkspaceOnly, servers: savedServerStatus.saved, fetch: (...args) => session.defaultSession.fetch(...args), send: (channel, view) => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send(channel, view); } }); const appInstaller = createDesktopAppInstaller({ app, shell, nativeImage, env: process.env, platform: process.platform, log: slog }); installAppInstall({ ipcMain, guard: localWorkspaceOnly, installer: appInstaller }); installLocalAppWindows({ ipcMain, guard: localOrHome, BrowserWindow, senderOrigin: (event) => { try { return new URL(event.senderFrame.url).origin; } catch { return null; } }, webPreferences: () => ({ contextIsolation: true, preload: path.join(__dirname, "preload.cjs"), additionalArguments: [...desktopCompanionRendererArguments(rendererOrigin(), desktopRemoteAccess), ...(app.isPackaged && !desktopRemoteAccess ? ["--omb-company-desktop=1"] : []), `--omb-app-version=${app.getVersion()}`, ...(linuxSoftwareRendering ? [SOFTWARE_RENDERING_ARG] : [])] }), openChat: queueChatLink, openExternal: (url) => shell.openExternal(externalLinkUrl(url)), sizes: createAppWindowSizes({ file: () => path.join(app.getPath("userData"), "app-windows.json"), log: slog }), workAreas: () => screen.getAllDisplays().map((display) => display.workArea), icon: APP_ICON, background: () => windowBackground(nativeTheme.shouldUseDarkColors), log: slog, launches: appLaunches, ready: () => app.isReady() && serverReady, launchOrigin: () => rendererOrigin(), windowDetails: (id) => appInstaller.windowDetails(id) });
+installServerStatus({ ipcMain, guard: localWorkspaceOnly, status: savedServerStatus, app, powerMonitor, online: () => net.isOnline() }); installUpdateAll({ ipcMain, guard: localWorkspaceOnly, servers: savedServerStatus.saved, fetch: (...args) => session.defaultSession.fetch(...args), send: (channel, view) => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send(channel, view); } }); const appInstaller = createDesktopAppInstaller({ app, shell, nativeImage, env: process.env, platform: process.platform, log: slog }); installAppInstall({ ipcMain, guard: localWorkspaceOnly, installer: appInstaller }); installLocalAppWindows({ ipcMain, guard: localOrHome, BrowserWindow, senderOrigin: (event) => { try { return new URL(event.senderFrame.url).origin; } catch { return null; } }, webPreferences: () => ({ contextIsolation: true, preload: path.join(__dirname, "preload.cjs"), additionalArguments: [...desktopCompanionRendererArguments(rendererOrigin(), desktopRemoteAccess), ...(app.isPackaged && !desktopRemoteAccess ? ["--omb-company-desktop=1"] : []), `--omb-app-version=${app.getVersion()}`, ...(linuxSoftwareRendering ? [SOFTWARE_RENDERING_ARG] : [])] }), openChat: queueChatLink, openExternal: (url) => shell.openExternal(externalLinkUrl(url)), sizes: createAppWindowSizes({ file: () => path.join(app.getPath("userData"), "app-windows.json"), log: slog }), workAreas: () => screen.getAllDisplays().map((display) => display.workArea), icon: APP_ICON, background: () => windowBackground(nativeTheme.shouldUseDarkColors), log: slog, launches: appLaunches, ready: () => app.isReady() && serverReady, launchOrigin: () => rendererOrigin(), windowDetails: (id) => appInstaller.windowDetails(id) }); for (const signal of ["resume", "unlock-screen"]) powerMonitor.on(signal, () => cloudAccount?.freshen()); // a woken computer reads its MausBot Cloud sign-in at once
// A cloud page may open the native chooser, never choose a destination or edit the saved list.
// Once My Cloud is home the switcher lists only whole places, and shows only when there is more than My Cloud.
diff --git a/electron/move-status.node-test.mjs b/electron/move-status.node-test.mjs
index cbd736238d..eff9564c90 100644
--- a/electron/move-status.node-test.mjs
+++ b/electron/move-status.node-test.mjs
@@ -382,9 +382,9 @@ test("a send that fails waits longer each time, whatever changes meanwhile, and
await h.pass(18 * 60_000);
assert.equal(h.sent.length, 7, "the next half hour's try is refused for an hour");
await h.pass(57 * 60_000);
- assert.equal(h.sent.length, 7, "an hour, as the Admin asked, rather than the next half hour");
+ assert.equal(h.sent.length, 7, "an hour, as the Admin asked (spread only later), rather than the next half hour");
h.answer = async () => true;
- await h.pass(4 * 60_000);
+ await h.pass(10 * 60_000);
assert.equal(h.sent.length, 8);
h.body = { ...h.body, passes: 3 };
h.r.changed();
diff --git a/electron/updates-consent.d.mts b/electron/updates-consent.d.mts
index bfa1df1d31..ceb17e9047 100644
--- a/electron/updates-consent.d.mts
+++ b/electron/updates-consent.d.mts
@@ -1,6 +1,7 @@
export type UpdatesConsentStatus = "opted_in" | "declined" | "withdrawn";
export declare const UPDATES_CONSENT_VERSION: string;
export declare const UPDATES_CONSENT_STATUSES: readonly UpdatesConsentStatus[];
+export declare const UPDATES_CONSENT_RECHECK_MS: number;
export interface UpdatesConsentRecord {
status: UpdatesConsentStatus; version: string; at: number;
account?: string; email?: string; receipt?: string; replacedReceipts?: string[]; pending?: true;
diff --git a/electron/updates-consent.mjs b/electron/updates-consent.mjs
index fa75868df5..494733660e 100644
--- a/electron/updates-consent.mjs
+++ b/electron/updates-consent.mjs
@@ -11,6 +11,9 @@ const RECEIPT = /^[A-Za-z0-9_-]{43}$/;
// oxlint-disable-next-line no-control-regex
const text = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max && !/[\x00-\x1f\x7f]/.test(value);
const STATE_WAIT_MS = 8_000;
+/** A look asks the Admin again once the last read that put this computer in step with it is this old: an answer changed on the
+ * website shows without a restart, and pages asking often never each ask. */
+export const UPDATES_CONSENT_RECHECK_MS = 10 * 60_000;
/**
* The record kept on this computer. `account`: the MausBot Cloud account the answer belongs to (given while signed in,
@@ -62,13 +65,14 @@ export function parseAccountConsent(result) {
* `account()`: the Cloud account client (cloud-account.mjs), or null where there is none. `available()`: this app may
* ask at all (the installed app, not a branded build). A failure to reach the Admin never loses an answer: it stays
* `pending` and is sent again on the next launch, sign-in or look at Settings, after a wait that grows with each failure.
- * Once this computer's answer is in step with the Admin's for the account signed in, the Admin is not asked again this
- * run until another account signs in or an answer waits to be sent: a page asking for the state is answered from here.
+ * Once this computer's answer is in step with the Admin's for the account signed in, a page asking for the state is
+ * answered from here; the Admin is asked again when another account signs in, an answer waits to be sent, or that read is
+ * UPDATES_CONSENT_RECHECK_MS old.
*/
export function createUpdatesConsent({ prefs, account, available, now = Date.now, onChange = () => {}, random = Math.random }) {
let running = null, choices = 0;
/** The account (null: signed out) whose answer is in step with the Admin's this run; undefined before the first. */
- let settled, failedFor;
+ let settled, settledAt = -Infinity, failedFor;
/** Failures in a row for the account `failedFor`: another account signing in asks at once. */
const failing = createBackoff({ now, random });
const client = () => account();
@@ -170,7 +174,7 @@ export function createUpdatesConsent({ prefs, account, available, now = Date.now
const sameAnswer = () => choices === answer;
const fresh = () => sameAnswer() && (signedIn()?.id ?? null) === who;
try { await reconcile(sameAnswer, fresh); } catch (error) { if (fresh()) { if (failedFor !== who) failing.ok(); failedFor = who; failing.failed(error); throw error; } }
- if (fresh()) { settled = who; failing.ok(); return; }
+ if (fresh()) { settled = who; settledAt = now(); failing.ok(); return; }
}
}
@@ -180,7 +184,7 @@ export function createUpdatesConsent({ prefs, account, available, now = Date.now
const local = prefs.updatesConsent(), who = signedIn()?.id ?? null;
// An answer this sign-in (or no sign-in) can send now; another account's waits for that account.
const waiting = Boolean((local?.pending && (local.account ?? null) === who) || local?.replacedReceipts?.length || (who && local?.pendingAccounts?.some(choice => choice.account === who)));
- return (waiting || settled !== who) && !(failedFor === who && failing.waiting());
+ return (waiting || settled !== who || now() - settledAt >= UPDATES_CONSENT_RECHECK_MS) && !(failedFor === who && failing.waiting());
};
const snapshot = () => {
diff --git a/electron/updates-consent.node-test.mjs b/electron/updates-consent.node-test.mjs
index af4c39f98e..687a111322 100644
--- a/electron/updates-consent.node-test.mjs
+++ b/electron/updates-consent.node-test.mjs
@@ -3,7 +3,7 @@ import { createServer } from "node:http";
import test from "node:test";
import { createCloudAccountClient } from "./cloud-account.mjs";
import { createDesktopPrefs, registerDesktopPrefs } from "./desktop-prefs.mjs";
-import { createUpdatesConsent, parseUpdatesConsent, registerUpdatesConsent, UPDATES_CONSENT_VERSION } from "./updates-consent.mjs";
+import { createUpdatesConsent, parseUpdatesConsent, registerUpdatesConsent, UPDATES_CONSENT_RECHECK_MS, UPDATES_CONSENT_VERSION } from "./updates-consent.mjs";
// The real Cloud client and desktop prefs against a fake Admin on loopback: what this computer keeps, and what reaches
// the Admin's consent endpoints (account: GET/POST /api/cloud/desktop/updates-consent; no account: POST /api/updates-consent).
@@ -159,6 +159,20 @@ test("the account's answer is read once per sign-in: later looks are answered he
assert.equal(f.requests.length, 4);
});
+test("an answer changed on the website shows on a look once the last read is 10 minutes old, without a restart", async t => {
+ const f = await world(t);
+ await f.signInNow();
+ f.account = { status: "opted_in", textVersion: UPDATES_CONSENT_VERSION, source: "cloud_page", decidedAt: f.now };
+ assert.equal((await f.consent.state()).status, "opted_in");
+ f.account = { status: "withdrawn", textVersion: UPDATES_CONSENT_VERSION, source: "cloud_page", decidedAt: f.now };
+ f.now += UPDATES_CONSENT_RECHECK_MS - 1_000;
+ assert.equal((await f.consent.state()).status, "opted_in", "under 10 minutes: answered from here");
+ f.now += 1_000;
+ assert.equal((await f.consent.state()).status, "withdrawn");
+ assert.deepEqual(f.requests.map(({ method }) => method), ["GET", "GET"]);
+ assert.equal(UPDATES_CONSENT_RECHECK_MS, 10 * 60_000);
+});
+
test("an answer given while signed out is carried over to an account that has none, with no second question", async t => {
const f = await world(t);
await f.consent.choose({ status: "opted_in" });