Skip to content
TypeScript

feat(server,web): choose where new worktrees are created (#16231)

Julius Marminge102494157506
diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts
index ef66b6d5419..b5e80107de7 100644
--- a/apps/server/src/environment/ServerEnvironment.ts
+++ b/apps/server/src/environment/ServerEnvironment.ts
@@ -229,6 +229,7 @@ export const make = Effect.gen(function* () {
threadAutoSettlement: true,
storageCleanup: true,
projectWorktreeCleanup: true,
+ worktreesDirectory: true,
threadRestartContinuation: true,
projectSettingsOverrides: true,
threadSnooze: true,
diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts
index 04433f26e53..3d5cdb5b8b2 100644
--- a/apps/server/src/git/GitManager.ts
+++ b/apps/server/src/git/GitManager.ts
@@ -733,6 +733,11 @@ export const make = Effect.gen(function* () {
);
return resolveProjectSettings(settings, projectId).settings;
});
+ // Best effort: a settings read failure falls back to the default location.
+ const readWorktreesDirectory = serverSettingsService.getSettings.pipe(
+ Effect.map((settings) => settings.worktreesDirectory),
+ Effect.orElseSucceed(() => ""),
+ );
const createWorktree: GitManager["Service"]["createWorktree"] = Effect.fn(
"GitManager.createWorktree",
)(function* (input, options) {
@@ -743,7 +748,8 @@ export const make = Effect.gen(function* () {
Effect.map((settings) => settings.worktreeSubmodules),
Effect.orElseSucceed(() => null),
);
- return yield* gitCore.createWorktree(input, { ...options, submodules });
+ const worktreesDirectory = yield* readWorktreesDirectory;
+ return yield* gitCore.createWorktree(input, { worktreesDirectory, ...options, submodules });
});
const readRepositoryInstructions = (cwd: string, fileName: string) =>
@@ -2604,6 +2610,7 @@ export const make = Effect.gen(function* () {
path: null,
},
{
+ worktreesDirectory: yield* readWorktreesDirectory,
// Best effort: a settings read failure falls back to the checkout's t3.json.
submodules: yield* projectSettingsFor(input).pipe(
Effect.map((settings) => settings.worktreeSubmodules),
diff --git a/apps/server/src/review/ReviewService.test.ts b/apps/server/src/review/ReviewService.test.ts
index 736a34d2c44..eec36e1fd7f 100644
--- a/apps/server/src/review/ReviewService.test.ts
+++ b/apps/server/src/review/ReviewService.test.ts
@@ -6,6 +6,7 @@ import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as ServerConfig from "../config.ts";
+import * as ServerSettings from "../serverSettings.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as ReviewService from "./ReviewService.ts";
@@ -14,6 +15,8 @@ function makeLayer(input: {
readonly workspaceRoot: string;
readonly baseDir: string;
readonly detectCalls?: Array<{ readonly cwd: string }>;
+ readonly worktreesDirectory?: string;
+ readonly previousWorktreesDirectories?: ReadonlyArray<string>;
}) {
return ReviewService.layer.pipe(
Layer.provide(
@@ -28,6 +31,12 @@ function makeLayer(input: {
}),
),
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
+ Layer.provide(
+ ServerSettings.ServerSettingsService.layerTest({
+ worktreesDirectory: input.worktreesDirectory ?? "",
+ previousWorktreesDirectories: [...(input.previousWorktreesDirectories ?? [])],
+ }),
+ ),
Layer.provide(ServerConfig.layerTest(input.workspaceRoot, input.baseDir)),
Layer.provideMerge(NodeServices.layer),
);
@@ -90,6 +99,41 @@ describe("ReviewService", () => {
}).pipe(Effect.provide(NodeServices.layer)),
);
+ it.effect("allows previous custom worktree locations but never a filesystem root", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const workspaceRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-workspace-" });
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-base-" });
+ const previous = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-old-worktrees-" });
+ const outsideRoot = yield* fs.makeTempDirectoryScoped({ prefix: "t3-review-outside-" });
+
+ const result = yield* Effect.gen(function* () {
+ const review = yield* ReviewService.ReviewService;
+ return yield* review.getDiffPreview({ cwd: previous });
+ }).pipe(
+ Effect.provide(
+ makeLayer({
+ workspaceRoot,
+ baseDir,
+ worktreesDirectory: "/",
+ previousWorktreesDirectories: [previous],
+ }),
+ ),
+ );
+ assert.strictEqual(result.cwd, previous);
+
+ const rootLink = `${baseDir}/root-link`;
+ yield* fs.symlink("/", rootLink);
+ for (const worktreesDirectory of ["/", rootLink]) {
+ const error = yield* Effect.gen(function* () {
+ const review = yield* ReviewService.ReviewService;
+ return yield* review.getDiffPreview({ cwd: outsideRoot }).pipe(Effect.flip);
+ }).pipe(Effect.provide(makeLayer({ workspaceRoot, baseDir, worktreesDirectory })));
+ assert.strictEqual(error._tag, "VcsRepositoryDetectionError");
+ }
+ }).pipe(Effect.provide(NodeServices.layer)),
+ );
+
it.effect("allows diff preview cwd inside the configured workspace root", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/review/ReviewService.ts b/apps/server/src/review/ReviewService.ts
index dc13e5650c3..7aee5847001 100644
--- a/apps/server/src/review/ReviewService.ts
+++ b/apps/server/src/review/ReviewService.ts
@@ -18,6 +18,8 @@ import {
import * as ServerConfig from "../config.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
+import * as ServerSettings from "../serverSettings.ts";
+import { isFilesystemRoot, managedWorktreesDirectories } from "../worktreesDirectory.ts";
export class ReviewService extends Context.Service<
ReviewService,
@@ -38,6 +40,7 @@ export const make = Effect.gen(function* () {
const path = yield* Path.Path;
const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
const git = yield* GitVcsDriver.GitVcsDriver;
+ const settings = yield* ServerSettings.ServerSettingsService;
const canonicalizePath = (value: string) => {
const resolvedPath = path.resolve(value);
@@ -67,13 +70,28 @@ export const make = Effect.gen(function* () {
operation: "ReviewService.getDiffPreview" | "ReviewService.getDiffFileContents",
cwd: string,
) {
- const [candidate, workspaceRoot, worktreesRoot] = yield* Effect.all([
+ const worktreesDirectories = yield* settings.getSettings.pipe(
+ Effect.orElseSucceed(() => ({ worktreesDirectory: "", previousWorktreesDirectories: [] })),
+ );
+ const [candidate, workspaceRoot, worktreesRoots] = yield* Effect.all([
canonicalizePath(cwd),
canonicalizePath(config.cwd),
- canonicalizePath(config.worktreesDir),
+ // A managed root that cannot be resolved, or resolves to a filesystem
+ // root through a symlink, is skipped rather than failing every review.
+ Effect.forEach(
+ managedWorktreesDirectories(worktreesDirectories, config.worktreesDir, path),
+ (directory) => canonicalizePath(directory).pipe(Effect.orElseSucceed(() => null)),
+ ).pipe(
+ Effect.map((roots) =>
+ roots.filter((root): root is string => root !== null && !isFilesystemRoot(root, path)),
+ ),
+ ),
]);
- if (isWithinRoot(candidate, workspaceRoot) || isWithinRoot(candidate, worktreesRoot)) {
+ if (
+ isWithinRoot(candidate, workspaceRoot) ||
+ worktreesRoots.some((root) => isWithinRoot(candidate, root))
+ ) {
return;
}
diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts
index 6b68d986dab..f9ff03a9ef7 100644
--- a/apps/server/src/storageCleanup.ts
+++ b/apps/server/src/storageCleanup.ts
@@ -35,6 +35,7 @@ import { threadHasQueuedTurnStart } from "./orchestration-v2/ThreadSettlementSer
import { forkParked } from "./serverActivation.ts";
import * as Settings from "./serverSettings.ts";
import * as TerminalManager from "./terminal/Manager.ts";
+import { isFilesystemRoot, managedWorktreesDirectories } from "./worktreesDirectory.ts";
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
import { withWorkspaceLease } from "./workspace/workspaceLease.ts";
@@ -176,7 +177,20 @@ export const make = Effect.gen(function* () {
now: number,
) {
if (!anyWorktreePolicy(serverSettings, worktreeCleanupEnabled)) return;
- if (!(yield* fs.exists(config.worktreesDir))) return;
+ const roots: Array<string> = [];
+ for (const directory of managedWorktreesDirectories(
+ serverSettings,
+ config.worktreesDir,
+ path,
+ )) {
+ // An unmounted drive only skips its own worktrees.
+ const root = yield* fs.exists(directory).pipe(
+ Effect.flatMap((exists) => (exists ? fs.realPath(directory) : Effect.succeed(null))),
+ Effect.orElseSucceed(() => null),
+ );
+ if (root !== null && !isFilesystemRoot(root, path)) roots.push(root);
+ }
+ if (roots.length === 0) return;
const hasDeleteRule = anyWorktreePolicy(serverSettings, (rules) => rules.worktreeOnDelete);
const deletedRows = hasDeleteRule
? yield* sql<{ payload_json: string; workspaceRoot: string }>`
@@ -197,7 +211,6 @@ export const make = Effect.gen(function* () {
resolveWorktreeCleanup(serverSettings, thread.projectId).worktreeOnDelete,
);
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),
@@ -222,8 +235,13 @@ export const make = Effect.gen(function* () {
)
continue;
yield* Effect.gen(function* () {
- if (!inside(root, worktreePath) || !(yield* fs.exists(worktreePath))) return;
- if ((yield* fs.realPath(worktreePath)) !== worktreePath) return;
+ if (!(yield* fs.exists(worktreePath))) return;
+ // Roots are canonical, so compare canonical paths. A symlinked parent
+ // (a linked drive) is fine; a symlinked worktree directory is not.
+ const realPath = yield* fs.realPath(worktreePath);
+ const realParent = yield* fs.realPath(path.dirname(worktreePath));
+ if (realPath !== path.join(realParent, path.basename(worktreePath))) return;
+ if (!roots.some((root) => inside(root, realPath))) 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;
diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts
index 87ec4aaa662..45ebf0c143c 100644
--- a/apps/server/src/vcs/GitVcsDriver.ts
+++ b/apps/server/src/vcs/GitVcsDriver.ts
@@ -156,6 +156,8 @@ export interface CreateWorktreeOptions {
* own t3.json.
*/
readonly submodules?: WorktreeSubmodules | null;
+ /** The `worktreesDirectory` setting, used when the input has no explicit path. */
+ readonly worktreesDirectory?: string;
}
export interface GitCommitProgress {
diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts
index cf5bd098d94..3763c03469d 100644
--- a/apps/server/src/vcs/GitVcsDriverCore.test.ts
+++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts
@@ -2981,6 +2981,45 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
+ it.effect("creates worktrees under the configured worktrees directory", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const pathService = yield* Path.Path;
+ const cwd = yield* makeTmpDir();
+ const { initialBranch } = yield* initRepoWithCommit(cwd);
+ const worktreesDirectory = yield* makeTmpDir("custom-worktrees-");
+ const driver = yield* GitVcsDriver.GitVcsDriver;
+
+ const created = yield* driver.createWorktree(
+ { cwd, path: null, refName: initialBranch, newRefName: "feature/custom-dir" },
+ { worktreesDirectory },
+ );
+ const expected = pathService.join(
+ worktreesDirectory,
+ pathService.basename(cwd),
+ "feature-custom-dir",
+ );
+ assert.equal(created.worktree.path, expected);
+ assert.equal(yield* fileSystem.exists(expected), true);
+
+ const error = yield* driver
+ .createWorktree(
+ { cwd, path: null, refName: initialBranch, newRefName: "feature/relative-dir" },
+ { worktreesDirectory: "relative/worktrees" },
+ )
+ .pipe(Effect.flip);
+ assert.match(error.detail, /must be an absolute folder on this machine/);
+
+ const rootError = yield* driver
+ .createWorktree(
+ { cwd, path: null, refName: initialBranch, newRefName: "feature/root-dir" },
+ { worktreesDirectory: "/" },
+ )
+ .pipe(Effect.flip);
+ assert.match(rootError.detail, /not a drive root/);
+ }),
+ );
+
it.effect("resolves the submodule mode from the option, then t3.json", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts
index 70a1ef1c036..9ec0d4e7753 100644
--- a/apps/server/src/vcs/GitVcsDriverCore.ts
+++ b/apps/server/src/vcs/GitVcsDriverCore.ts
@@ -36,6 +36,7 @@ import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
import { resolveProjectFileBackedSetting } from "@t3tools/shared/projectSettings";
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
+import { resolveWorktreesDirectory } from "../worktreesDirectory.ts";
import {
parseRemoteNames,
parseRemoteNamesInGitOrder,
@@ -3345,7 +3346,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
const targetBranch = input.newRefName ?? input.refName;
const sanitizedBranch = targetBranch.replace(/\//g, "-");
const repoName = path.basename(input.cwd);
- const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch);
+ let worktreePath = input.path;
+ if (worktreePath == null) {
+ const parentDir = resolveWorktreesDirectory(
+ options?.worktreesDirectory ?? "",
+ worktreesDir,
+ path,
+ );
+ if (parentDir === null) {
+ return yield* new GitCommandError({
+ operation: "GitVcsDriver.createWorktree",
+ command: "git worktree add",
+ cwd: input.cwd,
+ detail: `The worktree location "${options?.worktreesDirectory}" must be an absolute folder on this machine, not a drive root. Change it in Settings → Storage.`,
+ });
+ }
+ worktreePath = path.join(parentDir, repoName, sanitizedBranch);
+ }
const args = input.newRefName
? ["worktree", "add", "-b", input.newRefName, worktreePath, input.refName]
: ["worktree", "add", worktreePath, input.refName];
diff --git a/apps/server/src/worktreesDirectory.ts b/apps/server/src/worktreesDirectory.ts
new file mode 100644
index 00000000000..5d465239374
--- /dev/null
+++ b/apps/server/src/worktreesDirectory.ts
@@ -0,0 +1,44 @@
+import type * as Path from "effect/Path";
+
+import { expandHomePathWith } from "./pathExpansion.ts";
+
+/**
+ * Directory new worktrees are created under: the `worktreesDirectory`
+ * setting, or `defaultDir` (`<T3 home>/worktrees`) when it is empty. Null when
+ * the setting is not an absolute path on this machine, such as `D:\worktrees`
+ * configured for a Windows server and synced to a Linux one, or when it is a
+ * filesystem root, which would make every path on that drive look managed.
+ */
+export function resolveWorktreesDirectory(
+ setting: string,
+ defaultDir: string,
+ path: Path.Path,
+): string | null {
+ if (setting === "") return defaultDir;
+ const expanded = expandHomePathWith(setting, path);
+ if (!path.isAbsolute(expanded)) return null;
+ const resolved = path.resolve(expanded);
+ return isFilesystemRoot(resolved, path) ? null : resolved;
+}
+
+/** Callers re-check after resolving symlinks: a link can point at a root. */
+export function isFilesystemRoot(directory: string, path: Path.Path): boolean {
+ return path.dirname(directory) === directory;
+}
+
+/** Every directory that holds T3-managed worktrees on this machine. */
+export function managedWorktreesDirectories(
+ settings: {
+ readonly worktreesDirectory: string;
+ readonly previousWorktreesDirectories: ReadonlyArray<string>;
+ },
+ defaultDir: string,
+ path: Path.Path,
+): ReadonlyArray<string> {
+ const directories = new Set([defaultDir]);
+ for (const setting of [settings.worktreesDirectory, ...settings.previousWorktreesDirectories]) {
+ const directory = resolveWorktreesDirectory(setting, defaultDir, path);
+ if (directory !== null) directories.add(directory);
+ }
+ return [...directories];
+}
diff --git a/apps/web/src/components/settings/StorageSettings.tsx b/apps/web/src/components/settings/StorageSettings.tsx
index 360979eead7..0106acc7ceb 100644
--- a/apps/web/src/components/settings/StorageSettings.tsx
+++ b/apps/web/src/components/settings/StorageSettings.tsx
@@ -1,7 +1,8 @@
import type { StorageCleanupSettings, WorktreeCleanupRules } from "@t3tools/contracts";
import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
-import { useState } from "react";
+import { useRef, useState } from "react";
+import { Input } from "../ui/input";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Switch } from "../ui/switch";
import {
@@ -11,16 +12,77 @@ import {
NumberFieldIncrement,
NumberFieldInput,
} from "../ui/number-field";
-import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
+import {
+ SettingResetButton,
+ SettingsPageContainer,
+ SettingsRow,
+ SettingsSection,
+} from "./settingsLayout";
import { SettingsScopeNotice } from "./SettingsScopeNotice";
import type { ScopedSettingsTarget } from "./scopedSettings";
import { useSettingsScope } from "./SettingsScopeContext";
+import { searchableSetting } from "./settingsSearch";
import {
useClearScopedSettings,
useScopedSettings,
+ useScopedSettingsMixed,
useUpdateScopedSettings,
} from "./useScopedSettings";
+function WorktreesDirectoryRow() {
+ const { connectedEnvironments, targets } = useSettingsScope();
+ const settings = useScopedSettings();
+ const updateSettings = useUpdateScopedSettings();
+ const mixed = useScopedSettingsMixed(["worktreesDirectory"]);
+ const edited = useRef(false);
+ if (
+ connectedEnvironments.some(
+ (environment) =>
+ environment.serverConfig?.environment.capabilities.worktreesDirectory !== true,
+ )
+ )
+ return null;
+ const scopeKey = targets.map((target) => target.environmentId).join(",");
+
+ return (
+ <SettingsRow
+ {...searchableSetting("storage-worktrees-location")}
+ description={
+ "Folder where new worktrees are created, on any drive, such as D:\\worktrees or ~/worktrees. Existing worktrees stay where they are. Leave empty to use the T3 home folder."
+ }
+ serverScoped
+ settingKeys={["worktreesDirectory"]}
+ resetAction={
+ mixed || settings.worktreesDirectory !== "" ? (
+ <SettingResetButton
+ label="worktree location"
+ onClick={() => updateSettings({ worktreesDirectory: "" })}
+ />
+ ) : null
+ }
+ control={
+ <Input
+ key={`${scopeKey}:${mixed}:${settings.worktreesDirectory}`}
+ aria-label="Worktree location"
+ autoCapitalize="none"
+ spellCheck={false}
+ placeholder={mixed ? "Mixed" : "Default"}
+ defaultValue={mixed ? "" : settings.worktreesDirectory}
+ onChange={() => {
+ edited.current = true;
+ }}
+ onBlur={(event) => {
+ const value = event.target.value.trim();
+ if (edited.current && (mixed || value !== settings.worktreesDirectory))
+ updateSettings({ worktreesDirectory: value });
+ edited.current = false;
+ }}
+ />
+ }
+ />
+ );
+}
+
function RetentionControl({
label,
value,
@@ -152,6 +214,7 @@ export function StorageSettingsPanel() {
return (
<SettingsPageContainer>
<SettingsSection id="storage-worktrees" title="Worktrees">
+ {!isProjectScope && <WorktreesDirectoryRow />}
{isProjectScope && (
<SettingsRow
title="Automatic worktree cleanup"
diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts
index be1eb15a6c1..4797c9b64dd 100644
--- a/apps/web/src/components/settings/settingsSearch.ts
+++ b/apps/web/src/components/settings/settingsSearch.ts
@@ -143,6 +143,13 @@ export const SETTINGS_SEARCH_ITEMS = [
"disk storage delete deleted archived threads old inactive merged unchanged worktrees retention days project inherit off custom",
],
},
+ {
+ id: "storage-worktrees-location",
+ title: "Worktree location",
+ to: "/settings/storage",
+ scope: "environment-defaults",
+ searchTerms: ["worktree location folder directory path drive external disk"],
+ },
{
id: "storage-artifacts",
title: "Artifacts and logs",
diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md
index 20c41f0ae9b..e1e8aaaf2fb 100644
--- a/docs/user/project-settings.md
+++ b/docs/user/project-settings.md
@@ -123,6 +123,13 @@ itself, or **Skip** to leave them for a setup script. It resolves in the same or
workspace default: a `"worktreeSubmodules"` value in the `t3.json` of the branch being checked out
applies when the project and environment are both on **Inherit**.
+## Worktree location
+
+New worktrees go in the `worktrees` folder of the T3 home directory. To put them somewhere else,
+such as another drive, set **Settings → Storage → Worktree location** to an absolute path like
+`D:\worktrees` or `~/worktrees`. The setting is per machine. Existing worktrees stay where they
+are, and cleanup covers both the default folder and the custom one.
+
## Storage cleanup
Open **Settings → Storage** to enable automatic cleanup on one machine or all connected
diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts
index 0fdbbe6d9fd..5444a2645a4 100644
--- a/packages/contracts/src/environment.ts
+++ b/packages/contracts/src/environment.ts
@@ -126,6 +126,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
threadAutoSettlement: Schema.optionalKey(Schema.Boolean),
storageCleanup: Schema.optionalKey(Schema.Boolean),
projectWorktreeCleanup: Schema.optionalKey(Schema.Boolean),
+ /** Server honors the `worktreesDirectory` setting. */
+ worktreesDirectory: 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. */
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index f4d1c771971..7e73079a58d 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -1217,6 +1217,18 @@ export const ServerSettings = Schema.Struct({
storageCleanup: StorageCleanupSettings.pipe(
Schema.withDecodingDefault(Effect.succeed(Schema.decodeSync(StorageCleanupSettings)({}))),
),
+ /**
+ * Absolute directory new worktrees are created under, e.g. `D:\worktrees`
+ * or `~/worktrees`. Empty uses `<T3 home>/worktrees`.
+ */
+ worktreesDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
+ /**
+ * Custom locations used before the current one. Server-maintained so
+ * worktrees left there stay eligible for cleanup and review diffs.
+ */
+ previousWorktreesDirectories: Schema.Array(TrimmedString).pipe(
+ Schema.withDecodingDefault(Effect.succeed([])),
+ ),
responseStreamingMode: ResponseStreamingMode.pipe(
Schema.withDecodingDefault(Effect.succeed("paragraph" as const)),
),
@@ -1620,6 +1632,7 @@ export const ServerSettingsPatch = Schema.Struct({
logsAfterDays: Schema.optionalKey(StorageRetentionDays),
}),
),
+ worktreesDirectory: Schema.optionalKey(TrimmedString),
// Server settings
responseStreamingMode: Schema.optionalKey(ResponseStreamingMode),
enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
diff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.ts
index 093e79547dd..fb25119cadc 100644
--- a/packages/shared/src/serverSettings.test.ts
+++ b/packages/shared/src/serverSettings.test.ts
@@ -795,3 +795,16 @@ describe("serverSettings helpers", () => {
expect(resolved.pauseWhenOnBattery).toBe(false);
});
});
+
+describe("worktreesDirectory", () => {
+ it("remembers previous custom locations so their worktrees stay managed", () => {
+ const first = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { worktreesDirectory: "/a" });
+ expect(first.previousWorktreesDirectories).toEqual([]);
+ const second = applyServerSettingsPatch(first, { worktreesDirectory: "/b" });
+ expect(second.previousWorktreesDirectories).toEqual(["/a"]);
+ const reset = applyServerSettingsPatch(second, { worktreesDirectory: "" });
+ expect(reset.previousWorktreesDirectories).toEqual(["/a", "/b"]);
+ const back = applyServerSettingsPatch(reset, { worktreesDirectory: "/a" });
+ expect(back.previousWorktreesDirectories).toEqual(["/b"]);
+ });
+});
diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts
index a3e0ffb23df..aabc3612c98 100644
--- a/packages/shared/src/serverSettings.ts
+++ b/packages/shared/src/serverSettings.ts
@@ -364,6 +364,20 @@ export function applyServerSettingsPatch(
...(patch.providerInstances !== undefined
? { providerInstances: patch.providerInstances }
: {}),
+ ...(patch.worktreesDirectory !== undefined &&
+ patch.worktreesDirectory !== current.worktreesDirectory
+ ? {
+ previousWorktreesDirectories: [
+ ...current.previousWorktreesDirectories.filter(
+ (directory) => directory !== patch.worktreesDirectory,
+ ),
+ ...(current.worktreesDirectory !== "" &&
+ !current.previousWorktreesDirectories.includes(current.worktreesDirectory)
+ ? [current.worktreesDirectory]
+ : []),
+ ],
+ }
+ : {}),
...(projectSettingsOverridesPatch !== undefined
? {
projectSettingsOverrides: Object.fromEntries(