fix(vcs): keep worktree operation errors through refresh (#4271)

This commit is contained in:
l0ng-ai
2026-11-18 21:20:10 +08:00
committed by GitHub
parent 4990a90bbf
commit 3ed4fa6836
2 changed files with 112 additions and 31 deletions
@@ -1,11 +1,25 @@
import { beforeEach, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
const { list } = vi.hoisted(() => ({ list: vi.fn() }));
const { list, move, remove, open, confirm } = vi.hoisted(() => ({
list: vi.fn(),
move: vi.fn(),
remove: vi.fn(),
open: vi.fn(),
confirm: vi.fn(),
}));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return { ...real, commands: { ...real.commands, vcsWorktrees: list } };
return {
...real,
commands: { ...real.commands, vcsWorktrees: list, vcsMoveWorktree: move, vcsRemoveWorktree: remove },
};
});
vi.mock("@/platform/dialog", () => ({ open }));
vi.mock("../dialogs", async (original) => ({
...(await original<typeof import("../dialogs")>()),
confirmDialog: confirm,
}));
import { WorktreesPanel } from "../gitMenuDialogs";
import { useVcs } from "../store";
@@ -15,10 +29,16 @@ const worktrees = [
{ path: "/work/app", branch: "main", head: "12345678", main: true, locked: false, prunable: false },
{ path: "/work/app-feature", branch: "feature", head: "12345678", main: false, locked: false, prunable: false },
];
const ok = <T,>(data: T) => ({ status: "ok" as const, data });
const fail = (message: string) => ({ status: "error", error: { kind: "invalidInput", message, detail: null } });
beforeEach(() => {
useProject.setState({ project: { root: "/work/app-feature" } as never });
list.mockReset().mockResolvedValue({ status: "ok", data: worktrees });
list.mockReset().mockResolvedValue(ok(worktrees));
move.mockReset();
remove.mockReset();
open.mockReset();
confirm.mockReset().mockResolvedValue(true);
useVcs.setState({ root: "/work/app-feature", roots: ["/work/app-feature"], repo: null });
});
@@ -64,3 +84,49 @@ it("keeps the main worktree protected", async () => {
fireEvent.mouseDown(await screen.findByText("main"));
expect(screen.getByRole("button", { name: "Remove Worktree" })).toBeDisabled();
});
it("keeps a failed move's error and original selection through refresh, then clears the error on success", async () => {
const occupied = "/work/occupied/app-feature";
const free = "/work/free/app-feature";
const failure = `${occupied} already exists`;
useProject.setState({ project: { root: "/work/app" } as never });
useVcs.setState({ root: "/work/app", roots: ["/work/app"] });
open.mockResolvedValueOnce(occupied).mockResolvedValueOnce(free);
move.mockResolvedValueOnce(fail(failure)).mockResolvedValueOnce(ok(null));
render(<WorktreesPanel />);
fireEvent.mouseDown(await screen.findByText("feature"));
const moveButton = screen.getByRole("button", { name: "Move Worktree…" });
fireEvent.click(moveButton);
await waitFor(() => expect(list).toHaveBeenCalledTimes(2));
expect(move).toHaveBeenCalledWith("/work/app", "/work/app-feature", occupied);
expect(await screen.findByRole("alert")).toHaveTextContent(failure);
expect(screen.getByRole("treeitem", { name: /feature/ })).toHaveAttribute("aria-selected", "true");
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Refresh" })));
expect(list).toHaveBeenCalledTimes(3);
expect(screen.getByRole("alert")).toHaveTextContent(failure);
list.mockResolvedValueOnce(ok([worktrees[0], { ...worktrees[1], path: free }]));
fireEvent.click(moveButton);
expect(await screen.findByText(free)).toBeVisible();
expect(move).toHaveBeenLastCalledWith("/work/app", "/work/app-feature", free);
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("keeps the error and selected worktree after force removal fails", async () => {
const failure = "Worktree is locked";
useProject.setState({ project: { root: "/work/app" } as never });
useVcs.setState({ root: "/work/app", roots: ["/work/app"] });
remove.mockResolvedValueOnce(fail("Worktree contains changes")).mockResolvedValueOnce(fail(failure));
render(<WorktreesPanel />);
fireEvent.mouseDown(await screen.findByText("feature"));
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Remove Worktree" })));
expect(remove.mock.calls).toEqual([
["/work/app", "/work/app-feature", false],
["/work/app", "/work/app-feature", true],
]);
expect(list).toHaveBeenCalledTimes(2);
expect(await screen.findByRole("alert")).toHaveTextContent(failure);
expect(screen.getByRole("treeitem", { name: /feature/ })).toHaveAttribute("aria-selected", "true");
});
+42 -27
View File
@@ -683,13 +683,14 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin
const [groups, setGroups] = useState<RepoWorktrees[]>([]);
/** The selected tree row (`r:` repository, `w:` worktree). */
const [selected, setSelected] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [mutationError, setMutationError] = useState<{ project: string | undefined; message: string } | null>(null);
/** The last reload wins: a scan of the roots may change them while it runs. */
const run = useRef(0);
const mutationRun = useRef(0);
const reload = () => {
const id = ++run.current;
return Promise.all(
repos.map((root) =>
useVcs.getState().roots.map((root) =>
call(commands.vcsWorktrees(root)).then(
(worktrees): RepoWorktrees => ({ root, worktrees }),
(e): RepoWorktrees => ({ root, worktrees: [], error: errorMessage(e) }),
@@ -698,7 +699,6 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin
).then((lists) => {
if (id !== run.current) return;
setGroups(groupWorktrees(lists));
setError(null);
});
};
useEffect(() => {
@@ -738,6 +738,23 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin
return [...flags, w.path].join(" ");
};
const mutate = async (task: () => Promise<unknown>, selection: string | null) => {
if (projectRoot !== useProject.getState().project?.root) return;
const id = ++mutationRun.current;
let failure: string | null = null;
try {
await task();
} catch (e) {
failure = errorMessage(e);
}
if (projectRoot !== useProject.getState().project?.root) return;
if (id === mutationRun.current) {
setMutationError(failure === null ? null : { project: projectRoot, message: failure });
if (failure === null) setSelected(selection);
}
await reload();
};
const remove = async () => {
if (!current || !currentGroup || current.main || containsProject) return;
const ok = await confirmDialog({
@@ -747,22 +764,22 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin
danger: true,
});
if (!ok) return;
try {
await call(commands.vcsRemoveWorktree(currentGroup.root, current.path, false));
} catch (e) {
const force = await confirmDialog({
title: "Remove Worktree",
message: tx`${errorMessage(e)}\n\nRemove it anyway, discarding its changes?`,
okLabel: "Force Remove",
danger: true,
});
if (force)
await call(commands.vcsRemoveWorktree(currentGroup.root, current.path, true)).catch((x) =>
setError(errorMessage(x)),
);
}
setSelected(null);
await reload();
await mutate(async () => {
try {
await call(commands.vcsRemoveWorktree(currentGroup.root, current.path, false));
} catch (e) {
if (projectRoot !== useProject.getState().project?.root) return;
const force = await confirmDialog({
title: "Remove Worktree",
message: tx`${errorMessage(e)}\n\nRemove it anyway, discarding its changes?`,
okLabel: "Force Remove",
danger: true,
});
if (!force) throw e;
if (projectRoot === useProject.getState().project?.root)
await call(commands.vcsRemoveWorktree(currentGroup.root, current.path, true));
}
}, null);
};
const move = async () => {
@@ -784,13 +801,7 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin
okLabel: "Move",
});
if (!ok) return;
try {
await call(commands.vcsMoveWorktree(currentGroup.root, current.path, to));
setSelected(`w:${to}`);
} catch (e) {
setError(errorMessage(e));
}
await reload();
await mutate(() => call(commands.vcsMoveWorktree(currentGroup.root, current.path, to)), `w:${to}`);
};
return (
@@ -858,7 +869,11 @@ export function WorktreesPanel({ className, listClassName }: { className?: strin
</div>
),
)}
{error && <div className={styles.error}>{error}</div>}
{mutationError && mutationError.project === projectRoot && (
<div className={styles.error} role="alert">
{mutationError.message}
</div>
)}
</div>
);
}