Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: tolerate slow CLI detection and keep existing chats accessible
Krishna Dobhal1fd4772b2cfe
diff --git a/docs/verification/engines.md b/docs/verification/engines.mdindex ea58545ef7..036c04cf5d 100644--- a/docs/verification/engines.md+++ b/docs/verification/engines.md@@ -49,6 +49,26 @@ prove real OAuth login or native Windows execution.provider.- Model-picker rendering is Electron UI and remains outside this first map.+## Slow or empty CLI version responses++```sh+pnpm exec vitest run server/cli-version-probe.test.ts server/procs.test.ts server/engine-status-reads.e2e.test.ts src/App.engine-status.test.ts+```++The disposable server fixture runs a synthetic Claude CLI that takes nine+seconds to report its version, and another that returns empty output once.+Concurrent engine-list reads must report it available and signed in, using+one version process for the slow case and two for the empty-response retry.+Both cases send two chat turns through the control surface and retain the+bot's saved model selection.++The probe tests cover the thirty-second total budget, overlapping checks,+temporary failures, and clearing a remembered version when the executable is+missing or cannot be executed. The renderer test keeps an existing chat+visible while engine status is unavailable and retains setup when there is+no conversation. These checks do not prove a real provider's login or a+packaged Windows window.+## Groq API setup```shdiff --git a/server/cli-version-probe.test.ts b/server/cli-version-probe.test.tsnew file mode 100644index 0000000000..f6c8faf951--- /dev/null+++ b/server/cli-version-probe.test.ts@@ -0,0 +1,69 @@+import { afterEach, expect, it, vi } from "vitest";+import { cliVersionProbe } from "./cli-version-probe.ts";+import { cliVersionReader, type execCli } from "./procs.ts";++afterEach(() => vi.useRealTimers());++it("shares overlapping slow probes and accepts a version after the old eight-second limit", async () => {+ vi.useFakeTimers();+ const run = vi.fn<typeof execCli>((_cli, _args, options, callback) => {+ expect(options.timeout).toBe(30_000);+ setTimeout(() => callback(null, "2.1.311 (Claude Code)\n"), 16_000);+ });+ const probe = cliVersionProbe("claude", run);+ const first = probe({ PATH: "fixture" });+ expect(probe({ PATH: "fixture" })).toBe(first);+ await vi.advanceTimersByTimeAsync(16_000);+ expect(await first).toEqual({ version: "2.1.311 (Claude Code)" });+ expect(run).toHaveBeenCalledTimes(1);+});++it("retries an empty success once within the original thirty-second budget", async () => {+ vi.useFakeTimers();+ const run = vi.fn<typeof execCli>()+ .mockImplementationOnce((_cli, _args, options, callback) => {+ expect(options.timeout).toBe(30_000);+ setTimeout(() => callback(null, ""), 20_000);+ })+ .mockImplementationOnce((_cli, _args, options, callback) => {+ expect(options.timeout).toBe(10_000);+ callback(null, "codex-cli 0.165.0");+ });+ const result = cliVersionProbe("codex", run)({});+ await vi.advanceTimersByTimeAsync(20_000);+ expect(await result).toEqual({ version: "codex-cli 0.165.0" });+ expect(run).toHaveBeenCalledTimes(2);+});++it("does not retry forever or label an empty success as a missing installation", async () => {+ const run = vi.fn<typeof execCli>((_cli, _args, _options, callback) => callback(null, " \n"));+ expect(await cliVersionProbe("codex", run)({})).toEqual({ reason: "`codex` returned no version. Check again." });+ expect(run).toHaveBeenCalledTimes(2);+});++it("rechecks after settlement and preserves the last version through temporary failures", async () => {+ const failed = Object.assign(new Error("fixture process failure"), { code: 1 });+ const run = vi.fn<typeof execCli>()+ .mockImplementationOnce((_cli, _args, _options, callback) => callback(null, "2.1.311"))+ .mockImplementationOnce((_cli, _args, _options, callback) => callback(failed, ""))+ .mockImplementation((_cli, _args, _options, callback) => callback(null, ""));+ const probe = cliVersionProbe("claude", run);+ expect(await probe({})).toEqual({ version: "2.1.311" });+ expect(await probe({})).toEqual({ version: "2.1.311" });+ expect(await probe({})).toEqual({ version: "2.1.311" });+ expect(run).toHaveBeenCalledTimes(4);+});++it.each(["ENOENT", "EACCES", "EPERM"])("forgets a known version after %s instead of resurrecting it on a later timeout", (code) => {+ const read = cliVersionReader("claude");+ expect(read(null, "2.1.311")).toEqual({ version: "2.1.311" });+ const unavailable = read(Object.assign(new Error("fixture launch failure"), { code }), "");+ expect(unavailable).toEqual({ reason: expect.stringContaining(code === "ENOENT" ? "CLI not found" : "file permissions") });+ expect(read(Object.assign(new Error("fixture timeout"), { killed: true }), "")).toEqual({ reason: expect.stringContaining("took longer than 30 seconds") });+});++it("reports an unrecognized failure without claiming the CLI is missing or exposing its output", () => {+ expect(cliVersionReader("codex")(new Error("private diagnostic"), "private output")).toEqual({+ reason: "`codex` could not report its version. Check that it starts in a terminal, then check again.",+ });+});diff --git a/server/cli-version-probe.ts b/server/cli-version-probe.tsnew file mode 100644index 0000000000..40b5faee73--- /dev/null+++ b/server/cli-version-probe.ts@@ -0,0 +1,20 @@+import { CLI_VERSION_TIMEOUT_MS, cliVersionReader, execCli } from "./procs.ts";++// Shares version checks and retries empty responses.+export function cliVersionProbe(cli: string, run: typeof execCli = execCli) {+ const read = cliVersionReader(cli);+ let pending: Promise<ReturnType<typeof read>> | undefined;+ return (env: NodeJS.ProcessEnv): Promise<ReturnType<typeof read>> => {+ if (pending) return pending;+ const deadline = Date.now() + CLI_VERSION_TIMEOUT_MS;+ const attempt = () => new Promise<{ error: Error | null; stdout: string }>((resolve) => {+ run(cli, ["--version"], { timeout: Math.max(1, deadline - Date.now()), env }, (error, stdout) => resolve({ error, stdout }));+ });+ pending = (async () => {+ let result = await attempt();+ if (!result.error && !result.stdout.trim() && Date.now() < deadline) result = await attempt();+ return read(result.error, result.stdout);+ })().finally(() => { pending = undefined; });+ return pending;+ };+}diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.tsindex d342b8784e..eb9331d37d 100644--- a/server/drivers/claude.test.ts+++ b/server/drivers/claude.test.ts@@ -2009,7 +2009,7 @@ describe("ClaudeDriver turns (fake CLI)", () => {const both = Promise.all([instance.snapshot(), instance.snapshot()]);await vi.waitFor(() => {const log = readFileSync(probes, "utf8");- expect(log.match(/^version /gm)).toHaveLength(2);+ expect(log.match(/^version /gm)).toHaveLength(1);expect(log).toMatch(/^help /m);}, { timeout: 10_000 });await new Promise((resolve) => setTimeout(resolve, 300));diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex 830031e6fd..748c4bd021 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -10,7 +10,8 @@ import { DATA_DIR, stripWorkspaceCredentialEnv } from "../config.ts";import { openStartupModelCatalog, unconfirmedModelCatalog, writeStartupModelCache } from "../startup-model-catalog.ts";import { writeFileAtomicIfChanged } from "../atomic.ts";import { augmentedPath } from "../env-path.ts";-import { brokerSocketPath, cliVersionReader, describeSpawnFailure, execCli, killCliTree, spawnCli } from "../procs.ts";+import { brokerSocketPath, describeSpawnFailure, execCli, killCliTree, spawnCli } from "../procs.ts";+import { cliVersionProbe } from "../cli-version-probe.ts";import { claudeAuthStatus } from "./claude-auth-status.ts";import { projectMcpServers } from "./claude-project-mcp.ts";import { botSettingsFor, withBotSettings } from "./claude-bot-settings.ts";@@ -809,10 +810,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {// Whether `claude --help` lists --autocompact: 2.1.129 rejects it despite the floor.let cliHasAutocompact: boolean | null = null;let cliHelpVersion: string | null = null;- const versionOf = cliVersionReader(config.cli);- const readCliVersion = (env: NodeJS.ProcessEnv) => new Promise<ReturnType<typeof versionOf>>((resolve) => {- execCli(config.cli, ["--version"], { timeout: 8000, env }, (err, stdout) => resolve(versionOf(err, stdout)));- });+ const readCliVersion = cliVersionProbe(config.cli);const ensureCliVersion = async (env: NodeJS.ProcessEnv): Promise<void> => {if (cliVersionChecked) return;const probe = await readCliVersion(env);diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex 63b406d7cc..45c3cf1bd2 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -18,7 +18,8 @@ import { hostedWorkspaceConfigured } from "../enterprise.ts";import { cloudHomeConfigured } from "../cloud-home.ts";import { serverVersion } from "../environment.ts";import { ChatGptPlanAuthController } from "./chatgpt-plan-auth.ts";-import { captureCliTree, cliVersionReader, describeSpawnFailure, execCli, killCliTree, spawnCli, waitForExit } from "../procs.ts";+import { captureCliTree, describeSpawnFailure, killCliTree, spawnCli, waitForExit } from "../procs.ts";+import { cliVersionProbe } from "../cli-version-probe.ts";import { codexLaunch, codexLaunchesStarting, codexLaunchSlot, codexRpcTimeoutMs, keepStopping, RELAUNCH_EXIT_WAIT_MS, spawnHoldingSlot, tryCodexLaunchSlot } from "./codex-process.ts";import { isReservedMcpEnvEntry } from "../mcp-registry.ts";@@ -1558,13 +1559,11 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {return { turnId };};- const versionOf = cliVersionReader(config.cli);+ const readCliVersion = cliVersionProbe(config.cli);const snapshot = async (): Promise<ProviderSnapshot> => {if (planUnavailable) return { state: "unavailable", authenticated: false, chatgptPlan: true, reason: planUnavailable, authenticationUnavailableReason: planUnavailable };const env = childEnv();- const probe = await new Promise<ReturnType<typeof versionOf>>((resolve) => {- execCli(config.cli, ["--version"], { timeout: 8000, env }, (err, stdout) => resolve(versionOf(err, stdout)));- });+ const probe = await readCliVersion(env);if (!("version" in probe)) return { state: "unavailable", reason: probe.reason, ...(plan ? { chatgptPlan: true } : {}) };const { version } = probe;if (planAuth) return { state: "available", version, chatgptPlan: true, billing: "subscription", ...await planAuth.snapshot(), update: await codexReleaseUpdate(version, config.cli),diff --git a/server/engine-status-reads.e2e.test.ts b/server/engine-status-reads.e2e.test.tsindex 38100facf7..2e8337e46d 100644--- a/server/engine-status-reads.e2e.test.ts+++ b/server/engine-status-reads.e2e.test.ts@@ -1,6 +1,6 @@// Real server, fake Claude CLI that logs each status probe: an engine's CLI is probed once per answer, not once per reader.import { spawn, type ChildProcess } from "node:child_process";-import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { fileURLToPath } from "node:url";@@ -39,9 +39,13 @@ async function boot(home: string, knobs: Record<string, string> = {}) {stdio: ["ignore", "pipe", "pipe"],});children.push(child);+ const logDir = join(tmpdir(), "openmausbot-verification-evidence");+ mkdirSync(logDir, { recursive: true });+ const logPath = join(logDir, `engine-status-${port}.log`);let output = "";- child.stdout!.on("data", (chunk) => { output += chunk; });- child.stderr!.on("data", (chunk) => { output += chunk; });+ const capture = (chunk: Buffer) => { output += chunk; appendFileSync(logPath, chunk); };+ child.stdout!.on("data", capture);+ child.stderr!.on("data", capture);await expect.poll(async () => {if (child.exitCode !== null) throw new Error(`server exited during boot:\n${output}`);try { return (await fetch(base + "/api/health")).ok; } catch { return false; }@@ -55,7 +59,7 @@ async function boot(home: string, knobs: Record<string, string> = {}) {return response.json() as Promise<any>;};const stop = () => waitForExit(child, { signal: "SIGTERM" });- return { call, control: (...args: string[]) => runControlOmb([...args, "--url", base]) as Promise<any>, stop };+ return { call, control: (...args: string[]) => runControlOmb([...args, "--url", base]) as Promise<any>, stop, logPath };}const probeCount = (log: string, probe: "version" | "help" | "auth") =>@@ -63,6 +67,36 @@ const probeCount = (log: string, probe: "version" | "help" | "auth") =>const claudeStatus = (body: { instances: Array<{ instanceId: string; snapshot: Record<string, unknown> }> }) =>body.instances.find((instance) => instance.instanceId === "claude")!.snapshot;+it.each(["slow", "empty-once"])("detects a %s CLI across concurrent status reads and continues a saved chat", async (mode) => {+ const home = freshHome();+ const probes = join(home, "probes.log");+ const server = await boot(home, {+ FAKE_CLAUDE_PROBE_LOG: probes,+ ...(mode === "slow" ? { FAKE_CLAUDE_VERSION_DELAY_MS: "9000" } : { FAKE_CLAUDE_EMPTY_VERSION_ONCE: join(home, "empty-version-returned") }),+ });+ const lists = await Promise.all([server.call("GET", "/api/instances"), server.call("GET", "/api/instances"), server.call("GET", "/api/instances")]);+ for (const list of lists) expect(claudeStatus(list)).toMatchObject({ state: "available", authenticated: true, version: expect.stringContaining("Claude Code") });+ expect(probeCount(probes, "version")).toBe(mode === "slow" ? 1 : 2);+ const { bot } = await server.control("new-bot", "--name", "Detection fixture");+ const read = async () => (await server.call("GET", "/api/bots?messages=0")).bots.find((item: { id: string }) => item.id === bot.id);+ const selection = (await read()).modelSelection;+ const replies = (messages: Array<{ role: string; kind: string }>) => messages.filter((message) => message.role === "bot" && message.kind === "text");+ const initial = await server.control("messages", "--bot", bot.id);+ const turns = [];+ for (const text of ["First fixture turn", "Continue with the saved model"]) {+ await server.control("send", "--bot", bot.id, "--text", text);+ const settled = await server.control("wait", "--bot", bot.id, "--timeout", "30");+ turns.push({ text, settled });+ expect(settled).toMatchObject({ status: "settled" });+ }+ const transcript = await server.control("messages", "--bot", bot.id);+ expect(replies(transcript.messages)).toHaveLength(replies(initial.messages).length + 2);+ expect((await read()).modelSelection).toEqual(selection);+ const evidenceDir = join(ROOT, ".omb-scratch", "issue-4195-detection");+ mkdirSync(evidenceDir, { recursive: true });+ writeFileSync(join(evidenceDir, `${mode}.json`), JSON.stringify({ mode, logPath: server.logPath, statuses: lists, versionProbes: probeCount(probes, "version"), selection, turns, transcript }, null, 2));+}, 90_000);+it("probes the engine's CLI once on a later start while the model lists arrive and the engine list is read", async () => {const home = freshHome();await (await boot(home)).stop();diff --git a/server/procs.test.ts b/server/procs.test.tsindex ced9c02b0b..5bb1ffeb1d 100644--- a/server/procs.test.ts+++ b/server/procs.test.ts@@ -111,7 +111,7 @@ describe("CLI version probes", () => {const timedOut = await new Promise<Error | null>((resolve) => {execCli(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { timeout: 200 }, (error) => resolve(error));});- expect(cliVersionReader("claude")(timedOut, "")).toEqual({ reason: expect.stringContaining("took longer than 8 seconds") });+ expect(cliVersionReader("claude")(timedOut, "")).toEqual({ reason: expect.stringContaining("took longer than 30 seconds") });const read = cliVersionReader("claude");expect(read(null, " 2.1.302\n")).toEqual({ version: "2.1.302" });expect(read(timedOut, "")).toEqual({ version: "2.1.302" });@@ -127,7 +127,7 @@ describe("CLI version probes", () => {execCli(process.execPath, ["-e", "process.stdout.write('2.1.302')"], { timeout: 100 }, (err, stdout) => resolve({ err, stdout }));Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1_500);});- expect(cliVersionReader("claude")(late.err, late.stdout)).toEqual({ reason: expect.stringContaining("took longer than 8 seconds") });+ expect(cliVersionReader("claude")(late.err, late.stdout)).toEqual({ reason: expect.stringContaining("took longer than 30 seconds") });const read = cliVersionReader("claude");expect(read(null, "2.1.302")).toEqual({ version: "2.1.302" });expect(read(late.err, late.stdout)).toEqual({ version: "2.1.302" });diff --git a/server/procs.ts b/server/procs.tsindex 5ab7da4dd0..a51fe8f82c 100644--- a/server/procs.ts+++ b/server/procs.ts@@ -265,7 +265,8 @@ function cutOffError(cli: string, timeout: number | undefined): Error {return Object.assign(new Error(`${cli} timed out after ${timeout} ms`), { killed: true, code: null, signal: null });}-/** Concurrent probes on a busy machine can outlast the timeout, so a CLI that answered before keeps its last version. */+export const CLI_VERSION_TIMEOUT_MS = 30_000;+export function cliVersionReader(cli: string): (err: Error | null, stdout: string) => { version: string } | { reason: string } {let last: string | null = null;return (err, stdout) => {@@ -273,8 +274,18 @@ export function cliVersionReader(cli: string): (err: Error | null, stdout: strinif (version) return { version: (last = version) };const failure = err as (NodeJS.ErrnoException & { killed?: boolean }) | null;const timedOut = failure?.killed === true && typeof failure.code !== "string";- if (timedOut && last) return { version: last };- return { reason: timedOut ? `\`${cli}\` took longer than 8 seconds to answer --version. The machine may be busy; check again.` : `\`${cli}\` CLI not found` };+ if (failure?.code === "ENOENT") {+ last = null;+ return { reason: `\`${cli}\` CLI not found` };+ }+ if (failure?.code === "EACCES" || failure?.code === "EPERM") {+ last = null;+ return { reason: `\`${cli}\` could not run --version. Check its file permissions.` };+ }+ if (last && (timedOut || !err || typeof failure?.code === "number")) return { version: last };+ return { reason: timedOut+ ? `\`${cli}\` took longer than ${CLI_VERSION_TIMEOUT_MS / 1000} seconds to answer --version. The machine may be busy; check again.`+ : !err ? `\`${cli}\` returned no version. Check again.` : `\`${cli}\` could not report its version. Check that it starts in a terminal, then check again.` };};}diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.tsindex 1c4a4fac8b..afbc7d6da3 100755--- a/server/testing/fake-claude-cli.ts+++ b/server/testing/fake-claude-cli.ts@@ -295,6 +295,13 @@ if (probe) {}if (argv[0] === "--version") {+ const delay = Number(process.env.FAKE_CLAUDE_VERSION_DELAY_MS ?? 0);+ if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));+ const emptyOnce = process.env.FAKE_CLAUDE_EMPTY_VERSION_ONCE;+ if (emptyOnce && !existsSync(emptyOnce)) {+ writeFileSync(emptyOnce, "");+ process.exit(0);+ }// FAKE_CLAUDE_VERSION stands in for an older CLI.process.stdout.write(`${process.env.FAKE_CLAUDE_VERSION ?? "2.1.232"} (Claude Code)\n`);process.exit(0);diff --git a/src/App.engine-status.test.ts b/src/App.engine-status.test.tsnew file mode 100644index 0000000000..f135a19b71--- /dev/null+++ b/src/App.engine-status.test.ts@@ -0,0 +1,61 @@+// @vitest-environment happy-dom+import { createElement, type ReactNode } from "react";+import { flushSync } from "react-dom";+import { createRoot } from "react-dom/client";+import { afterEach, expect, it, vi } from "vitest";+import { initialState, type AppState, type Bot } from "./state/store";++let state: AppState;+vi.mock("./state/store", async (original) => ({+ ...await original<typeof import("./state/store")>(),+ StoreProvider: ({ children }: { children: ReactNode }) => children,+ useStore: () => ({ state, dispatch: () => {}, flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} }),+}));+vi.mock("./lib/analytics", () => ({ initAnalytics: () => {}, track: () => {}, emailGateDone: () => true }));+const { default: App } = await import("./App");++afterEach(() => { vi.unstubAllGlobals(); });++it("keeps a saved conversation visible through an unavailable engine status and recovery", () => {+ vi.stubGlobal("fetch", () => new Promise(() => {}));+ const bot = { id: "pepper", threadId: "main", name: "Pepper", title: "", description: "", color: "green", tasks: [],+ modelSelection: { instanceId: "claude", model: "claude-sonnet-5" },+ messages: [{ id: "saved", role: "user", text: "Saved conversation before the status failure", timestamp: 1 }],+ } as unknown as Bot;+ state = { ...initialState, connected: true, hydrated: true, bots: [bot], selectedId: bot.id,+ instances: [{ instanceId: "claude", driverKind: "claudeAgent", displayName: "Claude", models: { default: "claude-sonnet-5", options: [{ id: "claude-sonnet-5", label: "Sonnet" }] }, snapshot: { state: "unavailable", reason: "CLI probe timed out" } }],+ };+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ try {+ flushSync(() => root.render(createElement(App)));+ expect(container.querySelector("[data-chathead-identity]")).not.toBeNull();+ expect(container.textContent).toContain("Saved conversation before the status failure");+ state = { ...state, instances: state.instances.map((instance) => ({ ...instance, snapshot: { state: "available", authenticated: true } })) };+ flushSync(() => root.render(createElement(App)));+ expect(container.textContent).toContain("Saved conversation before the status failure");+ expect(bot.modelSelection).toEqual({ instanceId: "claude", model: "claude-sonnet-5" });+ } finally {+ root.unmount();+ container.remove();+ }+});++it("offers AI setup when there is no conversation and every engine is unavailable", () => {+ vi.stubGlobal("fetch", () => new Promise(() => {}));+ state = { ...initialState, connected: true, hydrated: true,+ instances: [{ instanceId: "claude", driverKind: "claudeAgent", displayName: "Claude", models: { default: "", options: [] }, snapshot: { state: "unavailable" } }],+ };+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ try {+ flushSync(() => root.render(createElement(App)));+ expect(container.querySelector("[data-chathead-identity]")).toBeNull();+ expect(container.textContent).toContain("Check again");+ } finally {+ root.unmount();+ container.remove();+ }+});diff --git a/src/App.tsx b/src/App.tsxindex a416196369..e5a927a9f2 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -370,14 +370,14 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {<CloudIntent />) : firstRun === "sign-in" ? (<CloudEngineSignIn />- ) : noEngines ? (- <NoEngines />) : chiefStep ? (<EmptyChatShell />) : group ? (<GroupView key={group.id} group={group} />) : bot ? (<ChatView bot={bot} />+ ) : noEngines ? (+ <NoEngines />) : (<main data-app-loading={loading.text} className="relative flex h-full min-w-0 flex-1 flex-col items-center justify-center gap-3 bg-app text-ink-secondary"><WindowDragStrip />