Skip to content

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

Antigravity cleanup: count only confirmed stops, read UTF-8 paths, rescan after a running sweep

AdityaUmale419b832901b6
diff --git a/server/drivers/antigravity-processes.test.ts b/server/drivers/antigravity-processes.test.ts
index 3b5a5d61cc..651cb84bf4 100644
--- a/server/drivers/antigravity-processes.test.ts
+++ b/server/drivers/antigravity-processes.test.ts
@@ -56,7 +56,7 @@ describe("runtimes an earlier server left running on Windows", () => {
});
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([
+ const run = vi.fn(async (_script: string, env: NodeJS.ProcessEnv) => env.OMB_AGY_RUNTIMES === undefined ? "41\r\n" : 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" },
@@ -68,6 +68,22 @@ describe("runtimes an earlier server left running on Windows", () => {
expect(run.mock.calls[1]![0]).toContain("taskkill /PID $id /T /F");
});
+ it("counts only the runtimes the stop confirms are gone", async () => {
+ const listed = (pid: number) => ({ ProcessId: pid, ExecutablePath: `${release}\\agy_acp_server.exe`, Started: "2026-11-21T08:00:00.0000000Z", ParentStarted: null });
+ for (const [confirmed, count] of [["", 0], ["41\r\n", 1], ["41\r\n42\r\n99\r\n", 2]] as const) {
+ const run = vi.fn(async (_script: string, env: NodeJS.ProcessEnv) => env.OMB_AGY_RUNTIMES === undefined ? confirmed : JSON.stringify([listed(41), listed(42)]));
+ expect(await stopOrphanedAntigravityRuntimes({ platform: "win32", dataDir, run })).toBe(count);
+ }
+ });
+
+ it("reads a data folder with non-ASCII letters the way PowerShell writes it", async () => {
+ const homeDir = "C:\\Users\\René\\.openmausbot";
+ const listing = `\uFEFF${JSON.stringify([{ ProcessId: 41, ExecutablePath: `${homeDir}\\tools\\antigravity-acp\\win32-x64\\agy_acp_server.exe`, Started: "2026-11-21T08:00:00.0000000Z", ParentStarted: null }])}`;
+ const run = vi.fn(async (_script: string, env: NodeJS.ProcessEnv) => env.OMB_AGY_RUNTIMES === undefined ? "41" : listing);
+ expect(await stopOrphanedAntigravityRuntimes({ platform: "win32", dataDir: homeDir, run })).toBe(1);
+ expect(run.mock.calls[0]![0]).toContain("[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false");
+ });
+
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 },
diff --git a/server/drivers/antigravity-processes.ts b/server/drivers/antigravity-processes.ts
index e2e682b42b..67d12bab41 100644
--- a/server/drivers/antigravity-processes.ts
+++ b/server/drivers/antigravity-processes.ts
@@ -76,15 +76,16 @@ export function orphanedRuntimeProcesses(rows: RuntimeProcessRow[], runtimesRoot
}
/** 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 }"
+const WINDOWS_RUNTIME_PROCESSES = "[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; $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. */
+ * its unpacked folder stays locked until it has exited. Writes the pid of each one stopped and gone, one per line. */
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 } }";
+ + "; if ($p -and $p.CreationDate -and $p.CreationDate.ToUniversalTime().ToString('o') -eq $s) { taskkill /PID $id /T /F | Out-Null"
+ + "; if ($LASTEXITCODE -eq 0) { Wait-Process -Id $id -Timeout 10 -ErrorAction SilentlyContinue; if (-not (Get-Process -Id $id -ErrorAction SilentlyContinue)) { $id } } } }; exit 0";
type PowerShell = (script: string, env: NodeJS.ProcessEnv) => Promise<string | null>;
@@ -96,7 +97,7 @@ const powershell: PowerShell = (script, env) => new Promise((done) => {
function listedRows(listing: string | null): RuntimeProcessRow[] {
let rows: unknown;
- try { rows = JSON.parse(listing ?? ""); } catch { return []; }
+ try { rows = JSON.parse((listing ?? "").replace(/^\uFEFF/, "")); } 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 [];
@@ -111,7 +112,7 @@ export interface OrphanStopOptions {
}
/** 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. */
+ * and its unpacked folder (0.3-1.3 GB) until it is stopped. Resolves to how many were stopped and have exited. */
export async function stopOrphanedAntigravityRuntimes(options: OrphanStopOptions = {}): Promise<number> {
if ((options.platform ?? process.platform) !== "win32") return 0;
const run = options.run ?? powershell;
@@ -119,7 +120,8 @@ export async function stopOrphanedAntigravityRuntimes(options: OrphanStopOptions
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;
+ const gone = new Set(stopped?.split(/\s+/));
+ return orphans.filter(({ pid }) => gone.has(String(pid))).length;
}
let orphansStopped: Promise<number> | undefined;
diff --git a/server/drivers/antigravity-temp.test.ts b/server/drivers/antigravity-temp.test.ts
index f7428cf10d..895e5a5b2f 100644
--- a/server/drivers/antigravity-temp.test.ts
+++ b/server/drivers/antigravity-temp.test.ts
@@ -157,6 +157,17 @@ describe("the automatic sweep", () => {
expect(readdirSync(directory).sort()).toEqual([hexName(0x1111), hexName(0x4444), decimalName(17348), "keep-me", "tmp_python_scratch"].sort());
});
+ it("scans again for a sweep asked for while one is running", async () => {
+ const dataDir = tempRoot("rerun");
+ const directory = antigravityTempDir(dataDir, "work");
+ const folder = unpackFolder(directory, hexName(0x2222));
+ const running = sweepAntigravityTemp("work", { dataDir, isAlive: () => true });
+ const after = sweepAntigravityTemp("work", { dataDir, isAlive: () => false });
+ expect(await running).toBe(0);
+ expect(await after).toBe(1);
+ expect(existsSync(folder)).toBe(false);
+ });
+
it("counts a process it may not inspect (EPERM) as alive", async () => {
const dataDir = tempRoot("eperm");
const directory = antigravityTempDir(dataDir, "work");
diff --git a/server/drivers/antigravity-temp.ts b/server/drivers/antigravity-temp.ts
index c0a4c7950a..7f49c67288 100644
--- a/server/drivers/antigravity-temp.ts
+++ b/server/drivers/antigravity-temp.ts
@@ -267,13 +267,25 @@ function retryableRemoveError(error: unknown): boolean {
}
const sweeps = new Map<string, Promise<number>>();
+const sweepsAfter = new Map<string, Promise<number>>();
-/** Touches nothing outside dataDir/tmp/agy/<instance>. */
+/** Touches nothing outside dataDir/tmp/agy/<instance>. A sweep asked for while one runs scans again once it ends, since a
+ * folder whose process ended during that scan was already passed over; every such request shares that one scan. */
export function sweepAntigravityTemp(instanceId: string, options: AntigravityTempOptions = {}): Promise<number> {
const dataDir = options.dataDir ?? DATA_DIR;
const key = antigravityTempDir(dataDir, instanceId);
const running = sweeps.get(key);
- if (running) return running;
+ if (running) {
+ let after = sweepsAfter.get(key);
+ if (!after) {
+ after = running.catch(() => 0).then(() => {
+ sweepsAfter.delete(key);
+ return sweepAntigravityTemp(instanceId, options);
+ });
+ sweepsAfter.set(key, after);
+ }
+ return after;
+ }
const sweep = (async () => {
const isAlive = options.isAlive ?? processIsAlive;
let removed = 0;