Skip to content

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

Antigravity: stop runtimes an earlier server left running on Windows

AdityaUmale7cf26568659b
diff --git a/server/drivers/antigravity-processes.test.ts b/server/drivers/antigravity-processes.test.ts
index f3e169a92e..3b5a5d61cc 100644
--- a/server/drivers/antigravity-processes.test.ts
+++ b/server/drivers/antigravity-processes.test.ts
@@ -1,8 +1,9 @@
import { spawn } from "node:child_process";
+import { sep } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import * as procs from "../procs.ts";
-import { AntigravityProcesses } from "./antigravity-processes.ts";
+import { AntigravityProcesses, orphanedRuntimeProcesses, stopOrphanedAntigravityRuntimes } from "./antigravity-processes.ts";
const children: ReturnType<typeof spawn>[] = [];
@@ -35,3 +36,57 @@ describe("waiting for an account's runtime processes to end", () => {
expect(processes.count("a")).toBe(1);
});
});
+
+describe("runtimes an earlier server left running on Windows", () => {
+ const dataDir = "C:\\Users\\a\\.openmausbot";
+ const release = `${dataDir}\\tools\\antigravity-acp\\win32-x64\\versions\\abc`;
+ const row = (pid: number, path: string, parentStarted: string | null, started = "2026-11-21T08:00:00.0000000Z") => ({ pid, path, started, parentStarted });
+
+ it("lists only this app's runtime images whose parent is gone or holds a reused pid", () => {
+ const rows = [
+ row(1, `${release}\\agy_acp_server.exe`, null),
+ row(2, `${release}\\AGY_ACP_SERVER.EXE`, "2026-11-22T09:00:00.0000000Z"),
+ row(3, `${release}\\agy_acp_server.exe`, "2026-11-21T07:59:00.0000000Z"),
+ row(4, `${release}\\localharness_external.exe`, "2026-11-21T08:00:00.0000000Z"),
+ row(5, "C:\\Users\\a\\Zed\\agy\\agy_acp_server.exe", null),
+ row(6, `${release}\\other.exe`, null),
+ row(7, `${dataDir}\\tools\\antigravity-acp-copy\\agy_acp_server.exe`, null),
+ ];
+ expect(orphanedRuntimeProcesses(rows, `${dataDir}\\tools\\antigravity-acp`).map(({ pid }) => pid)).toEqual([1, 2]);
+ });
+
+ it("stops each orphan once with the start time it was listed with", async () => {
+ const run = vi.fn(async (_script: string, env: NodeJS.ProcessEnv) => env.OMB_AGY_RUNTIMES === undefined ? "" : JSON.stringify([
+ { ProcessId: 41, ExecutablePath: `${release}\\agy_acp_server.exe`, Started: "2026-11-21T08:00:00.0000000Z", ParentStarted: null },
+ { ProcessId: 42, ExecutablePath: `${release}\\localharness_external.exe`, Started: "2026-11-21T08:00:01.0000000Z", ParentStarted: "2026-11-21T08:00:00.0000000Z" },
+ { ProcessId: 43, ExecutablePath: `${release}\\agy_acp_server.exe`, Started: "2026-11-25T08:00:00.0000000Z", ParentStarted: "2026-11-25T07:00:00.0000000Z" },
+ ]));
+ expect(await stopOrphanedAntigravityRuntimes({ platform: "win32", dataDir, run })).toBe(1);
+ expect(run).toHaveBeenCalledTimes(2);
+ expect(run.mock.calls[0]![1]).toEqual({ OMB_AGY_RUNTIMES: `${dataDir}${sep}tools${sep}antigravity-acp` });
+ expect(run.mock.calls[1]![1]).toEqual({ OMB_AGY_STOP: "41=2026-11-21T08:00:00.0000000Z" });
+ expect(run.mock.calls[1]![0]).toContain("taskkill /PID $id /T /F");
+ });
+
+ it("counts none stopped when the stop itself fails", async () => {
+ const run = vi.fn(async (_script: string, env: NodeJS.ProcessEnv) => env.OMB_AGY_RUNTIMES === undefined ? null : JSON.stringify(
+ { ProcessId: 41, ExecutablePath: `${release}\\agy_acp_server.exe`, Started: "2026-11-21T08:00:00.0000000Z", ParentStarted: null },
+ ));
+ expect(await stopOrphanedAntigravityRuntimes({ platform: "win32", dataDir, run })).toBe(0);
+ expect(run).toHaveBeenCalledTimes(2);
+ });
+
+ it("stops nothing when no orphan is listed or the listing fails", async () => {
+ for (const listing of [null, "", "[]"]) {
+ const run = vi.fn(async () => listing);
+ expect(await stopOrphanedAntigravityRuntimes({ platform: "win32", dataDir, run })).toBe(0);
+ expect(run).toHaveBeenCalledOnce();
+ }
+ });
+
+ it("does nothing outside Windows, where a runtime ends with its server", async () => {
+ const run = vi.fn(async () => "[]");
+ for (const platform of ["linux", "darwin"] as const) expect(await stopOrphanedAntigravityRuntimes({ platform, dataDir, run })).toBe(0);
+ expect(run).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/drivers/antigravity-processes.ts b/server/drivers/antigravity-processes.ts
index 7f6ec5c77f..e2e682b42b 100644
--- a/server/drivers/antigravity-processes.ts
+++ b/server/drivers/antigravity-processes.ts
@@ -1,6 +1,10 @@
-// The runtime processes each Antigravity account has running, so a sign-out can wait for them to end.
-import type { ChildProcess } from "node:child_process";
+// The runtime processes each Antigravity account has running, so a sign-out can wait for them to end, and the ones a
+// server that has since ended left running on Windows.
+import { execFile, type ChildProcess } from "node:child_process";
+import { win32 } from "node:path";
+import { DATA_DIR } from "../config.ts";
+import { antigravityRuntimesRoot } from "../engine-roots.ts";
import { killCliTree } from "../procs.ts";
const EXIT_WAIT_MS = 7_000;
@@ -49,3 +53,82 @@ export class AntigravityProcesses {
return gone.every(Boolean);
}
}
+
+/** A runtime process as Windows lists it; start times are UTC strings, which sort as they compare. */
+export interface RuntimeProcessRow {
+ pid: number;
+ path: string;
+ started: string;
+ /** Null when the parent is gone. */
+ parentStarted: string | null;
+}
+
+const RUNTIME_IMAGES = new Set(["agy_acp_server.exe", "localharness_external.exe"]);
+
+/** The runtime processes, from this app's own releases, whose parent is gone: a parent started after its child holds a
+ * reused pid. A live parent (this server, or the runtime that started a harness) keeps its child. */
+export function orphanedRuntimeProcesses(rows: RuntimeProcessRow[], runtimesRoot: string): RuntimeProcessRow[] {
+ const root = `${win32.resolve(runtimesRoot).toLowerCase()}\\`;
+ return rows.filter((row) => {
+ const path = win32.resolve(row.path).toLowerCase();
+ return path.startsWith(root) && RUNTIME_IMAGES.has(win32.basename(path)) && (row.parentStarted === null || row.parentStarted > row.started);
+ });
+}
+
+/** The folder goes in through the environment, so no path is ever quoted into the script. */
+const WINDOWS_RUNTIME_PROCESSES = "$r = $env:OMB_AGY_RUNTIMES.TrimEnd('\\') + '\\'; $all = @(Get-CimInstance Win32_Process); $by = @{}; foreach ($p in $all) { $by[$p.ProcessId] = $p }"
+ + " ; ConvertTo-Json -Compress -InputObject @($all | Where-Object { $_.CreationDate -and $_.ExecutablePath -and $_.ExecutablePath.StartsWith($r, [StringComparison]::OrdinalIgnoreCase) }"
+ + " | ForEach-Object { $q = $by[$_.ParentProcessId]; [pscustomobject]@{ ProcessId = $_.ProcessId; ExecutablePath = $_.ExecutablePath;"
+ + " Started = $_.CreationDate.ToUniversalTime().ToString('o'); ParentStarted = $(if ($q -and $q.CreationDate) { $q.CreationDate.ToUniversalTime().ToString('o') }) } })";
+
+/** Each `pid=started` is stopped with its tree only while that pid still runs the process that was listed, and waited for:
+ * its unpacked folder stays locked until it has exited. */
+const WINDOWS_STOP_PROCESSES = "foreach ($e in $env:OMB_AGY_STOP.Split(' ')) { $id, $s = $e.Split('='); $p = Get-CimInstance Win32_Process -Filter ('ProcessId=' + [uint32]$id)"
+ + "; if ($p -and $p.CreationDate -and $p.CreationDate.ToUniversalTime().ToString('o') -eq $s) { taskkill /PID $id /T /F | Out-Null; Wait-Process -Id $id -Timeout 10 -ErrorAction SilentlyContinue } }";
+
+type PowerShell = (script: string, env: NodeJS.ProcessEnv) => Promise<string | null>;
+
+const powershell: PowerShell = (script, env) => new Promise((done) => {
+ execFile("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], {
+ encoding: "utf8", timeout: 30_000, windowsHide: true, maxBuffer: 16 * 1024 * 1024, env: { ...process.env, ...env },
+ }, (error, stdout) => done(error ? null : stdout));
+});
+
+function listedRows(listing: string | null): RuntimeProcessRow[] {
+ let rows: unknown;
+ try { rows = JSON.parse(listing ?? ""); } catch { return []; }
+ return (Array.isArray(rows) ? rows : [rows]).flatMap((row) => {
+ const { ProcessId: pid, ExecutablePath: path, Started: started, ParentStarted: parentStarted } = (row ?? {}) as Record<string, unknown>;
+ if (!Number.isInteger(pid) || typeof path !== "string" || typeof started !== "string" || !started) return [];
+ return [{ pid: pid as number, path, started, parentStarted: typeof parentStarted === "string" && parentStarted ? parentStarted : null }];
+ });
+}
+
+export interface OrphanStopOptions {
+ platform?: NodeJS.Platform;
+ dataDir?: string;
+ run?: PowerShell;
+}
+
+/** Windows keeps a child running when its parent ends: each runtime a crashed or killed server left behind keeps its memory
+ * and its unpacked folder (0.3-1.3 GB) until it is stopped. Resolves to how many were stopped, 0 when stopping failed. */
+export async function stopOrphanedAntigravityRuntimes(options: OrphanStopOptions = {}): Promise<number> {
+ if ((options.platform ?? process.platform) !== "win32") return 0;
+ const run = options.run ?? powershell;
+ const root = antigravityRuntimesRoot(options.dataDir ?? DATA_DIR);
+ const orphans = orphanedRuntimeProcesses(listedRows(await run(WINDOWS_RUNTIME_PROCESSES, { OMB_AGY_RUNTIMES: root })), root);
+ if (!orphans.length) return 0;
+ const stopped = await run(WINDOWS_STOP_PROCESSES, { OMB_AGY_STOP: orphans.map(({ pid, started }) => `${pid}=${started}`).join(" ") });
+ return stopped === null ? 0 : orphans.length;
+}
+
+let orphansStopped: Promise<number> | undefined;
+
+/** Once per server: a runtime this server starts keeps it as its parent while it runs. */
+export function stopOrphanedAntigravityRuntimesOnce(): Promise<number> {
+ orphansStopped ??= stopOrphanedAntigravityRuntimes().catch((error) => {
+ console.warn(`antigravity: could not stop runtimes left by an earlier run: ${error instanceof Error ? error.message : String(error)}`);
+ return 0;
+ });
+ return orphansStopped;
+}
diff --git a/server/drivers/antigravity.ts b/server/drivers/antigravity.ts
index fd1dbb18e0..41f943af30 100644
--- a/server/drivers/antigravity.ts
+++ b/server/drivers/antigravity.ts
@@ -57,7 +57,7 @@ import {
import { ANTIGRAVITY_NATIVE_CLI } from "./antigravity-cli-install.ts";
import { acpFileEditWithin } from "./permission-command.ts";
import { resolveAntigravityReleaseAsset } from "./antigravity-release.ts";
-import { AntigravityProcesses } from "./antigravity-processes.ts";
+import { AntigravityProcesses, stopOrphanedAntigravityRuntimesOnce } from "./antigravity-processes.ts";
import { VERIFICATION_TEMP_KEY, scheduleAntigravityTempSweep } from "./antigravity-temp.ts";
import { augmentedPath } from "../env-path.ts";
import { killCliTree } from "../procs.ts";
@@ -341,6 +341,12 @@ export const AntigravityDriver: ProviderDriver<AcpConfig> = {
const base = await AcpAntigravityDriver.create(input);
scheduleAntigravityTempSweep(input.instanceId);
scheduleAntigravityTempSweep(VERIFICATION_TEMP_KEY);
+ // A stopped runtime's unpacked folder can be removed only once it has ended.
+ void stopOrphanedAntigravityRuntimesOnce().then((stopped) => {
+ if (!stopped) return;
+ scheduleAntigravityTempSweep(input.instanceId);
+ scheduleAntigravityTempSweep(VERIFICATION_TEMP_KEY);
+ });
const auth = new AntigravityAuthController(() => {
noteAntigravitySignedIn(antigravityTokenPath(input.instanceId));
void base.refreshModels?.();