Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 58d8776033 feat(editor): copy a multi-line selection's path as path:first-last
Copy Path with Line Number (and its entry in Copy Path/Reference…) copies
`path:12-18` when the selection spans several lines, leaving out a last
line the selection only reaches the start of; a caret or single-line
selection still copies `path:12`.

Closes #3962
2026-11-17 21:38:51 +08:00
23 змінених файлів з 64 додано та 492 видалено

No files matched your search

-3
Переглянути файл
@@ -135,8 +135,6 @@ pub struct CommitSettings {
/// `Settings::default()`, or `SettingsStore::set` rejects the key as unknown.
#[specta(optional)]
pub double_click_opens_diff: Option<bool>,
/// Team conventions for Generate Commit Message with Agent, added to its prompt.
pub agent_instructions: String,
}
impl Default for CommitSettings {
@@ -158,7 +156,6 @@ impl Default for CommitSettings {
wrap_at_margin: false,
disabled_plugin_checks: Vec::new(),
double_click_opens_diff: None,
agent_instructions: String::new(),
}
}
}
-4
Переглянути файл
@@ -360,10 +360,6 @@ pub struct Stash {
pub index: u32,
pub message: String,
pub time_ms: f64,
/// The stash commit; its changes are those against `base`.
pub id: String,
/// The commit the stash was made on (the stash commit's first parent).
pub base: Option<String>,
}
/// Push dialog › Push tags: every tag, or only annotated tags on the pushed commits.
+1 -9
Переглянути файл
@@ -158,15 +158,7 @@ pub(crate) fn stashes(r: &Repo) -> IdeResult<Vec<Stash>> {
for (index, line) in lines.enumerate() {
let line = line.map_err(gx)?;
let time_ms = line.signature.time.seconds as f64 * 1000.0;
let id = line.new_oid.to_owned();
let base = repo.find_commit(id).ok().and_then(|c| c.parent_ids().next().map(|p| p.to_string()));
out.push(Stash {
index: index as u32,
message: to_string(line.message.as_ref()),
time_ms,
id: id.to_string(),
base,
});
out.push(Stash { index: index as u32, message: to_string(line.message.as_ref()), time_ms });
}
Ok(out)
}
-5
Переглянути файл
@@ -849,11 +849,6 @@ fn stash_push_list_apply_pop() {
assert!(stashes[0].message.contains("WIP on main"), "{stashes:?}");
assert!(stashes[1].message.contains("first stash"), "{stashes:?}");
assert!(stashes[0].time_ms > 0.0);
// Each stash lists the files it changed against the commit it was made on.
let head = repo.head().unwrap().1.unwrap();
assert!(stashes.iter().all(|s| s.base.as_deref() == Some(head.as_str())), "{stashes:?}");
let files = repo.commit_files(&stashes[1].id).unwrap();
assert_eq!(files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(), ["s.txt"]);
repo.stash_apply(1, false, false).unwrap();
assert_eq!(fx.read("s.txt"), "change 1\n");
-1
Переглянути файл
@@ -846,7 +846,6 @@ mod tests {
"wrapAtMargin": false,
"disabledPluginChecks": [],
"doubleClickOpensDiff": null,
"agentInstructions": "",
})
);
}
-6
Переглянути файл
@@ -3583,8 +3583,6 @@ export type CommitSettings = {
* `Settings::default()`, or `SettingsStore::set` rejects the key as unknown.
*/
doubleClickOpensDiff?: boolean | null,
/** Team conventions for Generate Commit Message with Agent, added to its prompt. */
agentInstructions?: string,
};
export type Commit_Deserialize = {
@@ -10799,10 +10797,6 @@ export type Stash = {
index: number,
message: string,
timeMs: number | null,
/** The stash commit; its changes are those against `base`. */
id: string,
/** The commit the stash was made on (the stash commit's first parent). */
base: string | null,
};
/** A plugin's status bar item. */
-5
Переглянути файл
@@ -406,11 +406,6 @@ function SessionStatus({
>
{/* Where the task works, in one quiet line like the new-task page: project (in a workspace), branch, worktree. */}
<span className={styles.where} title={task.cwd}>
{/* Which agent runs the task: with several tasks side by side, this tells their answers apart. */}
<span className={styles.fact} title={providerName(task.provider)}>
<Icon name={providerIcon(task.provider)} size={13} />
<span className={styles.factText}>{providerName(task.provider)}</span>
</span>
{project?.workspace && projectName && (
<span className={styles.fact}>
<Icon name="folder" size={13} />
-9
Переглянути файл
@@ -112,15 +112,6 @@ describe("commitMessagePrompt", () => {
it("leaves out the style hint without earlier commits", () => {
expect(commitMessagePrompt(PATCH, 72, [])).not.toContain("latest commits");
});
it("adds the project's commit conventions before the recent subjects", () => {
const prompt = commitMessagePrompt(PATCH, 72, ["fix: y"], " Use Conventional Commits.\nPrefix the issue key. ");
const conventions = prompt.indexOf("Follow these conventions for commit messages here:\nUse Conventional Commits.");
expect(conventions).toBeGreaterThan(0);
expect(prompt).toContain("Prefix the issue key.\n");
expect(conventions).toBeLessThan(prompt.indexOf("latest commits"));
expect(commitMessagePrompt(PATCH, 72, [], " \n ")).not.toContain("conventions");
});
});
describe("commitMessageOf", () => {
+2 -14
Переглянути файл
@@ -44,12 +44,7 @@ export function fitPatch(patch: string, budget = PATCH_BUDGET, perFile = FILE_BU
return omitted.length ? `${out}\nDiff omitted for: ${omitted.join(", ")}\n` : out;
}
export function commitMessagePrompt(
patch: string,
subjectLimit: number,
recentSubjects: readonly string[],
instructions = "",
): string {
export function commitMessagePrompt(patch: string, subjectLimit: number, recentSubjects: readonly string[]): string {
const lines = [
"Write a commit message",
"",
@@ -59,8 +54,6 @@ export function commitMessagePrompt(
"- Don't edit files or run commands. The whole diff is below.",
"- Reply with the commit message only: no quotes, no code fence, no commentary.",
];
// The project's own conventions (Settings › Version Control › Commit) come before the style of recent commits.
if (instructions.trim()) lines.push("", "Follow these conventions for commit messages here:", instructions.trim());
if (recentSubjects.length) {
lines.push(
"",
@@ -257,12 +250,7 @@ async function generate(): Promise<void> {
const { commit } = workflowSettings().vcs;
const subjects = await recentSubjects(changes.roots[0]);
const prompt = commitMessagePrompt(
changes.patch,
commit.limitSubject ? commit.subjectLimit : 72,
subjects,
commit.agentInstructions,
);
const prompt = commitMessagePrompt(changes.patch, commit.limitSubject ? commit.subjectLimit : 72, subjects);
let task: AgentTask | undefined;
let release = () => {};
try {
-5
Переглянути файл
@@ -373,11 +373,6 @@ describe("composer UI during submission", () => {
expect(screen.getByRole("button", { name: "Send" })).toBeEnabled();
});
it("names the task's agent under the composer", () => {
render(<SessionEditor input={{ kind: SESSION_KIND, key: sessionKey("A"), data: { task: "A" } }} />);
expect(screen.getByTitle("Codex")).toHaveTextContent("Codex");
});
it("clears an unchanged session draft after only moving the caret", async () => {
const response = deferred();
backend.prompt.mockReturnValue(response.promise);
-70
Переглянути файл
@@ -1,70 +0,0 @@
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import type { ComponentType } from "react";
import { afterEach, beforeEach, expect, it } from "vitest";
import { DEFAULT_DEPLOYMENT_SERVER } from "@/platform/remoteSettings";
import { useContextMenuStore } from "@/ui";
import { PageContext } from "../components/context";
import { DEFAULT_SETTINGS } from "../model/schema";
import { stagedValue, useSettingsDialog } from "../model/staging";
import { DEPLOYMENT_PAGES } from "../pages/deployment";
const server = (id: string, name: string) => ({ ...DEFAULT_DEPLOYMENT_SERVER, id, name });
beforeEach(() => {
const base = structuredClone(DEFAULT_SETTINGS) as typeof DEFAULT_SETTINGS & { deployment: Record<string, unknown> };
base.deployment = { ...base.deployment, servers: [server("a", "Alpha"), server("b", "Beta")], defaultServer: "a" };
useSettingsDialog.setState({ base, globalBase: structuredClone(DEFAULT_SETTINGS), staged: {}, query: "" });
});
afterEach(() => {
act(() => useContextMenuStore.setState({ menu: null }));
cleanup();
});
function renderList() {
const page = DEPLOYMENT_PAGES.find((p) => p.id === "build.deployment")!;
const option = page
.sections!.flatMap((s) => s.options)
.find((o) => o.kind === "custom" && o.label === "Deployment servers");
const Editor = (option as unknown as { component: ComponentType }).component;
render(
<PageContext.Provider value={{ pageId: page.id, scope: "project" }}>
<Editor />
</PageContext.Provider>,
);
}
const menuItem = (label: string) => {
const item = useContextMenuStore.getState().menu!.items.find((i) => "label" in i && i.label === label) as {
run?: () => void;
disabled?: boolean;
};
return item;
};
const staged = (key: string) => stagedValue(useSettingsDialog.getState(), "project", key);
it("offers Add, Duplicate, Use as Default and Remove on a server row", () => {
renderList();
fireEvent.contextMenu(screen.getByRole("option", { name: /Beta/ }));
expect(screen.getByRole("option", { name: /Beta/ })).toHaveAttribute("aria-selected", "true");
expect(menuItem("Add")).toBeDefined();
act(() => menuItem("Use as Default").run!());
expect(staged("deployment.defaultServer")).toBe("b");
fireEvent.contextMenu(screen.getByRole("option", { name: /Beta/ }));
expect(menuItem("Use as Default").disabled).toBe(true);
act(() => menuItem("Duplicate").run!());
expect((staged("deployment.servers") as { name: string }[]).map((s) => s.name)).toEqual([
"Alpha",
"Beta",
"Beta (copy)",
]);
fireEvent.contextMenu(screen.getByRole("option", { name: /Alpha/ }));
act(() => menuItem("Remove").run!());
expect((staged("deployment.servers") as { name: string }[]).map((s) => s.name)).toEqual(["Beta", "Beta (copy)"]);
});
it("only adds from the empty part of the list", () => {
renderList();
fireEvent.contextMenu(screen.getByRole("listbox", { name: "Deployment servers" }));
const labels = useContextMenuStore.getState().menu!.items.map((i) => ("label" in i ? i.label : i.kind));
expect(labels).toEqual(["Add"]);
});
-37
Переглянути файл
@@ -1,37 +0,0 @@
import { beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
const { choose, tauri } = vi.hoisted(() => ({ choose: vi.fn(), tauri: { on: true } }));
vi.mock("@/platform/choosePath", () => ({ choosePath: choose }));
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
isTauri: () => tauri.on,
}));
import { GlobListEditor } from "../components/Form";
beforeEach(() => {
choose.mockReset();
tauri.on = true;
});
const browse = { directory: true, title: "Choose Include Path" };
it("adds the folder picked in the chooser and leaves the list alone when it is cancelled", async () => {
const onChange = vi.fn();
choose.mockResolvedValueOnce("/opt/platform").mockResolvedValueOnce(null);
render(<GlobListEditor value={["/a"]} onChange={onChange} browse={browse} aria-label="Include paths" />);
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Add" })));
expect(choose).toHaveBeenCalledWith({ directory: true, title: "Choose Include Path" });
expect(onChange).toHaveBeenCalledWith(["/a", "/opt/platform"]);
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Add" })));
expect(onChange).toHaveBeenCalledTimes(1);
expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
});
it("types the path inline without a chooser", async () => {
tauri.on = false;
render(<GlobListEditor value={[]} onChange={vi.fn()} browse={browse} itemLabel="Include path" />);
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Add" })));
expect(choose).not.toHaveBeenCalled();
expect(screen.getByRole("textbox", { name: "Include path" })).toBeInTheDocument();
});
+6 -19
Переглянути файл
@@ -7,8 +7,6 @@ import { useId, useRef, useState, type KeyboardEvent, type ReactNode } from "rea
import clsx from "clsx";
import { Checkbox, IconButton, Input, Select as UiSelect, type SelectOption, T } from "@/ui";
import { tx, useTx } from "@/platform/i18n";
import { choosePath } from "@/platform/choosePath";
import { isTauri } from "@/platform/ipc";
import { highlightIndices } from "../model/pages";
import { HEX_COLOR } from "../model/schema";
import { useLabelMatch, useSearchQuery, useSetting } from "./context";
@@ -305,8 +303,6 @@ export interface GlobListEditorProps {
emptyText?: string;
/** Accessible name of the inline editor. */
itemLabel?: string;
/** Entries are paths: + opens this chooser (Edit still takes typing). */
browse?: { directory: boolean; title: string };
}
/** Editable list of glob patterns (+ / − / edit toolbar, inline editing); also plain string lists. */
@@ -316,7 +312,6 @@ export function GlobListEditor({
placeholder = "**/pattern",
emptyText = "No patterns",
itemLabel = "Pattern",
browse,
...aria
}: GlobListEditorProps) {
const [selected, setSelected] = useState<number | null>(null);
@@ -345,19 +340,6 @@ export function GlobListEditor({
setEditing(null);
};
const add = async () => {
// Outside the desktop app there is no chooser: type the path instead.
if (!browse || !isTauri()) {
setEditing({ index: value.length, text: "" });
return;
}
const picked = await choosePath({ ...browse, title: tx(browse.title) });
if (!picked) return;
const next = [...new Set([...value, picked])];
onChange(next);
setSelected(next.indexOf(picked));
};
const remove = () => {
if (selected === null) return;
const next = value.filter((_, i) => i !== selected);
@@ -398,7 +380,12 @@ export function GlobListEditor({
return (
<div className={styles.globEditor}>
<div className={styles.listToolbar} role="toolbar" aria-controls={listId}>
<IconButton icon="plus" title="Add" size="small" onClick={() => void add()} />
<IconButton
icon="plus"
title="Add"
size="small"
onClick={() => setEditing({ index: value.length, text: "" })}
/>
<IconButton icon="minus" title="Remove" size="small" disabled={selected === null} onClick={remove} />
<IconButton
icon="edit"
-1
Переглянути файл
@@ -221,7 +221,6 @@ export function PhpPage() {
emptyText="No include paths"
itemLabel="Include path"
aria-label="Include paths"
browse={{ directory: true, title: "Choose Include Path" }}
/>
</Row>
<Row
-27
Переглянути файл
@@ -244,30 +244,3 @@
.toolsLayout .alignedRow {
grid-template-columns: subgrid;
}
/* Multi-line setting (agent instructions): a text field frame, full width. */
.instructions {
box-sizing: border-box;
width: 100%;
min-height: 72px;
padding: var(--space-1-5) var(--space-2);
border: 0;
border-radius: var(--radius-control, 4px);
background: var(--bg-field, var(--bg-button));
box-shadow: inset 0 0 0 1px var(--border-button);
color: var(--fg-strong);
font: inherit;
font-size: var(--fs-ui);
resize: vertical;
outline: none;
-webkit-user-select: text;
user-select: text;
}
.instructions::placeholder {
color: var(--fg-faint);
}
.instructions:focus {
box-shadow:
inset 0 0 0 1px var(--focus-ring),
0 0 0 1px var(--focus-ring);
}
+6 -62
Переглянути файл
@@ -3,7 +3,7 @@
* mappings, excluded remote paths) and the transfer options. Consumed by the
* deployment feature and `ide-remote` (automatic upload, remote delete).
*/
import { useEffect, useId, useState, type KeyboardEvent, type MouseEvent as ReactMouseEvent } from "react";
import { useEffect, useId, useState, type KeyboardEvent } from "react";
import clsx from "clsx";
import { call, commands, IpcError, isTauri, type FsConnection, type RemoteEntry } from "@/platform/ipc";
import { useTx, tx, txTemplate } from "@/platform/i18n";
@@ -30,7 +30,6 @@ import {
Spinner,
T,
Tabs,
type MenuItem,
} from "@/ui";
import { GlobListEditor, Row } from "../components/Form";
import { SshConfigSelect, useSshConfigs } from "../components/SshConfigSelect";
@@ -770,26 +769,6 @@ function DeploymentServersEditor() {
setGroups([...groupList, group]);
setSelected({ kind: "group", id: group.id });
};
const removeTarget = (target: Selection) => {
if (!target) return;
if (target.kind === "group") {
const group = groupList.find((g) => g.id === target.id);
if (!group) return;
const index = groupList.indexOf(group);
const rest = groupList.filter((g) => g.id !== group.id);
setGroups(rest);
const next = rest[Math.min(index, rest.length - 1)] ?? null;
setSelected(next ? { kind: "group", id: next.id } : list[0] ? { kind: "server", id: list[0].id } : null);
return;
}
const server = list.find((s) => s.id === target.id);
if (!server) return;
const index = list.indexOf(server);
const rest = list.filter((s) => s.id !== server.id);
commit(rest);
const next = rest[Math.min(index, rest.length - 1)] ?? null;
setSelected(next ? { kind: "server", id: next.id } : null);
};
const remove = () => {
if (currentGroup) {
const index = groupList.indexOf(currentGroup);
@@ -807,34 +786,6 @@ function DeploymentServersEditor() {
setSelected(next ? { kind: "server", id: next.id } : null);
};
const isSelected = (kind: "server" | "group", id: string) => selected?.kind === kind && selected.id === id;
const addItems: MenuItem[] = [
{ label: "Server", icon: "web", run: () => add() },
{ label: "Server Group", icon: "folder", run: addGroup },
];
// Right-click on a row works on that row (it is selected first); on the empty list it only adds.
const rowMenu = (e: ReactMouseEvent, target: Selection) => {
e.preventDefault();
e.stopPropagation();
setSelected(target);
const server = target?.kind === "server" ? list.find((s) => s.id === target.id) : undefined;
showContextMenu(e, [
{ label: "Add", icon: "plus", submenu: addItems },
...(server
? [
{ label: "Duplicate", icon: "copy", run: () => add(server) } as MenuItem,
{
label: "Use as Default",
icon: "check",
disabled: server.id === effectiveDefault,
run: () => setDefaultServer(server.id),
} as MenuItem,
]
: []),
{ kind: "separator" },
// `remove` acts on the selection, which the state update above has not applied yet.
{ label: "Remove", icon: "minus", run: () => removeTarget(target) },
]);
};
return (
<div className={styles.layout}>
@@ -846,7 +797,10 @@ function DeploymentServersEditor() {
size="small"
onClick={(e) => {
const r = e.currentTarget.getBoundingClientRect();
showContextMenu({ x: r.left, y: r.bottom }, addItems);
showContextMenu({ x: r.left, y: r.bottom }, [
{ label: "Server", icon: "web", run: () => add() },
{ label: "Server Group", icon: "folder", run: addGroup },
]);
}}
/>
<IconButton icon="minus" title="Remove" size="small" disabled={!current && !currentGroup} onClick={remove} />
@@ -865,15 +819,7 @@ function DeploymentServersEditor() {
onClick={() => current && setDefaultServer(current.id)}
/>
</div>
<div
className={styles.serverList}
role="listbox"
aria-label={tx("Deployment servers")}
onContextMenu={(e) => {
e.preventDefault();
showContextMenu(e, [{ label: "Add", icon: "plus", submenu: addItems }]);
}}
>
<div className={styles.serverList} role="listbox" aria-label={tx("Deployment servers")}>
{list.length === 0 && groupList.length === 0 && (
<div className={styles.empty}>
<T>No servers. Click + to add one.</T>
@@ -886,7 +832,6 @@ function DeploymentServersEditor() {
aria-selected={isSelected("group", g.id)}
className={clsx(styles.serverRow, isSelected("group", g.id) && styles.serverSelected)}
onMouseDown={() => setSelected({ kind: "group", id: g.id })}
onContextMenu={(e) => rowMenu(e, { kind: "group", id: g.id })}
>
<Icon name="folder" />
<span className={styles.serverName}>{g.name || g.id}</span>
@@ -900,7 +845,6 @@ function DeploymentServersEditor() {
aria-selected={isSelected("server", s.id)}
className={clsx(styles.serverRow, isSelected("server", s.id) && styles.serverSelected)}
onMouseDown={() => setSelected({ kind: "server", id: s.id })}
onContextMenu={(e) => rowMenu(e, { kind: "server", id: s.id })}
>
<Icon name="web" />
<span className={clsx(styles.serverName, s.id === effectiveDefault && styles.default)}>
-36
Переглянути файл
@@ -277,31 +277,6 @@ function MessageLimits() {
);
}
function AgentInstructionsRow() {
const [value, set] = useSetting<string>("vcs.commit.agentInstructions");
const id = useId();
return (
<Row
label="Instructions for Generate Commit Message with Agent"
htmlFor={id}
hint="Added to the agent's prompt, e.g. a commit format, issue key prefixes or the language to write in."
stacked
>
<textarea
id={id}
className={styles.instructions}
rows={4}
spellCheck={false}
placeholder={tx(
"Use Conventional Commits (feat:, fix:, …) and start with the issue key if the branch has one.",
)}
value={value}
onChange={(e) => set(e.target.value)}
/>
</Row>
);
}
function CommitChecks() {
return (
<Grid
@@ -427,17 +402,6 @@ export const VCS_PAGES: PageSpec[] = [
},
],
},
{
title: "Commit Message Generation",
options: [
{
kind: "custom",
label: "Instructions for Generate Commit Message with Agent",
keywords: ["agent", "ai", "prompt", "conventional commits"],
component: AgentInstructionsRow,
},
],
},
{
title: "Commit Checks",
options: [
+43 -121
Переглянути файл
@@ -26,6 +26,7 @@ import {
EmptyState,
Icon,
IconButton,
List,
Menu,
Select,
SplitGroup,
@@ -102,8 +103,7 @@ import {
import { DiffEditor } from "./DiffEditor";
import { KIND_COLOR, KIND_LABEL, fileCount, formatTime, stashLabel, stripSlash } from "./model";
import { call, commands } from "@/platform/ipc";
import type { Commit, FileStatus, Stash } from "@/bindings";
import { showChangesDiff, toLogChanges, type LogChange } from "./logChanges";
import type { FileStatus } from "@/bindings";
import { OperationBanner } from "./operations";
import { runOp } from "./ops";
import { ShelfPanel, loadShelves, useShelf } from "./shelf";
@@ -1334,33 +1334,18 @@ function CommitPanel({ included }: { included: number }) {
// ---------------------------------------------------------------------------
type StashEntry = Stash & { repo: string | null };
type StashNode = { key: string; stash: StashEntry; change?: LogChange };
const stashKey = (s: StashEntry) => `${s.repo}:${s.index}:${s.id}`;
const STASH_PREVIEW_DELAY = 120;
/** A stash's changes against the commit it was made on, as Git Log changes (diffs, line counts). */
async function stashFileChanges(stash: StashEntry): Promise<LogChange[]> {
const files = await call(commands.vcsCommitFiles(stash.repo, stash.id));
const commit = { id: stash.id, shortId: stash.id.slice(0, 8), parents: stash.base ? [stash.base] : [] };
return toLogChanges(files, commit as unknown as Commit, stash.repo, true);
}
export function StashesPanel() {
const repo = useVcs((s) => s.repo);
const repos = useVcs((s) => s.roots);
const version = useVcs((s) => s.version);
const [tick, setTick] = useState(0);
const [selectedKey, setSelectedKey] = useState<string | null>(null);
const [active, setActive] = useState(0);
const request = useMemo(() => ({ repos, repo, version, tick }), [repos, repo, version, tick]);
const [result, setResult] = useState<{
request: typeof request;
stashes: StashEntry[];
stashes: (import("@/bindings").Stash & { repo: string | null })[];
error: string | null;
} | null>(null);
const [files, setFiles] = useState<ReadonlyMap<string, LogChange[]>>(new Map());
const previewTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
const loaded = result?.request === request;
const stashes = loaded ? result.stashes : [];
const error = loaded ? result.error : null;
@@ -1381,29 +1366,7 @@ export function StashesPanel() {
live = false;
};
}, [request]);
useEffect(() => () => clearTimeout(previewTimer.current), []);
const roots = useMemo<StashNode[]>(() => stashes.map((stash) => ({ key: stashKey(stash), stash })), [stashes]);
const childrenOf = (node: StashNode): StashNode[] | undefined =>
node.change
? undefined
: files.get(node.key)?.map((change) => ({ key: `${node.key}\u0000${change.path}`, stash: node.stash, change }));
const loadFiles = async (node: StashNode) => {
if (files.has(node.key)) return;
const changes = await stashFileChanges(node.stash).catch(() => []);
setFiles((prev) => new Map(prev).set(node.key, changes));
};
const nodeOf = (key: string | null): StashNode | undefined => {
if (!key) return undefined;
const root = roots.find((r) => key === r.key || key.startsWith(`${r.key}\u0000`));
if (!root || key === root.key) return root;
return childrenOf(root)?.find((n) => n.key === key);
};
const selectedNode = nodeOf(selectedKey);
const current = selectedNode?.stash ?? stashes[0];
const showDiff = (node: StashNode, preview: boolean) => {
const chain = files.get(stashKey(node.stash)) ?? [];
if (node.change) void showChangesDiff([node.change], preview, chain).catch(() => undefined);
};
const current = stashes[active];
return (
<div className={styles.changes}>
<div className={styles.toolbar} role="toolbar" aria-label={tx("Stashes")}>
@@ -1415,15 +1378,7 @@ export function StashesPanel() {
options={repos.map((root) => ({ value: root, label: repoName(root) }))}
/>
)}
<IconButton
icon="refresh"
title="Refresh"
size="small"
onClick={() => {
setFiles(new Map());
setTick((n) => n + 1);
}}
/>
<IconButton icon="refresh" title="Refresh" size="small" onClick={() => setTick((n) => n + 1)} />
<IconButton icon="plus" title="Stash Changes…" size="small" onClick={() => void stashChanges()} />
<span className={styles.sep} />
<IconButton
@@ -1448,77 +1403,44 @@ export function StashesPanel() {
onClick={() => current && void dropStash(current.index, current.message, current.repo)}
/>
</div>
<div className={styles.treeWrap}>
<Tree<StashNode>
roots={roots}
getKey={(n) => n.key}
getLabel={(n) => (n.change ? basename(n.change.path) : n.stash.message)}
getChildren={childrenOf}
isExpandable={(n) => !n.change}
loadChildren={loadFiles}
selected={useMemo(() => new Set(selectedKey ? [selectedKey] : []), [selectedKey])}
multiSelect={false}
rowHeight={22}
aria-label="Stashes"
className={styles.stashList}
empty={<span className={styles.empty}>{error ?? (loaded ? tx("No stashes") : tx("Loading…"))}</span>}
onSelectionChange={(sel) => {
const key = [...sel][0] ?? null;
setSelectedKey(key);
clearTimeout(previewTimer.current);
const node = nodeOf(key);
// With Show Diff Preview on, the selection walks a preview tab through the stash's files.
if (node?.change && useCommit.getState().diffPreview && !vcsDiffInFront())
previewTimer.current = setTimeout(() => showDiff(node, true), STASH_PREVIEW_DELAY);
}}
onActivate={(n) => showDiff(n, false)}
onContextMenu={(n, _sel, e) => {
if (!n) return;
e.preventDefault();
setSelectedKey(n.key);
const s = n.stash;
showContextMenu(e, [
...(n.change
? [
{ label: "Show Diff", icon: "diff", run: () => showDiff(n, false) } as MenuItem,
{ kind: "separator" } as MenuItem,
]
: []),
{ label: "Apply Stash", icon: "check", run: () => void applyStash(s.index, false, s.repo) },
{ label: "Pop Stash", icon: "undo", run: () => void applyStash(s.index, true, s.repo) },
{ label: "Unstash…", run: () => showUnstashDialog(s.index, s.repo) },
{ kind: "separator" },
{ label: "Drop Stash", icon: "trash", run: () => void dropStash(s.index, s.message, s.repo) },
]);
}}
renderNode={(n) => {
if (n.change) {
const kind = n.change.kind === "untracked" ? "added" : n.change.kind;
return (
<>
<Icon name={fileIconName(basename(n.change.path), n.change.path)} size={16} className={styles.icon} />
<span className={styles.label} style={{ color: KIND_COLOR[kind] }}>
{basename(n.change.path)}
</span>
<span className={styles.detail}>{dirname(n.change.path)}</span>
</>
);
}
const s = n.stash;
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}
</span>
{branch && <span className={clsx(styles.detail, styles.stashBranch)}>{branch}</span>}
<span className={clsx(styles.detail, styles.stashTime)}>{formatTime(s.timeMs)}</span>
<List
items={stashes}
getKey={(s) => `${s.repo}:${s.index}`}
activeIndex={Math.min(active, Math.max(0, stashes.length - 1))}
onActiveChange={setActive}
rowHeight={22}
aria-label="Stashes"
className={styles.stashList}
empty={<span className={styles.empty}>{error ?? (loaded ? tx("No stashes") : tx("Loading…"))}</span>}
onActivate={(s, _i, e) => {
if (e.type === "click" && (e as MouseEvent).detail < 2) return;
void applyStash(s.index, false, s.repo);
}}
onContextMenu={(s, i, e) => {
e.preventDefault();
setActive(i);
showContextMenu(e, [
{ label: "Apply Stash", icon: "check", run: () => void applyStash(s.index, false, s.repo) },
{ label: "Pop Stash", icon: "undo", run: () => void applyStash(s.index, true, s.repo) },
{ label: "Unstash…", run: () => showUnstashDialog(s.index, s.repo) },
{ kind: "separator" },
{ label: "Drop Stash", icon: "trash", run: () => void dropStash(s.index, s.message, s.repo) },
]);
}}
renderItem={(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}
</span>
);
}}
/>
</div>
{branch && <span className={clsx(styles.detail, styles.stashBranch)}>{branch}</span>}
<span className={clsx(styles.detail, styles.stashTime)}>{formatTime(s.timeMs)}</span>
</span>
);
}}
/>
</div>
);
}
+3 -41
Переглянути файл
@@ -1,11 +1,6 @@
import { beforeEach, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
const { apply, list, files, diff } = vi.hoisted(() => ({
apply: vi.fn(),
list: vi.fn(),
files: vi.fn(),
diff: vi.fn(),
}));
const { apply, list } = vi.hoisted(() => ({ apply: vi.fn(), list: vi.fn() }));
vi.mock("@/platform/ipc", async (original) => {
const real = await original<typeof import("@/platform/ipc")>();
return {
@@ -13,7 +8,6 @@ vi.mock("@/platform/ipc", async (original) => {
commands: {
...real.commands,
vcsStashes: list,
vcsCommitFiles: files,
},
};
});
@@ -21,32 +15,15 @@ vi.mock("../changeOps", async (original) => ({
...(await original<typeof import("../changeOps")>()),
applyStash: apply,
}));
vi.mock("../logChanges", async (original) => ({
...(await original<typeof import("../logChanges")>()),
showChangesDiff: diff,
}));
import { StashesPanel } from "../CommitView";
import { useVcs } from "../store";
beforeEach(() => {
apply.mockReset();
diff.mockReset().mockResolvedValue(undefined);
files.mockReset().mockResolvedValue({
status: "ok",
data: [{ path: "src/app.ts", kind: "modified", oldPath: null }],
});
list.mockReset().mockImplementation((repo: string) =>
Promise.resolve({
status: "ok",
data: [
{
index: 0,
message: `On main: ${repo.endsWith("front") ? "First" : "Second"}`,
timeMs: 0,
id: `${repo}-stash`,
base: `${repo}-base`,
},
],
data: [{ index: 0, message: `On main: ${repo.endsWith("front") ? "First" : "Second"}`, timeMs: 0 }],
}),
);
useVcs.setState({ root: "/p", roots: ["/p/front", "/p/back"], repo: "/p/front" });
@@ -76,24 +53,9 @@ it("disables stale stash actions while another repository is loading", async ()
expect(screen.queryByText("front · 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" }] });
resolve({ status: "ok", data: [{ index: 0, message: "On main: New project", timeMs: 0 }] });
});
await screen.findByText("New project");
fireEvent.click(screen.getByRole("button", { name: "Apply Stash" }));
expect(apply).toHaveBeenCalledWith(0, false, "/other");
});
it("lists a stash's changed files and opens their diff instead of applying the stash", async () => {
render(<StashesPanel />);
const row = await screen.findByText("front · First");
// Double-clicking a stash expands it; it never applies the stash.
fireEvent.doubleClick(row);
expect(await screen.findByText("app.ts")).toBeInTheDocument();
expect(files).toHaveBeenCalledWith("/p/front", "/p/front-stash");
expect(apply).not.toHaveBeenCalled();
fireEvent.doubleClick(screen.getByText("app.ts"));
expect(diff).toHaveBeenCalledTimes(1);
const [[change], preview] = diff.mock.calls[0]!;
expect(preview).toBe(false);
expect(change).toMatchObject({ path: "src/app.ts", before: "/p/front-base", after: "/p/front-stash" });
});
+1 -1
Переглянути файл
@@ -48,7 +48,7 @@ import { VcsDialogHost } from "../dialogs";
import { showUnstashDialog } from "../changeOps";
import { useVcs } from "../store";
const stash = (index: number, message: string): Stash => ({ index, message, timeMs: null, id: `s${index}`, base: "b" });
const stash = (index: number, message: string): Stash => ({ index, message, timeMs: null });
beforeEach(() => {
mocks.stashes = new Map([
+1 -6
Переглянути файл
@@ -2377,10 +2377,5 @@
"Additional servers": "Additional servers",
"Run alongside the one above": "Run alongside the one above",
"The agent jar changed since you approved it. Approve the new jar before the next launch.": "The agent jar changed since you approved it. Approve the new jar before the next launch.",
"Approve new jar": "Approve new jar",
"Commit Message Generation": "Commit Message Generation",
"Instructions for Generate Commit Message with Agent": "Instructions for Generate Commit Message with Agent",
"Added to the agent's prompt, e.g. a commit format, issue key prefixes or the language to write in.": "Added to the agent's prompt, e.g. a commit format, issue key prefixes or the language to write in.",
"Use Conventional Commits (feat:, fix:, …) and start with the issue key if the branch has one.": "Use Conventional Commits (feat:, fix:, …) and start with the issue key if the branch has one.",
"Choose Include Path": "Choose Include Path"
"Approve new jar": "Approve new jar"
}
+1 -6
Переглянути файл
@@ -8755,10 +8755,5 @@
"Additional servers": "附加服务器",
"Run alongside the one above": "与上面选中的服务器同时运行",
"The agent jar changed since you approved it. Approve the new jar before the next launch.": "Agent jar 在授权后发生了变化。请先批准新的 jar,再启动应用。",
"Approve new jar": "批准新的 jar",
"Commit Message Generation": "提交信息生成",
"Instructions for Generate Commit Message with Agent": "用 Agent 生成提交信息时的要求",
"Added to the agent's prompt, e.g. a commit format, issue key prefixes or the language to write in.": "会加到 Agent 的提示词里,例如提交格式、问题编号前缀或使用的语言。",
"Use Conventional Commits (feat:, fix:, …) and start with the issue key if the branch has one.": "使用 Conventional Commits(feat:、fix: 等),分支带问题编号时以它开头。",
"Choose Include Path": "选择包含路径"
"Approve new jar": "批准新的 jar"
}
-4
Переглянути файл
@@ -59,8 +59,6 @@ export interface CommitSettingsValid {
disabledPluginChecks: string[];
/** Double-click opens the diff (`true`), the source file (`false`), or follows the interface (`null`). */
doubleClickOpensDiff: boolean | null;
/** Team conventions for Generate Commit Message with Agent, added to its prompt. */
agentInstructions: string;
}
export interface VcsSettingsValid {
@@ -276,7 +274,6 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
wrapAtMargin: false,
disabledPluginChecks: [],
doubleClickOpensDiff: null,
agentInstructions: "",
},
confirmation: {
onCreate: "ask",
@@ -436,7 +433,6 @@ export function validateVcs(raw: unknown): VcsSettingsValid {
wrapAtMargin: bool(c.wrapAtMargin, d.commit.wrapAtMargin),
disabledPluginChecks: strings(c.disabledPluginChecks, d.commit.disabledPluginChecks),
doubleClickOpensDiff: tri(c.doubleClickOpensDiff),
agentInstructions: text(c.agentInstructions, d.commit.agentInstructions),
},
confirmation: {
onCreate: oneOf(conf.onCreate, confirm, d.confirmation.onCreate),