The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 14:45 UTC
fix(server): cancelling worktree setup removes its unclaimed worktree and branch (#36760)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Wout Stiens committed
Nov 14, 2026 at 15:12 UTC
77a39e9a37ceb82559a218ab2520c4deba0ea786
5 files changed
+399
-24
apps/server/src/vcs/GitVcsDriver.ts
+4
-1
@@ -124,7 +124,10 @@ export interface ExecuteGitProgress {
124
}
125
126
export interface CreateWorktreeProgress {
127
- /** Git refuses existing paths; claimed paths belong to this call and can be removed on cancel. */
127
+ /**
128
+ * Runs uninterruptibly once the worktree exists; from then on the caller owns its cleanup.
129
+ * For new-branch calls on Git supporting add --reason, cancellation before the claim removes what it made.
130
+ */
131
readonly onWorktreeClaimed?: (path: string) => Effect.Effect<void, never>;
132
readonly onCheckoutProgress?: (input: {
133
percent: number;
apps/server/src/vcs/GitVcsDriverCore.test.ts
+192
-4
@@ -1,6 +1,7 @@
1
// @effect-diagnostics nodeBuiltinImport:off - realpathSync.native resolves Windows 8.3 short names, which the Effect realPath does not.
2
import * as NodeChildProcess from "node:child_process";
3
import * as NodeFS from "node:fs";
4
+import * as NodeNet from "node:net";
5
import * as NodePath from "node:path";
6
import * as NodeURL from "node:url";
7
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
@@ -556,7 +557,10 @@ it.effect.each([
557
assert.equal(created.failure.exitCode, hookExitCode);
558
}
559
const metadataQueries = spawnedArgs.filter((args) => args.includes("--git-common-dir"));
559
- assert.deepStrictEqual(metadataQueries, [["rev-parse", "--git-common-dir"]]);
560
+ assert.deepStrictEqual(
561
+ metadataQueries,
562
+ Array.from({ length: 2 }, () => ["rev-parse", "--git-common-dir"]),
563
+ );
564
assert.isFalse(spawnedArgs.some((args) => args.includes("symbolic-ref")));
565
invalidationFailure = "none";
566
@@ -619,7 +623,7 @@ it.effect.each(["branch", "detached", "nested", "aliased-root", "aliased-nested"
623
newRefName: "feature/cold",
624
});
625
622
- assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1);
626
+ assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 2);
627
assert.isFalse(spawnedArgs.some((args) => args.includes("--show-toplevel")));
628
assert.isFalse(spawnedArgs.some((args) => args.includes("symbolic-ref")));
629
spawnedArgs.length = 0;
@@ -681,7 +685,10 @@ it.effect.each(["bare", "unborn"] as const)(
685
assert.equal(result.failure.operation, "GitVcsDriver.createWorktree.createBranch");
686
assert.equal(result.failure.detail, "git branch failed");
687
}
684
- assert.equal(spawnedArgs.filter((args) => args.includes("--git-common-dir")).length, 1);
688
+ assert.equal(
689
+ spawnedArgs.filter((args) => args.includes("--git-common-dir")).length,
690
+ state === "bare" ? 2 : 1,
691
+ );
692
assert.isFalse(spawnedArgs.some((args) => args[0] === "symbolic-ref"));
693
spawnedArgs.length = 0;
694
const refs = yield* driver.listRefs({ cwd });
@@ -1832,7 +1839,8 @@ it.effect("lets a worktree checkout that is still working run past five minutes"
1839
Effect.gen(function* () {
1840
if (!ChildProcess.isStandardCommand(command))
1841
return yield* Effect.die("expected Git command");
1835
- if (!command.args.includes("worktree")) return makeSuccessfulHandle("");
1842
+ if (!command.args.includes("worktree") || command.args.includes("-h"))
1843
+ return makeSuccessfulHandle("");
1844
yield* Deferred.succeed(checkoutStarted, undefined);
1845
return ChildProcessSpawner.makeHandle({
1846
...makeSuccessfulHandle(""),
@@ -2282,6 +2290,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
2290
const spawner = ChildProcessSpawner.make((command) => {
2291
if (
2292
ChildProcess.isStandardCommand(command) &&
2293
+ !command.args.includes("-h") &&
2294
(command.args.includes("worktree") ||
2295
command.args[0] === "branch" ||
2296
command.args[0] === "checkout")
@@ -5405,6 +5414,172 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
5414
});
5415
5416
describe("worktree operations", () => {
5417
+ it.effect.each(["current", "legacy"] as const)(
5418
+ "preserves another creator's worktree on its new branch at the same path (%s)",
5419
+ (version) =>
5420
+ Effect.gen(function* () {
5421
+ const cwd = yield* makeTmpDir();
5422
+ const { initialBranch } = yield* initRepoWithCommit(cwd);
5423
+ const path = NodePath.join(yield* makeTmpDir("git-worktrees-"), "contested");
5424
+ const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
5425
+ const reachedAdd = yield* Deferred.make<void>();
5426
+ let paused = false;
5427
+ const spawner = ChildProcessSpawner.make((command) =>
5428
+ Effect.gen(function* () {
5429
+ if (
5430
+ ChildProcess.isStandardCommand(command) &&
5431
+ command.args.includes("worktree") &&
5432
+ command.args.includes("add")
5433
+ ) {
5434
+ if (command.args.includes("-h")) {
5435
+ return version === "legacy"
5436
+ ? makeFailedHandle("usage: git worktree add [--lock]")
5437
+ : yield* delegate.spawn(command);
5438
+ }
5439
+ if (!paused) {
5440
+ paused = true;
5441
+ yield* Deferred.succeed(reachedAdd, undefined);
5442
+ return yield* Effect.never;
5443
+ }
5444
+ }
5445
+ return yield* delegate.spawn(command);
5446
+ }),
5447
+ );
5448
+ const driver = yield* makeGitVcsDriverCore().pipe(
5449
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
5450
+ Effect.provide(layerServerConfig),
5451
+ );
5452
+ const creator = yield* driver
5453
+ .createWorktree({
5454
+ cwd,
5455
+ path,
5456
+ refName: initialBranch,
5457
+ newRefName: "contested",
5458
+ })
5459
+ .pipe(Effect.forkChild);
5460
+ yield* Deferred.await(reachedAdd);
5461
+ yield* git(cwd, ["worktree", "add", "--", path, "contested"]);
5462
+ yield* writeTextFile(path, "owned-by-B.txt", "keep this work\n");
5463
+ yield* Fiber.interrupt(creator);
5464
+ assert.include(yield* git(cwd, ["worktree", "list", "--porcelain"]), path);
5465
+ assert.equal(yield* git(path, ["branch", "--show-current"]), "contested");
5466
+ assert.equal(
5467
+ yield* (yield* FileSystem.FileSystem).readFileString(
5468
+ NodePath.join(path, "owned-by-B.txt"),
5469
+ ),
5470
+ "keep this work\n",
5471
+ );
5472
+ const created = yield* driver.createWorktree({
5473
+ cwd,
5474
+ path: `${path}-retry`,
5475
+ refName: initialBranch,
5476
+ newRefName: "retry",
5477
+ });
5478
+ assert.equal(yield* git(created.worktree.path, ["branch", "--show-current"]), "retry");
5479
+ assert.notInclude(yield* git(cwd, ["worktree", "list", "--porcelain"]), "locked");
5480
+ }),
5481
+ );
5482
+
5483
+ it.effect.each(["main", "linked"] as const)(
5484
+ "removes its worktree and branch when cancelled before the claim (%s)",
5485
+ (checkout) =>
5486
+ Effect.gen(function* () {
5487
+ const repo = yield* makeTmpDir();
5488
+ const { initialBranch } = yield* initRepoWithCommit(repo);
5489
+ const cwd =
5490
+ checkout === "main"
5491
+ ? repo
5492
+ : NodePath.join(yield* makeTmpDir("git-linked-"), "checkout");
5493
+ if (checkout === "linked") {
5494
+ yield* git(repo, ["config", "worktree.useRelativePaths", "true"]);
5495
+ yield* git(repo, ["worktree", "add", "--detach", cwd]);
5496
+ }
5497
+ const fs = yield* FileSystem.FileSystem;
5498
+ const path = yield* Path.Path;
5499
+ const driver = yield* GitVcsDriver.GitVcsDriver;
5500
+ const worktreePath = path.join(yield* makeTmpDir("git-worktrees-"), "cancelled ü");
5501
+ const hookPath = path.join(repo, ".git/hooks/post-checkout");
5502
+ const connected = Promise.withResolvers<void>();
5503
+ const sockets = new Set<NodeNet.Socket>();
5504
+ const server = yield* Effect.acquireRelease(
5505
+ Effect.sync(() =>
5506
+ NodeNet.createServer((socket) => {
5507
+ sockets.add(socket);
5508
+ connected.resolve();
5509
+ }),
5510
+ ),
5511
+ (server) =>
5512
+ Effect.sync(() => {
5513
+ for (const socket of sockets) socket.destroy();
5514
+ server.close();
5515
+ }),
5516
+ );
5517
+ yield* Effect.promise(
5518
+ () =>
5519
+ new Promise<void>((resolve, reject) => {
5520
+ server.once("error", reject);
5521
+ server.listen(0, "127.0.0.1", resolve);
5522
+ }),
5523
+ );
5524
+ const address = server.address();
5525
+ assert.isTrue(address !== null && typeof address !== "string");
5526
+ if (address === null || typeof address === "string") return;
5527
+ const gate = path.join(cwd, "hook-gate.cjs");
5528
+ yield* fs.writeFileString(
5529
+ gate,
5530
+ `const s = require('node:net').connect(${address.port}, '127.0.0.1'); s.on('connect', () => process.stderr.write('Updating files: 50% (1/1000)\\n')); s.resume();`,
5531
+ );
5532
+ yield* writeTextFile(
5533
+ repo,
5534
+ ".git/hooks/post-checkout",
5535
+ `#!/bin/sh\nexec "${process.execPath.replaceAll("\\", "/")}" "${gate.replaceAll("\\", "/")}"\n`,
5536
+ );
5537
+ yield* fs.chmod(hookPath, 0o755);
5538
+ const hookStarted = yield* Deferred.make<void>();
5539
+ let claims = 0;
5540
+ const input = {
5541
+ cwd,
5542
+ path: worktreePath,
5543
+ refName: initialBranch,
5544
+ newRefName: "t3/cancel",
5545
+ };
5546
+ const worktrees = git(cwd, ["worktree", "list", "--porcelain"]);
5547
+
5548
+ const cancelled = yield* driver
5549
+ .createWorktree(input, {
5550
+ progress: {
5551
+ onCheckoutProgress: ({ total }) =>
5552
+ total === 1000 ? Deferred.succeed(hookStarted, undefined) : Effect.void,
5553
+ onWorktreeClaimed: () => Effect.sync(() => void claims++),
5554
+ },
5555
+ })
5556
+ .pipe(Effect.forkChild);
5557
+ yield* Deferred.await(hookStarted);
5558
+ yield* Effect.promise(() => connected.promise);
5559
+ assert.include(yield* worktrees, worktreePath);
5560
+ yield* Fiber.interrupt(cancelled);
5561
+
5562
+ assert.equal(claims, 0);
5563
+ assert.notInclude(yield* worktrees, worktreePath);
5564
+ assert.equal(yield* git(cwd, ["branch", "--list", "t3/cancel"]), "");
5565
+ assert.isFalse(yield* fs.exists(worktreePath));
5566
+
5567
+ // A retry gets the same path and branch, and a claimed worktree outlives a later cancel.
5568
+ yield* fs.remove(hookPath);
5569
+ const claimed = yield* Deferred.make<void>();
5570
+ const retry = yield* driver
5571
+ .createWorktree(input, {
5572
+ progress: { onWorktreeClaimed: () => Deferred.succeed(claimed, undefined) },
5573
+ })
5574
+ .pipe(Effect.forkChild);
5575
+ yield* Deferred.await(claimed);
5576
+ yield* Fiber.interrupt(retry);
5577
+ assert.include(yield* worktrees, worktreePath);
5578
+ assert.notInclude(yield* worktrees, "locked");
5579
+ assert.equal(yield* git(worktreePath, ["branch", "--show-current"]), "t3/cancel");
5580
+ }),
5581
+ );
5582
+
5583
it.effect("uses parallel checkout without skipping filters or hooks", () =>
5584
Effect.gen(function* () {
5585
const cwd = yield* makeTmpDir();
@@ -5461,6 +5636,19 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => {
5636
`${expected}\n`,
5637
);
5638
}
5639
+ yield* writeTextFile(
5640
+ cwd,
5641
+ ".git/hooks/post-checkout",
5642
+ '#!/bin/sh\ngit worktree unlock "$PWD" 2>/dev/null || :\ngit worktree lock --reason user-kept "$PWD"\n',
5643
+ );
5644
+ const lockedPath = path.join(yield* makeTmpDir("git-worktrees-"), "hook-locked");
5645
+ yield* driver.createWorktree({
5646
+ cwd,
5647
+ path: lockedPath,
5648
+ refName: initialBranch,
5649
+ newRefName: "feature/hook-locked",
5650
+ });
5651
+ assert.include(yield* git(cwd, ["worktree", "list", "--porcelain"]), "locked user-kept");
5652
}),
5653
);
5654
apps/server/src/vcs/GitVcsDriverCore.ts
+100
-12
@@ -1,7 +1,9 @@
1
import * as Cache from "effect/Cache";
2
+import * as Cause from "effect/Cause";
3
import * as Clock from "effect/Clock";
4
import * as Data from "effect/Data";
5
import * as Digest from "effect/crypto/Digest";
6
+import * as SecureRandom from "effect/crypto/SecureRandom";
7
import * as DateTime from "effect/DateTime";
8
import * as Duration from "effect/Duration";
9
import * as Effect from "effect/Effect";
@@ -981,6 +983,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
983
const { worktreesDir, worktreeCheckoutCacheDir } = yield* ServerConfig.ServerConfig;
984
const isServerInternalPath = yield* makeIsServerInternalPath;
985
const digest = yield* Digest.Digest;
986
+ const random = yield* SecureRandom.SecureRandom;
987
const hostPlatform = yield* HostProcess.Platform;
988
const serviceScope = yield* Effect.scope;
989
const statusFetches = new Map<string, Fiber.Fiber<void, GitCommandError>>();
@@ -4727,6 +4730,40 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4730
yield* refresh;
4731
});
4732
4733
+ // Git writes the lock reason during registration, before checkout or user hooks can run.
4734
+ const releaseWorktreeRegistration = Effect.fn("releaseWorktreeRegistration")(function* (
4735
+ cwd: string,
4736
+ reason: string,
4737
+ remove: boolean,
4738
+ ) {
4739
+ const commonDir = yield* readGitCommonDir(cwd);
4740
+ if (commonDir === null) return;
4741
+ const registrations = path.join(commonDir, "worktrees");
4742
+ const entries = yield* fileSystem.readDirectory(registrations).pipe(
4743
+ Effect.catchIf(
4744
+ (error) => error.reason._tag === "NotFound",
4745
+ () => Effect.succeed([]),
4746
+ ),
4747
+ );
4748
+ for (const entry of entries) {
4749
+ const adminDir = path.join(registrations, entry);
4750
+ const locked = yield* fileSystem
4751
+ .readFileString(path.join(adminDir, "locked"))
4752
+ .pipe(Effect.orElseSucceed(() => ""));
4753
+ if (locked.replace(/\r?\n$/, "") !== reason) continue;
4754
+ // gitdir can be relative to the registration with worktree.useRelativePaths enabled.
4755
+ const gitdir = yield* fileSystem.readFileString(path.join(adminDir, "gitdir"));
4756
+ const registered = path.dirname(path.resolve(adminDir, gitdir.replace(/\r?\n$/, "")));
4757
+ yield* runGit("GitVcsDriver.createWorktree.unlock", cwd, [
4758
+ "worktree",
4759
+ "unlock",
4760
+ "--",
4761
+ registered,
4762
+ ]);
4763
+ if (remove) yield* removeWorktree({ cwd, path: registered, force: true });
4764
+ }
4765
+ });
4766
+
4767
const createWorktree: GitVcsDriver.GitVcsDriver["Service"]["createWorktree"] = Effect.fn(
4768
"createWorktree",
4769
)(function* (input, options) {
@@ -4771,6 +4808,20 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4808
}
4809
}
4810
const newRefName = input.newRefName;
4811
+ // Older Git still creates worktrees normally, but cannot prove ownership for cancellation.
4812
+ const addHelp = newRefName
4813
+ ? yield* executeGit(
4814
+ "GitVcsDriver.createWorktree.capabilities",
4815
+ input.cwd,
4816
+ ["worktree", "add", "-h"],
4817
+ { allowNonZeroExit: true },
4818
+ )
4819
+ : null;
4820
+ const lockReason =
4821
+ addHelp && `${addHelp.stdout}\n${addHelp.stderr}`.includes("--reason")
4822
+ ? `t3-create-${yield* random.uuidV4()}`
4823
+ : undefined;
4824
+
4825
if (newRefName) {
4826
// Kept apart from the checkout so the shared-config lock only covers the tracking write.
4827
yield* createBranchAt(
@@ -4804,6 +4855,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4855
`checkout.workers=${checkoutWorkers}`,
4856
"worktree",
4857
"add",
4858
+ ...(lockReason ? ["--lock", "--reason", lockReason] : []),
4859
"--",
4860
worktreePath,
4861
checkoutRef,
@@ -4831,30 +4883,66 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
4883
: {}),
4884
},
4885
);
4886
+ // Set inside the claim's uninterruptible region: a pending cancel still surfaces as it ends.
4887
+ let claimed = false;
4888
+ const onWorktreeClaimed = progress?.onWorktreeClaimed;
4889
yield* (
4890
fastCheckout
4891
? checkoutCache
4837
- .create({ cwd: input.cwd, worktreePath, refName: checkoutRef, checkoutWorkers })
4892
+ .create({
4893
+ cwd: input.cwd,
4894
+ worktreePath,
4895
+ refName: checkoutRef,
4896
+ checkoutWorkers,
4897
+ lockReason,
4898
+ })
4899
.pipe(Effect.flatMap((cloned) => (cloned ? Effect.void : stockCheckout)))
4900
: stockCheckout
4901
).pipe(
4841
- Effect.onError(() =>
4842
- newRefName
4843
- ? deleteLocalBranch({ cwd: input.cwd, refName: newRefName, force: true }).pipe(
4902
+ Effect.andThen(
4903
+ fastCheckout ? checkoutCache.schedule(worktreePath, cacheGeneration) : Effect.void,
4904
+ ),
4905
+ Effect.andThen(
4906
+ onWorktreeClaimed
4907
+ ? Effect.uninterruptible(
4908
+ onWorktreeClaimed(worktreePath).pipe(
4909
+ Effect.andThen(
4910
+ Effect.sync(() => {
4911
+ claimed = true;
4912
+ }),
4913
+ ),
4914
+ ),
4915
+ )
4916
+ : Effect.void,
4917
+ ),
4918
+ Effect.onError((cause) =>
4919
+ newRefName && !claimed
4920
+ ? // A failed hook keeps its worktree, as Git does; only a cancel abandons it.
4921
+ (Cause.hasInterrupts(cause)
4922
+ ? lockReason
4923
+ ? releaseWorktreeRegistration(input.cwd, lockReason, true)
4924
+ : Effect.void
4925
+ : Effect.void
4926
+ ).pipe(
4927
+ Effect.andThen(
4928
+ deleteLocalBranch({ cwd: input.cwd, refName: newRefName, force: true }),
4929
+ ),
4930
Effect.catch((cause) =>
4845
- Effect.logWarning("could not remove the branch of a failed worktree", { cause }),
4931
+ Effect.logWarning("could not clean up a failed worktree or its branch", { cause }),
4932
+ ),
4933
+ )
4934
+ : Effect.void,
4935
+ ),
4936
+ Effect.onExit(() =>
4937
+ lockReason
4938
+ ? releaseWorktreeRegistration(input.cwd, lockReason, false).pipe(
4939
+ Effect.catch((cause) =>
4940
+ Effect.logWarning("could not unlock a created worktree", { cause }),
4941
),
4942
)
4943
: Effect.void,
4944
),
4945
);
4851
- if (fastCheckout) {
4852
- yield* checkoutCache.schedule(worktreePath, cacheGeneration);
4853
- }
4854
-
4855
- if (progress?.onWorktreeClaimed) {
4856
- yield* progress.onWorktreeClaimed(worktreePath);
4857
- }
4946
4947
// worktree add leaves submodules empty, potentially omitting project skills, tools or source.
4948
const hasSubmodules = yield* fileSystem
apps/server/src/vcs/worktreeCheckoutCache.ts
+10
-7
@@ -511,6 +511,7 @@ export const makeWorktreeCheckoutCache = Effect.fn("WorktreeCheckoutCache.make")
511
readonly worktreePath: string;
512
readonly refName: string;
513
readonly checkoutWorkers: string;
514
+ readonly lockReason?: string | undefined;
515
}) {
516
if (!(yield* gitSupported)) return false;
517
const worktreePath = path.resolve(input.cwd, input.worktreePath);
@@ -613,13 +614,14 @@ export const makeWorktreeCheckoutCache = Effect.fn("WorktreeCheckoutCache.make")
614
if (moved === null || (yield* fileSystem.exists(target.indexHook))) return null;
615
return target;
616
});
616
- const rollback = git("rollback", input.cwd, [
617
- "worktree",
618
- "remove",
619
- "--force",
620
- "--",
621
- worktreePath,
622
- ]).pipe(
617
+ const rollback = (
618
+ input.lockReason
619
+ ? git("unlockRollback", input.cwd, ["worktree", "unlock", "--", worktreePath])
620
+ : Effect.void
621
+ ).pipe(
622
+ Effect.andThen(
623
+ git("rollback", input.cwd, ["worktree", "remove", "--force", "--", worktreePath]),
624
+ ),
625
Effect.flatMap((removed) =>
626
removed === null
627
? Effect.logWarning("could not remove a partially created worktree", { worktreePath })
@@ -633,6 +635,7 @@ export const makeWorktreeCheckoutCache = Effect.fn("WorktreeCheckoutCache.make")
635
"worktree",
636
"add",
637
"--no-checkout",
638
+ ...(input.lockReason ? ["--lock", "--reason", input.lockReason] : []),
639
"--",
640
worktreePath,
641
input.refName,
scripts/scenarios/cancelled-worktree-setup-removes-its-worktree.e2e.ts
new
+93
@@ -0,0 +1,93 @@
1
+import * as NodeNet from "node:net";
2
+import { expect } from "e2e";
3
+import * as Effect from "effect/Effect";
4
+import * as FileSystem from "effect/FileSystem";
5
+import * as Schema from "effect/Schema";
6
+
7
+import { APP_DIR, T3_HOME } from "../e2e.config.ts";
8
+import { run } from "./shell.ts";
9
+import { runPromise, test, WEB } from "./t3.ts";
10
+
11
+const decodeLaunched = Schema.decodeUnknownEffect(
12
+ Schema.fromJsonString(Schema.Struct({ threadId: Schema.String })),
13
+);
14
+
15
+test(
16
+ "Cancelling worktree setup during its post-checkout hook removes the new worktree",
17
+ WEB,
18
+ async ({ t3, app, screen }) => {
19
+ const project = await t3.project("demo");
20
+ const git = (...args: ReadonlyArray<string>) =>
21
+ runPromise(run("git", args, { cwd: project })).then(({ stdout }) => stdout);
22
+ const connected = Promise.withResolvers<void>();
23
+ const sockets = new Set<NodeNet.Socket>();
24
+ const server = NodeNet.createServer((socket) => {
25
+ sockets.add(socket);
26
+ connected.resolve();
27
+ });
28
+ using _gateServer = {
29
+ [Symbol.dispose]() {
30
+ for (const socket of sockets) socket.destroy();
31
+ server.close();
32
+ },
33
+ };
34
+ await new Promise<void>((resolve, reject) => {
35
+ server.once("error", reject);
36
+ server.listen(0, "127.0.0.1", resolve);
37
+ });
38
+ const address = server.address();
39
+ if (address === null || typeof address === "string") throw new Error("Missing hook gate port");
40
+ await runPromise(
41
+ Effect.gen(function* () {
42
+ const fs = yield* FileSystem.FileSystem;
43
+ const hook = `${project}/.git/hooks/post-checkout`;
44
+ const gate = `${project}/hook-gate.cjs`;
45
+ yield* fs.writeFileString(
46
+ gate,
47
+ `const s = require('node:net').connect(${address.port}, '127.0.0.1'); s.on('connect', () => process.stderr.write('Updating files: 50% (1/1000)\\n')); s.resume();`,
48
+ );
49
+ yield* fs.writeFileString(
50
+ hook,
51
+ `#!/bin/sh\nexec "${process.execPath.replaceAll("\\", "/")}" "${gate.replaceAll("\\", "/")}"\n`,
52
+ );
53
+ yield* fs.chmod(hook, 0o755);
54
+ }),
55
+ );
56
+ const started = await runPromise(
57
+ run(
58
+ process.execPath,
59
+ [
60
+ "apps/server/src/bin.ts",
61
+ "thread",
62
+ "start",
63
+ project,
64
+ "hello",
65
+ "--worktree",
66
+ "main",
67
+ "--provider",
68
+ "devReplay",
69
+ "--model",
70
+ "showcase",
71
+ "--json",
72
+ "--base-dir",
73
+ T3_HOME,
74
+ ],
75
+ { cwd: APP_DIR, env: { PATH: process.env.PATH, HOME: process.env.HOME } },
76
+ ).pipe(Effect.flatMap(({ stdout }) => decodeLaunched(stdout))),
77
+ );
78
+
79
+ await connected.promise;
80
+ await t3.open(started);
81
+ await expect(screen.getByText("50%")).toBeVisible();
82
+ await screen.getByRole("button", "Cancel").tap();
83
+ await app.screenshot("after-cancel");
84
+
85
+ // The project's own checkout is the only one left once the cancel has cleaned up.
86
+ await expect
87
+ .poll(
88
+ async () => (await git("worktree", "list", "--porcelain")).match(/^worktree /gm)?.length,
89
+ )
90
+ .toBe(1);
91
+ await expect.poll(() => git("branch", "--list", "t3/*")).toBe("");
92
+ },
93
+);