Skip to content

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

Fewer Cloud wakes, stage 1: apps stop reaching a sleeping home, and the home says what woke it (#3872)

Milind Sonidd7045000c0f
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.md
index 8e50a33821..d329708e7f 100644
--- a/docs/cloud-pro.md
+++ b/docs/cloud-pro.md
@@ -1563,15 +1563,22 @@ its own nonces. `200`:
```json
{ "v": 1, "at": 1792355000000, "bootedAt": 1792350000000, "wokeAt": 1792354000000,
"idle": false, "busy": ["recent-activity"], "lastActivityAt": 1792354900000, "lastWorkAt": null,
- "nextDueAt": 1792358600000, "sleeping": false }
+ "nextDueAt": 1792358600000, "sleeping": false, "wokeBy": { "by": "events", "background": true } }
```
`busy` holds fixed codes only: `turn`, `run`, `live-call`, `computer`,
`maintenance`, `recent-activity`, `recent-work`, `just-woke`, `due-soon`.
`nextDueAt` is the earliest enabled routine's next run or queued run's retry,
or, while a bot waits for something (`wait_until`), 30 minutes on, so its
-checks go on that often: the Admin starts a sleeping home a minute before it.
-`wokeAt` is the boot, or the last resume (noticed as a jump of the clock).
+checks go on that often: the Admin starts a sleeping home a minute before it
+(3 minutes for one stopped to sleep, which boots). `wokeAt` is the boot, or
+the last resume (noticed as a jump of the clock, by the tick or by a request).
+`wokeBy` (additive) is the first request after that, if one came within 30 s:
+its kind as a fixed code by path alone (`events` the page's stream, `version`
+the desktop's version check, `sync`, `lending`, `phone`, `presence`, `session`,
+`pair`, `admin`, `health`, `webhook`, `sign-in`, `api`, `page`) and whether it
+was a background one; `null` otherwise. The Admin counts it for a wake by
+Fly's proxy, to tell which app reaches a sleeping home.
**`POST /api/cloud/power/sleep`**, signed over its JSON body
`{"v":1,"idleMinutes":10}`. `409 {"ok":false,"busy":[…]}` while not idle;
@@ -1585,7 +1592,11 @@ resume, someone's use, or 120 s (a sleep the Admin never carried out):
so a page that kept polling would keep it awake. The frame is live only: a
stream that resumes from before it never gets it again. The wake is one
ordinary request (`GET /api/auth/session`), so it also ends a sleep the
- Admin has not carried out yet;
+ Admin has not carried out yet. A page that is hidden (a background tab, a
+ minimized window) sends no background request at all, frame or not: each
+ waits until the page shows again, one per path (`src/state/api.ts`), so a
+ hidden tab whose stream dropped (the laptop slept) can't wake a sleeping home
+ every minute;
- held `GET /api/sync/changes` and `POST /api/shared-computers/<id>/poll`
answer `503 {"error":"asleep"}` with `x-omb-cloud-power: asleep`, and new
ones get the same, so the desktop's Files sync and lending pause instead of
@@ -1664,13 +1675,18 @@ without them works as before; a malformed one is dropped, never the machine):
entitlement still decides everything.
- `cloud.credit: {grantedUsd, remainingUsd, state}`: the trial's Claude
credit (`active` or `used_up`), shown in Settings here and on the Cloud.
-- `clouds[]` (top level): every Cloud the person can open. The app reads one
- thing from it, the plan's renewal (`electron/cloud-home.mjs`
+- `clouds[]` (top level): every Cloud the person can open. The app reads the
+ plan's renewal from it (`electron/cloud-home.mjs`
`parseCloudRenewal`): the account's own primary Cloud's `renewal: {trial,
endsAt, keptDays}`, which the Admin sends only to the account that pays for
it while its plan runs. The state carries `renewal: {trial, cancelled,
renewsAt, endsAt, keptDays, team?}` without the Cloud's id, which stays in
- main. See [Cancel trial / Cancel plan](#cancel-trial--cancel-plan).
+ main. See [Cancel trial / Cancel plan](#cancel-trial--cancel-plan). And each
+ Ready Cloud's `power` (additive, as `cloud.power`, for a plan that sleeps):
+ lending to another Cloud of the person's own, the window's version check
+ and the quiet updater never reach a Cloud the Admin says is asleep, and go on
+ at the next session read that says it is awake (`electron/cloud-account.mjs`
+ `powerOf`).
- `offer` (top level, beside `cloud`): what this account may buy now, only
while it can (no plan, no Cloud, no payment being linked). See
[Add a Cloud](#add-a-cloud) for its fields.
diff --git a/electron/cloud-account-clouds.node-test.mjs b/electron/cloud-account-clouds.node-test.mjs
index 6562739567..c399b0105e 100644
--- a/electron/cloud-account-clouds.node-test.mjs
+++ b/electron/cloud-account-clouds.node-test.mjs
@@ -88,6 +88,18 @@ test("the session's Clouds: each other own Cloud pairs with its id, and only a g
assert.equal(f.delay, 15_000, "a Cloud of theirs being set up is checked every 15 s");
});
+test("the Admin's word on each of the person's Clouds by its address: My Cloud's `cloud.power`, another's from the Clouds list", async t => {
+ const f = await admin(t);
+ f.session = { cloud: { state: "ready", origin: HOME, pairingAvailable: true, power: { state: "awake", since: 5, sleeps: true } },
+ clouds: [PRIMARY, entry({ power: { state: "asleep", since: 7, sleeps: true } }), entry({ id: "c-b", name: "Client B", origin: "https://omb-c-b.fly.dev" })] };
+ await f.client.start();
+ assert.deepEqual(f.client.powerOf(HOME), { state: "awake", since: 5, sleeps: true });
+ assert.deepEqual(f.client.powerOf(CLIENT_A), { state: "asleep", since: 7, sleeps: true });
+ assert.equal(f.client.powerOf("https://omb-c-b.fly.dev"), null, "a Cloud whose plan never sleeps");
+ assert.equal(f.client.powerOf(TEAM), null, "nothing the session lists");
+ assert.equal(f.client.powerOf(""), null);
+});
+
test("buying another Cloud: the plan, the name and the swatch go to the Admin, its own checkout opens, and the session is followed every 3 s", async t => {
const f = await admin(t);
f.session = { ...f.session, clouds: [PRIMARY] };
diff --git a/electron/cloud-account.mjs b/electron/cloud-account.mjs
index 3185e8a198..042af41a67 100644
--- a/electron/cloud-account.mjs
+++ b/electron/cloud-account.mjs
@@ -585,6 +585,12 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceN
homeTarget,
/** The Admin's last verified word on a Cloud whose plan sleeps, kept while a re-check fails; null for any other. */
power: () => (value.status === "connected" ? value.machine?.power ?? null : null),
+ /** The same for the Cloud at `origin`: My Cloud's `cloud.power`, or another's from the Clouds list (contract v1, Oct 30). */
+ powerOf: origin => {
+ if (value.status !== "connected" || typeof origin !== "string" || !origin) return null;
+ if (value.machine?.origin === origin) return value.machine.power ?? null;
+ return (value.clouds ?? []).find(cloud => cloud.origin === origin)?.power ?? null;
+ },
/** Starts a sleeping Cloud through the Admin (`awake` once started, `waking` if it is still starting), then reads the
* session again so Files and lending resume. Null when there is nothing to wake or the Admin can't say. */
async wakeHome() {
diff --git a/electron/cloud-list.mjs b/electron/cloud-list.mjs
index 399153b969..440fc348eb 100644
--- a/electron/cloud-list.mjs
+++ b/electron/cloud-list.mjs
@@ -1,6 +1,6 @@
// The verified session's `clouds` (contract v1, additive): every Cloud this person owns and every team's Cloud they are
// in, the account's primary Cloud first. Only the Admin lists a Cloud; a page never names one.
-import { CLOUD_SETUP_STEPS, homeOrigin } from "./cloud-home.mjs";
+import { CLOUD_SETUP_STEPS, homeOrigin, parseCloudPower } from "./cloud-home.mjs";
import environments from "./environments.cjs";
export const MAX_CLOUDS = 20;
@@ -55,9 +55,11 @@ function parseCloudEntry(input) {
const setup = input.status === "setting_up" ? setupOf(input.setup) : null;
const lastSeenAt = typeof input.lastSeenAt === "number" && Number.isSafeInteger(input.lastSeenAt) && input.lastSeenAt > 0 ? input.lastSeenAt : null;
const version = typeof input.version === "string" && VERSION.test(input.version) ? input.version : null;
+ // Additive (Oct 30): as `cloud.power`, for a Ready Cloud whose plan sleeps; this app never reaches one the Admin says is asleep.
+ const power = input.status === "ready" ? parseCloudPower(input.power) : null;
return { id: input.id, name, color: Object.hasOwn(CLOUD_SWATCH_COLORS, input.color) ? input.color : null, role: input.role,
tier: typeof input.tier === "string" && TIER.test(input.tier) ? input.tier : null, runsOn: input.runsOn, status: input.status, origin, teamId,
- primary: input.primary, managed, ...(setup ? { setup } : {}), ...(lastSeenAt ? { lastSeenAt } : {}), ...(version ? { version } : {}) };
+ primary: input.primary, managed, ...(setup ? { setup } : {}), ...(lastSeenAt ? { lastSeenAt } : {}), ...(version ? { version } : {}), ...(power ? { power } : {}) };
}
/** An OpenMausBot release as the Admin names it ("0.1.130"), or null: anything else is no version at all. */
diff --git a/electron/cloud-list.node-test.mjs b/electron/cloud-list.node-test.mjs
index 7531458bfa..3a0dc937e9 100644
--- a/electron/cloud-list.node-test.mjs
+++ b/electron/cloud-list.node-test.mjs
@@ -30,6 +30,16 @@ test("the session's Clouds are read strictly: a malformed one is left out whole,
assert.equal(parseCloudList([cloud({ status: "ready", setup: { step: "storage" } })])[0].setup, undefined, "only while it is set up");
});
+test("each Cloud's `power` as the Admin says it of a Ready Cloud whose plan sleeps; anything malformed, or on a Cloud not Ready, is none", () => {
+ const power = { state: "asleep", since: 1_761_000_000_000, sleeps: true };
+ assert.deepEqual(parseCloudList([cloud({ power })])[0].power, power);
+ assert.deepEqual(parseCloudList([cloud({ power: { ...power, state: "waking", extra: 1 } })])[0].power, { ...power, state: "waking" });
+ for (const bad of [{ ...power, state: "dozing" }, { ...power, sleeps: false }, { ...power, since: -1 }, "asleep", null]) {
+ assert.equal(parseCloudList([cloud({ power: bad })])[0].power, undefined, JSON.stringify(bad));
+ }
+ assert.equal(parseCloudList([cloud({ status: "stopped", power })])[0].power, undefined, "only a Ready Cloud sleeps or wakes");
+});
+
test("a server or computer of the person's own that signed in with their account: read with or without an address, and never a Cloud of theirs", () => {
const mini = cloud({ id: "s-mini", name: "Mac mini", color: null, tier: null, runsOn: "server", managed: false, status: "offline", origin: null,
lastSeenAt: 1_761_000_000_000, version: "0.1.118", kind: "desktop", reachable: { via: "tailscale" } });
diff --git a/electron/computer-sharing.mjs b/electron/computer-sharing.mjs
index a4ab18e26b..768d04d6aa 100644
--- a/electron/computer-sharing.mjs
+++ b/electron/computer-sharing.mjs
@@ -185,9 +185,10 @@ const BROWSE_NOTE_MS = 10 * 60_000;
* project folders are lent to. `ownClouds()`: the saved servers that are the verified session's own Clouds, never a
* Team Cloud: each is lent this computer by itself (automaticGrant) unless lending is paused. `screen()`: whether apps
* and screen can be lent here: computer control works, or only macOS's permissions are missing, which
- * `askForScreen(connection)` asks macOS for when a Cloud's bot first needs them. */
+ * `askForScreen(connection)` asks macOS for when a Cloud's bot first needs them. `cloudPower(origin)`: the Admin's word on
+ * another Cloud of the person's own (the Clouds list's `power`), so a sleeping one is never dialled. */
export function createComputerSharing({ file, fetch: fetchImpl, environments, cuaConnection, hostControl, screenLocked = () => false, idleSeconds = () => null, protectedPaths = [], enabled = async () => false, home = os.homedir(), activityFile, cloud = () => null, onChange = () => {}, reconnect = null, now = Date.now, power = createCloudPowerGate(),
- linkHeaders = () => ({}), WebSocket: linkSocket = globalThis.WebSocket, egress = {}, chrome = {}, myCloud = () => null, ownClouds = () => [], screen = () => false, askForScreen = () => {} }) {
+ linkHeaders = () => ({}), WebSocket: linkSocket = globalThis.WebSocket, egress = {}, chrome = {}, myCloud = () => null, ownClouds = () => [], screen = () => false, askForScreen = () => {}, cloudPower = () => null }) {
const protectedRoots = [path.dirname(file), ...protectedPaths.filter(entry => typeof entry === "string" && entry), ...personalSecretPaths(home)];
const activity = createLendingActivity(activityFile ?? path.join(path.dirname(file), "lending-activity.jsonl"));
const presence = createLentScreenPresence({ idleSeconds, now });
@@ -276,12 +277,13 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
};
const sleepsHere = env => Boolean(records[env.id]?.cloud) || cloud()?.origin === env.origin;
/** My Cloud sleeps by the Admin's word and its own, on the gate this app shares with Files (`power`); another Cloud of
- * the person's own by its own "going to sleep" answer alone, on a gate of its own, so one Cloud asleep never holds
- * another's lending, and a sleeping one is not dialled again before its hold ends. */
+ * the person's own by the same two (the Clouds list's `power`, `cloudPower`, and its own "going to sleep" answer) on a
+ * gate of its own, so one Cloud asleep never holds another's lending, and a sleeping one is not dialled until the Admin
+ * says it is awake (any request reaching it would wake it). */
const ownGates = new Map();
const sleepGate = env => {
if (env.id === myCloud()?.id || cloud()?.origin === env.origin) return power;
- if (!ownGates.has(env.id)) ownGates.set(env.id, createCloudPowerGate());
+ if (!ownGates.has(env.id)) ownGates.set(env.id, createCloudPowerGate({ power: () => cloudPower(env.origin) }));
return ownGates.get(env.id);
};
const request = async (env, route, body, signal, secret) => {
@@ -696,6 +698,8 @@ export function createComputerSharing({ file, fetch: fetchImpl, environments, cu
},
cloudChanged() {
if (closed) return;
+ // The Admin's word on each other Cloud may have changed: a lending loop waiting for one to wake goes on.
+ for (const gate of ownGates.values()) gate.changed();
const automatic = lentAutomatically();
for (const env of environments()) {
const grant = records[env.id];
diff --git a/electron/home-window.mjs b/electron/home-window.mjs
index dc74482532..9581692530 100644
--- a/electron/home-window.mjs
+++ b/electron/home-window.mjs
@@ -200,6 +200,9 @@ export function createHomeWindow(deps) {
const state = () => account()?.state() ?? null;
const wanted = (token) => token === opens;
const cloudOrigin = () => (home.kind === "cloud" ? home.origin : null);
+ /** The Cloud at `origin` sleeps now: My Cloud by its gate (the Admin's word and its own answer), any other of the
+ * person's Clouds by the Admin's word in the Clouds list. A request to a sleeping one would wake it. */
+ const asleepAt = (origin) => (origin && origin === cloudOrigin() ? power.asleep() : account()?.powerOf?.(origin)?.state === "asleep");
/** The origin of the place on screen, or on its way: a team's Cloud while one is shown, else My Cloud. */
const placeOrigin = () => (otherPlace(shown) ? (signedOut() ? null : shown.origin) : cloudOrigin());
const teamName = () => (otherPlace(opening) ? opening.name : null);
@@ -500,10 +503,10 @@ export function createHomeWindow(deps) {
return typeof body?.version === "string" ? body.version : null;
} catch { return null; }
}
- /** A newer page reloads at a quiet moment; an asleep My Cloud is never asked (that would start it). */
+ /** A newer page reloads at a quiet moment; a Cloud asleep is never asked (that would start it). */
async function watchVersion() {
const origin = placeOrigin();
- if (!origin || !shows(origin) || (!otherPlace(shown) && power.asleep())) return;
+ if (!origin || !shows(origin) || asleepAt(origin)) return;
const current = await version(origin);
if (!current) return;
if (!loaded) { loaded = current; return; }
@@ -535,6 +538,8 @@ export function createHomeWindow(deps) {
view,
/** My Cloud's origin while it is home, else null. */
cloudOrigin,
+ /** Whether the Cloud at `origin` sleeps now (see `asleepAt`): nothing in the background asks it then. */
+ asleepAt,
/** The origin of the place the window shows (a team's Cloud, or My Cloud), else null. */
placeOrigin,
/** Home as last worked out. */
diff --git a/electron/home-window.node-test.mjs b/electron/home-window.node-test.mjs
index d57023d341..d32035ae34 100644
--- a/electron/home-window.node-test.mjs
+++ b/electron/home-window.node-test.mjs
@@ -83,6 +83,7 @@ function world({ journal = done(), marker = null, state = connected(), power = n
const account = {
state: () => w.state,
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"; },
setWaking: (on) => w.waking.push(on),
async pairHome(cloudId = null) {
@@ -874,6 +875,27 @@ test("choosing another Cloud of the person's own opens it through the Admin's pa
assert.deepEqual(w.home.view(), { screen: "opening", name: "Client A" });
});
+test("another Cloud of the person's own that the Admin says is asleep is never asked for its version; once the Admin says it is awake, it is", async () => {
+ const w = world({ state: { ...connected(), clouds: [CLIENT_A] } });
+ await w.home.show({ place: { cloud: "c-a" } });
+ w.url = `${CLIENT}/`;
+ w.home.navigated(w.url);
+ await w.tick();
+ const versions = () => w.fetched.filter(([route]) => route === "client:/.well-known/openmausbot/environment");
+ const read = versions().length;
+ assert.ok(read > 0, "the shown Cloud's version is read while it is awake");
+ // The Clouds list says it sleeps (`power`, contract v1): any request reaching it would wake it.
+ w.state = { ...w.state, clouds: [{ ...CLIENT_A, power: { state: "asleep", since: 5, sleeps: true } }] };
+ await w.tick();
+ await w.tick();
+ assert.equal(versions().length, read, "a Cloud the Admin says is asleep is never asked");
+ assert.deepEqual([w.home.asleepAt(CLIENT), w.home.asleepAt(CLOUD)], [true, false], "and the quiet updater asks the same: only that Cloud sleeps");
+ w.state = { ...w.state, clouds: [{ ...CLIENT_A, power: { state: "awake", since: 6, sleeps: true } }] };
+ await w.tick();
+ assert.equal(versions().length, read + 1, "awake again, it is asked");
+ assert.deepEqual(versions().at(-1), ["client:/.well-known/openmausbot/environment", "1"], "as a background read");
+});
+
test("another Cloud the Admin says is no longer theirs is dropped at once and My Cloud opens, with no line; one being set up shows its setup with its name", async () => {
const w = world({ state: { ...connected(), clouds: [CLIENT_A] }, client: { signedIn: false, gone: true } });
await w.home.show({ place: { cloud: "c-a" } });
diff --git a/electron/main.mjs b/electron/main.mjs
index 5d1a9cca39..9db015b029 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -1459,7 +1459,7 @@ function sharingController() {
fetch: (...args) => session.defaultSession.fetch(...args),
environments: () => environmentsState.environments,
enabled: refreshSharedComputersAllowed,
- cloud: lendingTarget.cloud, myCloud: lendingTarget.environment, ownClouds: lendingTarget.places, screen: lendsScreen, askForScreen, power: cloudPower, reconnect: reconnectCloud,
+ cloud: lendingTarget.cloud, myCloud: lendingTarget.environment, ownClouds: lendingTarget.places, screen: lendsScreen, askForScreen, power: cloudPower, cloudPower: origin => cloudAccount?.powerOf?.(origin) ?? null, reconnect: reconnectCloud,
linkHeaders: async env => ({ cookie: (await session.defaultSession.cookies.get({ url: env.origin })).map(cookie => `${cookie.name}=${cookie.value}`).join("; ") }),
onChange: summary => { lendingIndicator().update(summary); loginItem.follow(summary.lending.length > 0); },
cuaConnection: () => cuaReady, screenLocked: () => powerMonitor.getSystemIdleState(1) === "locked", idleSeconds: () => powerMonitor.getSystemIdleState(1) === "unknown" ? null : powerMonitor.getSystemIdleTime(),
@@ -3157,7 +3157,7 @@ app.whenReady().then(async () => {
return credentials;
}).finally(syncManagedComposioCredentials);
}
- startUpdater(quietSignals({ powerMonitor, window: () => mainWindow, lastInput: oneHome.lastInput, local: localServerRequest, place: () => homeWindow.placeOrigin(), cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => origin === homeWindow.cloudOrigin() && cloudPower.asleep(), busy: () => (oneHome.oneHome.busy() && "move") || (computerSharing?.busy() && "lending") || (talk.busy() && "talk") || (companyBackupController || companyRestoreCommitting ? "backup" : null) }));
+ startUpdater(quietSignals({ powerMonitor, window: () => mainWindow, lastInput: oneHome.lastInput, local: localServerRequest, place: () => homeWindow.placeOrigin(), cloudFetch: (...args) => session.defaultSession.fetch(...args), asleep: origin => homeWindow.asleepAt(origin), busy: () => (oneHome.oneHome.busy() && "move") || (computerSharing?.busy() && "lending") || (talk.busy() && "talk") || (companyBackupController || companyRestoreCommitting ? "backup" : null) }));
refreshApplicationMenu();
openWindowForLink = () => {
if (!mainWindow || mainWindow.isDestroyed()) createWindow({ deferNavigation: homeWindow.current().kind !== "computer" });
diff --git a/electron/use-my-mac.node-test.mjs b/electron/use-my-mac.node-test.mjs
index f266776c4e..d86737a529 100644
--- a/electron/use-my-mac.node-test.mjs
+++ b/electron/use-my-mac.node-test.mjs
@@ -493,3 +493,31 @@ test("another Cloud of the person's own going to sleep holds only its own link:
assert.equal(to(OTHER).length, 1, "the Cloud going to sleep is not dialled again at once");
assert.equal(to(ORIGIN).filter((socket) => !socket.closed).length, 1, "My Cloud's link stays open");
});
+
+test("another Cloud of the person's own that the Admin says is asleep is never dialled, even after its own hold ends, and lends once the Admin says it is awake", async (t) => {
+ const dir = await realpath(await mkdtemp(path.join(tmpdir(), "omb-use-my-mac-")));
+ t.after(() => rm(dir, { recursive: true, force: true }));
+ const OTHER = "https://omb-c-b.fly.dev";
+ const mine = env, other = { id: "client-b", name: "Client B", origin: OTHER, cloud: { id: "c-b", role: "owner" } };
+ const homes = { [ORIGIN]: cloudHome(), [OTHER]: cloudHome() };
+ const sockets = fakeSockets((url) => { const at = new URL(url.replace(/^wss:/, "https:")); return homes[at.origin].registered.has(at.pathname.split("/")[3]); });
+ // The Admin's word on each Cloud, as the session's Clouds list carries it (`power`): My Cloud awake, Client B asleep.
+ let words = { [ORIGIN]: { state: "awake", since: 1, sleeps: true }, [OTHER]: { state: "asleep", since: 1, sleeps: true } };
+ const power = createCloudPowerGate({ power: () => words[ORIGIN], holdMs: 60_000 });
+ const sharing = createComputerSharing({
+ file: path.join(dir, "profile", "computer-sharing.json"), fetch: (url, init) => homes[new URL(url).origin].fetch(url, init), environments: () => [mine, other],
+ enabled: async () => false, myCloud: () => mine, ownClouds: () => [mine, other], cloud: (place) => ({ status: "connected", accountId: "acct_1", origin: place?.cloud ? place.origin : ORIGIN }),
+ home: path.join(dir, "home"), cuaConnection: async () => null, power, WebSocket: sockets.FakeSocket, linkHeaders: () => ({}),
+ cloudPower: (origin) => words[origin] ?? null,
+ });
+ t.after(() => sharing.close());
+ sharing.start();
+ await until(() => sharing.cloudState(other).problem === "asleep" && sharing.cloudState(mine).link === "on", "My Cloud to lend and Client B to wait");
+ await delay(300);
+ assert.equal(sharing.cloudState(other).enabled, true, "it is lent");
+ assert.deepEqual(homes[OTHER].calls, [], "nothing called the Cloud the Admin says is asleep: any request reaching it wakes it");
+ // The Admin's word changing (a session read) lets it go on.
+ words = { ...words, [OTHER]: { state: "awake", since: 2, sleeps: true } };
+ sharing.cloudChanged();
+ await until(() => sharing.cloudState(other).link === "on" && homes[OTHER].connects.length === 1, "Client B's link to open once the Admin says it is awake");
+});
diff --git a/server/cloud-power.test.ts b/server/cloud-power.test.ts
index c77d09e2b4..27279d1b26 100644
--- a/server/cloud-power.test.ts
+++ b/server/cloud-power.test.ts
@@ -7,7 +7,7 @@ import { afterEach, describe, expect, it } from "vitest";
import { cloudRequestSignature } from "./cloud-home.ts";
import {
CLOUD_IDLE_ACTIVITY_MS, CLOUD_IDLE_AWAKE_MS, CLOUD_IDLE_WORK_MS, CLOUD_POWER_PATH, CLOUD_POWER_SLEEP_PATH, CLOUD_SLEEP_PENDING_MS,
- countsAsActivity, createCloudPower, wokeFromSleep, type CloudPowerProbes,
+ countsAsActivity, createCloudPower, wakeCode, wokeFromSleep, WOKE_BY_MS, type CloudPowerProbes,
} from "./cloud-power.ts";
import { createCloudSignedRoutes } from "./routes/cloud-signed.ts";
import { SessionRegistry } from "./sessions.ts";
@@ -139,6 +139,40 @@ describe("the sleep handshake", () => {
});
});
+describe("what woke the home", () => {
+ it("is the first request after a boot or a resume, its kind and whether it was a background one, never more of it", () => {
+ const h = home();
+ expect(h.power.report().wokeBy).toBeNull();
+ h.power.arrived("/api/events", {});
+ h.power.arrived("/api/bots", {});
+ expect(h.power.report().wokeBy).toEqual({ by: "events", background: true });
+ h.pass(CLOUD_IDLE_AWAKE_MS);
+ h.power.prepareSleep();
+ // Suspended, then resumed for a request: noticed by the request itself, before the clock tick does.
+ h.jump(33_000);
+ h.power.arrived("/.well-known/openmausbot/environment", { "x-omb-background": "1" });
+ expect(h.power.sleeping()).toBe(false);
+ expect(h.power.report()).toMatchObject({ wokeAt: h.now(), wokeBy: { by: "version", background: true } });
+ h.power.arrived("/api/threads", {});
+ expect(h.power.report().wokeBy, "only the first one").toEqual({ by: "version", background: true });
+ // Resumed, and nothing reached it for a while: whatever comes later did not wake it.
+ h.pass(CLOUD_IDLE_AWAKE_MS);
+ h.jump(3600_000);
+ h.power.tick();
+ h.pass(WOKE_BY_MS + 5_000);
+ h.power.arrived("/api/bots", {});
+ expect(h.power.report().wokeBy).toBeNull();
+ });
+
+ it("names each kind of request by its path alone", () => {
+ const paths = ["/api/events", "/api/sync/changes", "/api/shared-computers/abc/poll", "/.well-known/openmausbot/environment", "/api/phones/self/jobs",
+ "/api/presence/active", "/api/auth/session", "/api/auth/pair", "/pair", "/api/cloud/pairing", "/api/health", "/hooks", "/mcp-oauth/callback",
+ "/api/bots/b1/read", "/", "/assets/index.js"];
+ expect(paths.map(wakeCode)).toEqual(["events", "sync", "lending", "version", "phone", "presence", "session", "pair", "pair", "admin", "health", "webhook",
+ "sign-in", "api", "page", "page"]);
+ });
+});
+
describe("waking from a sleep the machine was stopped for", () => {
it("is not a startup once, and only after a sleep", () => {
const dataDir = mkdtempSync(join(tmpdir(), "omb-cloud-power-"));
diff --git a/server/cloud-power.ts b/server/cloud-power.ts
index f0eeac95bc..0ab90c0f8e 100644
--- a/server/cloud-power.ts
+++ b/server/cloud-power.ts
@@ -22,6 +22,9 @@ export interface CloudPowerReport {
nextDueAt: number | null;
/** The home said yes to a sleep request and has not been used or woken since. */
sleeping: boolean;
+ /** What the first request after its last wake (or boot) was, if one came within WOKE_BY_MS: a fixed code for its kind
+ * (`wakeCode`) and whether it was a background one. The Admin logs it for a wake by Fly's proxy: what woke it. */
+ wokeBy: { by: string; background: boolean } | null;
}
export interface CloudPowerProbes {
@@ -49,6 +52,17 @@ export const CLOUD_IDLE_DUE_MS = 5 * 60_000;
export const CLOUD_SLEEP_PENDING_MS = 120_000;
/** The clock tick that notices a resume: a jump this much larger than the tick means the machine was suspended. */
const TICK_MS = 5_000, RESUME_JUMP_MS = 15_000;
+/** The first request this soon after a wake or a boot is taken for what woke the home (`wokeBy`). */
+export const WOKE_BY_MS = 30_000;
+/** Each kind of request, as a fixed code, by its path: never more of the request than that. Anything else is a page. */
+const WAKE_CODES: readonly [RegExp, string][] = [
+ [/^\/api\/events$/, "events"], [/^\/api\/sync(\/|$)/, "sync"], [/^\/api\/shared-computers(\/|$)/, "lending"],
+ [/^\/\.well-known\/openmausbot\/environment$/, "version"], [/^\/api\/phones(\/|$)/, "phone"], [/^\/api\/presence(\/|$)/, "presence"],
+ [/^\/api\/auth\/session$/, "session"], [/^\/(?:api\/)?(?:auth\/)?pair(?:ing)?(?:\/|$)/, "pair"], [/^\/api\/cloud\//, "admin"],
+ [/^\/api\/health$/, "health"], [/^\/hooks(\/|$)/, "webhook"], [/^\/mcp-oauth\//, "sign-in"], [/^\/api\//, "api"],
+];
+/** A request's kind (`wokeBy`): "events" (a page's live stream), "version" (the desktop's version check), "api" and so on. */
+export const wakeCode = (path: string) => WAKE_CODES.find(([pattern]) => pattern.test(path))?.[1] ?? "page";
/** Paths that never count as someone using the home: the event stream, the public probe, Files and lending loops,
* and the Admin's own power reads. */
const BACKGROUND = [/^\/api\/events$/, /^\/api\/health$/, /^\/api\/sync(\/|$)/, /^\/api\/shared-computers(\/|$)/, /^\/api\/cloud\/power(\/|$)/];
@@ -98,6 +112,8 @@ export function createCloudPower(options: {
const now = options.now ?? Date.now;
const bootedAt = now();
let wokeAt = bootedAt, lastActivityAt: number | null = null, lastWorkAt: number | null = null;
+ /** The first request since `wokeAt` (`arrived`), and whether one came. */
+ let wokeBy: CloudPowerReport["wokeBy"] = null, wokeSeen = false;
let sleepingSince: number | null = null, inFlight = 0;
let sleepAbort = new AbortController();
let lastTick = now();
@@ -123,13 +139,19 @@ export function createCloudPower(options: {
if (probes.maintenance() || inFlight > 0) busy.push("maintenance");
return busy;
};
+ /** A resume: the clock jumped past the tick (noticed once, by the tick or by a request). */
+ const resumed = (at: number) => {
+ if (at - lastTick <= TICK_MS + RESUME_JUMP_MS) return;
+ lastTick = at;
+ wokeAt = at;
+ wokeBy = null;
+ wokeSeen = false;
+ endSleep();
+ };
/** Samples work (so "finished two minutes ago" needs no hook in every kind of work) and notices a resume. */
const tick = () => {
const at = now();
- if (at - lastTick > TICK_MS + RESUME_JUMP_MS) {
- wokeAt = at;
- endSleep();
- }
+ resumed(at);
lastTick = at;
if (working().length) lastWorkAt = at;
};
@@ -164,6 +186,15 @@ export function createCloudPower(options: {
return {
noteActivity,
begin,
+ /** Any request at all, first thing (the server's own and its webhooks'): the first after a wake or a boot is what woke
+ * it (`wokeBy`). Only its kind is kept. A resume is noticed here too, before the clock tick. */
+ arrived(path: string, headers: IncomingHttpHeaders) {
+ const at = now();
+ resumed(at);
+ if (wokeSeen || at - wokeAt > WOKE_BY_MS) return;
+ wokeSeen = true;
+ wokeBy = { by: wakeCode(path), background: !countsAsActivity(path, headers) };
+ },
/** An authenticated request: someone using the home (`countsAsActivity`), and work in progress until it ends. */
request(path: string, headers: IncomingHttpHeaders, res: Pick<ServerResponse, "once">) {
if (countsAsActivity(path, headers)) noteActivity();
@@ -171,7 +202,7 @@ export function createCloudPower(options: {
},
report(activityMs = CLOUD_IDLE_ACTIVITY_MS): CloudPowerReport {
const busy = busyNow(activityMs);
- return { v: 1, at: now(), bootedAt, wokeAt, idle: busy.length === 0, busy, lastActivityAt, lastWorkAt, nextDueAt: options.probes.nextDueAt(), sleeping: sleeping() };
+ return { v: 1, at: now(), bootedAt, wokeAt, idle: busy.length === 0, busy, lastActivityAt, lastWorkAt, nextDueAt: options.probes.nextDueAt(), sleeping: sleeping(), wokeBy };
},
/** The Admin is about to suspend or stop this machine: yes only when idle now. From here until a resume, someone's
* use or CLOUD_SLEEP_PENDING_MS, held polls answer "asleep" and new ones are refused (`sleeping`). */
diff --git a/server/index.ts b/server/index.ts
index 2d813103e0..dd25ef71b8 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -9650,7 +9650,7 @@ let webhookIngressError: string | null = null;
try {
webhookIngress = await listenWebhookIngress(webhooks, {
port: WEBHOOK_PORT, publicBaseUrl: WEBHOOK_PUBLIC_URL,
- claimRequest: () => { moveFreeze.assertTurns(); return workspaceMaintenance.request(); },
+ claimRequest: () => { cloudPower?.arrived("/hooks", {}); moveFreeze.assertTurns(); return workspaceMaintenance.request(); },
});
const advertised = WEBHOOK_PUBLIC_URL ? ` (advertised as ${webhookIngress.baseUrl})` : "";
console.log(`openmausbot webhook receiver on http://${webhookIngress.host}:${webhookIngress.port}${advertised}`);
@@ -12726,7 +12726,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
return json(res, 400, { error: "invalid request URL" });
}
const path = url.pathname;
- const method = req.method ?? "GET";
+ const method = req.method ?? "GET"; cloudPower?.arrived(path, req.headers); // a Cloud home's first request after a wake: what woke it
let m: RegExpMatchArray | null = null;
let releaseWorkspaceRequest: (() => void) | undefined;
try {
diff --git a/src/App.tsx b/src/App.tsx
index 30809f8f48..33a9b98526 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -205,7 +205,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
useEffect(() => {
if (!state.connected) return;
- void preloadConnectedApps().catch(() => {});
+ void preloadConnectedApps(false, true).catch(() => {}); // a background read: a reconnect is nobody using a Cloud home
}, [state.connected]);
useUsageSnapshot();
diff --git a/src/components/CloudTimeZone.tsx b/src/components/CloudTimeZone.tsx
index 30912ccdab..63a68ce57b 100644
--- a/src/components/CloudTimeZone.tsx
+++ b/src/components/CloudTimeZone.tsx
@@ -17,7 +17,8 @@ export function deviceTimeZone(): string | null {
/** Only the owner's own devices: a guest or teammate has no admin scope, and their zone is not the owner's. */
export async function syncCloudTimeZone(zone: string | null, request: typeof api = api): Promise<boolean> {
if (!zone) return false;
- const current = await request<{ timeZone?: string; adopts?: boolean }>("/api/time-zone", { timeoutMs: 10_000 });
+ // A read after every reconnect, not someone using My Cloud (src/state/api.ts `background`); the rare change below is.
+ const current = await request<{ timeZone?: string; adopts?: boolean }>("/api/time-zone", { timeoutMs: 10_000, background: true });
if (!current?.adopts || current.timeZone === zone) return false;
await request("/api/time-zone", { method: "PUT", body: JSON.stringify({ timeZone: zone }), timeoutMs: 10_000 });
return true;
diff --git a/src/components/PluginsPanel.tsx b/src/components/PluginsPanel.tsx
index 4fb726288e..a957c151fc 100644
--- a/src/components/PluginsPanel.tsx
+++ b/src/components/PluginsPanel.tsx
@@ -50,7 +50,7 @@ export interface ConnectorInventory {
authoritative: boolean;
}
-export function preloadConnectedApps(force = false): Promise<ConnectorInventory> {
+export function preloadConnectedApps(force = false, background = false): Promise<ConnectorInventory> { // background: src/state/api.ts
if (!force && cachedConnectorStatus !== null && Date.now() - cachedConnectorStatusAt < CONNECTOR_STATUS_CACHE_MS) {
return Promise.resolve({
services: cachedConnectorStatus,
@@ -58,7 +58,7 @@ export function preloadConnectedApps(force = false): Promise<ConnectorInventory>
});
}
if (connectorStatusRequest) return connectorStatusRequest;
- connectorStatusRequest = api("/api/connectors/connected")
+ connectorStatusRequest = api("/api/connectors/connected", background ? { background: true } : undefined)
.then((response: { services?: Record<string, ConnectorStatus>; credentialStore?: string; inventoryComplete?: boolean }) => {
const services: Record<string, ConnectorStatus> = response.services ?? {};
if (response.credentialStore === "unavailable" || response.inventoryComplete === false) {
diff --git a/src/hooks/use-usage-snapshot.test.ts b/src/hooks/use-usage-snapshot.test.ts
index c668f88422..c6a60666e9 100644
--- a/src/hooks/use-usage-snapshot.test.ts
+++ b/src/hooks/use-usage-snapshot.test.ts
@@ -76,6 +76,10 @@ describe("useUsageSnapshot", () => {
await draw(ready());
expect(sent()).toHaveLength(1);
expect(sent()[0]![1]).toMatchObject({ bots: 0, engines: ["claude"], platform: "browser", remote_client: false });
+ // Its reads are background reads: nobody is using a Cloud home when the day's snapshot goes (src/state/api.ts).
+ expect(fixture.api.mock.calls.length).toBeGreaterThan(0);
+ expect(fixture.api.mock.calls.every(([, init]) => (init as { background?: boolean } | undefined)?.background === true)).toBe(true);
+ expect(fixture.connectedApps).toHaveBeenCalledWith(false, true);
});
it("still sends one through re-renders and readiness that comes and goes", async () => {
diff --git a/src/hooks/use-usage-snapshot.ts b/src/hooks/use-usage-snapshot.ts
index 57ca044853..1791f8840b 100644
--- a/src/hooks/use-usage-snapshot.ts
+++ b/src/hooks/use-usage-snapshot.ts
@@ -13,8 +13,9 @@ function browserSources(config: ConfigStatus | null): UsageSources {
const local = !remoteClient && localDesktopPage();
const companion = (globalThis as { ogb?: { companion?: CompanionDevices } }).ogb?.companion ?? null;
return {
- request: (path) => api(path),
- connectedApps: () => preloadConnectedApps(),
+ // Background reads: the daily snapshot is nobody using a Cloud home (src/state/api.ts).
+ request: (path) => api(path, { background: true }),
+ connectedApps: () => preloadConnectedApps(false, true),
companion: local ? companion : null,
cloudAccount: local ? ogb?.cloudAccount ?? null : null,
cloudPlan: !remoteClient && !local && config?.cloudHome === true ? ogb?.cloudPlan ?? null : null,
diff --git a/src/lib/cloud-power.ts b/src/lib/cloud-power.ts
index 0ebc1ce104..9ad2f6c81c 100644
--- a/src/lib/cloud-power.ts
+++ b/src/lib/cloud-power.ts
@@ -51,6 +51,24 @@ export function markCloudAsleep(target: Pick<Window, "addEventListener" | "remov
detach = () => { for (const name of events) target.removeEventListener(name, wake, { capture: true }); };
}
+/** The page is out of sight: a background tab, a minimized or hidden window. */
+export function pageHidden(): boolean {
+ return typeof document !== "undefined" && document.visibilityState === "hidden";
+}
+
+/** Resolves once the page shows again (at once when it isn't hidden); rejects if `signal` aborts first. */
+export function pageShown(signal?: AbortSignal): Promise<void> {
+ if (!pageHidden()) return Promise.resolve();
+ return new Promise((resolve, reject) => {
+ const done = () => { document.removeEventListener("visibilitychange", check); signal?.removeEventListener("abort", abort); };
+ const check = () => { if (!pageHidden()) { done(); resolve(); } };
+ const abort = () => { done(); reject(signal?.reason ?? new DOMException("The request was aborted.", "AbortError")); };
+ if (signal?.aborted) { abort(); return; }
+ document.addEventListener("visibilitychange", check);
+ signal?.addEventListener("abort", abort, { once: true });
+ });
+}
+
/** An "asleep" answer from the home (held polls and refused background requests carry it). */
export function asleepAnswer(response: Pick<Response, "status" | "headers">): boolean {
return response.status === 503 && response.headers.get(CLOUD_POWER_HEADER) === "asleep";
diff --git a/src/lib/phones.ts b/src/lib/phones.ts
index 90673ea8f2..7a42174001 100644
--- a/src/lib/phones.ts
+++ b/src/lib/phones.ts
@@ -84,7 +84,8 @@ export function usePhones(): { phase: "loading" | "ready"; phones: PublicPhone[]
const disposed = useRef(false);
const refresh = useCallback(() => {
- void api<{ phones: PublicPhone[] }>("/api/phones")
+ // A poll: never someone using a Cloud home, and never sent from a hidden page (src/state/api.ts `background`).
+ void api<{ phones: PublicPhone[] }>("/api/phones", { background: true })
.then((response) => {
if (!disposed.current) setState({ phase: "ready", phones: response.phones ?? [] });
})
diff --git a/src/state/api-background.test.ts b/src/state/api-background.test.ts
index 81ec0fc8ad..7416280011 100644
--- a/src/state/api-background.test.ts
+++ b/src/state/api-background.test.ts
@@ -36,4 +36,50 @@ describe("api() and a Cloud home that sleeps", () => {
await expect(api("/api/sync")).rejects.toBeInstanceOf(ApiError);
expect(cloudAsleep()).toBe(true);
});
+
+ it("holds background requests while the page is hidden, one per path, and sends them once it shows", async () => {
+ const fetch = vi.fn(async (_path: string, _init?: RequestInit) => new Response("{}", { status: 200 }));
+ vi.stubGlobal("fetch", fetch);
+ const page = hiddenPage();
+ vi.stubGlobal("document", page);
+ // A poll that ticks twice while hidden asks once; other paths each wait; the person's own request goes at once.
+ const held = [api("/api/limit-resets", { background: true }), api("/api/limit-resets", { background: true }), api("/api/inbox", { background: true }),
+ api("/api/inbox/a/read", { method: "POST", background: true })];
+ await api("/api/threads");
+ expect(fetch.mock.calls.map(([path]) => path)).toEqual(["/api/threads"]);
+ page.show();
+ await Promise.all(held);
+ expect(fetch.mock.calls.map(([path]) => path)).toEqual(["/api/threads", "/api/limit-resets", "/api/inbox", "/api/inbox/a/read"]);
+ expect(new Headers(fetch.mock.calls[1]![1]?.headers).get("x-omb-background")).toBe("1");
+ expect(page.listeners.size).toBe(0);
+ });
+
+ it("refuses a held background request if the home fell asleep before the page showed, and lets a caller's signal end the wait", async () => {
+ const fetch = vi.fn(async (_path: string, _init?: RequestInit) => new Response("{}", { status: 200 }));
+ vi.stubGlobal("fetch", fetch);
+ const page = hiddenPage();
+ vi.stubGlobal("document", page);
+ const held = api("/api/limit-resets", { background: true });
+ const controller = new AbortController();
+ const mine = api("/api/team-map", { background: true, signal: controller.signal });
+ controller.abort();
+ await expect(mine).rejects.toMatchObject({ name: "AbortError" });
+ markCloudAsleep(undefined);
+ page.show();
+ await expect(held).rejects.toMatchObject({ status: 503 });
+ expect(fetch).not.toHaveBeenCalled();
+ });
});
+
+/** A hidden page's `document`, as far as api() reads it, that can be shown. */
+function hiddenPage() {
+ const listeners = new Set<() => void>();
+ const page = {
+ visibilityState: "hidden" as DocumentVisibilityState,
+ listeners,
+ addEventListener: (_type: string, listener: () => void) => { listeners.add(listener); },
+ removeEventListener: (_type: string, listener: () => void) => { listeners.delete(listener); },
+ show() { page.visibilityState = "visible"; for (const listener of Array.from(listeners)) listener(); },
+ };
+ return page;
+}
diff --git a/src/state/api.ts b/src/state/api.ts
index c0f1a144d6..9d734655ce 100644
--- a/src/state/api.ts
+++ b/src/state/api.ts
@@ -1,6 +1,6 @@
// The renderer's JSON request helper. A Cloud home that went to sleep is never woken by a background poll
-// (src/lib/cloud-power.ts).
-import { asleepAnswer, BACKGROUND_HEADER, cloudAsleep, markCloudAsleep, markCloudAwake } from "../lib/cloud-power";
+// (src/lib/cloud-power.ts), and a page out of sight sends none at all.
+import { asleepAnswer, BACKGROUND_HEADER, cloudAsleep, markCloudAsleep, markCloudAwake, pageHidden, pageShown } from "../lib/cloud-power";
export class ApiError extends Error {
readonly status: number;
@@ -13,10 +13,17 @@ export class ApiError extends Error {
}
}
+type ApiInit = RequestInit & { timeoutMs?: number; background?: boolean };
+/** Background reads waiting for a hidden page to show again, one per path: a poll that ticks while hidden asks once. */
+const heldReads = new Map<string, Promise<unknown>>();
+
/** `background`: a poll nobody asked for just now. It never wakes a Cloud home that went to sleep (it is refused here
- * instead, src/lib/cloud-power.ts) and the home doesn't count it as someone using it. Anything else wakes it. */
-export async function api<T = any>(path: string, init?: RequestInit & { timeoutMs?: number; background?: boolean }): Promise<T> {
+ * instead, src/lib/cloud-power.ts) and the home doesn't count it as someone using it. Anything else wakes it. While the
+ * page is hidden (a background tab, a minimized window) a background request waits until it shows again, so a page out of
+ * sight never reaches a Cloud home on its own: a Cloud home asleep is woken by any request that reaches it. */
+export async function api<T = any>(path: string, init?: ApiInit): Promise<T> {
const { timeoutMs, signal, background, headers, ...rest } = init ?? {};
+ if (background && pageHidden()) return heldUntilShown<T>(path, init!);
if (cloudAsleep()) {
if (background) throw new ApiError("My Cloud is asleep", 503, { error: "asleep" });
markCloudAwake();
@@ -41,3 +48,16 @@ export async function api<T = any>(path: string, init?: RequestInit & { timeoutM
}
return body;
}
+
+/** A background request from a hidden page, sent once it shows again (src/lib/cloud-power.ts `pageShown`), by then refused if
+ * the Cloud home fell asleep meanwhile. Reads of one path without a signal of their own share one request. */
+function heldUntilShown<T>(path: string, init: ApiInit): Promise<T> {
+ const shared = (init.method ?? "GET").toUpperCase() === "GET" && !init.signal;
+ const waiting = shared ? heldReads.get(path) : undefined;
+ if (waiting) return waiting as Promise<T>;
+ const sent = pageShown(init.signal ?? undefined).then(() => api<T>(path, init));
+ if (!shared) return sent;
+ heldReads.set(path, sent);
+ void sent.finally(() => { if (heldReads.get(path) === sent) heldReads.delete(path); }).catch(() => {});
+ return sent;
+}