feat(settings): add automatic storage cleanup per machine and project (#11598)

Co-authored-by: maria-rcks <[email protected]>
This commit is contained in:
mariaandmaria-rcks authored and GitHub committed 2026-09-17 02:39:49 -03:00
1 parent 2a47fc905a
commit c4ca1b0f94
36 files changed
+1911 -7

No files matched your search

@@ -39,6 +39,7 @@ import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapte
import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import * as StorageCleanup from "../src/storageCleanup.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
import {
@@ -384,6 +385,12 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(VcsProcess.layer),
);
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
Layer.provideMerge(
Layer.succeed(StorageCleanup.StorageCleanup, {
start: () => Effect.void,
drain: Effect.void,
}),
),
Layer.provideMerge(runtimeIngestionLayer),
Layer.provideMerge(providerCommandReactorLayer),
Layer.provideMerge(checkpointReactorLayer),
@@ -83,6 +83,7 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getDeletedWorktreeThreads: () => Effect.die("unused"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
@@ -199,6 +200,7 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getDeletedWorktreeThreads: () => Effect.die("unused"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
@@ -290,6 +292,7 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getDeletedWorktreeThreads: () => Effect.die("unused"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
@@ -366,6 +369,7 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getDeletedWorktreeThreads: () => Effect.die("unused"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
@@ -427,6 +431,7 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getDeletedWorktreeThreads: () => Effect.die("unused"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
@@ -224,6 +224,8 @@ export const make = Effect.gen(function* () {
inlineMessageContext: true,
threadSettlement: true,
threadAutoSettlement: true,
storageCleanup: true,
projectWorktreeCleanup: true,
threadRestartContinuation: true,
projectSettingsOverrides: true,
threadSnooze: true,
@@ -434,6 +434,7 @@ describe("OrchestrationEngine", () => {
threads: [],
updatedAt: projectionSnapshot.updatedAt,
}),
getDeletedWorktreeThreads: () => Effect.die("unused"),
getArchivedShellSnapshot: () =>
Effect.succeed({
snapshotSequence: projectionSnapshot.snapshotSequence,
@@ -15,6 +15,7 @@ import * as ThreadPullRequestReactor from "../ThreadPullRequestReactor.ts";
import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";
import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";
import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";
import { StorageCleanup } from "../../storageCleanup.ts";
describe("OrchestrationReactor", () => {
let runtime: ManagedRuntime.ManagedRuntime<OrchestrationReactor, never> | null = null;
@@ -31,6 +32,15 @@ describe("OrchestrationReactor", () => {
runtime = ManagedRuntime.make(
Layer.effect(OrchestrationReactor, makeOrchestrationReactor).pipe(
Layer.provideMerge(
Layer.succeed(StorageCleanup, {
start: () => {
started.push("storage-cleanup");
return Effect.void;
},
drain: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(ProviderRuntimeIngestionService, {
start: () => {
@@ -120,6 +130,7 @@ describe("OrchestrationReactor", () => {
"thread-settlement-reactor",
"pull-request-sync-reactor",
"agent-awareness-relay",
"storage-cleanup",
]);
await Effect.runPromise(Scope.close(scope, Exit.void));
@@ -13,6 +13,7 @@ import * as ThreadSettlementReactor from "../ThreadSettlementReactor.ts";
import * as PullRequestSyncReactor from "../PullRequestSyncReactor.ts";
import * as ThreadPullRequestReactor from "../ThreadPullRequestReactor.ts";
import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";
import * as StorageCleanup from "../../storageCleanup.ts";
export const makeOrchestrationReactor = Effect.gen(function* () {
const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;
@@ -23,6 +24,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
const pullRequestSyncReactor = yield* PullRequestSyncReactor.PullRequestSyncReactor;
const threadPullRequestReactor = yield* ThreadPullRequestReactor.ThreadPullRequestReactor;
const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
const storageCleanup = yield* StorageCleanup.StorageCleanup;
const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {
yield* providerRuntimeIngestion.start();
@@ -33,6 +35,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
yield* threadSettlementReactor.start();
yield* pullRequestSyncReactor.start();
yield* agentAwarenessRelay.start();
yield* storageCleanup.start();
});
return {
@@ -1068,6 +1068,40 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
(yield* snapshotQuery.getThreadRuntimeContext(ThreadId.make("thread-active")))._tag,
"None",
);
assert.deepEqual(yield* snapshotQuery.getDeletedWorktreeThreads(), []);
yield* sql`
UPDATE projection_threads
SET branch = 'retained-branch', worktree_path = '/tmp/archived-worktree',
deleted_at = '2026-04-06T00:00:09.000Z'
WHERE thread_id = 'thread-archived'
`;
assert.deepEqual(yield* snapshotQuery.getDeletedWorktreeThreads(), [
{
id: ThreadId.make("thread-archived"),
projectId: ProjectId.make("project-archive-test"),
branch: "retained-branch",
worktreePath: "/tmp/archived-worktree",
workspaceRoot: "/tmp/archive-test",
deletedAt: "2026-04-06T00:00:09.000Z",
},
]);
assert.deepEqual((yield* snapshotQuery.getArchivedShellSnapshot()).threads, []);
yield* sql`
UPDATE projection_projects
SET deleted_at = '2026-04-06T00:00:10.000Z', updated_at = '2026-04-06T00:00:10.000Z'
WHERE project_id = 'project-archive-test'
`;
assert.deepEqual((yield* snapshotQuery.getShellSnapshot()).projects, []);
assert.deepEqual(yield* snapshotQuery.getDeletedWorktreeThreads(), [
{
id: ThreadId.make("thread-archived"),
projectId: ProjectId.make("project-archive-test"),
branch: "retained-branch",
worktreePath: "/tmp/archived-worktree",
workspaceRoot: "/tmp/archive-test",
deletedAt: "2026-04-06T00:00:09.000Z",
},
]);
}),
);
@@ -637,6 +637,36 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listDeletedWorktreeRows = SqlSchema.findAll({
Request: Schema.Void,
Result: Schema.Struct({
id: ThreadId,
projectId: ProjectId,
branch: Schema.String,
worktreePath: Schema.String,
workspaceRoot: Schema.String,
deletedAt: IsoDateTime,
}),
execute: () => sql`
SELECT t.thread_id AS "id", t.project_id AS "projectId", t.branch,
t.worktree_path AS "worktreePath", p.workspace_root AS "workspaceRoot",
t.deleted_at AS "deletedAt"
FROM projection_threads t
JOIN projection_projects p ON p.project_id = t.project_id
WHERE t.deleted_at IS NOT NULL AND t.worktree_path IS NOT NULL AND t.branch IS NOT NULL
ORDER BY t.deleted_at DESC, t.thread_id ASC
`,
});
const getDeletedWorktreeThreads: ProjectionSnapshotQueryShape["getDeletedWorktreeThreads"] = () =>
listDeletedWorktreeRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getDeletedWorktreeThreads:query",
"ProjectionSnapshotQuery.getDeletedWorktreeThreads:decodeRows",
),
),
);
const listArchivedThreadRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadDbRowSchema,
@@ -3734,6 +3764,7 @@ pending_approval_requests AS (
getSnapshot,
getShellSnapshot,
getArchivedShellSnapshot,
getDeletedWorktreeThreads,
searchThreads,
getSnapshotSequence,
getCounts,
@@ -1,3 +1,4 @@
import { withWorkspaceLease } from "../../workspace/workspaceLease.ts";
import {
type ChatAttachment,
CommandId,
@@ -26,6 +27,7 @@ import * as Equal from "effect/Equal";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
@@ -214,6 +216,7 @@ const make = Effect.gen(function* () {
const providerRegistry = yield* ProviderRegistry;
const gitWorkflow = yield* GitWorkflowService;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
@@ -1784,16 +1787,23 @@ const make = Effect.gen(function* () {
return;
}
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
yield* ensureSessionForThread(
const resume = ensureSessionForThread(
event.payload.threadId,
event.occurredAt,
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
);
yield* thread.worktreePath
? withWorkspaceLease(path.resolve(thread.worktreePath), resume)
: resume;
return;
}
case "thread.turn-start-requested":
yield* processTurnStartRequested(event);
case "thread.turn-start-requested": {
const thread = yield* resolveThreadShell(event.payload.threadId);
yield* thread?.worktreePath
? withWorkspaceLease(path.resolve(thread.worktreePath), processTurnStartRequested(event))
: processTurnStartRequested(event);
return;
}
case "thread.turn-interrupt-requested":
yield* processTurnInterruptRequested(event);
return;
@@ -131,6 +131,19 @@ export interface ProjectionSnapshotQueryShape {
ProjectionRepositoryError
>;
/** Durable worktree ownership retained after thread deletion, including across restarts. */
readonly getDeletedWorktreeThreads: () => Effect.Effect<
ReadonlyArray<{
readonly id: ThreadId;
readonly projectId: ProjectId;
readonly branch: string;
readonly worktreePath: string;
readonly workspaceRoot: string;
readonly deletedAt: string;
}>,
ProjectionRepositoryError
>;
/**
* Search active thread navigation metadata, user messages, and canonical
* assistant outputs without hydrating thread detail snapshots.
@@ -3,6 +3,7 @@ import {
EventId,
ProjectId,
ProviderInstanceId,
ProviderDriverKind,
PullRequestOperationError,
ThreadId,
type OrchestrationCommand,
@@ -17,8 +18,10 @@ import {
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { assert, describe, it } from "@effect/vitest";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
@@ -41,6 +44,16 @@ import {
} from "./Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
import * as ThreadSettlementReactor from "./ThreadSettlementReactor.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Path from "effect/Path";
import { ChildProcessSpawner } from "effect/unstable/process";
import { ServerConfig } from "../config.ts";
import * as StorageCleanup from "../storageCleanup.ts";
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
import { TerminalManager } from "../terminal/Manager.ts";
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
import { ThreadDeletionReactor } from "./Services/ThreadDeletionReactor.ts";
import { ProviderService } from "../provider/Services/ProviderService.ts";
const NOW = "2026-08-28T12:00:00.000Z";
const PROJECT_ID = ProjectId.make("settlement-project");
@@ -1363,3 +1376,508 @@ describe("ThreadSettlementReactor", () => {
),
);
});
describe("storage cleanup", () => {
it.effect("serializes users of one workspace while other workspaces can start", () =>
Effect.gen(function* () {
const releaseCleanup = yield* Deferred.make<void>();
const providerEntered = yield* Deferred.make<void>();
const cleanup = yield* withWorkspaceLease(
"/workspace/shared",
Deferred.await(releaseCleanup),
).pipe(Effect.forkScoped({ startImmediately: true }));
const provider = yield* withWorkspaceLease(
"/workspace/shared",
Deferred.succeed(providerEntered, undefined),
).pipe(Effect.forkScoped({ startImmediately: true }));
assert.strictEqual(yield* Deferred.isDone(providerEntered), false);
yield* withWorkspaceLease("/workspace/other", Effect.void);
yield* Deferred.succeed(releaseCleanup, undefined);
yield* Fiber.join(cleanup);
yield* Fiber.join(provider);
assert.strictEqual(yield* Deferred.isDone(providerEntered), true);
}).pipe(Effect.scoped),
);
for (const protection of [
"none",
"dirty",
"ignored",
"ignored-directory",
"shared",
"project-root",
"nested-project",
"new-nested-project",
"session",
"terminal-cwd",
"terminal-worktree",
"recent",
"merged",
"unmerged",
"unchanged",
"unchanged-two-worktrees",
"diverged",
"head-moved",
"deleted",
"deleted-event",
"deleted-dirty",
"deleted-ignored",
"deleted-shared",
"deleted-project",
"deleted-owner",
"deleted-owner-root",
"deleted-owner-nested",
"deleted-provider",
"project-off",
"project-custom",
"project-policy-disabled",
"deleted-project-custom",
"deleted-project-off",
"policy-disabled",
"policy-extended",
"files-disabled",
"files-extended",
] as const) {
it.effect(
`retains protected worktrees (${protection}) and expires only old artifacts and rotated logs`,
() =>
Effect.gen(function* () {
yield* TestClock.setTime(Date.parse(NOW));
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const config = yield* ServerConfig;
const worktreePath = path.join(config.worktreesDir, "feature");
yield* fs.makeDirectory(worktreePath, { recursive: true });
yield* fs.writeFileString(path.join(worktreePath, ".git"), "gitdir: /test/admin");
const secondWorktreePath = path.join(config.worktreesDir, "feature-two");
if (protection === "unchanged-two-worktrees") {
yield* fs.makeDirectory(secondWorktreePath);
yield* fs.writeFileString(
path.join(secondWorktreePath, ".git"),
"gitdir: /test/admin-two",
);
}
if (protection === "ignored" || protection === "deleted-ignored")
yield* fs.writeFileString(path.join(worktreePath, ".env"), "secret");
if (protection === "ignored-directory") {
yield* fs.makeDirectory(path.join(worktreePath, ".cache"));
yield* fs.writeFileString(path.join(worktreePath, ".cache", "local-data"), "keep");
}
yield* fs.makeDirectory(config.browserArtifactsDir, { recursive: true });
const oldImage = path.join(config.browserArtifactsDir, "old.png");
const recentImage = path.join(config.browserArtifactsDir, "recent.png");
const oldLog = path.join(config.logsDir, "server.log.1");
const activeLog = path.join(config.logsDir, "server.log");
const old = DateTime.toDateUtc(DateTime.makeUnsafe("2026-08-01T00:00:00.000Z"));
for (const file of [oldImage, oldLog, activeLog]) {
yield* fs.writeFileString(file, "keep or remove");
yield* fs.utimes(file, old, old);
}
yield* fs.writeFileString(recentImage, "recent");
const recent = DateTime.toDateUtc(DateTime.makeUnsafe(NOW));
yield* fs.utimes(recentImage, recent, recent);
const thread = makeThread("storage-thread", {
branch: "feature",
worktreePath,
latestUserMessageAt:
protection === "recent" ? "2026-08-26T00:00:00.000Z" : "2026-08-01T00:00:00.000Z",
...(protection === "session"
? {
session: {
threadId: ThreadId.make("storage-thread"),
status: "ready",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: NOW,
},
}
: {}),
});
const snapshotRead = yield* Deferred.make<void>();
const deletionStarted = yield* Deferred.make<void>();
const deletionStopped = yield* Deferred.make<void>();
if (protection !== "deleted-event") yield* Deferred.succeed(deletionStopped, undefined);
const domainEvents = yield* PubSub.unbounded<OrchestrationEvent>();
const deleteRule = protection.startsWith("deleted");
let tombstoned = deleteRule && protection !== "deleted-event";
const removals: string[] = [];
const mergeRule = protection === "merged" || protection === "unmerged";
const unchangedRule =
protection === "unchanged" ||
protection === "unchanged-two-worktrees" ||
protection === "diverged" ||
protection === "head-moved";
let headReads = 0;
let snapshotReads = 0;
let defaultRefFetched = false;
let fetches = 0;
const settingsService = yield* ServerSettingsService.pipe(
Effect.provide(
ServerSettingsService.layerTest({
projectSettingsOverrides: {
[PROJECT_ID]:
protection === "project-off" || protection === "deleted-project-off"
? { worktreeCleanup: { mode: "off" as const } }
: protection === "project-custom" || protection === "deleted-project-custom"
? {
worktreeCleanup: {
mode: "custom" as const,
rules: {
worktreeAfterDays: protection === "project-custom" ? 8 : null,
worktreeOnDelete: deleteRule,
worktreeOnMerge: false,
worktreeUnchanged: false,
},
},
}
: {},
},
storageCleanup: {
worktreeAfterDays:
deleteRule || mergeRule || unchangedRule || protection === "project-custom"
? null
: 8,
worktreeOnDelete: deleteRule && protection !== "deleted-project-custom",
worktreeOnMerge: mergeRule,
worktreeUnchanged: unchangedRule,
browserArtifactsAfterDays: 8,
logsAfterDays: 8,
},
}),
),
);
const cleanup = yield* StorageCleanup.make.pipe(
Effect.provide(
Layer.mergeAll(
Layer.succeed(ServerSettingsService, settingsService),
Layer.succeed(FileSystem.FileSystem, {
...fs,
stat: (target) =>
fs.stat(target).pipe(
Effect.tap(() => {
if (
!protection.startsWith("files-") ||
(target !== oldImage && target !== oldLog)
)
return Effect.void;
return settingsService
.updateSettings({
storageCleanup: {
[target === oldImage ? "browserArtifactsAfterDays" : "logsAfterDays"]:
protection === "files-disabled" ? null : 60,
},
})
.pipe(Effect.orDie);
}),
),
}),
Layer.mock(ProjectionSnapshotQuery)({
getDeletedWorktreeThreads: () =>
Effect.succeed(
tombstoned
? [
{
id: thread.id,
projectId: thread.projectId,
branch: "feature",
worktreePath,
workspaceRoot:
protection === "deleted-owner-root"
? worktreePath
: protection === "deleted-owner-nested"
? path.join(worktreePath, "nested")
: config.baseDir,
deletedAt: NOW,
},
]
: [],
),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 2 }),
getShellSnapshot: () =>
Deferred.succeed(snapshotRead, undefined).pipe(
Effect.andThen(
Effect.sync(() => {
snapshotReads++;
const projects =
protection.startsWith("deleted-owner") ||
protection === "deleted-project-off" ||
protection === "deleted-project-custom"
? []
: [makeProject(PROJECT_ID, config.baseDir)];
const threads = tombstoned ? [] : [thread];
if (protection === "deleted-shared")
threads.push({ ...thread, id: ThreadId.make("surviving-thread") });
if (protection === "deleted-project")
projects.push(makeProject(LINKED_PROJECT_ID, worktreePath));
if (
protection === "project-root" ||
protection === "nested-project" ||
(protection === "new-nested-project" && snapshotReads > 1)
) {
projects.push(
makeProject(
LINKED_PROJECT_ID,
protection === "project-root"
? worktreePath
: path.join(worktreePath, "nested"),
),
);
threads.push(
makeThread("local-project-thread", { projectId: LINKED_PROJECT_ID }),
);
}
if (protection === "unchanged-two-worktrees") {
threads.push({
...thread,
id: ThreadId.make("second-worktree-thread"),
branch: "feature-two",
worktreePath: secondWorktreePath,
});
}
return makeSnapshot(threads, projects);
}),
),
),
getArchivedShellSnapshot: () =>
Effect.succeed(
makeSnapshot(
protection === "shared"
? [
{
...thread,
id: ThreadId.make("archived-sharing-thread"),
archivedAt: NOW,
},
]
: [],
),
),
}),
Layer.mock(GitManager)({
invalidateStatus: () => Effect.void,
branchPullRequest: (_input, options) => {
assert.strictEqual(options?.refresh, true);
return Effect.succeed(
makeBranchPullRequest(protection === "unmerged" ? "open" : "merged"),
);
},
}),
Layer.mock(OrchestrationEngineService)({
subscribeDomainEvents: PubSub.subscribe(domainEvents).pipe(
Effect.map((subscription) => Stream.fromSubscription(subscription)),
),
}),
Layer.mock(ThreadDeletionReactor)({
drainThrough: (sequence) => {
assert.strictEqual(sequence, 2);
return Deferred.succeed(deletionStarted, undefined).pipe(
Effect.andThen(Deferred.await(deletionStopped)),
);
},
}),
Layer.mock(ProviderService)({
listSessions: () =>
Effect.succeed(
protection === "deleted-provider"
? [
{
threadId: thread.id,
provider: ProviderDriverKind.make("codex"),
status: "ready",
runtimeMode: "full-access",
cwd: worktreePath,
createdAt: NOW,
updatedAt: NOW,
},
]
: [],
),
}),
Layer.mock(GitVcsDriver)({
resolvePrimaryRemoteName: () => Effect.succeed("origin"),
resolveDefaultBranchName: () => Effect.succeed("main"),
fetchRemoteTrackingBranch: (input) =>
Effect.sync(() => {
assert.deepStrictEqual(input, {
cwd: config.baseDir,
remoteName: "origin",
remoteBranch: "main",
});
defaultRefFetched = true;
fetches++;
}),
resolveCommit: ({ revision }) =>
Effect.sync(() => {
if (revision !== "HEAD")
return { commitSha: (defaultRefFetched ? "b" : "d").repeat(40) };
headReads++;
return {
commitSha:
protection === "head-moved" && headReads > 1
? "c".repeat(40)
: "a".repeat(40),
};
}),
statusDetailsLocal: (cwd) =>
Effect.succeed({
isRepo: true,
hasOriginRemote: false,
isDefaultBranch: false,
branch: cwd === secondWorktreePath ? "feature-two" : "feature",
upstreamRef: null,
hasWorkingTreeChanges:
protection === "dirty" || protection === "deleted-dirty",
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
aheadOfDefaultCount: 0,
}),
execute: (input) =>
Effect.succeed({
exitCode: ChildProcessSpawner.ExitCode(
input.operation === "StorageCleanup.integratedBranch" &&
(protection === "diverged" || input.args.at(-1) !== "b".repeat(40))
? 1
: 0,
),
stdout:
protection === "ignored" || protection === "deleted-ignored"
? ".env\0"
: protection === "ignored-directory"
? ".cache/\0"
: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
}).pipe(
Effect.tap(() =>
(protection.startsWith("policy-") ||
protection === "project-policy-disabled") &&
headReads > 1
? settingsService
.updateSettings({
...(protection === "project-policy-disabled"
? {
projectSettingsOverrides: {
[PROJECT_ID]: { worktreeCleanup: { mode: "off" as const } },
},
}
: {}),
...(protection === "project-policy-disabled"
? {}
: {
storageCleanup: {
worktreeAfterDays:
protection === "policy-disabled" ? null : 60,
},
}),
})
.pipe(Effect.orDie)
: Effect.void,
),
),
removeWorktree: (input) => {
assert.strictEqual(input.force, false);
removals.push(input.path);
return fs.remove(input.path, { recursive: true }).pipe(Effect.orDie);
},
}),
Layer.mock(TerminalManager)({
subscribeMetadata: (listener) =>
listener({
type: "snapshot",
terminals:
protection === "terminal-cwd" || protection === "terminal-worktree"
? [
{
threadId: "terminal-thread",
terminalId: "default",
cwd:
protection === "terminal-cwd"
? `${worktreePath}${path.sep}`
: config.baseDir,
worktreePath:
protection === "terminal-worktree"
? `${worktreePath}${path.sep}`
: null,
status: "running",
pid: 42,
exitCode: null,
exitSignal: null,
hasRunningSubprocess: false,
label: "shell",
updatedAt: NOW,
},
]
: [],
}).pipe(Effect.as(() => {})),
}),
),
),
);
yield* cleanup.start();
yield* Deferred.await(snapshotRead);
yield* cleanup.drain;
if (protection === "deleted-event") {
assert.strictEqual(yield* fs.exists(worktreePath), true);
tombstoned = true;
yield* PubSub.publish(domainEvents, {
type: "thread.deleted",
sequence: 2,
eventId: EventId.make("storage-thread-deleted"),
aggregateKind: "thread",
aggregateId: thread.id,
occurredAt: NOW,
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
payload: { threadId: thread.id, deletedAt: NOW },
});
yield* Deferred.await(deletionStarted);
assert.strictEqual(yield* fs.exists(worktreePath), true);
yield* Deferred.succeed(deletionStopped, undefined);
yield* cleanup.drain;
}
const removed =
protection === "project-custom" ||
protection === "deleted-project-custom" ||
protection === "none" ||
protection === "deleted" ||
protection === "deleted-event" ||
protection === "deleted-owner" ||
protection === "files-disabled" ||
protection === "files-extended" ||
protection === "merged" ||
protection === "unchanged" ||
protection === "unchanged-two-worktrees";
assert.strictEqual(yield* fs.exists(worktreePath), !removed);
assert.deepStrictEqual(
removals,
protection === "unchanged-two-worktrees"
? [worktreePath, secondWorktreePath]
: removed
? [worktreePath]
: [],
);
assert.strictEqual(fetches, mergeRule || unchangedRule ? 1 : 0);
assert.strictEqual(thread.worktreePath, worktreePath);
assert.strictEqual(thread.branch, "feature");
assert.strictEqual(yield* fs.exists(oldImage), protection.startsWith("files-"));
assert.strictEqual(yield* fs.exists(recentImage), true);
assert.strictEqual(yield* fs.exists(oldLog), protection.startsWith("files-"));
assert.strictEqual(yield* fs.exists(activeLog), true);
}).pipe(
Effect.provide(
ServerConfig.layerTest(process.cwd(), { prefix: "t3-storage-cleanup-" }).pipe(
Layer.provideMerge(NodeServices.layer),
),
),
Effect.scoped,
),
);
}
});
@@ -47,6 +47,7 @@ const makeProjectionSnapshotQueryLayer = (importedWorkspaceRoots: ReadonlyArray<
threads: [],
updatedAt: "2026-01-01T00:00:00.000Z",
}),
getDeletedWorktreeThreads: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
@@ -33,6 +33,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getDeletedWorktreeThreads: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),
getCounts: () => Effect.die("unused"),
@@ -4970,6 +4970,7 @@ describe("agent browser access", () => {
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getDeletedWorktreeThreads: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
@@ -238,6 +238,7 @@ describe("ProviderSessionReaper", () => {
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getDeletedWorktreeThreads: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () =>
Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
+2
View File
@@ -84,6 +84,7 @@ import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderComma
import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";
import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";
import * as ThreadSettlementReactor from "./orchestration/ThreadSettlementReactor.ts";
import * as StorageCleanup from "./storageCleanup.ts";
import * as PullRequestSyncReactor from "./orchestration/PullRequestSyncReactor.ts";
import * as ThreadPullRequestReactor from "./orchestration/ThreadPullRequestReactor.ts";
import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
@@ -246,6 +247,7 @@ const ReactorLayerLive = Layer.empty.pipe(
Layer.provideMerge(ProviderRuntimeIngestionLive),
Layer.provideMerge(ProviderCommandReactorLive),
Layer.provideMerge(CheckpointReactorLive),
Layer.provideMerge(StorageCleanup.layer),
Layer.provideMerge(ThreadDeletionReactorLive),
Layer.provideMerge(ThreadSettlementReactor.layer),
Layer.provideMerge(PullRequestSyncReactor.layer),
@@ -168,6 +168,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getDeletedWorktreeThreads: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
@@ -298,6 +299,7 @@ it.effect.each([
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getDeletedWorktreeThreads: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
@@ -384,6 +386,7 @@ it.effect(
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getDeletedWorktreeThreads: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
@@ -448,6 +451,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getDeletedWorktreeThreads: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
+482
View File
@@ -0,0 +1,482 @@
import type {
OrchestrationThreadShell,
ProjectId,
ServerSettings,
ServerSettingsError,
TerminalSummary,
WorktreeCleanupRules,
} from "@t3tools/contracts";
import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import type { PlatformError } from "effect/PlatformError";
import * as Schedule from "effect/Schedule";
import type * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as ServerConfig from "./config.ts";
import * as GitManager from "./git/GitManager.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import * as ThreadDeletionReactor from "./orchestration/Services/ThreadDeletionReactor.ts";
import * as ProviderService from "./provider/Services/ProviderService.ts";
import { threadHasQueuedTurnStart } from "./orchestration/ThreadSettlementPolicy.ts";
import { forkParked } from "./serverActivation.ts";
import * as Settings from "./serverSettings.ts";
import * as TerminalManager from "./terminal/Manager.ts";
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
import { withWorkspaceLease } from "./workspace/workspaceLease.ts";
export class StorageCleanup extends Context.Service<
StorageCleanup,
{
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
readonly drain: Effect.Effect<void>;
}
>()("t3/storageCleanup") {}
const DAY_MS = 86_400_000;
const worktreeCleanupEnabled = (rules: WorktreeCleanupRules) =>
rules.worktreeAfterDays !== null ||
rules.worktreeOnMerge ||
rules.worktreeOnDelete ||
rules.worktreeUnchanged;
function anyWorktreePolicy(
settings: ServerSettings,
predicate: (rules: WorktreeCleanupRules) => boolean,
): boolean {
return (
predicate(resolveWorktreeCleanup(settings, null)) ||
Object.keys(settings.projectSettingsOverrides).some((projectId) =>
predicate(resolveWorktreeCleanup(settings, projectId as ProjectId)),
)
);
}
function sameProjectWorktreePolicies(left: ServerSettings, right: ServerSettings): boolean {
return [
...new Set([
...Object.keys(left.projectSettingsOverrides),
...Object.keys(right.projectSettingsOverrides),
]),
].every((projectId) =>
Equal.equals(
left.projectSettingsOverrides[projectId as ProjectId]?.worktreeCleanup,
right.projectSettingsOverrides[projectId as ProjectId]?.worktreeCleanup,
),
);
}
/** Live sessions keep their cwd even when no turn is currently running. */
function storageCleanupThreadIdle(thread: OrchestrationThreadShell, now: number): boolean {
return (
thread.branch !== null &&
thread.worktreePath !== null &&
(thread.session === null || thread.session.status === "stopped") &&
thread.latestTurn?.state !== "running" &&
thread.backgroundLiveness == null &&
!thread.hasPendingApprovals &&
!thread.hasPendingUserInput &&
!threadHasQueuedTurnStart(thread, DateTime.formatIso(DateTime.makeUnsafe(now)))
);
}
/** PR metadata refreshes must not reset the inactivity clock. */
function storageCleanupActivityAt(thread: OrchestrationThreadShell): number {
return Math.max(
...[
thread.createdAt,
thread.latestUserMessageAt,
thread.latestTurn?.requestedAt,
thread.latestTurn?.startedAt,
thread.latestTurn?.completedAt,
].flatMap((value) => (value == null ? [] : [Date.parse(value)])),
);
}
export const make = Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const settingsService = yield* Settings.ServerSettingsService;
const snapshots = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
const threadDeletion = yield* ThreadDeletionReactor.ThreadDeletionReactor;
const providers = yield* ProviderService.ProviderService;
const git = yield* GitVcsDriver.GitVcsDriver;
const gitManager = yield* GitManager.GitManager;
const terminals = yield* TerminalManager.TerminalManager;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const liveTerminals = new Map<string, Map<string, TerminalSummary>>();
const noteTerminal = (terminal: TerminalSummary) => {
const threadTerminals =
liveTerminals.get(terminal.threadId) ?? new Map<string, TerminalSummary>();
threadTerminals.set(terminal.terminalId, terminal);
liveTerminals.set(terminal.threadId, threadTerminals);
};
const inside = (root: string, target: string) => {
const relative = path.relative(root, target);
return (
relative !== "" &&
relative !== ".." &&
!relative.startsWith(`..${path.sep}`) &&
!path.isAbsolute(relative)
);
};
const hasTerminal = (worktreePath: string) =>
[...liveTerminals.values()]
.flatMap((entries) => [...entries.values()])
.some((terminal) => {
if (terminal.status !== "starting" && terminal.status !== "running") return false;
const cwd = path.resolve(terminal.cwd);
return (
(terminal.worktreePath !== null &&
path.resolve(terminal.worktreePath) === worktreePath) ||
cwd === worktreePath ||
inside(worktreePath, cwd)
);
});
const readThreads = Effect.fn("StorageCleanup.readThreads")(function* () {
const active = yield* snapshots.getShellSnapshot();
const archived = yield* snapshots.getArchivedShellSnapshot();
return { projects: active.projects, threads: [...active.threads, ...archived.threads] };
});
// Local threads under another project need not have a worktreePath of their own.
const containsProjectRoot = Effect.fn("StorageCleanup.containsProjectRoot")(function* (
worktreePath: string,
projects: ReadonlyArray<{ readonly workspaceRoot: string }>,
) {
for (const project of projects) {
const projectPath = path.resolve(project.workspaceRoot);
if (projectPath === worktreePath || inside(worktreePath, projectPath)) return true;
const realPath = yield* fs
.realPath(projectPath)
.pipe(Effect.orElseSucceed(() => projectPath));
if (realPath === worktreePath || inside(worktreePath, realPath)) return true;
}
return false;
});
const cleanWorktrees = Effect.fn("StorageCleanup.cleanWorktrees")(function* (
serverSettings: ServerSettings,
now: number,
) {
if (!anyWorktreePolicy(serverSettings, worktreeCleanupEnabled)) return;
if (!(yield* fs.exists(config.worktreesDir))) return;
const hasDeleteRule = anyWorktreePolicy(serverSettings, (rules) => rules.worktreeOnDelete);
const deletedThreads = hasDeleteRule
? (yield* snapshots.getDeletedWorktreeThreads()).filter(
(thread) => resolveWorktreeCleanup(serverSettings, thread.projectId).worktreeOnDelete,
)
: [];
if (deletedThreads.length > 0) {
// Read tombstones before taking this fence. A later deletion waits for the
// next sweep; every captured deletion must finish stopping its resources.
const { snapshotSequence } = yield* snapshots.getSnapshotSequence();
yield* threadDeletion.drainThrough(snapshotSequence);
}
const snapshot = yield* readThreads();
const root = yield* fs.realPath(config.worktreesDir);
const refreshedDefaultRefs = new Map<string, Set<string>>();
const groups = Map.groupBy(
snapshot.threads.filter((thread) => thread.worktreePath !== null),
(thread) => path.resolve(thread.worktreePath!),
);
const candidates = [
...[...groups.values()].flatMap((group) => (group.length === 1 ? [group[0]!] : [])),
...deletedThreads.filter((thread) => !groups.has(path.resolve(thread.worktreePath))),
];
for (const thread of candidates) {
const settings = resolveWorktreeCleanup(serverSettings, thread.projectId);
if (!worktreeCleanupEnabled(settings)) continue;
const worktreePath = path.resolve(thread.worktreePath!);
const deleted = "deletedAt" in thread;
const project = deleted
? { workspaceRoot: thread.workspaceRoot }
: snapshot.projects.find((entry) => entry.id === thread.projectId);
if (
project === undefined ||
(!deleted && !storageCleanupThreadIdle(thread, now)) ||
hasTerminal(worktreePath)
)
continue;
yield* Effect.gen(function* () {
if (!inside(root, worktreePath) || !(yield* fs.exists(worktreePath))) return;
if ((yield* fs.realPath(worktreePath)) !== worktreePath) return;
if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects])) return;
// A linked worktree has a .git file. Never remove a main checkout.
if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File") return;
const status = yield* git.statusDetailsLocal(worktreePath);
if (!status.isRepo || status.branch !== thread.branch || status.hasWorkingTreeChanges)
return;
const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" });
const ignored = yield* git.execute({
operation: "StorageCleanup.ignoredFiles",
cwd: worktreePath,
args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"],
maxOutputBytes: 64 * 1024,
});
// Ignored files can contain secrets or local datasets. Dependency installs
// are reproducible; every other ignored path prevents automatic removal.
if (
ignored.stdoutTruncated ||
ignored.stdout
.split("\0")
.some((entry) => entry !== "" && !/(^|\/)node_modules\/$/.test(entry))
)
return;
const old =
!deleted &&
settings.worktreeAfterDays !== null &&
storageCleanupActivityAt(thread) < now - settings.worktreeAfterDays * DAY_MS;
let eligible = deleted || old;
if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) {
const repositoryCwd = path.resolve(project.workspaceRoot);
const remote = yield* git.resolvePrimaryRemoteName(repositoryCwd);
const branch = yield* git.resolveDefaultBranchName(repositoryCwd, remote);
if (branch === null) return;
const defaultRef = `refs/remotes/${remote}/${branch}`;
const refreshed = refreshedDefaultRefs.get(repositoryCwd) ?? new Set<string>();
if (!refreshed.has(defaultRef)) {
yield* git.fetchRemoteTrackingBranch({
cwd: repositoryCwd,
remoteName: remote,
remoteBranch: branch,
});
refreshed.add(defaultRef);
refreshedDefaultRefs.set(repositoryCwd, refreshed);
}
const base = yield* git.resolveCommit({
cwd: worktreePath,
revision: defaultRef,
});
const ancestor = yield* git.execute({
operation: "StorageCleanup.integratedBranch",
cwd: worktreePath,
args: ["merge-base", "--is-ancestor", head.commitSha, base.commitSha],
allowNonZeroExit: true,
});
if (ancestor.exitCode !== 0) return;
eligible = settings.worktreeUnchanged;
if (!eligible && settings.worktreeOnMerge && thread.branch !== null) {
const pullRequest = yield* gitManager.branchPullRequest(
{ cwd: worktreePath, branch: thread.branch },
{ refresh: true },
);
eligible = pullRequest?.state === "merged";
}
}
if (!eligible) return;
// Re-read after Git/host calls so a queued turn, resumed session or new
// thread sharing this path cancels the removal.
const latestSnapshot = yield* readThreads();
if (yield* containsProjectRoot(worktreePath, [project, ...latestSnapshot.projects])) return;
const latest = latestSnapshot.threads.filter(
(entry) =>
entry.worktreePath !== null && path.resolve(entry.worktreePath) === worktreePath,
);
if (hasTerminal(worktreePath)) return;
if (deleted) {
if (
latest.length > 0 ||
!resolveWorktreeCleanup(yield* settingsService.getSettings, thread.projectId)
.worktreeOnDelete
)
return;
// A failed session stop is logged by the deletion reactor. Its drain
// alone is not proof that a provider released this checkout.
if (
(yield* providers.listSessions()).some(
(session) =>
session.status !== "closed" &&
(session.threadId === thread.id ||
(session.cwd !== undefined &&
(path.resolve(session.cwd) === worktreePath ||
inside(worktreePath, path.resolve(session.cwd))))),
)
)
return;
} else if (
latest.length !== 1 ||
latest[0]!.id !== thread.id ||
!storageCleanupThreadIdle(latest[0]!, now) ||
storageCleanupActivityAt(latest[0]!) !== storageCleanupActivityAt(thread)
)
return;
const finalStatus = yield* git.statusDetailsLocal(worktreePath);
if (
!finalStatus.isRepo ||
finalStatus.branch !== thread.branch ||
finalStatus.hasWorkingTreeChanges
)
return;
if (
(yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !==
head.commitSha
)
return;
const finalIgnored = yield* git.execute({
operation: "StorageCleanup.ignoredFiles",
cwd: worktreePath,
args: ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z"],
maxOutputBytes: 64 * 1024,
});
if (
finalIgnored.stdoutTruncated ||
finalIgnored.stdout
.split("\0")
.some((entry) => entry !== "" && !/(^|\/)node_modules\/$/.test(entry))
)
return;
const current = resolveWorktreeCleanup(
yield* settingsService.getSettings,
thread.projectId,
);
if (
Object.keys(settings).some(
(key) =>
current[key as keyof typeof settings] !== settings[key as keyof typeof settings],
)
)
return;
yield* git.removeWorktree({ cwd: project.workspaceRoot, path: worktreePath, force: false });
yield* gitManager.invalidateStatus(project.workspaceRoot);
// Preserve branch and path: ProviderCommandReactor recreates the checkout
// from that branch when the thread is resumed.
yield* Effect.logInfo("storage cleanup removed worktree", { threadId: thread.id });
}).pipe(
(effect) => withWorkspaceLease(worktreePath, effect),
Effect.catch((error) =>
Effect.logDebug("storage cleanup skipped worktree", { threadId: thread.id, error }),
),
);
}
});
const cleanFiles = Effect.fn("StorageCleanup.cleanFiles")(function* (
root: string,
days: number | null,
now: number,
rotatedLogs: boolean,
) {
if (days === null || !(yield* fs.exists(root))) return;
const realRoot = yield* fs.realPath(root);
if (realRoot !== path.resolve(root)) return;
const visit = Effect.fn("StorageCleanup.visitFiles")(function* (
directory: string,
): Effect.fn.Return<void, PlatformError | ServerSettingsError> {
for (const name of yield* fs.readDirectory(directory)) {
const target = path.join(directory, name);
if ((yield* fs.realPath(target)) !== target || !inside(realRoot, target)) continue;
const stat = yield* fs.stat(target);
if (stat.type === "Directory" && rotatedLogs) {
yield* visit(target);
} else if (stat.type === "File" && (!rotatedLogs || /\.(?:log|ndjson)\.\d+$/.test(name))) {
const modified = Option.getOrNull(stat.mtime);
if (modified !== null && modified.getTime() < now - days * DAY_MS) {
const current = (yield* settingsService.getSettings).storageCleanup;
if ((rotatedLogs ? current.logsAfterDays : current.browserArtifactsAfterDays) !== days)
return;
yield* fs.remove(target);
}
}
}
});
yield* visit(realRoot);
});
const sweep = Effect.fn("StorageCleanup.sweep")(function* () {
const serverSettings = yield* settingsService.getSettings;
const settings = serverSettings.storageCleanup;
const now = yield* Clock.currentTimeMillis;
yield* cleanWorktrees(serverSettings, now).pipe(
Effect.catch((error) => Effect.logWarning("worktree cleanup failed", { error })),
);
yield* cleanFiles(
config.browserArtifactsDir,
settings.browserArtifactsAfterDays,
now,
false,
).pipe(
Effect.catch((error) => Effect.logWarning("browser artifact cleanup failed", { error })),
);
yield* cleanFiles(config.logsDir, settings.logsAfterDays, now, true).pipe(
Effect.catch((error) => Effect.logWarning("rotated log cleanup failed", { error })),
);
});
const worker = yield* makeDrainableWorker(() =>
sweep().pipe(
Effect.catchCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.failCause(cause)
: Effect.logWarning("storage cleanup failed", { cause }),
),
),
);
const start = Effect.fn("StorageCleanup.start")(function* () {
const unsubscribe = yield* terminals.subscribeMetadata((event) =>
Effect.sync(() => {
if (event.type === "snapshot") {
liveTerminals.clear();
for (const terminal of event.terminals) noteTerminal(terminal);
} else if (event.type === "upsert") {
noteTerminal(event.terminal);
} else {
const threadTerminals = liveTerminals.get(event.threadId);
threadTerminals?.delete(event.terminalId);
if (threadTerminals?.size === 0) liveTerminals.delete(event.threadId);
}
}),
);
yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
const changes = yield* settingsService.subscribeChanges;
const events = yield* engine.subscribeDomainEvents;
let lastSettings = yield* settingsService.getSettings.pipe(Effect.orDie);
yield* forkParked(
worker
.enqueue(undefined)
.pipe(
Effect.andThen(worker.drain),
Effect.repeat(Schedule.spaced("1 hour")),
Effect.asVoid,
),
);
yield* forkParked(
Stream.runForEach(changes, (settings) => {
if (
Equal.equals(settings.storageCleanup, lastSettings.storageCleanup) &&
Equal.equals(settings.worktreeCleanup, lastSettings.worktreeCleanup) &&
sameProjectWorktreePolicies(settings, lastSettings)
)
return Effect.void;
lastSettings = settings;
return worker.enqueue(undefined);
}),
);
yield* forkParked(
Stream.runForEach(events, (event) =>
event.type === "thread.deleted" &&
anyWorktreePolicy(lastSettings, (rules) => rules.worktreeOnDelete)
? worker.enqueue(undefined)
: Effect.void,
),
);
});
return { start, drain: worker.drain } satisfies StorageCleanup["Service"];
});
export const layer = Layer.effect(StorageCleanup, make);
+18 -2
View File
@@ -6,6 +6,7 @@
*
* @module TerminalManager
*/
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
import {
DEFAULT_TERMINAL_ID,
TerminalCwdError,
@@ -2516,7 +2517,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
}).pipe(Effect.ignoreCause({ log: true })),
);
const openLocked = Effect.fn("terminal.openLocked")(function* (input: TerminalOpenInput) {
const openWithWorkspaceLease = Effect.fn("terminal.openLocked")(function* (
input: TerminalOpenInput,
) {
const terminalId = input.terminalId;
yield* assertValidCwd(input.cwd);
@@ -2639,6 +2642,12 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
return snapshot(liveSession);
});
const openLocked = (input: TerminalOpenInput) =>
withWorkspaceLease(
path.resolve(input.worktreePath ?? input.cwd),
openWithWorkspaceLease(input),
);
const open: TerminalManager["Service"]["open"] = (input) =>
withThreadLock(
input.threadId,
@@ -3010,7 +3019,14 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
const restart: TerminalManager["Service"]["restart"] = (input) =>
withThreadLock(
input.threadId,
resolveLaunchInputEnvironment(input).pipe(Effect.flatMap(restartResolved)),
resolveLaunchInputEnvironment(input).pipe(
Effect.flatMap((resolved) =>
withWorkspaceLease(
path.resolve(resolved.worktreePath ?? resolved.cwd),
restartResolved(resolved),
),
),
),
);
const close: TerminalManager["Service"]["close"] = (input) =>
@@ -0,0 +1,23 @@
import * as Effect from "effect/Effect";
import * as Semaphore from "effect/Semaphore";
const leases = new Map<string, { semaphore: Semaphore.Semaphore; users: number }>();
/** Coordinates checkout removal and startup across threads using the same resolved cwd. */
export const withWorkspaceLease = <A, E, R>(
cwd: string,
effect: Effect.Effect<A, E, R>,
): Effect.Effect<A, E, R> =>
Effect.suspend(() => {
const lease = leases.get(cwd) ?? { semaphore: Semaphore.makeUnsafe(1), users: 0 };
leases.set(cwd, lease);
lease.users++;
return lease.semaphore.withPermit(effect).pipe(
Effect.ensuring(
Effect.sync(() => {
lease.users--;
if (lease.users === 0) leases.delete(cwd);
}),
),
);
});
@@ -15,6 +15,7 @@ import {
BotIcon,
createLucideIcon,
GitBranchIcon,
HardDriveIcon,
PanelsTopLeftIcon,
KeyboardIcon,
Link2Icon,
@@ -83,6 +84,7 @@ const SETTINGS_SECTION_ICONS: Readonly<
"/settings/providers": BotIcon,
"/settings/integrations": BlocksIcon,
"/settings/source-control": GitBranchIcon,
"/settings/storage": HardDriveIcon,
"/settings/connections": Link2Icon,
"/settings/archived": ArchiveIcon,
};
@@ -0,0 +1,288 @@
import type { StorageCleanupSettings, WorktreeCleanupRules } from "@t3tools/contracts";
import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
import { useState } from "react";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Switch } from "../ui/switch";
import {
NumberField,
NumberFieldDecrement,
NumberFieldGroup,
NumberFieldIncrement,
NumberFieldInput,
} from "../ui/number-field";
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
import { SettingsScopeNotice } from "./SettingsScopeNotice";
import type { ScopedSettingsTarget } from "./scopedSettings";
import { useSettingsScope } from "./SettingsScopeContext";
import {
useClearScopedSettings,
useScopedSettings,
useUpdateScopedSettings,
} from "./useScopedSettings";
function RetentionControl({
label,
value,
onChange,
}: {
label: string;
value: number | null;
onChange: (value: number | null) => void;
}) {
const [draft, setDraft] = useState(value);
const [savedValue, setSavedValue] = useState(value);
if (savedValue !== value) {
setSavedValue(value);
setDraft(value);
}
return (
<div className="flex items-center gap-3">
{value !== null ? (
<NumberField
value={draft}
min={1}
max={3650}
step={1}
size="sm"
className="w-auto"
onValueChange={setDraft}
onValueCommitted={(next) => {
if (next === null) setDraft(value);
else {
const days = Math.min(3650, Math.max(1, Math.round(next)));
setDraft(days);
onChange(days);
}
}}
>
<NumberFieldGroup>
<NumberFieldDecrement aria-label={`Decrease ${label}`} />
<NumberFieldInput
aria-label={`${label} in days`}
size={new Intl.NumberFormat().format(draft ?? value).length}
className="field-sizing-content w-auto min-w-[1ch] grow-0 text-right in-data-[size=sm]:px-1"
/>
<span aria-hidden="true" className="self-center pr-2 text-xs">
days
</span>
<NumberFieldIncrement aria-label={`Increase ${label}`} />
</NumberFieldGroup>
</NumberField>
) : (
<span className="text-xs text-muted-foreground">Off</span>
)}
<Switch
aria-label={label}
checked={value !== null}
onCheckedChange={(enabled) => onChange(enabled ? 8 : null)}
/>
</div>
);
}
export function StorageSettingsPanel() {
const { scope, connectedEnvironments, targets, target } = useSettingsScope();
const scopedSettings = useScopedSettings();
const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
const settings = {
...scopedSettings.storageCleanup,
...resolveWorktreeCleanup(scopedSettings, null),
};
const projectMode = (entry: ScopedSettingsTarget | null) =>
entry?.sources.worktreeCleanup === "project"
? (entry.settings.worktreeCleanup?.mode ?? "inherit")
: "inherit";
const mode = projectMode(target);
const mixedModes = targets.some((entry) => projectMode(entry) !== mode);
const updateSettings = useUpdateScopedSettings();
const clearSettings = useClearScopedSettings();
const ruleStatus = (key: keyof StorageCleanupSettings) =>
targets.some(
(target) =>
({ ...target.settings.storageCleanup, ...resolveWorktreeCleanup(target.settings, null) })[
key
] !== settings[key],
)
? "Mixed across selected machines"
: undefined;
const update = (patch: Partial<StorageCleanupSettings>) =>
updateSettings({ storageCleanup: patch });
const updateWorktree = (patch: Partial<WorktreeCleanupRules>) =>
isProjectScope
? updateSettings({ worktreeCleanup: { mode: "custom", rules: patch } })
: update(patch);
if (
isProjectScope &&
connectedEnvironments.some(
(environment) =>
environment.serverConfig?.environment.capabilities.projectWorktreeCleanup !== true,
)
) {
return (
<SettingsScopeNotice target="all">
Update the selected machines to configure project worktree cleanup.
</SettingsScopeNotice>
);
}
if (
connectedEnvironments.some(
(environment) => environment.serverConfig?.environment.capabilities.storageCleanup !== true,
)
) {
return (
<SettingsScopeNotice
target="environment"
eligibleEnvironmentIds={connectedEnvironments
.filter(
(environment) =>
environment.serverConfig?.environment.capabilities.storageCleanup === true,
)
.map((environment) => environment.environmentId)}
>
Update the selected environments to use storage cleanup, or choose a machine that supports
it.
</SettingsScopeNotice>
);
}
return (
<SettingsPageContainer>
<SettingsSection id="storage-worktrees" title="Worktrees">
{isProjectScope && (
<SettingsRow
title="Automatic worktree cleanup"
description={
mode === "off"
? "Keep this project's worktrees until you delete them manually."
: mode === "custom"
? "Use these rules for this project."
: "Use each machine's worktree cleanup settings."
}
serverScoped
settingKeys={["worktreeCleanup"]}
mixed={mixedModes}
control={
<Select
value={mixedModes ? null : mode}
onValueChange={(next) => {
if (next === "inherit") clearSettings(["worktreeCleanup"]);
else if (next === "off") updateSettings({ worktreeCleanup: { mode: "off" } });
else if (next === "custom")
updateSettings({ worktreeCleanup: { mode: "custom", rules: {} } });
}}
>
<SelectTrigger size="sm" aria-label="Automatic worktree cleanup">
<SelectValue>
{mixedModes
? "Mixed"
: mode === "inherit"
? "Inherit"
: mode === "off"
? "Off"
: "Custom"}
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
<SelectItem value="inherit">Inherit</SelectItem>
<SelectItem value="off">Off</SelectItem>
<SelectItem value="custom">Custom</SelectItem>
</SelectPopup>
</Select>
}
/>
)}
{(!isProjectScope || (!mixedModes && mode === "custom")) && (
<>
<SettingsRow
title="Delete worktrees with deleted threads"
status={ruleStatus("worktreeOnDelete")}
description="Remove unused worktrees when active or archived threads are deleted. Worktrees with local changes are kept."
serverScoped={!isProjectScope}
control={
<Switch
aria-label="Delete worktrees with deleted threads"
checked={settings.worktreeOnDelete}
onCheckedChange={(worktreeOnDelete) => updateWorktree({ worktreeOnDelete })}
/>
}
/>
<SettingsRow
title="Delete inactive worktrees"
status={ruleStatus("worktreeAfterDays")}
description="Remove worktrees after their threads have been inactive for this many days. Branches and thread history are kept."
serverScoped={!isProjectScope}
control={
<RetentionControl
label="Delete inactive worktrees"
value={settings.worktreeAfterDays}
onChange={(worktreeAfterDays) => updateWorktree({ worktreeAfterDays })}
/>
}
/>
<SettingsRow
title="Delete merged worktrees"
status={ruleStatus("worktreeOnMerge")}
description="Remove worktrees whose pull request is merged and whose commits are included in the default branch."
serverScoped={!isProjectScope}
control={
<Switch
aria-label="Delete merged worktrees"
checked={settings.worktreeOnMerge}
onCheckedChange={(worktreeOnMerge) => updateWorktree({ worktreeOnMerge })}
/>
}
/>
<SettingsRow
title="Delete unchanged worktrees"
status={ruleStatus("worktreeUnchanged")}
description="Remove worktrees with no commits beyond the default branch."
serverScoped={!isProjectScope}
control={
<Switch
aria-label="Delete unchanged worktrees"
checked={settings.worktreeUnchanged}
onCheckedChange={(worktreeUnchanged) => updateWorktree({ worktreeUnchanged })}
/>
}
/>
</>
)}
</SettingsSection>
{!isProjectScope && (
<SettingsSection id="storage-artifacts" title="Artifacts and logs">
<SettingsRow
title="Delete old browser artifacts"
status={ruleStatus("browserArtifactsAfterDays")}
description="Delete saved browser captures after this many days. Older capture links will no longer open."
serverScoped
control={
<RetentionControl
label="Delete old browser artifacts"
value={settings.browserArtifactsAfterDays}
onChange={(browserArtifactsAfterDays) => update({ browserArtifactsAfterDays })}
/>
}
/>
<SettingsRow
title="Delete old rotated logs"
status={ruleStatus("logsAfterDays")}
description="Delete inactive rotated log files after this many days. Current logs are kept."
serverScoped
control={
<RetentionControl
label="Delete old rotated logs"
value={settings.logsAfterDays}
onChange={(logsAfterDays) => update({ logsAfterDays })}
/>
}
/>
</SettingsSection>
)}
</SettingsPageContainer>
);
}
@@ -5,6 +5,8 @@ import {
type ServerSettings,
} from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
import type { SidebarProjectSnapshot } from "../../sidebarProjectGrouping";
import {
@@ -146,6 +148,48 @@ describe("scoped settings targets", () => {
});
describe("scoped settings writes", () => {
it("edits the effective machine policy without changing other machines' rules", () => {
const custom = environment("Laptop", {
settings: {
worktreeCleanup: {
mode: "custom",
rules: {
worktreeAfterDays: 12,
worktreeOnDelete: true,
worktreeOnMerge: true,
worktreeUnchanged: false,
},
},
},
});
const disabled = environment("Server", {
settings: { worktreeCleanup: { mode: "off" } },
});
const targets = [custom, disabled];
const plan = planScopedSettingsPatch(all, targets, {
storageCleanup: { worktreeOnDelete: false },
});
const policies = plan.serverWrites.map((write, index) =>
resolveWorktreeCleanup(
applyServerSettingsPatch(targets[index]!.serverConfig!.settings, write.patch),
null,
),
);
expect(policies).toEqual([
{
worktreeAfterDays: 12,
worktreeOnDelete: false,
worktreeOnMerge: true,
worktreeUnchanged: false,
},
{
worktreeAfterDays: null,
worktreeOnDelete: false,
worktreeOnMerge: false,
worktreeUnchanged: false,
},
]);
});
it("isolates a formerly shared server preference to the named environment", async () => {
const persistServer = vi.fn().mockResolvedValue({ _tag: "Success" });
const persistClient = vi.fn();
@@ -231,6 +275,74 @@ describe("scoped settings writes", () => {
});
});
it("keeps each project's other cleanup rules when changing one rule across machines", () => {
const machine = environment("Laptop", {
settings: {
storageCleanup: { ...DEFAULT_SERVER_SETTINGS.storageCleanup, worktreeAfterDays: 30 },
},
});
const customized = environment("Server", {
settings: {
projectSettingsOverrides: {
[projectId]: {
defaultAutoPull: true,
worktreeCleanup: {
mode: "custom",
rules: {
worktreeAfterDays: 8,
worktreeOnDelete: false,
worktreeOnMerge: true,
worktreeUnchanged: false,
},
},
},
},
},
});
const plan = planScopedSettingsPatch(project, [machine, customized], {
worktreeCleanup: { mode: "custom", rules: { worktreeOnDelete: true } },
});
expect(plan.serverWrites.map((write) => write.patch.projectSettingsOverrides)).toEqual([
{
[projectId]: {
defaultAutoPull: true,
worktreeCleanup: {
mode: "custom",
rules: {
worktreeAfterDays: 8,
worktreeOnDelete: true,
worktreeOnMerge: true,
worktreeUnchanged: false,
},
},
},
},
{
[laptopProjectId]: {
worktreeCleanup: {
mode: "custom",
rules: {
worktreeAfterDays: 30,
worktreeOnDelete: true,
worktreeOnMerge: false,
worktreeUnchanged: false,
},
},
},
},
]);
expect(
planScopedSettingsClear(checkout, [customized], ["worktreeCleanup"]).serverWrites[0]?.patch,
).toEqual({
projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } },
});
expect(
planScopedSettingsPatch(project, [machine, customized], {
storageCleanup: { browserArtifactsAfterDays: 8 },
}).serverWrites,
).toEqual([]);
});
it("scopes agent device access to projects while keeping hub and hosts environment-wide", () => {
const plan = planScopedSettingsPatch(project, [laptop, server], {
enableAgentDeviceAccess: true,
@@ -13,6 +13,7 @@ import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connect
import {
clearProjectSettingsOverrides,
resolveProjectSettings,
resolveWorktreeCleanup,
type ProjectSettingSource,
} from "@t3tools/shared/projectSettings";
import * as Equal from "effect/Equal";
@@ -223,6 +224,16 @@ export function planScopedSettingsPatch(
const effective = resolveProjectSettings(settings, projectId).settings;
const next: Record<string, unknown> = { ...current };
for (const [key, value] of Object.entries(serverPatch)) {
if (key === "worktreeCleanup" && serverPatch.worktreeCleanup?.mode === "custom") {
next[key] = {
mode: "custom",
rules: {
...resolveWorktreeCleanup(settings, projectId),
...serverPatch.worktreeCleanup.rules,
},
};
continue;
}
const base = effective[key as keyof ServerSettings];
next[key] =
isPlainObject(value) && isPlainObject(base) ? { ...base, ...value } : value;
@@ -233,7 +244,25 @@ export function planScopedSettingsPatch(
? connectedEnvironments.map((environment) => ({
environmentId: environment.environmentId,
label: environment.label,
patch: serverPatch,
patch:
environment.serverConfig?.settings.worktreeCleanup != null &&
serverPatch.storageCleanup &&
Object.keys(serverPatch.storageCleanup).some((key) => key.startsWith("worktree"))
? {
...serverPatch,
worktreeCleanup: {
mode: "custom",
rules: {
...resolveWorktreeCleanup(environment.serverConfig.settings, null),
...Object.fromEntries(
Object.entries(serverPatch.storageCleanup).filter(([key]) =>
key.startsWith("worktree"),
),
),
},
},
}
: serverPatch,
}))
: [];
const hasClientWrite = Object.keys(clientPatch).length > 0;
@@ -20,6 +20,7 @@ export type SettingsPath =
| "/settings/providers"
| "/settings/integrations"
| "/settings/source-control"
| "/settings/storage"
| "/settings/connections"
| "/settings/archived";
@@ -88,6 +89,7 @@ export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
"/settings/providers": "Providers",
"/settings/integrations": "Integrations",
"/settings/source-control": "Source Control",
"/settings/storage": "Storage",
"/settings/connections": "Connections",
"/settings/archived": "Archive",
};
@@ -125,6 +127,22 @@ const KEYBINDING_SEARCH_ITEMS = STATIC_KEYBINDING_COMMANDS.toSorted((left, right
* that may not be mounted point at their nearest stable section instead.
*/
export const SETTINGS_SEARCH_ITEMS = [
{
id: "storage-worktrees",
title: "Worktree cleanup",
to: "/settings/storage",
scope: "project-defaults",
searchTerms: [
"disk storage delete deleted archived threads old inactive merged unchanged worktrees retention days project inherit off custom",
],
},
{
id: "storage-artifacts",
title: "Artifacts and logs",
to: "/settings/storage",
scope: "environment-defaults",
searchTerms: ["disk storage browser screenshots captures rotated logs cleanup retention"],
},
{
id: "project-defaults",
title: "Project defaults and overrides",
@@ -789,6 +807,7 @@ const SETTINGS_CATEGORY_SCOPES: Readonly<Record<SettingsPath, SettingsSearchScop
"/settings/providers": null,
"/settings/integrations": null,
"/settings/source-control": "environment-defaults",
"/settings/storage": "project-defaults",
"/settings/connections": "connections",
"/settings/archived": "project-defaults",
};
+10 -1
View File
@@ -7,6 +7,7 @@ import {
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { canSnooze, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
import * as Cause from "effect/Cause";
import * as Schema from "effect/Schema";
import { AsyncResult } from "effect/unstable/reactivity";
@@ -16,6 +17,8 @@ import { useCallback, useMemo, useRef } from "react";
import { getFallbackThreadIdAfterDelete, pinOrderKeyBetween } from "../components/Sidebar.logic";
import { useComposerDraftStore } from "../composerDraftStore";
import { terminalEnvironment } from "../state/terminal";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { environmentServerConfigsAtom } from "../state/server";
import { threadEnvironment } from "../state/threads";
import { vcsEnvironment } from "../state/vcs";
import { useNewThreadHandler } from "./useHandleNewThread";
@@ -356,7 +359,13 @@ export function useThreadActions() {
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== null;
const localApi = readLocalApi();
let shouldDeleteWorktree = false;
if (canDeleteWorktree && localApi) {
const environmentSettings = appAtomRegistry
.get(environmentServerConfigsAtom)
.get(threadRef.environmentId)?.settings;
const automaticWorktreeCleanup = environmentSettings
? resolveWorktreeCleanup(environmentSettings, thread.projectId).worktreeOnDelete
: false;
if (canDeleteWorktree && localApi && !automaticWorktreeCleanup) {
const confirmationResult = await settlePromise(() =>
localApi.dialogs.confirm(
[
+21
View File
@@ -16,6 +16,7 @@ import { Route as PairRouteImport } from './routes/pair'
import { Route as ConnectRouteImport } from './routes/connect'
import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as SettingsStorageRouteImport } from './routes/settings.storage'
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
import { Route as SettingsSnapShotRouteImport } from './routes/settings.snap-shot'
import { Route as SettingsProvidersRouteImport } from './routes/settings.providers'
@@ -67,6 +68,11 @@ const ChatIndexRoute = ChatIndexRouteImport.update({
path: '/',
getParentRoute: () => ChatRoute,
} as any)
const SettingsStorageRoute = SettingsStorageRouteImport.update({
id: '/storage',
path: '/storage',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsSourceControlRoute = SettingsSourceControlRouteImport.update({
id: '/source-control',
path: '/source-control',
@@ -171,6 +177,7 @@ export interface FileRoutesByFullPath {
'/settings/providers': typeof SettingsProvidersRoute
'/settings/snap-shot': typeof SettingsSnapShotRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/settings/storage': typeof SettingsStorageRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
}
@@ -194,6 +201,7 @@ export interface FileRoutesByTo {
'/settings/providers': typeof SettingsProvidersRoute
'/settings/snap-shot': typeof SettingsSnapShotRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/settings/storage': typeof SettingsStorageRoute
'/': typeof ChatIndexRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
@@ -220,6 +228,7 @@ export interface FileRoutesById {
'/settings/providers': typeof SettingsProvidersRoute
'/settings/snap-shot': typeof SettingsSnapShotRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/settings/storage': typeof SettingsStorageRoute
'/_chat/': typeof ChatIndexRoute
'/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/_chat/draft/$draftId': typeof ChatDraftDraftIdRoute
@@ -247,6 +256,7 @@ export interface FileRouteTypes {
| '/settings/providers'
| '/settings/snap-shot'
| '/settings/source-control'
| '/settings/storage'
| '/$environmentId/$threadId'
| '/draft/$draftId'
fileRoutesByTo: FileRoutesByTo
@@ -270,6 +280,7 @@ export interface FileRouteTypes {
| '/settings/providers'
| '/settings/snap-shot'
| '/settings/source-control'
| '/settings/storage'
| '/'
| '/$environmentId/$threadId'
| '/draft/$draftId'
@@ -295,6 +306,7 @@ export interface FileRouteTypes {
| '/settings/providers'
| '/settings/snap-shot'
| '/settings/source-control'
| '/settings/storage'
| '/_chat/'
| '/_chat/$environmentId/$threadId'
| '/_chat/draft/$draftId'
@@ -361,6 +373,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ChatIndexRouteImport
parentRoute: typeof ChatRoute
}
'/settings/storage': {
id: '/settings/storage'
path: '/storage'
fullPath: '/settings/storage'
preLoaderRoute: typeof SettingsStorageRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/source-control': {
id: '/settings/source-control'
path: '/source-control'
@@ -505,6 +524,7 @@ interface SettingsRouteChildren {
SettingsProvidersRoute: typeof SettingsProvidersRoute
SettingsSnapShotRoute: typeof SettingsSnapShotRoute
SettingsSourceControlRoute: typeof SettingsSourceControlRoute
SettingsStorageRoute: typeof SettingsStorageRoute
}
const SettingsRouteChildren: SettingsRouteChildren = {
@@ -520,6 +540,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {
SettingsProvidersRoute: SettingsProvidersRoute,
SettingsSnapShotRoute: SettingsSnapShotRoute,
SettingsSourceControlRoute: SettingsSourceControlRoute,
SettingsStorageRoute: SettingsStorageRoute,
}
const SettingsRouteWithChildren = SettingsRoute._addFileChildren(
+4
View File
@@ -0,0 +1,4 @@
import { createFileRoute } from "@tanstack/react-router";
import { StorageSettingsPanel } from "../components/settings/StorageSettings";
export const Route = createFileRoute("/settings/storage")({ component: StorageSettingsPanel });
+26
View File
@@ -41,6 +41,32 @@ on each selected environment, and reset returns to the environment's shared list
For workspace mode, a project's `t3.json` preference applies when the project has no override.
Browser access changes apply when an agent session next starts.
## Storage cleanup
Open **Settings → Storage** to enable automatic cleanup on one machine or all connected
environments. Policies are off by default and run on the server at startup, when changed, and
hourly. Offline machines keep their existing policies.
Select a project to set **Automatic worktree cleanup** to **Inherit**, **Off**, or **Custom**.
Inherit follows each machine's rules; Off keeps that project's worktrees until you remove them
manually. Custom applies separate worktree rules to the selected project or checkout. Browser
captures and log retention remain machine-wide.
Worktrees can be removed after a chosen number of inactive days, after merging, or when they
have no commits beyond the default branch. Only T3-managed worktrees are eligible. Active
sessions, shared worktrees, uncommitted changes, and ignored files other than `node_modules`
prevent removal. Branches and thread history stay; starting another turn recreates the checkout.
Merge cleanup requires the commits to be included in the remote default branch, so squash merges
may need the inactivity rule instead.
Enable **Delete worktrees with deleted threads** to remove safe worktrees after their last
thread is deleted, including archived threads and worktrees left by earlier deletions. The
server waits for sessions and terminals to stop and retries skipped worktrees after restart.
Existing prompts for deleting a worktree manually remain available when this policy is off.
Browser captures and rotated logs have separate retention periods. Expired capture links stop
working. Current logs, message attachments, and browser profiles are kept.
## Project icons
Select the project and open Project to choose an icon, emoji, monogram, or image. The choice applies to
+2
View File
@@ -105,6 +105,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
threadSettlement: Schema.optionalKey(Schema.Boolean),
/** Server evaluates merge and inactivity settlement without a client. */
threadAutoSettlement: Schema.optionalKey(Schema.Boolean),
storageCleanup: Schema.optionalKey(Schema.Boolean),
projectWorktreeCleanup: Schema.optionalKey(Schema.Boolean),
/** Server persists the opt-in for continuing interrupted threads after restarts. */
threadRestartContinuation: Schema.optionalKey(Schema.Boolean),
/** Server resolves `projectSettingsOverrides`; older servers ignore the key. */
+44
View File
@@ -20,6 +20,50 @@ const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
const decodeClaudeSettings = Schema.decodeUnknownSync(ClaudeSettings);
describe("storage cleanup settings", () => {
it("keeps cleanup disabled for existing installations", () => {
expect(decodeServerSettings({}).worktreeCleanup).toBeNull();
expect(decodeServerSettings({}).storageCleanup).toEqual({
worktreeAfterDays: null,
worktreeOnMerge: false,
worktreeOnDelete: false,
worktreeUnchanged: false,
browserArtifactsAfterDays: null,
logsAfterDays: null,
});
});
it("accepts eight-day retention and disabling one rule without resetting others", () => {
expect(decodeServerSettingsPatch({ storageCleanup: { worktreeAfterDays: 8 } })).toEqual({
storageCleanup: { worktreeAfterDays: 8 },
});
expect(decodeServerSettingsPatch({ storageCleanup: { worktreeAfterDays: null } })).toEqual({
storageCleanup: { worktreeAfterDays: null },
});
});
it("accepts partial custom patches but requires complete stored project rules", () => {
expect(
decodeServerSettingsPatch({
worktreeCleanup: { mode: "custom", rules: { worktreeAfterDays: 8 } },
}),
).toEqual({ worktreeCleanup: { mode: "custom", rules: { worktreeAfterDays: 8 } } });
expect(() =>
decodeServerSettings({
projectSettingsOverrides: {
project: { worktreeCleanup: { mode: "custom", rules: { worktreeAfterDays: 8 } } },
},
}),
).toThrow();
});
it.each([0, -1, 1.5, 3651])("rejects invalid retention %s", (days) => {
expect(() =>
decodeServerSettingsPatch({ storageCleanup: { browserArtifactsAfterDays: days } }),
).toThrow();
});
});
describe("ClientSettings rich text composer", () => {
it("enables rich text for new and existing settings without a saved preference", () => {
expect(decodeClientSettings({}).composerRichTextEnabled).toBe(true);
+66
View File
@@ -967,7 +967,28 @@ export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;
export const ResponseStreamingMode = Schema.Literals(["turn", "paragraph", "token"]);
export type ResponseStreamingMode = typeof ResponseStreamingMode.Type;
const StorageRetentionDays = Schema.NullOr(
Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 3650 })),
);
export const WorktreeCleanupRules = Schema.Struct({
worktreeAfterDays: StorageRetentionDays,
worktreeOnMerge: Schema.Boolean,
worktreeOnDelete: Schema.Boolean,
worktreeUnchanged: Schema.Boolean,
});
export type WorktreeCleanupRules = typeof WorktreeCleanupRules.Type;
export const WorktreeCleanup = Schema.NullOr(
Schema.Union([
Schema.Struct({ mode: Schema.Literal("off") }),
Schema.Struct({ mode: Schema.Literal("custom"), rules: WorktreeCleanupRules }),
]),
);
export type WorktreeCleanup = typeof WorktreeCleanup.Type;
export const PROJECT_SCOPED_SERVER_SETTING_KEYS = [
"worktreeCleanup",
"defaultModelSelection",
"defaultRuntimeMode",
"defaultThreadEnvMode",
@@ -993,6 +1014,7 @@ export type ProjectScopedServerSettingKey = (typeof PROJECT_SCOPED_SERVER_SETTIN
* model, no dedicated writer model, never auto-settle).
*/
export const ProjectSettingsOverrides = Schema.Struct({
worktreeCleanup: Schema.optionalKey(WorktreeCleanup),
defaultModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
defaultRuntimeMode: Schema.optionalKey(RuntimeMode),
defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
@@ -1012,7 +1034,25 @@ export const ProjectSettingsOverrides = Schema.Struct({
} satisfies Record<ProjectScopedServerSettingKey, unknown>);
export type ProjectSettingsOverrides = typeof ProjectSettingsOverrides.Type;
export const StorageCleanupSettings = Schema.Struct({
worktreeAfterDays: StorageRetentionDays.pipe(Schema.withDecodingDefault(Effect.succeed(null))),
worktreeOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
worktreeOnDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
worktreeUnchanged: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
browserArtifactsAfterDays: StorageRetentionDays.pipe(
Schema.withDecodingDefault(Effect.succeed(null)),
),
logsAfterDays: StorageRetentionDays.pipe(Schema.withDecodingDefault(Effect.succeed(null))),
});
export type StorageCleanupSettings = typeof StorageCleanupSettings.Type;
export const ServerSettings = Schema.Struct({
worktreeCleanup: WorktreeCleanup.pipe(Schema.withDecodingDefault(Effect.succeed(null))),
storageCleanup: StorageCleanupSettings.pipe(
Schema.withDecodingDefault(
Effect.succeed(Schema.decodeUnknownSync(StorageCleanupSettings)({})),
),
),
// How assistant text reaches clients during a turn. Deliberately a fresh
// key (was `enableLegacyTokenStreaming`, before that
// `enableAssistantStreaming`): decoding drops the old key, so everyone,
@@ -1352,6 +1392,32 @@ const OpenCodeSettingsPatch = Schema.Struct({
});
export const ServerSettingsPatch = Schema.Struct({
worktreeCleanup: Schema.optionalKey(
Schema.NullOr(
Schema.Union([
Schema.Struct({ mode: Schema.Literal("off") }),
Schema.Struct({
mode: Schema.Literal("custom"),
rules: Schema.Struct({
worktreeAfterDays: Schema.optionalKey(StorageRetentionDays),
worktreeOnMerge: Schema.optionalKey(Schema.Boolean),
worktreeOnDelete: Schema.optionalKey(Schema.Boolean),
worktreeUnchanged: Schema.optionalKey(Schema.Boolean),
}),
}),
]),
),
),
storageCleanup: Schema.optionalKey(
Schema.Struct({
worktreeAfterDays: Schema.optionalKey(StorageRetentionDays),
worktreeOnMerge: Schema.optionalKey(Schema.Boolean),
worktreeOnDelete: Schema.optionalKey(Schema.Boolean),
worktreeUnchanged: Schema.optionalKey(Schema.Boolean),
browserArtifactsAfterDays: Schema.optionalKey(StorageRetentionDays),
logsAfterDays: Schema.optionalKey(StorageRetentionDays),
}),
),
// Server settings
responseStreamingMode: Schema.optionalKey(ResponseStreamingMode),
enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
@@ -10,6 +10,7 @@ import {
clearProjectSettingsOverrides,
hasProjectSettingsOverrides,
resolveProjectSettings,
resolveWorktreeCleanup,
withProjectSettingsOverrides,
} from "./projectSettings.ts";
import { applyServerSettingsPatch } from "./serverSettings.ts";
@@ -214,3 +215,60 @@ describe("projectSettingsOverrides patches", () => {
});
});
});
describe("resolveWorktreeCleanup", () => {
it("inherits machine rules, disables one project and keeps custom rules isolated", () => {
const machine = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
storageCleanup: { worktreeAfterDays: 8, worktreeOnDelete: true, logsAfterDays: 3 },
});
const inherited = resolveWorktreeCleanup(machine, projectId);
const off = applyServerSettingsPatch(machine, {
projectSettingsOverrides: {
[projectId]: { worktreeCleanup: { mode: "off" } },
},
});
expect(resolveWorktreeCleanup(off, projectId)).toEqual({
worktreeAfterDays: null,
worktreeOnDelete: false,
worktreeOnMerge: false,
worktreeUnchanged: false,
});
expect(resolveWorktreeCleanup(off, otherProjectId)).toEqual(inherited);
const custom = applyServerSettingsPatch(off, {
projectSettingsOverrides: {
[projectId]: {
worktreeCleanup: { mode: "custom", rules: { ...inherited, worktreeAfterDays: 15 } },
},
},
});
expect(resolveWorktreeCleanup(custom, projectId).worktreeAfterDays).toBe(15);
expect(custom.storageCleanup.logsAfterDays).toBe(3);
const reset = applyServerSettingsPatch(custom, {
projectSettingsOverrides: {
[projectId]: clearProjectSettingsOverrides(custom, projectId, ["worktreeCleanup"]),
},
});
expect(resolveWorktreeCleanup(reset, projectId)).toEqual(inherited);
});
it("completes partial machine custom rules and preserves them across edits", () => {
const initial = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
storageCleanup: { worktreeAfterDays: 8, worktreeOnDelete: true },
});
const custom = applyServerSettingsPatch(initial, {
worktreeCleanup: { mode: "custom", rules: { worktreeOnMerge: true } },
});
const edited = applyServerSettingsPatch(custom, {
worktreeCleanup: { mode: "custom", rules: { worktreeAfterDays: 15 } },
});
expect(resolveWorktreeCleanup(edited, null)).toEqual({
worktreeAfterDays: 15,
worktreeOnDelete: true,
worktreeOnMerge: true,
worktreeUnchanged: false,
});
expect(
resolveWorktreeCleanup(applyServerSettingsPatch(edited, { worktreeCleanup: null }), null)
.worktreeAfterDays,
).toBe(8);
});
});
+20
View File
@@ -6,6 +6,7 @@ import {
type ProjectSettingsOverrides,
type ServerSettings,
type ThreadEnvMode,
type WorktreeCleanupRules,
} from "@t3tools/contracts";
import { isModelSelectionProviderEnabled } from "./serverSettings.ts";
@@ -124,3 +125,22 @@ export function clearProjectSettingsOverrides(
for (const key of keys) delete next[key];
return Object.keys(next).length === 0 ? null : next;
}
/** Worktree rules are project-scoped; artifact and log retention stays environment-wide. */
export function resolveWorktreeCleanup(
settings: ServerSettings,
projectId: ProjectId | null,
): WorktreeCleanupRules {
const policy = resolveProjectSettings(settings, projectId).settings.worktreeCleanup;
if (policy?.mode === "custom") return policy.rules;
if (policy?.mode === "off")
return {
worktreeAfterDays: null,
worktreeOnMerge: false,
worktreeOnDelete: false,
worktreeUnchanged: false,
};
const { worktreeAfterDays, worktreeOnMerge, worktreeOnDelete, worktreeUnchanged } =
settings.storageCleanup;
return { worktreeAfterDays, worktreeOnMerge, worktreeOnDelete, worktreeUnchanged };
}
@@ -24,6 +24,23 @@ import {
const FOLDED_SERVER_SETTINGS = { ...DEFAULT_SERVER_SETTINGS, projectSettingsFolded: true };
describe("serverSettings helpers", () => {
it("changes a cleanup rule without replacing the machine's other rules", () => {
const enabled = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {
storageCleanup: { worktreeAfterDays: 8, worktreeOnMerge: true, logsAfterDays: 30 },
});
expect(
applyServerSettingsPatch(enabled, {
storageCleanup: { worktreeAfterDays: null },
}).storageCleanup,
).toEqual({
worktreeAfterDays: null,
worktreeOnMerge: true,
worktreeOnDelete: false,
worktreeUnchanged: false,
browserArtifactsAfterDays: null,
logsAfterDays: 30,
});
});
it("replaces SSH host lists when saving, editing, and removing hosts", () => {
const host = { id: "mini", label: "Mac mini", target: "mini" };
const saved = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { deviceHosts: [host] });
+21
View File
@@ -270,6 +270,7 @@ export function applyServerSettingsPatch(
providerHealthRefreshInterval,
backgroundActivityProfile,
backgroundActivity,
worktreeCleanup: worktreeCleanupPatch,
// Merged per entry below; its `null` removals must not reach deepMerge.
usageLimitSources: usageLimitSourcesPatch,
usagePriceOverrides: usagePriceOverridesPatch,
@@ -320,6 +321,26 @@ export function applyServerSettingsPatch(
const next = deepMerge(current, patchForMerge);
const nextWithReplacementsBase = {
...next,
...(worktreeCleanupPatch === undefined
? {}
: {
worktreeCleanup:
worktreeCleanupPatch?.mode === "custom"
? {
mode: "custom" as const,
rules: {
worktreeAfterDays: next.storageCleanup.worktreeAfterDays,
worktreeOnMerge: next.storageCleanup.worktreeOnMerge,
worktreeOnDelete: next.storageCleanup.worktreeOnDelete,
worktreeUnchanged: next.storageCleanup.worktreeUnchanged,
...(current.worktreeCleanup?.mode === "custom"
? current.worktreeCleanup.rules
: {}),
...worktreeCleanupPatch.rules,
},
}
: worktreeCleanupPatch,
}),
...(backgroundActivity !== undefined
? {
backgroundActivity: {