Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,40 @@ async function runDestroyPhases(
message: `Failed to remove worktree at ${local.worktreePath}`,
});
}
worktreeRemoved = true;
// `git worktree remove --force` is not atomic: it can fully
// unregister the worktree (so it no longer appears in
// `git worktree list`) while still failing to delete the working
// directory when a nested file is undeletable (#6730). Trusting
// `stillRegistered` alone then leaves an orphaned folder on disk
// and archives the row over it. Mirror the repo-missing branch
// above: when git no longer tracks it but the directory survives,
// remove it directly under the same root guard.
if (existsSync(local.worktreePath)) {
const worktreeBaseDir =
project.worktreeBaseDir ?? getHostWorktreeBaseDir(ctx);
if (
!isInsideProjectWorktreesRoot(
local.worktreePath,
project.id,
worktreeBaseDir,
)
) {
warnings.push(
`Skipped orphaned worktree removal at ${local.worktreePath}: folder is outside the managed worktrees root`,
);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} else {
try {
await rm(local.worktreePath, { recursive: true, force: true });
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: `Failed to remove orphaned worktree at ${local.worktreePath}: ${message}`,
});
}
worktreeRemoved = true;
}
}
}
}

Expand Down
19 changes: 17 additions & 2 deletions packages/host-service/src/workers/tasks/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -218,11 +218,26 @@ export const gitWorktreeRemoveTask = defineWorkerTask<
// command's locale- and version-dependent exit text. `--force --force`
// also unregisters a worktree whose directory is already gone, so no
// separate prune (which would clobber other stale worktrees' metadata)
// is needed.
// is needed. Log the real git error though — `--force --force` can
// unregister while still failing to delete the folder (undeletable
// nested file, #6730), and without this the underlying cause is
// invisible to anyone debugging an orphan.
reportPhase?.("worktree-remove");
await git
.raw(["worktree", "remove", "--force", "--force", target])
.catch(() => {});
.catch((err) => {
const message =
typeof err === "object" && err !== null && "message" in err
? String((err as { message: unknown }).message)
: String(err);
console.warn(
`[host-service] git worktree remove --force failed but may still unregister`,
{
error: message,
target,
},
);
});
// A `worktree list` failure throws out of the task: the post-remove
// state is unknown and the caller must not treat it as removed.
reportPhase?.("worktree-list");
Expand Down
112 changes: 110 additions & 2 deletions packages/host-service/test/workspace-cleanup.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
import {
existsSync,
mkdirSync,
mkdtempSync,
rmSync,
Expand All @@ -26,7 +27,7 @@ type WorkspaceRow = {
pullRequestId?: string | null;
archivedAt?: number | null;
};
type ProjectRow = { id: string; repoPath: string };
type ProjectRow = { id: string; repoPath: string; worktreeBaseDir?: string };

type WorktreeState = { hasChanges: boolean; hasUnpushedCommits: boolean };

Expand All @@ -42,6 +43,10 @@ interface ContextSpec {
resolveGitEnvThrows?: boolean;
removeWorktree?: () => Promise<{ stillRegistered: boolean }>;
deleteBranch?: () => Promise<{ deleted: boolean }>;
// Value returned by the host-settings lookup (`getHostWorktreeBaseDir`).
// When set, the worktree-removal root guard resolves against this base dir
// instead of the (absent) live settings row.
hostWorktreeBaseDir?: string;
// Simulates sqlite failure at the archive UPDATE — the commit point.
dbUpdateThrows?: boolean | "once";
}
Expand Down Expand Up @@ -118,7 +123,14 @@ function makeCtx(spec: ContextSpec): HostServiceContext & {
},
select: () => ({
from: () => ({
where: () => ({ all: terminalSelectAll }),
where: () => ({
all: terminalSelectAll,
// `getHostWorktreeBaseDir` reads the host-settings row.
get: () =>
spec.hostWorktreeBaseDir !== undefined
? { worktreeBaseDir: spec.hostWorktreeBaseDir }
: null,
}),
}),
}),
update: () => ({
Expand Down Expand Up @@ -480,6 +492,102 @@ describe("workspaceCleanup.destroy cleanup ordering", () => {
}
});

test("git-unregistered-but-left-on-disk worktree is removed, not orphaned", async () => {
// Regression for #6730: `git worktree remove --force` is not atomic —
// it can fully unregister the worktree (so it's absent from `git worktree
// list`, hence stillRegistered=false) while the working directory stays
// on disk when a nested file is undeletable. The destroy saga must then
// delete the leftover folder directly instead of trusting stillRegistered
// and archiving the row over an orphan.
const base = mkdtempSync(join(tmpdir(), "worktree-base-"));
const repo = mkdtempSync(join(tmpdir(), "workspace-delete-repo-"));
// Worktree must sit under <base>/<projectId>/ so the managed-root guard
// passes and the direct rm is allowed.
const projectRoot = join(base, "p-1");
mkdirSync(projectRoot, { recursive: true });
const worktree = join(projectRoot, "ws-1");
mkdirSync(worktree, { recursive: true });
try {
const ctx = makeCtx({
workspace: {
id: "ws-1",
projectId: "p-1",
worktreePath: worktree,
branch: "feature",
},
project: { id: "p-1", repoPath: repo, worktreeBaseDir: base },
// `runDestroyPhases` resolves the managed base dir via the
// host-settings lookup; surface it so the root guard treats the
// leftover worktree as inside the managed root.
hostWorktreeBaseDir: base,
// git says the worktree is no longer registered, but the folder
// still exists on disk (the undeletable-file case).
removeWorktree: async () => ({ stillRegistered: false }),
});
const caller = workspaceCleanupRouter.createCaller(ctx);

const result = await caller.destroy({
workspaceId: "ws-1",
deleteBranch: false,
force: true,
});
// The leftover folder must be gone now, not silently orphaned.
expect(existsSync(worktree)).toBe(false);
// No warning naming it as skipped (it was inside the managed root).
expect(
result.warnings.some((w: string) => w.includes("Skipped orphaned")),
).toBe(false);
} finally {
rmSync(base, { recursive: true, force: true });
rmSync(repo, { recursive: true, force: true });
}
});

test("orphaned worktree outside the managed root is skipped with worktreeRemoved=false", async () => {
// Regression for reviewer #6753: when the root guard skips orphaned
// removal, `worktreeRemoved` must stay false — the folder was NOT
// removed, so reporting it removed would be a lie in the response.
const base = mkdtempSync(join(tmpdir(), "worktree-base-"));
const repo = mkdtempSync(join(tmpdir(), "workspace-delete-repo-"));
// Worktree sits OUTSIDE <base>/<projectId>/ so the guard skips removal.
const safePath = mkdtempSync(join(tmpdir(), "worktree-outside-root-"));
const worktree = join(safePath, "ws-1");
mkdirSync(worktree, { recursive: true });
try {
const ctx = makeCtx({
workspace: {
id: "ws-1",
projectId: "p-1",
worktreePath: worktree,
branch: "feature",
},
project: { id: "p-1", repoPath: repo, worktreeBaseDir: base },
hostWorktreeBaseDir: base,
// git says no longer registered, but the folder exists on disk —
// and it is outside the managed root, so the direct rm is skipped.
removeWorktree: async () => ({ stillRegistered: false }),
});
const caller = workspaceCleanupRouter.createCaller(ctx);

const result = await caller.destroy({
workspaceId: "ws-1",
deleteBranch: false,
force: true,
});
// Folder survives (guard skipped the direct rm)...
expect(existsSync(worktree)).toBe(true);
// ...and we must NOT claim it was removed.
expect(result.worktreeRemoved).toBe(false);
// The skip is surfaced as a warning, not silent.
expect(
result.warnings.some((w: string) => w.includes("Skipped orphaned")),
).toBe(true);
} finally {
rmSync(base, { recursive: true, force: true });
rmSync(repo, { recursive: true, force: true });
}
});

test("missing project metadata warns but still deletes local state", async () => {
const tmp = mkdtempSync(join(tmpdir(), "workspace-delete-"));
try {
Expand Down