Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Launch fix round: Local VM recovery and availability read at once; probe answers keyed on the script's interpreter; a re-check after an unfinished check runs the program; Windows package job checks the asar entry

milind-sonia3cc5d5c3a6d
diff --git a/.github/workflows/package-win.yml b/.github/workflows/package-win.yml
index 9a04d8f900..2f6637c721 100644
--- a/.github/workflows/package-win.yml
+++ b/.github/workflows/package-win.yml
@@ -73,6 +73,15 @@ jobs:
[ -f "$res/server/index.js" ] || { echo "::error::missing $res/server/index.js"; fail=1; }
# missing → the desktop falls back to index.js with no compile cache
[ -f "$res/server/desktop-entry.mjs" ] || { echo "::error::missing $res/server/desktop-entry.mjs"; fail=1; }
+ # package.json "main" is electron/boot.mjs, which loads main.mjs: a missing or broken entry
+ # inside app.asar is an app that never opens. The packed exe reads its own asar as Node.
+ exe=release/win-unpacked/OpenMausBot.exe
+ for entry in boot.mjs main-compile-cache.mjs main.mjs; do
+ ELECTRON_RUN_AS_NODE=1 "$exe" --check "$res/app.asar/electron/$entry" || {
+ echo "::error::app.asar/electron/$entry is missing or does not parse"; fail=1; }
+ done
+ main=$(ELECTRON_RUN_AS_NODE=1 "$exe" -p "require(process.argv[1]).main" "$res/app.asar/package.json")
+ [ "$main" = "electron/boot.mjs" ] || { echo "::error::app.asar package.json main is '$main'"; fail=1; }
# missing → the server has nothing to serve → black window
[ -f "$res/ui/index.html" ] || { echo "::error::missing $res/ui/index.html"; fail=1; }
[ -f "$res/cloudflared/cloudflared.exe" ] || {
diff --git a/server/cli-probe-cache.test.ts b/server/cli-probe-cache.test.ts
index 02f5ff9481..52ea746c1d 100644
--- a/server/cli-probe-cache.test.ts
+++ b/server/cli-probe-cache.test.ts
@@ -15,6 +15,8 @@ function place() {
roots.push(root);
const bin = join(root, "bin");
mkdirSync(bin);
+ // The interpreter the test programs' `#!/usr/bin/env node` names, found on the same PATH.
+ writeFileSync(join(bin, windows ? "node.exe" : "node"), "\u007fELF node");
return { root, bin, file: join(root, "user-data", "engine-probes.json") };
}
@@ -124,8 +126,8 @@ describe("engine probe answers kept between desktop starts", () => {
expect(probedProgram("engine", { env: { PATH: bin } })).toBeNull();
expect(probedProgram("other", { env: { PATH: shims } })).toBeNull();
expect(probedProgram("engine --flag", { env: { PATH: bin } })).toBeNull();
- expect(probedProgram("native", { env: { PATH: bin } })).toMatch(/native$/);
- expect(probedProgram("node-cli", { env: { PATH: bin } })).toMatch(/node-cli$/);
+ expect(probedProgram("native", { env: { PATH: bin } })).toEqual({ program: expect.stringMatching(/native$/), interpreter: null });
+ expect(probedProgram("node-cli", { env: { PATH: bin } })).toEqual({ program: expect.stringMatching(/node-cli$/), interpreter: expect.stringMatching(/node$/) });
});
it("runs every probe where nothing may be kept", async () => {
@@ -144,6 +146,42 @@ describe("engine probe answers kept between desktop starts", () => {
mkdirSync(join(bin, "node_modules", "engine", "bin"), { recursive: true });
writeFileSync(script, "console.log('1.0.0');\n");
writeFileSync(join(bin, "engine.cmd"), '@ECHO off\r\n"%~dp0\\node_modules\\engine\\bin\\engine.js" %*\r\n');
- expect(probedProgram(join(bin, "engine.cmd"), {})?.toLowerCase()).toBe(realpathSync(script).toLowerCase());
+ expect(probedProgram(join(bin, "engine.cmd"), {})?.program.toLowerCase()).toBe(realpathSync(script).toLowerCase());
+ });
+
+ it("keys a script on the interpreter its #! line names too, and keeps nothing when that interpreter is gone", async () => {
+ const { bin, file } = place();
+ program(bin, "engine");
+ const counted = runner();
+ const cache = createCliProbeCache({ file, appVersion: "1", run: counted.run });
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
+ expect(counted.calls).toHaveLength(1);
+ // Another Node on the same PATH: asked again.
+ const node = join(bin, windows ? "node.exe" : "node");
+ rmSync(node);
+ writeFileSync(node, "\u007fELF another node build");
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
+ expect(counted.calls).toHaveLength(2);
+ // No Node at all: the program cannot run, so no kept answer may say it is installed.
+ rmSync(node);
+ expect(probedProgram(cliFor(bin, "engine"), { env: { PATH: bin } })).toBeNull();
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
+ expect(counted.calls).toHaveLength(3);
+ });
+
+ it("runs the program again after a status check of that CLI could not finish", async () => {
+ const { bin, file } = place();
+ program(bin, "engine");
+ const counted = runner();
+ let unsettled = false;
+ const cache = createCliProbeCache({ file, appVersion: "1", run: counted.run, unsettled: () => unsettled });
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
+ unsettled = true;
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
+ expect(counted.calls).toHaveLength(2);
+ unsettled = false;
+ await ask(cache.exec, cliFor(bin, "engine"), ["--version"], bin);
+ expect(counted.calls).toHaveLength(2);
});
});
diff --git a/server/cli-probe-cache.ts b/server/cli-probe-cache.ts
index c8ea835808..9c9a4150f5 100644
--- a/server/cli-probe-cache.ts
+++ b/server/cli-probe-cache.ts
@@ -3,8 +3,9 @@
// Windows). Only under the desktop app (its own folder, OMB_USER_DATA, never the data folder); any other server runs every
// probe as before. Only successful answers are kept, never a sign-in check (`auth status`), whose answer changes.
//
-// The key is the program file itself: its real path, size, modification and change times and inode, plus the app's
-// version, the platform and the arguments. An update writes a new file (npm and Homebrew both do, and a reinstall gets a
+// The key is the program file itself, and the interpreter a script names (`#!/usr/bin/env node` is the `node` on the probe's
+// PATH; Windows runs a shim's script with node.exe): each one's real path, size, modification and change times and inode,
+// plus the app's version, the platform and the arguments. A script whose interpreter cannot be found is never kept. An update writes a new file (npm and Homebrew both do, and a reinstall gets a
// new change time even when the package keeps the 1985 modification time npm gives every file), so it is asked again. Not
// kept: a program that is a shell script or a version manager's shim (asdf, mise, volta and the like), whose file stays
// the same while the version it runs changes.
@@ -32,10 +33,13 @@ export function probeCacheFile(env: NodeJS.ProcessEnv = process.env): string | n
return env.OMB_DESKTOP_PARENT === "1" && env.OMB_USER_DATA && isAbsolute(env.OMB_USER_DATA) ? join(env.OMB_USER_DATA, PROBE_CACHE_FILE) : null;
}
-/** The file a probe of `cli` actually runs, found the way execCli finds it (procs.ts): on Windows a shim or #! script
- * becomes Node plus the script, so the script; elsewhere a bare name is looked up on the PATH the probe runs with. Null
- * when it is not a file whose answer may be kept. */
-export function probedProgram(cli: string, opts: ExecFileOptions): string | null {
+/** A name on a PATH, the way an engine's spawn finds it. */
+const programOnPath = (name: string, path: string): string | null => findCliCandidates(name, path).find(isFile) ?? null;
+
+/** What a probe of `cli` actually runs, found the way execCli finds it (procs.ts): on Windows a shim or #! script becomes
+ * Node plus the script; elsewhere a bare name is looked up on the PATH the probe runs with, and a script's #! line names its
+ * interpreter. Null when it is not something whose answer may be kept. */
+export function probedProgram(cli: string, opts: ExecFileOptions): { program: string; interpreter: string | null } | null {
if (splitCliString(cli).length !== 1) return null;
let command: string, rest: string[], env: NodeJS.ProcessEnv;
try {
@@ -44,42 +48,69 @@ export function probedProgram(cli: string, opts: ExecFileOptions): string | null
} catch {
return null;
}
+ const path = String(env.PATH ?? env.Path ?? "");
const file = rest.length
? rest.find((arg) => isAbsolute(arg) && isFile(arg))
- : /[\\/]/.test(command) ? command : findCliCandidates(command, String(env.PATH ?? env.Path ?? ""))[0];
+ : /[\\/]/.test(command) ? command : programOnPath(command, path);
if (!file) return null;
let real: string;
try { real = realpathSync(file); } catch { return null; }
const name = basename(real).toLowerCase().replace(/\.(?:exe|cmd|bat|ps1)$/, "");
if (SHIM_PROGRAMS.has(name) || real.toLowerCase().split(/[\\/]/).includes("shims")) return null;
if (/\.(?:ps1|sh|cmd|bat)$/i.test(real) || shellScript(real)) return null;
- return real;
+ const interpreter = rest.length ? command : interpreterOf(real, path);
+ if (interpreter === undefined) return null;
+ if (interpreter === null) return { program: real, interpreter: null };
+ try { return { program: real, interpreter: realpathSync(interpreter) }; } catch { return null; }
}
-function isFile(path: string): boolean {
- try { return statSync(path).isFile(); } catch { return false; }
+/** The program a script's #! line runs: null for a file with none (a native program), undefined when it cannot be found. */
+function interpreterOf(file: string, path: string): string | null | undefined {
+ const line = firstLine(file);
+ if (line === undefined) return undefined;
+ if (!line.startsWith("#!")) return null;
+ const words = line.slice(2).trim().split(/\s+/).filter(Boolean);
+ if (!words[0]) return undefined;
+ if (basename(words[0]) !== "env") return isFile(words[0]) ? words[0] : undefined;
+ const name = words.slice(1).find((word) => !word.startsWith("-") && !word.includes("="));
+ return name ? programOnPath(name, path) ?? undefined : undefined;
}
-function shellScript(file: string): boolean {
+function firstLine(file: string): string | undefined {
let fd: number | undefined;
try {
fd = openSync(file, "r");
- const head = Buffer.alloc(128);
+ const head = Buffer.alloc(256);
const read = readSync(fd, head, 0, head.length, 0);
- return SHELL_INTERPRETERS.test(head.subarray(0, read).toString("utf8").split("\n")[0] ?? "");
+ return head.subarray(0, read).toString("utf8").split("\n")[0]?.replace(/\r$/, "") ?? "";
} catch {
- return true;
+ return undefined;
} finally {
if (fd !== undefined) try { closeSync(fd); } catch {}
}
}
-/** The key one answer is kept under, or null when the program cannot be read. */
-export function probeKey(program: string, args: readonly string[], appVersion: string, platform: NodeJS.Platform = process.platform): string | null {
+function isFile(path: string): boolean {
+ try { return statSync(path).isFile(); } catch { return false; }
+}
+
+function shellScript(file: string): boolean {
+ const line = firstLine(file);
+ return line === undefined || SHELL_INTERPRETERS.test(line);
+}
+
+function identity(file: string): string[] | null {
let stat;
- try { stat = statSync(program, { bigint: true }); } catch { return null; }
- if (!stat.isFile()) return null;
- return createHash("sha256").update(JSON.stringify([appVersion, platform, program, String(stat.size), String(stat.mtimeNs), String(stat.ctimeNs), String(stat.ino), String(stat.dev), args])).digest("hex").slice(0, 40);
+ try { stat = statSync(file, { bigint: true }); } catch { return null; }
+ return stat.isFile() ? [file, String(stat.size), String(stat.mtimeNs), String(stat.ctimeNs), String(stat.ino), String(stat.dev)] : null;
+}
+
+/** The key one answer is kept under, or null when the program or its interpreter cannot be read. */
+export function probeKey(run: { program: string; interpreter: string | null }, args: readonly string[], appVersion: string, platform: NodeJS.Platform = process.platform): string | null {
+ const program = identity(run.program);
+ const interpreter = run.interpreter === null ? [] : identity(run.interpreter);
+ if (!program || !interpreter) return null;
+ return createHash("sha256").update(JSON.stringify([appVersion, platform, program, interpreter, args])).digest("hex").slice(0, 40);
}
function readEntries(file: string): Map<string, Entry> {
@@ -101,7 +132,7 @@ function readEntries(file: string): Map<string, Entry> {
* execCli for a probe whose answer is fixed by the program file: answered from the desktop app's kept copy when the file
* is unchanged, else run, and kept when it succeeds with some output. The callback gets exactly what a run would give.
*/
-export function createCliProbeCache(options: { file: string | null; appVersion: string; run?: ExecCli; platform?: NodeJS.Platform }) {
+export function createCliProbeCache(options: { file: string | null; appVersion: string; run?: ExecCli; platform?: NodeJS.Platform; unsettled?: (cli: string) => boolean }) {
const run: ExecCli = (...args) => (options.run ?? execCli)(...args); // read at each call: tests replace execCli
const platform = options.platform ?? process.platform;
let entries: Map<string, Entry> | null = null;
@@ -116,7 +147,8 @@ export function createCliProbeCache(options: { file: string | null; appVersion:
const exec: ExecCli = (cli, args, opts, cb) => {
const program = options.file && args.length === 1 && CACHED_ARGS.has(args[0]!) ? probedProgram(cli, opts) : null;
const key = program ? probeKey(program, args, options.appVersion, platform) : null;
- const kept = key ? loaded().get(key) : undefined;
+ // A check again after one that could not finish runs the program: an earlier answer never stands in for it.
+ const kept = key && !(options.unsettled ?? lastCheckUnsettled)(cli) ? loaded().get(key) : undefined;
if (kept) {
queueMicrotask(() => cb(null, kept.stdout, kept.stderr));
return;
@@ -135,6 +167,9 @@ export function createCliProbeCache(options: { file: string | null; appVersion:
return { exec, forget() { entries = new Map(); save(); } };
}
+/** Whether a CLI's last status check could not finish; none is known here until the engine status hold reports one. */
+const lastCheckUnsettled = (_cli: string): boolean => false;
+
let shared: ReturnType<typeof createCliProbeCache> | null = null;
/** execCli for `--version` and `--help` probes: the desktop app's kept answer when the program is unchanged. */
diff --git a/server/index.ts b/server/index.ts
index c3ce6083f0..ce236bc545 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -1786,7 +1786,7 @@ const MAX_COMMS_DEPTH = 1;
const MAX_WORKSPACE_BOTS = 100;
const phoneProxyPath = SPAWNED_PROXIES.phone;
-const researchAvailability = createResearchAvailability({ credential: () => researchCredential(cfg.treg?.key) }); researchAvailability.available(); const localVmAvailability = createLocalVmAvailability(() => containerRuntimeStatus(), Date.now, afterLaunchSettles);
+const researchAvailability = createResearchAvailability({ credential: () => researchCredential(cfg.treg?.key) }); researchAvailability.available(); const localVmAvailability = createLocalVmAvailability(() => containerRuntimeStatus()); // at once, sharing Local VM recovery's read: a turn's tools never change once known
function agentsIntegration(
botId: string,
threadId: string,
@@ -6212,11 +6212,11 @@ function releaseLocalVmThread(threadId: string): void {
localVmThreadTargets.delete(threadId);
}
-afterLaunchSettles(() => void recoverLocalVms({
+void recoverLocalVms({ // at once: a queued or channel turn sent as the server listens finds a running VM
mode: localVmMode(cfg), seats: localVmMaxInstances(cfg), bots: store.bots, seen: localVmSeen,
status: (target) => containerComputerStatus(undefined, undefined, target).catch(() => null),
note: noteLocalVmSeen, armIdle: (target) => localVmIdleFor(target).touch(),
-}).then(() => localVmUpdates.sweep()).catch(() => {}));
+}).then(() => localVmUpdates.sweep()).catch(() => {});
async function localVmInventoryPayload() {
const runtime = await containerRuntimeStatus();
diff --git a/server/local-vm-availability.test.ts b/server/local-vm-availability.test.ts
index b88d46ff2f..6a388bc14f 100644
--- a/server/local-vm-availability.test.ts
+++ b/server/local-vm-availability.test.ts
@@ -54,16 +54,12 @@ describe("whether this server can give a bot a Local VM", () => {
expect(availability.available()).toBe(true);
});
- it("holds its first read until the caller starts it (the desktop window in use), reading as usable meanwhile", async () => {
+ it("starts its first read at once, so the first turn already lists the tools every later turn lists", async () => {
let probes = 0;
- let start: (() => void) | null = null;
- const availability = createLocalVmAvailability(async () => { probes += 1; return { available: [] }; }, Date.now, (first) => { start = first; });
- await flush();
- expect(probes).toBe(0);
- expect(availability.available()).toBe(true);
- start!();
- await flush();
+ const availability = createLocalVmAvailability(async () => { probes += 1; return { available: [] }; });
expect(probes).toBe(1);
- expect(availability.available()).toBe(false);
+ await flush();
+ const turns = [availability.available(), availability.available()];
+ expect(turns).toEqual([false, false]);
});
});
diff --git a/server/local-vm-availability.ts b/server/local-vm-availability.ts
index 16aa27dbcd..056e711cd4 100644
--- a/server/local-vm-availability.ts
+++ b/server/local-vm-availability.ts
@@ -9,8 +9,8 @@ export interface LocalVmRuntimeStatus {
const RECHECK_MS = 60_000;
-/** `start`: when the first check runs (the desktop app holds it until its window is in use); until then it reads as usable. */
-export function createLocalVmAvailability(probe: () => Promise<LocalVmRuntimeStatus>, now: () => number = Date.now, start: (first: () => void) => void = (first) => first()) {
+/** The first check starts at once, so the answer is known before the first turn lists its tools. */
+export function createLocalVmAvailability(probe: () => Promise<LocalVmRuntimeStatus>, now: () => number = Date.now) {
let usable = true;
let checkedAt = 0;
let checking = false;
@@ -26,7 +26,7 @@ export function createLocalVmAvailability(probe: () => Promise<LocalVmRuntimeSta
.catch(() => {})
.finally(() => { checking = false; });
};
- start(check);
+ check();
return {
available: () => {
if (!usable && now() - checkedAt >= RECHECK_MS) check();
diff --git a/server/local-vm-boot-order.test.ts b/server/local-vm-boot-order.test.ts
new file mode 100644
index 0000000000..0c6642ed9b
--- /dev/null
+++ b/server/local-vm-boot-order.test.ts
@@ -0,0 +1,20 @@
+// The Local VM's recovery and its first availability read start as the server loads, not after the desktop window is in
+// use (perf/launch-probe.ts): a queued or channel turn sent as the server listens must find a running VM, and the first
+// turn's tool list must already be the one every later turn gets.
+import { readFileSync } from "node:fs";
+import { describe, expect, it } from "vitest";
+
+const source = readFileSync(new URL("./index.ts", import.meta.url), "utf8");
+
+describe("the Local VM at server start", () => {
+ it("recovers running VMs before the server listens, never behind the window", () => {
+ const recover = source.indexOf("void recoverLocalVms({");
+ expect(recover).toBeGreaterThan(0);
+ expect(recover).toBeLessThan(source.indexOf("server.listen(PORT"));
+ expect(source).not.toMatch(/afterLaunchSettles\(\(\) => void recoverLocalVms/);
+ });
+
+ it("starts its availability read at once", () => {
+ expect(source).toMatch(/createLocalVmAvailability\(\(\) => containerRuntimeStatus\(\)\);/);
+ });
+});