Skip to content

Commit 964a68e

Browse files
committed
fix(server): narrow worktree optimization and fetch fallback
1 parent c986ab9 commit 964a68e

6 files changed

Lines changed: 188 additions & 280 deletions

File tree

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

Lines changed: 77 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -1557,90 +1557,6 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
15571557
});
15581558

15591559
describe("worktree operations", () => {
1560-
for (const state of [
1561-
"new",
1562-
"new-missing",
1563-
"existing",
1564-
"existing-missing",
1565-
"concurrent",
1566-
] as const) {
1567-
it.effect(`cleans up only newly registered worktrees on interruption: ${state}`, () =>
1568-
Effect.gen(function* () {
1569-
const cwd = yield* makeTmpDir();
1570-
const { initialBranch } = yield* initRepoWithCommit(cwd);
1571-
const fs = yield* FileSystem.FileSystem;
1572-
const path = yield* Path.Path;
1573-
const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "interrupted");
1574-
const existing = state.startsWith("existing") || state === "concurrent";
1575-
if (state.startsWith("existing")) {
1576-
yield* git(cwd, ["worktree", "add", "-b", "feature/existing", worktreePath]);
1577-
if (state === "existing-missing") {
1578-
yield* fs.remove(worktreePath, { recursive: true });
1579-
}
1580-
}
1581-
const baseDriver = yield* GitVcsDriver.GitVcsDriver;
1582-
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
1583-
const commandFinished = yield* Deferred.make<void>();
1584-
const spawner = ChildProcessSpawner.make((command) =>
1585-
Effect.gen(function* () {
1586-
const isWorktreeAdd =
1587-
ChildProcess.isStandardCommand(command) &&
1588-
command.args.includes("worktree") &&
1589-
command.args.includes("add");
1590-
if (isWorktreeAdd && state === "concurrent") {
1591-
yield* git(cwd, ["worktree", "add", "-b", "feature/existing", worktreePath]).pipe(
1592-
Effect.provideService(GitVcsDriver.GitVcsDriver, baseDriver),
1593-
Effect.orDie,
1594-
);
1595-
yield* fs.writeFileString(
1596-
path.join(worktreePath, "uncommitted.txt"),
1597-
"keep these edits",
1598-
);
1599-
}
1600-
const handle = yield* delegate.spawn(command);
1601-
return isWorktreeAdd
1602-
? ChildProcessSpawner.makeHandle({
1603-
...handle,
1604-
exitCode: handle.exitCode.pipe(
1605-
Effect.andThen(Deferred.succeed(commandFinished, undefined)),
1606-
Effect.andThen(Effect.never),
1607-
),
1608-
})
1609-
: handle;
1610-
}),
1611-
);
1612-
const driver = yield* makeGitVcsDriverCore().pipe(
1613-
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
1614-
Effect.provide(ServerConfigLayer),
1615-
);
1616-
const creating = yield* driver
1617-
.createWorktree({
1618-
cwd,
1619-
path: worktreePath,
1620-
refName: initialBranch,
1621-
newRefName: "feature/interrupted",
1622-
})
1623-
.pipe(Effect.forkChild({ startImmediately: true }));
1624-
yield* Deferred.await(commandFinished);
1625-
if (state === "new-missing") {
1626-
yield* fs.remove(worktreePath, { recursive: true });
1627-
}
1628-
yield* Fiber.interrupt(creating);
1629-
1630-
assert.equal(yield* fs.exists(worktreePath), existing && !state.endsWith("missing"));
1631-
if (state === "concurrent") {
1632-
assert.equal(
1633-
yield* fs.readFileString(path.join(worktreePath, "uncommitted.txt")),
1634-
"keep these edits",
1635-
);
1636-
}
1637-
const registered = yield* git(cwd, ["worktree", "list", "--porcelain", "-z"]);
1638-
assert.equal(registered.includes("feature/existing"), existing);
1639-
assert.notInclude(registered, "feature/interrupted");
1640-
}),
1641-
);
1642-
}
1643-
16441560
it.effect("uses parallel checkout without skipping filters or hooks", () =>
16451561
Effect.gen(function* () {
16461562
const cwd = yield* makeTmpDir();
@@ -1680,18 +1596,23 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
16801596
yield* git(cwd, ["config", "branch.feature/parallel.gh-merge-base"]),
16811597
initialBranch,
16821598
);
1683-
yield* git(cwd, ["config", "checkout.workers", "1"]);
1684-
const configuredPath = path.join(yield* makeTmpDir("git-worktrees-"), "configured");
1685-
yield* driver.createWorktree({
1686-
cwd,
1687-
path: configuredPath,
1688-
refName: initialBranch,
1689-
newRefName: "feature/configured",
1690-
});
1691-
assert.equal(
1692-
yield* fs.readFileString(path.join(configuredPath, "checkout-workers")),
1693-
"1\n",
1694-
);
1599+
for (const [configured, expected] of [
1600+
["1", "1"],
1601+
["", "0"],
1602+
] as const) {
1603+
yield* git(cwd, ["config", "checkout.workers", configured]);
1604+
const configuredPath = path.join(yield* makeTmpDir("git-worktrees-"), "configured");
1605+
yield* driver.createWorktree({
1606+
cwd,
1607+
path: configuredPath,
1608+
refName: initialBranch,
1609+
newRefName: `feature/configured-${expected}`,
1610+
});
1611+
assert.equal(
1612+
yield* fs.readFileString(path.join(configuredPath, "checkout-workers")),
1613+
`${expected}\n`,
1614+
);
1615+
}
16951616
}),
16961617
);
16971618
it("parses checkout progress lines from git's stderr", () => {
@@ -2094,6 +2015,61 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
20942015
});
20952016

20962017
describe("remote operations", () => {
2018+
for (const failure of ["offline", "auth", "timeout"] as const) {
2019+
it.effect(`does not retry a scoped fetch after ${failure}`, () =>
2020+
Effect.gen(function* () {
2021+
const cwd = yield* makeTmpDir();
2022+
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
2023+
const started = yield* Deferred.make<void>();
2024+
const attempts: Array<ReadonlyArray<string>> = [];
2025+
const spawner = ChildProcessSpawner.make((command) =>
2026+
Effect.gen(function* () {
2027+
if (!ChildProcess.isStandardCommand(command))
2028+
return yield* Effect.die("unexpected command");
2029+
if (command.args[0] !== "fetch") return yield* delegate.spawn(command);
2030+
attempts.push(command.args);
2031+
yield* Deferred.succeed(started, undefined);
2032+
return ChildProcessSpawner.makeHandle({
2033+
...makeNonRepositoryHandle(),
2034+
exitCode:
2035+
failure === "timeout"
2036+
? Effect.never
2037+
: Effect.succeed(ChildProcessSpawner.ExitCode(128)),
2038+
stderr: Stream.encodeText(
2039+
Stream.make(
2040+
failure === "auth"
2041+
? "fatal: Authentication failed"
2042+
: "fatal: Could not resolve host",
2043+
),
2044+
),
2045+
});
2046+
}),
2047+
);
2048+
const driver = yield* makeGitVcsDriverCore().pipe(
2049+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
2050+
Effect.provide(ServerConfigLayer),
2051+
);
2052+
const fetching = yield* driver
2053+
.fetchRemote({ cwd, remoteName: "origin", refName: "main" })
2054+
.pipe(Effect.result, Effect.forkChild({ startImmediately: true }));
2055+
yield* Deferred.await(started);
2056+
if (failure === "timeout") {
2057+
yield* TestClock.adjust("31 seconds");
2058+
yield* TestClock.adjust("31 seconds");
2059+
}
2060+
const result = yield* Fiber.join(fetching);
2061+
assert.isTrue(Result.isFailure(result));
2062+
assert.equal(attempts.length, 1);
2063+
if (Result.isFailure(result)) {
2064+
assert.equal(
2065+
result.failure.detail,
2066+
failure === "timeout" ? "Git command timed out." : "git fetch origin failed",
2067+
);
2068+
}
2069+
}),
2070+
);
2071+
}
2072+
20972073
it.effect("creates a worktree from the latest fetched remote commit", () =>
20982074
Effect.gen(function* () {
20992075
const cwd = yield* makeTmpDir();
@@ -2126,10 +2102,6 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
21262102
assert.isFalse(
21272103
yield* driver.remoteBranchExists({ cwd, remoteName: "origin", refName: "unrelated" }),
21282104
);
2129-
yield* driver.fetchRemote({ cwd, remoteName: "origin", refName: "local-only" });
2130-
assert.isTrue(
2131-
yield* driver.remoteBranchExists({ cwd, remoteName: "origin", refName: "unrelated" }),
2132-
);
21332105

21342106
assert.equal(
21352107
yield* driver.remoteBranchExists({
@@ -2191,6 +2163,11 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
21912163
const status = yield* driver.statusDetails(worktreePath);
21922164
assert.equal(status.aheadCount, 0);
21932165
assert.equal(status.aheadOfDefaultCount, 0);
2166+
2167+
yield* driver.fetchRemote({ cwd, remoteName: "origin", refName: "local-only" });
2168+
assert.isTrue(
2169+
yield* driver.remoteBranchExists({ cwd, remoteName: "origin", refName: "unrelated" }),
2170+
);
21942171
}),
21952172
);
21962173

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

Lines changed: 34 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -3036,17 +3036,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
30363036
const sanitizedBranch = targetBranch.replace(/\//g, "-");
30373037
const repoName = path.basename(input.cwd);
30383038
const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch);
3039-
const lockReason = `t3code-create-${yield* crypto.randomUUIDv4.pipe(Effect.orDie)}`;
3040-
const args = [
3041-
"worktree",
3042-
"add",
3043-
"--lock",
3044-
"--reason",
3045-
lockReason,
3046-
...(input.newRefName ? ["-b", input.newRefName] : []),
3047-
worktreePath,
3048-
input.refName,
3049-
];
3039+
const args = input.newRefName
3040+
? ["worktree", "add", "-b", input.newRefName, worktreePath, input.refName]
3041+
: ["worktree", "add", worktreePath, input.refName];
30503042
const progress = options?.progress;
30513043
const onCheckoutProgress = progress?.onCheckoutProgress;
30523044

@@ -3072,46 +3064,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
30723064
}
30733065
: {}),
30743066
},
3075-
).pipe(
3076-
Effect.tap(() => progress?.onWorktreeClaimed?.(worktreePath) ?? Effect.void),
3077-
Effect.onExit((exit) =>
3078-
Effect.gen(function* () {
3079-
if (!Exit.isSuccess(exit)) {
3080-
const registeredWorktrees = yield* runGitStdout(
3081-
"GitVcsDriver.createWorktree.registeredPaths",
3082-
input.cwd,
3083-
["worktree", "list", "--porcelain", "-z"],
3084-
);
3085-
const matchingPaths = registeredWorktrees
3086-
.split("\0\0")
3087-
.filter((record) =>
3088-
record
3089-
.split("\0")
3090-
.some(
3091-
(field) =>
3092-
field.startsWith("worktree ") &&
3093-
path.resolve(field.slice("worktree ".length)) === path.resolve(worktreePath),
3094-
),
3095-
);
3096-
if (
3097-
matchingPaths.length !== 1 ||
3098-
!matchingPaths[0]?.split("\0").includes(`locked ${lockReason}`)
3099-
) {
3100-
return;
3101-
}
3102-
}
3103-
yield* runGit("GitVcsDriver.createWorktree.unlock", input.cwd, [
3104-
"worktree",
3105-
"unlock",
3106-
worktreePath,
3107-
]);
3108-
if (Exit.hasInterrupts(exit)) {
3109-
yield* removeWorktree({ cwd: input.cwd, path: worktreePath, force: true });
3110-
}
3111-
}).pipe(Effect.ignoreCause({ log: true })),
3112-
),
31133067
);
31143068

3069+
if (progress?.onWorktreeClaimed) {
3070+
yield* progress.onWorktreeClaimed(worktreePath);
3071+
}
3072+
31153073
// `git worktree add` leaves submodules empty, so a repo that keeps agent
31163074
// skills, tooling or source in one gets a worktree that is quietly missing
31173075
// them. Best-effort: the objects are usually already in the parent's
@@ -3300,12 +3258,35 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
33003258
const branch =
33013259
parseRemoteRefWithRemoteNames(input.refName, [input.remoteName])?.branchName ??
33023260
input.refName;
3303-
yield* executeGit(
3261+
const scopedArgs = [
3262+
...args,
3263+
`+refs/heads/${branch}:refs/remotes/${input.remoteName}/${branch}`,
3264+
];
3265+
const result = yield* executeGitWithStableDiagnostics(
33043266
"GitVcsDriver.fetchRemote",
33053267
input.cwd,
3306-
[...args, `+refs/heads/${branch}:refs/remotes/${input.remoteName}/${branch}`],
3307-
options,
3308-
).pipe(Effect.catch(() => fetchAll));
3268+
scopedArgs,
3269+
{ ...options, allowNonZeroExit: true },
3270+
);
3271+
if (result.exitCode === 0) return;
3272+
if (
3273+
result.stderr
3274+
.split(/\r?\n/)
3275+
.includes(`fatal: couldn't find remote ref refs/heads/${branch}`)
3276+
) {
3277+
return yield* fetchAll.pipe(Effect.asVoid);
3278+
}
3279+
return yield* new GitCommandError({
3280+
...gitCommandContext({
3281+
operation: "GitVcsDriver.fetchRemote",
3282+
cwd: input.cwd,
3283+
args: scopedArgs,
3284+
}),
3285+
detail: options.fallbackErrorDetail,
3286+
exitCode: result.exitCode,
3287+
stdoutLength: result.stdout.length,
3288+
stderrLength: result.stderr.length,
3289+
});
33093290
},
33103291
);
33113292

0 commit comments

Comments
 (0)