feat(settings): add automatic storage cleanup per machine and project #11598
Mergedmaria-rcksmerged 25 commits into
main fromrefs/pull/11598/headmerged by maria-rcks View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/web/src/components/settings/StorageSettings.tsx lines 131 to 132Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +64,21 @@64+export function StorageSettingsPanel() {65+ const { scope, connectedEnvironments, environments } = useSettingsScope();66+ const settings = useScopedSettings(67+ (value) => value.storageCleanup ?? DEFAULT_SERVER_SETTINGS.storageCleanup,68+ );69+ const updateSettings = useUpdateScopedSettings();70+ const mixed = useScopedSettingsMixed(["storageCleanup"]);71+ const update = (patch: Partial<StorageCleanupSettings>) =>72+ updateSettings({ storageCleanup: patch });73+74+ if (scope.kind === "project" || scope.kind === "checkout") {75+ return (76+ <SettingsScopeNotice target="all">77+ Storage cleanup applies to machines. Choose all environments or a single machine to manage78+ its files.79+ </SettingsScopeNotice>80+ );81+ }82+83+ if (84+ connectedEnvironments.some(apps/server/src/storageCleanup.ts lines 97 to 99OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +79,21 @@79+ liveTerminals.set(terminal.threadId, threadTerminals);80+ };81+82+ const inside = (root: string, target: string) => {83+ const relative = path.relative(root, target);84+ return (85+ relative !== "" &&86+ relative !== ".." &&87+ !relative.startsWith(`..${path.sep}`) &&88+ !path.isAbsolute(relative)89+ );90+ };91+ const hasTerminal = (worktreePath: string) =>92+ [...liveTerminals.values()]93+ .flatMap((entries) => [...entries.values()])94+ .some(95+ (terminal) =>96+ (terminal.status === "starting" || terminal.status === "running") &&97+ (terminal.worktreePath === worktreePath ||98+ terminal.cwd === worktreePath ||99+ inside(worktreePath, terminal.cwd)),apps/server/src/terminal/Manager.ts line 2646OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2639,3 +2642,5 @@26392642 return snapshot(liveSession);26402643 });264126442645+ const openLocked = (input: TerminalOpenInput) =>2646+ withThreadWorkspaceLease(input.threadId, openWithWorkspaceLease(input));
- apps/server/src/storageCleanup.ts line 31OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +11,21 @@11+import * as Option from "effect/Option";12+import * as Path from "effect/Path";13+import type { PlatformError } from "effect/PlatformError";14+import * as Schedule from "effect/Schedule";15+import type * as Scope from "effect/Scope";16+import * as Stream from "effect/Stream";17+18+import { ServerConfig } from "./config.ts";19+import { GitManager } from "./git/GitManager.ts";20+import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";21+import { threadHasQueuedTurnStart } from "./orchestration/ThreadSettlementPolicy.ts";22+import { forkParked } from "./serverActivation.ts";23+import { ServerSettingsService } from "./serverSettings.ts";24+import { TerminalManager } from "./terminal/Manager.ts";25+import { GitVcsDriver } from "./vcs/GitVcsDriver.ts";26+import { withThreadWorkspaceLease } from "./workspace/threadWorkspaceLease.ts";27+28+const DAY_MS = 86_400_000;29+30+/** Live sessions keep their cwd even when no turn is currently running. */31+export function storageCleanupThreadIdle(thread: OrchestrationThreadShell, now: number): boolean {
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/storageCleanup.ts line 355Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +282,21 @@282+ )283+ return;284+ if (285+ (yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !==286+ head.commitSha287+ )288+ return;289+ const finalIgnored = yield* git.execute({290+ operation: "StorageCleanup.ignoredFiles",291+ cwd: worktreePath,292+ args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"],293+ maxOutputBytes: 64 * 1024,294+ });295+ if (296+ finalIgnored.stdoutTruncated ||297+ finalIgnored.stdout298+ .split("\0")299+ .some((entry) => entry !== "" && !/(^|\/)node_modules\/$/.test(entry))300+ )301+ return;302+ yield* git.removeWorktree({ cwd: project.workspaceRoot, path: worktreePath, force: false });
- apps/server/src/resourceTelemetry/StorageUsage.ts lines 53 to 55OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +35,21 @@35+ [36+ config.worktreesDir,37+ config.browserArtifactsDir,38+ config.logsDir,39+ config.attachmentsDir,40+ ].map((root) => NodeFSP.realpath(root).catch(() => NodePath.resolve(root))),41+ );42+ const scan = async (roots: readonly string[], excluded = new Set<string>()) => {43+ const result = { bytes: 0, fileCount: 0, partial: false };44+ const initialRoots = new Set(roots.map((root) => NodePath.resolve(root)));45+ const directories = [...initialRoots];46+ while (directories.length > 0) {47+ if (!withinBudget()) {48+ result.partial = true;49+ break;50+ }51+ let directory = directories.pop()!;52+ try {53+ const stat = await NodeFSP.lstat(directory);54+ // A configured root or a directory renamed during the scan may be a link.55+ if (!stat.isDirectory()) {
- apps/server/integration/OrchestrationEngineHarness.integration.ts lines 42 to 42OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -39,3 +39,4 @@3939 import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts";4040 import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";4141 import { ServerSettingsService } from "../src/serverSettings.ts";42+import { StorageCleanup } from "../src/storageCleanup.ts";apps/server/src/resourceTelemetry/StorageUsage.ts lines 11 to 11OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,11 @@1+// @effect-diagnostics nodeBuiltinImport:off - streamed directory entries, lstat and statfs form the filesystem boundary.2+import * as NodeFSP from "node:fs/promises";3+import * as NodePath from "node:path";4+import type { StorageUsageInput, StorageUsageSnapshot } from "@t3tools/contracts";5+import * as Context from "effect/Context";6+import * as DateTime from "effect/DateTime";7+import * as Effect from "effect/Effect";8+import * as Layer from "effect/Layer";9+import * as Semaphore from "effect/Semaphore";10+11+import { ServerConfig } from "../config.ts";apps/server/src/orchestration/Layers/OrchestrationReactor.ts lines 16 to 16OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -13,3 +13,4 @@1313 import * as PullRequestSyncReactor from "../PullRequestSyncReactor.ts";1414 import * as ThreadPullRequestReactor from "../ThreadPullRequestReactor.ts";1515 import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";16+import { StorageCleanup } from "../../storageCleanup.ts";apps/server/src/storageCleanup.ts lines 23 to 33OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +13,21 @@13+import * as Equal from "effect/Equal";14+import * as FileSystem from "effect/FileSystem";15+import * as Layer from "effect/Layer";16+import * as Option from "effect/Option";17+import * as Path from "effect/Path";18+import type { PlatformError } from "effect/PlatformError";19+import * as Schedule from "effect/Schedule";20+import type * as Scope from "effect/Scope";21+import * as Stream from "effect/Stream";22+23+import { ServerConfig } from "./config.ts";24+import { GitManager } from "./git/GitManager.ts";25+import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";26+import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";27+import { ThreadDeletionReactor } from "./orchestration/Services/ThreadDeletionReactor.ts";28+import { ProviderService } from "./provider/Services/ProviderService.ts";29+import { threadHasQueuedTurnStart } from "./orchestration/ThreadSettlementPolicy.ts";30+import { forkParked } from "./serverActivation.ts";31+import { ServerSettingsService } from "./serverSettings.ts";32+import { TerminalManager } from "./terminal/Manager.ts";33+import { GitVcsDriver } from "./vcs/GitVcsDriver.ts";
- apps/server/src/storageCleanup.ts line 355Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +290,21 @@290+ return;291+ if (292+ (yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !==293+ head.commitSha294+ )295+ return;296+ const finalIgnored = yield* git.execute({297+ operation: "StorageCleanup.ignoredFiles",298+ cwd: worktreePath,299+ args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"],300+ maxOutputBytes: 64 * 1024,301+ });302+ if (303+ finalIgnored.stdoutTruncated ||304+ finalIgnored.stdout305+ .split("\0")306+ .some((entry) => entry !== "" && !/(^|\/)node_modules\/$/.test(entry))307+ )308+ return;309+ if (!Equal.equals((yield* settingsService.getSettings).storageCleanup, settings)) return;310+ yield* git.removeWorktree({ cwd: project.workspaceRoot, path: worktreePath, force: false });apps/server/src/resourceTelemetry/StorageUsage.ts line 61OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +41,21 @@41+ );42+ const scan = async (roots: readonly string[], excluded = new Set<string>()) => {43+ const result = { bytes: 0, fileCount: 0, partial: false };44+ const initialRoots = new Set(roots.map((root) => NodePath.resolve(root)));45+ const directories = [...initialRoots];46+ while (directories.length > 0) {47+ if (!withinBudget()) {48+ result.partial = true;49+ break;50+ }51+ let directory = directories.pop()!;52+ try {53+ const stat = await NodeFSP.lstat(directory);54+ // A configured root or a directory renamed during the scan may be a link.55+ if (!stat.isDirectory()) {56+ result.partial = true;57+ continue;58+ }59+ const realPath = await NodeFSP.realpath(directory);60+ // Canonicalize platform aliases such as macOS /var before descending.61+ if (initialRoots.has(directory)) directory = realPath;apps/server/src/resourceTelemetry/StorageUsage.ts line 72OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +52,21 @@52+ try {53+ const stat = await NodeFSP.lstat(directory);54+ // A configured root or a directory renamed during the scan may be a link.55+ if (!stat.isDirectory()) {56+ result.partial = true;57+ continue;58+ }59+ const realPath = await NodeFSP.realpath(directory);60+ // Canonicalize platform aliases such as macOS /var before descending.61+ if (initialRoots.has(directory)) directory = realPath;62+ else if (realPath !== directory) {63+ result.partial = true;64+ continue;65+ }66+ const handle = await NodeFSP.opendir(directory, { bufferSize: 64 });67+ let files: string[] = [];68+ const countFiles = async () => {69+ await Promise.all(70+ files.map(async (file) => {71+ try {72+ const info = await NodeFSP.lstat(file);
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/web/src/components/settings/StorageSettings.tsx lines 35 to 35OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +15,21 @@15+16+function RetentionControl({17+ label,18+ value,19+ onChange,20+}: {21+ label: string;22+ value: number | null;23+ onChange: (value: number | null) => void;24+}) {25+ return (26+ <div className="flex items-center gap-3">27+ {value !== null ? (28+ <NumberField29+ value={value}30+ min={1}31+ max={3650}32+ step={1}33+ size="sm"34+ className="w-40"35+ onValueChange={(next) => {
- @@ -0,0 +25,21 @@25+ return (26+ <div className="flex items-center gap-3">27+ {value !== null ? (28+ <NumberField29+ value={value}30+ min={1}31+ max={3650}32+ step={1}33+ size="sm"34+ className="w-40"35+ onValueChange={(next) => {36+ if (next !== null) onChange(next);37+ }}38+ >39+ <NumberFieldGroup>40+ <NumberFieldDecrement aria-label={`Decrease ${label}`} />41+ <NumberFieldInput42+ aria-label={`${label} in days`}43+ className="text-right in-data-[size=sm]:px-1"44+ />45+ <span aria-hidden="true" className="self-center pr-2 text-xs">
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/storageCleanup.ts lines 425 to 425OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +405,21 @@405+ yield* cleanWorktrees(serverSettings, now).pipe(406+ Effect.catch((error) => Effect.logWarning("worktree cleanup failed", { error })),407+ );408+ yield* cleanFiles(409+ config.browserArtifactsDir,410+ settings.browserArtifactsAfterDays,411+ now,412+ false,413+ ).pipe(414+ Effect.catch((error) => Effect.logWarning("browser artifact cleanup failed", { error })),415+ );416+ yield* cleanFiles(config.logsDir, settings.logsAfterDays, now, true).pipe(417+ Effect.catch((error) => Effect.logWarning("rotated log cleanup failed", { error })),418+ );419+ });420+ const worker = yield* makeDrainableWorker(() =>421+ sweep().pipe(422+ Effect.catchCause((cause) =>423+ Cause.hasInterruptsOnly(cause)424+ ? Effect.failCause(cause)425+ : Effect.logWarning("storage cleanup failed", { cause: Cause.pretty(cause) }),apps/server/src/storageCleanup.ts lines 50 to 50Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +22,21 @@22+import * as Schedule from "effect/Schedule";23+import type * as Scope from "effect/Scope";24+import * as Stream from "effect/Stream";25+26+import * as ServerConfig from "./config.ts";27+import * as GitManager from "./git/GitManager.ts";28+import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";29+import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";30+import * as ThreadDeletionReactor from "./orchestration/Services/ThreadDeletionReactor.ts";31+import * as ProviderService from "./provider/Services/ProviderService.ts";32+import { threadHasQueuedTurnStart } from "./orchestration/ThreadSettlementPolicy.ts";33+import { forkParked } from "./serverActivation.ts";34+import * as Settings from "./serverSettings.ts";35+import * as TerminalManager from "./terminal/Manager.ts";36+import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";37+import { withWorkspaceLease } from "./workspace/workspaceLease.ts";38+39+const DAY_MS = 86_400_000;40+41+const worktreeCleanupEnabled = (rules: WorktreeCleanupRules) =>42+ rules.worktreeAfterDays !== null ||
maria-rcks changed the title
maria-rcks merged thisc4ca1b0
maria-rcks closed this
Sign in to join this conversation.










Bugbot is paused — on-demand spend limit reached
Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.
A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.