fix(vcs): align the Apply Patch preview (#4860)

fix(vcs): align the Apply Patch preview
This commit is contained in:
l0ng-ai
2026-11-21 07:19:24 +08:00
committed by GitHub
parent dfafe6c767
commit 04bed01942
5 changed files with 319 additions and 66 deletions
+95
View File
@@ -0,0 +1,95 @@
import type { Page } from "@playwright/test";
import type { PatchFile } from "../src/bindings";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
const repo = "/dev/billing";
const path = "/tmp/release-2026/requests/adjust-invoices.patch";
const patch = "diff --git a/ledger/invoice.ts b/ledger/invoice.ts";
const invoice: PatchFile = {
path: "ledger/invoice.ts",
oldPath: null,
kind: "modified",
added: 3,
removed: 1,
binary: false,
applies: true,
};
async function openPatch(page: Page, source: "file" | "clipboard", files: PatchFile[]) {
await page.evaluate(
async ({ source, repo, path, patch, files }) => {
const handlers = window.__ipc.handlers;
handlers.fs_read_text = () => patch;
handlers.clipboard_text = () => patch;
handlers.vcs_patch_preview = () => files;
handlers.vcs_apply_patch = () => ({ applied: [files[0]?.path], conflicts: [] });
const store = "/src/features/vcs/store.ts";
const context = "/src/platform/context.ts";
const actions = "/src/platform/actions.ts";
(await import(/* @vite-ignore */ store)).useVcs.setState({ available: true, root: repo, repo, roots: [repo] });
(await import(/* @vite-ignore */ context)).setContext("vcsAvailable", true);
const { executeAction } = await import(/* @vite-ignore */ actions);
await executeAction(source === "file" ? "vcs.applyPatch" : "vcs.applyPatchFromClipboard", path);
},
{ source, repo, path, patch, files },
);
}
test("Apply Patch keeps the source, repository and file status aligned in a narrow dialog", async ({
workbench: page,
}) => {
await page.setViewportSize({ width: 485, height: 490 });
await stubDesktop(page);
await openPatch(page, "file", [
invoice,
{ ...invoice, path: "apps/batch/ledger/international/settlement/settle-invoice.ts", applies: false },
...Array.from({ length: 20 }, (_, i) => ({ ...invoice, path: `ledger/settlement-${i + 1}.ts` })),
]);
const dialog = page.getByRole("dialog", { name: "Apply Patch: adjust-invoices.patch", exact: true });
const source = dialog.getByRole("textbox", { name: "Patch source", exact: true });
const target = dialog.getByRole("textbox", { name: "Repository", exact: true });
const list = dialog.getByRole("listbox", { name: "Patch files", exact: true });
await expect(source).toHaveValue(path);
await expect(source).not.toBeEditable();
await expect(target).toHaveValue(repo);
await expect(dialog.getByRole("heading", { name: "Patch files", exact: true })).toBeVisible();
await expect(dialog.getByText("22 files", { exact: true })).toBeVisible();
expect((await source.boundingBox())!.y).toBeLessThan((await target.boundingBox())!.y);
expect((await target.boundingBox())!.y).toBeLessThan((await list.boundingBox())!.y);
const stats = list.getByText("+3 −1", { exact: true });
const first = (await stats.nth(0).boundingBox())!;
const second = (await stats.nth(1).boundingBox())!;
expect(Math.abs(first.x - second.x)).toBeLessThan(1);
await expect(list.getByLabel("Does not apply cleanly", { exact: true })).toBeInViewport({ ratio: 1 });
await expect(dialog.getByRole("status")).toHaveText("1 file will be merged; conflicts open in the merge tool");
await list.press("End");
await expect(list.getByText("settlement-20.ts", { exact: true })).toBeInViewport({ ratio: 1 });
await expect(dialog.getByRole("button", { name: "Apply", exact: true })).toBeInViewport({ ratio: 1 });
expect(await dialog.locator("[data-dialog-body]").evaluate((el) => el.scrollWidth - el.clientWidth)).toBe(0);
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(dialog).toBeHidden();
expect(await ipcCalls(page, "vcs_apply_patch")).toEqual([]);
});
test("Apply Patch previews clipboard contents and applies them to the previewed repository", async ({
workbench: page,
}) => {
await stubDesktop(page);
await openPatch(page, "clipboard", []);
const dialog = page.getByRole("dialog", { name: "Apply Patch: Clipboard", exact: true });
await expect(dialog.getByRole("textbox", { name: "Patch source", exact: true })).toHaveValue("Clipboard");
await expect(dialog.getByText("No changes", { exact: true })).toBeVisible();
const apply = dialog.getByRole("button", { name: "Apply", exact: true });
await expect(apply).toBeDisabled();
await dialog.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(dialog).toBeHidden();
await openPatch(page, "clipboard", [invoice]);
await expect(dialog.getByText("1 file", { exact: true })).toBeVisible();
await expect(apply).toBeEnabled();
await apply.click();
await expect(dialog).toBeHidden();
await expect.poll(() => ipcCalls(page, "vcs_apply_patch")).toEqual([{ repo, patch }]);
});
+121
View File
@@ -0,0 +1,121 @@
.dialog {
height: 440px;
}
.dialog > [data-dialog-body] {
display: flex;
flex-direction: column;
}
.preview {
display: flex;
flex: 1;
flex-direction: column;
gap: var(--space-3);
min-height: 0;
padding: var(--space-2) var(--space-4) 0;
}
.fields {
display: grid;
gap: var(--space-2);
}
.field {
display: flex;
flex-direction: column;
gap: var(--space-1);
min-width: 0;
color: var(--fg);
}
.field > input {
min-width: 0;
}
.files {
display: flex;
flex: 1;
flex-direction: column;
min-height: min(132px, 42vh);
border: 1px solid var(--border);
border-radius: var(--radius-small);
}
.filesHeader {
display: flex;
flex: none;
align-items: center;
justify-content: space-between;
gap: var(--space-2);
min-height: var(--h-field);
padding-inline: var(--space-3);
border-bottom: 1px solid var(--border);
}
.heading {
margin: 0;
color: var(--fg);
font-size: var(--fs-ui);
font-weight: 500;
}
.list {
flex: 1;
min-height: 0;
}
.filePath {
display: flex;
flex: 1;
align-items: center;
gap: var(--space-1-5);
min-width: 0;
}
.fileName {
flex: none;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
}
.stats {
flex: none;
color: var(--fg-secondary);
font-size: var(--fs-small);
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.fileStatus {
display: grid;
flex: none;
width: var(--space-4);
place-items: center;
}
.warning,
.error {
padding: var(--space-2) var(--space-3);
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
.warning {
display: flex;
flex: none;
align-items: center;
gap: var(--space-2);
border-top: 1px solid var(--border-feedback-warning);
background: var(--bg-feedback-warning);
color: var(--fg-secondary);
}
.warning > svg {
flex: none;
}
.error {
color: var(--danger);
}
+99 -66
View File
@@ -17,8 +17,8 @@ import { FileChecklist, defaultChangeFiles, reportApply } from "./shelf";
import { activeList, useChangelists } from "./changelists";
import { currentRepoRoot, useVcs } from "./store";
import styles from "./common.module.css";
import { tx } from "@/platform/i18n";
import { useRowHeight } from "@/ui/density";
import { tx, useTx } from "@/platform/i18n";
import previewStyles from "./ApplyPatch.module.css";
export type PatchOrigin =
| { kind: "changes"; files: FileStatus[] }
@@ -222,7 +222,7 @@ function CreatePatchDialog({ origin, onClose }: { origin: PatchOrigin; onClose:
/** Apply Patch…: from a file (chooser), or the clipboard. */
export async function showApplyPatch(from: "file" | "clipboard", path?: string) {
let text: string | null;
let source = "Clipboard";
let sourcePath: string | null = null;
try {
if (from === "clipboard") {
text = await readClipboardPlainText();
@@ -239,7 +239,7 @@ export async function showApplyPatch(from: "file" | "clipboard", path?: string)
file = typeof picked === "string" ? picked : null;
}
if (!file) return;
source = baseName(file);
sourcePath = file;
text = await call(commands.fsReadText(file));
}
} catch (e) {
@@ -256,11 +256,47 @@ export async function showApplyPatch(from: "file" | "clipboard", path?: string)
return;
}
const patch = text;
openDialog((close) => <ApplyPatchDialog patch={patch} source={source} onClose={close} />);
openDialog((close) => <ApplyPatchDialog patch={patch} sourcePath={sourcePath} onClose={close} />);
}
function ApplyPatchDialog({ patch, source, onClose }: { patch: string; source: string; onClose: () => void }) {
const rowHeight = useRowHeight(22);
function PatchFileRow({ file }: { file: PatchFile }) {
const t = useTx();
const name = baseName(file.path);
return (
<span
className={styles.fileTreeRow}
title={file.applies ? t("Applies cleanly") : t("Does not apply cleanly: a 3-way merge will be attempted")}
>
<Icon name={fileIconName(name, file.path)} size={14} />
<span className={previewStyles.filePath}>
<span
className={previewStyles.fileName}
style={{ color: KIND_COLOR[file.kind === "untracked" ? "added" : file.kind] }}
title={file.path}
>
{name}
</span>
<span className={styles.fileDir}>{file.oldPath ? t`from ${file.oldPath}` : dirName(file.path)}</span>
</span>
<span className={previewStyles.stats}>{file.binary ? t("binary") : `+${file.added} −${file.removed}`}</span>
<span className={previewStyles.fileStatus}>
{!file.applies && <Icon name="warning" size={14} label="Does not apply cleanly" />}
</span>
</span>
);
}
function ApplyPatchDialog({
patch,
sourcePath,
onClose,
}: {
patch: string;
sourcePath: string | null;
onClose: () => void;
}) {
const t = useTx();
const source = sourcePath ? baseName(sourcePath) : t("Clipboard");
const [repo] = useState(currentRepoRoot);
const [files, setFiles] = useState<PatchFile[] | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -274,12 +310,13 @@ function ApplyPatchDialog({ patch, source, onClose }: { patch: string; source: s
return () => {
alive = false;
};
}, [patch]);
}, [patch, repo]);
const count = files?.length ?? 0;
const failing = files?.filter((f) => !f.applies).length ?? 0;
const run = async () => {
onClose();
await saveAll();
const outcome = await runOp(tx`Apply patch (${source})`, () => call(commands.vcsApplyPatch(repo, patch)), {
const outcome = await runOp(t`Apply patch (${source})`, () => call(commands.vcsApplyPatch(repo, patch)), {
refresh: false,
});
if (outcome) await reportApply(outcome, "Patch applied");
@@ -287,71 +324,67 @@ function ApplyPatchDialog({ patch, source, onClose }: { patch: string; source: s
return (
<Dialog
open
title={tx`Apply Patch: ${source}`}
title="Apply Patch"
aria-label={t`Apply Patch: ${source}`}
onClose={onClose}
width={600}
footerStart={
files && failing > 0 ? (
<span className={styles.hint}>
{failing === 1
? tx`${failing} file will be merged; conflicts open in the merge tool`
: tx`${failing} files will be merged; conflicts open in the merge tool`}
</span>
) : undefined
}
width={660}
resizable="both"
minWidth={320}
className={previewStyles.dialog}
buttons={[
{ label: "OK", role: "default", autoFocus: true, disabled: !files?.length, onClick: () => void run() },
{ label: "Apply", role: "default", autoFocus: true, disabled: !count, onClick: () => void run() },
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.section}>
{files ? `${files.length} file${files.length === 1 ? "" : "s"} in the patch` : ""}
</div>
<div style={{ height: 280, display: "flex", flexDirection: "column", padding: "0 14px 14px" }}>
{error ? (
<div className={styles.error}>{error}</div>
) : !files ? (
<div className={styles.empty}>
<Spinner size={14} />
<div className={previewStyles.preview}>
<div className={previewStyles.fields}>
<label className={previewStyles.field}>
<T>Patch source</T>
<Input readOnly value={sourcePath ?? source} title={sourcePath ?? undefined} />
</label>
{repo && (
<label className={previewStyles.field}>
<T>Repository</T>
<Input readOnly value={repo} title={repo} />
</label>
)}
</div>
<section className={previewStyles.files}>
<div className={previewStyles.filesHeader}>
<h2 className={previewStyles.heading}>
<T>Patch files</T>
</h2>
{files && <span className={previewStyles.stats}>{count === 1 ? t`${count} file` : t`${count} files`}</span>}
</div>
) : (
<List
items={files}
getKey={(f) => f.path}
rowHeight={rowHeight}
aria-label="Patch files"
className={styles.boxList}
empty={
{error ? (
<div className={previewStyles.error} role="alert">
{error}
</div>
) : !files ? (
<div className={styles.empty}>
<Spinner size={14} />
</div>
) : (
<List
items={files}
getKey={(f) => f.path}
aria-label="Patch files"
className={previewStyles.list}
empty={<T>No changes</T>}
renderItem={(file) => <PatchFileRow file={file} />}
/>
)}
{failing > 0 && (
<div className={previewStyles.warning} role="status">
<Icon name="warning" size={14} />
<span>
<T>No changes</T>
{failing === 1
? t`${failing} file will be merged; conflicts open in the merge tool`
: t`${failing} files will be merged; conflicts open in the merge tool`}
</span>
}
renderItem={(f) => (
<span
className={styles.fileRow}
style={{ flex: 1, padding: 0 }}
title={
f.applies ? tx("Applies cleanly") : tx("Does not apply cleanly: a 3-way merge will be attempted")
}
>
<Icon name={fileIconName(baseName(f.path), f.path)} size={14} />
<span
className={styles.fileName}
style={{
color:
KIND_COLOR[f.kind === "untracked" ? "added" : f.kind === "conflicted" ? "conflicted" : f.kind],
}}
>
{baseName(f.path)}
</span>
<span className={styles.fileDir}>{f.oldPath ? tx`from ${f.oldPath}` : dirName(f.path)}</span>
<span className={styles.grow} />
<span className={styles.commitMeta}>{f.binary ? tx("binary") : `+${f.added} −${f.removed}`}</span>
{!f.applies && <Icon name="warning" size={14} label="Does not apply cleanly" />}
</span>
)}
/>
)}
</div>
)}
</section>
</div>
</Dialog>
);
+2
View File
@@ -391,6 +391,8 @@
"String ({chars} chars)": "String ({chars} chars)",
"Roll back the changes to {path}?": "Roll back the changes to {path}?",
"Roll back the changes to {count} files?": "Roll back the changes to {count} files?",
"Apply Patch": "Apply Patch",
"Patch source": "Patch source",
"They go back to how they were when the task started, in the task's worktree.": "They go back to how they were when the task started, in the task's worktree.",
"They go back to how they were when the task started. Edits of yours made to them since then are lost too; edits from before the task are kept.": "They go back to how they were when the task started. Edits of yours made to them since then are lost too; edits from before the task are kept.",
"They go back to the last commit; changes made after it are lost.": "They go back to the last commit; changes made after it are lost.",
+2
View File
@@ -2163,6 +2163,7 @@
"Patch destination": "补丁目标",
"Patch file": "补丁文件",
"Patch files": "补丁文件",
"Patch source": "补丁来源",
"Path From Content Root": "来自内容根的路径",
"Path of the current file relative to the project": "当前文件相对于项目的路径",
"Path to Git executable": "Git 可执行文件路径",
@@ -5114,6 +5115,7 @@
"No revert in progress": "没有正在进行的还原",
"No patch application in progress": "没有正在进行的补丁应用",
"Apply Patch: {source}": "应用补丁:{source}",
"Apply Patch": "应用补丁",
"Drop {count} commits from the current branch? Their changes are removed.": "是否从当前分支丢弃 {count} 个提交?它们的更改将被移除。",
"Drop commit {id} “{summary}” from the current branch? Its changes are removed.": "是否从当前分支丢弃提交 {id}“{summary}”?其更改将被移除。",
"Action for {id}": "{id} 的操作",