Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Reduce background requests to the account server
milind-soni0e11a12357d1
diff --git a/electron/cloud-account-clouds.node-test.mjs b/electron/cloud-account-clouds.node-test.mjsindex a58388b484..afe2decb7c 100644--- a/electron/cloud-account-clouds.node-test.mjs+++ b/electron/cloud-account-clouds.node-test.mjs@@ -43,7 +43,7 @@ async function admin(t) {const saved = { origin: f.origin, token: accessToken, expiresAt: NOW + 86400_000, device: { id: "device-1" }, account: { id: "acct-1", email: "[email protected]" } };f.client = createCloudAccountClient({ origin: f.origin, fixture: true, deviceName: "Fixture computer", platform: "darwin", appVersion: "0.1.fixture", now: () => NOW,store: { read: async () => saved, write: async () => {} }, openBrowser: async url => { f.browsers.push(url); },- setTimer: (callback, delay) => { f.timer = callback; f.delay = delay; return 1; }, clearTimer: () => { f.timer = null; f.delay = null; } });+ setTimer: (callback, delay) => { f.timer = callback; f.delay = delay; return 1; }, clearTimer: () => { f.timer = null; f.delay = null; }, random: () => 0.5 });t.after(async () => { f.client.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); });return f;}diff --git a/electron/cloud-account.d.mts b/electron/cloud-account.d.mtsindex 23b9f03d52..6b9ee92979 100644--- a/electron/cloud-account.d.mts+++ b/electron/cloud-account.d.mts@@ -294,6 +294,8 @@ 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;signOut(): Promise<CloudAccountState>;openDashboard(): Promise<CloudAccountState>;offer(): Promise<import("./cloud-home.mjs").CloudOffer | null>;@@ -404,6 +406,10 @@ export declare function createCloudAccountClient(options: {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;+ /** 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. */+ attended?: () => boolean;}): 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 66772c66db..2c2ebac4b4 100644--- a/electron/cloud-account.mjs+++ b/electron/cloud-account.mjs@@ -1,7 +1,7 @@import { createManagedDesktopStore, retryDelay, unreadableRecord } from "./managed-desktop.mjs";import { 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 { anyOperation, OPERATION_REFRESH_MS } from "./cloud-operation.mjs";+import { anyOperation, OPERATION_REFRESH_MS } from "./cloud-operation.mjs"; import { IDLE_REFRESH_MS, jittered, jitteredBelow, REFRESH_MS, sessionRetryWait } from "./cloud-cadence.mjs";import { planTeam, teamPlan } from "./cloud-team-plan.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";@@ -24,7 +24,6 @@ const PRIVATE_CODE = /^[A-Za-z0-9_-]{43}$/;/** What the Admin says of a Cloud of this account's a computer moved to (POST moved-to). */const MOVED_TO = Object.freeze(["deleted", "ended", "live", "unknown"]);const TIER = /^[a-z][a-z0-9-]{0,23}$/;-const REFRESH_MS = 60_000;const STEADY_MS = 15 * 60_000;const SETUP_REFRESH_MS = 15_000;/** While My Cloud sleeps and Files or lending waits for it: the session every 15 s, so they resume soon after it wakes. */@@ -99,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, readWaitMs = READ_WAIT_MS }) {+ setTimer = setTimeout, clearTimer = clearTimeout, warn = message => console.warn(message), awaitingWake = () => false, t = englishText.t, readWaitMs = READ_WAIT_MS, random = Math.random, attended = () => true }) {origin = cloudOrigin(origin, fixture);const staging = origin === STAGING_CLOUD_ORIGIN;let grant = null, issued = null, cleanup = null, pending = null, cleanupNeeded = false;@@ -308,12 +307,12 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNconst settingUp = planCloud?.status === "provisioning" || (access.status === "active" && !planCloud) || Boolean(purchase) || otherOwnClouds(clouds).some(cloud => cloud.status === "setting_up");const added = adding ? clouds?.find(cloud => cloud.id === adding.cloudId) ?? null : null;const paying = watchingAdd() && Boolean(adding.url) && (!added || added.status === "checkout");- const delay = (watching() && planCloud?.status !== "ready") || paying ? WATCH_REFRESH_MS : settingUp ? SETUP_REFRESH_MS : awaitingWake() ? ASLEEP_REFRESH_MS : anyOperation(machine, clouds) ? OPERATION_REFRESH_MS : REFRESH_MS; // an operation of ours: sooner- schedule(refresh, Math.min(delay, verifiedUntil - now()));+ const delay = (watching() && planCloud?.status !== "ready") || paying ? WATCH_REFRESH_MS : settingUp ? SETUP_REFRESH_MS : awaitingWake() ? ASLEEP_REFRESH_MS : anyOperation(machine, clouds) ? OPERATION_REFRESH_MS : attended() ? REFRESH_MS : IDLE_REFRESH_MS; // an operation of ours: sooner; nobody looking and nothing under way: every 5 minutes, spread ±20%; the rest spread only sooner+ schedule(refresh, Math.min(delay === IDLE_REFRESH_MS ? jittered(delay, random) : jitteredBelow(delay, random), verifiedUntil - now()));} 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 = Math.min(retryDelay(failures), grant.expiresAt - now()); failingUntil = now() + Math.max(0, wait); // `failingUntil` below+ failures++; const wait = sessionRetryWait(failures, { retryAfter: error?.retryAfter, expiresIn: grant.expiresAt - now(), verifiedIn: verifiedUntil - now(), random }); failingUntil = now() + Math.max(0, wait); // `failingUntil` belowif (value.status === "connected") publish(value);else publish(view("unavailable", "unreachable"));schedule(refresh, wait);@@ -526,6 +525,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN},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/** 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() {diff --git a/electron/cloud-account.node-test.mjs b/electron/cloud-account.node-test.mjsindex 5c21b6a047..8ce17cedd1 100644--- a/electron/cloud-account.node-test.mjs+++ b/electron/cloud-account.node-test.mjs@@ -57,11 +57,11 @@ test("a failed check keeps the last verified answer (never a malformed one), sayassert.deepEqual(state.lastPlan, { tier: "max", active: true });});-test("a check that fails is asked again after 15 s, 30 s, then each minute", async t => {+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();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, 60_000]) { f.tick(); await until(() => f.timer); assert.equal(f.delay, delay); }+ 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); }f.sessionStatus = 200; f.tick(); await until(() => f.timer); assert.equal(f.client.failingUntil(), 0);f.sessionStatus = 503; f.tick(); await until(() => f.timer);assert.equal(f.delay, 15_000, "an answer starts the count again");diff --git a/electron/cloud-background.node-test.mjs b/electron/cloud-background.node-test.mjsnew file mode 100644index 0000000000..f1994c62e9--- /dev/null+++ b/electron/cloud-background.node-test.mjs@@ -0,0 +1,223 @@+// What a signed-in app asks the Admin by itself, counted per hour: the session, the move's report, the pages and+// research relay tokens and the product-updates answer, wired as main.mjs wires them (its `onState`), over a fake clock and a+// fake Admin. Nobody touches the app here: these are background requests only.+import assert from "node:assert/strict";+import test from "node:test";++import { createCloudAccountClient } from "./cloud-account.mjs";+import { fixture, until } from "./fixtures/cloud-account.mjs";+import { createDesktopIncludedPages } from "./included-pages.mjs";+import { createDesktopIncludedX } from "./included-x.mjs";+import { installOneHome } from "./one-home-main.mjs";+import { createUpdatesConsent } from "./updates-consent.mjs";++const ORIGIN = "http://127.0.0.1:9";+const TOKEN = `omc_${"T".repeat(43)}`;+const HOUR = 3_600_000;+const CLOUD = "https://home-7f3k2.fly.dev";+const json = (value, status = 200, headers = {}) => new Response(JSON.stringify(value), { status, headers: { "content-type": "application/json", ...headers } });++/**+ * One signed-in app. `paid`: an active plan with a ready Cloud of its own (moves off, so no move starts), else a free+ * account without one. `admin(key)`: a test's own answer for a route ("GET session", "POST move-status", ...), or+ * undefined for the healthy one; it may throw to stand for no answer at all. `attended()`: the window is in front.+ */+function app({ paid = false, admin = () => undefined, attended = () => false } = {}) {+ let clock = 1_800_000_000_000, journal = null, keep = null, consent = { status: "opted_in", version: "2026-10-23", at: 1, account: "acct-1" };+ const queue = [], counts = {}, realNow = Date.now, realRandom = Math.random;+ // Every wait unspread (a draw of 0.5), so the counts below are exact.+ Date.now = () => clock; Math.random = () => 0.5;+ const timers = { set: (work, ms) => { const timer = { work, at: clock + Math.max(0, ms) }; queue.push(timer); return timer; }, clear: (timer) => { const at = queue.indexOf(timer); if (at >= 0) queue.splice(at, 1); } };+ const session = () => ({ cloudContractVersion: 1, expiresAt: clock + 30 * 24 * HOUR, device: { id: "device-1" }, account: { id: "acct-1", email: "[email protected]" },+ entitlement: paid ? { plan: "pro", tier: "personal", status: "active", expiresAt: clock + 20 * 24 * HOUR, version: 3 } : { plan: "free", status: "inactive", expiresAt: null, version: 0 },+ ...(paid ? { cloud: { state: "ready", origin: CLOUD } } : {}), clouds: [], latestVersion: "0.1.182" });+ const healthy = (key) => {+ if (key === "GET session") return json(session());+ if (key === "POST move-status") return json({ cloudContractVersion: 1, recorded: true });+ if (key === "POST services/pages") return json({ cloudContractVersion: 1, url: `${ORIGIN}/api/pages/token`, token: `omb_pd_${"P".repeat(43)}` });+ if (key === "POST services/x") return paid ? json({ cloudContractVersion: 1, url: `${ORIGIN}/api/x`, token: `omb_xd_${"X".repeat(43)}` }) : json({ error: "subscription_inactive" }, 402);+ if (key === "GET updates-consent") return json({ cloudContractVersion: 1, consent: { status: "opted_in", textVersion: "2026-10-23" } });+ return json({ error: "not_found" }, 404);+ };+ const fetch = async (url, init = {}) => {+ const key = `${init.method ?? "GET"} ${new URL(url).pathname.replace("/api/cloud/desktop/", "")}`;+ counts[key] = (counts[key] ?? 0) + 1;+ return (await admin(key)) ?? healthy(key);+ };+ const saved = { origin: ORIGIN, token: TOKEN, expiresAt: clock + 30 * 24 * HOUR, device: { id: "device-1" }, account: { id: "acct-1", email: "[email protected]" } };+ let main = null, includedX = null, includedPages = null, updates = null;+ const client = createCloudAccountClient({ origin: ORIGIN, fixture: true, deviceName: "Fixture computer", platform: "darwin", appVersion: "0.1.182", now: () => clock, fetch,+ store: { read: async () => saved, write: async () => {} }, openBrowser: async () => {}, warn: () => {},+ setTimer: timers.set, clearTimer: timers.clear, random: () => 0.5, attended,+ // As main.mjs's `onState`: everything that follows the sign-in hears each state.+ onState: (state) => { void main?.kick(); void includedX?.onState(state); void includedPages?.onState(state); updates?.accountChanged(state); } });+ main = installOneHome({+ ipcMain: { handle: () => {} }, cloudPage: () => "local", server: () => null, home: () => null, cookieFetch: async () => json({}, 401),+ reconnect: async () => false, power: { asleep: () => false }, file: () => "/nonexistent/cloud-send.json", window: () => null, localOrigin: () => "http://127.0.0.1:4100",+ fetch: async () => json({}, 404), account: () => client, journalFile: () => "/nonexistent/one-home.json", tempRoot: () => "/nonexistent",+ localRequest: async (route) => (route === "/api/move/freeze" ? json({ frozen: false }) : json({}, 404)),+ journal: { read: () => journal, write: (value) => { journal = value; } }, keep: { read: () => keep, write: (value) => { keep = value; } },+ version: "0.1.182", reportTimers: timers,+ });+ includedX = createDesktopIncludedX({ account: () => client, server: () => null, log: () => {}, now: () => clock, timers });+ includedPages = createDesktopIncludedPages({ account: () => client, server: () => null, log: () => {}, now: () => clock, timers });+ updates = createUpdatesConsent({ prefs: { installId: () => "install-1", updatesConsent: () => consent, setUpdatesConsent: (value) => { consent = value; return true; } },+ account: () => client, available: async () => true, now: () => clock });+ const settle = async () => { for (let i = 0; i < 30; i++) await new Promise((resolve) => setImmediate(resolve)); };+ return {+ client, updates, counts,+ now: () => clock,+ started: 0,+ async start() { await client.start(); await settle(); },+ /** Moves the clock on, running each timer that comes due on the way. */+ async pass(ms) {+ const until = clock + ms;+ for (;;) {+ queue.sort((a, b) => a.at - b.at);+ const next = queue[0];+ if (!next || next.at > until) break;+ queue.shift();+ clock = next.at;+ next.work();+ await settle();+ }+ clock = until;+ await settle();+ },+ /** Counts from now on. */+ reset() { for (const key of Object.keys(counts)) delete counts[key]; this.started = clock; },+ close() { main.close(); client.close(); Date.now = realNow; Math.random = realRandom; },+ };+}++const ROUTES = ["GET session", "POST move-status", "POST services/pages", "POST services/x", "GET updates-consent"];+/** An hour's requests per route, after the first ten minutes (the launch's own asks: the session, one report, one of each token, the updates answer). */+async function hour(options, during = async () => {}) {+ const a = app(options);+ try {+ await a.start();+ await a.pass(10 * 60_000);+ a.reset();+ await during(a);+ await a.pass(HOUR - (a.now() - a.started));+ return Object.fromEntries(ROUTES.map((route) => [route, a.counts[route] ?? 0]));+ } finally { a.close(); }+}+const failing = {+ "503": () => json({ error: "unavailable" }, 503),+ "429 with Retry-After": () => json({ error: "rate_limited" }, 429, { "retry-after": "60" }),+ "no answer": () => { throw Object.assign(new Error("The operation was aborted due to timeout"), { name: "TimeoutError" }); },+};++// Before this change, measured the same way on the code it replaced: an idle signed-in app sent 60 session reads and 4 move+// reports an hour with a healthy Admin; with an Admin failing the other routes, 60 move reports, 60 pages token asks and+// (on a paid plan) 60 research relay token asks an hour on top, one per session read, since each read's state asked again.+test("an idle signed-in app, healthy Admin, window in the back: 12 session reads an hour and nothing else (was 60 + 4 move reports)", async () => {+ for (const paid of [false, true]) {+ const counts = await hour({ paid });+ assert.deepEqual(counts, { "GET session": 12, "POST move-status": 0, "POST services/pages": 0, "POST services/x": 0, "GET updates-consent": 0 }, paid ? "paid" : "free");+ }+});++test("the same app with its window in front reads the session every minute, as before, and still nothing else", async () => {+ const counts = await hour({ paid: true, attended: () => true });+ 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 () => {+ 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);+ }+});++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() });+ assert.deepEqual(counts, { "GET session": 12, "POST move-status": 2, "POST services/pages": 0, "POST services/x": 0, "GET updates-consent": 0 }, name);+ }+});++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 () => {+ 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);+});++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 () => {+ let down = false;+ const counts = await hour({ paid: true, admin: () => (down ? json({ error: "unavailable" }, 503) : undefined) }, async (a) => {+ down = true;+ await a.pass(20 * 60_000);+ assert.equal(a.client.state().status, "unavailable", "the verified answer stopped counting meanwhile");+ down = false;+ await a.pass(6 * 60_000);+ assert.equal(a.client.state().status, "connected");+ });+ // 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["POST move-status"], 3, "the report says it is unverified, and verified again, as each changes");+});++test("coming to the front reads the session at once when its answer is a minute old, and not again within the minute", async () => {+ let front = false;+ const a = app({ attended: () => front });+ try {+ await a.start();+ await a.pass(2 * 60_000);+ a.reset();+ front = true;+ a.client.freshen();+ await a.pass(1_000);+ assert.equal(a.counts["GET session"], 1);+ a.client.freshen();+ await a.pass(30_000);+ assert.equal(a.counts["GET session"], 1);+ await a.pass(30_000);+ assert.equal(a.counts["GET session"], 2, "in front: every minute from then on");+ } finally { a.close(); }+});++// 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" } };+ await f.client.refresh();+ assert.equal(f.delay, 600_000, "the Admin's own wait, not 15 s");+ assert.equal(f.client.state().status, "connected");+});++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 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");+ 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");+});++test("nobody looking and nothing under way: the session every 5 minutes, spread a fifth either way; in front, every minute and never later; coming to the front reads it at once", async t => {+ let front = false, draw = 0.5;+ const f = await fixture(t, { attended: () => front, random: () => draw }); await f.connect();+ assert.equal(f.delay, 300_000);+ for (const [drawn, delay] of [[0, 240_000], [1, 360_000]]) { draw = drawn; await f.client.refresh(); assert.equal(f.delay, delay); }+ draw = 0.5;+ const before = f.requests.length;+ f.client.freshen();+ assert.equal(f.requests.length, before, "an answer under a minute old is not asked again");+ f.now += 61_000; front = true;+ f.client.freshen(); await until(() => f.requests.length === before + 1);+ await until(() => f.delay === 60_000);+ for (const [drawn, delay] of [[0, 48_000], [1, 48_000], [0.5, 60_000]]) { draw = drawn; await f.client.refresh(); assert.equal(f.delay, delay, "in front: never later than every minute"); }+ // A sign-in that must be redone is never read on coming to the front.+ f.revoked = true; await f.client.refresh();+ const ended = f.requests.length;+ f.now += 120_000; f.client.freshen();+ assert.equal(f.requests.length, ended);+});diff --git a/electron/cloud-cadence.mjs b/electron/cloud-cadence.mjsnew file mode 100644index 0000000000..9e9f70e723--- /dev/null+++ b/electron/cloud-cadence.mjs@@ -0,0 +1,60 @@+// How often this app asks the MausBot Cloud Admin by itself, and how long it waits after an ask that failed. Every wait+// is spread by ±20% (`jittered`), so thousands of apps started together never ask in step, and an Admin that fails is+// asked less and less often, never sooner than its own Retry-After.++/** The session's steady re-read while the window is in front, or a move to My Cloud is under way. */+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. */+export const SESSION_RETRY_MS = Object.freeze([15_000, 30_000, 60_000, 120_000, 240_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. */+const RETRY_AFTER_MAX_MS = 60 * 60_000;+const SPREAD = 0.2;++/** `ms` spread by up to ±20%: `random()` 0.5 leaves it as it is. */+export function jittered(ms, random = Math.random) {+ const drawn = Number(random());+ const spread = Number.isFinite(drawn) ? Math.min(1, Math.max(0, drawn)) * 2 - 1 : 0;+ return Math.max(1, Math.round(ms * (1 + spread * SPREAD)));+}++/** `ms` spread down by up to 20%, never later (`random()` 0.5 leaves it as it is): a cadence the person may be watching+ * gets no staler than it was. */+export function jitteredBelow(ms, random = Math.random) {+ const drawn = Number(random());+ const spread = Number.isFinite(drawn) ? Math.abs(Math.min(1, Math.max(0, drawn)) * 2 - 1) : 0;+ return Math.max(1, Math.round(ms * (1 - spread * 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 } = {}) {+ 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);+}++/** 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);+}++/**+ * One background ask's failures in a row: `failed(error)` notes one and says until when not to ask again, `ok()` starts+ * the count again, `waiting()` is true until then.+ */+export function createBackoff({ steps = ASK_RETRY_MS, now = Date.now, random = Math.random } = {}) {+ let failures = 0, until = 0;+ return {+ failed(error) { failures++; until = now() + retryWait(failures, { steps, retryAfter: error?.retryAfter, random }); return until; },+ ok() { failures = 0; until = 0; },+ waiting: () => until > now(),+ until: () => until,+ };+}diff --git a/electron/fixtures/cloud-account.mjs b/electron/fixtures/cloud-account.mjsindex 6adf6cc33b..4a5f5fffc6 100644--- a/electron/fixtures/cloud-account.mjs+++ b/electron/fixtures/cloud-account.mjs@@ -55,7 +55,7 @@ export async function fixture(t, options = {}) {if (req.method === "DELETE") { if (f.sessionPage) { res.writeHead(f.sessionPage, { "content-type": "text/html" }); return res.end("<!doctype html>Attention required"); } if (f.sessionStatus === 503) return send(503, { error: "unavailable" }); f.revoked = true; return send(200, { revoked: true }); }if (f.revoked) return send(401, { error: "invalid_token" });if (f.sessionPage) { res.writeHead(f.sessionPage, { "content-type": "text/html" }); return res.end("<!doctype html>Attention required"); }- if (f.sessionError) return send(f.sessionError.status, f.sessionError.body);+ if (f.sessionError) { res.writeHead(f.sessionError.status, { "content-type": "application/json", ...f.sessionError.headers }); return res.end(JSON.stringify(f.sessionError.body)); }if (f.sessionStatus !== 200) return send(f.sessionStatus, { error: "unavailable" });return send(200, { ...identity(), ...(f.invalidIdentity ? { account: { id: "someone-else", email: "[email protected]" } } : {}),entitlement: f.invalidEntitlement ? { plan: "pro", status: "active" } : f.entitlement, ...(f.cloud === undefined ? {} : { cloud: f.cloud }),@@ -68,7 +68,7 @@ export async function fixture(t, options = {}) {f.client = createCloudAccountClient({ origin: f.origin, fixture: true, deviceName: "Fixture computer", platform: "darwin", appVersion: "0.1.fixture", now: () => f.now,store: { read: async () => f.saved, write: async value => { if (f.failWrite) throw new Error("fixture storage failure"); f.saved = structuredClone(value); } },openBrowser: async url => { f.browsers.push(url); }, onState: state => f.states.push(state),- setTimer: (callback, delay) => { f.timer = callback; f.delay = delay; return 1; }, clearTimer: () => { f.timer = null; f.delay = null; }, ...options });+ setTimer: (callback, delay) => { f.timer = callback; f.delay = delay; return 1; }, clearTimer: () => { f.timer = null; f.delay = null; }, random: () => 0.5, ...options });f.tick = () => { const callback = f.timer; assert.ok(callback); f.timer = null; callback(); };f.connect = async () => { await f.client.begin(); f.approved = true; f.tick(); await until(() => f.client.state().status === "connected"); };t.after(async () => { f.client.close(); server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); });diff --git a/electron/included-pages.mjs b/electron/included-pages.mjsindex 5c967e483b..35bdd17d45 100644--- a/electron/included-pages.mjs+++ b/electron/included-pages.mjs@@ -1,6 +1,7 @@// Published pages' access on the desktop: every signed-in MausBot account may publish (a free one has its free pages),// so as soon as this computer is signed in, its sign-in's own pages token is fetched from the Admin once and handed to// the local server over the private parent port (server/pages/access.ts). Kept in memory only; a sign-out clears it.+// A failed fetch is tried again later, longer each time (included-x.mjs).import { createIncludedXSync } from "./included-x.mjs";const signedInDevice = (state) => state?.status === "connected" && typeof state.deviceId === "string" ? state.deviceId : null;@@ -9,8 +10,9 @@ const signedInDevice = (state) => state?.status === "connected" && typeof state.* @param {{ account: () => { pagesAccess(): Promise<{ url: string; token: string } | null> } | null,* server: () => { postMessage(message: unknown): void } | null, log: (line: string) => void }} options*/-export function createDesktopIncludedPages({ account, server, log }) {+export function createDesktopIncludedPages({ account, server, log, ...cadence }) {return createIncludedXSync({+ ...cadence,device: signedInDevice,fetchAccess: () => account()?.pagesAccess() ?? Promise.resolve(null),send: (access, note) => {diff --git a/electron/included-x.mjs b/electron/included-x.mjsindex def96f606f..9e2450a610 100644--- a/electron/included-x.mjs+++ b/electron/included-x.mjs@@ -9,7 +9,12 @@// active there, or X research is off), that answer stands for the sign-in and// its plan version, and the server is told it is not offered, so the app says// so instead of connecting forever. A server restart gets the held token-// again; a plan that stopped, a sign-out or a sign-in to redo clears it.+// again; a plan that stopped, a sign-out or a sign-in to redo clears it. While+// 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";const paidDevice = (state) =>state?.status === "connected" && state.entitlement?.plan === "pro" && state.entitlement.status === "active" && typeof state.deviceId === "string"@@ -18,11 +23,14 @@ const paidDevice = (state) =>/*** @param {{ fetchAccess: () => Promise<{ url: string; token: string } | null>,* send: (access: { url: string; token: string } | null, note?: { offered: false }) => void,- * device?: (state: any) => string | null }} options+ * device?: (state: any) => string | null, now?: () => number, random?: () => number,+ * timers?: { set(work: () => void, ms: number): unknown, clear(timer: unknown): void } }} options* `fetchAccess` asks the Admin (null: the plan is not active there, or X research is not offered); `send` posts to the server.- * `device`: the sign-in that gets access, or null for none (default: one on an active paid plan).+ * `device`: the sign-in that gets access, or null for none (default: one on an active paid plan). `timers`: the wait+ * before asking again after a failure (setTimeout's by default).*/-export function createIncludedXSync({ fetchAccess, send, device = paidDevice }) {+export function createIncludedXSync({ fetchAccess, send, device = paidDevice, now = Date.now, random = Math.random,+ timers = { set: (work, ms) => { const timer = setTimeout(work, ms); timer.unref?.(); return timer; }, clear: (timer) => clearTimeout(timer) } }) {/** The sign-in and the plan's version: a changed plan asks again after a no. */const planKey = (state) => `${device(state)}@${state?.entitlement?.version ?? ""}`;/** @type {{ deviceId: string; access: { url: string; token: string } } | null} */@@ -33,28 +41,47 @@ export function createIncludedXSync({ fetchAccess, send, device = paidDevice })let latest = null;/** @type {Promise<void> | null} */let inflight = null;+ /** 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 askLater = (ms) => {+ if (retry) timers.clear(retry);+ retry = timers.set(() => { retry = null; if (latest) void onState(latest); }, Math.max(1, ms));+ };+ const unverified = (state, entry) => Boolean(entry) && state?.status === "unavailable" && state.deviceId === entry.deviceId;const onState = async (state) => {latest = state;const deviceId = device(state);if (!deviceId) {+ if (unverified(state, held)) parked = held;+ else if (!unverified(state, parked)) parked = null;// Clears a held token, or the server's note that the Admin said no.if (held || refused) { held = null; refused = null; send(null); }return;}if (held?.deviceId === deviceId || refused === planKey(state)) return;- if (inflight) return inflight;+ if (parked?.deviceId === deviceId) { held = parked; parked = null; send(held.access); return; }+ parked = null;const key = planKey(state);+ // Another sign-in or plan asks at once; the same one waits out its failures.+ if (failingKey !== key) { failing.ok(); failingKey = key; }+ if (failing.waiting()) return;+ if (inflight) return inflight;inflight = (async () => {try {const access = await fetchAccess();+ failing.ok();// The sign-in or plan changed while asking: this answer is for a state that is gone.if (planKey(latest) !== key) return;if (access) { held = { deviceId, access }; refused = null; send(access); }else { held = null; refused = key; send(null, { offered: false }); }- } catch {- // Offline or the Admin is down: the next state change tries again. Another sign-in's token never stays with the server- // meanwhile: the account in use just changed, and its bots would run on the one before.+ } catch (error) {+ // Offline or the Admin is down: asked again after a wait, longer each time. Another sign-in's token never stays with+ // the server meanwhile: the account in use just changed, and its bots would run on the one before.if (held && held.deviceId !== deviceId && planKey(latest) === key) { held = null; send(null); }+ if (planKey(latest) === key) askLater(failing.failed(error) - now());} finally {inflight = null;}@@ -78,8 +105,9 @@ export function createIncludedXSync({ fetchAccess, send, device = paidDevice })* @param {{ account: () => { xResearchAccess(): Promise<{ url: string; token: string } | null> } | null,* server: () => { postMessage(message: unknown): void } | null, log: (line: string) => void }} options*/-export function createDesktopIncludedX({ account, server, log }) {+export function createDesktopIncludedX({ account, server, log, ...cadence }) {return createIncludedXSync({+ ...cadence,fetchAccess: () => account()?.xResearchAccess() ?? Promise.resolve(null),send: (access, note) => {const proc = server();diff --git a/electron/included-x.test.mjs b/electron/included-x.test.mjsindex 517305bdb8..da8cf1e544 100644--- a/electron/included-x.test.mjs+++ b/electron/included-x.test.mjs@@ -4,9 +4,17 @@ import { createDesktopIncludedX, createIncludedXSync } from "./included-x.mjs";const access = { url: "https://cloud.openmausbot.com/api/cloud/services/x", token: `omb_xd_${"a".repeat(43)}` };const paid = (deviceId = "device-1") => ({ status: "connected", deviceId, entitlement: { plan: "pro", status: "active", tier: "pro" } });+/** Over a fake clock: `pass(ms)` moves it on and runs the retry wait if it came due. */function sync(fetchAccess = vi.fn(async () => access)) {- const sent = [], notes = [];- return { sent, notes, fetchAccess, x: createIncludedXSync({ fetchAccess, send: (value, note) => { sent.push(value); notes.push(note ?? null); } }) };+ const sent = [], notes = [], waits = [];+ let clock = 1_800_000_000_000;+ const timers = { set: (work, ms) => { const timer = { work, at: clock + ms, ms }; waits.push(timer); return timer; }, clear: (timer) => { const at = waits.indexOf(timer); if (at >= 0) waits.splice(at, 1); } };+ const pass = async (ms) => {+ clock += ms;+ for (const timer of waits.filter((entry) => entry.at <= clock)) { waits.splice(waits.indexOf(timer), 1); timer.work(); }+ for (let i = 0; i < 10; i++) await Promise.resolve();+ };+ return { sent, notes, fetchAccess, waits, pass, x: createIncludedXSync({ fetchAccess, send: (value, note) => { sent.push(value); notes.push(note ?? null); }, now: () => clock, random: () => 0.5, timers }) };}describe("included X research access on the desktop", () => {@@ -46,12 +54,12 @@ describe("included X research access on the desktop", () => {it("a change of account with the Admin down: the account before's token doesn't stay with the server", async () => {const fetchAccess = vi.fn(async () => access);- const { x, sent } = sync(fetchAccess);+ const { x, sent, pass } = sync(fetchAccess);await x.onState(paid("device-a"));fetchAccess.mockRejectedValueOnce(new Error("offline"));await x.onState(paid("device-b"));expect(sent).toEqual([access, null]);- await x.onState(paid("device-b"));+ await pass(60_000);expect(sent).toEqual([access, null, access]);});@@ -66,13 +74,49 @@ describe("included X research access on the desktop", () => {expect(refused.notes).toEqual([{ offered: false }]);});- it("keeps trying on later state changes after a failed fetch, without sending anything for it", async () => {- const fetchAccess = vi.fn().mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce(access);- const { x, sent } = sync(fetchAccess);+ it("after a failed fetch, asks again by itself after a wait that grows (never on each state the sign-in publishes), sending nothing for it", async () => {+ const offline = Object.assign(new Error("offline"), { status: 503 });+ const fetchAccess = vi.fn().mockRejectedValueOnce(offline).mockRejectedValueOnce(offline).mockRejectedValueOnce(Object.assign(new Error("limited"), { status: 429, retryAfter: 900 }))+ .mockResolvedValueOnce(access);+ const { x, sent, waits, pass } = sync(fetchAccess);await x.onState(paid());expect(sent).toEqual([]);- await x.onState(paid());+ for (let i = 0; i < 5; i++) { await pass(10_000); await x.onState(paid()); }+ expect(fetchAccess, "each session refresh in the minute after asks nothing").toHaveBeenCalledTimes(1);+ expect(waits.map((timer) => timer.ms)).toEqual([60_000]);+ await pass(10_000);+ expect(fetchAccess, "the minute is over: asked again").toHaveBeenCalledTimes(2);+ 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(fetchAccess).toHaveBeenCalledTimes(3);+ await pass(1_000);+ expect(fetchAccess).toHaveBeenCalledTimes(4);expect(sent).toEqual([access]);+ expect(waits).toEqual([]);+ });++ 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());+ await x.onState({ status: "unavailable", message: "verification-expired", deviceId: "device-1" });+ expect(sent, "the server holds nothing meanwhile, as before").toEqual([access, null]);+ await x.onState({ status: "unavailable", message: "unreachable", deviceId: "device-1" });+ await x.onState(paid());+ expect(sent).toEqual([access, null, access]);+ expect(fetchAccess).toHaveBeenCalledTimes(1);+ // A sign-in that ended, another one, or a plan that stopped in between asks again (or not at all).+ for (const between of [{ status: "reauth-required", message: "access-ended", deviceId: "device-1" }, { status: "signed-out" }]) {+ await x.onState({ status: "unavailable", message: "unreachable", deviceId: "device-1" });+ await x.onState(between);+ await x.onState(paid());+ }+ expect(fetchAccess).toHaveBeenCalledTimes(3);+ await x.onState({ status: "unavailable", message: "unreachable", deviceId: "device-1" });+ await x.onState(paid("device-2"));+ expect(fetchAccess).toHaveBeenCalledTimes(4);});it("re-sends the token it holds when the server starts again, and nothing when it holds none", async () => {diff --git a/electron/main.mjs b/electron/main.mjsindex 598ed71d89..247e6a324c 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,+ openBrowser: url => shell.openExternal(url), awaitingWake: () => cloudPower.awaiting(), warn: slog, attended: () => { try { return BrowserWindow.getFocusedWindow() !== null || oneHome.holding() !== null; } catch { return true; } },onState: state => {cloudSync.accountChanged(state.account?.id ?? null); rememberCloudHome(state);rememberedHome = rememberedCloudHome(rememberedHome, state);@@ -1952,7 +1952,7 @@ function createWindow({ deferNavigation = false } = {}) {});mainWindow = win; hiddenStart = false; chromeRail.attach(win);win.on("show", () => desktopTray?.windowShown(win));- win.on("focus", () => { if (cloudAccount?.checkoutPending()) void cloudAccount.refresh().catch(() => {}); cloudFocusWake.focused({ shown: !desktopRemoteAccess && win.isVisible() && !win.isMinimized(), showingCloud: placeShown() === "cloud" }); }); win.on("blur", () => cloudFocusWake.blurred({ showingCloud: placeShown() === "cloud" }));+ 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("close", (event) => {if (process.platform === "win32" && !desktopShutdownStarted && desktopTray) {event.preventDefault();diff --git a/electron/move-status.d.mts b/electron/move-status.d.mtsindex e8813f45aa..e9c5823878 100644--- a/electron/move-status.d.mts+++ b/electron/move-status.d.mts@@ -45,6 +45,7 @@ export declare const MOVE_PHASES: readonly MovePhase[];export declare const MOVE_REASONS: readonly MoveReason[];export declare const MOVE_BUSY: readonly ("bot" | "room" | "sign-in" | "other")[];export declare const MOVE_STATUS_HEARTBEAT_MS: number;+export declare const MOVE_STATUS_IDLE_HEARTBEAT_MS: number;export declare const MOVE_STATUS_SETTLE_MS: number;export declare const MOVE_STATUS_GAP_MS: number;export declare const MOVE_STATUS_OFF_MS: number;@@ -66,5 +67,7 @@ export function createMoveStatusReport(deps: {signIn(): string | null;now?(): number;log?(line: string): void;+ /** Spreads each heartbeat and failure's wait by ±20% (Math.random). */+ random?(): number;timers?: { set(work: () => void, ms: number): unknown; clear(timer: unknown): void };}): { changed(): void; flush(): Promise<void>; close(): void };diff --git a/electron/move-status.mjs b/electron/move-status.mjsindex df86c068b6..423c15b752 100644--- a/electron/move-status.mjs+++ b/electron/move-status.mjs@@ -1,6 +1,8 @@// Where this computer's one-time move to My Cloud stands (one-home.mjs), as the Admin keeps it per sign-in: POST-// /api/cloud/desktop/move-status, sent when it changes and every 15 minutes otherwise, so an operator can see why a move-// hasn't finished, or never started. Ids and codes only: never a name, a path or anything the person wrote.+// /api/cloud/desktop/move-status, sent when it changes, and otherwise every 15 minutes while a move is under way and every+// 6 hours while none is, so an operator can see why a move hasn't finished, or never started. Ids and codes only: never a+// name, a path or anything the person wrote.+import { createBackoff, jittered } from "./cloud-cadence.mjs";import { teamPlan } from "./cloud-team-plan.mjs";import { FAILURE_CODES, FAILURE_PHASES, safeSentence } from "./move-failure.mjs";import { awayIn } from "./one-home.mjs";@@ -14,7 +16,10 @@ export const MOVE_REASONS = Object.freeze(["frozen_without_move", "local_unavailable", "already_moved", "cloud_outdated", "thaw_failed", "retry_wait", "waiting_quiet", "waiting_busy",]);export const MOVE_BUSY = Object.freeze(["bot", "room", "sign-in", "other"]);+/** While a move is under way, the same report goes again after this long (spread ±20%). */export const MOVE_STATUS_HEARTBEAT_MS = 15 * 60_000;+/** While none is (`none`, `done`, `back`: nothing changes by itself), only after this long (spread ±20%). */+export const MOVE_STATUS_IDLE_HEARTBEAT_MS = 6 * 3_600_000;/** A burst of changes (a pass's phases follow each other within seconds) goes as one report. */export const MOVE_STATUS_SETTLE_MS = 5_000;/** At most one report a minute, whatever changes. */@@ -25,6 +30,7 @@ export const MOVE_STATUS_OFF_MS = 6 * 3_600_000;const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);const moment = (value) => (Number.isSafeInteger(value) && value > 0 ? value : null);const STARTS = new Set(["none", "back"]);+const SETTLED = new Set(["none", "done", "back"]);const WAITS = new Set(["wait", "freeze"]);/** Why no move starts on this computer, in the order one-home.mjs's run asks; null once one would start. */@@ -115,12 +121,15 @@ export function moveStatus({ journal, state, kept, facts = { noted: null, waitin/*** Sends `status()` to the Admin with `send` (true once recorded, false when the Admin doesn't take reports yet) for the- * sign-in `signIn()` names: a moment after it changes, at most once a minute, and every 15 minutes while it doesn't.- * Fire and forget: a report that fails is only logged, and nothing about the move waits for it or changes with it.+ * sign-in `signIn()` names: a moment after it changes, at most once a minute, and while it doesn't, every 15 minutes+ * during a move and every 6 hours otherwise. A send that fails waits longer each time (1, 2, 5, 10, then 30 minutes,+ * never before the Admin's Retry-After), whatever changes meanwhile. Fire and forget: a report that fails is only+ * logged, and nothing about the move waits for it or changes with it.*/-export function createMoveStatusReport({ status, send, signIn, now = Date.now, log = () => {},+export function createMoveStatusReport({ status, send, signIn, now = Date.now, log = () => {}, random = Math.random,timers = { set: (work, ms) => { const timer = setTimeout(work, ms); timer.unref?.(); return timer; }, clear: (timer) => clearTimeout(timer) } }) {let timer = null, dueAt = Infinity, sent = null, triedAt = -Infinity, offUntil = -Infinity, busy = false, again = false, closed = false;+ const failing = createBackoff({ now, random });const plan = (ms) => {if (closed) return;if (timer) timers.clear(timer);@@ -137,14 +146,20 @@ export function createMoveStatusReport({ status, send, signIn, now = Date.now, ltry { who = signIn(); body = who ? status() : null; } catch (error) { log(`one home: the move's status could not be read (${error?.message ?? error})`); }if (!body) return plan(MOVE_STATUS_HEARTBEAT_MS);const at = now(), key = JSON.stringify(body), same = sent?.key === key && sent.who === who;- const wait = Math.max(same ? sent.at + MOVE_STATUS_HEARTBEAT_MS - at : 0, triedAt + MOVE_STATUS_GAP_MS - at, offUntil - at);+ const wait = Math.max(same ? sent.at + sent.every - at : 0, triedAt + MOVE_STATUS_GAP_MS - at, offUntil - at, failing.until() - at);if (wait > 0) return plan(wait);triedAt = at;+ const every = jittered(SETTLED.has(body.phase) ? MOVE_STATUS_IDLE_HEARTBEAT_MS : MOVE_STATUS_HEARTBEAT_MS, random);+ let next = every;try {- if (await send(body)) sent = { key, who, at };- else offUntil = at + MOVE_STATUS_OFF_MS;- } catch (error) { log(`one home: the Admin hears where the move stands later (${error?.message ?? error})`); }- plan(MOVE_STATUS_HEARTBEAT_MS);+ if (await send(body)) sent = { key, who, at, every };+ else { offUntil = at + MOVE_STATUS_OFF_MS; next = MOVE_STATUS_OFF_MS; }+ failing.ok();+ } catch (error) {+ next = failing.failed(error) - now();+ log(`one home: the Admin hears where the move stands later (${error?.message ?? error})`);+ }+ plan(next);} finally {busy = false;if (again) { again = false; changed(); }diff --git a/electron/move-status.node-test.mjs b/electron/move-status.node-test.mjsindex 349cf13f24..9c06bc7c34 100644--- a/electron/move-status.node-test.mjs+++ b/electron/move-status.node-test.mjs@@ -3,7 +3,7 @@ import test from "node:test";import { CloudSendError } from "./cloud-send.mjs";import { failureCode, safeSentence, SENTENCE_MAX } from "./move-failure.mjs";-import { createMoveStatusReport, MOVE_STATUS_GAP_MS, MOVE_STATUS_HEARTBEAT_MS, MOVE_STATUS_OFF_MS, MOVE_STATUS_SETTLE_MS, moveStatus } from "./move-status.mjs";+import { createMoveStatusReport, MOVE_STATUS_GAP_MS, MOVE_STATUS_HEARTBEAT_MS, MOVE_STATUS_IDLE_HEARTBEAT_MS, MOVE_STATUS_OFF_MS, MOVE_STATUS_SETTLE_MS, moveStatus } from "./move-status.mjs";import { CHECK_PASSES, createOneHome, INCOMPLETE, parseJournal, QUIET_MS } from "./one-home.mjs";import { installOneHome, oneHomeCloud } from "./one-home-main.mjs";@@ -282,11 +282,31 @@ test("what leaves this computer is ids and fixed words: quotes, what My Cloud saassert.equal(failureCode(new CloudSendError("no_cloud", "This computer has no My Cloud yet."), "copy"), "no_cloud");});-test("a report goes a moment after it changes, at most once a minute, and every 15 minutes while it doesn't", async () => {+/** createMoveStatusReport over a fake clock; `pass(ms)` moves it on, running each timer due on the way. */+function reporter(initial, { random = () => 0.5 } = {}) {+ const h = { clock: 1_800_000_000_000, body: initial, who: "device-1", sent: [], answer: async () => true };+ const timers = [];+ h.timers = timers;+ h.r = createMoveStatusReport({ status: () => h.body, signIn: () => h.who, send: async (report) => { h.sent.push(structuredClone(report)); return h.answer(); }, now: () => h.clock, random,+ timers: { set: (work, ms) => { const timer = { work, at: h.clock + ms }; timers.push(timer); return timer; }, clear: (timer) => { const at = timers.indexOf(timer); if (at >= 0) timers.splice(at, 1); } } });+ h.pass = async (ms) => {+ const until = h.clock + ms;+ for (let next = timers.sort((a, b) => a.at - b.at)[0]; next && next.at <= until; next = timers.sort((a, b) => a.at - b.at)[0]) {+ timers.splice(timers.indexOf(next), 1);+ h.clock = next.at;+ next.work();+ await new Promise((resolve) => setImmediate(resolve));+ }+ h.clock = until;+ };+ return h;+}++test("a report goes a moment after it changes, at most once a minute, and every 15 minutes during a move while it doesn't", async () => {let clock = 1_800_000_000_000, body = { v: 1, phase: "copy", reason: null }, who = "device-1";const timers = [], sent = [];let answer = async () => true;- const r = createMoveStatusReport({ status: () => body, signIn: () => who, send: async (report) => { sent.push(structuredClone(report)); return answer(); }, now: () => clock,+ const r = createMoveStatusReport({ status: () => body, signIn: () => who, send: async (report) => { sent.push(structuredClone(report)); return answer(); }, now: () => clock, random: () => 0.5,timers: { set: (work, ms) => { const timer = { work, at: clock + ms }; timers.push(timer); return timer; }, clear: (timer) => { const at = timers.indexOf(timer); if (at >= 0) timers.splice(at, 1); } } });/** Moves the clock on, running each timer due on the way. */const pass = async (ms) => {@@ -328,7 +348,7 @@ test("a report goes a moment after it changes, at most once a minute, and everybody = { ...body, phase: "check" };r.changed();await pass(MOVE_STATUS_GAP_MS);- assert.equal(sent.length, 6, "a failed send goes again at the next change");+ assert.equal(sent.length, 6, "a failed send goes again once its wait (a minute after the first failure) is over");body = { ...body, phase: "switch" };r.changed();await pass(MOVE_STATUS_OFF_MS - 60_000);@@ -341,6 +361,68 @@ test("a report goes a moment after it changes, at most once a minute, and everyassert.equal(timers.length, 0);});+test("a send that fails waits longer each time, whatever changes meanwhile, and never before the Admin's Retry-After", async () => {+ const h = reporter({ v: 1, phase: "copy", reason: null });+ h.answer = async () => { throw Object.assign(new Error("Cloud request failed."), { status: 503 }); };+ h.r.changed();+ await h.pass(MOVE_STATUS_SETTLE_MS);+ assert.equal(h.sent.length, 1);+ // The app's session is read each minute, and each read says "changed": none of them sends until the wait is over.+ const tries = [];+ for (let minute = 0; minute < 60; minute++) {+ h.body = { ...h.body, passes: minute % 2 };+ h.r.changed();+ await h.pass(60_000);+ tries.push(h.sent.length);+ }+ const at = [...new Set(tries)].map((count) => tries.indexOf(count));+ assert.deepEqual(at, [0, 2, 7, 17, 47], "tried again after 1, 2, 5 and 10 minutes, then every 30, instead of each minute");+ assert.equal(h.sent.length, 6, "6 sends in the hour where each minute's change sent one before");+ h.answer = async () => { throw Object.assign(new Error("Too many."), { status: 429, retryAfter: 3600 }); };+ 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");+ h.answer = async () => true;+ await h.pass(4 * 60_000);+ assert.equal(h.sent.length, 8);+ h.body = { ...h.body, passes: 3 };+ h.r.changed();+ await h.pass(MOVE_STATUS_GAP_MS);+ assert.equal(h.sent.length, 9, "an answer starts the count again: the next change goes within the minute");+ h.r.close();+});++test("with no move under way, the same report goes again only after 6 hours; once one starts, every 15 minutes", async () => {+ for (const phase of ["none", "done", "back"]) {+ const h = reporter({ v: 1, phase, reason: phase === "none" ? "no_cloud" : null });+ h.r.changed();+ for (let minute = 0; minute < 6 * 60 - 1; minute++) { h.r.changed(); await h.pass(60_000); }+ assert.equal(h.sent.length, 1, `${phase}: once, though the session is read each minute`);+ await h.pass(2 * 60_000);+ assert.equal(h.sent.length, 2, `${phase}: and again 6 hours later`);+ h.body = { ...h.body, phase: "copy", reason: null };+ h.r.changed();+ await h.pass(MOVE_STATUS_SETTLE_MS);+ assert.equal(h.sent.length, 3, "a move starting goes at once");+ await h.pass(MOVE_STATUS_HEARTBEAT_MS);+ assert.equal(h.sent.length, 4);+ h.r.close();+ }+ // Spread by up to a fifth either way, so apps started together never report together.+ for (const [drawn, hours] of [[0, 4.8], [1, 7.2]]) {+ const h = reporter({ v: 1, phase: "none", reason: "no_cloud" }, { random: () => drawn });+ h.r.changed();+ await h.pass(MOVE_STATUS_SETTLE_MS);+ await h.pass(hours * 3_600_000 - 1_000);+ assert.equal(h.sent.length, 1);+ await h.pass(2_000);+ assert.equal(h.sent.length, 2);+ h.r.close();+ }+ assert.equal(MOVE_STATUS_IDLE_HEARTBEAT_MS, 6 * 3_600_000);+});+test("the move's own changes send the report by themselves, a moment later", async () => {const timers = [];const f = installed({ state: signedIn({ machine: { status: "ready", origin: CLOUD } }),@@ -351,7 +433,8 @@ test("the move's own changes send the report by themselves, a moment later", asytimers.shift().work();await new Promise((resolve) => setImmediate(resolve));assert.deepEqual(f.sent.map((report) => report.reason), ["moves_off"]);- assert.equal(timers.at(-1)?.ms, MOVE_STATUS_HEARTBEAT_MS, "and again in 15 minutes");+ const next = timers.at(-1)?.ms;+ assert.ok(next >= 0.8 * MOVE_STATUS_IDLE_HEARTBEAT_MS && next <= 1.2 * MOVE_STATUS_IDLE_HEARTBEAT_MS, "and, with no move under way, again in about 6 hours");} finally { f.main.close(); }});diff --git a/electron/updates-consent.d.mts b/electron/updates-consent.d.mtsindex 2a54e4d208..bfa1df1d31 100644--- a/electron/updates-consent.d.mts+++ b/electron/updates-consent.d.mts@@ -40,6 +40,8 @@ export declare function createUpdatesConsent(options: {available(): boolean | Promise<boolean>;now?: () => number;onChange?: () => void;+ /** Spreads the wait after a failed read (Math.random). */+ random?: () => number;}): UpdatesConsent;export declare function registerUpdatesConsent(options: {ipcMain: { handle(channel: string, handler: (event: unknown, ...args: unknown[]) => unknown): void };diff --git a/electron/updates-consent.mjs b/electron/updates-consent.mjsindex 6b9a5fe2b3..fa75868df5 100644--- a/electron/updates-consent.mjs+++ b/electron/updates-consent.mjs@@ -1,5 +1,6 @@// The one-time "Get MausBot updates?" question: this computer's answer, kept in desktop-prefs.json before anything is// sent, and the MausBot Cloud Admin's consent record (account or email-only), kept in step with it.+import { createBackoff } from "./cloud-cadence.mjs";import { cleanEmail } from "./cloud-signin.mjs";/** The consent wording shown, by version: the Admin keeps the version with each answer as proof of what was asked. */@@ -60,10 +61,16 @@ 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.+ * `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.*/-export function createUpdatesConsent({ prefs, account, available, now = Date.now, onChange = () => {} }) {+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;+ /** Failures in a row for the account `failedFor`: another account signing in asks at once. */+ const failing = createBackoff({ now, random });const client = () => account();const signedIn = () => {const current = client()?.state();@@ -162,12 +169,19 @@ export function createUpdatesConsent({ prefs, account, available, now = Date.nowconst answer = choices, who = signedIn()?.id ?? null;const sameAnswer = () => choices === answer;const fresh = () => sameAnswer() && (signedIn()?.id ?? null) === who;- try { await reconcile(sameAnswer, fresh); } catch (error) { if (fresh()) throw error; }- if (fresh()) return;+ 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; }}}const sync = () => running ??= settle().finally(() => { running = null; });+ /** Whether the Admin needs asking: an answer waits to be sent, or the account signed in isn't in step yet; never inside a failure's wait. */+ const due = () => {+ 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());+ };const snapshot = () => {const saved = prefs.updatesConsent(), who = signedIn();@@ -178,7 +192,7 @@ export function createUpdatesConsent({ prefs, account, available, now = Date.nowasync function state() {if (!client() || !await available()) return { available: false, due: false, status: null, signedIn: false, email: null, version: UPDATES_CONSENT_VERSION };- await Promise.race([sync().catch(() => {}), new Promise(resolve => setTimeout(resolve, STATE_WAIT_MS).unref?.())]);+ if (running || due()) await Promise.race([sync().catch(() => {}), new Promise(resolve => setTimeout(resolve, STATE_WAIT_MS).unref?.())]);return snapshot();}@@ -210,7 +224,7 @@ export function createUpdatesConsent({ prefs, account, available, now = Date.nowconst id = current?.status === "connected" ? current.account?.id ?? null : null;if (id === lastAccount) return;lastAccount = id;- if (id) void sync().catch(() => {});+ if (id && due()) void sync().catch(() => {});}return { state, choose, sync, accountChanged };diff --git a/electron/updates-consent.node-test.mjs b/electron/updates-consent.node-test.mjsindex c4102006ce..af4c39f98e 100644--- a/electron/updates-consent.node-test.mjs+++ b/electron/updates-consent.node-test.mjs@@ -133,6 +133,32 @@ test("signed in: one tap is recorded on the account, and the account's own answeassert.deepEqual(await f.consent.state(), { available: true, due: false, status: "withdrawn", signedIn: true, email: "[email protected]", version: UPDATES_CONSENT_VERSION });});+test("the account's answer is read once per sign-in: later looks are answered here, a failed read waits before the next, another account reads at once", 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 };+ for (let look = 0; look < 3; look++) assert.equal((await f.consent.state()).status, "opted_in");+ f.consent.accountChanged(f.client.state());+ assert.deepEqual(f.requests.map(({ method }) => method), ["GET"], "one read for this sign-in, however many pages ask");+ // A new launch reads it again; with the Admin down, each look within the next minute asks nothing more.+ f.launch(); f.down = true;+ await f.consent.state(); await f.consent.state();+ assert.equal(f.requests.length, 2);+ f.now += 75_000; f.down = false; // a minute, spread by up to a fifth+ assert.equal((await f.consent.state()).status, "opted_in");+ assert.equal(f.requests.length, 3, "asked again once the wait is over");+ await f.consent.state();+ assert.equal(f.requests.length, 3);+ // Another account signs in: its own answer is read at once.+ await f.client.signOut();+ f.accountId = "account-2"; f.accessToken = `omc_${"B".repeat(43)}`; f.account = null;+ await f.signInNow();+ f.consent.accountChanged(f.client.state());+ await until(() => f.requests.length === 4);+ assert.equal((await f.consent.state()).due, true);+ assert.equal(f.requests.length, 4);+});+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" });@@ -530,7 +556,8 @@ test("an unanswered account withdraws another account's retained email receipt wassert.equal(state.due, true);assert.equal(state.status, null);assert.equal(f.account, null);- assert.deepEqual(f.requests.filter(request => request.path === "/api/cloud/desktop/updates-consent").map(request => request.method), ["GET", "GET", "GET"]);+ // The state is answered from what this run already has in step with the Admin: no third read.+ assert.deepEqual(f.requests.filter(request => request.path === "/api/cloud/desktop/updates-consent").map(request => request.method), ["GET", "GET"]);assert.deepEqual(f.requests.filter(request => request.method === "POST").map(request => request.body), [{ status: "opted_in", email: "[email protected]", installId: f.saved.installId, textVersion: UPDATES_CONSENT_VERSION },{ status: "withdrawn", receipt: receiptOf("[email protected]") },