Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: free up disk space after updates

ogsamrat6e602a00ff64
diff --git a/apps/app/src/app/lib/desktop.ts b/apps/app/src/app/lib/desktop.ts
index c433fc12..841fe975 100644
--- a/apps/app/src/app/lib/desktop.ts
+++ b/apps/app/src/app/lib/desktop.ts
@@ -848,6 +848,7 @@ const {
opencodeMcpAuth,
setWindowDecorations,
openLogsFolder,
+ freeUpSpace,
} = desktopBridge;
export {
@@ -928,4 +929,5 @@ export {
opencodeMcpAuth,
setWindowDecorations,
openLogsFolder,
+ freeUpSpace,
};
diff --git a/apps/app/src/i18n/locales/en.ts b/apps/app/src/i18n/locales/en.ts
index 971c765a..f977b84d 100644
--- a/apps/app/src/i18n/locales/en.ts
+++ b/apps/app/src/i18n/locales/en.ts
@@ -1530,6 +1530,18 @@ export default {
"settings.diagnostics_open_logs_done": "Opened the logs folder",
"settings.diagnostics_open_logs_failed": "Could not open the logs folder",
"settings.diagnostics_section_title": "Diagnostics",
+ "settings.free_space_section_title": "Storage",
+ "settings.free_space_card_title": "Free up space",
+ "settings.free_space_card_desc": "Removes what the app no longer needs: update downloads that are installed, stopped downloads, old logs and crash reports, and temporary files. The installer for Restore previous version stays. Chats, projects, settings and anything not uploaded yet are never touched. This also runs on its own after an update.",
+ "settings.free_space_check": "Check",
+ "settings.free_space_clean": "Free up space",
+ "settings.free_space_found": "{size} can be freed ({count} items)",
+ "settings.free_space_done": "Freed {size}",
+ "settings.free_space_nothing": "Nothing to remove",
+ "settings.free_space_in_use": "in use, kept",
+ "settings.free_space_busy": "A cleanup is already running. Try again in a moment.",
+ "settings.free_space_update_pending": "An update is downloading or waiting to install. Try again after it is installed.",
+ "settings.free_space_failed": "Could not free up space",
"settings.diagnostics_unavailable": "Diagnostics unavailable.",
"settings.disable_developer_mode": "Disable Developer Mode",
"settings.disabled": "Disabled",
diff --git a/apps/app/src/react-app/domains/settings/pages/free-space-section.tsx b/apps/app/src/react-app/domains/settings/pages/free-space-section.tsx
new file mode 100644
index 00000000..ff105c10
--- /dev/null
+++ b/apps/app/src/react-app/domains/settings/pages/free-space-section.tsx
@@ -0,0 +1,102 @@
+/** @jsxImportSource react */
+import { useState } from "react";
+import { HardDrive, Search, Trash2 } from "lucide-react";
+
+import { t } from "../../../../i18n";
+import { freeUpSpace } from "../../../../app/lib/desktop";
+import { isElectronRuntime } from "../../../../app/utils";
+
+export type FreeSpaceItem = { kind: string; path: string; bytes: number; size: string; reason: string; inUse: boolean };
+export type FreeSpaceResult = { ok: boolean; skipped: string | null; dryRun: boolean; freedBytes: number; freed: string; items: FreeSpaceItem[] };
+export type FreeSpaceDeps = { freeUpSpace: (options: { dryRun: boolean }) => Promise<FreeSpaceResult> };
+
+/** One status line for a result. */
+export function freeSpaceMessage(result: FreeSpaceResult): string {
+ if (!result.ok) return result.skipped === "update-pending" ? t("settings.free_space_update_pending") : t("settings.free_space_busy");
+ const removable = result.items.filter((item) => !item.inUse);
+ if (removable.length === 0) return t("settings.free_space_nothing");
+ return result.dryRun
+ ? t("settings.free_space_found", { size: result.freed, count: String(removable.length) })
+ : t("settings.free_space_done", { size: result.freed });
+}
+
+export type FreeSpaceSectionProps = {
+ /** Shown only in the desktop app; defaults to the current runtime. */
+ available?: boolean;
+ /** Test seam. */
+ deps?: FreeSpaceDeps;
+};
+
+/**
+ * Settings > General > Storage: what the app no longer needs (installed
+ * update downloads, stopped downloads, old logs, old crash reports, temp files
+ * of runs that stopped). "Check" only lists; "Free up space" removes those.
+ * Chats, projects, settings and anything not uploaded yet are never touched.
+ */
+export function FreeSpaceSection(props: FreeSpaceSectionProps) {
+ const [busy, setBusy] = useState<"check" | "clean" | null>(null);
+ const [result, setResult] = useState<FreeSpaceResult | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const available = props.available ?? isElectronRuntime();
+ if (!available) return null;
+
+ async function run(dryRun: boolean) {
+ const deps = props.deps ?? { freeUpSpace: (options) => freeUpSpace(options) as Promise<FreeSpaceResult> };
+ setBusy(dryRun ? "check" : "clean");
+ setError(null);
+ try {
+ setResult(await deps.freeUpSpace({ dryRun }));
+ } catch (cause) {
+ setError(cause instanceof Error && cause.message ? cause.message : String(cause ?? ""));
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ const buttonClass = "inline-flex items-center gap-1.5 rounded-lg border border-dls-border px-3 py-2 text-[12px] text-dls-text hover:bg-dls-hover disabled:opacity-50";
+ const listed = result?.items ?? [];
+
+ return (
+ <div className="space-y-3" data-testid="settings-free-space">
+ <div className="text-[11px] font-semibold uppercase tracking-[0.15em] text-dls-secondary">
+ {t("settings.free_space_section_title")}
+ </div>
+ <div className="flex items-start gap-4 rounded-2xl border border-dls-border bg-dls-surface p-4">
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-dls-border bg-dls-hover">
+ <HardDrive size={17} className="text-dls-secondary" />
+ </div>
+ <div className="min-w-0 flex-1 space-y-3">
+ <div>
+ <div className="text-[13px] font-medium text-dls-text">{t("settings.free_space_card_title")}</div>
+ <div className="text-[11px] text-dls-secondary">{t("settings.free_space_card_desc")}</div>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <button type="button" className={buttonClass} disabled={busy !== null} onClick={() => void run(true)}>
+ <Search size={13} />
+ {t("settings.free_space_check")}
+ </button>
+ <button type="button" className={buttonClass} disabled={busy !== null} onClick={() => void run(false)}>
+ <Trash2 size={13} />
+ {t("settings.free_space_clean")}
+ </button>
+ </div>
+ {result ? (
+ <div className="space-y-1" role="status" data-testid="settings-free-space-status">
+ <div className="text-[11px] text-dls-secondary">{freeSpaceMessage(result)}</div>
+ {listed.length > 0 ? (
+ <ul className="max-h-40 space-y-0.5 overflow-auto text-[11px] text-dls-secondary">
+ {listed.map((item) => (
+ <li key={item.path} className="truncate" title={item.path}>
+ {item.inUse ? t("settings.free_space_in_use") : item.size} · {item.reason} · {item.path}
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ </div>
+ ) : null}
+ {error ? <div className="text-[11px] text-red-400" role="status">{t("settings.free_space_failed")}: {error}</div> : null}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/app/src/react-app/domains/settings/pages/general-view.tsx b/apps/app/src/react-app/domains/settings/pages/general-view.tsx
index b885f409..1f2d8f63 100644
--- a/apps/app/src/react-app/domains/settings/pages/general-view.tsx
+++ b/apps/app/src/react-app/domains/settings/pages/general-view.tsx
@@ -41,6 +41,7 @@ import {
type ApprovalsClient,
} from "../approval-mode";
import { DiagnosticsSection } from "./diagnostics-section";
+import { FreeSpaceSection } from "./free-space-section";
import { keptPendingLine, sendPendingBeforeSignOut } from "../sign-out-uploads";
import { BEST_PRACTICES_HELP, useBestPractices, type BestPracticesClient } from "../best-practices";
import { AGENT_ASSIST_ITEMS, useAgentAssist, type AgentAssistClient } from "../agent-assist";
@@ -591,6 +592,8 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {
/>
) : null}
+ <FreeSpaceSection />
+
<DiagnosticsSection buildBundle={props.buildDiagnosticsBundle} />
</div>
);
diff --git a/apps/app/tests/settings-free-space-section.test.tsx b/apps/app/tests/settings-free-space-section.test.tsx
new file mode 100644
index 00000000..b06b9f68
--- /dev/null
+++ b/apps/app/tests/settings-free-space-section.test.tsx
@@ -0,0 +1,31 @@
+/** @jsxImportSource react */
+import { describe, expect, test } from "bun:test";
+import { renderToStaticMarkup } from "react-dom/server";
+
+import { FreeSpaceSection, freeSpaceMessage, type FreeSpaceResult } from "../src/react-app/domains/settings/pages/free-space-section";
+
+const result = (over: Partial<FreeSpaceResult> = {}): FreeSpaceResult => ({ ok: true, skipped: null, dryRun: true, freedBytes: 0, freed: "0 B", items: [], ...over });
+
+describe("settings free up space section", () => {
+ test("renders Check and Free up space in the desktop app, and says what is never touched", () => {
+ const markup = renderToStaticMarkup(<FreeSpaceSection available deps={{ freeUpSpace: async () => result() }} />);
+ expect(markup).toContain("Storage");
+ expect(markup).toContain("Check");
+ expect(markup).toContain("Free up space");
+ expect(markup).toContain("Restore previous version stays");
+ expect(markup).toContain("never touched");
+ });
+
+ test("is hidden outside the desktop app", () => {
+ expect(renderToStaticMarkup(<FreeSpaceSection available={false} />)).toBe("");
+ });
+
+ test("status lines: found, freed, nothing, update pending, busy", () => {
+ const items = [{ kind: "installer", path: "/x/pending", bytes: 1, size: "180 MB", reason: "update 3.6.4 installed", inUse: false }];
+ expect(freeSpaceMessage(result({ freed: "180 MB", items }))).toBe("180 MB can be freed (1 items)");
+ expect(freeSpaceMessage(result({ dryRun: false, freed: "180 MB", items }))).toBe("Freed 180 MB");
+ expect(freeSpaceMessage(result())).toBe("Nothing to remove");
+ expect(freeSpaceMessage(result({ ok: false, skipped: "update-pending" }))).toContain("waiting to install");
+ expect(freeSpaceMessage(result({ ok: false, skipped: "busy" }))).toContain("already running");
+ });
+});
diff --git a/apps/desktop/electron/disk-cleanup.test.mjs b/apps/desktop/electron/disk-cleanup.test.mjs
new file mode 100644
index 00000000..14dfeca4
--- /dev/null
+++ b/apps/desktop/electron/disk-cleanup.test.mjs
@@ -0,0 +1,239 @@
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { cleanupDue, cleanupPass, installerVersion, LOCK_FILE, MARKER_FILE, PACKAGES_FILE, rememberDownloadedPackage, runAutomatic, scheduleDiskCleanup, updaterCacheDirName } from "./disk-cleanup/index.mjs";
+import { acquireLock, versionsToRemove } from "./disk-cleanup/retention.mjs";
+
+const DAY = 86_400_000;
+const MB = 1024 * 1024;
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+
+function fixture(t) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "desk-clean-"));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const paths = { userData: path.join(root, "userData"), logs: path.join(root, "userData", "logs"), temp: path.join(root, "tmp"), updaterCache: path.join(root, "cache", "omnirush-updater") };
+ for (const dir of Object.values(paths)) fs.mkdirSync(dir, { recursive: true });
+ return { root, paths };
+}
+
+function write(file, bytes = 1024) {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, Buffer.alloc(bytes));
+ return file;
+}
+
+function age(p, ms) {
+ const at = new Date(Date.now() - ms);
+ fs.utimesSync(p, at, at);
+}
+
+/** What the cleanup must never touch. */
+function userData(paths) {
+ const files = [
+ "app-recovery-cache/OmniRush-Setup-3.6.3.exe", "app-recovery-cache/metadata.json", "app-recovery.v1.json",
+ "engine-data/omnirush/opencode.db", "Partitions/omnirush-browser/Cookies", "IndexedDB/x/1.ldb", "Local Storage/leveldb/1.log",
+ "start-reset-20261001/settings.json", "logs/omnirush-server.log", "start-reports.json",
+ ].map((rel) => write(path.join(paths.userData, rel)));
+ for (const f of files) age(f, 400 * DAY);
+ return files;
+}
+
+test("the shared retention module is the CLI's (PARITY.sha256)", () => {
+ const dir = path.join(HERE, "disk-cleanup");
+ const rows = fs.readFileSync(path.join(dir, "PARITY.sha256"), "utf8").split("\n").filter((line) => line && !line.startsWith("#"));
+ assert.ok(rows.length >= 2);
+ for (const row of rows) {
+ const [hash, name] = row.split(/\s+/);
+ assert.equal(createHash("sha256").update(fs.readFileSync(path.join(dir, name))).digest("hex"), hash, `${name}: port it to omnirush-cli (src/disk-cleanup/) and update PARITY.sha256 in both`);
+ }
+});
+
+test("installer versions are read from the file names electron-builder writes", () => {
+ assert.equal(installerVersion("OmniRush.ai-Setup-3.6.4.exe"), "3.6.4");
+ assert.equal(installerVersion("OmniRush.ai-3.7.0-arm64-mac.zip"), "3.7.0");
+ assert.equal(installerVersion("omnirush-desktop_3.6.10_amd64.deb"), "3.6.10");
+ // The names this repo's releases publish.
+ for (const name of ["omnirush-linux-amd64-3.6.4.deb", "omnirush-linux-x86_64-3.6.4.AppImage", "omnirush-linux-aarch64-3.6.4.rpm", "omnirush-mac-arm64-3.6.4.dmg", "omnirush-win-x64-3.6.4.exe"]) assert.equal(installerVersion(name), "3.6.4", name);
+ assert.equal(installerVersion("installer.exe"), null);
+ assert.equal(installerVersion("omnirush-win-x64-3.6.5-alpha.2.exe"), "3.6.5-alpha.2");
+ assert.equal(installerVersion("OmniRush.ai-3.6.4-arm64-mac.zip"), "3.6.4");
+ assert.deepEqual(versionsToRemove(["3.6.1", "3.6.2", "3.6.3", "3.6.4"], { current: "3.6.4" }), ["3.6.1", "3.6.2"]);
+});
+
+test("updaterCacheDirName comes from app-update.yml and is never a path", async (t) => {
+ const { root } = fixture(t);
+ fs.writeFileSync(path.join(root, "app-update.yml"), "provider: github\nupdaterCacheDirName: omnirushdesktop-updater\n");
+ assert.equal(updaterCacheDirName({ resourcesPath: root }), "omnirushdesktop-updater");
+ fs.writeFileSync(path.join(root, "app-update.yml"), "updaterCacheDirName: ../../home\n");
+ assert.equal(updaterCacheDirName({ resourcesPath: root }), null);
+ assert.equal(updaterCacheDirName({ resourcesPath: path.join(root, "none") }), null);
+});
+
+test("three successive updates: the installed installers go, a newer downloaded one and the recovery installer stay; user data never touched; idempotent", async (t) => {
+ const { paths } = fixture(t);
+ const data = userData(paths);
+ // 3.6.2 → 3.6.3 → 3.6.4: what each update left.
+ write(path.join(paths.updaterCache, "pending", "OmniRush.ai-Setup-3.6.4.exe"), 3 * MB);
+ fs.writeFileSync(path.join(paths.updaterCache, "pending", "update-info.json"), JSON.stringify({ fileName: "OmniRush.ai-Setup-3.6.4.exe" }));
+ write(path.join(paths.updaterCache, "installer.exe"), 2 * MB);
+ write(path.join(paths.updaterCache, "current.blockmap"), 1000);
+ write(path.join(paths.userData, "app-update-installer", "OmniRush.ai-3.6.3-arm64.dmg"), 2 * MB);
+ write(path.join(paths.userData, "app-update-installer", "OmniRush.ai-3.6.5-arm64.dmg.part"), MB);
+ const dry = await cleanupPass({ paths, currentVersion: "3.6.4", dryRun: true });
+ assert.ok(dry.freed >= 8 * MB, String(dry.freed));
+ assert.ok(fs.existsSync(path.join(paths.updaterCache, "pending")), "dry run removes nothing");
+ const pass = await cleanupPass({ paths, currentVersion: "3.6.4" });
+ assert.ok(!fs.existsSync(path.join(paths.updaterCache, "pending")));
+ assert.ok(!fs.existsSync(path.join(paths.updaterCache, "installer.exe")));
+ assert.ok(!fs.existsSync(path.join(paths.userData, "app-update-installer", "OmniRush.ai-3.6.3-arm64.dmg")));
+ assert.ok(!fs.existsSync(path.join(paths.userData, "app-update-installer", "OmniRush.ai-3.6.5-arm64.dmg.part")));
+ assert.equal(pass.freed, dry.freed);
+ for (const file of data) assert.ok(fs.existsSync(file), `${file} kept`);
+ assert.equal((await cleanupPass({ paths, currentVersion: "3.6.4" })).items.length, 0, "a second pass has nothing to do");
+});
+
+test("an update downloaded but not installed yet (newer than the running version) stays", async (t) => {
+ const { paths } = fixture(t);
+ write(path.join(paths.updaterCache, "pending", "OmniRush.ai-Setup-3.6.5.exe"), MB);
+ fs.writeFileSync(path.join(paths.updaterCache, "pending", "update-info.json"), JSON.stringify({ fileName: "OmniRush.ai-Setup-3.6.5.exe" }));
+ write(path.join(paths.userData, "app-update-installer", "OmniRush.ai-3.6.5-arm64.dmg"), MB);
+ await cleanupPass({ paths, currentVersion: "3.6.4" });
+ assert.ok(fs.existsSync(path.join(paths.updaterCache, "pending", "OmniRush.ai-Setup-3.6.5.exe")));
+ assert.ok(fs.existsSync(path.join(paths.userData, "app-update-installer", "OmniRush.ai-3.6.5-arm64.dmg")));
+ // Protected paths (an update in progress) stay even when old.
+ const staged = write(path.join(paths.userData, "app-update-installer", "OmniRush.ai-3.6.3-arm64.zip"));
+ await cleanupPass({ paths, currentVersion: "3.6.4", protect: [staged] });
+ assert.ok(fs.existsSync(staged));
+});
+
+test("Linux packages in Downloads: only with Free up space, only the ones this app recorded, unchanged and installed", async (t) => {
+ const { root, paths } = fixture(t);
+ const downloads = path.join(root, "Downloads");
+ const old = write(path.join(downloads, "omnirush-desktop_3.6.3_amd64.deb"), 2 * MB);
+ const edited = write(path.join(downloads, "omnirush-desktop_3.6.2_amd64.deb"), MB);
+ const newer = write(path.join(downloads, "omnirush-desktop_3.6.5_amd64.deb"), MB);
+ const theirs = write(path.join(downloads, "omnirush-desktop_3.6.1_amd64.deb"), MB);
+ rememberDownloadedPackage(paths.userData, old, "3.6.3");
+ rememberDownloadedPackage(paths.userData, edited, "3.6.2");
+ rememberDownloadedPackage(paths.userData, newer, "3.6.5");
+ fs.appendFileSync(edited, "changed by the user");
+ await cleanupPass({ paths, currentVersion: "3.6.4" });
+ assert.ok(fs.existsSync(old), "the automatic pass never touches Downloads");
+ await cleanupPass({ paths, currentVersion: "3.6.4", includeDownloads: true });
+ assert.ok(!fs.existsSync(old));
+ assert.ok(fs.existsSync(edited), "changed since: the user's file");
+ assert.ok(fs.existsSync(newer), "not installed yet");
+ assert.ok(fs.existsSync(theirs), "never recorded: never touched");
+ const left = JSON.parse(fs.readFileSync(path.join(paths.userData, PACKAGES_FILE), "utf8")).packages.map((p) => path.basename(p.path));
+ assert.deepEqual(left, ["omnirush-desktop_3.6.5_amd64.deb"]);
+});
+
+test("temp leftovers of stopped updates and runs go by exact name and age; other temp files stay", async (t) => {
+ const { paths } = fixture(t);
+ const make = (name, days, dir = true) => { const p = path.join(paths.temp, name); if (dir) { fs.mkdirSync(p); age(write(path.join(p, "f")), days * DAY); } else write(p); age(p, days * DAY); return p; };
+ const gone = [make("omnirush-update-Ab12Cd", 2), make("omnirush-swap-4242.sh", 2, false), make("omnirush-engine2-import-x1y2z3", 4), make("omnirush-login-sync-abcdef", 4)];
+ const kept = [make("omnirush-update-Fresh1", 0.1), make("omnirush-engine2-import-young1", 1), make("omnirush-upload-4242", 30), make("omnirush-update-notmine-x", 30), make("someone-else", 30)];
+ await cleanupPass({ paths, currentVersion: "3.6.4" });
+ for (const p of gone) assert.ok(!fs.existsSync(p), p);
+ for (const p of kept) assert.ok(fs.existsSync(p), p);
+});
+
+test("logs: update-install.log rotates past 10 MB; rotated logs over 30 days go; the server log stays", async (t) => {
+ const { paths } = fixture(t);
+ const install = write(path.join(paths.logs, "update-install.log"), 11 * MB);
+ const oldRotated = write(path.join(paths.logs, "omnirush-server.log.3"), MB);
+ age(oldRotated, 40 * DAY);
+ const server = write(path.join(paths.logs, "omnirush-server.log"), 5 * MB);
+ age(server, 40 * DAY);
+ await cleanupPass({ paths, currentVersion: "3.6.4" });
+ assert.ok(!fs.existsSync(install));
+ assert.equal(fs.statSync(`${install}.1`).size, 11 * MB);
+ assert.ok(!fs.existsSync(oldRotated));
+ assert.ok(fs.existsSync(server), "a live log is never removed");
+});
+
+test("crash dumps older than 30 days go; the Crashpad database and fresh dumps stay", async (t) => {
+ const { paths } = fixture(t);
+ const old = write(path.join(paths.userData, "Crashpad", "completed", "a.dmp"));
+ age(old, 40 * DAY);
+ const fresh = write(path.join(paths.userData, "Crashpad", "completed", "b.dmp"));
+ const settings = write(path.join(paths.userData, "Crashpad", "settings.dat"));
+ age(settings, 400 * DAY);
+ await cleanupPass({ paths, currentVersion: "3.6.4" });
+ assert.ok(!fs.existsSync(old));
+ assert.ok(fs.existsSync(fresh) && fs.existsSync(settings));
+});
+
+test("Windows-locked files are kept and reported as in use, never thrown; the rest still goes", { skip: process.getuid?.() === 0 }, async (t) => {
+ const { paths } = fixture(t);
+ write(path.join(paths.updaterCache, "pending", "OmniRush.ai-Setup-3.6.3.exe"), MB);
+ fs.writeFileSync(path.join(paths.updaterCache, "pending", "update-info.json"), JSON.stringify({ fileName: "OmniRush.ai-Setup-3.6.3.exe" }));
+ write(path.join(paths.updaterCache, "installer.exe"), MB);
+ fs.chmodSync(path.join(paths.updaterCache, "pending"), 0o500);
+ const pass = await cleanupPass({ paths, currentVersion: "3.6.4" });
+ fs.chmodSync(path.join(paths.updaterCache, "pending"), 0o700);
+ assert.ok(pass.items.some((i) => i.path.endsWith("pending") && i.locked));
+ assert.ok(!fs.existsSync(path.join(paths.updaterCache, "installer.exe")));
+ assert.equal(pass.locked, 1);
+});
+
+test("one pass at a time; the automatic pass is due once a day and at once after an update; off switch", async (t) => {
+ const { paths } = fixture(t);
+ const release = acquireLock(path.join(paths.userData, LOCK_FILE));
+ assert.equal((await cleanupPass({ paths, currentVersion: "3.6.4" })).skipped, "busy");
+ release();
+ assert.equal(cleanupDue(paths.userData, "3.6.4"), true);
+ await runAutomatic({ paths, currentVersion: "3.6.4", log: () => {} });
+ assert.equal(JSON.parse(fs.readFileSync(path.join(paths.userData, MARKER_FILE), "utf8")).version, "3.6.4");
+ assert.equal(cleanupDue(paths.userData, "3.6.4"), false);
+ assert.equal(cleanupDue(paths.userData, "3.6.5"), true);
+ assert.equal(cleanupDue(paths.userData, "3.6.5", { env: { OMNIRUSH_DISK_CLEANUP: "off" } }), false);
+});
+
+test("scheduleDiskCleanup runs later, through the updater's queue, never at start", async (t) => {
+ const { paths } = fixture(t);
+ const app = { isPackaged: true, getPath: (name) => ({ userData: paths.userData, logs: paths.logs, home: path.dirname(paths.userData) })[name] };
+ const queued = [];
+ const timer = scheduleDiskCleanup({ app, currentVersion: "3.6.4", delayMs: 5, whenIdle: (fn) => { queued.push(fn); return { skipped: "update-pending" }; }, log: () => {} });
+ assert.ok(timer);
+ assert.equal(queued.length, 0);
+ await new Promise((resolve) => setTimeout(resolve, 40));
+ assert.equal(queued.length, 1, "handed to the updater queue");
+ assert.ok(!fs.existsSync(path.join(paths.userData, MARKER_FILE)), "skipped while an update waits");
+});
+
+test("pre-releases: a waiting alpha.2 stays while alpha.1 runs; a waiting stable stays while its alpha runs; an installed alpha goes", async (t) => {
+ const { paths } = fixture(t);
+ const pending = (name) => {
+ fs.rmSync(path.join(paths.updaterCache, "pending"), { recursive: true, force: true });
+ write(path.join(paths.updaterCache, "pending", name), 1000);
+ fs.writeFileSync(path.join(paths.updaterCache, "pending", "update-info.json"), JSON.stringify({ fileName: name }));
+ };
+ pending("omnirush-win-x64-3.6.5-alpha.2.exe");
+ await cleanupPass({ paths, currentVersion: "3.6.5-alpha.1" });
+ assert.ok(fs.existsSync(path.join(paths.updaterCache, "pending")), "alpha.2 waits");
+ pending("omnirush-win-x64-3.6.4.exe");
+ await cleanupPass({ paths, currentVersion: "3.6.4-alpha.3" });
+ assert.ok(fs.existsSync(path.join(paths.updaterCache, "pending")), "the stable waits");
+ pending("omnirush-win-x64-3.6.5-alpha.2.exe");
+ await cleanupPass({ paths, currentVersion: "3.6.5-alpha.2" });
+ assert.ok(!fs.existsSync(path.join(paths.updaterCache, "pending")), "installed");
+});
+
+test("a temp folder with a socket in it (a live channel) stays however old", { skip: process.platform === "win32" }, async (t) => {
+ const { paths } = fixture(t);
+ const net = await import("node:net");
+ const dir = path.join(paths.temp, "omnirush-login-sync-Sock01");
+ fs.mkdirSync(dir);
+ const server = net.createServer();
+ await new Promise((resolve) => server.listen(path.join(dir, "s.sock"), () => resolve(undefined)));
+ age(dir, 10 * DAY);
+ await cleanupPass({ paths, currentVersion: "3.6.4" });
+ server.close();
+ assert.ok(fs.existsSync(dir));
+});
diff --git a/apps/desktop/electron/disk-cleanup/PARITY.sha256 b/apps/desktop/electron/disk-cleanup/PARITY.sha256
new file mode 100644
index 00000000..3e422d0b
--- /dev/null
+++ b/apps/desktop/electron/disk-cleanup/PARITY.sha256
@@ -0,0 +1,4 @@
+# Disk retention rules (log caps, version retention, locks, Windows-locked files): the same files in omnirush-cli (src/disk-cleanup/) and omnirush-gui (apps/desktop/electron/disk-cleanup/).
+# A change to one must be ported to the other and this list updated in both.
+2b77be63658209702e963d0ea39b94fb19a055ef212999ac5af82b816df6ed78 retention.mjs
+ebeef9e976f117736a448298d68e71eb1f107514e8f17d58f441f04bfab4a61d retention.d.mts
diff --git a/apps/desktop/electron/disk-cleanup/index.mjs b/apps/desktop/electron/disk-cleanup/index.mjs
new file mode 100644
index 00000000..6846e7d8
--- /dev/null
+++ b/apps/desktop/electron/disk-cleanup/index.mjs
@@ -0,0 +1,373 @@
+// What the desktop app lets go of so updates do not keep eating disk space:
+// - the update installer electron-updater keeps after it was installed
+// (<cache>/<updaterCacheDirName>/pending, its installer.exe/blockmap copies)
+// - our own installer cache (app-update-installer: a macOS DMG/zip) once that
+// version or a newer one runs
+// - with "Free up space" only: Linux packages (.deb/.rpm/.pacman) this app
+// itself downloaded into Downloads, once that version or a newer one runs
+// (only files it recorded, unchanged)
+// - update staging folders and swap scripts a stopped macOS update left in temp
+// - logs: update-install.log past 10 MB (one rotated copy), rotated logs past
+// 30 days or over 50 MB together
+// - Chromium crash dumps (Crashpad) older than 30 days
+// - temp folders crashed runs left behind (3+ days old)
+//
+// Kept on purpose: the "Restore previous version" installer (app-recovery-cache,
+// one version), a downloaded update not installed yet, chats, projects,
+// settings, sign-in, browser logins, the upload and sync queues (what is not sent
+// yet; they bound themselves), Reset app data backups, the engine's data.
+// Sandbox images: the local server removes old ones itself (apps/server/src/box).
+//
+// The automatic pass runs in the background (async, yielding between steps) two minutes after the window
+// opened (so a start that fails never cleans), at most once a day and at once
+// after an update, under a lock, never while an update downloads or waits to
+// install (the updater queues it), best effort; logged to the console log and
+// <userData>/disk-cleanup.json.
+
+import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
+import { lstat, readdir, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+import { acquireLock, capLogs, compareVersions, formatBytes, parseVersion, rotateLog, sizeOf, summarize } from "./retention.mjs";
+
+export const MARKER_FILE = "disk-cleanup.json";
+export const LOCK_FILE = "disk-cleanup.lock";
+export const PACKAGES_FILE = "downloaded-packages.v1.json";
+export const EVERY_MS = 24 * 3_600_000;
+export const START_DELAY_MS = 2 * 60_000;
+const INSTALLER_CACHE_DIRECTORY = "app-update-installer";
+const DAY = 24 * 3_600_000;
+const LOCKED = new Set(["EBUSY", "EPERM", "EACCES", "ENOTEMPTY"]);
+/** Temp names only this app makes; anything else in temp is never looked at. */
+const TEMP_NAMES = [
+ { prefix: "omnirush-update-", re: /^omnirush-update-[A-Za-z0-9]{6}$/, maxAgeMs: DAY },
+ { prefix: "omnirush-swap-", re: /^omnirush-swap-\d+\.sh$/, maxAgeMs: DAY },
+ { prefix: "omnirush-engine2-import-", re: /^omnirush-engine2-import-[A-Za-z0-9]{6}$/, maxAgeMs: 3 * DAY },
+ { prefix: "omnirush-archive-ignore-", re: /^omnirush-archive-ignore-[A-Za-z0-9]{6}$/, maxAgeMs: 3 * DAY },
+ { prefix: "omnirush-login-sync-", re: /^omnirush-login-sync-[A-Za-z0-9]{6}$/, maxAgeMs: 3 * DAY },
+];
+/** Lets the main process breathe between steps (the window stays responsive). */
+const breathe = () => new Promise((resolve) => setImmediate(resolve));
+
+function readJson(file) {
+ try { return JSON.parse(readFileSync(file, "utf8")); } catch { return null; }
+}
+
+function writeJsonAtomic(file, value) {
+ try {
+ mkdirSync(path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.tmp`;
+ writeFileSync(tmp, JSON.stringify(value), { mode: 0o600 });
+ renameSync(tmp, file);
+ } catch { /* best effort */ }
+}
+
+/** Bytes under `p`, without blocking the main process (links are not followed). */
+async function sizeAsync(p) {
+ let st;
+ try { st = await lstat(p); } catch { return 0; }
+ if (st.isSymbolicLink()) return 0;
+ if (!st.isDirectory()) return st.size;
+ let names = [];
+ try { names = await readdir(p); } catch { return 0; }
+ let total = 0;
+ for (const name of names) total += await sizeAsync(path.join(p, name));
+ return total;
+}
+
+/** Remove a file or folder off the main thread's critical path; { ok, bytes, locked, error }. */
+async function removeAsync(p, { dryRun = false } = {}) {
+ const bytes = await sizeAsync(p);
+ if (dryRun) return { ok: true, bytes, dryRun: true };
+ try {
+ await rm(p, { recursive: true, force: true, maxRetries: 2, retryDelay: 100 });
+ return { ok: true, bytes };
+ } catch (error) {
+ const code = String(error?.code || "");
+ return { ok: false, bytes: 0, locked: LOCKED.has(code), error: code || String(error?.message || error) };
+ }
+}
+
+/**
+ * Entries of `dir` starting with one of `prefixes`, owned by this user, not
+ * touched for `maxAgeMs` (the entry and what is directly in it), holding no
+ * socket. The same rule as retention.mjs staleTemp, without blocking.
+ */
+async function staleTempAsync(dir, prefixes, { now = Date.now(), maxAgeMs }) {
+ let names = [];
+ try { names = await readdir(dir); } catch { return []; }
+ const uid = typeof process.getuid === "function" ? process.getuid() : null;
+ const out = [];
+ for (const name of names) {
+ if (!prefixes.some((prefix) => name.startsWith(prefix))) continue;
+ const p = path.join(dir, name);
+ try {
+ const st = await lstat(p);
+ if (st.isSymbolicLink() || (uid !== null && st.uid !== uid)) continue;
+ let newest = st.mtimeMs;
+ let live = false;
+ if (st.isDirectory()) {
+ for (const child of await readdir(p)) {
+ try {
+ const c = await lstat(path.join(p, child));
+ if (c.isSocket() || c.isFIFO()) { live = true; break; }
+ newest = Math.max(newest, c.mtimeMs);
+ } catch { /* gone */ }
+ }
+ }
+ if (!live && now - newest > maxAgeMs) out.push(p);
+ } catch { /* gone or unreadable */ }
+ }
+ return out;
+}
+
+const ARCH_OR_OS = /^(arm64|x64|x86_64|amd64|aarch64|ia32|armv7l|universal|mac|macos|darwin|win|win32|windows|linux|setup)$/i;
+const INSTALLER_EXT = /\.(exe|dmg|zip|AppImage|deb|rpm|pacman|tar\.gz|tgz|blockmap|part|yml)(\.(blockmap|part))?$/i;
+
+/**
+ * The version in an installer's file name, pre-release included
+ * (`omnirush-win-x64-3.6.4.exe` → 3.6.4, `…-3.6.5-alpha.2.exe` → 3.6.5-alpha.2,
+ * `OmniRush.ai-3.6.4-arm64-mac.zip` → 3.6.4), else null.
+ */
+export function installerVersion(name) {
+ const base = String(name || "").replace(INSTALLER_EXT, "");
+ const m = /(?:^|[^0-9.])(\d+\.\d+\.\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/.exec(base) ?? /(?:^|[^0-9.])(\d+\.\d+\.\d+)(?=[^0-9.]|$)/.exec(base);
+ if (!m) return null;
+ const pre = m[2] && !ARCH_OR_OS.test(m[2].split(/[-.]/)[0]) ? m[2] : null;
+ const version = pre ? `${m[1]}-${pre}` : m[1];
+ return parseVersion(version) ? version : null;
+}
+
+/** electron-updater's cache root for this OS (it appends updaterCacheDirName). */
+export function updaterCacheBase({ platform = process.platform, env = process.env, home = os.homedir() } = {}) {
+ if (platform === "win32") return env.LOCALAPPDATA || path.join(home, "AppData", "Local");
+ if (platform === "darwin") return path.join(home, "Library", "Caches");
+ return String(env.XDG_CACHE_HOME || "").trim() || path.join(home, ".cache");
+}
+
+/** The updater cache folder name app-update.yml names (electron-builder writes it into resources). */
+export function updaterCacheDirName({ resourcesPath = process.resourcesPath } = {}) {
+ try {
+ const text = readFileSync(path.join(resourcesPath || "", "app-update.yml"), "utf8");
+ const m = /^updaterCacheDirName:\s*['"]?([^'"\r\n]+?)['"]?\s*$/m.exec(text);
+ const name = m?.[1]?.trim();
+ // A plain folder name only: never a path out of the cache root.
+ return name && !/[\\/]|^\.\.?$/.test(name) ? name : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * The installer electron-updater downloaded, once it is not newer than the
+ * running version (installed, or older than what runs; pre-releases in semver
+ * order): pending/ and the installer/blockmap copies it keeps in the cache root.
+ */
+async function updaterCacheItems({ cacheDir, currentVersion, now, dryRun }) {
+ const items = [];
+ if (!cacheDir || !existsSync(cacheDir)) return items;
+ const pending = path.join(cacheDir, "pending");
+ if (existsSync(pending)) {
+ const info = readJson(path.join(pending, "update-info.json"));
+ let names = [];
+ try { names = await readdir(pending); } catch { /* none */ }
+ const fileName = typeof info?.fileName === "string" ? info.fileName : names.find((n) => /\.(exe|dmg|zip|AppImage|deb|rpm|pacman)$/i.test(n));
+ const version = installerVersion(fileName);
+ let old = false;
+ if (version) old = compareVersions(version, currentVersion) <= 0;
+ else {
+ // No version to read: only when it is older than two weeks (a download never offered again).
+ try { old = now - statSync(pending).mtimeMs > 14 * DAY; } catch { old = false; }
+ }
+ if (old) items.push({ kind: "installer", path: pending, reason: version ? `update ${version} installed` : "old update download", ...(await removeAsync(pending, { dryRun })) });
+ }
+ // Differential-download copies (differential downloads are off in this app).
+ for (const name of ["installer.exe", "current.blockmap"]) {
+ const file = path.join(cacheDir, name);
+ if (existsSync(file)) items.push({ kind: "installer", path: file, reason: "old installer copy", ...(await removeAsync(file, { dryRun })) });
+ }
+ return items;
+}
+
+/** Our installer cache (manual DMG / mac swap zip): its installer once that version or a newer one runs. */
+async function installerCacheItems({ userData, currentVersion, protect, dryRun }) {
+ const dir = path.join(userData, INSTALLER_CACHE_DIRECTORY);
+ const items = [];
+ let names = [];
+ try { names = await readdir(dir); } catch { return items; }
+ for (const name of names) {
+ const file = path.join(dir, name);
+ if (protect.has(path.resolve(file))) continue;
+ const version = installerVersion(name);
+ const partial = name.endsWith(".part");
+ if (partial || (version && compareVersions(version, currentVersion) <= 0)) {
+ items.push({ kind: "installer", path: file, reason: partial ? "stopped download" : `update ${version} installed`, ...(await removeAsync(file, { dryRun })) });
+ }
+ }
+ return items;
+}
+
+/**
+ * Remember a Linux package this app itself wrote to the user's Downloads (the
+ * updater calls it only when it downloaded the file, never for one that was
+ * already there). Only "Free up space" removes recorded files, unchanged ones.
+ */
+export function rememberDownloadedPackage(userData, file, version) {
+ try {
+ const st = statSync(file);
+ const list = readJson(path.join(userData, PACKAGES_FILE))?.packages ?? [];
+ const next = [...list.filter((p) => p?.path !== file), { path: file, version: String(version), size: st.size, mtimeMs: Math.floor(st.mtimeMs) }].slice(-20);
+ writeJsonAtomic(path.join(userData, PACKAGES_FILE), { packages: next });
+ } catch { /* not recorded: never removed */ }
+}
+
+async function downloadedPackageItems({ userData, currentVersion, protect, dryRun }) {
+ const file = path.join(userData, PACKAGES_FILE);
+ const list = readJson(file)?.packages;
+ if (!Array.isArray(list)) return [];
+ const items = [];
+ const keep = [];
+ for (const p of list) {
+ if (!p || typeof p.path !== "string" || !parseVersion(p.version)) continue;
+ let st;
+ try { st = lstatSync(p.path); } catch { continue; /* gone: forget it */ }
+ const unchanged = st.isFile() && st.size === p.size && Math.floor(st.mtimeMs) === p.mtimeMs;
+ if (!unchanged) continue; // the user moved, replaced or edited it: it is theirs now
+ if (protect.has(path.resolve(p.path)) || compareVersions(p.version, currentVersion) > 0) { keep.push(p); continue; }
+ const res = await removeAsync(p.path, { dryRun });
+ items.push({ kind: "installer", path: p.path, reason: `package ${p.version} installed`, ...res });
+ if (dryRun || !res.ok) keep.push(p);
+ }
+ if (!dryRun) writeJsonAtomic(file, { packages: keep });
+ return items;
+}
+
+async function tempItems({ tmp, now, protect, dryRun }) {
+ const items = [];
+ for (const rule of TEMP_NAMES) {
+ for (const p of await staleTempAsync(tmp, [rule.prefix], { now, maxAgeMs: rule.maxAgeMs })) {
+ if (!rule.re.test(path.basename(p)) || protect.has(path.resolve(p))) continue;
+ items.push({ kind: "temp", path: p, reason: "left by a run or update that stopped", ...(await removeAsync(p, { dryRun })) });
+ }
+ }
+ return items;
+}
+
+/** Crashpad reports (minidumps) older than 30 days; the database files stay. */
+async function crashItems({ userData, now, dryRun }) {
+ const items = [];
+ for (const sub of ["completed", "pending", "new"]) {
+ const dir = path.join(userData, "Crashpad", sub);
+ for (const p of await staleTempAsync(dir, [""], { now, maxAgeMs: 30 * DAY })) {
+ if (!/\.(dmp|meta)$/i.test(p)) continue;
+ items.push({ kind: "crash", path: p, reason: "old crash report", ...(await removeAsync(p, { dryRun })) });
+ }
+ }
+ return items;
+}
+
+function logItems({ logsDir, now, dryRun }) {
+ const items = [];
+ if (!logsDir) return items;
+ const install = path.join(logsDir, "update-install.log");
+ const rotated = rotateLog(install, { dryRun });
+ if (rotated && (rotated.bytes || rotated.locked || rotated.wouldRotate)) items.push({ kind: "log", path: `${install}.1`, reason: "log over 10 MB", ...rotated });
+ items.push(...capLogs(logsDir, { match: (name) => /\.log\.\d+$/.test(name), now, dryRun }).map((item) => ({ kind: "log", ...item })));
+ return items;
+}
+
+/**
+ * One cleanup pass (the main process; async, it yields between steps).
+ * `paths`: { userData, logs, temp, updaterCache } (updaterCache: the
+ * electron-updater cache folder or null). `protect`: files/folders an update
+ * in progress uses. `includeDownloads`: also the packages this app saved to
+ * Downloads (only "Free up space" asks for it). Never throws.
+ */
+export async function cleanupPass({ paths, currentVersion, now = Date.now(), dryRun = false, protect = [], includeDownloads = false }) {
+ const userData = paths.userData;
+ if (!parseVersion(currentVersion)) return { items: [], freed: 0, locked: 0, skipped: "no-version" };
+ const release = dryRun ? () => {} : acquireLock(path.join(userData, LOCK_FILE), { now });
+ if (!release) return { items: [], freed: 0, locked: 0, skipped: "busy" };
+ const kept = new Set(protect.filter(Boolean).map((p) => path.resolve(p)));
+ const items = [];
+ const step = async (fn) => {
+ try { items.push(...(await fn())); } catch (error) { items.push({ kind: "error", path: "", bytes: 0, error: String(error?.message || error) }); }
+ await breathe();
+ };
+ try {
+ await step(() => updaterCacheItems({ cacheDir: paths.updaterCache, currentVersion, now, dryRun }));
+ await step(() => installerCacheItems({ userData, currentVersion, protect: kept, dryRun }));
+ if (includeDownloads) await step(() => downloadedPackageItems({ userData, currentVersion, protect: kept, dryRun }));
+ await step(() => tempItems({ tmp: paths.temp, now, protect: kept, dryRun }));
+ await step(() => crashItems({ userData, now, dryRun }));
+ await step(() => logItems({ logsDir: paths.logs, now, dryRun }));
+ } finally { release(); }
+ const sum = summarize(items);
+ return { items: items.map(({ ok, ...rest }) => rest), freed: sum.bytes, locked: sum.locked };
+}
+
+/** Due: never ran, ran over a day ago, or ran on another version (just updated). */
+export function cleanupDue(userData, version, { now = Date.now(), env = process.env } = {}) {
+ if (["0", "off", "false", "no"].includes(String(env.OMNIRUSH_DISK_CLEANUP ?? "").trim().toLowerCase())) return false;
+ const last = readJson(path.join(userData, MARKER_FILE));
+ if (!last || last.version !== version) return true;
+ return !(Number.isFinite(last.at) && now - last.at < EVERY_MS && last.at <= now);
+}
+
+/** The automatic pass: marker + one log line. */
+export async function runAutomatic({ paths, currentVersion, now = Date.now(), protect = [], log = console.info }) {
+ if (!cleanupDue(paths.userData, currentVersion, { now })) return null;
+ const result = await cleanupPass({ paths, currentVersion, now, protect });
+ if (result.skipped) return result;
+ writeJsonAtomic(path.join(paths.userData, MARKER_FILE), { at: now, version: currentVersion, freed: result.freed, removed: result.items.filter((i) => !i.locked && !i.error).length, locked: result.locked });
+ if (result.items.length) log(`[disk-cleanup] freed ${formatBytes(result.freed)}: ${result.items.map((i) => `${i.kind}:${path.basename(String(i.path || ""))}${i.locked ? "(in use)" : ""}`).join(", ")}`);
+ return result;
+}
+
+/** The paths of a running Electron app. */
+export function appPaths(app, { resourcesPath = process.resourcesPath, platform = process.platform, env = process.env } = {}) {
+ const name = app.isPackaged ? updaterCacheDirName({ resourcesPath }) : null;
+ return {
+ userData: app.getPath("userData"),
+ logs: (() => { try { return app.getPath("logs"); } catch { return null; } })(),
+ temp: os.tmpdir(),
+ updaterCache: name ? path.join(updaterCacheBase({ platform, env, home: app.getPath("home") }), name) : null,
+ };
+}
+
+/**
+ * After the window opened: the automatic pass two minutes later, through
+ * `whenIdle` (the updater's queue: never during a download or a pending
+ * install). Never throws; never on the start path.
+ */
+export function scheduleDiskCleanup({ app, currentVersion, whenIdle = (fn) => fn(), protect = () => [], delayMs = START_DELAY_MS, log = console.info }) {
+ try {
+ if (!app.isPackaged && !process.env.OMNIRUSH_DISK_CLEANUP_DEV) return null;
+ const paths = appPaths(app);
+ if (!cleanupDue(paths.userData, currentVersion)) return null;
+ const timer = setTimeout(() => {
+ Promise.resolve(whenIdle(() => runAutomatic({ paths, currentVersion, protect: protect(), log })))
+ .catch((error) => console.warn("[disk-cleanup] failed", error?.message ?? error));
+ }, delayMs);
+ timer.unref?.();
+ return timer;
+ } catch { return null; }
+}
+
+/** For the "Free up space" entry: what would go (dryRun) or what went. */
+export async function freeUpSpace({ app, currentVersion, dryRun, protect = [] }) {
+ const paths = appPaths(app);
+ const result = await cleanupPass({ paths, currentVersion, dryRun, protect, includeDownloads: true });
+ if (!dryRun && !result.skipped) writeJsonAtomic(path.join(paths.userData, MARKER_FILE), { at: Date.now(), version: currentVersion, freed: result.freed, removed: result.items.filter((i) => !i.locked && !i.error).length, locked: result.locked });
+ return {
+ ok: !result.skipped,
+ skipped: result.skipped ?? null,
+ dryRun: Boolean(dryRun),
+ freedBytes: result.freed,
+ freed: formatBytes(result.freed),
+ items: result.items.filter((i) => i.kind !== "error").map((i) => ({ kind: i.kind, path: String(i.path || ""), bytes: Number(i.bytes) || 0, size: formatBytes(Number(i.bytes) || 0), reason: i.reason, inUse: Boolean(i.locked) })),
+ };
+}
+
+export { sizeOf };
diff --git a/apps/desktop/electron/disk-cleanup/retention.d.mts b/apps/desktop/electron/disk-cleanup/retention.d.mts
new file mode 100644
index 00000000..9a35a48c
--- /dev/null
+++ b/apps/desktop/electron/disk-cleanup/retention.d.mts
@@ -0,0 +1,22 @@
+export const MB: number;
+export const DAY_MS: number;
+export const LOG_FILE_CAP_BYTES: number;
+export const LOG_TOTAL_CAP_BYTES: number;
+export const LOG_MAX_AGE_MS: number;
+export const TEMP_MAX_AGE_MS: number;
+
+export interface Removal { ok: boolean; bytes: number; locked?: boolean; error?: string; dryRun?: boolean }
+export interface Rotation { rotated: boolean; bytes: number; locked?: boolean; error?: string; wouldRotate?: number; dryRun?: boolean }
+export interface LogRemoval { path: string; bytes: number; reason: string; locked?: boolean; dryRun?: boolean }
+
+export function sizeOf(p: string): number;
+export function formatBytes(bytes: number): string;
+export function removePath(p: string, options?: { dryRun?: boolean }): Removal;
+export function parseVersion(value: unknown): [number, number, number, string[]] | null;
+export function compareVersions(a: unknown, b: unknown): -1 | 0 | 1;
+export function versionsToRemove(versions: string[], options: { current: string; previous?: string | null; protect?: string[] }): string[];
+export function rotateLog(file: string, options?: { maxBytes?: number; dryRun?: boolean }): Rotation | null;
+export function capLogs(dir: string, options?: { match?: (name: string) => boolean; active?: string[]; maxTotalBytes?: number; maxAgeMs?: number; now?: number; dryRun?: boolean }): LogRemoval[];
+export function staleTemp(dir: string, prefixes: string[], options?: { now?: number; maxAgeMs?: number }): string[];
+export function acquireLock(file: string, options?: { staleMs?: number; now?: number }): (() => void) | null;
+export function summarize(items: Array<{ bytes?: number; locked?: boolean; error?: string } | null | undefined>): { count: number; bytes: number; locked: number };
diff --git a/apps/desktop/electron/disk-cleanup/retention.mjs b/apps/desktop/electron/disk-cleanup/retention.mjs
new file mode 100644
index 00000000..64b453ea
--- /dev/null
+++ b/apps/desktop/electron/disk-cleanup/retention.mjs
@@ -0,0 +1,245 @@
+// Disk retention rules shared by the CLI and the desktop app: the same file in
+// omnirush-cli (src/disk-cleanup/retention.mjs) and omnirush-gui
+// (apps/desktop/electron/disk-cleanup/retention.mjs); see PARITY.sha256.
+//
+// Every helper is best effort and never throws: a file another process holds
+// open (Windows), one of another user, or one that vanished is skipped and
+// reported, never retried in a loop. Nothing here decides WHAT is safe to
+// remove; callers pass only app-owned caches, downloads, temp files and logs.
+
+import { randomUUID } from "node:crypto";
+import { closeSync, lstatSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeSync } from "node:fs";
+import path from "node:path";
+
+export const MB = 1024 * 1024;
+export const DAY_MS = 24 * 3_600_000;
+/** One log file is rotated past this size (one rotated copy is kept). */
+export const LOG_FILE_CAP_BYTES = 10 * MB;
+/** All logs of a folder together stay under this. */
+export const LOG_TOTAL_CAP_BYTES = 50 * MB;
+/** Rotated logs older than this go. */
+export const LOG_MAX_AGE_MS = 30 * DAY_MS;
+/** Temp files of crashed runs are this old before they go. */
+export const TEMP_MAX_AGE_MS = 3 * DAY_MS;
+
+const LOCKED = new Set(["EBUSY", "EPERM", "EACCES", "ENOTEMPTY"]);
+
+/** Bytes under `p` (files, recursively; links are not followed). Never throws. */
+export function sizeOf(p) {
+ let st;
+ try { st = lstatSync(p); } catch { return 0; }
+ if (st.isSymbolicLink()) return 0;
+ if (!st.isDirectory()) return st.size;
+ let total = 0;
+ let names = [];
+ try { names = readdirSync(p); } catch { return 0; }
+ for (const name of names) total += sizeOf(path.join(p, name));
+ return total;
+}
+
+/** "1.2 GB" style sizes. */
+export function formatBytes(bytes) {
+ const n = Number(bytes) || 0;
+ if (n < 1024) return `${n} B`;
+ const units = ["KB", "MB", "GB", "TB"];
+ let v = n / 1024;
+ let i = 0;
+ while (v >= 1024 && i < units.length - 1) { v /= 1024; i += 1; }
+ return `${v >= 10 ? Math.round(v) : Math.round(v * 10) / 10} ${units[i]}`;
+}
+
+/**
+ * Remove a file or folder. { ok, bytes, locked, error }: `locked` when the OS
+ * refused (a file open in another process on Windows, a read-only folder).
+ * `dryRun` only measures.
+ */
+export function removePath(p, { dryRun = false } = {}) {
+ const bytes = sizeOf(p);
+ if (dryRun) return { ok: true, bytes, dryRun: true };
+ try {
+ rmSync(p, { recursive: true, force: true, maxRetries: 2, retryDelay: 100 });
+ return { ok: true, bytes };
+ } catch (error) {
+ const code = String(error?.code || "");
+ return { ok: false, bytes: 0, locked: LOCKED.has(code), error: code || String(error?.message || error) };
+ }
+}
+
+/**
+ * x.y.z[-pre.release] as [x, y, z, [pre identifiers]]; null when not a version. Build metadata (+...) is ignored.
+ * @param {unknown} value
+ * @returns {[number, number, number, string[]] | null}
+ */
+export function parseVersion(value) {
+ const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/.exec(String(value || "").trim());
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3]), m[4] ? m[4].split(".") : []] : null;
+}
+
+/** -1 / 0 / 1 in semver order (3.6.5-alpha.1 < 3.6.5-alpha.2 < 3.6.5); non-versions sort first. */
+export function compareVersions(a, b) {
+ const x = parseVersion(a), y = parseVersion(b);
+ if (!x || !y) return x ? 1 : y ? -1 : 0;
+ for (let i = 0; i < 3; i += 1) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
+ const p = x[3], q = y[3];
+ if (!p.length || !q.length) return p.length === q.length ? 0 : p.length ? -1 : 1;
+ for (let i = 0; i < Math.max(p.length, q.length); i += 1) {
+ if (p[i] === undefined) return -1;
+ if (q[i] === undefined) return 1;
+ if (p[i] === q[i]) continue;
+ const pn = /^\d+$/.test(p[i]), qn = /^\d+$/.test(q[i]);
+ if (pn && qn) return Number(p[i]) < Number(q[i]) ? -1 : 1;
+ if (pn !== qn) return pn ? -1 : 1;
+ return p[i] < q[i] ? -1 : 1;
+ }
+ return 0;
+}
+
+/**
+ * Of `versions`, the ones to remove: everything older than the one previous
+ * version kept. Kept: `current`, exactly one previous (the given `previous`
+ * when it is still there, else the newest older one), anything newer than
+ * `current` (a download not switched to yet), every name in `protect`, and
+ * every name that is not a version.
+ * @param {string[]} versions
+ * @param {{ current: string, previous?: string | null, protect?: string[] }} options
+ * @returns {string[]}
+ */
+export function versionsToRemove(versions, { current, previous = null, protect = [] }) {
+ const list = [...new Set(versions.map(String))];
+ if (!parseVersion(current)) return [];
+ const older = list.filter((v) => parseVersion(v) && compareVersions(v, current) < 0).sort(compareVersions);
+ const keepPrevious = previous && older.includes(String(previous)) ? String(previous) : older.at(-1) ?? null;
+ const keep = new Set([String(current), keepPrevious, ...protect.map(String)].filter(Boolean));
+ return older.filter((v) => !keep.has(v));
+}
+
+/**
+ * Rotate `file` when it is over `maxBytes`: it becomes `file.1` (the previous
+ * `file.1` goes). Writers that append by name start a new file. Returns
+ * { rotated, bytes, locked } (bytes: what the old `file.1` freed) or null when
+ * nothing was to do.
+ */
+export function rotateLog(file, { maxBytes = LOG_FILE_CAP_BYTES, dryRun = false } = {}) {
+ let size;
+ try { size = statSync(file).size; } catch { return null; }
+ if (size <= maxBytes) return null;
+ const old = `${file}.1`;
+ const oldBytes = sizeOf(old);
+ if (dryRun) return { rotated: false, bytes: oldBytes, wouldRotate: size, dryRun: true };
+ try {
+ rmSync(old, { force: true });
+ renameSync(file, old);
+ return { rotated: true, bytes: oldBytes };
+ } catch (error) {
+ // Windows: another process has it open without delete sharing; try again next time.
+ const code = String(error?.code || "");
+ return { rotated: false, bytes: 0, ...(LOCKED.has(code) ? { locked: true } : { error: code || "rotate-failed" }) };
+ }
+}
+
+/**
+ * Old logs in `dir` (names `match` accepts): ones past `maxAgeMs`, then the
+ * oldest while the folder's logs are over `maxTotalBytes`. Files in `active`
+ * (being written) are never removed. Returns [{ path, bytes, reason }].
+ */
+export function capLogs(dir, { match = (name) => /\.log(\.\d+)?$/.test(name), active = [], maxTotalBytes = LOG_TOTAL_CAP_BYTES, maxAgeMs = LOG_MAX_AGE_MS, now = Date.now(), dryRun = false } = {}) {
+ let names = [];
+ try { names = readdirSync(dir); } catch { return []; }
+ const keep = new Set(active.map((p) => path.resolve(p)));
+ const files = [];
+ for (const name of names) {
+ if (!match(name)) continue;
+ const p = path.join(dir, name);
+ try {
+ const st = lstatSync(p);
+ if (st.isFile()) files.push({ path: p, bytes: st.size, mtimeMs: st.mtimeMs });
+ } catch { /* gone */ }
+ }
+ files.sort((a, b) => a.mtimeMs - b.mtimeMs);
+ let total = files.reduce((sum, f) => sum + f.bytes, 0);
+ const out = [];
+ for (const f of files) {
+ if (keep.has(path.resolve(f.path))) continue;
+ const reason = now - f.mtimeMs > maxAgeMs ? "old log" : total > maxTotalBytes ? "logs over the size cap" : null;
+ if (!reason) continue;
+ const res = removePath(f.path, { dryRun });
+ if (res.ok) { out.push({ path: f.path, bytes: f.bytes, reason, ...(dryRun ? { dryRun: true } : {}) }); total -= f.bytes; }
+ else if (res.locked) out.push({ path: f.path, bytes: 0, reason, locked: true });
+ }
+ return out;
+}
+
+/**
+ * Entries of `dir` whose name starts with one of `prefixes`, owned by this
+ * user (a shared /tmp holds other users' too), that were not touched for
+ * `maxAgeMs` (the folder and what is directly in it), and that hold no socket
+ * (a live session's relay or approval channel).
+ */
+export function staleTemp(dir, prefixes, { now = Date.now(), maxAgeMs = TEMP_MAX_AGE_MS } = {}) {
+ let names = [];
+ try { names = readdirSync(dir); } catch { return []; }
+ const uid = typeof process.getuid === "function" ? process.getuid() : null;
+ const out = [];
+ for (const name of names) {
+ if (!prefixes.some((prefix) => name.startsWith(prefix))) continue;
+ const p = path.join(dir, name);
+ try {
+ const st = lstatSync(p);
+ if (st.isSymbolicLink() || (uid !== null && st.uid !== uid)) continue;
+ let newest = st.mtimeMs;
+ let live = false;
+ if (st.isDirectory()) {
+ for (const child of readdirSync(p)) {
+ try {
+ const c = lstatSync(path.join(p, child));
+ if (c.isSocket() || c.isFIFO()) { live = true; break; }
+ newest = Math.max(newest, c.mtimeMs);
+ } catch { /* gone */ }
+ }
+ }
+ if (!live && now - newest > maxAgeMs) out.push(p);
+ } catch { /* gone or unreadable */ }
+ }
+ return out;
+}
+
+function alive(pid) {
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
+ try { process.kill(pid, 0); return true; } catch (error) { return error?.code === "EPERM"; }
+}
+
+/**
+ * An exclusive lock file (`wx`): a release function, or null when another
+ * live process holds it. A lock of a dead process, or older than `staleMs`, is
+ * taken over.
+ */
+export function acquireLock(file, { staleMs = 30 * 60_000, now = Date.now() } = {}) {
+ const nonce = randomUUID();
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ try {
+ const fd = openSync(file, "wx", 0o600);
+ try { writeSync(fd, JSON.stringify({ pid: process.pid, nonce, at: now })); } finally { closeSync(fd); }
+ return () => {
+ try {
+ const held = JSON.parse(readFileSync(file, "utf8"));
+ if (held?.nonce === nonce) unlinkSync(file);
+ } catch { /* gone */ }
+ };
+ } catch (error) {
+ if (error?.code !== "EEXIST") return null;
+ let held = null;
+ try { held = JSON.parse(readFileSync(file, "utf8")); } catch { /* half written */ }
+ let age = 0;
+ try { age = now - statSync(file).mtimeMs; } catch { continue; }
+ if ((held && !alive(held.pid)) || age > staleMs) { try { unlinkSync(file); } catch { return null; } continue; }
+ return null;
+ }
+ }
+ return null;
+}
+
+/** What a run freed: { count, bytes, locked }. */
+export function summarize(items) {
+ const done = items.filter((item) => item && !item.locked && !item.error);
+ return { count: done.length, bytes: done.reduce((sum, item) => sum + (Number(item.bytes) || 0), 0), locked: items.filter((item) => item?.locked).length };
+}
diff --git a/apps/desktop/electron/main.mjs b/apps/desktop/electron/main.mjs
index b92ed4b0..380fc24c 100644
--- a/apps/desktop/electron/main.mjs
+++ b/apps/desktop/electron/main.mjs
@@ -105,6 +105,7 @@ import {
} from "./brand-icon-windows.mjs";
import { resetMacDockIcon } from "./brand-icon-darwin.mjs";
import { createOpenLogsFolderHandler } from "./logs-folder.mjs";
+import { freeUpSpace, scheduleDiskCleanup } from "./disk-cleanup/index.mjs";
import { readSkillFolder } from "./skill-folder.mjs";
import { createDesktopVaultKeyProvider } from "./secure-vault-key.mjs";
import { applyLinuxPasswordStore, recordLinuxPasswordStore } from "./linux-password-store.mjs";
@@ -2701,6 +2702,16 @@ const desktopCommandHandlers = {
"openLogsFolder": async (event) => {
return openLogsFolder(event);
},
+ // Settings > Storage. Only app-owned downloads, logs and temp files (disk-cleanup/index.mjs); no path from the renderer.
+ "freeUpSpace": async (event, ...args) => {
+ if (!mainWindow || mainWindow.isDestroyed() || event?.sender !== mainWindow.webContents || event?.senderFrame !== mainWindow.webContents.mainFrame) {
+ return { ok: false, skipped: "untrusted", dryRun: true, freedBytes: 0, freed: "0 B", items: [] };
+ }
+ const dryRun = Boolean(args[0] && typeof args[0] === "object" && args[0].dryRun);
+ const result = await whenUpdaterIdle(() => freeUpSpace({ app, currentVersion: app.getVersion(), dryRun, protect: pendingUpdatePaths() }));
+ if ("items" in result) return result;
+ return { ok: false, skipped: result.skipped, dryRun, freedBytes: 0, freed: "0 B", items: [] };
+ },
"__openPath": async (event, ...args) => {
const target = String(args[0] ?? "").trim();
if (!target) return "Path is required.";
@@ -3354,7 +3365,7 @@ const browserLoginSync = createBrowserLoginSync({
browserLoginSync.registerIpc(ipcMain, { evalSeam: browserLoginEvalSeam });
registerMigrationIpc({ app, ipcMain });
-const { ensureAutoUpdater, prepareInstallOnQuit, offerMoveAtLaunch } = registerUpdaterIpc({
+const { ensureAutoUpdater, prepareInstallOnQuit, offerMoveAtLaunch, whenUpdaterIdle, pendingUpdatePaths } = registerUpdaterIpc({
app,
ipcMain,
allowQuit: () => turnGuard.allowQuit(),
@@ -3544,6 +3555,8 @@ or use: pnpm dev:worktree`);
const win = await createMainWindow();
// In the background: the window never waits for it.
desktopPlacements.start();
+ // Installed update downloads, old logs and temp files go two minutes later, in the updater's queue.
+ scheduleDiskCleanup({ app, currentVersion: app.getVersion(), whenIdle: whenUpdaterIdle, protect: pendingUpdatePaths });
void desktopFeedback.start();
if (startReset.ran && startReset.moved.length > 0) {
runDetachedTask("show app data reset notice", async () => {
diff --git a/apps/desktop/electron/updater.mjs b/apps/desktop/electron/updater.mjs
index 645bbe1a..02060842 100644
--- a/apps/desktop/electron/updater.mjs
+++ b/apps/desktop/electron/updater.mjs
@@ -34,6 +34,7 @@ import {
replaceAppImage,
stageMacBundle,
} from "./self-install.mjs";
+import { rememberDownloadedPackage } from "./disk-cleanup/index.mjs";
const ELECTRON_UPDATER_CHANNEL_FILENAME = "electron-updater-channel.v1.json";
// Where a manually installed update (macOS DMG) is staged before it is opened.
@@ -1344,9 +1345,12 @@ export function registerUpdaterIpc({
: "The release manifest does not list a macOS installer for this update.");
}
if (installMode === "package") {
- downloadedInstallerPath = await downloadManualInstaller(checkedInstallerArtifact, {
- directory: await packageDownloadDirectory(),
- });
+ const directory = await packageDownloadDirectory();
+ // A file already there is the user's (it may be one they downloaded): never recorded for cleanup.
+ const wasThere = await fileExists(path.join(directory, checkedInstallerArtifact.fileName));
+ downloadedInstallerPath = await downloadManualInstaller(checkedInstallerArtifact, { directory });
+ // Recorded so "Free up space" can offer this file (and only it, unchanged) once it is installed.
+ if (!wasThere) rememberDownloadedPackage(app.getPath("userData"), downloadedInstallerPath, checkedInstallerArtifact.version);
} else {
downloadedInstallerPath = await downloadManualInstaller(checkedInstallerArtifact);
}
@@ -1626,5 +1630,28 @@ export function registerUpdaterIpc({
}
}
- return { ensureAutoUpdater, prepareInstallOnQuit, offerMoveAtLaunch };
+ /**
+ * Runs `operation` in the updater's queue (never while a check, download or
+ * install runs), unless an update is downloaded and waiting to install, or
+ * installing: then it is skipped ({ skipped: "update-pending" }).
+ * @template T
+ * @param {() => T | Promise<T>} operation
+ * @returns {Promise<T | { skipped: "update-pending" }>}
+ */
+ function whenUpdaterIdle(operation) {
+ return /** @type {Promise<any>} */ (queueUpdaterOperation(async () => {
+ if (updateDownloaded || installTriggered || quitInstallInProgress || stagedMacBundle) return { skipped: "update-pending" };
+ return operation();
+ }));
+ }
+
+ /**
+ * Files an update in progress uses (never cleaned).
+ * @returns {string[]}
+ */
+ function pendingUpdatePaths() {
+ return [downloadedInstallerPath, stagedMacBundle && path.dirname(stagedMacBundle), downloadedAppImagePath].filter(Boolean);
+ }
+
+ return { ensureAutoUpdater, prepareInstallOnQuit, offerMoveAtLaunch, whenUpdaterIdle, pendingUpdatePaths };
}
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 99c611b2..3b29bb01 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -27,7 +27,7 @@
"prepare:sidecar": "node ./scripts/prepare-sidecar.mjs",
"pretest": "pnpm --filter @omnirush/headless-threads build",
"test:omnirush-account": "node --test electron/omnirush-account.test.mjs",
- "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/build-variant.test.mjs electron/placements-desktop.test.mjs electron/feedback-desktop.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/computer-use-answers.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.test.mjs electron/app-request-secret.test.mjs",
+ "test": "node --test scripts/prepare-server-constants.test.mjs scripts/verify-update-manifest.test.mjs electron/after-pack-paths.test.mjs electron/agent-context-diagnostics-fetch.test.mjs electron/automation-runner.test.mjs electron/binary-transfer.test.mjs electron/blank-slate-profile.test.mjs electron/blank-slate-profile-isolation.test.mjs electron/brand-app-name.test.mjs electron/brand-icon-darwin.test.mjs electron/brand-icon-windows.test.mjs electron/browser-login-sync.test.mjs electron/browser-panel.test.mjs electron/connect-link.test.mjs electron/desktop-distribution.test.mjs electron/dev-profile.test.mjs electron/electron-builder-config.test.mjs electron/linux-desktop-integration.test.mjs electron/linux-password-store.test.mjs electron/logs-folder.test.mjs electron/media-permissions.test.mjs electron/no-bare-external-fetch.test.mjs electron/nuke.test.mjs electron/omnirush-account.test.mjs electron/omnirush-ui-mcp.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/process-resilience.test.mjs electron/runtime.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/sentry.test.mjs electron/server-dependency-mirror.test.mjs electron/skill-folder.test.mjs electron/secure-vault-key.test.mjs electron/stdio-errors.test.mjs electron/terminal-sessions.test.mjs electron/ui-control-server.test.mjs electron/updater.test.mjs electron/update-gate.test.mjs electron/quality.test.mjs electron/buildathon.test.mjs electron/build-variant.test.mjs electron/placements-desktop.test.mjs electron/feedback-desktop.test.mjs electron/turn-guard.test.mjs electron/keep-awake.test.mjs electron/computer-use-answers.test.mjs electron/remote-workspace.test.mjs electron/workspace-archive.test.mjs electron/workspace-store.test.mjs electron/start-report.test.mjs electron/start-reset.test.mjs electron/start-store-check.test.mjs electron/app-request-secret.test.mjs electron/disk-cleanup.test.mjs",
"test:core": "node --test scripts/prepare-server-constants.test.mjs electron/workspace-store.test.mjs electron/workspace-archive.test.mjs electron/connect-link.test.mjs electron/open-external.test.mjs electron/open-local-path.test.mjs electron/secure-vault-key.test.mjs electron/process-resilience.test.mjs electron/stdio-errors.test.mjs electron/runtime-ca.test.mjs electron/system-ca-trust.test.mjs electron/external-fetch.test.mjs electron/runtime-chain-repair.test.mjs electron/automation-runner.test.mjs",
"pretest:core": "pnpm --filter @omnirush/headless-threads build"
},
diff --git a/apps/server/src/box/PARITY.sha256 b/apps/server/src/box/PARITY.sha256
index 35321fed..de4689ef 100644
--- a/apps/server/src/box/PARITY.sha256
+++ b/apps/server/src/box/PARITY.sha256
@@ -1,6 +1,9 @@
# The sandbox image pins: the same files in omnirush-cli (src/box/) and omnirush-gui (apps/server/src/box/).
+# retention.mjs (+ .d.mts): which sandbox images stay across box-version updates (current + previous pins, images in use).
# host-builds.json: the rules and notices for folders with macOS/Windows builds (host-builds.js / host-builds.ts read it).
# A change to one must be ported to the other and this list updated in both (scripts/box/pins.mjs refreshes the pins' list).
f4cf889b29e169592863020c6ac2b02c69d8887a8df1502dd01c7939805a9b8a images.json
fd7531323e200f2133cdf66ed8608d04af3a38049cfeb01a0a285cbd72813c4d wsl.json
ec1c7507cd3919a1066c870e3f7018424bdca8641fbf34fec9c4eefd9def1d29 host-builds.json
+fe040597bec7f113721071097906380c51198d0cc785747c3891b754e55f34a2 retention.mjs
+e0478a8e95284a9f1713ee695dd5a2a7123991b2ab2d45297a09369cce037da7 retention.d.mts
diff --git a/apps/server/src/box/backends/apple.ts b/apps/server/src/box/backends/apple.ts
index 30b4d69b..f7e75933 100644
--- a/apps/server/src/box/backends/apple.ts
+++ b/apps/server/src/box/backends/apple.ts
@@ -32,7 +32,8 @@ import { BOX_PORT, HOME_IN_BOX, LABEL, RUN_DIR, SHIMS_DIR, containerName, contai
import { runCommand, type RunCommand } from "../run.js";
import type { RuntimeResult } from "../runtime.js";
import { versionAtLeast } from "./shared.js";
-import type { BoxDriver, OpenContext, Opened, PresentImage } from "./types.js";
+import { removableImage } from "../retention.mjs";
+import type { BoxDriver, OpenContext, Opened, PresentImage, Removed } from "./types.js";
type Env = NodeJS.ProcessEnv;
@@ -303,13 +304,15 @@ export const appleDriver: BoxDriver = {
const res = await run(runtime.bin, ["delete", "--force", containerName(key, env)], { timeoutMs: 60_000 });
return { removed: res.code === 0 };
},
- async gcImages(runtime, { run = runCommand, current, used }) {
- const removed = [];
+ async gcImages(runtime, { run = runCommand, current, used, keep = { refs: current, digests: new Set<string>() }, dryRun = false }) {
+ const removed: Removed[] = [];
const res = await run(runtime.bin, ["image", "list", "--format", "json"], { timeoutMs: 30_000 });
const parsed = parseJson(res.stdout);
for (const entry of Array.isArray(parsed) ? parsed.map(record) : []) {
const ref = String(entry.reference ?? entry.name ?? "");
- if (!ref || !/(^|\/)omnirush-ai\/box-[a-z]+:/.test(ref) || current.has(ref) || used.has(ref)) continue;
+ const digest = record(entry.descriptor).digest ?? entry.digest;
+ if (!ref || !removableImage({ ref, digest: typeof digest === "string" ? digest : null, id: "" }, { keep, used })) continue;
+ if (dryRun) { removed.push({ kind: "image", name: ref, reason: "not current", dryRun: true }); continue; }
const del = await run(runtime.bin, ["image", "delete", ref], { timeoutMs: 60_000 });
if (del.code === 0) removed.push({ kind: "image", name: ref, reason: "not current" });
}
diff --git a/apps/server/src/box/backends/bwrap.ts b/apps/server/src/box/backends/bwrap.ts
index 33fb8dd0..3383d572 100644
--- a/apps/server/src/box/backends/bwrap.ts
+++ b/apps/server/src/box/backends/bwrap.ts
@@ -17,13 +17,14 @@
// (kernel.apparmor_restrict_unprivileged_userns=1): the probe says so in one
// line and the next backend (rootless Podman, Docker) is used.
-import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { GOARCH, RUN_DIR, SHIMS_DIR, containerName, containerRoot, helperPath, newToken, readJson, writeJson, type BoxInstallLog, type BoxRuntime } from "../common.js";
import { runCommand, type RunCommand, type RunOptions } from "../run.js";
import type { RuntimeResult } from "../runtime.js";
+import { YOUNG_IMAGE_MS, removableImage, removeTree, staleEntries } from "../retention.mjs";
import { boxshExec, num, parseOut, str } from "./shared.js";
import type { BoxDriver, ListedBox, OpenContext, Opened, PresentImage, Removed } from "./types.js";
@@ -238,22 +239,26 @@ export const bwrapDriver: BoxDriver = {
const res = await run(runtime.bin, ["stop", "--box", boxDir(home, key)], { timeoutMs: 60_000 });
return { stopped: Boolean(parseOut(res.stdout)?.ok) };
},
- async gcImages(runtime, { run = runCommand, home = "", current, used }) {
+ async gcImages(runtime, { run = runCommand, home = "", current, used, keep = { refs: current, digests: new Set<string>() }, dryRun = false, now = Date.now() }) {
const removed: Removed[] = [];
+ // Downloads a killed pull left in the store (each one can be a whole image).
+ for (const item of staleEntries(path.join(storeDir(home), "tmp"), { now })) {
+ if (dryRun) removed.push({ kind: "download", name: item.path, reason: "left by a stopped download", dryRun: true });
+ else if (removeTree(item.path)) removed.push({ kind: "download", name: item.path, reason: "left by a stopped download" });
+ }
const dir = path.join(storeDir(home), "images");
let ids: string[] = [];
try { ids = readdirSync(dir); } catch { return removed; }
- const usedIds = new Set<string>();
+ const usedIds = new Set<string>(used);
for (const box of await list(runtime, { home })) {
const meta = readJson<BoxMeta>(metaFile(home, box.key));
if (meta?.image) usedIds.add(meta.image);
}
- const plain = (ref: unknown) => String(ref || "").replace(/@sha256:[0-9a-f]{64}$/, "").replace(/^docker\.io\//, "");
- const currentPlain = new Set([...current].map(plain));
for (const id of ids) {
- const img = readJson<{ ref?: string }>(path.join(dir, id, "image.json"));
- if (!img || usedIds.has(id) || used.has(String(img.ref)) || currentPlain.has(plain(img.ref))) continue;
- if (!/(^|\/)omnirush-ai\/box-[a-z]+:/.test(String(img.ref))) continue;
+ const img = readJson<{ ref?: string; digest?: string }>(path.join(dir, id, "image.json"));
+ if (!img || !removableImage({ ref: img.ref, digest: img.digest, id }, { keep, used: usedIds })) continue;
+ try { if (now - statSync(path.join(dir, id, "image.json")).mtimeMs < YOUNG_IMAGE_MS) continue; } catch { continue; }
+ if (dryRun) { removed.push({ kind: "image", name: String(img.ref), reason: "not current", path: path.join(dir, id), dryRun: true }); continue; }
const res = await run(runtime.bin, ["rmimage", ...storeArgs(home), "--id", id], { timeoutMs: 120_000 });
if (parseOut(res.stdout)?.ok) removed.push({ kind: "image", name: String(img.ref), reason: "not current" });
}
diff --git a/apps/server/src/box/backends/container.ts b/apps/server/src/box/backends/container.ts
index 84150e8a..a1f3e6eb 100644
--- a/apps/server/src/box/backends/container.ts
+++ b/apps/server/src/box/backends/container.ts
@@ -13,7 +13,8 @@ import os from "node:os";
import { BOX_PORT, GOARCH, HOME_IN_BOX, LABEL, RUN_DIR, SHIMS_DIR, containerName, containerRoot, firstLine, helperPath, newToken, wslPath, type BoxInstallLog, type BoxRuntime } from "../common.js";
import { runCommand, type RunCommand, type RunOptions } from "../run.js";
-import type { BoxDriver, ListedBox, OpenContext, Opened } from "./types.js";
+import { removableImage, removalTarget } from "../retention.mjs";
+import type { BoxDriver, ListedBox, OpenContext, Opened, Removed } from "./types.js";
type Env = NodeJS.ProcessEnv;
@@ -272,14 +273,27 @@ export const containerDriver: BoxDriver = {
return { removed: res.code === 0 };
},
/** Box images that no box uses and that are not the current pins (`omnirush-ai/box-*` only; never a prune). */
- async gcImages(runtime, { run = runCommand, current, used }) {
- const removed = [];
- const images = await rt(runtime, run)(["images", "--format", "{{.Repository}}:{{.Tag}} {{.ID}}"], { timeoutMs: 30_000 });
+ /**
+ * Box images that no box uses and that are neither the current nor the
+ * previous pins (`omnirush-ai/box-*` only, by tag or by digest; never a prune).
+ * A digest pull lists as `repo:<none>`: it is removed as `repo@digest`.
+ */
+ async gcImages(runtime, { run = runCommand, current, used, keep = { refs: current, digests: new Set<string>() }, dryRun = false }) {
+ const removed: Removed[] = [];
+ const images = await rt(runtime, run)(["images", "--digests", "--format", "{{.Repository}}\t{{.Tag}}\t{{.Digest}}\t{{.ID}}\t{{.Size}}"], { timeoutMs: 30_000 });
+ if (images.code !== 0) return removed;
+ const seen = new Set<string>();
for (const line of images.stdout.split("\n")) {
- const [ref, id] = line.trim().split(/\s+/);
- if (!ref || !/(^|\/)omnirush-ai\/box-[a-z]+:/.test(ref) || current.has(ref) || used.has(ref) || (id && used.has(id))) continue;
- const res = await rt(runtime, run)(["rmi", ref], { timeoutMs: 60_000 });
- if (res.code === 0) removed.push({ kind: "image", name: ref, reason: "not current" });
+ const [repo, tag, digest, id, size] = line.trim().split("\t");
+ if (!repo || repo === "<none>") continue;
+ const image = { ref: `${repo}:${tag || "<none>"}`, digest: /^sha256:/.test(digest || "") ? digest : null, id };
+ if (!removableImage(image, { keep, used })) continue;
+ const target = removalTarget(image);
+ if (!target || seen.has(target)) continue;
+ seen.add(target);
+ if (dryRun) { removed.push({ kind: "image", name: target, reason: "not current", size: size || null, dryRun: true }); continue; }
+ const res = await rt(runtime, run)(["rmi", target], { timeoutMs: 60_000 });
+ if (res.code === 0) removed.push({ kind: "image", name: target, reason: "not current", size: size || null });
}
return removed;
},
diff --git a/apps/server/src/box/backends/types.ts b/apps/server/src/box/backends/types.ts
index 8e76bef3..6169d8cf 100644
--- a/apps/server/src/box/backends/types.ts
+++ b/apps/server/src/box/backends/types.ts
@@ -59,7 +59,7 @@ export type Opened =
export type PresentImage = { id: string; digest: string | null; arch: string; config?: string; size?: number | null };
export type ListedBox = { key: string; name: string; root: string; running: boolean; image: string; created: string };
-export type Removed = { kind: string; name: string; reason: string };
+export type Removed = { kind: string; name: string; reason: string; size?: string | null; path?: string; dryRun?: boolean };
export type DriverOptions = { run?: RunCommand; env?: Env; home?: string; timeoutMs?: number; log?: BoxLog; onLine?: RunOptions["onLine"] };
export type BoxDriver = {
@@ -75,7 +75,8 @@ export type BoxDriver = {
list: (runtime: BoxRuntime, opts?: DriverOptions) => Promise<ListedBox[]>;
remove: (runtime: BoxRuntime, key: string, opts?: DriverOptions) => Promise<{ removed: boolean }>;
stop: (runtime: BoxRuntime, key: string, opts?: DriverOptions) => Promise<{ stopped: boolean }>;
- gcImages: (runtime: BoxRuntime, opts: DriverOptions & { current: Set<string>; used: Set<string> }) => Promise<Removed[]>;
+ /** Old box images (src/box/retention.mjs: kept are the current and previous pins and every image a box uses). */
+ gcImages: (runtime: BoxRuntime, opts: DriverOptions & { current: Set<string>; used: Set<string>; keep?: { refs: Set<string>; digests: Set<string> }; dryRun?: boolean; now?: number }) => Promise<Removed[]>;
upperBytes: (runtime: BoxRuntime, key: string, opts?: DriverOptions) => Promise<number | null>;
/** `<runtime> diff` (container engines only): the snapshot fallback when boxd cannot walk. */
diff?: (runtime: BoxRuntime, key: string, opts?: DriverOptions) => Promise<RunResult>;
diff --git a/apps/server/src/box/backends/wsl.ts b/apps/server/src/box/backends/wsl.ts
index 486e0c26..a5fa956d 100644
--- a/apps/server/src/box/backends/wsl.ts
+++ b/apps/server/src/box/backends/wsl.ts
@@ -39,8 +39,9 @@ import { externalFetch } from "../../server-fetch.js";
import type { RuntimeResult } from "../runtime.js";
import bundledPins from "../wsl.json" with { type: "json" };
import { IDLE_MINUTES, newMeta, upArgs, type BoxMeta } from "./bwrap.js";
+import { YOUNG_IMAGE_MS, removableImage, removeTree, staleEntries } from "../retention.mjs";
import { boxshExec, num, parseOut, str } from "./shared.js";
-import type { BoxDriver, OpenContext, Opened, PresentImage, SpawnLike } from "./types.js";
+import type { BoxDriver, OpenContext, Opened, PresentImage, Removed, SpawnLike } from "./types.js";
import { ping } from "../client.js";
type Env = NodeJS.ProcessEnv;
@@ -418,8 +419,54 @@ export const wslDriver: BoxDriver = {
const { out } = await boxrun(runtime, ["stop", "--box", boxPath(key)], { run, env });
return { stopped: Boolean(out?.ok) };
},
- async gcImages() {
- return [];
+ /**
+ * Box images in the distro's store that no box uses and that are neither
+ * the current nor the previous pins, and rootfs downloads of other pins
+ * (the distro is imported once; a tarball of other pins is never read again).
+ */
+ async gcImages(runtime, { run = runCommand, env = process.env, home = "", current, used, keep = { refs: current, digests: new Set<string>() }, dryRun = false, now = Date.now(), pins = loadWslPins() }: Parameters<BoxDriver["gcImages"]>[1] & { pins?: WslPins | null }) {
+ const removed: Removed[] = [];
+ if (home) {
+ const cache = path.join(home, "wsl", "cache");
+ const wanted = new Set(Object.values(pins?.assets ?? {}).map((asset) => `${asset?.sha256}.tar.gz`));
+ // The newest tarball of other pins stays (the previous box version's); older ones go.
+ const others = staleEntries(cache, { now, maxAgeMs: -1, match: (name) => /^[0-9a-f]{64}\.tar\.gz$/.test(name) && !wanted.has(name) }).sort((a, b) => b.mtimeMs - a.mtimeMs);
+ for (const item of others.slice(1)) {
+ if (dryRun) removed.push({ kind: "download", name: item.path, reason: "rootfs of other pins", dryRun: true });
+ else if (removeTree(item.path)) removed.push({ kind: "download", name: item.path, reason: "rootfs of other pins" });
+ }
+ // Partial downloads (`.part`) a stopped download left a day ago.
+ for (const item of staleEntries(cache, { now, match: (name) => /\.tmp$|\.part$|\.download$/.test(name) })) {
+ if (dryRun) removed.push({ kind: "download", name: item.path, reason: "left by a stopped download", dryRun: true });
+ else if (removeTree(item.path)) removed.push({ kind: "download", name: item.path, reason: "left by a stopped download" });
+ }
+ }
+ // The distro may not be there (never pulled): nothing in it to remove then.
+ const wsl: WslRuntime = runtime;
+ const listed = await wslCall(wsl.bin, ["--list", "--verbose"], { run, env }).catch(() => null);
+ if (!listed || !parseWslList(listed.stdout).some((row) => row.name.toLowerCase() === String(wsl.distro).toLowerCase())) return removed;
+ const script = `for f in ${STORE}/images/*/image.json; do [ -f "$f" ] || continue; d=\${f%/image.json}; printf '%s\\t%s\\t' "\${d##*/}" "$(stat -c %Y "$f" 2>/dev/null || echo 0)"; tr -d '\\n\\r' < "$f"; printf '\\n'; done`;
+ const res = await wslCall(wsl.bin, inDistro(wsl, ["/bin/sh", "-c", script]), { run, env, timeoutMs: 60_000 });
+ if (res.code !== 0) return removed;
+ const usedIds = new Set<string>(used);
+ for (const name of (() => { try { return readdirSync(path.join(home, "wsl", "boxes")).filter((n) => n.endsWith(".json")); } catch { return [] as string[]; } })()) {
+ const meta = readJson<WslMeta>(path.join(home, "wsl", "boxes", name));
+ if (meta?.image) usedIds.add(meta.image);
+ }
+ for (const line of String(res.stdout || "").split(/\r?\n/)) {
+ const [rawId = "", mtime = "", ...rest] = line.split("\t");
+ const id = rawId.trim();
+ let img: { ref?: string; digest?: string } | null = null;
+ try { img = JSON.parse(rest.join("\t")); } catch { continue; }
+ // Unpacked in the last week (or its age unknown): another app may be about to make a box on it.
+ const unpackedAt = Number(mtime) * 1000;
+ if (!Number.isFinite(unpackedAt) || unpackedAt <= 0 || now - unpackedAt < YOUNG_IMAGE_MS) continue;
+ if (!/^[0-9a-zA-Z._-]+$/.test(id) || !removableImage({ ref: img?.ref, digest: img?.digest, id }, { keep, used: usedIds })) continue;
+ if (dryRun) { removed.push({ kind: "image", name: String(img?.ref), reason: "not current", dryRun: true }); continue; }
+ const { out } = await boxrun(wsl, ["rmimage", "--store", STORE, "--id", id], { run, env, timeoutMs: 120_000 });
+ if (out?.ok) removed.push({ kind: "image", name: String(img?.ref), reason: "not current" });
+ }
+ return removed;
},
async upperBytes(runtime, key, { run = runCommand, env = process.env } = {}) {
const { out } = await boxrun(runtime, ["status", "--box", boxPath(key)], { run, env });
diff --git a/apps/server/src/box/backends/wslc.ts b/apps/server/src/box/backends/wslc.ts
index 716f44e7..9b36cb7b 100644
--- a/apps/server/src/box/backends/wslc.ts
+++ b/apps/server/src/box/backends/wslc.ts
@@ -30,7 +30,8 @@ import { runCommand, type RunCommand, type RunResult } from "../run.js";
import type { RuntimeResult } from "../runtime.js";
import { parseSize } from "./container.js";
import { versionAtLeast } from "./shared.js";
-import type { BoxDriver, OpenContext, Opened, PresentImage } from "./types.js";
+import { removableImage, removalTarget } from "../retention.mjs";
+import type { BoxDriver, OpenContext, Opened, PresentImage, Removed } from "./types.js";
import { ENABLE_HINT, decodeWsl, wslCall, wslExe } from "./wsl.js";
type Env = NodeJS.ProcessEnv;
@@ -248,14 +249,17 @@ export const wslcDriver: BoxDriver = {
const res = await wslc(runtime, ["container", "remove", "--force", containerName(key, env)], { run, timeoutMs: 60_000 });
return { removed: res.code === 0 };
},
- async gcImages(runtime, { run = runCommand, current, used }) {
- const removed = [];
+ async gcImages(runtime, { run = runCommand, current, used, keep = { refs: current, digests: new Set<string>() }, dryRun = false }) {
+ const removed: Removed[] = [];
const res = await wslc(runtime, ["image", "list", "--format", "json"], { run, timeoutMs: 30_000 });
for (const img of parseJsonRows(res.stdout)) {
const ref = img.Repository && img.Tag ? `${img.Repository}:${img.Tag}` : String(img.Name ?? img.Reference ?? "");
- if (!ref || !/(^|\/)omnirush-ai\/box-[a-z]+:/.test(ref) || current.has(ref) || used.has(ref)) continue;
- const del = await wslc(runtime, ["image", "remove", ref], { run, timeoutMs: 60_000 });
- if (del.code === 0) removed.push({ kind: "image", name: ref, reason: "not current" });
+ const image = { ref, digest: typeof img.Digest === "string" ? img.Digest : null, id: String(img.Id ?? img.ID ?? "") };
+ if (!ref || !removableImage(image, { keep, used })) continue;
+ const target = removalTarget(image) || ref;
+ if (dryRun) { removed.push({ kind: "image", name: target, reason: "not current", dryRun: true }); continue; }
+ const del = await wslc(runtime, ["image", "remove", target], { run, timeoutMs: 60_000 });
+ if (del.code === 0) removed.push({ kind: "image", name: target, reason: "not current" });
}
return removed;
},
diff --git a/apps/server/src/box/box-retention.test.ts b/apps/server/src/box/box-retention.test.ts
new file mode 100644
index 00000000..4d5f7f34
--- /dev/null
+++ b/apps/server/src/box/box-retention.test.ts
@@ -0,0 +1,107 @@
+// Old sandbox images across box-version updates (retention.mjs, shared with the CLI):
+// kept are the current and previous pins and every image a box uses.
+import { afterEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+import { gcBoxes } from "./box.js";
+import { bwrapDriver } from "./backends/bwrap.js";
+import { wslDriver } from "./backends/wsl.js";
+import { keptImages } from "./retention.mjs";
+import type { BoxRuntime } from "./common.js";
+import type { RunCommand } from "./run.js";
+
+const D = (c: string) => `sha256:${c.repeat(64)}`;
+const pinsOf = (version: string, digest: string) => ({ version, images: { base: { ref: `ghcr.io/omnirush-ai/box-base:${version}`, digest: D(digest) } } });
+const homes: string[] = [];
+const home = () => { const dir = mkdtempSync(path.join(os.tmpdir(), "box-ret-")); homes.push(dir); return dir; };
+afterEach(() => { for (const dir of homes.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+describe("box image retention", () => {
+ test("first run (no pins recorded yet): no image goes", async () => {
+ const h = home();
+ const removed: string[] = [];
+ const run = (async (_bin: string, args: string[]) => {
+ if (args[0] === "images") return { code: 0, stdout: `ghcr.io/omnirush-ai/box-base\t<none>\t${D("0")}\t000000000000\t1GB\n`, stderr: "" };
+ if (args[0] === "rmi") { removed.push(String(args[1])); return { code: 0, stdout: "", stderr: "" }; }
+ return { code: 0, stdout: "", stderr: "" };
+ }) as unknown as RunCommand;
+ await gcBoxes({ name: "docker", backend: "docker", bin: "docker" } as unknown as BoxRuntime, { home: h, run, pins: pinsOf("2026.10.2", "c") as never, exists: () => true });
+ expect(removed).toEqual([]);
+ });
+
+ test("docker: three box versions on disk, the oldest (a digest pull, <none> tag) goes as repo@digest", async () => {
+ const h = home();
+ keptImages(h, pinsOf("2026.10.1", "a"));
+ const rows = [
+ ["ghcr.io/omnirush-ai/box-base", "<none>", D("c"), "cccccccccccc", "1.03GB"],
+ ["ghcr.io/omnirush-ai/box-base", "<none>", D("a"), "aaaaaaaaaaaa", "1.02GB"],
+ ["ghcr.io/omnirush-ai/box-base", "<none>", D("0"), "000000000000", "1.01GB"],
+ ["ghcr.io/omnirush-ai/sandbox", "1", D("2"), "222222222222", "1.21GB"],
+ ];
+ const removed: string[] = [];
+ const run = (async (_bin: string, args: string[]) => {
+ if (args[0] === "ps") return { code: 0, stdout: "", stderr: "" };
+ if (args[0] === "images") return { code: 0, stdout: rows.map((r) => r.join("\t")).join("\n") + "\n", stderr: "" };
+ if (args[0] === "rmi") { removed.push(String(args[1])); return { code: 0, stdout: "", stderr: "" }; }
+ return { code: 1, stdout: "", stderr: "" };
+ }) as unknown as RunCommand;
+ const runtime = { name: "docker", backend: "docker", bin: "docker" } as unknown as BoxRuntime;
+ const dry = await gcBoxes(runtime, { home: h, run, pins: pinsOf("2026.10.2", "c") as never, exists: () => true, dryRun: true });
+ expect(removed).toEqual([]);
+ expect(dry.map((r) => r.name)).toEqual([`ghcr.io/omnirush-ai/box-base@${D("0")}`]);
+ await gcBoxes(runtime, { home: h, run, pins: pinsOf("2026.10.2", "c") as never, exists: () => true });
+ expect(removed).toEqual([`ghcr.io/omnirush-ai/box-base@${D("0")}`]);
+ });
+
+ test("bwrap: old store images go; a stopped pull's download goes; current and previous stay", async () => {
+ const h = home();
+ keptImages(h, pinsOf("2026.10.1", "a"));
+ const store = path.join(h, "bwrap", "store");
+ const weekAgo = new Date(Date.now() - 8 * 86_400_000);
+ const image = (id: string, digest: string) => { mkdirSync(path.join(store, "images", id), { recursive: true }); writeFileSync(path.join(store, "images", id, "image.json"), JSON.stringify({ ref: `ghcr.io/omnirush-ai/box-base@${digest}`, digest })); utimesSync(path.join(store, "images", id, "image.json"), weekAgo, weekAgo); };
+ image("cur", D("c")); image("prev", D("a")); image("old", D("0")); image("young", D("9"));
+ utimesSync(path.join(store, "images", "young", "image.json"), new Date(), new Date());
+ const stale = path.join(store, "tmp", "a1b2c3");
+ mkdirSync(stale, { recursive: true });
+ const old = new Date(Date.now() - 2 * 86_400_000);
+ utimesSync(stale, old, old);
+ const removed: string[] = [];
+ const run = (async (_bin: string, args: string[]) => {
+ if (args[0] === "rmimage") { removed.push(String(args[args.indexOf("--id") + 1])); return { code: 0, stdout: '{"ok":true}\n', stderr: "" }; }
+ return { code: 0, stdout: "", stderr: "" };
+ }) as unknown as RunCommand;
+ const keep = keptImages(h, pinsOf("2026.10.2", "c"));
+ await bwrapDriver.gcImages({ bin: "boxrun" } as unknown as BoxRuntime, { run, home: h, current: keep.refs, keep, used: new Set() });
+ expect(removed).toEqual(["old"]);
+ expect(existsSync(stale)).toBe(false);
+ });
+
+ test("WSL: images in the distro's store are collected; rootfs tarballs of other pins go", async () => {
+ const h = home();
+ const cache = path.join(h, "wsl", "cache");
+ mkdirSync(cache, { recursive: true });
+ const cur = "1".repeat(64), other = "2".repeat(64);
+ writeFileSync(path.join(cache, `${cur}.tar.gz`), "x");
+ writeFileSync(path.join(cache, `${other}.tar.gz`), "x");
+ utimesSync(path.join(cache, `${other}.tar.gz`), new Date(Date.now() - 30 * 86_400_000), new Date(Date.now() - 30 * 86_400_000));
+ const prev = "4".repeat(64);
+ writeFileSync(path.join(cache, `${prev}.tar.gz`), "previous pins");
+ const longAgo = Math.floor((Date.now() - 30 * 86_400_000) / 1000);
+ const store = [`cur\t${longAgo}\t${JSON.stringify({ ref: `ghcr.io/omnirush-ai/box-base@${D("c")}`, digest: D("c") })}`, `old\t${longAgo}\t${JSON.stringify({ ref: `ghcr.io/omnirush-ai/box-base@${D("0")}`, digest: D("0") })}`].join("\n");
+ const removed: string[] = [];
+ const run = (async (_bin: string, args: string[]) => {
+ if (args.includes("--list")) return { code: 0, stdout: " NAME STATE VERSION\n* OmniRushBox Stopped 2\n", stderr: "" };
+ if (args.includes("/bin/sh")) return { code: 0, stdout: store + "\n", stderr: "" };
+ if (args.includes("rmimage")) { removed.push(String(args[args.indexOf("--id") + 1])); return { code: 0, stdout: '{"ok":true}\n', stderr: "" }; }
+ return { code: 1, stdout: "", stderr: "" };
+ }) as unknown as RunCommand;
+ const keep = keptImages(h, pinsOf("2026.10.2", "c"));
+ await wslDriver.gcImages({ bin: "wsl.exe", distro: "OmniRushBox" } as unknown as BoxRuntime, { run, env: {}, home: h, current: keep.refs, keep, used: new Set(), pins: { assets: { amd64: { url: null, sha256: cur } } } } as never);
+ expect(removed).toEqual(["old"]);
+ expect(existsSync(path.join(cache, `${cur}.tar.gz`))).toBe(true);
+ expect(existsSync(path.join(cache, `${other}.tar.gz`))).toBe(false);
+ expect(existsSync(path.join(cache, `${prev}.tar.gz`))).toBe(true);
+ });
+});
diff --git a/apps/server/src/box/box.ts b/apps/server/src/box/box.ts
index 5e642b28..150982f2 100644
--- a/apps/server/src/box/box.ts
+++ b/apps/server/src/box/box.ts
@@ -38,6 +38,7 @@ import { driverFor } from "./backends/index.js";
import type { ListedBox, SpawnLike } from "./backends/types.js";
import { detectStack, imageFor, type BoxImage, type ImagePins } from "./images.js";
import { runCommand, type RunCommand, type RunOptions } from "./run.js";
+import { keptImages } from "./retention.mjs";
type Env = NodeJS.ProcessEnv;
@@ -730,7 +731,7 @@ export class Box {
// --- status, reset, gc --------------------------------------------------------------
-type Removed = Array<{ kind: string; name: string; reason: string }>;
+type Removed = Array<{ kind: string; name: string; reason: string; size?: string | null; path?: string; dryRun?: boolean }>;
/** Boxes on this machine: { key, name, root, running, image, created }[] */
/** Where boxsh asks the app to start a stopped boxd again (launch.ts boxRun). */
@@ -759,10 +760,10 @@ export async function stopBox(runtime: BoxRuntime, root: string, { env = process
/**
* Remove boxes whose folder is gone or that were not used for `maxIdleDays`,
- * and box images no box uses that are not the current pins. Only boxes and
+ * and box images no box uses that are neither the current nor the previous pins (retention.mjs). Only boxes and
* images labelled/named as OmniRush boxes are touched; nothing is pruned.
*/
-export async function gcBoxes(runtime: BoxRuntime, { env = process.env, home = boxHome(env), run = runCommand, maxIdleDays = 30, pins = null, now = Date.now(), exists = existsSync }: { env?: Env; home?: string; run?: RunCommand; maxIdleDays?: number; pins?: ImagePins | null; now?: number; exists?: (file: string) => boolean } = {}): Promise<Removed> {
+export async function gcBoxes(runtime: BoxRuntime, { env = process.env, home = boxHome(env), run = runCommand, maxIdleDays = 30, pins = null, now = Date.now(), exists = existsSync, dryRun = false }: { env?: Env; home?: string; run?: RunCommand; maxIdleDays?: number; pins?: ImagePins | null; now?: number; exists?: (file: string) => boolean; dryRun?: boolean } = {}): Promise<Removed> {
const driver = driverFor(runtime);
const removed: Removed = [];
const boxes = await driver.list(runtime, { run, env, home });
@@ -773,6 +774,7 @@ export async function gcBoxes(runtime: BoxRuntime, { env = process.env, home = b
if (!rec || (rec.pid && rec.pid !== process.pid && alive(rec.pid)) || (rec.root && box.root && path.resolve(rec.root) !== path.resolve(box.root))) continue;
const idle = rec.updated ? (now - rec.updated) / 86_400_000 : Infinity;
if ((box.root && !exists(box.root)) || idle > maxIdleDays) {
+ if (dryRun) { removed.push({ kind: "container", name: box.name, reason: box.root && !exists(box.root) ? "folder gone" : "unused", dryRun: true }); continue; }
const res = await driver.remove(runtime, box.key, { run, env, home });
if (res.removed) {
removed.push({ kind: "container", name: box.name, reason: box.root && !exists(box.root) ? "folder gone" : "unused" });
@@ -781,10 +783,13 @@ export async function gcBoxes(runtime: BoxRuntime, { env = process.env, home = b
}
}
}
- const current = new Set(Object.values(pins?.images ?? {}).map((pin) => pin.ref));
+ // Kept: the current pins, the box version before them, and every image a box uses.
+ const keep = keptImages(home, pins, { write: !dryRun, now });
+ // The first run knows only the current pins (the previous ones were never recorded): no image goes yet.
+ if (keep.firstRun) return removed;
const used = new Set<string>();
for (const box of await driver.list(runtime, { run, env, home })) used.add(box.image);
- removed.push(...await driver.gcImages(runtime, { run, env, home, current, used }));
+ removed.push(...await driver.gcImages(runtime, { run, env, home, current: keep.refs, keep, used, dryRun, now }));
return removed;
}
diff --git a/apps/server/src/box/launch.ts b/apps/server/src/box/launch.ts
index 8f6e4fc5..94062a4c 100644
--- a/apps/server/src/box/launch.ts
+++ b/apps/server/src/box/launch.ts
@@ -26,6 +26,7 @@ import { boxKey, containerName, gcBoxes, installShell, openBox, recordFile, revi
import { driverFor, normalizeBackend } from "./backends/index.js";
import type { BoxExec } from "./backends/types.js";
import { detectStack, imageFor, loadPins, type BoxImage } from "./images.js";
+import { rememberPins } from "./retention.mjs";
import { detectRuntime, runCommand, type RunCommand, type RuntimeResult } from "./runtime.js";
export const MODES = ["off", "offer", "on"] as const;
@@ -277,6 +278,8 @@ export async function planBox({ env = process.env, home, root, log = () => {}, r
return { box: null, notice: `Sandbox is downloading (${image.approxMb ? `about ${image.approxMb} MB, ` : ""}once${runtime.backend === "wsl" && !runtime.installed ? ", with the OmniRush WSL distro" : ""}); chats here run on this machine until it is ready.`, runtime, image, downloading: true };
}
}
+ // The pins this box starts on are remembered: the next box version keeps their images as the previous ones.
+ rememberPins(home, loadPins());
if (env.OMNIRUSH_BOX_GC !== "off") setTimeout(() => gcInBackground(runtime, home, { log }), 30_000).unref?.();
let opening: Promise<Box> | null = null;
let phase: string | null = null;
diff --git a/apps/server/src/box/retention.d.mts b/apps/server/src/box/retention.d.mts
new file mode 100644
index 00000000..86b25443
--- /dev/null
+++ b/apps/server/src/box/retention.d.mts
@@ -0,0 +1,18 @@
+export const PINS_SEEN_FILE: string;
+export const KEEP_BOX_VERSIONS: number;
+export const STALE_PULL_MS: number;
+
+export interface KeptImages { refs: Set<string>; digests: Set<string>; versions: string[]; firstRun: boolean }
+export const YOUNG_IMAGE_MS: number;
+export function rememberPins(home: string, pins: unknown): void;
+export interface ImageRow { ref?: string | null; digest?: string | null; id?: string | null }
+export interface StaleEntry { name: string; path: string; mtimeMs: number }
+
+export function imageRepo(ref: string | null | undefined): string;
+export function refDigest(ref: string | null | undefined): string | null;
+export function isBoxImage(ref: string | null | undefined): boolean;
+export function keptImages(home: string, pins: unknown, options?: { write?: boolean; now?: number }): KeptImages;
+export function removableImage(image: ImageRow, options?: { keep?: { refs?: Set<string>; digests?: Set<string> }; used?: Set<string> }): boolean;
+export function removalTarget(image: ImageRow): string | null;
+export function removeTree(dir: string): boolean;
+export function staleEntries(dir: string, options?: { now?: number; maxAgeMs?: number; match?: (name: string) => boolean }): StaleEntry[];
diff --git a/apps/server/src/box/retention.mjs b/apps/server/src/box/retention.mjs
new file mode 100644
index 00000000..c8cf51b9
--- /dev/null
+++ b/apps/server/src/box/retention.mjs
@@ -0,0 +1,167 @@
+// Which sandbox images stay on disk across box-version updates. The same file
+// in omnirush-cli (src/box/retention.mjs) and omnirush-gui
+// (apps/server/src/box/retention.mjs); see PARITY.sha256 in both.
+//
+// Kept: the images of the current pins and of the box version before them
+// (so going back one app version does not download again), and every image a
+// box still uses. Only OmniRush box images (omnirush-ai/box-<stack>, by tag
+// or by digest) are ever removed; nothing is pruned.
+
+import { chmodSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+export const PINS_SEEN_FILE = "pins-seen.json";
+/** Box versions remembered: the current one and the one before it. */
+export const KEEP_BOX_VERSIONS = 2;
+/** Downloads a killed pull left behind are removed once this old. */
+export const STALE_PULL_MS = 24 * 3_600_000;
+
+/** The repository of an image reference, without its tag or digest. */
+export function imageRepo(ref) {
+ let text = String(ref || "").trim();
+ const at = text.indexOf("@");
+ if (at >= 0) text = text.slice(0, at);
+ const slash = text.lastIndexOf("/");
+ const colon = text.lastIndexOf(":");
+ if (colon > slash) text = text.slice(0, colon);
+ return text.replace(/^docker\.io\//, "");
+}
+
+/** The digest in a reference (`repo@sha256:…`), else null. */
+export function refDigest(ref) {
+ const m = /@(sha256:[0-9a-f]{64})$/.exec(String(ref || "").trim());
+ return m ? m[1] : null;
+}
+
+/** An OmniRush box image (`…/omnirush-ai/box-<stack>`, by tag or by digest). */
+export function isBoxImage(ref) {
+ return /(^|\/)omnirush-ai\/box-[a-z]+$/.test(imageRepo(ref));
+}
+
+function pinEntry(pins) {
+ const images = Object.values(pins?.images ?? {});
+ const refs = images.map((pin) => String(pin?.ref || "")).filter(Boolean);
+ const digests = images.map((pin) => String(pin?.digest || "")).filter((d) => /^sha256:[0-9a-f]{64}$/.test(d));
+ return { version: String(pins?.version || ""), refs, digests };
+}
+
+function readSeen(home) {
+ try {
+ const value = JSON.parse(readFileSync(path.join(home, PINS_SEEN_FILE), "utf8"));
+ return Array.isArray(value?.versions) ? value.versions.filter((v) => v && typeof v.version === "string" && Array.isArray(v.refs) && Array.isArray(v.digests)) : [];
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * The images to keep: the current pins and the box version seen before them.
+ * Records the current pins in `<home>/pins-seen.json` (unless `write` is false),
+ * so the next box version knows which one came before it.
+ */
+export function keptImages(home, pins, { write = true, now = Date.now() } = {}) {
+ const current = pinEntry(pins);
+ const seen = readSeen(home);
+ const firstRun = seen.length === 0;
+ const versions = current.version
+ ? [{ ...current, seen_at: now }, ...seen.filter((v) => v.version !== current.version)].slice(0, KEEP_BOX_VERSIONS)
+ : seen.slice(0, KEEP_BOX_VERSIONS);
+ if (write && current.version && (seen[0]?.version !== current.version || seen.length > KEEP_BOX_VERSIONS)) {
+ try {
+ mkdirSync(home, { recursive: true });
+ const file = path.join(home, PINS_SEEN_FILE);
+ const tmp = `${file}.${process.pid}.tmp`;
+ writeFileSync(tmp, JSON.stringify({ v: 1, versions }));
+ renameSync(tmp, file);
+ } catch { /* best effort: only the current pins are known then */ }
+ }
+ const refs = new Set();
+ const digests = new Set();
+ for (const v of versions) {
+ for (const ref of v.refs) refs.add(String(ref));
+ for (const digest of v.digests) digests.add(String(digest));
+ }
+ // The legacy "current" set some callers pass (refs only) is covered by refs.
+ for (const ref of current.refs) refs.add(ref);
+ return { refs, digests, versions: versions.map((v) => v.version), firstRun };
+}
+
+/** Records the pins a box starts on (a box start or pull), so the next box version knows the one before it. Never throws. */
+export function rememberPins(home, pins) {
+ try { keptImages(home, pins); } catch { /* best effort */ }
+}
+
+/** Images unpacked this recently are never removed (another app may be about to make a box on it). */
+export const YOUNG_IMAGE_MS = 7 * 24 * 3_600_000;
+
+/**
+ * Whether an image may be removed: an OmniRush box image that is neither
+ * kept (current or previous pins) nor used by a box. `image`: { ref, digest, id }
+ * where ref is `repo:tag`, `repo@digest` or `repo:<none>`; `used` holds the
+ * refs, ids and digests boxes run on.
+ */
+export function removableImage(image, { keep = { refs: new Set(), digests: new Set() }, used = new Set() } = {}) {
+ const ref = String(image?.ref || "");
+ if (!ref || !isBoxImage(ref)) return false;
+ const repo = imageRepo(ref);
+ // The listed digest and the one in the reference (a store may record another digest than the pin's).
+ const digests = [...new Set([/^sha256:[0-9a-f]{64}$/.test(String(image?.digest || "")) ? String(image.digest) : null, refDigest(ref)].filter(Boolean))];
+ const id = String(image?.id || "");
+ const tagged = /:[^/@]+$/.test(ref) && !/:<none>$/.test(ref) && !refDigest(ref) ? ref : null;
+ const names = [ref, tagged, ...digests, ...digests.map((d) => `${repo}@${d}`), id, id && `sha256:${id}`].filter(Boolean);
+ if (names.some((name) => used.has(name))) return false;
+ if (tagged && keep.refs?.has(tagged)) return false;
+ if (digests.some((d) => keep.digests?.has(d))) return false;
+ // An id that is a prefix of a used full id (docker prints 12 characters).
+ if (id && [...used].some((u) => typeof u === "string" && (u.startsWith(id) || u.startsWith(`sha256:${id}`)))) return false;
+ return true;
+}
+
+/** What to name in `rmi`: repo@digest when known (a digest pull has no tag), else repo:tag, else the id. */
+export function removalTarget({ ref, digest, id }) {
+ const repo = imageRepo(ref);
+ const d = /^sha256:[0-9a-f]{64}$/.test(String(digest || "")) ? digest : refDigest(ref);
+ if (d) return `${repo}@${d}`;
+ if (ref && /:[^/@]+$/.test(ref) && !/:<none>$/.test(ref)) return ref;
+ return id || null;
+}
+
+/**
+ * Remove a folder tree this user owns, also when parts are read-only (an
+ * unpacked rootfs). Returns false when something stayed (a locked file on
+ * Windows, a file of another user); never throws.
+ */
+export function removeTree(dir) {
+ try {
+ const walk = (p) => {
+ let st;
+ try { st = lstatSync(p); } catch { return; }
+ if (!st.isDirectory()) return;
+ try { chmodSync(p, 0o700); } catch { /* not ours */ }
+ let names = [];
+ try { names = readdirSync(p); } catch { return; }
+ for (const name of names) walk(path.join(p, name));
+ };
+ walk(dir);
+ rmSync(dir, { recursive: true, force: true, maxRetries: 2, retryDelay: 200 });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Entries of `dir` (a pull's download folder) older than `maxAgeMs`: [{ name, path, mtimeMs }]. */
+export function staleEntries(dir, { now = Date.now(), maxAgeMs = STALE_PULL_MS, match = () => true } = {}) {
+ let names = [];
+ try { names = readdirSync(dir); } catch { return []; }
+ const out = [];
+ for (const name of names) {
+ if (!match(name)) continue;
+ const p = path.join(dir, name);
+ try {
+ const st = statSync(p);
+ if (now - st.mtimeMs > maxAgeMs) out.push({ name, path: p, mtimeMs: st.mtimeMs });
+ } catch { /* gone */ }
+ }
+ return out;
+}
diff --git a/apps/server/src/opencode-v2-binary.ts b/apps/server/src/opencode-v2-binary.ts
index 317d89f4..3554734b 100644
--- a/apps/server/src/opencode-v2-binary.ts
+++ b/apps/server/src/opencode-v2-binary.ts
@@ -1,7 +1,7 @@
import { externalFetch } from "./server-fetch.js";
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
-import { access, chmod, mkdir, mkdtemp, rename, rm, writeFile } from "node:fs/promises";
+import { access, chmod, mkdir, mkdtemp, readdir, rename, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import artifacts from "./opencode-v2-artifacts.json" with { type: "json" };
@@ -21,7 +21,7 @@ export async function installOpencodeV2Binary(cacheRoot: string, version: string
const directory = join(cacheRoot, version, key);
const name = platform === "windows" ? "opencode2.exe" : "opencode2";
const binary = join(directory, name);
- try { await access(binary); return binary; } catch { /* First installation. */ }
+ try { await access(binary); void pruneOpencodeV2Versions(cacheRoot, version); return binary; } catch { /* First installation. */ }
await mkdir(cacheRoot, { recursive: true, mode: 0o700 });
await chmod(cacheRoot, 0o700);
await mkdir(directory, { recursive: true, mode: 0o700 });
@@ -39,8 +39,41 @@ export async function installOpencodeV2Binary(cacheRoot: string, version: string
const extracted = join(staging, "package", "bin", name);
await chmod(extracted, 0o755);
await rename(extracted, binary);
+ void pruneOpencodeV2Versions(cacheRoot, version);
return binary;
} finally {
await rm(staging, { recursive: true, force: true });
}
}
+
+function versionParts(value: string): number[] | null {
+ const m = /^(\d+)\.(\d+)\.(\d+)/.exec(value);
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
+}
+
+function olderThan(a: number[], b: number[]): boolean {
+ for (let i = 0; i < 3; i += 1) if (a[i] !== b[i]) return a[i] < b[i];
+ return false;
+}
+
+/**
+ * Downloaded engine versions other than the current one and the newest older
+ * one (what the previous app version runs) go; newer ones (an app version
+ * ahead of this one) and names that are not versions stay. Never throws.
+ */
+export async function pruneOpencodeV2Versions(cacheRoot: string, current: string): Promise<string[]> {
+ const now = versionParts(current);
+ if (!now) return [];
+ let names: string[] = [];
+ try { names = await readdir(cacheRoot); } catch { return []; }
+ const older = names
+ .map((name) => ({ name, parts: versionParts(name) }))
+ .filter((entry): entry is { name: string; parts: number[] } => Boolean(entry.parts) && entry.name !== current && /^\d+\.\d+\.\d+[0-9A-Za-z.+-]*$/.test(entry.name))
+ .filter((entry) => olderThan(entry.parts, now))
+ .sort((a, b) => (olderThan(a.parts, b.parts) ? -1 : olderThan(b.parts, a.parts) ? 1 : 0));
+ const removed: string[] = [];
+ for (const entry of older.slice(0, -1)) {
+ try { await rm(join(cacheRoot, entry.name), { recursive: true, force: true, maxRetries: 2 }); removed.push(entry.name); } catch { /* in use (Windows): next start */ }
+ }
+ return removed;
+}
diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.ts
index b80db9c3..54e5d771 100644
--- a/packages/types/src/desktop-ipc.ts
+++ b/packages/types/src/desktop-ipc.ts
@@ -1185,6 +1185,18 @@ export type DesktopCommandMap = {
/** Opens <userData>/logs in the system file manager. Takes no path from the renderer. */
openLogsFolder: { args: []; result: { ok: boolean; error?: string } };
+ /** Settings > Storage. Lists (dryRun) or removes what the app no longer needs; takes no path from the renderer. */
+ freeUpSpace: {
+ args: [options?: { dryRun?: boolean }];
+ result: {
+ ok: boolean;
+ skipped: string | null;
+ dryRun: boolean;
+ freedBytes: number;
+ freed: string;
+ items: Array<{ kind: string; path: string; bytes: number; size: string; reason: string; inUse: boolean }>;
+ };
+ };
// Window / OS utilities (dunder commands)
__openPath: { args: [target: string]; result: unknown };