Skip to content

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

Wait for lent computers after a Cloud wakes, and tell the Admin at once (#5135)

Milind Soni128f60c8bcaf
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.md
index 40d4747e32..4c6b8b5698 100644
--- a/docs/cloud-pro.md
+++ b/docs/cloud-pro.md
@@ -1819,6 +1819,17 @@ the desktop's version check, `sync`, `lending`, `phone`, `presence`, `session`,
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/machines/woke`** on the Admin (additive, sent by the home,
+signed with its machine secret over `{"v":1,"wokeAt":<ms>}`, as
+`omb-power-woke-v1\n<machine id>\n<timestamp>\n<nonce>\n<hash of the body>`;
+sent at each wake (a resume, or a boot from a sleep it was stopped for), never
+retried; an Admin without it answers `404` and nothing changes). It says the
+home is awake now, so the Admin can move `cloud.power` on at the desktops' next
+session read instead of at its next power read. The lent computers also get a
+grace window: for about 90 s after a wake, a bot's `shared_computer` call and
+`list_shared_computers` wait for a computer lent to this home instead of
+failing at once (`server/shared-computers.ts`).
+
**`POST /api/cloud/power/sleep`**, signed over its JSON body
`{"v":1,"idleMinutes":10}`. `409 {"ok":false,"busy":[…]}` while not idle;
`200 {"ok":true,"nextDueAt":…}` once the home agreed. From then on, until a
diff --git a/server/cloud-power.test.ts b/server/cloud-power.test.ts
index 3fb0c0e435..c0e1374a43 100644
--- a/server/cloud-power.test.ts
+++ b/server/cloud-power.test.ts
@@ -21,7 +21,7 @@ afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
-function home(probes: Partial<CloudPowerProbes> = {}) {
+function home(probes: Partial<CloudPowerProbes> = {}, onWoke?: () => void, bootedFromSleep = false) {
let clock = START;
const dataDir = mkdtempSync(join(tmpdir(), "omb-cloud-power-"));
dirs.push(dataDir);
@@ -30,13 +30,31 @@ function home(probes: Partial<CloudPowerProbes> = {}) {
const power = createCloudPower({ dataDir, now: () => clock, broadcast: (payload) => sent.push(payload), probes: {
turn: () => state.turn, run: () => state.run, handoff: () => state.handoff, liveCall: () => state.liveCall, computer: () => state.computer,
maintenance: () => state.maintenance, nextDueAt: () => state.nextDueAt, ...probes,
- } });
+ }, onWoke, bootedFromSleep });
powers.push(power);
/** Moves the clock in ticks, as the 5-second timer would (a single big step is a resume). */
const pass = (ms: number) => { for (let left = ms; left > 0; left -= 5_000) { clock += Math.min(5_000, left); power.tick(); } };
return { power, state, sent, dataDir, pass, jump: (ms: number) => { clock += ms; }, now: () => clock };
}
+describe("telling the Admin it woke", () => {
+ it("a plain restart isn't a wake; a boot from a sleep it was stopped for, and each resume the tick or a request notices, are", () => {
+ let woke = 0;
+ const plain = home({}, () => { woke++; });
+ expect(woke).toBe(0);
+ expect(plain.power.sleptUntil()).toBeNull();
+ const fromSleep = home({}, () => { woke++; }, true);
+ expect(woke).toBe(1);
+ expect(fromSleep.power.sleptUntil()).toBe(START);
+ plain.jump(10 * 60_000);
+ plain.power.tick();
+ expect(woke).toBe(2);
+ expect(plain.power.sleptUntil()).toBe(plain.now());
+ plain.pass(10_000);
+ expect(woke).toBe(2);
+ });
+});
+
describe("the home's idle verdict", () => {
it("is busy just after it wakes, then idle with nothing going on", () => {
const h = home();
diff --git a/server/cloud-power.ts b/server/cloud-power.ts
index e495cfd2fb..76d848a9ad 100644
--- a/server/cloud-power.ts
+++ b/server/cloud-power.ts
@@ -109,10 +109,17 @@ export function createCloudPower(options: {
broadcast(payload: Record<string, unknown>): void;
now?: () => number;
log?: (line: string) => void;
+ /** It woke from a sleep it was stopped for: this boot, like a resume, is a wake. */
+ bootedFromSleep?: boolean;
+ /** It just woke: the Admin hears at once, not at its next read (`createWokeNotifier`). */
+ onWoke?: () => void;
}) {
const now = options.now ?? Date.now;
const bootedAt = now();
let wokeAt = bootedAt, lastActivityAt: number | null = null, lastWorkAt: number | null = null;
+ /** The last wake from sleep; null while this process has only ever booted normally. */
+ let sleptUntil: number | null = options.bootedFromSleep ? bootedAt : null;
+ if (options.bootedFromSleep) options.onWoke?.();
/** The first request since `wokeAt` (`arrived`), and whether one came. */
let wokeBy: CloudPowerReport["wokeBy"] = null, wokeSeen = false;
let sleepingSince: number | null = null, inFlight = 0;
@@ -148,7 +155,9 @@ export function createCloudPower(options: {
wokeAt = at;
wokeBy = null;
wokeSeen = false;
+ sleptUntil = at;
endSleep();
+ options.onWoke?.();
};
/** Samples work (so "finished two minutes ago" needs no hook in every kind of work) and notices a resume. */
const tick = () => {
@@ -219,6 +228,8 @@ export function createCloudPower(options: {
return { ok: true, nextDueAt: options.probes.nextDueAt() };
},
sleeping,
+ /** The last wake from sleep (a resume, or a boot from one), kept current by the tick and each request; null otherwise. */
+ sleptUntil: () => sleptUntil,
/** Aborted the moment the home agrees to sleep: held long-polls end with it and answer "asleep". */
sleepSignal: () => sleepAbort.signal,
/** Tests: the clock tick, without waiting for the timer. */
@@ -230,6 +241,6 @@ export function createCloudPower(options: {
export type CloudPower = ReturnType<typeof createCloudPower>;
/** The running home's power, for route modules built before it (Files sync); null on any server that is not a Cloud home. */
-let registered: Pick<CloudPower, "sleeping" | "sleepSignal"> | null = null;
-export function registerCloudPower(power: Pick<CloudPower, "sleeping" | "sleepSignal"> | null) { registered = power; }
+let registered: Pick<CloudPower, "sleeping" | "sleepSignal" | "sleptUntil"> | null = null;
+export function registerCloudPower(power: Pick<CloudPower, "sleeping" | "sleepSignal" | "sleptUntil"> | null) { registered = power; }
export const cloudPowerNow = () => registered;
diff --git a/server/cloud-woke.test.ts b/server/cloud-woke.test.ts
new file mode 100644
index 0000000000..0826915c20
--- /dev/null
+++ b/server/cloud-woke.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it, vi } from "vitest";
+import { createWokeNotifier, wokeSignature, WOKE_ADMIN_PATH } from "./cloud-woke.ts";
+
+const options = { adminOrigin: "https://admin.test", machineId: "cm_1", secret: "s".repeat(43) };
+
+describe("the wake notice to the Admin", () => {
+ it("is signed over its body with this machine's secret", async () => {
+ const calls: { url: string; init: RequestInit }[] = [];
+ const fetcher = vi.fn(async (url: string | URL | Request, init?: RequestInit) => { calls.push({ url: String(url), init: init! }); return new Response("{}", { status: 200 }); });
+ createWokeNotifier({ ...options, fetcher: fetcher as never, now: () => 1_700_000_000_000 })();
+ await vi.waitFor(() => expect(calls).toHaveLength(1));
+ const [{ url, init }] = calls;
+ expect(url).toBe(`https://admin.test${WOKE_ADMIN_PATH}`);
+ expect(init.body).toBe(JSON.stringify({ v: 1, wokeAt: 1_700_000_000_000 }));
+ const headers = init.headers as Record<string, string>;
+ expect(headers["x-omb-cloud-machine"]).toBe("cm_1");
+ expect(headers["x-omb-cloud-signature"]).toBe(`v1=${wokeSignature(options.secret, "cm_1", headers["x-omb-cloud-timestamp"]!, headers["x-omb-cloud-nonce"]!, init.body as string)}`);
+ });
+ it("an older Admin that doesn't know it, or an Admin that can't be reached, changes nothing and is said once", async () => {
+ const log = vi.fn();
+ const older = createWokeNotifier({ ...options, log, fetcher: (async () => new Response("", { status: 404 })) as never });
+ older();
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(log).not.toHaveBeenCalled();
+ const down = createWokeNotifier({ ...options, log, fetcher: (async () => { throw new TypeError("network"); }) as never });
+ down(); down();
+ await vi.waitFor(() => expect(log).toHaveBeenCalledTimes(1));
+ expect(log.mock.calls[0]![0]).toMatch(/could not reach the Admin/);
+ });
+});
diff --git a/server/cloud-woke.ts b/server/cloud-woke.ts
new file mode 100644
index 0000000000..d48130aee2
--- /dev/null
+++ b/server/cloud-woke.ts
@@ -0,0 +1,33 @@
+// A Cloud home that woke (or started) says so to the Admin at once, signed with its machine secret, so the Admin's word
+// on it (the session's `cloud.power`) moves on at the desktops' next read, not a minute later at the Admin's next read
+// of this home: a desktop that lends to it stops calling while it sleeps. docs/cloud-pro.md, "Sleeping homes". An older
+// Admin answers 404 and nothing changes; this never retries.
+import { createHash, createHmac, randomBytes } from "node:crypto";
+
+export const WOKE_ADMIN_PATH = "/api/cloud/machines/woke";
+const WOKE_TIMEOUT_MS = 5_000;
+
+export function wokeSignature(secret: string, machineId: string, timestamp: string, nonce: string, body: string): string {
+ const bodyHash = createHash("sha256").update(body).digest("hex");
+ return createHmac("sha256", secret).update(`omb-power-woke-v1\n${machineId}\n${timestamp}\n${nonce}\n${bodyHash}`).digest("base64url");
+}
+
+export function createWokeNotifier(options: {
+ adminOrigin: string; machineId: string; secret: string; fetcher?: typeof fetch; now?: () => number; log?: (line: string) => void;
+}): () => void {
+ const { adminOrigin, machineId, secret, fetcher = fetch, now = Date.now, log } = options;
+ let warned = false;
+ return () => {
+ const body = JSON.stringify({ v: 1, wokeAt: now() });
+ const timestamp = String(Math.floor(now() / 1000)), nonce = randomBytes(18).toString("base64url");
+ void fetcher(`${adminOrigin}${WOKE_ADMIN_PATH}`, { method: "POST", redirect: "error", cache: "no-store", body, signal: AbortSignal.timeout(WOKE_TIMEOUT_MS), headers: {
+ accept: "application/json", "content-type": "application/json", "x-omb-cloud-machine": machineId, "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce,
+ "x-omb-cloud-signature": `v1=${wokeSignature(secret, machineId, timestamp, nonce, body)}`,
+ } }).then(async (response) => {
+ await response.body?.cancel().catch(() => {});
+ if (!response.ok && response.status !== 404 && !warned) { warned = true; log?.(`cloud power: the Admin answered HTTP ${response.status} to the wake notice`); }
+ }, (error: unknown) => {
+ if (!warned) { warned = true; log?.(`cloud power: could not reach the Admin with the wake notice (${error instanceof Error ? error.name : "error"})`); }
+ });
+ };
+}
diff --git a/server/index.ts b/server/index.ts
index 6b4e75039a..de95acaf59 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -279,7 +279,7 @@ import { hostedModelPolicy, HOSTED_MODEL_POLICY_HEADER } from "./hosted-models.t
import { CLOUD_HOME_SECRET_KEYS, CLOUD_IGNORED_KEYS, cloudHomeConfiguration, cloudHomeOffersPlace, cloudHomePlaceRefusal, firstCloudTurnPatch } from "./cloud-home.ts";
import { botBox, startBotBoxAtBoot } from "./bot-box/boot.ts"; import { attachmentsForBox } from "./box-attachments.ts"; import { brokerPath } from "./bot-box/broker-probe.ts";
import { createCloudSignedHost } from "./host/cloud-signed-host.ts"; import { createBotNameClash } from "./host/bot-name-clash.ts"; import { hiddenThreadRefusal, hideOthersSyncFolders } from "./host/team-private.ts"; import { createTeamMemberLeft } from "./host/team-member-left.ts"; import { createUploadOwners, uploadsFor } from "./host/member-uploads.ts"; import { createMemberOwnBot } from "./host/member-own-bot.ts"; import { createVisibilityHost } from "./host/visibility-host.ts"; import { createBotAccessHost, refusalFor, relayedSendRefusal } from "./host/bot-access-gate.ts"; import { createBotAccessRoutes, writeAccess } from "./routes/bot-access.ts"; import { createAccessRequests } from "./host/access-requests.ts";
-import { createCloudPower, registerCloudPower, wokeFromSleep, type CloudPower } from "./cloud-power.ts"; import { createSharedComputerRoutes } from "./routes/shared-computers.ts";
+import { cloudPowerNow, createCloudPower, registerCloudPower, wokeFromSleep, type CloudPower } from "./cloud-power.ts"; import { createWokeNotifier } from "./cloud-woke.ts"; import { createSharedComputerRoutes } from "./routes/shared-computers.ts";
import { lentCopies, noteSyncBotTurn } from "./routes/cloud-sync.ts"; import { mcpReconnectLine, retryBrokeredMcp } from "./bot-box/broker-mcp.ts";
import { type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts";
import { createCloudMoveRoutes } from "./cloud-move-http.ts";
@@ -689,7 +689,7 @@ const sessions = new SessionRegistry({
},
portalMembership: hostedWorkspaceConfiguration()?.portalMembership === true, recheckMs: 1_000,
}); onConfigSaved(() => sessions.membershipChanged());
-const deviceLinks = new DeviceLinks(); const sharedComputers = new SharedComputers(id => sessions.isLive(id), new LentComputers(join(DATA_DIR, "lent-computers.json")), deviceLinks, lentCopies);
+const deviceLinks = new DeviceLinks(); const sharedComputers = new SharedComputers(id => sessions.isLive(id), new LentComputers(join(DATA_DIR, "lent-computers.json")), deviceLinks, lentCopies); sharedComputers.wokeAt = () => cloudPowerNow()?.sleptUntil() ?? null; let startedFromSleep = false;
// A Cloud home's secrets come over the launcher's pipe, never this process's environment.
const CLOUD_SECRETS = BOOT_CLOUD_SECRETS;
const CLOUD_ENV: NodeJS.ProcessEnv = { ...process.env, ...CLOUD_SECRETS };
@@ -8791,7 +8791,7 @@ routines = new RoutineManager({
limitBackup: (botId, scope) => { const bot = store.bot(botId); return quotaSwitchEnabled() ? Boolean(bot && limitTakeover.backups(botId, bot.modelSelection, scope, approvalModeFor(bot)).length) : Boolean(bot && startupBackups(bot, cfg.automaticRecovery).length); },
launchId: DESKTOP_MANAGED && /^[\w-]{1,100}$/.test(process.env.OMB_DESKTOP_LAUNCH_ID ?? "")
? process.env.OMB_DESKTOP_LAUNCH_ID : undefined,
- skipStartupRuns: Boolean(CLOUD_HOME) && wokeFromSleep(DATA_DIR), // a Cloud home waking from a sleep it was stopped for
+ skipStartupRuns: (startedFromSleep = Boolean(CLOUD_HOME) && wokeFromSleep(DATA_DIR)), // a Cloud home waking from a sleep it was stopped for
hasPendingDelegations: runtimeWorkPending, refusedHandoff: refusedHandoffs.take, handedOffWorkLive: (threadId) => coordinator.outstandingFor(threadId).length > 0,
routineTurn: (threadId) => directRequestOwners.get(threadId)?.automation !== undefined,
botState: unattendedDispatchState,
@@ -13205,7 +13205,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
}
// Off: a 404 like a route that never existed. On: a turn sees only the computers of the person it provably acts for.
if (method === "GET" && path === "/api/internal/shared-computers" && botLending()) {
- const principal = sharedComputerPrincipal(internalCapability);
+ const principal = sharedComputerPrincipal(internalCapability); await sharedComputers.settledAfterWake(principal, () => internalCapabilityIsActive(internalCapability));
// `say` too: the bot says why instead of asking the person to open OpenMausBot, which can't help while the computer is lent already.
const why = CLOUD_HOME && !principal && (CLOUD_TEAM || sharedComputers.status(CLOUD_HOME_LENDER).length > 0) ? cloudLendingRefusalNotice(internalCapability) : null;
return json(res, 200, { computers: sharedComputers.list(principal), ...sharedComputers.away(principal), ...sharedComputers.screenNotLent(principal), ...(why ? { unavailable: cloudLendingRefusalForBot(internalCapability), say: why } : {}) });
@@ -15490,7 +15490,7 @@ restoreChannelMessages();
if (movedAutoPins) console.log(`Works on: moved ${movedAutoPins} auto-pinned thread(s) to their bot's current Works on`);
}
-if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATA_DIR, broadcast: (payload) => broadcast(payload), log: (line) => console.warn(line), probes: {
+if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATA_DIR, broadcast: (payload) => broadcast(payload), log: (line) => console.warn(line), bootedFromSleep: startedFromSleep, onWoke: createWokeNotifier({ adminOrigin: CLOUD_HOME.adminOrigin, machineId: CLOUD_HOME.machineId, secret: CLOUD_HOME.bootstrapSecret, log: (line) => console.warn(line) }), probes: {
turn: () => store.bots.some((bot) => botHasActiveTurn(bot.id)) || store.groups.some(groupIsWorking), run: () => Boolean(routines?.hasActiveRuns()), handoff: () => coordinator.pace() === "busy",
liveCall: () => liveCalls.current() !== null, computer: () => cloudComputerPower.awake() || boatLifecycleBusyBots.size > 0, nextDueAt: () => { const due = [routines?.nextDueAt() ?? null, proactive.brief.nextWakeAt(), botWaits.nextWakeAt()].filter((at): at is number => at !== null); return due.length ? Math.min(...due) : null; },
maintenance: () => workspaceMaintenance.active || providerFleetReloading || providerAuthSessions.active || browserEngineInstall !== null } }));
diff --git a/server/lent-computers.test.ts b/server/lent-computers.test.ts
index eb033595b0..1c6969b99f 100644
--- a/server/lent-computers.test.ts
+++ b/server/lent-computers.test.ts
@@ -56,6 +56,103 @@ describe("what a server remembers about computers lent to it", () => {
});
});
+describe("a Cloud that just woke waits for the computers lent to it", () => {
+ const owner = { session: "s1", person: "cloud-home" };
+ const woken = (lent = new LentComputers(file())) => {
+ const broker = new SharedComputers(() => true, lent);
+ return { broker, lent };
+ };
+
+ it("a computer it hasn't heard from since it slept: the call waits for it, past the 60 s that used to fail it", async () => {
+ vi.useFakeTimers();
+ const { broker } = woken();
+ const computer = lend();
+ broker.register(computer, owner, secret);
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
+ const woke = Date.now() - 5_000;
+ broker.wokeAt = () => woke;
+ const waiting = broker.request({ computer_id: computer.id, action: "computer_tools" }, owner.person, () => true);
+ await vi.advanceTimersByTimeAsync(40_000);
+ broker.register(computer, owner, secret);
+ await vi.advanceTimersByTimeAsync(250);
+ const job = await broker.poll(computer.id, owner.session, secret);
+ broker.complete(computer.id, owner.session, secret, job!.id, "back");
+ await expect(waiting).resolves.toBe("back");
+ broker.close();
+ });
+
+ it("a computer known only from before a real boot is waited for too, and named once the wait ends", async () => {
+ vi.useFakeTimers();
+ const lent = new LentComputers(file());
+ const computer = lend({ name: "HOME-PC", platform: "win32" });
+ lent.connected("cloud-home", { id: computer.id, name: "HOME-PC", platform: "win32", folders: 1, terminal: false, screen: true });
+ const broker = new SharedComputers(() => true, lent);
+ const woke = Date.now();
+ broker.wokeAt = () => woke;
+ let settled = false;
+ const waiting = broker.request({ computer_id: computer.id, action: "computer_tools" }, "cloud-home", () => true).catch(error => { settled = true; throw error; });
+ await vi.advanceTimersByTimeAsync(80_000);
+ expect(settled).toBe(false);
+ const named = expect(waiting).rejects.toThrow(/HOME-PC is offline/);
+ await vi.advanceTimersByTimeAsync(11_000);
+ await named;
+ broker.close();
+ });
+
+ it("not after the wait, not for one that stopped lending, and not for a stopped turn", async () => {
+ vi.useFakeTimers();
+ const lent = new LentComputers(file());
+ const computer = lend();
+ lent.connected("cloud-home", { id: computer.id, name: "ASH-PC", folders: 1, terminal: false, screen: true });
+ const broker = new SharedComputers(() => true, lent);
+ const longAgo = Date.now() - 91_000;
+ broker.wokeAt = () => longAgo;
+ await expect(broker.request({ computer_id: computer.id, action: "computer_tools" }, "cloud-home", () => true)).rejects.toThrow(/offline/);
+ const justNow = Date.now();
+ broker.wokeAt = () => justNow;
+ lent.stopped("cloud-home", computer.id);
+ await expect(broker.request({ computer_id: computer.id, action: "computer_tools" }, "cloud-home", () => true)).rejects.toThrow(/no longer lent/);
+ broker.close();
+ const other = new LentComputers(file());
+ other.connected("cloud-home", { id: computer.id, name: "ASH-PC", folders: 1, terminal: false, screen: true });
+ const away = new SharedComputers(() => true, other);
+ away.wokeAt = () => justNow;
+ let live = true;
+ const stopped = expect(away.request({ computer_id: computer.id, action: "computer_tools" }, "cloud-home", () => live)).rejects.toThrow(/offline/);
+ live = false;
+ await vi.advanceTimersByTimeAsync(500);
+ await stopped;
+ away.close();
+ });
+
+ it("a bot's look at its computers holds until one of them is back, or the wait ends; nothing lent means no wait", async () => {
+ vi.useFakeTimers();
+ const lent = new LentComputers(file());
+ const computer = lend();
+ lent.connected("cloud-home", { id: computer.id, name: "ASH-PC", folders: 1, terminal: false, screen: true });
+ const broker = new SharedComputers(() => true, lent);
+ const woke = Date.now();
+ broker.wokeAt = () => woke;
+ let done = false;
+ const settled = broker.settledAfterWake("cloud-home", () => true).then(() => { done = true; });
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(done).toBe(false);
+ broker.register(computer, owner, secret);
+ await vi.advanceTimersByTimeAsync(500);
+ await settled;
+ expect(broker.list("cloud-home")).toHaveLength(1);
+ broker.close();
+
+ const none = new SharedComputers(() => true, new LentComputers(file()));
+ none.wokeAt = () => woke;
+ await none.settledAfterWake("cloud-home", () => true);
+ none.close();
+ const off = new SharedComputers(() => true, new LentComputers(file()));
+ await off.settledAfterWake("cloud-home", () => true);
+ off.close();
+ });
+});
+
describe("the shared-computer registry with that memory", () => {
it("takes a platform from a new desktop, still takes an old desktop's registration, and gives bots the device word", () => {
const pc = lend({ platform: "win32" });
diff --git a/server/shared-computers.ts b/server/shared-computers.ts
index b410f42bae..e4aa624b0f 100644
--- a/server/shared-computers.ts
+++ b/server/shared-computers.ts
@@ -81,6 +81,9 @@ const DELIVERY_MS = 10_000;
/** How long a request waits for a computer seen this recently to finish reconnecting. */
const RECONNECTING_MS = 60_000;
const RECONNECT_WAIT_MS = 15_000;
+/** Longer than a desktop takes to notice a wake (the Admin's power read, then its own 15 s session read, about 75 s at
+ * worst): while a Cloud sleeps its desktops stop calling, so a computer lent to it is not offline, just not back yet. */
+const WAKE_WAIT_MS = 90_000;
const OFFLINE = "This shared computer is offline. Keep its desktop app open; do not substitute files on the server.";
const RESTARTING = "This server is restarting. Lending resumes by itself once it is back.";
const lentButOffline = (name: string, seen: number, device: "PC" | "Mac" | "computer" = "computer") => `${name} is lent but has been offline for ${Math.max(1, Math.round((Date.now() - seen) / 60_000))} min: OpenMausBot on it is closed, the ${device} is asleep or locked, or its desktop app is signed out of MausBot Cloud. Tell the person in one sentence to open OpenMausBot on that ${device}; do not substitute files on the server.`;
@@ -155,6 +158,8 @@ export class SharedComputers {
private copies: Pick<LentCopies, "away" | "answer"> | undefined;
/** A computer connected, changed what it lends, or stopped. */
changed: () => void = () => {};
+ /** When this server last woke from sleep; null when it never slept (off a Cloud home, or a plain restart). */
+ wokeAt: () => number | null = () => null;
/** On the person's own Cloud, the bots' tool that asks them to turn on what their computer doesn't give now. */
askTool: string | null = null;
constructor(sessionLive: (id: string) => boolean, lent?: LentComputers, links?: Pick<DeviceLinks, "drop">, copies?: Pick<LentCopies, "away" | "answer">) {
@@ -197,6 +202,14 @@ export class SharedComputers {
if (entry.jobs.size === 0 && (!this.sessionLive(entry.owner.session) || Date.now() - entry.seen > RETAIN_MS)) { this.computers.delete(key); this.links?.drop(key); }
}
}
+ private wakeLeft() {
+ const at = this.wokeAt();
+ return at === null ? 0 : Math.max(0, at + WAKE_WAIT_MS - Date.now());
+ }
+ /** A computer lent here and not stopped, which a server that just woke should wait for: known even after a boot that lost the live list. */
+ private lentAndExpected(principal: string, id: string) {
+ return this.lent?.list(principal).some(record => record.id === id && record.stoppedAt === null) ?? false;
+ }
private online(entry: Computer) { return this.sessionLive(entry.owner.session) && Date.now() - entry.seen < 40_000; }
/** The desktop takes a 401 or 403 for a lost sign-in and signs in again, so a stopping server answers 503. */
private authorize(id: string, session: string, secret: string) {
@@ -365,7 +378,9 @@ export class SharedComputers {
for (const deadline = Date.now() + RECONNECT_WAIT_MS; ;) {
const known = lent();
if (known && this.online(known)) break;
- if (!known || Date.now() - known.seen > RECONNECTING_MS || Date.now() >= deadline || !active()) {
+ const reconnecting = known !== undefined && Date.now() - known.seen <= RECONNECTING_MS && Date.now() < deadline;
+ const waking = this.wakeLeft() > 0 && (known ? this.sessionLive(known.owner.session) : this.lentAndExpected(principal, operation.computer_id));
+ if ((!reconnecting && !waking) || !active()) {
// Away: its lent folders answer from their copy here, a write to one lent with editing waits for it.
const copy = active() ? this.copies?.answer(operation, principal, this.list(principal)) : null;
if (copy) return copy;
@@ -400,6 +415,13 @@ export class SharedComputers {
entry.jobs.set(id, job); entry.wake?.();
});
}
+ /** A server that just woke holds a bot's look at its computers until one of this person's lent ones is back, or the wait ends. */
+ async settledAfterWake(principal: string | null, active: () => boolean): Promise<void> {
+ if (!principal) return;
+ while (this.wakeLeft() > 0 && active() && this.list(principal).length === 0 && (this.lent?.list(principal) ?? []).some(record => record.stoppedAt === null)) {
+ await new Promise(resolve => setTimeout(resolve, 250));
+ }
+ }
/** Names the computer and its kind when it is known, so a bot says "your PC" to a Windows user, never "your Mac". */
private offline(principal: string, id: string): string {
const known = this.lent?.list(principal).find(computer => computer.id === id);