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 22, 10:45 UTC
fix(server): deleted worktree threads recover from a detached checkout (#26758)
Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
shivam committed
Oct 31, 2026 at 07:13 UTC
6366aba7442e8e8b295c1e9c0c344a554522b2c9
2 files changed
+108
-38
apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts
+67
-31
@@ -788,7 +788,7 @@ function makeLocalCommandHarness(input: {
788
}
789
790
effectIt.effect(
791
- "recovers the thread branch tip, falls back to the current project branch, and rejects detached HEAD",
791
+ "recovers the local or pushed thread tip, else the current branch, remote default, or detached HEAD",
792
() =>
793
Effect.gen(function* () {
794
const fileSystem = yield* FileSystem.FileSystem;
@@ -797,6 +797,7 @@ effectIt.effect(
797
const driver = yield* GitVcsDriver.GitVcsDriver;
798
const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-recreate-repo-" });
799
const workspaceRoot = path.join(root, "project");
800
+ const originRoot = path.join(root, "origin.git");
801
const worktreesDir = path.join(root, "worktrees");
802
const worktreePath = path.join(worktreesDir, "project", "restore");
803
yield* fileSystem.makeDirectory(workspaceRoot);
@@ -804,10 +805,19 @@ effectIt.effect(
805
driver
806
.execute({ operation: "test.worktreeRecovery", cwd, args })
807
.pipe(Effect.map((result) => result.stdout.trim()));
808
+ const branchConfig = (key: string) =>
809
+ git(workspaceRoot, ["config", "--get", `branch.feature/restore.${key}`]).pipe(
810
+ Effect.orElseSucceed(() => ""),
811
+ );
812
+ yield* git(root, ["init", "--bare", "-b", "main", originRoot]);
813
yield* git(workspaceRoot, ["init", "-b", "main"]);
814
yield* git(workspaceRoot, ["config", "user.name", "Test"]);
815
yield* git(workspaceRoot, ["config", "user.email", "test@example.com"]);
816
yield* git(workspaceRoot, ["commit", "--allow-empty", "-m", "base"]);
817
+ const baseTip = yield* git(workspaceRoot, ["rev-parse", "HEAD"]);
818
+ yield* git(workspaceRoot, ["remote", "add", "origin", originRoot]);
819
+ yield* git(workspaceRoot, ["push", "origin", "main"]);
820
+ yield* git(workspaceRoot, ["remote", "set-head", "origin", "main"]);
821
yield* git(workspaceRoot, ["worktree", "add", "-b", "feature/restore", worktreePath]);
822
yield* fileSystem.writeFileString(path.join(worktreePath, "thread.txt"), "thread work");
823
yield* git(worktreePath, ["add", "."]);
@@ -825,18 +835,48 @@ effectIt.effect(
835
// Tags must neither hide the thread branch nor select a different recovery tip.
836
yield* git(workspaceRoot, ["tag", "feature/restore", projectTip]);
837
yield* git(workspaceRoot, ["tag", "project-current", threadTip]);
838
+ yield* git(workspaceRoot, ["tag", "origin/feature/restore", threadTip]);
839
840
+ const expectedTips = {
841
+ retained: { tip: threadTip, file: "thread.txt", upstream: null, base: "" },
842
+ deleted: { tip: projectTip, file: "project.txt", upstream: null, base: "project-current" },
843
+ pushed: {
844
+ tip: threadTip,
845
+ file: "thread.txt",
846
+ upstream: "refs/remotes/origin/feature/restore",
847
+ base: "",
848
+ },
849
+ "pushed-detached": {
850
+ tip: threadTip,
851
+ file: "thread.txt",
852
+ upstream: "refs/remotes/origin/feature/restore",
853
+ base: "",
854
+ },
855
+ detached: { tip: baseTip, file: null, upstream: null, base: "main" },
856
+ "detached-no-remote": { tip: projectTip, file: "project.txt", upstream: null, base: "" },
857
+ } as const;
858
// Reuse the workflow across turns so recovery cannot select a cached project branch.
830
- for (const scenario of ["retained", "deleted", "detached"] as const) {
859
+ for (const scenario of Object.keys(expectedTips) as Array<keyof typeof expectedTips>) {
860
+ const expected = expectedTips[scenario];
861
+ if (scenario === "pushed") {
862
+ yield* git(workspaceRoot, ["push", "origin", `${threadTip}:refs/heads/feature/restore`]);
863
+ yield* git(workspaceRoot, ["fetch", "origin"]);
864
+ }
865
+ if (scenario === "pushed-detached") {
866
+ yield* git(workspaceRoot, ["switch", "--detach"]);
867
+ expect(yield* git(workspaceRoot, ["branch", "--show-current"])).toBe("");
868
+ }
869
+ if (scenario === "detached") {
870
+ yield* git(workspaceRoot, ["push", "origin", "--delete", "feature/restore"]);
871
+ }
872
+ if (scenario === "detached-no-remote") {
873
+ yield* git(workspaceRoot, ["remote", "remove", "origin"]);
874
+ }
875
yield* fileSystem.remove(worktreePath, { recursive: true });
876
if (scenario !== "retained") {
877
yield* git(workspaceRoot, ["worktree", "prune"]);
878
yield* git(workspaceRoot, ["branch", "-D", "feature/restore"]);
879
}
836
- if (scenario === "detached") {
837
- yield* git(workspaceRoot, ["switch", "--detach"]);
838
- expect(yield* git(workspaceRoot, ["branch", "--show-current"])).toBe("");
839
- }
880
const harness = makeLocalCommandHarness({
881
text: "Continue",
882
workspaceRoot,
@@ -850,38 +890,34 @@ effectIt.effect(
890
harness.open.mockImplementation(() =>
891
Effect.gen(function* () {
892
expect(yield* git(worktreePath, ["branch", "--show-current"])).toBe("feature/restore");
853
- expect(yield* git(worktreePath, ["rev-parse", "HEAD"])).toBe(
854
- scenario === "retained" ? threadTip : projectTip,
893
+ expect(yield* git(worktreePath, ["rev-parse", "HEAD"])).toBe(expected.tip);
894
+ for (const file of ["thread.txt", "project.txt"]) {
895
+ expect(yield* fileSystem.exists(path.join(worktreePath, file))).toBe(
896
+ file === expected.file,
897
+ );
898
+ }
899
+ expect(yield* branchConfig("merge")).toBe(
900
+ expected.upstream === null ? "" : "refs/heads/feature/restore",
901
);
856
- expect(
857
- yield* fileSystem.readFileString(
858
- path.join(worktreePath, scenario === "retained" ? "thread.txt" : "project.txt"),
859
- ),
860
- ).toBe(scenario === "retained" ? "thread work" : "new project code");
902
+ if (expected.upstream !== null) {
903
+ expect(
904
+ yield* git(worktreePath, ["rev-parse", "--symbolic-full-name", "@{upstream}"]),
905
+ ).toBe(expected.upstream);
906
+ }
907
+ expect(yield* branchConfig("t3-merge-base")).toBe(expected.base);
908
return yield* open();
909
}).pipe(Effect.orDie),
910
);
911
912
yield* harness.start;
913
867
- if (scenario === "detached") {
868
- expect(harness.open).not.toHaveBeenCalled();
869
- expect(harness.startRootRun).not.toHaveBeenCalled();
870
- expect(harness.projection().runs.at(-1)?.status).toBe("failed");
871
- expect(harness.projection().turnItems).toMatchObject([
872
- { type: "error", failure: { message: expect.stringContaining("no current branch") } },
873
- ]);
874
- expect(yield* fileSystem.exists(worktreePath)).toBe(false);
875
- expect(yield* git(workspaceRoot, ["branch", "--list", "feature/restore"])).toBe("");
876
- } else {
877
- expect(harness.open).toHaveBeenCalledOnce();
878
- expect(harness.startRootRun).toHaveBeenCalledWith(
879
- expect.objectContaining({
880
- runtimePolicy: expect.objectContaining({ cwd: worktreePath }),
881
- }),
882
- );
883
- expect(harness.projection().runs.at(-1)?.status).toBe("running");
884
- }
914
+ expect(harness.open).toHaveBeenCalledOnce();
915
+ expect(harness.startRootRun).toHaveBeenCalledWith(
916
+ expect.objectContaining({
917
+ runtimePolicy: expect.objectContaining({ cwd: worktreePath }),
918
+ }),
919
+ );
920
+ expect(harness.projection().runs.at(-1)?.status).toBe("running");
921
}
922
}).pipe(Effect.scoped, Effect.provide(layerRealGit)),
923
);
apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+41
-7
@@ -87,7 +87,7 @@ class WorktreeRecreateNoBaseError extends Schema.TaggedError<WorktreeRecreateNoB
87
{ worktreePath: Schema.String, branch: Schema.String },
88
) {
89
override get message(): string {
90
- return `Could not recreate branch '${this.branch}' at ${this.worktreePath}: the project workspace has no current branch to start it from (detached HEAD?).`;
90
+ return `Could not recreate branch '${this.branch}' at ${this.worktreePath}: the project workspace has no commit to start it from.`;
91
}
92
}
93
@@ -160,6 +160,31 @@ export const layer: Layer.Layer<
160
const runtimePolicy = yield* RuntimePolicy.RuntimePolicyV2;
161
const isManagedWorktreePath = yield* makeIsManagedWorktreePath;
162
163
+ const resolveRecreateBase = Effect.fn("ProviderTurnStartService.resolveRecreateBase")(
164
+ function* (cwd: string) {
165
+ // Recovery can follow an external checkout, before the status cache expires.
166
+ yield* gitWorkflow.invalidateLocalStatus(cwd);
167
+ const { refName: currentBranch } = yield* gitWorkflow.localStatus({ cwd });
168
+ if (currentBranch !== null) {
169
+ const refName = `refs/heads/${currentBranch}`;
170
+ return { refName, baseRefName: refName };
171
+ }
172
+ if (yield* gitWorkflow.hasCommit({ cwd, refName: "refs/remotes/origin/HEAD" })) {
173
+ const { commitSha } = yield* gitWorkflow.resolveRemoteTrackingCommit({
174
+ cwd,
175
+ refName: "HEAD",
176
+ fallbackRemoteName: "origin",
177
+ });
178
+ // Start from the commit so the thread branch does not track the default branch.
179
+ return { refName: commitSha, baseRefName: "refs/remotes/origin/HEAD" };
180
+ }
181
+ if (yield* gitWorkflow.hasCommit({ cwd, refName: "HEAD" })) {
182
+ return { refName: "HEAD", baseRefName: undefined };
183
+ }
184
+ return null;
185
+ },
186
+ );
187
+
188
const recreateMissingWorktree = Effect.fn("ProviderTurnStartService.recreateMissingWorktree")(
189
function* (input: {
190
readonly cwd: string;
@@ -173,17 +198,26 @@ export const layer: Layer.Layer<
198
yield* gitWorkflow.createWorktree({ cwd, refName: branch, path: worktreePath });
199
return;
200
}
176
- // Recovery can follow an external checkout, before the status cache expires.
177
- yield* gitWorkflow.invalidateLocalStatus(cwd);
178
- const { refName: baseRef } = yield* gitWorkflow.localStatus({ cwd });
179
- if (baseRef === null) {
201
+ // Push keeps the tracking ref current, so recovery reads it without fetching.
202
+ const pushedRef = `refs/remotes/origin/${branch}`;
203
+ if (yield* gitWorkflow.hasCommit({ cwd, refName: pushedRef })) {
204
+ yield* gitWorkflow.createWorktree({
205
+ cwd,
206
+ refName: pushedRef,
207
+ newRefName: branch,
208
+ path: worktreePath,
209
+ });
210
+ return;
211
+ }
212
+ const base = yield* resolveRecreateBase(cwd);
213
+ if (base === null) {
214
return yield* new WorktreeRecreateNoBaseError({ worktreePath, branch });
215
}
216
yield* gitWorkflow.createWorktree({
217
cwd,
184
- refName: `refs/heads/${baseRef}`,
218
+ refName: base.refName,
219
newRefName: branch,
186
- baseRefName: `refs/heads/${baseRef}`,
220
+ ...(base.baseRefName === undefined ? {} : { baseRefName: base.baseRefName }),
221
path: worktreePath,
222
});
223
},