Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Merge #5126: Keep a chat-runtime turn going when one MCP server dies, and give small Clouds time to start them
milind-soni7472b46441f7
diff --cc electron/cua-watch-restart.test.mjsindex 0000000000,b681d7cbc5..ed23fb0875mode 000000,100644..100644--- a/electron/cua-watch-restart.test.mjs+++ b/electron/cua-watch-restart.test.mjs@@@ -1,0 -1,117 +1,127 @@@+ // The Mac driver's watch as cua.mjs wires it: a real start, a socket that stops answering, and a real restart. Nothing here can+ // start the operator's own driver: attachStandalone stops at the app it can't find, and no child process exists to launch.+ import { mkdtempSync, rmSync } from "node:fs";+ import { tmpdir } from "node:os";+ import { join } from "node:path";+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+-const fixture = vi.hoisted(() => ({ home: "", alive: true, hosts: [], failStarts: 0, granted: true }));++const fixture = vi.hoisted(() => ({ home: "", alive: true, dead: new Set(), hosts: [], failStarts: 0, granted: true }));+ vi.mock("electron", () => ({ app: { isPackaged: false, getPath: () => fixture.home }, ipcMain: { handle: () => {} } }));+ vi.mock("@trycua/cua-driver/embedded", () => ({+ EmbeddedCuaDriverHost: class {- constructor() { fixture.hosts.push(this); }++ static withOptions() { return new this(); }++ // Each start answers on its own socket, so one driver can stop answering while the next one works.++ constructor() { fixture.hosts.push(this); this.socket = `/fixture/driver-${fixture.hosts.length}.sock`; }+ async start() {+ if (fixture.failStarts > 0) { fixture.failStarts -= 1; throw new Error("the driver could not start"); }- return { socketPath: "/fixture/driver.sock" };++ return { socketPath: this.socket };+ }++ // Main's exit watch (cua.mjs watchEmbeddedHost): this driver never exits, it only stops answering.++ waitForExit() { return new Promise(() => {}); }+ stop = vi.fn(async () => {});+ uniffiDestroy = vi.fn();+ },+ }));+ vi.mock("@trycua/cua-driver/electron", () => ({+ requestMacOSPermissions: () => ({ accessibility: fixture.granted, screenRecording: fixture.granted }),+ hasRequiredMacOSPermissions: () => fixture.granted,+ }));+ vi.mock("node:fs", async (original) => {+ const fs = await original();+ return { ...fs, default: { ...fs.default, existsSync: (file) => {- if (String(file).endsWith(".sock")) return fixture.alive;++ if (String(file).endsWith(".sock")) return fixture.alive && !fixture.dead.has(String(file));+ if (String(file).includes("CuaDriver.app")) return false;+ return fs.existsSync(file);+ } } };+ });+ vi.mock("node:net", async (original) => {+ const net = await original();+ const { EventEmitter } = await import("node:events");+ return { ...net, default: { ...net.default, createConnection: () => {+ const socket = Object.assign(new EventEmitter(), { destroy: vi.fn() });+ queueMicrotask(() => socket.emit("connect"));+ return socket;+ } } };+ });+ vi.mock("./cua-watch.mjs", async (original) => {+ const actual = await original();- return { ...actual, DEAD_DRIVER_RETRY_MS: [5, 5], watchDriver: (options) => actual.watchDriver({ ...options, everyMs: 5, log: () => {} }) };++ return { ...actual, watchDriver: (options) => actual.watchDriver({ ...options, everyMs: 5, log: () => {} }) };++});++// The helper's own bounded restarts (three tries), quickly.++vi.mock("./cua-restart.mjs", async (original) => {++ const actual = await original();++ return { ...actual, createHelperRestarts: (options) => actual.createHelperRestarts({ ...options, waitsMs: [5, 5, 5], log: () => {} }) };+ });++ let cua;+ beforeEach(async () => {- Object.assign(fixture, { home: mkdtempSync(join(tmpdir(), "omb-cua-watch-")), alive: true, hosts: [], failStarts: 0, granted: true });++ Object.assign(fixture, { home: mkdtempSync(join(tmpdir(), "omb-cua-watch-")), alive: true, dead: new Set(), hosts: [], failStarts: 0, granted: true });+ vi.stubEnv("OPENMAUSBOT_CUA_EMBEDDED", "1");+ vi.stubEnv("CUA_DRIVER_PATH", "/fixture/cua-driver");+ vi.resetModules();+ cua = await import("./cua.mjs");+ });+ afterEach(async () => {+ await cua?.stopCua();+ vi.unstubAllEnvs();+ rmSync(fixture.home, { recursive: true, force: true });+ });+ const pause = (ms = 60) => new Promise((resolve) => setTimeout(resolve, ms));++ describe.skipIf(process.platform !== "darwin")("the Mac driver dies after it started", () => {+ it("leaves a driver that answers alone", async () => {+ await cua.startCua();+ await pause();+ expect(fixture.hosts).toHaveLength(1);+ });++ it("starts it again, and watches the new one", async () => {+ await expect(cua.startCua()).resolves.toMatchObject({ mode: "embedded" });- fixture.alive = false;- await expect.poll(() => fixture.hosts.length).toBeGreaterThanOrEqual(2);++ fixture.dead.add(fixture.hosts[0].socket);++ await expect.poll(() => fixture.hosts.length).toBe(2);+ expect(fixture.hosts[0].stop).toHaveBeenCalledOnce();- fixture.alive = true;- const settled = fixture.hosts.length;+ await pause();- expect(fixture.hosts).toHaveLength(settled);- fixture.alive = false;- await expect.poll(() => fixture.hosts.length).toBeGreaterThan(settled);++ expect(fixture.hosts).toHaveLength(2);++ fixture.dead.add(fixture.hosts[1].socket);++ await expect.poll(() => fixture.hosts.length).toBe(3);++ await pause();++ expect(fixture.hosts).toHaveLength(3);+ });++ it("tries again when the restart fails, and stops trying after a few", async () => {+ await cua.startCua();+ fixture.failStarts = 100;+ fixture.alive = false;+ await expect.poll(() => fixture.hosts.length).toBe(4);+ await pause(100);+ expect(fixture.hosts).toHaveLength(4);+ });++ it("recovers when a later try works", async () => {+ await cua.startCua();+ fixture.failStarts = 1;+ fixture.alive = false;+ await expect.poll(() => fixture.hosts.length).toBeGreaterThanOrEqual(3);+ fixture.alive = true;- expect(JSON.parse((await import("node:fs")).readFileSync(join(fixture.home, "cua-connection.json"), "utf8")).mode).toBe("embedded");++ const { readFileSync } = await import("node:fs");++ await expect.poll(() => JSON.parse(readFileSync(join(fixture.home, "cua-connection.json"), "utf8")).mode).toBe("embedded");+ });++ it("doesn't keep asking when macOS permissions are what's missing", async () => {+ await cua.startCua();+ fixture.granted = false;+ fixture.alive = false;+ await expect.poll(() => fixture.hosts.length).toBe(1);+ await pause(100);+ expect(fixture.hosts).toHaveLength(1);+ expect(JSON.parse((await import("node:fs")).readFileSync(join(fixture.home, "cua-connection.json"), "utf8")).mode).toBe("unavailable");+ });++ it("stops watching on an explicit Stop", async () => {+ await cua.startCua();+ await cua.stopCua();+ fixture.alive = false;+ await pause();+ expect(fixture.hosts).toHaveLength(1);+ });+ });diff --cc electron/cua-watch.mjsindex 0000000000,37bf2bbc4a..8b993816afmode 000000,100644..100644--- a/electron/cua-watch.mjs+++ b/electron/cua-watch.mjs@@@ -1,0 -1,34 +1,26 @@@-// Nothing else notices when the computer-control driver dies after it started: its socket stops answering, every MCP bridge-// exits as soon as it connects, and computer control stays broken until the app restarts. This asks the socket every so-// often and calls `restart` once when it has stopped answering.++// A Mac driver that hangs without exiting, or a standalone one whose exit nothing sees, would leave computer control broken:++// its socket stops answering, and every MCP bridge exits as soon as it connects. This asks the socket every so often and++// calls `restart` once when it has stopped answering; cua.mjs hands that to the helper's bounded restarts (cua-restart.mjs).++ export const WATCH_EVERY_MS = 15_000;+ export const MISSES_BEFORE_RESTART = 2;-/** Between further tries when a restart didn't bring the driver back; then it waits for the person. */-export const DEAD_DRIVER_RETRY_MS = [5_000, 30_000, 120_000, 600_000];--/** A failure more tries won't fix: the person has to act, and each try may ask macOS for the permission again. */-export function restartWorthTrying(message) {- return !/grant access|permission|restart cancelled/i.test(String(message ?? ""));-}-+ /** `restart` runs at most once per watch: a successful restart starts a new one. */+ export function watchDriver({ alive, restart, everyMs = WATCH_EVERY_MS, misses = MISSES_BEFORE_RESTART, log = console.warn }) {+ let timer = null, stopped = false, missed = 0;+ const arm = () => {+ timer = setTimeout(tick, everyMs);+ timer.unref?.();+ };+ async function tick() {+ timer = null;+ const up = await Promise.resolve().then(alive).catch(() => false);+ if (stopped) return;+ missed = up ? 0 : missed + 1;+ if (missed < misses) return arm();+ stopped = true;+ log(`[cua] the driver stopped answering after ${missed} checks; starting it again`);+ await Promise.resolve().then(restart).catch((error) => log(`[cua] could not start the driver again: ${error?.message ?? error}`));+ }+ arm();+ return { stop() { stopped = true; clearTimeout(timer); timer = null; } };+ }diff --cc electron/cua-watch.test.mjsindex 0000000000,93b0dfffd4..86e45928b4mode 000000,100644..100644--- a/electron/cua-watch.test.mjs+++ b/electron/cua-watch.test.mjs@@@ -1,0 -1,67 +1,58 @@@+ import { afterEach, describe, expect, it, vi } from "vitest";+-import { MISSES_BEFORE_RESTART, WATCH_EVERY_MS, restartWorthTrying, watchDriver } from "./cua-watch.mjs";++import { MISSES_BEFORE_RESTART, WATCH_EVERY_MS, watchDriver } from "./cua-watch.mjs";++ const tick = () => vi.advanceTimersByTimeAsync(WATCH_EVERY_MS);++ describe("watching the computer-control driver", () => {+ afterEach(() => { vi.useRealTimers(); });++ it("leaves a driver that answers alone", async () => {+ vi.useFakeTimers();+ const restart = vi.fn();+ const watch = watchDriver({ alive: async () => true, restart });+ for (let i = 0; i < 6; i++) await tick();+ expect(restart).not.toHaveBeenCalled();+ watch.stop();+ });++ it("starts it again once, after enough checks in a row have gone unanswered", async () => {+ vi.useFakeTimers();+ const restart = vi.fn(async () => {}), log = vi.fn();+ const watch = watchDriver({ alive: async () => false, restart, log });+ for (let i = 0; i < MISSES_BEFORE_RESTART - 1; i++) await tick();+ expect(restart).not.toHaveBeenCalled();+ for (let i = 0; i < 4; i++) await tick();+ expect(restart).toHaveBeenCalledTimes(1);+ expect(log.mock.calls[0][0]).toContain("stopped answering");+ watch.stop();+ });++ it("forgives one missed check: a laptop waking from sleep isn't a dead driver", async () => {+ vi.useFakeTimers();+ const answers = [false, true, false, true, false, true];+ const restart = vi.fn();+ const watch = watchDriver({ alive: async () => answers.shift() ?? true, restart });+ for (let i = 0; i < 6; i++) await tick();+ expect(restart).not.toHaveBeenCalled();+ watch.stop();+ });++ it("counts a check that throws as unanswered", async () => {+ vi.useFakeTimers();+ const restart = vi.fn(async () => {});+ const watch = watchDriver({ alive: async () => { throw new Error("no socket"); }, restart, log: () => {} });+ for (let i = 0; i < MISSES_BEFORE_RESTART; i++) await tick();+ expect(restart).toHaveBeenCalledTimes(1);+ watch.stop();+ });++ it("does nothing once stopped", async () => {+ vi.useFakeTimers();+ const restart = vi.fn();+ const watch = watchDriver({ alive: async () => false, restart });+ watch.stop();+ for (let i = 0; i < 6; i++) await tick();+ expect(restart).not.toHaveBeenCalled();+ });-- it.each([- ["Accessibility and Screen Recording required; grant access in System Settings and restart OpenMausBot", false],- ["Computer use restart cancelled", false],- ["embedded host failed: EmbeddedDriverError.Spawn; standalone launch failed: timed out", true],- [undefined, true],- ])("decides whether another try can help: %s", (message, worth) => {- expect(restartWorthTrying(message)).toBe(worth);- });+ });diff --cc electron/cua.mjsindex 333b4b7f4e,a95fb91695..b24fdf476b--- a/electron/cua.mjs+++ b/electron/cua.mjs@@@ -14,8 -13,7 +14,9 @@@ import { pathToFileURL } from "node:urlimport localOriginModule from "./local-origin.cjs";import { createLocalComputerGrant } from "./local-computer-grant.mjs";import { driverFailure } from "./cua-failure.mjs";-import { DEAD_DRIVER_RETRY_MS, restartWorthTrying, watchDriver } from "./cua-watch.mjs";+import { createHelperRestarts, followLinuxConnection } from "./cua-restart.mjs";++import { watchDriver } from "./cua-watch.mjs";+import { missingPermissions } from "./lent-screen-failures.mjs";const { localOnly } = localOriginModule;@@@ -56,6 -53,9 +57,7 @@@ let startupAbort = null* is tried again by itself after these waits; a blocked or missing helper is not. */const RETRY_AFTER_MS = [15_000, 60_000];let retryTimer = null;+ let driverWatch = null;-let deadDriverRetry = null;-let deadDriverRestarts = 0;let lifecycleGeneration = 0;let macRetry = null;let linuxRuntime = null;@@@ -383,21 -349,24 +386,40 @@@ export async function startCua({ attempreturn persistAndNotify(nextConnection);}-/** Starts computer control again when the running Mac driver stops answering, and keeps trying for a while if that fails. */+function watchEmbeddedHost(host, generation) {+ const gone = (detail) => {+ // An exit we asked for is not a crash: stopCua forgets the host first.+ if (host !== embeddedHost) return;+ embeddedHost = null;+ embeddedGeneration = null;+ void host.stop().catch(() => {}).finally(() => host.uniffiDestroy?.());+ helperRestarts.exited(detail);+ };+ void host.waitForExit(generation).then(+ (exit) => gone(`code ${exit?.code ?? "none"}`),+ (error) => gone(driverFailure(error)),+ );+}+++/** A Mac driver that stopped answering without exiting, or a standalone one whose exit nothing here sees, counts as one that++ * died: the helper's bounded restarts take it from there (cua-restart.mjs), the same as an embedded host that exited. */+ function watchMacDriver(connection) {+ driverWatch?.stop();+ driverWatch = null;+ if (process.platform !== "darwin" || (connection.mode !== "embedded" && connection.mode !== "standalone")) return;- deadDriverRestarts = 0;- driverWatch = watchDriver({ alive: () => socketAlive(connection.socketPath), restart: restartDeadDriver });-}--async function restartDeadDriver() {- const attempt = deadDriverRestarts;- const outcome = await restartCua();- if (outcome.enabled || !restartWorthTrying(outcome.message) || attempt >= DEAD_DRIVER_RETRY_MS.length) return;- deadDriverRestarts = attempt + 1;- deadDriverRetry = setTimeout(() => { deadDriverRetry = null; void restartDeadDriver().catch(() => {}); }, DEAD_DRIVER_RETRY_MS[attempt]);- deadDriverRetry.unref?.();++ const host = connection.mode === "embedded" ? embeddedHost : null;++ driverWatch = watchDriver({ alive: () => socketAlive(connection.socketPath), restart: () => {++ if (host) {++ // Already gone and handled by the exit watch, or replaced since.++ if (host !== embeddedHost) return;++ embeddedHost = null;++ embeddedGeneration = null;++ void host.stop().catch(() => {}).finally(() => host.uniffiDestroy?.());++ }++ helperRestarts.exited("its socket stopped answering");++ } });+ }+export async function cuaPermissionsStatus() {const binary = resolveDriverBinary();if (!binary) return { available: false };@@@ -416,9 -385,12 +438,11 @@@}export async function stopCua() {+ helperRestarts.reset();clearTimeout(retryTimer);retryTimer = null;+ driverWatch?.stop();+ driverWatch = null;- clearTimeout(deadDriverRetry);- deadDriverRetry = null;lifecycleGeneration++;startupAbort?.abort();startupAbort = null;