Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
A hand-off starts at once on a Cloud that just woke
milind-soniff09137879bc
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex b5e0c20c86..410b534fc4 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1582,6 +1582,11 @@ measured 0.72 s) or, when Fly can't suspend it, stops it (about 20 s to wake).The home never stops itself. On every plan that doesn't sleep the Admin nevercalls these routes, and nothing below changes how a home behaves.+Waking a suspended machine moves the wall clock on, and its pending timers keep+the awake time they had left (measured on Fly: a 120 s timer suspended for 4+minutes at 30 s fired 120 s of awake time after boot, not at resume). So never+judge a pending timer by a wall-clock time stored when it was set.+**What idle means (`server/cloud-power.ts`).** All of:- no turn running (bots, rooms, delegated work), no routine run queued to startdiff --git a/docs/verification/chat-turns.md b/docs/verification/chat-turns.mdindex eca6e34401..860d6fee99 100644--- a/docs/verification/chat-turns.md+++ b/docs/verification/chat-turns.md@@ -289,3 +289,4 @@ engines. What stays one at a time, and what the person sees:to the waiter. The holder's next call is refused once, so nothing lands on a page it did not open.- One computer: a turn takes it at its first screen call, not when it starts, and keeps it until it ends.- Memory on a Linux Cloud: a turn that would run the machine out says "Waiting for memory" and starts by itself.+- A Cloud that just woke: a hand-off starts at once. `OMB_TEST_RESUME_CLOCK=1` lets a fixture move `Date.now()` on as a wake does, by writing milliseconds to `<data dir>/resume-clock-ms`; `server/handoff-wake.e2e.test.ts` uses it.diff --git a/scripts/control-omb.ts b/scripts/control-omb.tsindex d8c2b7488e..70914a989a 100644--- a/scripts/control-omb.ts+++ b/scripts/control-omb.ts@@ -215,6 +215,8 @@ export function verificationServerEnvironment(parentEnv: NodeJS.ProcessEnv, dataif (parentEnv.OMB_TEST_APPROVAL_CLOCK === "1") childEnv.OMB_TEST_APPROVAL_CLOCK = "1";// The stall watchdog fires on a marker file, not after 20 minutes of silence.if (parentEnv.OMB_TEST_STALL_CLOCK === "1") childEnv.OMB_TEST_STALL_CLOCK = "1";+ // Date.now() jumps when a marker file says so, as it does when a suspended machine wakes; timers don't.+ if (parentEnv.OMB_TEST_RESUME_CLOCK === "1") childEnv.OMB_TEST_RESUME_CLOCK = "1";// The first-reply rescue's delay in ms, so a check need not sit through 20 s of silence.if (/^\d{1,6}$/.test(parentEnv.OMB_FIRST_REPLY_NOTICE_MS ?? "")) childEnv.OMB_FIRST_REPLY_NOTICE_MS = parentEnv.OMB_FIRST_REPLY_NOTICE_MS;// How long a tool call may hold the person's message unread, in ms, so a check need not sit through a minute.@@ -247,6 +249,7 @@ export function verificationServerArgs(childEnv: NodeJS.ProcessEnv): string[] {...(childEnv.OMB_TEST_DESKTOP_OWNER_TOKEN || childEnv.OMB_TEST_DESKTOP_CUA_CONNECTION ? hook("desktop-parent.mjs") : []),...(childEnv.OMB_TEST_APPROVAL_CLOCK === "1" ? hook("approval-clock-hooks.mjs") : []),...(childEnv.OMB_TEST_STALL_CLOCK === "1" ? hook("stall-clock-hooks.mjs") : []),+ ...(childEnv.OMB_TEST_RESUME_CLOCK === "1" ? hook("resume-clock-hooks.mjs") : []),join(ROOT, "server", "index.ts"),];}diff --git a/server/due-timer.test.ts b/server/due-timer.test.tsindex 713b338fcc..6a48cd3919 100644--- a/server/due-timer.test.ts+++ b/server/due-timer.test.ts@@ -61,6 +61,20 @@ describe("startDueTimer", () => {timer.stop();});+ it("runs work due now on a poke after a wake, though the clock has passed the timer the sleep left behind", async () => {+ const run = vi.fn();+ let due = Date.now() + 30_000;+ const timer = startDueTimer({ run, next: () => due });+ await vi.advanceTimersByTimeAsync(0);+ expect(run).toHaveBeenCalledTimes(1);+ vi.setSystemTime(Date.now() + 9 * 60 * 60_000);+ due = Date.now();+ timer.poke();+ await vi.advanceTimersByTimeAsync(0);+ expect(run).toHaveBeenCalledTimes(2);+ timer.stop();+ });+it("retries work still due after a run (waiting on something outside) every retryMs, not in a tight loop", async () => {const run = vi.fn();const timer = startDueTimer({ run, next: () => Date.now() - 1, retryMs: 5_000 });diff --git a/server/due-timer.ts b/server/due-timer.tsindex 9a489e6331..881b887ac8 100644--- a/server/due-timer.ts+++ b/server/due-timer.ts@@ -68,7 +68,8 @@ export function startDueTimer(options: DueTimerOptions): DueTimer {if (stopped) return;if (running) { pokedWhileRunning = true; return; }const wait = dueIn();- if (wait !== null && wait <= DUE_CLOCK_MS && now() + wait < firesAt) arm(wait);+ // Past on the wall clock with the timer still pending: a wake moved the clock on and left the timer with its awake time to run.+ if (wait !== null && wait <= DUE_CLOCK_MS && (now() + wait < firesAt || firesAt < now())) arm(wait);};const fire = () => {disarm();diff --git a/server/handoff-ticks.test.ts b/server/handoff-ticks.test.tsindex b59e075820..c54762fbef 100644--- a/server/handoff-ticks.test.ts+++ b/server/handoff-ticks.test.ts@@ -47,6 +47,20 @@ describe("hand-off ticks", () => {expect(tick).toHaveBeenCalledTimes(3);});+ it("ticks at once on a write after a wake, though the clock has passed the timer the sleep left behind", async () => {+ const tick = vi.fn();+ const ticks = createHandoffTicks();+ ticks.start({ tick, pace: () => "idle" });+ await vi.advanceTimersByTimeAsync(HANDOFF_TICK_MS.busy);+ expect(tick).toHaveBeenCalledTimes(1);+ // A suspended machine's clock jumps when it wakes, and its timers carry on from where they stopped: this one still has an hour to go.+ vi.setSystemTime(Date.now() + 9 * 60 * 60_000);+ ticks.kick();+ await vi.advanceTimersByTimeAsync(0);+ expect(tick).toHaveBeenCalledTimes(2);+ ticks.stop();+ });+it("keeps ticking after a tick throws", async () => {const errors = vi.spyOn(console, "error").mockImplementation(() => {});const tick = vi.fn(() => { throw new Error("boom"); });diff --git a/server/handoff-ticks.ts b/server/handoff-ticks.tsindex 976b6a6ad9..1b1350cf0e 100644--- a/server/handoff-ticks.ts+++ b/server/handoff-ticks.ts@@ -14,18 +14,20 @@ export interface HandoffTicks {export function createHandoffTicks(): HandoffTicks {let options: { tick(): void; pace(): HandoffPace } | null = null;let timer: ReturnType<typeof setTimeout> | null = null;- let firesAt = Infinity;+ /** The timer fires within one busy tick. Not worked out from the clock: waking a suspended machine moves the clock on, and its+ * pending timers keep the awake time they had left (measured on Fly, Node 22). */+ let near = false;let ticking = false;const arm = (delay: number) => {if (timer) clearTimeout(timer);- firesAt = Date.now() + delay;+ near = delay <= HANDOFF_TICK_MS.busy;timer = setTimeout(fire, delay);timer.unref();};const fire = () => {timer = null;- firesAt = Infinity;+ near = false;if (!options) return;ticking = true;let pace: HandoffPace = "busy";@@ -42,7 +44,7 @@ export function createHandoffTicks(): HandoffTicks {return {kick() {- if (!options || ticking || firesAt - Date.now() <= HANDOFF_TICK_MS.busy) return;+ if (!options || ticking || near) return;arm(0);},start(next) {@@ -53,7 +55,7 @@ export function createHandoffTicks(): HandoffTicks {options = null;if (timer) clearTimeout(timer);timer = null;- firesAt = Infinity;+ near = false;},};}diff --git a/server/handoff-wake.e2e.test.ts b/server/handoff-wake.e2e.test.tsnew file mode 100644index 0000000000..9dd9c9e318--- /dev/null+++ b/server/handoff-wake.e2e.test.ts@@ -0,0 +1,42 @@+// A hand-off sent after a suspended Cloud wakes. Only the hand-off tick starts a queued hand-off; a person's own line needs no tick.+import { writeFileSync } from "node:fs";+import { join } from "node:path";+import { DatabaseSync } from "node:sqlite";+import { expect, it } from "vitest";+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";+import { request } from "../scripts/mcp-server.ts";+import { HANDOFF_TICK_MS } from "./handoff-ticks.ts";+import { readHandoffs } from "./testing/handoff-rows.ts";++const HOUR = 60 * 60_000;++it("starts a hand-off at once on a Cloud that just woke, with a dozen teammates about", async () => {+ const session = await launchVerificationServer({ ...process.env, OMB_TEST_RESUME_CLOCK: "1" }, undefined, undefined, undefined, undefined, { scripted: true });+ const cli = (...args: string[]) => runControlOmb(args, { env: { OPENMAUSBOT_URL: session.info.url } }) as Promise<any>;+ const api = (path: string, body: unknown, method: string) => request(path, { method, body: JSON.stringify(body) }, session.info.url) as Promise<any>;+ try {+ const bots = [];+ for (let at = 0; at < 13; at += 1) bots.push((await cli("new-bot", "--name", `Teammate ${at}`, "--section", "Team")).bot);+ const [chief, teammate] = bots;+ await api(`/api/bots/${chief.id}`, { chiefOfStaff: true, managedSections: ["Team"], acknowledgePeerScope: true }, "PATCH");+ writeFileSync(join(session.info.dataDir, "room-plan.json"), JSON.stringify({+ [chief.id]: { steps: [{ arguments: { bot_ids: [teammate.id], message: "Fetch the setting" } }], reply: "Asked", resumeReply: "Have it" },+ [teammate.id]: { reply: "Here it is" },+ }));+ // Nothing is due, so the tick has settled on its slowest pace.+ await new Promise((resolve) => setTimeout(resolve, 2 * HANDOFF_TICK_MS.busy + 3_000));+ // The machine was suspended overnight and has just woken.+ writeFileSync(join(session.info.dataDir, "resume-clock-ms"), String(9 * HOUR));+ await new Promise((resolve) => setTimeout(resolve, 200));++ await cli("send", "--bot", chief.id, "--task", chief.activeTaskId, "--text", "Please ask your teammate for the setting.");+ await expect.poll(() => readHandoffs(session.info.dataDir).find((node: any) => node.parentId)?.status, { timeout: 15_000 }).toBeDefined();+ await expect.poll(() => readHandoffs(session.info.dataDir).find((node: any) => node.parentId)?.status, { timeout: 15_000 }).toBe("completed");+ const handoff = readHandoffs(session.info.dataDir).find((node: any) => node.parentId)!;+ const db = new DatabaseSync(join(session.info.dataDir, "runtime.db"), { readOnly: true });+ try {+ const kinds = (db.prepare("SELECT kind FROM assignment_events WHERE assignment_id = ? ORDER BY id").all(handoff.id) as Array<{ kind: string }>).map((row) => row.kind);+ expect(kinds.slice(0, 3)).toEqual(["enqueued", "admitted", "started"]);+ } finally { db.close(); }+ } finally { await session.close(); }+}, 90_000);diff --git a/server/testing/resume-clock-hooks.mjs b/server/testing/resume-clock-hooks.mjsnew file mode 100644index 0000000000..7b5b67fbcb--- /dev/null+++ b/server/testing/resume-clock-hooks.mjs@@ -0,0 +1,16 @@+// Loaded with --import in isolated fixtures when OMB_TEST_RESUME_CLOCK=1: writing a number of milliseconds to+// <data dir>/resume-clock-ms moves Date.now() on by that much, as waking a suspended machine does. Timers carry on from+// where they were, as they do across a suspend (server/due-timer.ts).+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+const dataDir = process.env.OMB_DATA_DIR;+if (!dataDir || dataDir !== process.env.HOME || process.env.OMB_TEST_RESUME_CLOCK !== '1') {+ throw new Error('The resume clock requires an explicitly isolated fixture');+}+const marker = join(dataDir, 'resume-clock-ms');+const realNow = Date.now.bind(Date);+let skew = 0;+Date.now = () => realNow() + skew;+setInterval(() => {+ try { skew = Number(readFileSync(marker, 'utf8')) || 0; } catch { /* not resumed yet */ }+}, 20).unref();