Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
bot link: a hand-off may wake a sleeping Cloud and its result is not held by a stale "asleep"
milind-soni3f60e683a101
diff --git a/electron/bot-link-main.mjs b/electron/bot-link-main.mjsindex 295691f84e..1f183d4f5d 100644--- a/electron/bot-link-main.mjs+++ b/electron/bot-link-main.mjs@@ -9,6 +9,8 @@// A Cloud that sleeps is never started for the link's sake: pairing is a background request made only while the Admin// says the Cloud is awake (or the person has just turned the switch on), a refusal is not asked again for hours, and// main passes the Admin's word on to this computer's server every minute so its end sleeps and wakes with the Cloud.+// "Asleep" goes with the time main first heard it, so that end can tell the Admin's lagging word from the Cloud's own+// answers since (server/bot-link/dial.ts).//// Security: only My Cloud is ever paired (the address the person's account names), never a server saved by hand or a// team's Cloud. The link's sign-in goes from My Cloud to this computer's server and nowhere else; no page sees it.@@ -35,7 +37,7 @@ async function body(response) {* pref: { read(): unknown },* localRequest(route: string, init?: RequestInit): Promise<Response>,* fetch: typeof fetch,- * cloud(): { origin: string | null, account: string | null, asleep: boolean, signedOut?: boolean },+ * cloud(): { origin: string | null, account: string | null, asleep: boolean, since?: string | number | null, signedOut?: boolean },* cloudName(): string,* changed?(): void,* log?(line: string): void,@@ -43,8 +45,8 @@ async function body(response) {* now?(): number,* }} deps `wanted()`: the switch is on and both places exist. `pref`: the switch's own file: turning it off ends a* link (My Cloud not being seen for a moment leaves it alone, and so does a file that cannot be read). `cloud()`: My- * Cloud's address and the signed-in account while the person has them, whether the Admin says it sleeps now, and- * whether the person signed out. `cloudName()`: what the app calls My Cloud, in the person's language. `changed()`: the+ * Cloud's address and the signed-in account while the person has them, whether the Admin says it sleeps now (and+ * since when, in its words: a new `since` is a new word), and whether the person signed out. `cloudName()`: what the app calls My Cloud, in the person's language. `changed()`: the* addresses `address` gives changed (the link came, went, or is another Cloud's now).*/export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImpl, cloud, cloudName, changed = () => {}, log = () => {}, watchMs = WATCH_MS, now = Date.now }) {@@ -104,6 +106,15 @@ export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImplconst switchedOff = () => { try { return !parseTogether(pref.read()); } catch (error) { return error?.code === "ENOENT"; } };let retryAt = -Infinity, switchWasOn = null, looking = null, idle = false;+ /** The Admin's "asleep" and when main first heard it, on this computer's clock: heard again when the Admin's `since`+ * moves on or it said awake in between. */+ let heard = null;+ const hearing = (mine) => {+ if (!mine.asleep) { heard = null; return null; }+ const key = String(mine.since ?? "");+ if (!heard || heard.key !== key) heard = { key, at: now() };+ return heard.at;+ };async function tryPair(force) {if (!force && now() < retryAt) return;let paired;@@ -114,6 +125,7 @@ export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImpl}async function reconcile() {idle = false;+ const heardAt = hearing(cloud());const state = await local("GET").catch(() => null);if (!state) return;if (state.on) await thisComputer().catch(() => null);@@ -142,7 +154,7 @@ export function createBotLinkMain({ wanted, pref, localRequest, fetch: fetchImplif (!mine.origin) return;if (state.needsPairing) { if (!mine.asleep) await tryPair(false); return; }// The Admin's word, passed on for this link's own Cloud only, for as long as this computer's end disagrees with it.- if (mine.asleep && !state.asleep) await local("PUT", { cloud: "asleep", origin: mine.origin });+ if (mine.asleep && !state.asleep) await local("PUT", { cloud: "asleep", origin: mine.origin, ...(heardAt === null ? {} : { heardAt }) });else if (!mine.asleep && state.asleep) await local("PUT", { cloud: "awake", origin: mine.origin });}/** Brings the link in line with the switch, the account and the Cloud: now, when any of them changes, and every minute. */diff --git a/electron/bot-link-main.node-test.mjs b/electron/bot-link-main.node-test.mjsindex 315d35f80b..7c71de6697 100644--- a/electron/bot-link-main.node-test.mjs+++ b/electron/bot-link-main.node-test.mjs@@ -30,7 +30,7 @@ function harness({ origin = CLOUD, pairStatus = 200, on = false, putFails = falsif (init.method === "DELETE") return answer(200, { ok: true });return pairStatus === 200 ? answer(200, { token: "link-sign-in-0123456789", place: { id: "cloud-1", name: "My Cloud" } }) : answer(pairStatus, { error: "no" });},- cloud: () => ({ origin: the.origin, account: the.account, asleep: the.asleep, signedOut: the.signedOut }),+ cloud: () => ({ origin: the.origin, account: the.account, asleep: the.asleep, since: the.since ?? null, signedOut: the.signedOut }),cloudName: () => "My Cloud",watchMs,changed: () => { the.changes = (the.changes ?? 0) + 1; },@@ -199,7 +199,7 @@ test("the Admin's word on sleep goes to this computer's server for its own Cloudawait h.link.look();h.the.asleep = true;await h.link.look();- assert.deepEqual(h.localCalls.at(-1), { method: "PUT", body: { cloud: "asleep", origin: CLOUD } });+ assert.deepEqual(h.localCalls.at(-1), { method: "PUT", body: { cloud: "asleep", origin: CLOUD, heardAt: 1_000_000 } });const puts = h.localCalls.filter((call) => call.method === "PUT").length;await h.link.look();assert.equal(h.localCalls.filter((call) => call.method === "PUT").length, puts);@@ -225,3 +225,28 @@ test("the Admin's word on sleep goes to this computer's server for its own Cloudawait ended.link.look();assert.deepEqual(ended.localCalls.filter((call) => call.method === "PUT"), [{ method: "PUT", body: { cloud: "awake", origin: CLOUD } }]);});++test("\"asleep\" goes with when main first heard it: the same word keeps its time, a new one (a new since, or awake between) gets a new time", async (t) => {+ const h = harness({ on: true });+ t.after(() => h.link.close());+ await h.link.look();+ const sleeps = () => h.localCalls.filter((call) => call.method === "PUT" && call.body.cloud === "asleep").map((call) => call.body.heardAt);+ h.the.asleep = true; h.the.since = "2026-11-24T10:00:00Z";+ await h.link.look();+ // This computer's end did not park (the Cloud answered work since): main says it again each minute, with the same time.+ h.server = { ...h.server, asleep: false };+ h.the.clock += 60_000;+ await h.link.look();+ assert.deepEqual(sleeps(), [1_000_000, 1_000_000]);+ h.the.since = "2026-11-24T10:05:00Z";+ h.the.clock += 60_000;+ h.server = { ...h.server, asleep: false };+ await h.link.look();+ h.the.asleep = false;+ await h.link.look();+ h.the.asleep = true;+ h.the.clock += 60_000;+ h.server = { ...h.server, asleep: false };+ await h.link.look();+ assert.deepEqual(sleeps(), [1_000_000, 1_000_000, 1_120_000, 1_180_000]);+});diff --git a/electron/main.mjs b/electron/main.mjsindex 7075920e16..e073af9059 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -2578,7 +2578,7 @@ const cloudLook = createCloudLook({ store: lookFile(() => path.join(app.getPath(const cloudBuy = installCloudBuy({ ipcMain, guard: localWorkspaceOnly, client: ensureCloudAccount, offersReady: cloudOffersReady, clipboard, look: cloudLook });const localServerRequest = (route, init = {}) => (serverProc && serverReady ? fetch(`http://127.0.0.1:${SERVER_PORT}${route}`, { ...init, redirect: "error", credentials: "omit", headers: { ...init.headers, [DESKTOP_MUTATION_HEADER]: desktopMutationToken } }) : Promise.reject(new Error("not running"))); launchRecord.deliverWith((part) => localServerRequest("/api/diagnostics/launch", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(part), signal: AbortSignal.timeout(5_000) }).then((res) => res.json()));const teamProfileSeeds = createTeamProfileSeeds({ teamFetch: (...args) => session.defaultSession.fetch(...args), localRequest: localServerRequest, log: slog });-const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, pageOrigin: activePageOrigin, confirmMove: confirmTeamMove, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1, chooses: true, t: nativeT }); ownHome = installOwnHome({ t: nativeT, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); botLink = createBotLinkMain({ wanted: () => placesTogether.on(), pref: jsonFile(path.join(app.getPath("userData"), PLACES_TOGETHER_FILE)), localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep(), signedOut: cloudAccount?.state().status === "signed-out" }), cloudName: () => nativeT("cloudSetup.myCloud"), changed: () => placesTogether.linkChanged(), log: slog }); twoPlaces = installTwoPlacesMain({ t: nativeT, ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });+const oneHome = installOneHome({ ipcMain, clean: cleanWorkspace, cloudPage: cloudPageAsking, pageOrigin: activePageOrigin, confirmMove: confirmTeamMove, server: () => serverProc, cookieFetch: (...args) => session.defaultSession.fetch(...args), home: () => (myCloud() && cloudAccount ? { origin: myCloud(), grant: () => cloudAccount.pairHome() } : null), power: cloudPower, file: () => path.join(app.getPath("userData"), "cloud-send.json"), localRequest: localServerRequest, space: { disk: () => cloudPlanDisk(ensureCloudAccount().state()), grow: sizeGb => ensureCloudAccount().growDisk(sizeGb) }, reconnect: origin => signInCloudSession({ origin, mine: myCloud(), pair: () => ensureCloudAccount().pairHome(), fetch: (...args) => session.defaultSession.fetch(...args) }), window: () => (desktopRemoteAccess ? null : mainWindow), localOrigin: rendererOrigin, account: () => cloudAccount, journalFile: () => path.join(app.getPath("userData"), "one-home.json"), tempRoot: () => path.join(app.getPath("temp"), "openmaus-one-home"), lend: projects => sharingController().lendProjects(projects), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: () => void showHome({ place: "cloud" }), openTeam: team => void showHome({ place: { team: team.id, name: team.name } }), openLocal: () => void showHome(), restart: () => relaunchAfterDesktopRemoteChange(), version: app.getVersion(), log: slog, other: () => ownHome, accountsHere: () => accountRing()?.count() ?? 1, chooses: true, t: nativeT }); ownHome = installOwnHome({ t: nativeT, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, handoff: what => oneHome.handoff(what), cloudJournal: () => oneHome.journal(), journal: jsonFile(path.join(app.getPath("userData"), "own-home.json")), choice: jsonFile(path.join(app.getPath("userData"), "own-home-choice.json")), sendState: jsonFile(path.join(app.getPath("userData"), "own-home-send.json")), lend: (projects, place) => sharingController().lendProjects(projects, place), phone: { paired: () => companionStartsAtLaunch({ remoteClient: Boolean(desktopRemoteAccess), serverReady }), start: () => startDesktopCompanion({ waitForHosted: false, remember: false }).then(() => {}) }, openHome: place => void workspaceMenuAction(() => switchEnvironment(place.id)), lastInput: oneHome.lastInput, version: app.getVersion(), log: slog, onChange: () => { oneHome.publish(); computerSharing?.cloudChanged(); railChanged(); } }); botLink = createBotLinkMain({ wanted: () => placesTogether.on(), pref: jsonFile(path.join(app.getPath("userData"), PLACES_TOGETHER_FILE)), localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), cloud: () => ({ origin: myCloud(), account: cloudAccount?.state().account?.id ?? null, asleep: cloudPower.asleep(), since: cloudAccount?.power()?.since ?? null, signedOut: cloudAccount?.state().status === "signed-out" }), cloudName: () => nativeT("cloudSetup.myCloud"), changed: () => placesTogether.linkChanged(), log: slog }); twoPlaces = installTwoPlacesMain({ t: nativeT, ipcMain, guard: localWorkspaceOnly, localRequest: localServerRequest, fetch: (...args) => session.defaultSession.fetch(...args), environments: () => environmentsState.environments, cloud: () => ({ origin: myCloud(), asleep: cloudPower.asleep() }), oneHome, ownHome, dismissed: jsonFile(path.join(app.getPath("userData"), "two-places.json")), account: () => cloudAccount, teamsRemembered: jsonFile(path.join(app.getPath("userData"), "team-places.json")), log: slog, tell: () => { if (mainWindow && !mainWindow.isDestroyed() && senderIsLocal({ sender: mainWindow.webContents })) mainWindow.webContents.send("two-places:changed"); } });// Teams from the verified session as places this window shows (home-places.mjs): the one to open next time, and its lines.const homePlaces = createHomePlaces({ store: jsonFile(path.join(app.getPath("userData"), "home-place.json")), environments: () => environmentsState, persist: persistEnvironments, makeId: randomUUID, homeOrigin: myCloud, homeName: name => cloudLook.homeName(name), synced: state => teamLinks.changed(state), log: slog });const homeWindow = createHomeWindow({ clean: cleanWorkspace, journal: oneHome.journal, frozen: oneHome.marker, account: () => (app.isPackaged && !desktopRemoteAccess ? cloudAccount : null), restored: cloudAccountRestored,diff --git a/server/bot-link/dial.test.ts b/server/bot-link/dial.test.tsindex f6e273c7e3..8b141a69a6 100644--- a/server/bot-link/dial.test.ts+++ b/server/bot-link/dial.test.ts@@ -46,6 +46,7 @@ function linkAt(origin: string) {setLevel: vi.fn(),setSleeps: vi.fn(),sleeps: () => false,+ setWaking: vi.fn(),setTransfer: vi.fn(),onOutgoing: (listener: () => void) => { outgoing = listener; return () => { outgoing = () => {}; }; },onWanted: () => () => {},@@ -202,3 +203,149 @@ describe("bot-link exchange lifetime", () => {expect(payload).toMatchObject({ fresh: false, wait: 0, frames: [{ t: "cancel", id: "cancelled-work" }] });});});++/** A Cloud that answers each exchange as `answer` says, and holds an idle poll open until it is hung up. */+async function sleepyCloud(answer: (request: { background: boolean; wait: number }) => "ok" | "asleep" | "hold" = ({ wait }) => (wait > 0 ? "hold" : "ok")) {+ const seen: Array<{ background: boolean; wait: number }> = [];+ const listeners = new Set<() => void>();+ const origin = await cloud((request, response) => {+ const chunks: Buffer[] = [];+ request.on("data", (chunk: Buffer) => chunks.push(chunk));+ request.on("end", () => {+ const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as { wait: number };+ const one = { background: request.headers["x-omb-background"] === "1", wait: body.wait };+ seen.push(one);+ for (const listener of listeners) listener();+ const said = answer(one);+ if (said === "asleep") { response.writeHead(503, { "content-type": "application/json", "x-omb-cloud-power": "asleep" }); response.end(JSON.stringify({ error: "asleep" })); }+ else if (said === "ok") { response.writeHead(200, { "content-type": "application/json" }); response.end(JSON.stringify({ session: "session-1", frames: [] })); }+ });+ });+ const requests = (count: number) => new Promise<void>((resolve) => {+ const check = () => { if (seen.length >= count) { listeners.delete(check); resolve(); } };+ listeners.add(check);+ check();+ });+ return { origin, seen, requests };+}++/** A computer's link whose Cloud sleeps: work can be wanted, and what the dialer says of waking is kept. */+function sleepyLink(origin: string) {+ let wanted: () => void = () => {};+ const waking: boolean[] = [];+ const link = {+ dial: () => ({ origin, token: "fixture-link-token" }),+ cloudPeer: () => "cloud-peer",+ sessionStarted: vi.fn(),+ outgoing: vi.fn(() => []),+ hasOutgoing: () => false,+ receive: vi.fn(),+ setOnline: vi.fn(),+ setLevel: vi.fn(),+ setSleeps: vi.fn(),+ sleeps: () => true,+ setWaking: (_peer: string, on: boolean) => { waking.push(on); },+ setTransfer: vi.fn(),+ onOutgoing: () => () => {},+ onWanted: (listener: () => void) => { wanted = listener; return () => { wanted = () => {}; }; },+ ended: () => [],+ forgetEnded: vi.fn(),+ };+ return { link: link as unknown as BotLink, observed: link, want: () => wanted(), waking };+}++const settle = () => new Promise((resolve) => setTimeout(resolve, 150));++describe("a Cloud that sleeps", () => {+ it("parked, nothing is asked of it: not by time, not by directory news", async () => {+ const sleepy = await sleepyCloud();+ const { link } = sleepyLink(sleepy.origin);+ const dialer = createDialer({ link, holdMs: 200, firstRetryMs: 1 });+ cleanups.push(() => dialer.close());+ dialer.start({ gentle: true });+ await settle();+ expect(dialer.state()).toMatchObject({ running: true, asleep: true });+ expect(sleepy.seen).toEqual([]);+ });++ it("work a person waits on wakes it with an exchange that is not background; the idle polls after it are background again", async () => {+ const sleepy = await sleepyCloud();+ const { link, observed, want, waking } = sleepyLink(sleepy.origin);+ const dialer = createDialer({ link, holdMs: 5_000 });+ cleanups.push(() => dialer.close());+ dialer.start({ gentle: true });+ want();+ expect(waking).toEqual([true]);+ await sleepy.requests(2);+ expect(sleepy.seen).toEqual([{ background: false, wait: 0 }, { background: true, wait: 5_000 }]);+ expect(observed.setOnline).toHaveBeenCalledWith("cloud-peer", true);+ });++ it("a Cloud that answers even that exchange with asleep parks the link once, with no second ask", async () => {+ const sleepy = await sleepyCloud(() => "asleep");+ const { link, want, waking } = sleepyLink(sleepy.origin);+ const dialer = createDialer({ link, firstRetryMs: 1 });+ cleanups.push(() => dialer.close());+ dialer.start({ gentle: true });+ want();+ await sleepy.requests(1);+ await settle();+ expect(sleepy.seen).toEqual([{ background: false, wait: 0 }]);+ expect(dialer.state()).toMatchObject({ asleep: true });+ expect(waking).toEqual([true, false]);+ });++ it("the app's asleep heard before the Cloud last answered work parks nothing; one heard after it does", async () => {+ let clock = 10_000;+ const sleepy = await sleepyCloud();+ const { link, want } = sleepyLink(sleepy.origin);+ const transport = observeFetch();+ const dialer = createDialer({ link, fetch: transport.fetch, holdMs: 5_000, now: () => clock });+ cleanups.push(() => dialer.close());+ dialer.start({ gentle: true });+ want();+ await sleepy.requests(2);+ clock = 20_000;+ dialer.sleep(5_000);+ dialer.sleep(10_000);+ expect(dialer.state()).toMatchObject({ asleep: false });+ expect(transport.signals[1]!.aborted).toBe(false);+ dialer.sleep(10_001);+ expect(dialer.state()).toMatchObject({ asleep: true });+ expect(transport.signals[1]!.aborted).toBe(true);+ // Parked by the newer word: the old one is no longer stale, and a word without a time parks as before.+ dialer.start();+ await sleepy.requests(3);+ dialer.sleep(5_000);+ expect(dialer.state()).toMatchObject({ asleep: true });+ });++ it("while work is waking it, the app's asleep parks nothing, whenever it was heard", async () => {+ const sleepy = await sleepyCloud(() => "hold");+ const { link, want } = sleepyLink(sleepy.origin);+ const transport = observeFetch();+ const dialer = createDialer({ link, fetch: transport.fetch });+ cleanups.push(() => dialer.close());+ dialer.start({ gentle: true });+ want();+ await sleepy.requests(1);+ dialer.sleep(Date.now() + 60_000);+ dialer.sleep();+ expect(dialer.state()).toMatchObject({ asleep: false });+ expect(transport.signals[0]!.aborted).toBe(false);+ });++ it("an idle poll answered while the app says asleep proves nothing: the word parks it", async () => {+ let clock = 10_000;+ const sleepy = await sleepyCloud();+ const { link } = sleepyLink(sleepy.origin);+ const dialer = createDialer({ link, holdMs: 5_000, now: () => clock });+ cleanups.push(() => dialer.close());+ dialer.start();+ await sleepy.requests(2);+ expect(sleepy.seen.every((one) => one.background)).toBe(true);+ clock = 20_000;+ dialer.sleep(1);+ expect(dialer.state()).toMatchObject({ asleep: true });+ });+});diff --git a/server/bot-link/dial.ts b/server/bot-link/dial.tsindex 32be23eb1c..03813174db 100644--- a/server/bot-link/dial.ts+++ b/server/bot-link/dial.ts@@ -6,6 +6,12 @@// the other has not acknowledged. The Cloud's answer that it sleeps stops the asking until this computer has work for it// or the app says the Cloud is awake (`start`), since any request would start a sleeping Cloud; the app looks every// minute and never asks the Cloud itself to find out.+//+// Work a person waits on (a hand-off, a room turn: `onWanted`) may wake a sleeping Cloud: the exchanges that follow are+// not marked background until one is answered, so the Cloud counts them as use and answers them even if it has not yet+// noticed it was woken. Everything else (directory news, idle polls) stays background and is never sent while parked,+// so it never wakes the Cloud or keeps it awake. An answer to such an exchange is the Cloud's own word that it is awake:+// the app's "asleep" heard before it is stale and parks nothing; only one heard after it does.import { createWriteStream, openAsBlob, rmSync } from "node:fs";import { stat } from "node:fs/promises";import { Readable, Transform } from "node:stream";@@ -30,10 +36,15 @@ export interface DialerOptions {firstRetryMs?: number;/** What this computer says its version reads; a test stands in for an older app with it. */level?: number;+ now?: () => number;}-export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, holdMs = HOLD_MS, firstRetryMs = FIRST_RETRY_MS, level = PROTOCOL_LEVEL }: DialerOptions) {+export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, holdMs = HOLD_MS, firstRetryMs = FIRST_RETRY_MS, level = PROTOCOL_LEVEL, now = Date.now }: DialerOptions) {let running = false, stopped = true, asleep = false, needsPairing = false;+ /** `wake`: work a person waits on wants the Cloud, so exchanges are not background until one is answered. `provedAt`:+ * when the Cloud last answered such an exchange (its own word that it is awake); `staleSaid`: the app's last "asleep"+ * that was older, so it is logged once. */+ let wake = false, provedAt = -Infinity, staleSaid: number | undefined | null = null;let session = "", ack = 0, fresh = true, retryMs = firstRetryMs;let active: AbortController | null = null, held: AbortController | null = null;let wakeUp: (() => void) | null = null;@@ -93,7 +104,19 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, h};link.setTransfer(transfer);const stopListening = link.onOutgoing(() => { held?.abort(); });- const stopWanted = link.onWanted(() => { if (stopped) return; asleep = false; retryMs = firstRetryMs; wakeUp?.(); });+ const stopWanted = link.onWanted(() => {+ if (stopped) return;+ const peer = link.cloudPeer();+ if (asleep && peer && !needsPairing && link.dial()) link.setWaking(peer, true);+ asleep = false; wake = true; retryMs = firstRetryMs;+ wakeUp?.();+ });+ /** The Cloud answered that it sleeps, or the app's word parks the link: nothing asks it until work or the app wakes it. */+ const park = (peer: string | null) => {+ asleep = true; fresh = true; wake = false; provedAt = -Infinity;+ link.setSleeps(true);+ if (peer) { link.setWaking(peer, false); link.setOnline(peer, false); }+ };async function exchange(target: { origin: string; token: string }, peer: string): Promise<void> {if (fresh) link.sessionStarted(peer);@@ -104,19 +127,18 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, htimeout.unref?.();const wait = sending.length > 0 || fresh ? 0 : holdMs;if (wait > 0) held = controller;+ const foreground = wake || carriesWork(sending);try {const response = await fetchImpl(`${target.origin}${SYNC_PATH}`, {method: "POST", redirect: "error", cache: "no-store", signal: controller.signal,headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${target.token}`, origin: target.origin, [LEVEL_HEADER]: String(level),- ...(carriesWork(sending) ? {} : { [BACKGROUND_HEADER]: "1" }) },+ ...(foreground ? {} : { [BACKGROUND_HEADER]: "1" }) },body: JSON.stringify({ fresh, ack, frames: sending.map((entry) => entry.frame), wait }),});controller.signal.throwIfAborted();if (response.status === 503 && response.headers.get(POWER_HEADER) === "asleep") {await response.body?.cancel();- asleep = true; fresh = true;- link.setSleeps(true);- link.setOnline(peer, false);+ park(peer);return;}if (response.status === 401 || response.status === 403) {@@ -130,6 +152,7 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, hcontroller.signal.throwIfAborted();const answer = syncAnswer.safeParse(data);if (!answer.success) throw new Error("the Cloud's answer did not parse");+ if (foreground) { provedAt = now(); wake = false; }link.outgoing(peer, sending.at(-1)?.seq ?? 0);if (answer.data.session !== session) {const restarted = session !== "";@@ -163,7 +186,8 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, htry { await exchange(target, peer); } catch (error) {if (stopped) break;link.setOnline(peer, false);- fresh = true;+ // The Cloud no longer answers, so its last answer proves nothing about now: the app's word governs again.+ fresh = true; provedAt = -Infinity;if (!asleep) log(`bot link: the Cloud could not be reached (${error instanceof Error ? error.message : String(error)}); trying again in ${Math.round(retryMs / 1000)} s`);await pause(retryMs * (0.75 + Math.random() / 2));retryMs = Math.min(retryMs * 2, MAX_RETRY_MS);@@ -192,12 +216,24 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, hwakeUp?.();void loop();},- /** The app says the Cloud sleeps now: nothing asks it until there is work for it or it is awake again. */- sleep(): void { if (!stopped) { link.setSleeps(true); asleep = true; fresh = true; const peer = link.cloudPeer(); if (peer) link.setOnline(peer, false); active?.abort(); } },+ /** The app says the Cloud sleeps now: nothing asks it until there is work for it or it is awake again. `heardAt`: when+ * the app first heard that word (this computer's clock). It parks nothing while work a person waits on is waking the+ * Cloud, or when the Cloud has answered such work since: the Admin's word lags the Cloud's own. */+ sleep(heardAt?: number): void {+ if (stopped) return;+ if (wake || (heardAt !== undefined && heardAt <= provedAt)) {+ if (staleSaid !== heardAt) log(`bot link: the app says the Cloud sleeps, but it has answered since${wake ? " (waking it for work)" : ""}; the link stays up`);+ staleSaid = heardAt;+ return;+ }+ park(link.cloudPeer());+ active?.abort();+ },/** Stops asking. `bye`: the link was turned off here, so the Cloud is told once, unless it sleeps. True when it knows. */async stop({ bye: tell = false }: { bye?: boolean } = {}): Promise<boolean> {- const target = link.dial(), sleeping = asleep;- stopped = true;+ const target = link.dial(), sleeping = asleep, peer = link.cloudPeer();+ stopped = true; wake = false;+ if (peer) link.setWaking(peer, false);active?.abort();wakeUp?.();return tell && target !== null && !sleeping ? bye(target) : false;diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.tsindex 409f67fce8..99e8bb6383 100644--- a/server/bot-link/link.test.ts+++ b/server/bot-link/link.test.ts@@ -20,6 +20,7 @@ import { createBotLink, SPOOL_KEEP_MS, type BotLink } from "./link.ts";import { createBotLinkRoutes as routesOf, linkSessionRefusal } from "../routes/bot-link.ts";import { createLinkedRooms, type LinkedRooms } from "../host/bot-link-rooms.ts";import { createRoomTranscript } from "../host/room-transcript.ts";+import { CLOUD_IDLE_AWAKE_MS, createCloudPower, type CloudPower } from "../cloud-power.ts";import { EXCHANGE_BYTES, LINK_EXPIRES_MS, PAIR_PATH, STATE_PATH, SYNC_PATH, linkedId, peerKey, type Frame } from "./protocol.ts";/** How a place addresses a bot of another: by that place's key and the bot's id there. */@@ -90,6 +91,10 @@ function place(label: string, bots: Bot[], version?: number) {};let coordinator!: Coordinator, link!: BotLink, dialer!: ReturnType<typeof createDialer>, ticker: NodeJS.Timeout | undefined, http: Server | undefined;let openedCount = 0, port = 0, generation = 0, skew = 0, minted = 0, directoryChanges = 0;+ /** A Cloud home's power (cloud-power.ts), as its server consults it before each route; none unless a test sets one. */+ let power: CloudPower | null = null;+ /** Each exchange this place answered: whether it came marked background. */+ const syncs: Array<{ background: boolean }> = [];const sockets = new Set<import("node:net").Socket>();function boot(options: { limits?: { queueMs?: number; stallMs?: number } } = {}) {@@ -137,7 +142,7 @@ function place(label: string, bots: Bot[], version?: number) {async function listen(at = 0): Promise<string> {const routes = routesOf({- link, dialer, environmentId: `${label}-environment`, seenMs: 900, power: () => null, ...(version ? { level: version } : {}),+ link, dialer, environmentId: `${label}-environment`, seenMs: 900, power: () => power, ...(version ? { level: version } : {}),local: (who) => who.kind === "loopback", owner: (who) => who.kind === "session" && who.session.id === "owner-session",issue: () => { const token = `link-token-${++minted}-0123456789`; issued.set(token, `link-session-${minted}`); return { token, sessionId: issued.get(token)! }; },revoke: (sessionId) => { for (const [token, id] of issued) if (id === sessionId) issued.delete(token); },@@ -146,9 +151,14 @@ function place(label: string, bots: Bot[], version?: number) {http = createServer((req, res) => {const url = new URL(req.url ?? "/", "http://127.0.0.1");requests.push(`${req.method} ${url.pathname}${url.searchParams.has("probe") ? "?probe" : ""}`);+ if (url.pathname === SYNC_PATH) syncs.push({ background: req.headers["x-omb-background"] === "1" });+ // As server/index.ts does: every request is seen first, and a signed-in one is someone using the home unless it is background.+ const who = auth(req);+ power?.arrived(url.pathname, req.headers);+ if (power && who.kind === "session") power.request(url.pathname, req.headers, res);const fails = failing.findIndex((one) => one.match.test(requests.at(-1)!));if (fails >= 0) { const status = failing.splice(fails, 1)[0]!.status; req.resume(); json(res, status, { error: "try again" }); return; }- void routes({ req, res, url, path: url.pathname, method: req.method ?? "GET", auth: auth(req), json: json as never, readBody: readBody as never })+ void routes({ req, res, url, path: url.pathname, method: req.method ?? "GET", auth: who, json: json as never, readBody: readBody as never }).catch((error) => { if (!res.headersSent) json(res, (error as { status?: number }).status ?? 500, { error: String(error) }); });});http.on("connection", (socket) => { sockets.add(socket); socket.on("close", () => sockets.delete(socket)); });@@ -165,6 +175,7 @@ function place(label: string, bots: Bot[], version?: number) {async function shutdown() {if (ticker) clearInterval(ticker);dialer.close();+ power?.close();await unplug();link.close();try { coordinator.close(); } catch { /* already closed */ }@@ -208,6 +219,7 @@ function place(label: string, bots: Bot[], version?: number) {},said: (groupId: string) => (words.get(groups.find((one) => one.id === groupId)!.threadId) ?? []).map((line) => (line.kind === "text" ? `${line.from?.name ?? "Sam"}: ${line.text}` : `(${line.tool?.name})`)),get link() { return link; }, get dialer() { return dialer; }, get coordinator() { return coordinator; }, get port() { return port; },+ syncs, usePower(next: CloudPower) { power = next; },engine(next: Run) { run = next; },/** Time passes for this place's link. */later(ms: number) { skew += ms; },@@ -1216,3 +1228,76 @@ describe("the link between a computer and its Cloud", () => {expect(linkSessionRefusal({ userId: "portal:abc" }, "GET", "/api/bots")).toBeNull();});});++describe("a Cloud that sleeps", () => {+ /** The Cloud home's power on a clock of the test's own, with nothing running there. */+ function sleepyHome(cloud: ReturnType<typeof place>) {+ let clock = 1_800_000_000_000;+ const power = createCloudPower({ dataDir: cloud.dir, now: () => clock, broadcast: () => {}, probes: {+ turn: () => false, run: () => false, handoff: () => false, liveCall: () => false, computer: () => false, maintenance: () => false, nextDueAt: () => null } });+ cloud.usePower(power);+ /** Time passes in the home's 5-second ticks; a single larger step (`jump`) is a suspend it may not notice. */+ const pass = (ms: number) => { for (let left = ms; left > 0; left -= 5_000) { clock += Math.min(5_000, left); power.tick(); } };+ return { power, pass, jump: (ms: number) => { clock += ms; } };+ }+ /** The home agrees to sleep, and the computer's end hears it on its next exchange and from the app. */+ async function asleep(computer: ReturnType<typeof place>, cloudOrigin: string, home: ReturnType<typeof sleepyHome>) {+ home.pass(CLOUD_IDLE_AWAKE_MS + 60_000);+ expect(home.power.prepareSleep()).toMatchObject({ ok: true });+ await until(() => computer.dialer.state().asleep && !computer.link.online(), "the computer's end parks");+ expect((await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: cloudOrigin, heardAt: Date.now() })).body).toMatchObject({ asleep: true });+ }++ it("suspended too briefly for the home to notice: the hand-off's own exchange wakes it, is answered, and the result comes back", async () => {+ const { computer, cloud, cloudOrigin } = await two();+ const home = sleepyHome(cloud);+ await asleep(computer, cloudOrigin, home);+ const before = cloud.syncs.length;+ // The machine was suspended and is started again by the hand-off's request: 12 s, under the home's resume mark.+ home.jump(12_000);+ const { receipts } = await computer.handOff("local-writer", call(["Analyst"], "Count the orders"));+ expect(receipts[0]!.detail).toContain("My Cloud was asleep and is waking up for this now");+ expect(receipts[0]!.detail).toContain("tell the person My Cloud is waking up for it");+ expect(receipts[0]!.detail).not.toContain("offline");+ await until(() => computer.results.length === 1, "the result comes back");+ expect(computer.results[0]!.result).toBe("cloud-analyst did: Count the orders");+ expect(cloud.syncs[before]).toEqual({ background: false });+ expect(home.power.sleeping()).toBe(false);+ });++ it("the app still says asleep after the Cloud answered work: the result is not held, and only a newer asleep parks the link", async () => {+ const { computer, cloud, cloudOrigin } = await two();+ // The person woke the Cloud themselves; the Admin's word has not caught up.+ const heard = Date.now();+ expect((await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: cloudOrigin, heardAt: heard })).body).toMatchObject({ asleep: true, online: false });+ let release!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ cloud.engine(async (node) => { await gate; return { ok: true, text: `${node.botId} did: ${node.text}` }; });+ const { receipts } = await computer.handOff("local-writer", call(["Analyst"], "Count the orders"));+ expect(receipts[0]!.detail).toContain("waking up for this now");+ expect(computer.link.agents().find((bot) => bot.name === "Analyst")!.statusText).toContain("waking up now");+ await until(() => cloud.runs.length === 1, "the work starts on the Cloud");+ // Main says it again each minute while this computer's end disagrees: the same old word parks nothing.+ expect((await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: cloudOrigin, heardAt: heard })).body).toMatchObject({ asleep: false, online: true });+ release();+ await until(() => computer.results.length === 1, "the result comes back while the app still says asleep");+ expect((await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: cloudOrigin, heardAt: Date.now() + 60_000 })).body).toMatchObject({ asleep: true, online: false });+ });++ it("background link traffic never wakes a sleeping Cloud or keeps one awake", async () => {+ const { computer, cloud, cloudOrigin } = await two();+ const home = sleepyHome(cloud);+ const from = cloud.syncs.length;+ await until(() => cloud.syncs.length >= from + 2, "two idle exchanges");+ expect(cloud.syncs.slice(from).every((one) => one.background)).toBe(true);+ expect(home.power.report().lastActivityAt).toBeNull();+ await asleep(computer, cloudOrigin, home);+ const asked = cloud.requests.length;+ computer.bots.push({ id: "late-bot", name: "Late" });+ computer.link.botsChanged();+ await new Promise((resolve) => setTimeout(resolve, 1_000));+ expect(cloud.requests.length).toBe(asked);+ expect(home.power.sleeping()).toBe(true);+ expect(computer.link.agents().find((bot) => bot.name === "Analyst")!.statusText).toContain("offline now");+ });+});diff --git a/server/bot-link/link.ts b/server/bot-link/link.tsindex fab19416dd..187da3f48b 100644--- a/server/bot-link/link.ts+++ b/server/bot-link/link.ts@@ -204,6 +204,8 @@ export function createBotLink(deps: BotLinkDeps) {const save = () => { if (state) writeFileAtomic(file, JSON.stringify(state), { mode: 0o600 }); };const linkOf = (peer: string): Live => { let one = live.get(peer); if (!one) { one = { online: false, seq: 0, outbox: [], level: 1 }; live.set(peer, one); } return one; };const isOnline = (peer: string) => live.get(peer)?.online === true;+ /** Places asleep that this computer is waking for work a person waits on (the dialer says so; never persisted). */+ const waking = new Set<string>();const placeName = (peer: string) => state?.peers[peer]?.place.name ?? "the other place";const directory = (): LinkedBot[] => deps.bots().filter((bot) => !bot.hidden && !bot.movedTo && /^[\w-]{1,128}$/u.test(bot.id)).map((bot) => ({id: bot.id, name: bot.name, ...(bot.title ? { title: bot.title.slice(0, 200) } : {}), ...(bot.description ? { description: bot.description.slice(0, 400) } : {}),@@ -301,6 +303,7 @@ export function createBotLink(deps: BotLinkDeps) {function setOnline(peer: string, next: boolean): void {const peerState = state?.peers[peer];if (!peerState) return;+ if (next) waking.delete(peer);if (next && now() - peerState.seenAt > SEEN_WRITE_MS) { peerState.seenAt = now(); save(); }const one = linkOf(peer);if (one.online === next) return;@@ -328,7 +331,8 @@ export function createBotLink(deps: BotLinkDeps) {return matches.length === 1 ? matches[0] : undefined;}- const offlineNote = (peer: string) => `${placeName(peer)} is offline now (off, asleep or not connected), so this waits and is delivered when it is back`;+ const offlineNote = (peer: string) => waking.has(peer) ? wakingNote(peer) : `${placeName(peer)} is offline now (off, asleep or not connected), so this waits and is delivered when it is back`;+ const wakingNote = (peer: string) => `${placeName(peer)} was asleep and is waking up for this now, so this is delivered as soon as it answers`;function keepAlive(): void {if (pending.size === 0) { if (alive) { clearInterval(alive); alive = undefined; } return; }@@ -617,6 +621,7 @@ export function createBotLink(deps: BotLinkDeps) {if (was.role === "acceptor") for (const known of Object.values(was.peers)) if (known.sessionId) deps.revoke?.(known.sessionId);const peers = [...live.keys()];live.clear();+ waking.clear();for (const retry of retries.values()) clearTimeout(retry.timer);retries.clear();rmSync(spoolRoot, { recursive: true, force: true });@@ -654,11 +659,13 @@ export function createBotLink(deps: BotLinkDeps) {if (!duplicate && call.files?.length) deps.files?.crossed(node.id, "sent", { botId: context.sender.id, name: context.sender.name }, call.files);const files = call.files?.length && !deps.files ? " Its files were not sent: files do not cross to the other place here, so put what it needs in the message." : "";const online = isOnline(remote.peer);+ // Said first, so a computer whose Cloud sleeps has asked it to wake before the bot is told what happens next.+ if (!online) for (const listener of wantedListeners) listener();+ const told = !online && waking.has(remote.peer) ? `Finish your turn and tell the person ${place} is waking up for it.` : `Finish your turn and tell the person it waits for ${place}.`;receipts.push(receipt(remote, duplicate && node.status !== "queued" ? "injected" : "queued",duplicate ? `already sent to ${remote.bot.name} on ${place}: it is ${node.status === "queued" ? "queued" : "under way"} and ${returns}`- : online ? `sent to ${remote.bot.name} on ${place}; ${returns}.${files}` : `${offlineNote(remote.peer)}; ${returns} then. Finish your turn and tell the person it waits for ${place}.${files}`,+ : online ? `sent to ${remote.bot.name} on ${place}; ${returns}.${files}` : `${offlineNote(remote.peer)}; ${returns} then. ${told}${files}`,{ requestId: node.id }));- if (!online) for (const listener of wantedListeners) listener();if (!duplicate) {context.handed(node.id);deps.sentRow({ sender: context.sender, threadId: context.address.threadId, recipient: { id: linked, name: `${remote.bot.name} (${place})` }, workThreadId: threadId, nodeId: node.id, ...(context.address.groupId && !deps.rooms?.member(context.address.groupId, linked) ? { roomId: context.address.groupId } : {}),@@ -768,7 +775,7 @@ export function createBotLink(deps: BotLinkDeps) {linked: () => Object.entries(state?.peers ?? {}).flatMap(([peer, known]) => known.bots.map((bot) => ({ id: linkedId(peer, bot.id), peer, place: known.place, kind: state!.role === "dialer" ? "cloud" as const : "computer" as const, online: isOnline(peer), bot }))),/** Other places' bots as list_bots names them. */agents: () => Object.entries(state?.peers ?? {}).flatMap(([peer, known]) => known.bots.map((bot) => ({ id: linkedId(peer, bot.id), name: bot.name, section: "", model: bot.model ?? "", busy: false,- status: isOnline(peer) ? "linked" : "offline", statusText: isOnline(peer) ? `on ${known.place.name}` : `on ${known.place.name}, offline now: work for it waits until it is back`,+ status: isOnline(peer) ? "linked" : "offline", statusText: isOnline(peer) ? `on ${known.place.name}` : waking.has(peer) ? `on ${known.place.name}, waking up now: work for it is delivered as soon as it answers` : `on ${known.place.name}, offline now: work for it waits until it is back`,title: bot.title || undefined, description: bot.description || undefined }))),/** Turned on, on a computer: it keeps the Cloud's address, its sign-in there and the account that was for. */turnOn(input: { self: Place; origin: string; token: string; account?: string; peer: Place }): void {@@ -879,6 +886,8 @@ export function createBotLink(deps: BotLinkDeps) {/** There is work for a place that is not connected, handed over outside `coordinate` (a room turn). */wanted(): void { for (const listener of wantedListeners) listener(); },onWanted(listener: () => void): () => void { wantedListeners.add(listener); return () => wantedListeners.delete(listener); },+ /** The dialer is waking this place, asleep, for work a person waits on (until it answers or parks again). */+ setWaking(peer: string, on: boolean): void { if (on) waking.add(peer); else waking.delete(peer); },sleeps: () => state?.sleeps === true,setSleeps(sleeps: boolean): void { if (state && state.role === "dialer" && (state.sleeps === true) !== sleeps) { state.sleeps = sleeps; save(); } },close(): void { if (alive) clearInterval(alive); alive = undefined; for (const retry of retries.values()) clearTimeout(retry.timer); retries.clear(); outboundListeners.clear(); wantedListeners.clear(); },diff --git a/server/cloud-power.test.ts b/server/cloud-power.test.tsindex eccb0bf39c..c6abd5a2fa 100644--- a/server/cloud-power.test.ts+++ b/server/cloud-power.test.ts@@ -326,3 +326,21 @@ describe("a hand-off between bots", () => {expect(existsSync(join(h.dataDir, "cloud-sleep.json"))).toBe(true);});});++describe("a suspend too short for the clock to notice", () => {+ it("the request that woke it ends the sleep when it is someone using the home; a background one is still told it sleeps", () => {+ const { power, pass, jump } = home();+ pass(CLOUD_IDLE_AWAKE_MS + 5_000);+ expect(power.prepareSleep()).toMatchObject({ ok: true });+ jump(12_000);+ const res = { once: () => {} };+ const link = "/api/bot-link/sync";+ power.arrived(link, { "x-omb-background": "1" });+ power.request(link, { "x-omb-background": "1" }, res as never);+ expect(power.sleeping()).toBe(true);+ expect(power.report().lastActivityAt).toBeNull();+ power.arrived(link, {});+ power.request(link, {}, res as never);+ expect(power.sleeping()).toBe(false);+ });+});diff --git a/server/routes/bot-link.ts b/server/routes/bot-link.tsindex 8416e751bf..d46c5f994b 100644--- a/server/routes/bot-link.ts+++ b/server/routes/bot-link.ts@@ -29,7 +29,8 @@ const origin = z.string().max(300).regex(/^https?:\/\/[^/\s]+$/u);const switchBody = z.union([z.object({ on: z.literal(true), origin, token: z.string().min(16).max(512), name, cloud: placeSchema, account: z.string().max(200).optional() }).strict(),z.object({ on: z.literal(false) }).strict(),- z.object({ cloud: z.enum(["asleep", "awake"]), origin }).strict(),+ /** `heardAt`: when the app first heard "asleep" (this computer's clock), so a word older than the Cloud's own answers parks nothing. */+ z.object({ cloud: z.enum(["asleep", "awake"]), origin, heardAt: z.number().int().nonnegative().optional() }).strict(),]);const pairBody = z.object({ computer: placeSchema, name }).strict();@@ -116,7 +117,7 @@ export function createBotLinkRoutes(deps: BotLinkRouteDeps): RouteHandler {if (!("on" in body.data)) {// The word is one Cloud's: a link to another Cloud is not told it.if (body.data.cloud === "awake") await dialer.tellEnded(body.data.origin);- if (link.role() === "dialer" && link.dial()?.origin === body.data.origin) { if (body.data.cloud === "asleep") dialer.sleep(); else dialer.start(); }+ if (link.role() === "dialer" && link.dial()?.origin === body.data.origin) { if (body.data.cloud === "asleep") dialer.sleep(body.data.heardAt); else dialer.start(); }return json(res, 200, state());}if (!body.data.on) {