Skip to content

Commit bc540a1

Browse files
feat(server,web): choose where new worktrees are created
Adds a per-machine Worktree location setting under Settings → Storage. Any absolute path works, including other drives (D:\worktrees, ~/worktrees). Cleanup and review path checks cover both the default and custom folders. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 9e5229b commit bc540a1

14 files changed

Lines changed: 199 additions & 10 deletions

File tree

‎apps/server/src/environment/ServerEnvironment.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,7 @@ export const make = Effect.gen(function* () {
229229
threadAutoSettlement: true,
230230
storageCleanup: true,
231231
projectWorktreeCleanup: true,
232+
worktreesDirectory: true,
232233
threadRestartContinuation: true,
233234
projectSettingsOverrides: true,
234235
threadSnooze: true,

‎apps/server/src/git/GitManager.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -733,6 +733,11 @@ export const make = Effect.gen(function* () {
733733
);
734734
return resolveProjectSettings(settings, projectId).settings;
735735
});
736+
// Best effort: a settings read failure falls back to the default location.
737+
const readWorktreesDirectory = serverSettingsService.getSettings.pipe(
738+
Effect.map((settings) => settings.worktreesDirectory),
739+
Effect.orElseSucceed(() => ""),
740+
);
736741
const createWorktree: GitManager["Service"]["createWorktree"] = Effect.fn(
737742
"GitManager.createWorktree",
738743
)(function* (input, options) {
@@ -743,7 +748,8 @@ export const make = Effect.gen(function* () {
743748
Effect.map((settings) => settings.worktreeSubmodules),
744749
Effect.orElseSucceed(() => null),
745750
);
746-
return yield* gitCore.createWorktree(input, { ...options, submodules });
751+
const worktreesDirectory = yield* readWorktreesDirectory;
752+
return yield* gitCore.createWorktree(input, { worktreesDirectory, ...options, submodules });
747753
});
748754

749755
const readRepositoryInstructions = (cwd: string, fileName: string) =>
@@ -2604,6 +2610,7 @@ export const make = Effect.gen(function* () {
26042610
path: null,
26052611
},
26062612
{
2613+
worktreesDirectory: yield* readWorktreesDirectory,
26072614
// Best effort: a settings read failure falls back to the checkout's t3.json.
26082615
submodules: yield* projectSettingsFor(input).pipe(
26092616
Effect.map((settings) => settings.worktreeSubmodules),

‎apps/server/src/review/ReviewService.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import * as Layer from "effect/Layer";
66
import * as PlatformError from "effect/PlatformError";
77

88
import * as ServerConfig from "../config.ts";
9+
import * as ServerSettings from "../serverSettings.ts";
910
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
1011
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
1112
import * as ReviewService from "./ReviewService.ts";
@@ -28,6 +29,7 @@ function makeLayer(input: {
2829
}),
2930
),
3031
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
32+
Layer.provide(ServerSettings.ServerSettingsService.layerTest()),
3133
Layer.provide(ServerConfig.layerTest(input.workspaceRoot, input.baseDir)),
3234
Layer.provideMerge(NodeServices.layer),
3335
);

‎apps/server/src/review/ReviewService.ts‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ import {
1818
import * as ServerConfig from "../config.ts";
1919
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
2020
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
21+
import * as ServerSettings from "../serverSettings.ts";
22+
import { managedWorktreesDirectories } from "../worktreesDirectory.ts";
2123

2224
export class ReviewService extends Context.Service<
2325
ReviewService,
@@ -38,6 +40,7 @@ export const make = Effect.gen(function* () {
3840
const path = yield* Path.Path;
3941
const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
4042
const git = yield* GitVcsDriver.GitVcsDriver;
43+
const settings = yield* ServerSettings.ServerSettingsService;
4144

4245
const canonicalizePath = (value: string) => {
4346
const resolvedPath = path.resolve(value);
@@ -67,13 +70,23 @@ export const make = Effect.gen(function* () {
6770
operation: "ReviewService.getDiffPreview" | "ReviewService.getDiffFileContents",
6871
cwd: string,
6972
) {
70-
const [candidate, workspaceRoot, worktreesRoot] = yield* Effect.all([
73+
const worktreesDirectory = yield* settings.getSettings.pipe(
74+
Effect.map((current) => current.worktreesDirectory),
75+
Effect.orElseSucceed(() => ""),
76+
);
77+
const [candidate, workspaceRoot, worktreesRoots] = yield* Effect.all([
7178
canonicalizePath(cwd),
7279
canonicalizePath(config.cwd),
73-
canonicalizePath(config.worktreesDir),
80+
Effect.forEach(
81+
managedWorktreesDirectories(worktreesDirectory, config.worktreesDir, path),
82+
canonicalizePath,
83+
),
7484
]);
7585

76-
if (isWithinRoot(candidate, workspaceRoot) || isWithinRoot(candidate, worktreesRoot)) {
86+
if (
87+
isWithinRoot(candidate, workspaceRoot) ||
88+
worktreesRoots.some((root) => isWithinRoot(candidate, root))
89+
) {
7790
return;
7891
}
7992

‎apps/server/src/storageCleanup.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import { threadHasQueuedTurnStart } from "./orchestration-v2/ThreadSettlementSer
3535
import { forkParked } from "./serverActivation.ts";
3636
import * as Settings from "./serverSettings.ts";
3737
import * as TerminalManager from "./terminal/Manager.ts";
38+
import { managedWorktreesDirectories } from "./worktreesDirectory.ts";
3839
import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
3940
import { withWorkspaceLease } from "./workspace/workspaceLease.ts";
4041

@@ -176,7 +177,15 @@ export const make = Effect.gen(function* () {
176177
now: number,
177178
) {
178179
if (!anyWorktreePolicy(serverSettings, worktreeCleanupEnabled)) return;
179-
if (!(yield* fs.exists(config.worktreesDir))) return;
180+
const roots: Array<string> = [];
181+
for (const directory of managedWorktreesDirectories(
182+
serverSettings.worktreesDirectory,
183+
config.worktreesDir,
184+
path,
185+
)) {
186+
if (yield* fs.exists(directory)) roots.push(yield* fs.realPath(directory));
187+
}
188+
if (roots.length === 0) return;
180189
const hasDeleteRule = anyWorktreePolicy(serverSettings, (rules) => rules.worktreeOnDelete);
181190
const deletedRows = hasDeleteRule
182191
? yield* sql<{ payload_json: string; workspaceRoot: string }>`
@@ -197,7 +206,6 @@ export const make = Effect.gen(function* () {
197206
resolveWorktreeCleanup(serverSettings, thread.projectId).worktreeOnDelete,
198207
);
199208
const snapshot = yield* readThreads();
200-
const root = yield* fs.realPath(config.worktreesDir);
201209
const refreshedDefaultRefs = new Map<string, Set<string>>();
202210
const groups = Map.groupBy(
203211
snapshot.threads.filter((thread) => thread.worktreePath !== null),
@@ -222,7 +230,8 @@ export const make = Effect.gen(function* () {
222230
)
223231
continue;
224232
yield* Effect.gen(function* () {
225-
if (!inside(root, worktreePath) || !(yield* fs.exists(worktreePath))) return;
233+
if (!roots.some((root) => inside(root, worktreePath)) || !(yield* fs.exists(worktreePath)))
234+
return;
226235
if ((yield* fs.realPath(worktreePath)) !== worktreePath) return;
227236
if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects])) return;
228237
// A linked worktree has a .git file. Never remove a main checkout.

‎apps/server/src/vcs/GitVcsDriver.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,8 @@ export interface CreateWorktreeOptions {
156156
* own t3.json.
157157
*/
158158
readonly submodules?: WorktreeSubmodules | null;
159+
/** The `worktreesDirectory` setting, used when the input has no explicit path. */
160+
readonly worktreesDirectory?: string;
159161
}
160162

161163
export interface GitCommitProgress {

‎apps/server/src/vcs/GitVcsDriverCore.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2981,6 +2981,37 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
29812981
}),
29822982
);
29832983

2984+
it.effect("creates worktrees under the configured worktrees directory", () =>
2985+
Effect.gen(function* () {
2986+
const fileSystem = yield* FileSystem.FileSystem;
2987+
const pathService = yield* Path.Path;
2988+
const cwd = yield* makeTmpDir();
2989+
const { initialBranch } = yield* initRepoWithCommit(cwd);
2990+
const worktreesDirectory = yield* makeTmpDir("custom-worktrees-");
2991+
const driver = yield* GitVcsDriver.GitVcsDriver;
2992+
2993+
const created = yield* driver.createWorktree(
2994+
{ cwd, path: null, refName: initialBranch, newRefName: "feature/custom-dir" },
2995+
{ worktreesDirectory },
2996+
);
2997+
const expected = pathService.join(
2998+
worktreesDirectory,
2999+
pathService.basename(cwd),
3000+
"feature-custom-dir",
3001+
);
3002+
assert.equal(created.worktree.path, expected);
3003+
assert.equal(yield* fileSystem.exists(expected), true);
3004+
3005+
const error = yield* driver
3006+
.createWorktree(
3007+
{ cwd, path: null, refName: initialBranch, newRefName: "feature/relative-dir" },
3008+
{ worktreesDirectory: "relative/worktrees" },
3009+
)
3010+
.pipe(Effect.flip);
3011+
assert.match(error.detail, /not an absolute path on this machine/);
3012+
}),
3013+
);
3014+
29843015
it.effect("resolves the submodule mode from the option, then t3.json", () =>
29853016
Effect.gen(function* () {
29863017
const fileSystem = yield* FileSystem.FileSystem;

‎apps/server/src/vcs/GitVcsDriverCore.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
3636
import { resolveProjectFileBackedSetting } from "@t3tools/shared/projectSettings";
3737
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
3838
import * as GitVcsDriver from "./GitVcsDriver.ts";
39+
import { resolveWorktreesDirectory } from "../worktreesDirectory.ts";
3940
import {
4041
parseRemoteNames,
4142
parseRemoteNamesInGitOrder,
@@ -3345,7 +3346,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
33453346
const targetBranch = input.newRefName ?? input.refName;
33463347
const sanitizedBranch = targetBranch.replace(/\//g, "-");
33473348
const repoName = path.basename(input.cwd);
3348-
const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch);
3349+
let worktreePath = input.path;
3350+
if (worktreePath == null) {
3351+
const parentDir = resolveWorktreesDirectory(
3352+
options?.worktreesDirectory ?? "",
3353+
worktreesDir,
3354+
path,
3355+
);
3356+
if (parentDir === null) {
3357+
return yield* new GitCommandError({
3358+
operation: "GitVcsDriver.createWorktree",
3359+
command: "git worktree add",
3360+
cwd: input.cwd,
3361+
detail: `The worktree location "${options?.worktreesDirectory}" is not an absolute path on this machine. Change it in Settings → Storage.`,
3362+
});
3363+
}
3364+
worktreePath = path.join(parentDir, repoName, sanitizedBranch);
3365+
}
33493366
const args = input.newRefName
33503367
? ["worktree", "add", "-b", input.newRefName, worktreePath, input.refName]
33513368
: ["worktree", "add", worktreePath, input.refName];
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import type * as Path from "effect/Path";
2+
3+
import { expandHomePathWith } from "./pathExpansion.ts";
4+
5+
/**
6+
* Directory new worktrees are created under: the `worktreesDirectory`
7+
* setting, or `defaultDir` (`<T3 home>/worktrees`) when it is empty. Null when
8+
* the setting is not an absolute path on this machine, such as `D:\worktrees`
9+
* configured for a Windows server and synced to a Linux one.
10+
*/
11+
export function resolveWorktreesDirectory(
12+
setting: string,
13+
defaultDir: string,
14+
path: Path.Path,
15+
): string | null {
16+
if (setting === "") return defaultDir;
17+
const expanded = expandHomePathWith(setting, path);
18+
return path.isAbsolute(expanded) ? path.resolve(expanded) : null;
19+
}
20+
21+
/** Every directory that holds T3-managed worktrees on this machine. */
22+
export function managedWorktreesDirectories(
23+
setting: string,
24+
defaultDir: string,
25+
path: Path.Path,
26+
): ReadonlyArray<string> {
27+
const custom = resolveWorktreesDirectory(setting, defaultDir, path);
28+
return custom === null || custom === defaultDir ? [defaultDir] : [defaultDir, custom];
29+
}

‎apps/web/src/components/settings/StorageSettings.tsx‎

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import type { StorageCleanupSettings, WorktreeCleanupRules } from "@t3tools/contracts";
22
import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
3-
import { useState } from "react";
3+
import { useRef, useState } from "react";
44

5+
import { Input } from "../ui/input";
56
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
67
import { Switch } from "../ui/switch";
78
import {
@@ -11,16 +12,76 @@ import {
1112
NumberFieldIncrement,
1213
NumberFieldInput,
1314
} from "../ui/number-field";
14-
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
15+
import {
16+
SettingResetButton,
17+
SettingsPageContainer,
18+
SettingsRow,
19+
SettingsSection,
20+
} from "./settingsLayout";
1521
import { SettingsScopeNotice } from "./SettingsScopeNotice";
1622
import type { ScopedSettingsTarget } from "./scopedSettings";
1723
import { useSettingsScope } from "./SettingsScopeContext";
1824
import {
1925
useClearScopedSettings,
2026
useScopedSettings,
27+
useScopedSettingsMixed,
2128
useUpdateScopedSettings,
2229
} from "./useScopedSettings";
2330

31+
function WorktreesDirectoryRow() {
32+
const { connectedEnvironments, targets } = useSettingsScope();
33+
const settings = useScopedSettings();
34+
const updateSettings = useUpdateScopedSettings();
35+
const mixed = useScopedSettingsMixed(["worktreesDirectory"]);
36+
const edited = useRef(false);
37+
if (
38+
connectedEnvironments.some(
39+
(environment) =>
40+
environment.serverConfig?.environment.capabilities.worktreesDirectory !== true,
41+
)
42+
)
43+
return null;
44+
const scopeKey = targets.map((target) => target.environmentId).join(",");
45+
46+
return (
47+
<SettingsRow
48+
title="Worktree location"
49+
description={
50+
"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."
51+
}
52+
serverScoped
53+
settingKeys={["worktreesDirectory"]}
54+
resetAction={
55+
mixed || settings.worktreesDirectory !== "" ? (
56+
<SettingResetButton
57+
label="worktree location"
58+
onClick={() => updateSettings({ worktreesDirectory: "" })}
59+
/>
60+
) : null
61+
}
62+
control={
63+
<Input
64+
key={`${scopeKey}:${mixed}:${settings.worktreesDirectory}`}
65+
aria-label="Worktree location"
66+
autoCapitalize="none"
67+
spellCheck={false}
68+
placeholder={mixed ? "Mixed" : "Default"}
69+
defaultValue={mixed ? "" : settings.worktreesDirectory}
70+
onChange={() => {
71+
edited.current = true;
72+
}}
73+
onBlur={(event) => {
74+
const value = event.target.value.trim();
75+
if (edited.current && (mixed || value !== settings.worktreesDirectory))
76+
updateSettings({ worktreesDirectory: value });
77+
edited.current = false;
78+
}}
79+
/>
80+
}
81+
/>
82+
);
83+
}
84+
2485
function RetentionControl({
2586
label,
2687
value,
@@ -152,6 +213,7 @@ export function StorageSettingsPanel() {
152213
return (
153214
<SettingsPageContainer>
154215
<SettingsSection id="storage-worktrees" title="Worktrees">
216+
{!isProjectScope && <WorktreesDirectoryRow />}
155217
{isProjectScope && (
156218
<SettingsRow
157219
title="Automatic worktree cleanup"

0 commit comments

Comments
 (0)