Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep a gateway recorded before its exec out of the stop, and clean up the test gateway's group
Bugfixer 2ca7b12134dc9
diff --git a/server/kill-tree.test.ts b/server/kill-tree.test.tsindex b146b53add..ccf3fef241 100644--- a/server/kill-tree.test.ts+++ b/server/kill-tree.test.ts@@ -120,41 +120,78 @@ describe("killCliTree", () => {}});+ /** A stand-in for Hermes' gateway: it starts one child and prints "<its pid> <child pid>". */+ const GATEWAY = `+ const s = require('node:child_process').spawn(process.execPath, ['-e', ${JSON.stringify(`console.log(process.pid); ${IDLE}`)}], { stdio: ['ignore', 'pipe', 'ignore'] });+ s.stdout.once('data', (pid) => console.log(process.pid + ' ' + String(pid).trim()));+ ${IDLE};+ `;++ /** Reads "<gateway pid> <gateway pid> <its child pid>" from the launcher. The launcher prints the gateway's pid as soon+ * as it starts it, so cleanup can end the gateway's group even when the rest never comes. */+ function gatewayPids(parent: ReturnType<typeof spawnCli>, started: { group: number }): Promise<number[]> {+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error("the gateway did not report its pids")), 5_000);+ let line = "";+ parent.stdout!.on("data", (chunk) => {+ line += String(chunk);+ if (!started.group && line.includes(" ")) started.group = Number(line.split(" ")[0]);+ if (!line.includes("\n")) return;+ clearTimeout(timer);+ resolve(line.trim().split(" ").slice(1).map(Number));+ });+ });+ }+it.runIf(process.platform === "linux").each([true, false])("leaves a gateway the CLI started to outlive it, and that gateway's own children, running (gateway command: %s)", async (isGateway) => {- const gateway = `- const s = require('node:child_process').spawn(process.execPath, ['-e', ${JSON.stringify(`console.log(process.pid); ${IDLE}`)}], { stdio: ['ignore', 'pipe', 'ignore'] });- s.stdout.once('data', (pid) => console.log(process.pid + ' ' + String(pid).trim()));- ${IDLE};- `;// Hermes starts it as `python -m hermes_cli.main gateway run --quiet --idle-exit`; any other command with the same// inherited variable is still stopped.- const gatewayArgs = ['-e', gateway, ...(isGateway ? ['gateway', 'run', '--quiet'] : [])];+ const gatewayArgs = ['-e', GATEWAY, ...(isGateway ? ['gateway', 'run', '--quiet'] : [])];const parent = spawnCli(process.execPath, ["-e", `const c = require('node:child_process').spawn(process.execPath, ${JSON.stringify(gatewayArgs)}, {detached: true, stdio: ['ignore', 'pipe', 'ignore'], env: { ...process.env, HERMES_GATEWAY_DETACHED: '1' },});+ process.stdout.write(c.pid + ' ');c.stdout.once('data', (pids) => process.stdout.write(pids));${IDLE};`], { stdio: ["pipe", "pipe", "pipe"] });- let kept: number[] = [];+ const started = { group: 0 };try {- kept = await new Promise<number[]>((resolve, reject) => {- const timer = setTimeout(() => reject(new Error("the gateway did not report its pids")), 5_000);- let line = "";- parent.stdout.on("data", (chunk) => {- line += String(chunk);- if (!line.includes("\n")) return;- clearTimeout(timer);- resolve(line.trim().split(" ").map(Number));- });- });+ const kept = await gatewayPids(parent, started);expect(kept).toHaveLength(2);captureCliTree(parent);await expect(killCliTree(parent, 80)).resolves.toBe(true);expect(kept.map(alive)).toEqual([isGateway, isGateway]);} finally {await killCliTree(parent, 0);- for (const pid of kept) if (alive(pid)) try { process.kill(pid, "SIGKILL"); } catch {}+ if (started.group) try { process.kill(-started.group, "SIGKILL"); } catch {}+ }+ }, 20_000);++ it.runIf(process.platform === "linux")("leaves a gateway running that was recorded before it became one", async () => {+ // A fork shows its launcher's command line and environment until it execs into the gateway.+ const parent = spawnCli(process.execPath, ["-e", `+ const c = require('node:child_process').spawn('/bin/sh', ['-c', 'read go; exec env HERMES_GATEWAY_DETACHED=1 "$0" -e "$1" gateway run', process.execPath, ${JSON.stringify(GATEWAY)}], {+ detached: true, stdio: ['pipe', 'pipe', 'ignore'],+ });+ process.stdout.write(c.pid + ' ');+ process.stdin.once('data', () => c.stdin.write('go\\n'));+ c.stdout.once('data', (pids) => process.stdout.write(pids));+ ${IDLE};+ `], { stdio: ["pipe", "pipe", "pipe"] });+ const started = { group: 0 };+ try {+ const pids = gatewayPids(parent, started);+ await vi.waitFor(() => expect(started.group).toBeGreaterThan(0));+ captureCliTree(parent);+ parent.stdin!.write("go\n");+ const kept = await pids;+ expect(kept[0]).toBe(started.group);+ await expect(killCliTree(parent, 80)).resolves.toBe(true);+ expect(kept.map(alive)).toEqual([true, true]);+ } finally {+ await killCliTree(parent, 0);+ if (started.group) try { process.kill(-started.group, "SIGKILL"); } catch {}}}, 20_000);diff --git a/server/procs.ts b/server/procs.tsindex 2def936d3d..496819b997 100644--- a/server/procs.ts+++ b/server/procs.ts@@ -144,6 +144,16 @@ function outlivesLauncher({ pid, session }: LinuxProcess): boolean {}}+/** A child recorded between its fork and its exec still showed its launcher's command line and environment, so a+ * gateway can already be in the tree: forget it before walking the tree. */+function forgetOutliving(tree: Map<number, string>): void {+ for (const [pid, start] of tree) {+ let current: LinuxProcess | null;+ try { current = linuxProcess(pid); } catch { continue; }+ if (current?.start === start && outlivesLauncher(current)) tree.delete(pid);+ }+}+function isLinuxProcess(pid: number, start: string): boolean {try { return linuxProcess(pid)?.start === start; } catch { return false; }}@@ -157,6 +167,7 @@ export function captureCliTree(child: ChildProcess): void {tree = new Map();linuxTrees.set(child, tree);}+ if (process.platform === "linux") forgetOutliving(tree);if (process.platform === "darwin" || !linuxChildrenFiles() || !addLinuxDescendants(tree)) {try { addDescendantsFromEveryProcess(tree); } catch {}}@@ -220,7 +231,7 @@ function linuxDescendantsStopped(child: ChildProcess): boolean {for (const [pid, start] of tree) {try {const current = read(pid);- if (current?.start === start && current.state !== "Z" && current.state !== "X") return false;+ if (current?.start === start && current.state !== "Z" && current.state !== "X" && !outlivesLauncher(current)) return false;} catch { return false; }}return true;