Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Idle task workspace sweep: remove dependency folders without blocking the server, keep build output
milind-soni4659b1c507c4
diff --git a/server/host/start-upkeep.ts b/server/host/start-upkeep.tsindex 2396120fdd..e5941e4e83 100644--- a/server/host/start-upkeep.ts+++ b/server/host/start-upkeep.ts@@ -15,7 +15,7 @@ export interface StartUpkeepDeps {openDirectHandoff: (threadId: string) => boolean;cleanupPartials?: () => number;sweepLogs?: typeof sweepThreadEventLogs;- sweepWorkspaces?: (candidates: Parameters<typeof sweepTaskWorkspaceBuildFolders>[0]) => string[];+ sweepWorkspaces?: (candidates: Parameters<typeof sweepTaskWorkspaceBuildFolders>[0]) => string[] | Promise<string[]>;}const reason = (error: unknown) => error instanceof Error ? error.message : String(error);@@ -35,17 +35,31 @@ 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`);+ // Read lazily: the removals before a thread's turn take time, and a thread that wakes meanwhile must read busy.+ function* workspaceCandidates() {+ for (const bot of deps.bots()) {+ for (const task of bot.tasks ?? []) {+ yield {+ 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),+ };+ }+ }+ }+ let sweepingWorkspaces = false;+ const sweepWorkspacesNow = async () => {+ if (sweepingWorkspaces) return;+ sweepingWorkspaces = true;+ try {+ const removed = await (deps.sweepWorkspaces ?? ((c) => sweepTaskWorkspaceBuildFolders(c)))(workspaceCandidates());+ if (removed.length > 0) console.log(`[retention] removed ${removed.length} dependency folder(s) from idle task workspaces`);+ } finally {+ sweepingWorkspaces = false;+ }};const sweepAll = () => {try {@@ -53,11 +67,7 @@ export function startUpkeep(deps: StartUpkeepDeps): void {} 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)}`);- }+ sweepWorkspacesNow().catch((error: unknown) => console.warn(`task workspace retention sweep failed: ${reason(error)}`));};setImmediate(() => {try {diff --git a/server/task-workspace-retention.test.ts b/server/task-workspace-retention.test.tsindex 67c2e144ad..9a23ac71f4 100644--- a/server/task-workspace-retention.test.ts+++ b/server/task-workspace-retention.test.ts@@ -35,26 +35,27 @@ function workspace(threadId: string) {}describe("task workspace retention", () => {- it("removes dependency and build folders of a long-idle thread and keeps its own files", () => {+ it("removes dependency folders of a long-idle thread and keeps its own files and build output", async () => {const dir = workspace("old");- const removed = sweepTaskWorkspaceBuildFolders([candidate({ threadId: "old" })], 14, now, root);+ const removed = await 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);+ expect(removed.sort()).toEqual([join(dir, "py", ".venv"), join(dir, "repo", "node_modules")].sort());+ // Build output syncs to the person's computer, so it stays.+ for (const kept of ["notes.md", "repo/package.json", "repo/src/index.ts", "rust/Cargo.toml", "rust/target/debug/app"]) expect(existsSync(join(dir, kept)), kept).toBe(true);});- it("keeps folders that only share a name with build output", () => {+ it("keeps folders that only share a name with a dependency folder", async () => {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(await 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", () => {+ it("never touches a recent, busy, unread or handed-off thread", async () => {const cases = [candidate({ threadId: "recent", lastActiveAt: now - 13 * DAY_MS }),candidate({ threadId: "exact", lastActiveAt: now - 14 * DAY_MS }),@@ -64,34 +65,34 @@ describe("task workspace retention", () => {];for (const each of cases) workspace(each.threadId);- expect(sweepTaskWorkspaceBuildFolders(cases, 14, now, root)).toEqual([]);+ expect(await 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", () => {+ it("does not follow a link out of the workspace", async () => {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(await sweepTaskWorkspaceBuildFolders([candidate({ threadId: "linked" })], 14, now, root)).toEqual([]);expect(existsSync(join(outside, "node_modules", "keep.js"))).toBe(true);});- it("skips a bot folder that is a link", () => {+ it("skips a bot folder that is a link", async () => {const outside = join(root, "outside");file(join(outside, "linked", "repo", "node_modules", "keep.js"));symlinkSync(outside, join(root, "linkbot"), "junction");- expect(sweepTaskWorkspaceBuildFolders([candidate({ botId: "linkbot", threadId: "linked" })], 14, now, root)).toEqual([]);+ expect(await sweepTaskWorkspaceBuildFolders([candidate({ botId: "linkbot", threadId: "linked" })], 14, now, root)).toEqual([]);expect(existsSync(join(outside, "linked", "repo", "node_modules", "keep.js"))).toBe(true);});- it("ignores ids that are not plain folder names and threads without a workspace", () => {+ it("ignores ids that are not plain folder names and threads without a workspace", async () => {file(join(root, "escape", "node_modules", "keep.js"));- expect(sweepTaskWorkspaceBuildFolders([+ expect(await sweepTaskWorkspaceBuildFolders([candidate({ botId: "..", threadId: "escape" }),candidate({ threadId: "never-created" }),], 14, now, root)).toEqual([]);diff --git a/server/task-workspace-retention.ts b/server/task-workspace-retention.tsindex 987cc974df..0b61470e92 100644--- a/server/task-workspace-retention.ts+++ b/server/task-workspace-retention.ts@@ -1,7 +1,9 @@-// 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";+// Removes re-creatable dependency folders (node_modules, Python virtualenvs) from the task workspaces of long-idle+// threads. A conversation's own files, clones and outputs stay; only what an install puts back is removed, and never in+// a busy, unread or handed-off thread. Only folders folder sync never carries to the person's computer, so no copy of+// theirs changes. Removal is asynchronous: gigabytes of them must not stall the server's replies.+import { existsSync, lstatSync, readdirSync } from "node:fs";+import { rm } from "node:fs/promises";import { join } from "node:path";import { TASK_WORKSPACES_DIR } from "./workspace.ts";@@ -22,7 +24,6 @@ export interface TaskWorkspaceRetentionCandidate {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;}@@ -50,13 +51,13 @@ function findRecreatable(dir: string, depth: number, found: string[]): void {}}-/** Returns the folders it removed. */-export function sweepTaskWorkspaceBuildFolders(+/** Returns the folders it removed. Each candidate is read when its turn comes, so a thread that wakes mid-sweep is kept. */+export async function sweepTaskWorkspaceBuildFolders(candidates: Iterable<TaskWorkspaceRetentionCandidate>,idleDays: number = TASK_WORKSPACE_IDLE_DAYS,now: number = Date.now(),root: string = TASK_WORKSPACES_DIR,-): string[] {+): Promise<string[]> {const cutoff = now - idleDays * DAY_MS;const removed: string[] = [];for (const candidate of candidates) {@@ -71,7 +72,7 @@ export function sweepTaskWorkspaceBuildFolders(for (const path of found) {if (!isRealDirectory(path)) continue;try {- rmSync(path, { recursive: true, force: true, maxRetries: 2 });+ await rm(path, { recursive: true, force: true, maxRetries: 2 });removed.push(path);} catch (error) {console.warn(`[retention] could not remove ${path}: ${(error as Error).message}`);