fix(vcs): group stashes by repository (#5380)

This commit is contained in:
l0ng-ai
2026-11-23 15:45:02 +08:00
committed by GitHub
parent 0b8d9135aa
commit f57a17ec14
6 changed files with 191 additions and 43 deletions
+79
View File
@@ -0,0 +1,79 @@
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
test("groups stashes by repository and keeps the selected stash actions scoped", async ({ workbench: page }) => {
await page.setViewportSize({ width: 1100, height: 720 });
await stubDesktop(page);
await page.evaluate(async () => {
const main = "/dev/acme-api";
const service = `${main}/warehouse-api`;
const stash = (index: number, id: string, title: string) => ({
index,
id,
message: `On main: ${title}`,
base: "base",
timeMs: new Date(2025, 4, 14, 10, 30).getTime(),
});
const handlers = window.__ipc.handlers;
handlers.vcs_stashes = ({ repo }) =>
repo === service
? [stash(0, "warehouse-stash", "Review warehouse routing")]
: [stash(0, "ledger-stash", "Check totals"), stash(1, "invoice-stash", "Match invoice balances")];
handlers.vcs_commit_files = ({ repo }) => [
{ path: repo === service ? "routing.txt" : "totals.txt", kind: "modified", oldPath: null },
];
const store = "/src/features/vcs/store.ts";
const context = "/src/platform/context.ts";
const actions = "/src/platform/actions.ts";
const toolWindows = "/src/workbench/toolwindows/store.ts";
const { useVcs } = await import(/* @vite-ignore */ store);
const { setContext } = await import(/* @vite-ignore */ context);
const { executeAction } = await import(/* @vite-ignore */ actions);
const { moveToolWindow, setToolWindowSize } = await import(/* @vite-ignore */ toolWindows);
useVcs.setState({ available: true, root: main, repo: main, roots: [main, service] });
setContext("vcsAvailable", true);
moveToolWindow("commit", "bottom");
await executeAction("vcs.showStashes");
setToolWindowSize("bottom", 310);
});
const tree = page.getByRole("tree", { name: "Stashes", exact: true });
const main = tree.getByRole("treeitem").filter({ has: page.getByText("acme-api", { exact: true }) });
const service = tree.getByRole("treeitem", { name: /warehouse-api/ });
const apply = page
.getByRole("toolbar", { name: "Stashes", exact: true })
.getByRole("button", { name: "Apply Stash" });
const first = tree.getByRole("treeitem", { name: /Check totals/ });
await expect(service, "repository group starts expanded").toHaveAttribute("aria-expanded", "true");
await expect(main).toHaveAccessibleName(/acme-api\s*2/);
await expect(first).toHaveAttribute("aria-level", "2");
await expect(first).toHaveAttribute("aria-selected", "true");
for (const width of [1100, 440]) {
await page.setViewportSize({ width, height: 720 });
const subject = first.getByText("Check totals", { exact: true });
const date = subject.locator("xpath=following-sibling::*[1]");
await expect(date).toHaveText(/2025/);
await expect.poll(() => subject.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true);
await expect(date).toHaveCSS("font-size", await subject.evaluate((el) => getComputedStyle(el).fontSize));
const titleBox = (await subject.boundingBox())!;
const dateBox = (await date.boundingBox())!;
expect(dateBox.x - titleBox.x - titleBox.width).toBeCloseTo(6, 0);
}
await tree.focus();
await tree.press("Home");
await tree.press("ArrowLeft");
await expect(main).toHaveAttribute("aria-expanded", "false");
await expect(first).toHaveCount(0);
await expect(apply).toBeDisabled();
await expect(page.getByText("Select a stash to view its changes.")).toBeVisible();
await tree.press("ArrowRight");
await expect(first).toBeVisible();
await tree.getByText("Review warehouse routing", { exact: true }).click();
await expect(apply).toBeEnabled();
await expect(page.getByRole("tree", { name: "Changed files" }).getByText("routing.txt")).toBeVisible();
expect((await ipcCalls(page, "vcs_commit_files")).at(-1)).toEqual({
repo: "/dev/acme-api/warehouse-api",
commit: "warehouse-stash",
});
});
+19 -10
View File
@@ -270,22 +270,31 @@
min-width: 0;
display: flex;
align-items: center;
gap: var(--space-2);
}
/* The message identifies a stash: the branch gives way first, the time stays whole. */
.stashRow > .detail {
white-space: nowrap;
}
.stashRow > .stashTime {
flex: none;
gap: var(--space-1-5);
}
.stashGroupName,
.stashTime,
.stashBranch,
.stashMessage {
flex: 1 1 auto;
min-width: 4em;
min-width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.stashMessage {
min-width: min(4em, 100%);
}
.stashGroupName {
font-weight: 600;
}
.stashTime {
flex-shrink: 10000;
color: var(--fg-secondary);
}
.stashBranch {
max-width: 30%;
margin-inline-start: auto;
}
@container stash-list (max-width: 320px) {
.stashBranch {
display: none;
+81 -23
View File
@@ -2,7 +2,7 @@ import { useEffect, useMemo, useState } from "react";
import clsx from "clsx";
import { tx } from "@/platform/i18n";
import { call, commands } from "@/platform/ipc";
import { IconButton, Select, SplitGroup, SplitHandle, SplitPanel, Tree, showContextMenu } from "@/ui";
import { Icon, IconButton, Select, SplitGroup, SplitHandle, SplitPanel, Tree, showContextMenu } from "@/ui";
import { useRowHeight } from "@/ui/density";
import { applyStash, dropStash, stashChanges } from "./changeOps";
import { formatTime, stashLabel } from "./model";
@@ -14,6 +14,15 @@ const stashIdentity = (stash: StashEntry) => JSON.stringify([stash.repo, stash.i
const stashKey = (stash: StashEntry) => `${stash.index}:${stashIdentity(stash)}`;
const EMPTY_STASHES: StashEntry[] = [];
interface StashGroup {
repo: string;
entries: StashEntry[];
}
type StashNode = StashGroup | StashEntry;
const isGroup = (node: StashNode): node is StashGroup => "entries" in node;
const nodeKey = (node: StashNode) => (isGroup(node) ? `repo:${node.repo}` : stashKey(node));
export function StashesPanel({ orientation = "vertical" }: { orientation?: "vertical" | "horizontal" }) {
const rowHeight = useRowHeight(22);
const project = useVcs((s) => s.root);
@@ -21,17 +30,41 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
const repo = useVcs((s) => s.repo);
const version = useVcs((s) => s.version);
const [tick, setTick] = useState(0);
const [selectedStash, setSelectedStash] = useState<StashEntry | null>(null);
const [selection, setSelection] = useState<StashNode | null>(null);
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());
const request = useMemo(() => ({ project, repos, repo, version, tick }), [project, repos, repo, version, tick]);
const [result, setResult] = useState<{ request: typeof request; stashes: StashEntry[]; error: string | null }>();
const loaded = result?.request === request;
const sameProject =
result?.request.project === project && result?.request.repos === repos && result?.request.repo === repo;
const stashes = sameProject ? result!.stashes : EMPTY_STASHES;
const groups = useMemo(() => {
const byRepo = new Map<string, StashGroup>();
if (repos.length > 1) {
for (const stash of stashes) {
if (!stash.repo) continue;
let group = byRepo.get(stash.repo);
if (!group) byRepo.set(stash.repo, (group = { repo: stash.repo, entries: [] }));
group.entries.push(stash);
}
}
return [...byRepo.values()];
}, [repos.length, stashes]);
const expanded = useMemo(
() => new Set(groups.filter((group) => !collapsed.has(group.repo)).map(nodeKey)),
[groups, collapsed],
);
const selectedGroup = selection && isGroup(selection) ? groups.find((group) => group.repo === selection.repo) : null;
const selectedStash = selection && !isGroup(selection) ? selection : null;
const selectedIdentity = selectedStash && stashIdentity(selectedStash);
const matching = selectedIdentity ? stashes.filter((entry) => stashIdentity(entry) === selectedIdentity) : [];
const current = matching.find((entry) => entry.index === selectedStash?.index) ?? matching[0] ?? stashes[0];
const selected = useMemo(() => new Set(current ? [stashKey(current)] : []), [current]);
const current = selectedGroup
? undefined
: (matching.find((entry) => entry.index === selectedStash?.index) ??
matching[0] ??
stashes.find((entry) => !groups.length || !entry.repo || !collapsed.has(entry.repo)));
const selectedNode = selectedGroup ?? current;
const selected = useMemo(() => new Set(selectedNode ? [nodeKey(selectedNode)] : []), [selectedNode]);
useEffect(() => {
let live = true;
@@ -54,22 +87,33 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
const stashList = (
<div className={styles.treeWrap}>
<Tree<StashEntry>
roots={stashes}
getKey={stashKey}
getLabel={(s) => stashLabel(s.message).text}
getChildren={() => undefined}
isExpandable={() => false}
<Tree<StashNode>
roots={groups.length ? groups : stashes}
getKey={nodeKey}
getLabel={(node) => (isGroup(node) ? repoName(node.repo) : stashLabel(node.message).text)}
getChildren={(node) => (isGroup(node) ? node.entries : undefined)}
isExpandable={isGroup}
expanded={expanded}
onExpandedChange={(_keys, node, open) => {
if (!isGroup(node)) return;
setCollapsed((keys) => {
const next = new Set(keys);
if (open) next.delete(node.repo);
else next.add(node.repo);
return next;
});
if (!open && current?.repo === node.repo) setSelection(node);
}}
selected={selected}
multiSelect={false}
rowHeight={rowHeight}
aria-label="Stashes"
className={styles.stashList}
empty={<span className={styles.empty}>{loaded ? (result.error ?? tx("No stashes")) : tx("Loading…")}</span>}
onSelectionChange={(_keys, lead) => setSelectedStash(lead)}
onSelectionChange={(_keys, lead) => setSelection(lead)}
onContextMenu={(s, _keys, e) => {
if (!s || !loaded) return;
setSelectedStash(s);
if (!s || isGroup(s) || !loaded) return;
setSelection(s);
showContextMenu(e, [
{ label: "Apply Stash", icon: "check", run: () => void applyStash(s, false, s.repo) },
{ label: "Pop Stash", icon: "undo", run: () => void applyStash(s, true, s.repo) },
@@ -79,16 +123,26 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
{ kind: "action", action: "vcs.clearStashes", arg: s.repo },
]);
}}
renderNode={(s) => {
const { branch, text } = stashLabel(s.message);
return (
<span className={styles.stashRow} title={`stash@{${s.index}}: ${s.message}`}>
<span className={styles.stashMessage}>
{repos.length > 1 && s.repo ? `${repoName(s.repo)} · ` : ""}
{text}
renderNode={(node) => {
if (isGroup(node)) {
return (
<span className={styles.stashRow} title={node.repo}>
<Icon name="toolwindow-git" size={16} />
<span className={styles.stashGroupName}>{repoName(node.repo)}</span>
<span className={styles.nodeCount}>{node.entries.length}</span>
</span>
);
}
const { branch, text } = stashLabel(node.message);
const time = formatTime(node.timeMs);
return (
<span
className={styles.stashRow}
title={[`stash@{${node.index}}: ${node.message}`, time].filter(Boolean).join("\n")}
>
<span className={styles.stashMessage}>{text}</span>
{time && <span className={styles.stashTime}>{time}</span>}
{branch && <span className={clsx(styles.detail, styles.stashBranch)}>{branch}</span>}
<span className={clsx(styles.detail, styles.stashTime)}>{formatTime(s.timeMs)}</span>
</span>
);
}}
@@ -132,7 +186,7 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
onClick={() => current && void dropStash(current, current.repo)}
/>
</div>
{current ? (
{stashes.length > 0 ? (
<SplitGroup
orientation={orientation}
className={styles.split}
@@ -143,7 +197,11 @@ export function StashesPanel({ orientation = "vertical" }: { orientation?: "vert
</SplitPanel>
<SplitHandle aria-label={tx("Resize stash panes")} />
<SplitPanel id="files" minSize="25%">
<StashChanges key={`${stashIdentity(current)}:${tick}`} stash={current} />
{current ? (
<StashChanges key={`${stashIdentity(current)}:${tick}`} stash={current} />
) : (
<span className={styles.empty}>{tx("Select a stash to view its changes.")}</span>
)}
</SplitPanel>
</SplitGroup>
) : (
@@ -65,17 +65,17 @@ beforeEach(() => {
it("lists stashes from every root and applies the selected row in its own repository", async () => {
render(<StashesPanel />);
expect(await screen.findByText("front · First")).toBeInTheDocument();
expect(await screen.findByText("back · Second")).toBeInTheDocument();
expect(await screen.findByText("First")).toBeInTheDocument();
expect(await screen.findByText("Second")).toBeInTheDocument();
act(() => useVcs.setState({ repo: "/p/back" }));
await screen.findByText("front · First");
await screen.findByText("First");
fireEvent.click(screen.getByRole("button", { name: "Apply Stash" }));
expect(apply).toHaveBeenCalledWith(expect.objectContaining({ index: 0, id: "/p/front-stash" }), false, "/p/front");
});
it("keeps the selected stash when a refresh inserts a new entry above it", async () => {
render(<StashesPanel />);
const original = await screen.findByText("front · First");
const original = await screen.findByText("First");
fireEvent.mouseDown(original, { button: 0 });
list.mockImplementation(async (repo: string) => ({
status: "ok",
@@ -88,15 +88,15 @@ it("keeps the selected stash when a refresh inserts a new entry above it", async
: [],
}));
act(() => useVcs.setState((state) => ({ version: state.version + 1 })));
expect(await screen.findByText("front · New")).toBeInTheDocument();
expect(screen.getByText("front · First").closest('[role="treeitem"]')).toHaveAttribute("aria-selected", "true");
expect(await screen.findByText("New")).toBeInTheDocument();
expect(screen.getByText("First").closest('[role="treeitem"]')).toHaveAttribute("aria-selected", "true");
fireEvent.click(screen.getByRole("button", { name: "Apply Stash" }));
expect(apply).toHaveBeenCalledWith(expect.objectContaining({ index: 1, id: "/p/front-stash" }), false, "/p/front");
});
it("disables stale stash actions while another repository is loading", async () => {
render(<StashesPanel />);
await screen.findByText("front · First");
await screen.findByText("First");
let resolve!: (value: unknown) => void;
list.mockImplementation(
() =>
@@ -105,7 +105,7 @@ it("disables stale stash actions while another repository is loading", async ()
}),
);
act(() => useVcs.setState({ root: "/other", roots: ["/other"], repo: "/other" }));
expect(screen.queryByText("front · First")).not.toBeInTheDocument();
expect(screen.queryByText("First")).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Apply Stash" })).toBeDisabled();
await act(async () => {
resolve({ status: "ok", data: [{ index: 0, message: "On main: New project", timeMs: 0, id: "n", base: "b" }] });
@@ -117,7 +117,7 @@ it("disables stale stash actions while another repository is loading", async ()
it("shows the selected stash's files and opens their diff without applying the stash", async () => {
render(<StashesPanel />);
fireEvent.mouseDown(await screen.findByText("back · Second"), { button: 0 });
fireEvent.mouseDown(await screen.findByText("Second"), { button: 0 });
const file = await within(await screen.findByRole("tree", { name: "Changed files" })).findByText("app.ts");
expect(files).toHaveBeenCalledWith("/p/back", "/p/back-stash");
expect(apply).not.toHaveBeenCalled();
@@ -206,7 +206,7 @@ it("ignores stale file results when switching stashes", async () => {
}),
);
render(<StashesPanel />);
fireEvent.mouseDown(await screen.findByText("back · Second"), { button: 0 });
fireEvent.mouseDown(await screen.findByText("Second"), { button: 0 });
expect(await screen.findByText("app.ts")).toBeInTheDocument();
await act(async () => {
resolve({ status: "ok", data: [{ path: "stale.ts", kind: "modified", oldPath: null }] });
+1
View File
@@ -2649,6 +2649,7 @@
"Show Files in Separate Diff Tabs": "Show Files in Separate Diff Tabs",
"Show All Files in One Diff View": "Show All Files in One Diff View",
"No changes": "No changes",
"Select a stash to view its changes.": "Select a stash to view its changes.",
"Scopes actions": "Scopes actions",
"Scopes": "Scopes",
"No scopes. Click + to add one.": "No scopes. Click + to add one.",
+1
View File
@@ -2359,6 +2359,7 @@
"No breakpoints. Click a line number to add one.": "没有断点。点击行号即可添加。",
"No build output": "没有构建输出",
"No changes": "没有更改",
"Select a stash to view its changes.": "请选择一条储藏以查看其中的更改。",
"No changes selected for commit": "未选择要提交的更改",
"No changes to create a patch from": "没有可用于创建补丁的更改",
"No changes to roll back": "没有要回滚的更改",