fix(vcs): Show Diff targets the editor's file, not the Project view selection (#6202)

With a file open in the editor, VCS Operations › Show Diff (and Show Diff in New Window) opened
the file the Project view still had selected, because the target resolver preferred the Project
view's retained selection even while the editor owned the context.

Show Diff, Show Diff in New Window and Compare with Branch now take the Project view selection
only while the tree has focus or owns the context (its lead), the same rule Show History, Add to
VCS and Add to .gitignore already use; over the editor the active file wins. The resolver still
goes through the commit-window guards, so an amend row or an ignored-only selection there does
not fall back to the editor's file.

Co-authored-by: aevioni <[email protected]>
Цей коміт міститься в:
Aevion authored and GitHub committed 2026-11-26 22:23:31 +08:00
1 джерело d21fd65341
коміт a3e7142e4c
4 files changed
+99 -10

No files matched your search

+48
Переглянути файл
@@ -0,0 +1,48 @@
/**
* Show Diff over the editor through the VCS Operations popup: it targets the editor's file, not
* the file the Project view still has selected. Git is stubbed at the IPC layer.
*/
import { expect, openFromTree, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
const TABLIST = "Editor tabs";
test("Show Diff from the VCS Operations popup opens the editor's file, not the Project view selection", async ({
workbench: page,
}) => {
const editor = await openFromTree(page, "build.gradle.kts");
await stubDesktop(page);
await page.evaluate(async (root) => {
const changes = ["build.gradle.kts", "README.md"].map((relPath) => ({
path: `${root}/${relPath}`,
relPath,
staged: null,
unstaged: "modified",
renamedFrom: null,
}));
const h = window.__ipc.handlers;
h.vcs_roots = () => [{ root, head: "main", headCommit: "1111111" }];
h.vcs_branch_info = () => ({ head: "main", headCommit: "1111111", operation: null });
h.vcs_status = () => changes;
h.vcs_file_at = () => "";
h.vcs_compare_scope = () => ({ repositories: [root], skippedPaths: [], singleFile: true });
const store = "/src/features/vcs/store.ts";
const { useVcs, refreshNow } = await import(/* @vite-ignore */ store);
useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false });
await refreshNow();
}, ROOT);
// The Project view keeps README.md selected while the editor goes back to build.gradle.kts.
await page.getByRole("treeitem", { name: "README.md", exact: true }).click();
await page
.getByRole("tablist", { name: TABLIST })
.getByRole("tab", { name: "build.gradle.kts", exact: true })
.click();
await editor.locator(".cm-content").click();
await page.keyboard.press("Control+v");
await page.getByRole("menuitem", { name: /Show Diff/ }).click();
await expect(page.getByRole("tab", { name: "build.gradle.kts (HEAD ↔ Your version)" })).toBeVisible();
await expect(page.getByRole("tab", { name: "README.md (HEAD ↔ Your version)" })).toHaveCount(0);
});
+16 -2
Переглянути файл
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { getAction, isActionEnabled } from "@/platform/actions";
import { provideProjectViewSelection } from "@/workbench/contributions";
import { provideEditorService, provideProjectViewSelection, type EditorService } from "@/workbench/contributions";
import { registerVcsActions } from "../actions";
const mocks = vi.hoisted(() => ({ compare: vi.fn() }));
@@ -14,7 +14,7 @@ describe("compare action context", () => {
try {
const action = getAction("vcs.compareWithBranch")!;
expect(isActionEnabled(action, { vcsAvailable: true, projectViewFocus: true })).toBe(true);
await action.run({ arg: undefined, ctx: { vcsAvailable: true } });
await action.run({ arg: undefined, ctx: { vcsAvailable: true, projectViewFocus: true } });
expect(mocks.compare).toHaveBeenCalledWith(["/workspace/client", "/workspace/server"]);
await action.run({ arg: { path: "/workspace/client/a.ts" }, ctx: { vcsAvailable: true } });
expect(mocks.compare).toHaveBeenLastCalledWith(["/workspace/client/a.ts"]);
@@ -23,4 +23,18 @@ describe("compare action context", () => {
unregister();
}
});
it("compares the active editor file while the Project view keeps an earlier selection", async () => {
const unregister = registerVcsActions();
const dispose = provideProjectViewSelection(() => ["/workspace/client"]);
provideEditorService({ activePath: () => "/workspace/server/b.ts" } as unknown as EditorService);
try {
await getAction("vcs.compareWithBranch")!.run({ arg: undefined, ctx: { vcsAvailable: true } });
expect(mocks.compare).toHaveBeenCalledWith(["/workspace/server/b.ts"]);
} finally {
provideEditorService(undefined as unknown as EditorService);
dispose();
unregister();
}
});
});
+21 -1
Переглянути файл
@@ -15,9 +15,11 @@ const opened = vi.hoisted(() => vi.fn());
const diffWindow = vi.hoisted(() => vi.fn());
const separateWindow = vi.hoisted(() => vi.fn());
const project = vi.hoisted(() => ({ paths: [] as string[] }));
const active = vi.hoisted(() => ({ path: null as string | null }));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
editorService: () => ({ openInput: opened }),
maybeEditorService: () => (active.path ? { activePath: () => active.path } : undefined),
projectViewSelection: () => project.paths,
}));
vi.mock("../comparePaths", () => ({ showDirectoryWorkingDiff: async () => false }));
@@ -44,6 +46,7 @@ beforeEach(() => {
diffWindow.mockClear();
separateWindow.mockClear();
project.paths = [];
active.path = null;
setContext("activeToolWindow", "");
const files = [status("z.ts"), status("b.ts"), status("a.ts"), status("other.ts")];
useVcs.setState({ root: "/repo", roots: ["/repo"], status: files, byPath: new Map(files.map((f) => [f.path, f])) });
@@ -123,10 +126,27 @@ it("shows the selected change rather than a Project view selection kept from ear
it("shows a Project view selection outside the changes tree", async () => {
project.paths = ["/repo/z.ts"];
setContext("activeToolWindow", "project");
await getAction("vcs.showDiff")!.run({ arg: undefined, ctx: { vcsAvailable: true } });
await getAction("vcs.showDiff")!.run({ arg: undefined, ctx: { vcsAvailable: true, projectViewFocus: true } });
expect(opened.mock.calls[0]![0].data.path).toBe("/repo/z.ts");
});
it("shows the active editor file, not a Project view selection kept from earlier", async () => {
// ⌃V opens the VCS Operations popup over the editor: the editor keeps no focus, but the
// Project view still lists the file the user selected before. Show Diff must target the
// editor's file.
project.paths = ["/repo/z.ts"];
active.path = "/repo/b.ts";
await getAction("vcs.showDiff")!.run({ arg: undefined, ctx: { vcsAvailable: true } });
expect(opened.mock.calls[0]![0].data.path).toBe("/repo/b.ts");
});
it("opens the active editor file, not a Project view selection kept from earlier, in a new window", async () => {
project.paths = ["/repo/z.ts"];
active.path = "/repo/b.ts";
await getAction("vcs.showDiffInNewWindow")!.run({ arg: undefined, ctx: { vcsAvailable: true } });
expect(separateWindow.mock.calls[0]![0]).toMatchObject({ path: "/repo/b.ts" });
});
it("opens the front diff window from the modal Local Changes selection (⌘D)", async () => {
modal();
setContext("activeToolWindow", "git");
+14 -7
Переглянути файл
@@ -278,7 +278,7 @@ function contextPaths(arg: unknown): string[] {
* else the Project view's — it keeps its selection while another view has focus — else the
* active file.
*/
function selectedPaths(arg: unknown): string[] {
function selectedPaths(arg: unknown, project = projectViewSelection()): string[] {
const changed = changedPaths(arg);
if (changed.length) return changed;
// The Commit dialog tree's selection is final, even when it is empty.
@@ -289,10 +289,17 @@ function selectedPaths(arg: unknown): string[] {
if (selectionKeys.length && selectionKeys.every((key) => key === "group:ignored" || key.startsWith("ignored:")))
return [];
}
const project = projectViewSelection();
return project.length ? project : contextPaths(arg);
}
/**
* Like {@link selectedPaths}, but the Project view's selection counts only while the tree has
* focus or owns the context: over the editor the active file wins.
*/
function focusedSelection(arg: unknown, ctx: { projectViewFocus?: unknown }): string[] {
return selectedPaths(arg, ctx.projectViewFocus || projectViewContextLead() ? projectViewSelection() : []);
}
/** Uses the Project view's selection while the tree has focus or owns the context. */
function focusedPaths(arg: unknown, ctx: { projectViewFocus?: unknown }): string[] {
return ctx.projectViewFocus || projectViewContextLead() ? selectedPaths(arg) : contextPaths(arg);
@@ -793,7 +800,7 @@ export function registerVcsActions(): () => void {
}
const line =
arg && typeof arg === "object" && "line" in arg ? Number((arg as { line: unknown }).line) : undefined;
const paths = selectedPaths(arg);
const paths = focusedSelection(arg, ctx);
if (!paths.length) {
notifications().notify({ group: "vcs", level: "info", title: "Select a changed file to show its diff" });
return;
@@ -832,9 +839,9 @@ export function registerVcsActions(): () => void {
icon: "diff",
when: VCS,
keyWhen: "!editorTextFocus",
run: ({ arg }) => {
run: ({ arg, ctx }) => {
const requested = arg && typeof arg === "object" && "left" in arg && "right" in arg ? (arg as DiffData) : null;
const path = selectedPaths(arg)[0];
const path = focusedSelection(arg, ctx)[0];
const data = requested ?? focusedDiffNavigator()?.viewer?.()?.data ?? (path ? workingDiffData(path) : null);
if (!data) {
notifications().notify({ group: "vcs", level: "info", title: "Select a changed file to show its diff" });
@@ -849,8 +856,8 @@ export function registerVcsActions(): () => void {
category: "Git",
icon: "diff",
when: VCS,
run: async ({ arg }) => {
const paths = selectedPaths(arg);
run: async ({ arg, ctx }) => {
const paths = focusedSelection(arg, ctx);
if (!paths.length) {
notifications().notify({ group: "vcs", level: "info", title: "Open or select a file or folder to compare" });
return;