Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(retention): prune dependency and build folders from idle task workspaces
boss477 fawaz_ahad59d6aa75a5
diff --git a/server/host/start-upkeep.test.ts b/server/host/start-upkeep.test.tsindex 0a59c5f905..d961176766 100644--- a/server/host/start-upkeep.test.ts+++ b/server/host/start-upkeep.test.ts@@ -20,6 +20,7 @@ describe("start-up upkeep", () => {busy: (_botId, threadId) => threadId === "working",openDirectHandoff: (threadId) => threadId === "quiet",cleanupPartials: () => { calls.push("partials"); return 0; },+ sweepWorkspaces: () => { calls.push("workspaces"); return []; },sweepLogs: (candidates, days) => {calls.push(`logs ${days}: ${[...candidates].map((c) => `${c.threadId}${c.busy ? " busy" : ""}${c.openDirectHandoff ? " handoff" : ""}${c.unread ? " unread" : ""}`).join(", ")}`);return 0;@@ -28,11 +29,11 @@ describe("start-up upkeep", () => {expect(calls).toEqual([]);await vi.advanceTimersByTimeAsync(0);const pass = "logs 30: quiet handoff, working busy, handed unread";- expect(calls).toEqual(["partials", pass]);+ expect(calls).toEqual(["partials", pass, "workspaces"]);await vi.advanceTimersByTimeAsync(THREAD_LOG_RETENTION_SWEEP_MS - 1);- expect(calls).toEqual(["partials", pass]);+ expect(calls).toEqual(["partials", pass, "workspaces"]);await vi.advanceTimersByTimeAsync(1);- expect(calls).toEqual(["partials", pass, pass]);+ expect(calls).toEqual(["partials", pass, "workspaces", pass, "workspaces"]);});it("still sweeps the logs when the partials fail, and sweeps none without a retention", async () => {@@ -47,6 +48,7 @@ describe("start-up upkeep", () => {openDirectHandoff: () => false,cleanupPartials: () => { throw new Error("disk gone"); },sweepLogs: (_candidates, days) => { swept.push(days); return 0; },+ sweepWorkspaces: () => [],});await vi.advanceTimersByTimeAsync(0);expect(warn).toHaveBeenCalledWith("attachments: startup partial cleanup failed: disk gone");@@ -55,4 +57,25 @@ describe("start-up upkeep", () => {await vi.advanceTimersByTimeAsync(THREAD_LOG_RETENTION_SWEEP_MS);expect(swept).toEqual([7]);});++ it("sweeps idle task workspaces even without a log retention, and keeps going when the logs' sweep fails", async () => {+ vi.useFakeTimers();+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const seen: string[] = [];+ startUpkeep({+ bots: () => [{ id: "bot", tasks: [task("idle", { createdAt: 5, updatedAt: 10, closedBy: { at: 20 } } as Partial<TaskRecord>), task("working")] }],+ retentionDays: () => 7,+ busy: (_botId, threadId) => threadId === "working",+ openDirectHandoff: () => false,+ cleanupPartials: () => 0,+ sweepLogs: () => { throw new Error("logs gone"); },+ sweepWorkspaces: (candidates) => {+ seen.push(...[...candidates].map((c) => `${c.botId}/${c.threadId} ${c.lastActiveAt}${c.busy ? " busy" : ""}`));+ return [];+ },+ });+ await vi.advanceTimersByTimeAsync(0);+ expect(warn).toHaveBeenCalledWith("thread event log retention sweep failed: logs gone");+ expect(seen).toEqual(["bot/idle 20", "bot/working 1 busy"]);+ });});diff --git a/server/host/start-upkeep.ts b/server/host/start-upkeep.tsindex ace653d16b..2396120fdd 100644--- a/server/host/start-upkeep.ts+++ b/server/host/start-upkeep.ts@@ -1,8 +1,9 @@-// The attachments' and the thread logs' upkeep. Both are safe beside requests: an upload in flight keeps its partial-// and its reservation, and a busy, unread or handed-off thread keeps its log. So the first pass runs once the server-// answers, not before it listens, and the logs' sweep then runs once a day.+// The attachments', the thread logs' and the task workspaces' upkeep. All are safe beside requests: an upload in+// flight keeps its partial and its reservation, and a busy, unread or handed-off thread keeps its log and its+// workspace. So the first pass runs once the server answers, not before it listens, and the sweeps then run once a day.import { cleanupStaleAttachmentPartials } from "../attachments.ts";import type { BotRecord } from "../store.ts";+import { sweepTaskWorkspaceBuildFolders } from "../task-workspace-retention.ts";import { sweepThreadEventLogs } from "../thread-retention.ts";export const THREAD_LOG_RETENTION_SWEEP_MS = 24 * 60 * 60 * 1000;@@ -14,6 +15,7 @@ export interface StartUpkeepDeps {openDirectHandoff: (threadId: string) => boolean;cleanupPartials?: () => number;sweepLogs?: typeof sweepThreadEventLogs;+ sweepWorkspaces?: (candidates: Parameters<typeof sweepTaskWorkspaceBuildFolders>[0]) => string[];}const reason = (error: unknown) => error instanceof Error ? error.message : String(error);@@ -33,6 +35,30 @@ export function startUpkeep(deps: StartUpkeepDeps): void {const swept = (deps.sweepLogs ?? sweepThreadEventLogs)(candidates, retentionDays);if (swept > 0) console.log(`[retention] removed event logs for ${swept} idle thread(s) past ${retentionDays} day(s)`);};+ const sweepWorkspacesNow = () => {+ const candidates = deps.bots().flatMap((bot) => (bot.tasks ?? []).map((task) => ({+ botId: bot.id,+ threadId: task.threadId,+ lastActiveAt: Math.max(task.updatedAt ?? task.createdAt ?? 0, task.closedBy?.at ?? 0, task.archivedAt ?? 0),+ unread: task.unread === true,+ busy: deps.busy(bot.id, task.threadId),+ openDirectHandoff: deps.openDirectHandoff(task.threadId),+ })));+ const removed = (deps.sweepWorkspaces ?? ((c) => sweepTaskWorkspaceBuildFolders(c)))(candidates);+ if (removed.length > 0) console.log(`[retention] removed ${removed.length} dependency or build folder(s) from idle task workspaces`);+ };+ const sweepAll = () => {+ try {+ sweepLogsNow();+ } catch (error) {+ console.warn(`thread event log retention sweep failed: ${reason(error)}`);+ }+ try {+ sweepWorkspacesNow();+ } catch (error) {+ console.warn(`task workspace retention sweep failed: ${reason(error)}`);+ }+ };setImmediate(() => {try {const reclaimed = (deps.cleanupPartials ?? cleanupStaleAttachmentPartials)();@@ -40,11 +66,7 @@ export function startUpkeep(deps: StartUpkeepDeps): void {} catch (error) {console.warn(`attachments: startup partial cleanup failed: ${reason(error)}`);}- try {- sweepLogsNow();- } catch (error) {- console.warn(`thread event log retention sweep failed: ${reason(error)}`);- }+ sweepAll();});- setInterval(sweepLogsNow, THREAD_LOG_RETENTION_SWEEP_MS).unref();+ setInterval(sweepAll, THREAD_LOG_RETENTION_SWEEP_MS).unref();}diff --git a/server/task-workspace-retention.test.ts b/server/task-workspace-retention.test.tsnew file mode 100644index 0000000000..3c8e1e5d43--- /dev/null+++ b/server/task-workspace-retention.test.ts@@ -0,0 +1,91 @@+import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { sweepTaskWorkspaceBuildFolders, type TaskWorkspaceRetentionCandidate } from "./task-workspace-retention.ts";++const DAY_MS = 24 * 60 * 60 * 1000;+const now = Date.parse("2026-01-31T12:00:00Z");+let root: string;++beforeEach(() => { root = mkdtempSync(join(tmpdir(), "omb-workspace-retention-")); });+afterEach(() => { rmSync(root, { recursive: true, force: true }); });++function candidate(overrides: Partial<TaskWorkspaceRetentionCandidate> & { threadId: string }): TaskWorkspaceRetentionCandidate {+ return { botId: "bot", lastActiveAt: now - 30 * DAY_MS, unread: false, busy: false, openDirectHandoff: false, ...overrides };+}++function file(path: string, text = "x") {+ mkdirSync(join(path, ".."), { recursive: true });+ writeFileSync(path, text);+}++function workspace(threadId: string) {+ const dir = join(root, "bot", threadId);+ file(join(dir, "notes.md"));+ file(join(dir, "repo", "package.json"), "{}");+ file(join(dir, "repo", "node_modules", "left-pad", "index.js"));+ file(join(dir, "repo", "src", "index.ts"));+ file(join(dir, "py", ".venv", "pyvenv.cfg"));+ file(join(dir, "py", ".venv", "lib", "site.py"));+ file(join(dir, "rust", "Cargo.toml"));+ file(join(dir, "rust", "target", "debug", "app"));+ return dir;+}++describe("task workspace retention", () => {+ it("removes dependency and build folders of a long-idle thread and keeps its own files", () => {+ const dir = workspace("old");++ const removed = sweepTaskWorkspaceBuildFolders([candidate({ threadId: "old" })], 14, now, root);++ expect(removed.sort()).toEqual([join(dir, "py", ".venv"), join(dir, "repo", "node_modules"), join(dir, "rust", "target")].sort());+ for (const kept of ["notes.md", "repo/package.json", "repo/src/index.ts", "rust/Cargo.toml"]) expect(existsSync(join(dir, kept)), kept).toBe(true);+ });++ it("keeps folders that only share a name with build output", () => {+ const dir = join(root, "bot", "lookalikes");+ file(join(dir, "docs", "target", "page.md"));+ file(join(dir, "venv", "readme.md"));++ expect(sweepTaskWorkspaceBuildFolders([candidate({ threadId: "lookalikes" })], 14, now, root)).toEqual([]);+ expect(existsSync(join(dir, "docs", "target", "page.md"))).toBe(true);+ expect(existsSync(join(dir, "venv", "readme.md"))).toBe(true);+ });++ it("never touches a recent, busy, unread or handed-off thread", () => {+ const cases = [+ candidate({ threadId: "recent", lastActiveAt: now - 13 * DAY_MS }),+ candidate({ threadId: "exact", lastActiveAt: now - 14 * DAY_MS }),+ candidate({ threadId: "busy", busy: true }),+ candidate({ threadId: "unread", unread: true }),+ candidate({ threadId: "handoff", openDirectHandoff: true }),+ ];+ for (const each of cases) workspace(each.threadId);++ expect(sweepTaskWorkspaceBuildFolders(cases, 14, now, root)).toEqual([]);+ for (const each of cases) expect(existsSync(join(root, "bot", each.threadId, "repo", "node_modules"))).toBe(true);+ });++ it("does not follow a link out of the workspace", () => {+ const outside = join(root, "outside");+ file(join(outside, "node_modules", "keep.js"));+ const dir = join(root, "bot", "linked");+ mkdirSync(dir, { recursive: true });+ symlinkSync(outside, join(dir, "elsewhere"), "junction");++ expect(sweepTaskWorkspaceBuildFolders([candidate({ threadId: "linked" })], 14, now, root)).toEqual([]);+ expect(existsSync(join(outside, "node_modules", "keep.js"))).toBe(true);+ });++ it("ignores ids that are not plain folder names and threads without a workspace", () => {+ file(join(root, "escape", "node_modules", "keep.js"));++ expect(sweepTaskWorkspaceBuildFolders([+ candidate({ botId: "..", threadId: "escape" }),+ candidate({ threadId: "never-created" }),+ ], 14, now, root)).toEqual([]);+ expect(existsSync(join(root, "escape", "node_modules", "keep.js"))).toBe(true);+ });+});diff --git a/server/task-workspace-retention.ts b/server/task-workspace-retention.tsnew file mode 100644index 0000000000..11a83f814e--- /dev/null+++ b/server/task-workspace-retention.ts@@ -0,0 +1,74 @@+// Removes re-creatable dependency and build folders (node_modules, Python virtualenvs, Cargo target) from the task+// workspaces of long-idle threads. A conversation's own files, clones and outputs stay; only what an install or a+// build puts back is removed, and never in a busy, unread or handed-off thread.+import { existsSync, lstatSync, readdirSync, rmSync } from "node:fs";+import { join } from "node:path";+import { TASK_WORKSPACES_DIR } from "./workspace.ts";++export const TASK_WORKSPACE_IDLE_DAYS = 14;+const MAX_DEPTH = 6;+const DAY_MS = 24 * 60 * 60 * 1000;+const ID = /^[A-Za-z0-9_-]{1,128}$/;++export interface TaskWorkspaceRetentionCandidate {+ botId: string;+ threadId: string;+ lastActiveAt: number;+ unread: boolean;+ busy: boolean;+ openDirectHandoff: boolean;+}++function isRecreatable(parent: string, name: string): boolean {+ if (name === "node_modules") return true;+ if (name === ".venv" || name === "venv") return existsSync(join(parent, name, "pyvenv.cfg"));+ if (name === "target") return existsSync(join(parent, "Cargo.toml"));+ return false;+}++function findRecreatable(dir: string, depth: number, found: string[]): void {+ let entries;+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch {+ return;+ }+ for (const entry of entries) {+ if (!entry.isDirectory() || entry.name === ".git") continue;+ if (isRecreatable(dir, entry.name)) found.push(join(dir, entry.name));+ else if (depth < MAX_DEPTH) findRecreatable(join(dir, entry.name), depth + 1, found);+ }+}++/** Returns the folders it removed. */+export function sweepTaskWorkspaceBuildFolders(+ candidates: Iterable<TaskWorkspaceRetentionCandidate>,+ idleDays: number = TASK_WORKSPACE_IDLE_DAYS,+ now: number = Date.now(),+ root: string = TASK_WORKSPACES_DIR,+): string[] {+ const cutoff = now - idleDays * DAY_MS;+ const removed: string[] = [];+ for (const candidate of candidates) {+ if (candidate.unread || candidate.busy || candidate.openDirectHandoff) continue;+ if (candidate.lastActiveAt >= cutoff) continue;+ if (!ID.test(candidate.botId) || !ID.test(candidate.threadId)) continue;+ const workspace = join(root, candidate.botId, candidate.threadId);+ try {+ if (!lstatSync(workspace).isDirectory()) continue;+ } catch {+ continue;+ }+ const found: string[] = [];+ findRecreatable(workspace, 1, found);+ for (const path of found) {+ try {+ rmSync(path, { recursive: true, force: true, maxRetries: 2 });+ removed.push(path);+ } catch (error) {+ console.warn(`[retention] could not remove ${path}: ${(error as Error).message}`);+ }+ }+ }+ return removed;+}