diff --git a/crates/ide-host/src/ops/vcs/commands.rs b/crates/ide-host/src/ops/vcs/commands.rs index 090da084c..05429a721 100644 --- a/crates/ide-host/src/ops/vcs/commands.rs +++ b/crates/ide-host/src/ops/vcs/commands.rs @@ -1304,6 +1304,25 @@ pub async fn vcs_create_patch( .await } +/// The changes a commit with `options` would make in `repo`, as one patch (what Commit +/// commits: the index with the selection applied, partial files' chosen hunks only). +pub async fn vcs_pending_patch( + host: &Host, + window: &str, + repo: Option, + options: CommitOptions, +) -> IdeResult { + const MAX_PATCH: usize = 1 << 20; + let project = host.project(window)?; + blocking(move || { + project.with_repo_at(repo.as_deref(), |r| { + let changes = r.pending_changes(&options, MAX_PATCH, &|path| project.vcs_encoding(path, None))?; + Ok(changes.into_iter().filter_map(|c| c.diff).collect()) + }) + }) + .await +} + pub async fn vcs_patch_preview( host: &Host, window: &str, @@ -1663,6 +1682,9 @@ pub(crate) fn register(d: &mut Dispatcher) { d.add("vcs_create_patch", |c| async move { vcs_create_patch(&c.host, &c.window, c.arg("repo")?, c.arg("source")?).await }); + d.add("vcs_pending_patch", |c| async move { + vcs_pending_patch(&c.host, &c.window, c.arg("repo")?, c.arg("options")?).await + }); d.add("vcs_patch_preview", |c| async move { vcs_patch_preview(&c.host, &c.window, c.arg("repo")?, c.arg("patch")?).await }); diff --git a/e2e/commitMessageAgent.spec.ts b/e2e/commitMessageAgent.spec.ts index 18e532367..392aaf3cf 100644 --- a/e2e/commitMessageAgent.spec.ts +++ b/e2e/commitMessageAgent.spec.ts @@ -70,7 +70,7 @@ async function stubRepositoryAndAgent(page: Page, reply: string) { operation: null, }); h.vcs_status = () => changes; - h.vcs_create_patch = () => patch; + h.vcs_pending_patch = () => patch; h.vcs_log = () => [{ id: "1111111", summary: "Bump the wrapper" }]; h.agent_create = (args) => { const created = { ...task, id: "new", title: "Write a commit message", status: "starting", updatedMs: 9 }; @@ -131,9 +131,11 @@ test("the agent of the latest task writes the commit message of the included cha // Only the included file's diff, and the style of the latest commits, go to the agent. expect(created.prompt.text).toContain("+++ b/build.gradle.kts"); expect(created.prompt.text).toContain("- Bump the wrapper"); - expect(await ipcCalls(page, "vcs_create_patch")).toEqual([ - expect.objectContaining({ source: { from: "changes", paths: [`${ROOT}/build.gradle.kts`], reverse: false } }), - ]); + // What Commit would commit: the included file only (read again before the message is filled in). + const pending = await ipcCalls(page, "vcs_pending_patch"); + expect(pending.length).toBeGreaterThan(0); + for (const call of pending) + expect(call).toMatchObject({ options: expect.objectContaining({ stage: [`${ROOT}/build.gradle.kts`] }) }); // The task ran for the message only: it is gone again, and nothing was left to read. expect(await ipcCalls(page, "agent_delete")).toEqual([expect.objectContaining({ task: "new" })]); await expect(page.getByRole("alert")).toHaveCount(0); diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index e098e844e..1b1df7981 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -402,6 +402,7 @@ pub fn builder() -> tauri_specta::Builder { vcs::vcs_has_hook, vcs::vcs_merge_base, vcs::vcs_create_patch, + vcs::vcs_pending_patch, vcs::vcs_patch_preview, vcs::vcs_apply_patch, vcs::vcs_shelve, diff --git a/src-tauri/src/commands/vcs.rs b/src-tauri/src/commands/vcs.rs index 74cd1247c..57bfc7a97 100644 --- a/src-tauri/src/commands/vcs.rs +++ b/src-tauri/src/commands/vcs.rs @@ -803,6 +803,17 @@ pub async fn vcs_create_patch( ide_host::ops::vcs::vcs_create_patch(&state.host, window.label(), repo, source).await } +#[tauri::command] +#[specta::specta] +pub async fn vcs_pending_patch( + window: Window, + state: State<'_, AppState>, + repo: Option, + options: CommitOptions, +) -> IdeResult { + ide_host::ops::vcs::vcs_pending_patch(&state.host, window.label(), repo, options).await +} + #[tauri::command] #[specta::specta] pub async fn vcs_patch_preview( diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index f343c8b55..a463606a8 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -649,6 +649,7 @@ vcs_move_worktree trusted project_host bin vcs_open_external_log always project_host bindings async vcs_operation trusted project_host bindings async vcs_patch_preview trusted project_host bindings async +vcs_pending_patch trusted project_host bindings async vcs_rebase trusted project_host bindings async vcs_rebase_with trusted project_host bindings async vcs_remote trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index ebf29a7ae..96e295ca7 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -841,6 +841,7 @@ export const commands = { /** The best common ancestor of `a` and `b` (`git merge-base`), if any. */ vcsMergeBase: (repo: string | null, a: string, b: string) => typedError(__TAURI_INVOKE("vcs_merge_base", { repo, a, b })), vcsCreatePatch: (repo: string | null, source: PatchSource) => typedError(__TAURI_INVOKE("vcs_create_patch", { repo, source })), + vcsPendingPatch: (repo: string | null, options: CommitOptions) => typedError(__TAURI_INVOKE("vcs_pending_patch", { repo, options })), vcsPatchPreview: (repo: string | null, patch: string) => typedError(__TAURI_INVOKE("vcs_patch_preview", { repo, patch })), vcsApplyPatch: (repo: string | null, patch: string) => typedError(__TAURI_INVOKE("vcs_apply_patch", { repo, patch })), /** Shelve Changes: saves the changes of `paths` as a patch on the shelf and reverts them. */ diff --git a/src/features/agents/commitMessage.test.ts b/src/features/agents/commitMessage.test.ts index bd6915c96..3bba0a341 100644 --- a/src/features/agents/commitMessage.test.ts +++ b/src/features/agents/commitMessage.test.ts @@ -20,6 +20,7 @@ const backend = vi.hoisted(() => ({ notify: vi.fn(), changes: vi.fn(), setMessage: vi.fn(), + revision: vi.fn(), })); vi.mock("@/platform/ipc", async (original) => ({ @@ -35,7 +36,12 @@ vi.mock("@/platform/ipc", async (original) => ({ vi.mock("@/workbench/contributions", async (original) => ({ ...(await original()), notifications: () => ({ notify: backend.notify }), - maybeCommitService: () => ({ changes: backend.changes, setMessage: backend.setMessage, selection: vi.fn() }), + maybeCommitService: () => ({ + changes: backend.changes, + setMessage: backend.setMessage, + revision: backend.revision, + selection: vi.fn(), + }), })); const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data }); @@ -283,6 +289,7 @@ describe("generateCommitMessage", () => { vi.clearAllMocks(); backend.changes.mockResolvedValue(changes); backend.setMessage.mockReturnValue(true); + backend.revision.mockReturnValue(changes.revision); backend.log.mockImplementation(() => ok([{ summary: "feat: earlier" }])); backend.cancel.mockImplementation(() => ok(null)); backend.remove.mockImplementation(() => ok(null)); @@ -382,6 +389,14 @@ describe("generateCommitMessage", () => { expect(backend.remove).toHaveBeenCalledWith("new", false); }); + it("does not fill in a message for changes edited in the files while the agent worked", async () => { + createdTask("ready"); + backend.changes.mockResolvedValueOnce(changes).mockResolvedValue({ ...changes, patch: changes.patch + "+more\n" }); + await generateCommitMessage(); + expect(backend.setMessage).not.toHaveBeenCalled(); + expect(notified()).toEqual([expect.objectContaining({ level: "info", title: "Commit message not replaced" })]); + }); + it("runs once at a time", async () => { createdTask("ready"); await Promise.all([generateCommitMessage(), generateCommitMessage()]); diff --git a/src/features/agents/commitMessage.ts b/src/features/agents/commitMessage.ts index 0e8d1aa77..2d2c66387 100644 --- a/src/features/agents/commitMessage.ts +++ b/src/features/agents/commitMessage.ts @@ -273,7 +273,15 @@ async function generate(): Promise { await turnEnd(created.id); const message = commitMessageOf(replyOf(await call(commands.agentEntries(created.id, null)))); if (!message) throw new Error(tx("The agent did not reply with a commit message")); - if (!service.setMessage(changes.revision, message)) { + // The files may have been edited since without touching the draft: the message must + // still describe what would be committed. + const unchanged = async () => { + if (service.revision() !== changes.revision) return null; + const now = await service.changes().catch(() => null); + return now && now.patch === changes.patch ? now.revision : null; + }; + const at = await unchanged(); + if (at === null || !service.setMessage(at, message)) { notify({ level: "info", title: "Commit message not replaced", diff --git a/src/features/vcs/__tests__/pluginCommit.test.ts b/src/features/vcs/__tests__/pluginCommit.test.ts index 614e38ce9..fdb5e9f0f 100644 --- a/src/features/vcs/__tests__/pluginCommit.test.ts +++ b/src/features/vcs/__tests__/pluginCommit.test.ts @@ -13,7 +13,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => { commands: { ...real.commands, vcsCommit: commit.mockImplementation(() => ok("commit1")), - vcsCreatePatch: createPatch.mockImplementation(() => ok("diff --git a/p b/p\n")), + vcsPendingPatch: createPatch.mockImplementation(() => ok("diff --git a/p b/p\n")), }, }; }); @@ -106,9 +106,9 @@ describe("the commit plugins see", () => { expect(maybeCommitService()!.setMessage(draftRevision(), "x")).toBe(false); }); - it("reads the diff of the included files only, at the revision of the draft", async () => { + it("reads the diff of what Commit would commit, at the revision of the draft", async () => { const changes = (await maybeCommitService()!.changes())!; - expect(createPatch).toHaveBeenCalledExactlyOnceWith("/p", { from: "changes", paths: ["/p/a.ts"], reverse: false }); + expect(createPatch).toHaveBeenCalledExactlyOnceWith("/p", expect.objectContaining({ stage: ["/p/a.ts"] })); expect(changes).toEqual({ revision: draftRevision(), roots: ["/p"], patch: "diff --git a/p b/p\n" }); expect(maybeCommitService()!.setMessage(changes.revision, "generated")).toBe(true); }); @@ -120,8 +120,8 @@ describe("the commit plugins see", () => { useCommit.setState({ checks: new Map() }); const changes = (await maybeCommitService()!.changes())!; expect(createPatch.mock.calls).toEqual([ - ["/w/b", { from: "changes", paths: ["/w/b/Bar.java"], reverse: false }], - ["/w/a", { from: "changes", paths: ["/w/a/Foo.java"], reverse: false }], + ["/w/b", expect.objectContaining({ stage: ["/w/b/Bar.java"] })], + ["/w/a", expect.objectContaining({ stage: ["/w/a/Foo.java"] })], ]); expect(changes.roots).toEqual(["/w/b", "/w/a"]); expect(changes.patch).toBe("diff --git a/p b/p\n\ndiff --git a/p b/p\n"); diff --git a/src/features/vcs/commitSelection.ts b/src/features/vcs/commitSelection.ts index fa89785b7..47cbd940f 100644 --- a/src/features/vcs/commitSelection.ts +++ b/src/features/vcs/commitSelection.ts @@ -19,7 +19,7 @@ import { useChangelists } from "./changelists"; import { inclusionChecks, stagingAreaOn } from "./staging"; import { useCommit } from "./commitStore"; import { hunkKeys } from "./hunks"; -import { baseName, rootOf, stripSlash } from "./model"; +import { baseName, rootOf } from "./model"; import { saveAll } from "./ops"; import { currentRepo, refreshNow, useVcs } from "./store"; @@ -124,35 +124,29 @@ async function pendingSelection(): Promise { return { ...selection, revision: rev }; } -/** The included files' local changes, one patch per repository. */ +/** What Commit would commit now, one patch per repository: the staged or chosen blocks only. */ async function pendingChanges(): Promise { if (!useVcs.getState().root) return null; await saveAll(); await refreshNow(); - const { root, roots } = useVcs.getState(); - if (!root) return null; + if (!useVcs.getState().root) return null; const rev = revision; - const { included } = currentPlan(); - const repos = commitRepos(included, roots, currentRepo()); + const plan = currentPlan(); + if (!plan.included.length) return { revision: rev, roots: [], patch: "" }; + const selection = await selectionOf(plan); const patches: string[] = []; - for (const repo of repos) { - const paths = included - .map((f) => stripSlash(f.path)) - .filter((path) => { - const owner = rootOf(path, roots); - return owner === null ? repos.length === 1 : owner === repo; - }); - if (!paths.length) continue; - const patch = await call(commands.vcsCreatePatch(repo ?? root, { from: "changes", paths, reverse: false })); + for (const { root, options } of selection.repositories) { + const patch = await call(commands.vcsPendingPatch(root, options)); if (patch.trim()) patches.push(patch); } - return { revision: rev, roots: repos.map((r) => r ?? root), patch: patches.join("\n") }; + return { revision: rev, roots: selection.repositories.map((r) => r.root), patch: patches.join("\n") }; } export function provideCommit(): () => void { provideCommitService({ selection: pendingSelection, changes: pendingChanges, + revision: draftRevision, setMessage: (rev, message) => { if (rev !== revision || !useVcs.getState().root) return false; useCommit.setState({ message }); diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index f5e7ffe99..c4e9a79f9 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -880,6 +880,8 @@ export interface CommitService { * `null` without a repository. */ changes(): Promise; + /** The draft's current revision: bumped whenever the message, Amend or the inclusion changes. */ + revision(): number; /** Replaces the message if the draft is still at `revision`; false when it changed. */ setMessage(revision: number, message: string): boolean; }