Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Fix four states the app could get stuck in
milind-soni0b2c12707957
diff --git a/electron/environment-switch.mjs b/electron/environment-switch.mjsindex ec67442296..120c02f68c 100644--- a/electron/environment-switch.mjs+++ b/electron/environment-switch.mjs@@ -82,3 +82,24 @@ export async function switchLocalEnvironment({ targetDir, targetId, port = DEFAU}return { ok: true };}++/** After a failed switch left no server child: take the previous folder's lease back when none is held (a rollback+ * can fail between releasing one lease and taking the other), then start the server there. A lease that stays held+ * elsewhere is never forced: after the retries the server stays stopped and the reason is logged. */+export async function reviveAfterFailedSwitch({ previousDir, hasLease, acquireLease, startChild, log, delays = [1_000, 2_000, 4_000], sleep = (ms) => new Promise((done) => setTimeout(done, ms)) }) {+ for (let attempt = 0; ; attempt += 1) {+ try {+ if (!hasLease()) await acquireLease(previousDir);+ if (await startChild(previousDir)) return true;+ log(`could not restart the server on ${previousDir} after the failed environment switch`);+ return false;+ } catch (error) {+ if (attempt >= delays.length) {+ log(`gave up restarting the server on ${previousDir} after the failed environment switch (${error?.message ?? error})`);+ return false;+ }+ log(`restart on ${previousDir} after the failed environment switch failed (${error?.message ?? error}); retrying`);+ await sleep(delays[attempt]);+ }+ }+}diff --git a/electron/environment-switch.node-test.mjs b/electron/environment-switch.node-test.mjsindex ab24be7594..881389f095 100644--- a/electron/environment-switch.node-test.mjs+++ b/electron/environment-switch.node-test.mjs@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { test } from "node:test";import { DataDirLeaseError } from "./data-dir-lease.mjs";-import { switchLocalEnvironment, validateTargetDir } from "./environment-switch.mjs";+import { reviveAfterFailedSwitch, switchLocalEnvironment, validateTargetDir } from "./environment-switch.mjs";function realDir() {const dir = mkdtempSync(join(tmpdir(), "omb-switch-"));@@ -222,3 +222,52 @@ test("stopChild throwing aborts the switch before release or acquire", async (t)await assert.rejects(() => switchLocalEnvironment({ targetDir: dir, targetId: "env-7", deps }), /did not stop/);assert.deepEqual(calls, ["stop"]);});++function reviveDeps({ held = false, acquireFailures = 0, startResult = { pid: 1 } } = {}) {+ const calls = [];+ let lease = held;+ let failures = acquireFailures;+ return {+ calls,+ deps: {+ previousDir: "/data/previous",+ hasLease: () => lease,+ acquireLease: async (dir) => {+ calls.push(`acquire ${dir}`);+ if (failures-- > 0) throw new DataDirLeaseError("held elsewhere");+ lease = true;+ },+ startChild: async (dir) => { calls.push(`start ${dir}`); return startResult; },+ log: () => {},+ sleep: async (ms) => { calls.push(`sleep ${ms}`); },+ },+ };+}++test("revive takes the previous folder's lease back before starting when a rollback left none", async () => {+ const { calls, deps } = reviveDeps();+ assert.equal(await reviveAfterFailedSwitch(deps), true);+ assert.deepEqual(calls, ["acquire /data/previous", "start /data/previous"]);+});++test("revive starts on the previous folder without a new lease when one is still held", async () => {+ const { calls, deps } = reviveDeps({ held: true });+ assert.equal(await reviveAfterFailedSwitch(deps), true);+ assert.deepEqual(calls, ["start /data/previous"]);+});++test("revive retries a lease that is briefly unavailable, then gives up without forcing it", async () => {+ const brief = reviveDeps({ acquireFailures: 2 });+ assert.equal(await reviveAfterFailedSwitch(brief.deps), true);+ assert.deepEqual(brief.calls, ["acquire /data/previous", "sleep 1000", "acquire /data/previous", "sleep 2000", "acquire /data/previous", "start /data/previous"]);+ const held = reviveDeps({ acquireFailures: 99 });+ assert.equal(await reviveAfterFailedSwitch(held.deps), false);+ assert.equal(held.calls.filter((call) => call.startsWith("acquire")).length, 4);+ assert.equal(held.calls.some((call) => call.startsWith("start")), false);+});++test("revive does not retry a start that returned no child", async () => {+ const { calls, deps } = reviveDeps({ held: true, startResult: null });+ assert.equal(await reviveAfterFailedSwitch(deps), false);+ assert.deepEqual(calls, ["start /data/previous"]);+});diff --git a/electron/main.mjs b/electron/main.mjsindex 8bcc0a8b47..dbbbd2c230 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -92,7 +92,7 @@ import { buildApplicationMenu } from "./menu.mjs";import { createComputerSharing, isHomeFolder, validateSharedFolders } from "./computer-sharing.mjs";import { createHostScreenLease } from "./host-screen-lease.mjs";import { acquireDataDirLease } from "./data-dir-lease.mjs";-import { switchLocalEnvironment } from "./environment-switch.mjs";+import { reviveAfterFailedSwitch, switchLocalEnvironment } from "./environment-switch.mjs";import { createManagedDesktopClient, createManagedDesktopRelay, createManagedDesktopStore } from "./managed-desktop.mjs";import { CHECKOUT_SOURCES, cloudMenuSublabel, cloudTarget, createCloudAccountClient as cloudAccountClient, createCloudAccountStore } from "./cloud-account.mjs";import { installCloudPlanIpc } from "./cloud-plan-ipc.mjs";@@ -1659,18 +1659,17 @@ async function switchLocalEnvironmentTo(targetDir, targetId, quiet = false) {slog(`environment switch to ${targetDir} failed (${error?.message ?? error})`);return failedSwitch();} finally {- localSwitchInFlight = false;serverSupervisor.resume();if (!switchSucceeded && (!serverProc || !serverSupervisor.isCurrent(serverProc))) {slog(`environment switch to ${targetDir} left no server child; restarting the active environment`);- try {- const revived = await startServerOn(SERVER_PORT);- if (revived.proc) serverSupervisor.ready(revived.proc);- else slog(`could not restart the server after the failed environment switch`);- } catch (error) {- slog(`restart after failed environment switch threw (${error?.message ?? error})`);- }+ await reviveAfterFailedSwitch({+ previousDir, hasLease: () => Boolean(desktopDataDirLease), log: slog,+ acquireLease: async (dir) => { desktopDataDirLease = acquireDataDirLeaseFor(dir); runningDataDir = dir; },+ startChild: async (dir) => { const revived = await startServerOn(SERVER_PORT, dir); if (revived.proc) serverSupervisor.ready(revived.proc); return revived.proc; },+ });}+ // Held through the revive, so a second switch cannot start while the previous folder is being taken back.+ localSwitchInFlight = false;}}diff --git a/electron/server-supervisor.node-test.mjs b/electron/server-supervisor.node-test.mjsindex b138ec7fdb..c8b6b7b6c1 100644--- a/electron/server-supervisor.node-test.mjs+++ b/electron/server-supervisor.node-test.mjs@@ -7,7 +7,7 @@ import { join } from "node:path";import { createRequire } from "node:module";import test from "node:test";import vm from "node:vm";-import { switchLocalEnvironment } from "./environment-switch.mjs";+import { reviveAfterFailedSwitch, switchLocalEnvironment } from "./environment-switch.mjs";import { createServerSupervisor } from "./server-supervisor.mjs";const require = createRequire(import.meta.url);@@ -203,7 +203,9 @@ test("local switching in main rejects dev mode and overlaps, and adopts the rollconst pause = body.indexOf("serverSupervisor.pause();");assert.ok(busyCheck < flagSet && flagSet < pause, "a rejected switch must not pause the supervisor");const finallyBlock = body.slice(body.lastIndexOf("} finally {"));- assert.match(finallyBlock, /localSwitchInFlight = false;\s*serverSupervisor\.resume\(\);/);+ // The flag stays set through the safety-net revive, so a second switch cannot race it for the previous folder's lease.+ assert.ok(finallyBlock.indexOf("serverSupervisor.resume();") < finallyBlock.indexOf("reviveAfterFailedSwitch("));+ assert.ok(finallyBlock.indexOf("reviveAfterFailedSwitch(") < finallyBlock.indexOf("localSwitchInFlight = false;"));assert.match(source, /function createLocalEnvironment\(name, dataDir\) \{\s*if \(!app\.isPackaged\) return \{ ok: false, error: "dev", state: environmentsState \};/);});@@ -323,11 +325,12 @@ test("a purge of a missing folder still removes the entry (rm runs with force)",assert.deepEqual(plain(rmOptions), [{ recursive: true, force: true }]);});-function switchFixture(t, { startResults = [], releaseLeaseThrows = false, stopUtilityServer = async () => true } = {}) {+function switchFixture(t, { startResults = [], releaseLeaseThrows = false, stopUtilityServer = async () => true, acquireThrowsOn = [] } = {}) {const targetDir = mkdtempSync(join(tmpdir(), "omb-switch-fixture-"));t.after(() => rmSync(targetDir, { recursive: true, force: true }));const forks = [];let forkIndex = 0;+ let acquires = 0;const context = vm.createContext({app: { isPackaged: true },localSwitchInFlight: false,@@ -342,10 +345,14 @@ function switchFixture(t, { startResults = [], releaseLeaseThrows = false, stopUisCurrent: (proc) => proc !== null && proc === context.serverProc,},switchLocalEnvironment,+ reviveAfterFailedSwitch,stopUtilityServer,desktopDataDirLease: { release: () => { if (releaseLeaseThrows) throw new Error("lease release exploded"); } },acquireDataDirLease: () => ({ release: () => {} }),- acquireDataDirLeaseFor: () => ({ release: () => {} }),+ acquireDataDirLeaseFor: (dir) => {+ if (acquireThrowsOn.includes(++acquires)) throw new Error(`lease for ${dir} is held`);+ return { release: () => {} };+ },fs: { promises: { mkdir: async () => {} } },startServerOn: async (...args) => {forks.push(args);@@ -375,10 +382,22 @@ test("a failed switch with no live child reforks the active environment once andconst { context, forks, targetDir } = switchFixture(t, { releaseLeaseThrows: true });const result = await context.switchLocalEnvironmentTo(targetDir, "l1");assert.deepEqual(plain(result), { ok: false, error: "switch-failed" });- assert.deepEqual(plain(forks), [[8799]], "exactly one safety-net re-fork on the active port");+ assert.deepEqual(plain(forks), [[8799, "/Users/me/.openmausbot"]], "exactly one safety-net re-fork, on the active port and folder");assert.equal(context.serverProc?.pid, 4001, "the re-forked child is adopted as ready");});+test("a rollback that could not take the previous folder's lease back is revived by taking it then", async (t) => {+ // The target child never starts; the rollback releases the target lease, then fails to re-acquire the previous one.+ const { context, forks, targetDir } = switchFixture(t, { startResults: [{ proc: null }], acquireThrowsOn: [2] });+ const result = await context.switchLocalEnvironmentTo(targetDir, "l1");+ assert.deepEqual(plain(result), { ok: false, error: "switch-failed" });+ assert.ok(context.desktopDataDirLease, "the previous folder's lease is held again");+ assert.equal(context.runningDataDir, "/Users/me/.openmausbot");+ assert.deepEqual(plain(forks.at(-1)), [8799, "/Users/me/.openmausbot"]);+ assert.equal(context.serverProc?.pid, 4002, "the revived child is adopted as ready");+ assert.equal(context.localSwitchInFlight, false);+});+test("a failed switch whose rollback restored a child does not re-fork", async (t) => {const { context, forks, targetDir } = switchFixture(t, { startResults: [{ proc: null }, { proc: { pid: 55 } }] });const result = await context.switchLocalEnvironmentTo(targetDir, "l1");diff --git a/server/limit-resets.test.ts b/server/limit-resets.test.tsindex a50105a569..eb0661b15e 100644--- a/server/limit-resets.test.ts+++ b/server/limit-resets.test.ts@@ -374,6 +374,33 @@ describe("LimitResetClock and the turns that follow a refusal", () => {expect(instance.blockedUntil("codex"), "a read from after it").toBeNull();});+ it("still ignores a usage read from before the refusal after a restart, including a hold saved without its start", () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-limit-held-at-"));+ try {+ const file = join(dir, "limit-holds.json");+ let now = NOW;+ const codexAccounts = () => [{ id: "codex", name: "Codex", driver: "codex" as const, environment: {} }];+ const boot = () => new LimitResetClock({ accounts: codexAccounts, now: () => now, file });+ boot().noteRefusal("codex", NOW + 23 * HOUR);+ now = NOW + 5 * 60_000;+ const restarted = boot();+ const room = codex([3, NOW + 4 * HOUR], [8, NOW + 5 * 24 * HOUR]);+ restarted.noteUsage({ fetchedAt: iso(NOW - 30_000), providers: [room] });+ expect(restarted.blockedUntil("codex"), "a cached read from before the refusal").toBe(NOW + 23 * HOUR);+ restarted.noteUsage({ fetchedAt: iso(NOW + 30_000), providers: [room] });+ expect(restarted.blockedUntil("codex"), "a read from after it").toBeNull();+ // A file an earlier version wrote names no start: the hold counts from this start.+ writeFileSync(file, JSON.stringify({ codex: { until: NOW + 23 * HOUR, guessed: false } }));+ const legacy = boot();+ legacy.noteUsage({ fetchedAt: iso(NOW + 60_000), providers: [room] });+ expect(legacy.blockedUntil("codex"), "a read from before this start").toBe(NOW + 23 * HOUR);+ legacy.noteUsage({ fetchedAt: iso(now), providers: [room] });+ expect(legacy.blockedUntil("codex")).toBeNull();+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+it("counts a Codex hold from its latest refusal, so a read between two refusals with the same reset does not end it", () => {let now = NOW;const instance = new LimitResetClock({ accounts: () => [{ id: "codex", name: "Codex", driver: "codex" as const, environment: {} }], now: () => now });diff --git a/server/limit-resets.ts b/server/limit-resets.tsindex d2ceef440b..15f5bb21a6 100644--- a/server/limit-resets.ts+++ b/server/limit-resets.ts@@ -181,7 +181,7 @@ export class LimitResetClock {noteRefusal(engine: string | undefined, resetsAt: number | undefined): void {if (!engine || resetsAt === undefined || !Number.isFinite(resetsAt) || resetsAt <= this.now()) return;// Without this refresh, a usage read between two refusals would end the hold.- if (this.refusals.get(engine) === resetsAt && !this.guessed.has(engine)) { this.heldAt.set(engine, this.now()); return; }+ if (this.refusals.get(engine) === resetsAt && !this.guessed.has(engine)) { this.heldAt.set(engine, this.now()); this.saveHolds(); return; }this.hold(engine, resetsAt, false);}@@ -207,6 +207,7 @@ export class LimitResetClock {next.set(limit.engine, limit);if (fetchedAt >= (this.heldAt.get(limit.engine) ?? 0) && codexHoldGone(row, limit, this.refusals.get(limit.engine), this.guessed.has(limit.engine))) {this.refusals.delete(limit.engine);+ this.heldAt.delete(limit.engine);released = true;}}@@ -275,17 +276,20 @@ export class LimitResetClock {let saved: unknown;try { saved = JSON.parse(readFileSync(this.options.file, "utf8")); } catch { return; }if (!saved || typeof saved !== "object" || Array.isArray(saved)) return;- for (const [engine, hold] of Object.entries(saved as Record<string, { until?: unknown; guessed?: unknown } | null>)) {+ for (const [engine, hold] of Object.entries(saved as Record<string, { until?: unknown; guessed?: unknown; heldAt?: unknown } | null>)) {const until = hold?.until;if (typeof until !== "number" || !Number.isFinite(until) || until < this.now() - REFUSAL_GRACE_MS) continue;this.refusals.set(engine, until);if (hold?.guessed === true) this.guessed.add(engine);+ // A file from before heldAt was kept: only a usage read made after this start can end the hold.+ const heldAt = hold?.heldAt;+ this.heldAt.set(engine, typeof heldAt === "number" && Number.isFinite(heldAt) ? heldAt : this.now());}}private saveHolds(): void {if (!this.options.file) return;- const holds = Object.fromEntries([...this.refusals].map(([engine, until]) => [engine, { until, guessed: this.guessed.has(engine) }]));+ const holds = Object.fromEntries([...this.refusals].map(([engine, until]) => [engine, { until, guessed: this.guessed.has(engine), heldAt: this.heldAt.get(engine) ?? this.now() }]));try {writeFileAtomic(this.options.file, JSON.stringify(holds), { mode: 0o600 });} catch (error) {diff --git a/src/state/api.ts b/src/state/api.tsindex 04b5fa9747..4f8a3ade2d 100644--- a/src/state/api.ts+++ b/src/state/api.ts@@ -75,3 +75,15 @@ export function snapshotArrays<T>(answer: T, ...keys: (keyof T)[]): T {for (const key of keys) if (!Array.isArray(answer[key])) throw new Error(`Invalid snapshot: ${String(key)} is not a list`);return answer;}++const RETRY_REQUEST_MS = [2_000, 5_000, 15_000, 30_000];++/** Sends `attempt` again after each failure, waiting longer each time, for as long as `wanted()` holds. */+export function retryRequest(wanted: () => boolean, attempt: () => Promise<unknown>): void {+ const run = (tries: number) => {+ attempt().catch(() => {+ if (wanted()) setTimeout(() => run(tries + 1), RETRY_REQUEST_MS[Math.min(tries, RETRY_REQUEST_MS.length - 1)]);+ });+ };+ run(0);+}diff --git a/src/state/snapshot-navigation.test.ts b/src/state/snapshot-navigation.test.tsindex 55d954ffc4..7328128dba 100644--- a/src/state/snapshot-navigation.test.ts+++ b/src/state/snapshot-navigation.test.ts@@ -151,6 +151,17 @@ describe("navigation while a reconnect snapshot is in flight", () => {expect(shown().messages.map(message => message.id)).toEqual(["fresh-b"]);});+ it("ends a pending switch whose response carries no bot", async () => {+ await resync();+ switchResponse = deferred();+ flushSync(() => dispatch({ type: "switchTask", botId: "bot", threadId: "b" }));+ await applySnapshot();+ expect(shown().switchingTo).toBe("b");+ switchResponse.resolve(json({}));+ await vi.waitFor(() => expect(shown().switchingTo).toBeUndefined());+ expect(shown().threadId).toBe("a");+ });+it("keeps the room thread opened after the request started", async () => {await resync();flushSync(() => dispatch({ type: "switchGroupTask", groupId: "room", threadId: "room-b" }));diff --git a/src/state/store.tsx b/src/state/store.tsxindex 2463ec6001..f86af0fd26 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -1,5 +1,5 @@import { cloudAsleep, onCloudPower } from "../lib/cloud-power";-import { api, ApiError, snapshotArrays } from "./api";+import { api, ApiError, retryRequest, snapshotArrays } from "./api";import {createContext,useCallback,@@ -2223,17 +2223,16 @@ export function StoreProvider({ children }: { children: ReactNode }) {if (bot) rawDispatch({ type: "botPatched", bot: withTaskWrites(bot) });}).catch((error) => {showError(error);- // Keep blocking sends while reconciliation fails or a newer write owns this lane.+ // Keep blocking sends while reconciliation fails (it is asked again) or a newer write owns this lane.if (taskWrites.get(threadId) === pending) {pending.patch = {};- void api(`/api/bots?messages=${MESSAGE_PAGE_SIZE}`).then(({ bots }) => {- if (taskWrites.get(threadId) !== pending) return;- const bot = bots.find((candidate: Bot) => candidate.id === botId);+ retryRequest(() => taskWrites.get(threadId) === pending, () => api(`/api/bots?messages=${MESSAGE_PAGE_SIZE}`).then(({ bots }) => {+ const bot = taskWrites.get(threadId) === pending ? bots.find((candidate: Bot) => candidate.id === botId) : undefined;if (bot) {rawDispatch({ type: "botPatched", bot: withTaskWrites(bot) });taskWrites.delete(threadId);}- }).catch(() => {});+ }));}});};@@ -2833,7 +2832,8 @@ export function StoreProvider({ children }: { children: ReactNode }) {: `/api/bots/${action.botId}/tasks/${action.threadId}${action.whole ? "" : `?messages=${MESSAGE_PAGE_SIZE}`}`, { method: "POST", body: JSON.stringify(action.type === "newTask" ? { projectId: action.projectId, cwd: action.cwd } : {}) })).then((r) => {if (action.type === "newTask") { settle(null); action.onCreated?.(); }- if (!r?.bot || navigation.get(action.botId) !== revision) return;+ if (navigation.get(action.botId) !== revision) return;+ if (!r?.bot) { if (action.type === "switchTask") rawDispatch({ type: "switchTaskFailed", botId: action.botId, threadId: action.threadId }); return; }const selectsAfterCreation = action.type === "newTask" && action.cwd !== undefined;if (selectsAfterCreation && selectionRevision.current !== selectedAtStart) return;dispatch({ type: "taskSwitched", bot: r.bot });diff --git a/src/state/task-write-recovery.test.ts b/src/state/task-write-recovery.test.tsindex 17f26d4662..49e4094107 100644--- a/src/state/task-write-recovery.test.ts+++ b/src/state/task-write-recovery.test.ts@@ -118,6 +118,30 @@ describe("thread setting save recovery", () => {expect(requests.mock.calls.map(([path]) => path)).toEqual(["/api/bots/bot/tasks/thread", SNAPSHOT]);});+ it("asks again after a failed reconciliation, and permits a send once the server answers", async () => {+ let reachable = false;+ const requests = vi.fn<typeof fetch>(async (path) => {+ if (path === SNAPSHOT) return reachable ? response({ bots: [bot] }) : response({ error: "Offline" }, 503);+ if (path === "/api/bots/bot/tasks/thread") return response({ error: "Save failed" }, 500);+ return response({});+ });+ const controls = mount(requests);+ controls.update();+ await flush();+ await vi.advanceTimersByTimeAsync(2_000);+ await flush();+ expect(requests.mock.calls.filter(([path]) => path === SNAPSHOT)).toHaveLength(2);+ reachable = true;+ await vi.advanceTimersByTimeAsync(5_000);+ await flush();+ expect(requests.mock.calls.filter(([path]) => path === SNAPSHOT)).toHaveLength(3);+ controls.send();+ await flush();+ expect(requests).toHaveBeenLastCalledWith("/api/bots/bot/messages", expect.objectContaining({ method: "POST" }));+ await vi.advanceTimersByTimeAsync(60_000);+ expect(requests.mock.calls.filter(([path]) => path === SNAPSHOT), "no more reads once reconciled").toHaveLength(3);+ });+it("does not let an old reconciliation clear a newer write", async () => {const reconcile = deferred();const nextWrite = deferred();