From 1531220eea30c015048a7326406ed248fadae69e Mon Sep 17 00:00:00 2001 From: rohitkumardanda Date: Mon, 16 Nov 2026 17:33:07 +0000 Subject: [PATCH] feat(agents): generate the commit message with the coding agent (#3766) Adds Generate Commit Message with Agent above the commit message (Commit tool window and Commit dialog). It sends the included changes (trimmed to a budget) and the last 5 commit subjects to the agent of the project's latest task, on that task's model and in a mode that asks before editing or running anything, as a short quiet task deleted afterwards. The reply replaces the message only if the draft and the included files are unchanged; otherwise a notification says so. Without an installed agent, a notification points to Settings > Agents. Co-authored-by: rohitdanda <10144914+rohitdanda@users.noreply.github.com> --- e2e/commitMessageAgent.spec.ts | 155 +++++++ src/features/agents/commitMessage.test.ts | 386 ++++++++++++++++++ src/features/agents/commitMessage.ts | 294 +++++++++++++ src/features/agents/index.ts | 23 ++ src/features/agents/store.ts | 13 +- .../vcs/__tests__/pluginCommit.test.ts | 36 +- src/features/vcs/commitSelection.ts | 35 +- src/platform/locales/text/en.json | 19 +- src/platform/locales/text/zh.json | 19 +- src/workbench/contributions.ts | 14 + 10 files changed, 987 insertions(+), 7 deletions(-) create mode 100644 e2e/commitMessageAgent.spec.ts create mode 100644 src/features/agents/commitMessage.test.ts create mode 100644 src/features/agents/commitMessage.ts diff --git a/e2e/commitMessageAgent.spec.ts b/e2e/commitMessageAgent.spec.ts new file mode 100644 index 0000000000..18e5323670 --- /dev/null +++ b/e2e/commitMessageAgent.spec.ts @@ -0,0 +1,155 @@ +/** + * Generate Commit Message with Agent: the button above the commit message has the agent of the + * latest task write the message. The agent and git are stubbed at the IPC layer. + */ +import type { Page } from "@playwright/test"; +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +const ROOT = "/dev/acme-api"; +const PATCH = + "diff --git a/build.gradle.kts b/build.gradle.kts\n--- a/build.gradle.kts\n+++ b/build.gradle.kts\n@@ -1 +1 @@\n-old\n+new\n"; + +const option = (category: string, values: string[], current: string) => ({ + id: category, + name: category, + description: null, + category, + current, + values: values.map((value) => ({ value, name: value, description: null })), + via: "option" as const, +}); + +const TASK = { + id: "t1", + title: "Update the build", + status: "ready" as const, + isolation: "local" as const, + provider: "claude", + model: null, + cwd: ROOT, + branch: null, + base: null, + baseCommit: null, + error: null, + createdMs: 0, + updatedMs: 5, + // The user's tasks approve everything; the one that reads the diff must not. + config: [ + option("model", ["fast", "smart"], "smart"), + option("mode", ["default", "bypassPermissions"], "bypassPermissions"), + ], + commands: [], + usage: null, + queue: [], +}; + +async function stubRepositoryAndAgent(page: Page, reply: string) { + await stubDesktop(page); + await page.evaluate( + async ({ root, patch, task, reply }) => { + const changes = [ + { + path: `${root}/build.gradle.kts`, + relPath: "build.gradle.kts", + staged: null, + unstaged: "modified", + renamedFrom: null, + }, + { path: `${root}/notes.txt`, relPath: "notes.txt", staged: null, unstaged: "untracked", renamedFrom: null }, + ]; + const storePath = "/src/features/agents/store.ts"; + const agents = await import(/* @vite-ignore */ storePath); + const h = window.__ipc.handlers; + h.vcs_roots = () => [{ root, operation: null, head: "main", headCommit: "1111111" }]; + h.vcs_branch_info = () => ({ + head: "main", + headCommit: "1111111", + upstream: null, + ahead: 0, + behind: 0, + operation: null, + }); + h.vcs_status = () => changes; + h.vcs_create_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 }; + const request = args.request as { provider: string }; + // The agent ends its turn a moment later, as an event of the task would say. + setTimeout(() => { + agents.useAgents.setState((s: { tasks: Map }) => ({ + tasks: new Map(s.tasks).set("new", { ...created, provider: request.provider, status: "ready" }), + })); + }, 300); + return created; + }; + h.agent_entries = () => [ + { type: "user", text: "Write a commit message", attachments: [] }, + { type: "agent", text: reply }, + ]; + h.agent_cancel = () => null; + h.agent_delete = () => null; + agents.useAgents.setState({ + loaded: true, + error: null, + providers: [{ id: "claude", name: "Claude", installed: true, config: [] }], + tasks: new Map([[task.id, task]]), + unread: new Set(), + }); + const vcsModule = "/src/features/vcs/store.ts"; + const { useVcs, refreshNow } = await import(/* @vite-ignore */ vcsModule); + useVcs.setState({ available: true, root, repo: root, branchesLoaded: false, stashesLoaded: false }); + await refreshNow(); + }, + { root: ROOT, patch: PATCH, task: TASK, reply }, + ); +} + +test("the agent of the latest task writes the commit message of the included changes", async ({ workbench: page }) => { + await stubRepositoryAndAgent(page, "```\nUpdate the Gradle build\n\nBump the Kotlin plugin.\n```"); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + const message = panel.getByRole("textbox", { name: "Commit message" }); + await expect(message).toHaveValue(""); + + await panel.getByRole("button", { name: "Generate Commit Message with Agent" }).click(); + + await expect(message).toHaveValue("Update the Gradle build\n\nBump the Kotlin plugin."); + const [request] = await ipcCalls(page, "agent_create"); + const created = request!.request as { + provider: string; + isolation: string; + config: unknown; + prompt: { text: string }; + }; + expect(created).toMatchObject({ provider: "claude", isolation: "local" }); + // The model of the latest task, but in the mode that asks before editing or running anything. + expect(created.config).toEqual([ + { id: "model", value: "smart" }, + { id: "mode", value: "default" }, + ]); + // 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 } }), + ]); + // 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); +}); + +test("a message typed while the agent works is not overwritten", async ({ workbench: page }) => { + await stubRepositoryAndAgent(page, "Update the Gradle build"); + await page.keyboard.press("Meta+k"); + const panel = page.getByRole("region", { name: "Commit", exact: true }); + const message = panel.getByRole("textbox", { name: "Commit message" }); + + await panel.getByRole("button", { name: "Generate Commit Message with Agent" }).click(); + // Once the agent has the changes, the draft they were read for is fixed. + await expect.poll(async () => (await ipcCalls(page, "agent_create")).length).toBe(1); + await message.fill("My own message"); + + await expect(page.getByText("Commit message not replaced")).toBeVisible(); + await expect(message).toHaveValue("My own message"); +}); diff --git a/src/features/agents/commitMessage.test.ts b/src/features/agents/commitMessage.test.ts new file mode 100644 index 0000000000..ce755ad47f --- /dev/null +++ b/src/features/agents/commitMessage.test.ts @@ -0,0 +1,386 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { AgentConfigOption, AgentEntry, AgentProvider, AgentTask } from "@/bindings"; +import { + askingChoices, + commitMessageOf, + commitMessagePrompt, + fitPatch, + generateCommitMessage, + pickAgent, + replyOf, +} from "./commitMessage"; +import { useAgents, type Draft } from "./store"; + +const backend = vi.hoisted(() => ({ + create: vi.fn(), + entries: vi.fn(), + cancel: vi.fn(), + remove: vi.fn(), + log: vi.fn(), + notify: vi.fn(), + changes: vi.fn(), + setMessage: vi.fn(), +})); + +vi.mock("@/platform/ipc", async (original) => ({ + ...(await original()), + commands: { + agentCreate: backend.create, + agentEntries: backend.entries, + agentCancel: backend.cancel, + agentDelete: backend.remove, + vcsLog: backend.log, + }, +})); +vi.mock("@/workbench/contributions", async (original) => ({ + ...(await original()), + notifications: () => ({ notify: backend.notify }), + maybeCommitService: () => ({ changes: backend.changes, setMessage: backend.setMessage, selection: vi.fn() }), +})); + +const ok = (data: unknown) => Promise.resolve({ status: "ok" as const, data }); + +const task = (id: string, provider: string, patch: Partial = {}): AgentTask => ({ + id, + title: id, + provider, + model: null, + status: "ready", + isolation: "local", + cwd: "/p", + branch: null, + base: null, + baseCommit: null, + error: null, + createdMs: 0, + updatedMs: 0, + config: [], + commands: [], + usage: null, + queue: [], + ...patch, +}); + +const modelOption = (current: string | null): AgentConfigOption => ({ + id: "model", + name: "Model", + description: null, + category: "model", + current, + values: ["fast", "smart"].map((value) => ({ value, name: value, description: null })), + via: "option", +}); + +const provider = (id: string, installed = true, config: AgentConfigOption[] = []) => + ({ id, name: id, installed, config }) as AgentProvider; + +const draft = (id: string): Draft => ({ provider: id, config: {}, isolation: "local", base: null }); + +const PATCH = "diff --git a/a.ts b/a.ts\n--- a/a.ts\n+++ b/a.ts\n@@ -1 +1 @@\n-old\n+new\n"; + +describe("fitPatch", () => { + it("keeps a patch that fits", () => { + expect(fitPatch(PATCH, 1_000)).toBe(PATCH); + }); + + it("cuts a long file short and names the files that no longer fit", () => { + const file = (name: string, lines: number) => + `diff --git a/${name} b/${name}\n@@ -1 +1 @@\n${"+line\n".repeat(lines)}`; + const fitted = fitPatch([file("big.ts", 600), file("later.ts", 600), file("last.ts", 600)].join(""), 3_000, 2_000); + expect(fitted).toContain("diff --git a/big.ts b/big.ts"); + expect(fitted).toContain("rest of this file's diff omitted"); + expect(fitted).toContain("Diff omitted for: last.ts"); + expect(fitted.length).toBeLessThan(3_200); + }); +}); + +describe("commitMessagePrompt", () => { + it("titles the task, states the limit and the style, and carries the changes", () => { + const prompt = commitMessagePrompt(PATCH, 50, ["feat: add x", "fix: y"]); + expect(prompt.split("\n")[0]).toBe("Write a commit message"); + expect(prompt).toContain("at most 50 characters"); + expect(prompt).toContain("- feat: add x\n- fix: y"); + expect(prompt).toContain(`\n${PATCH.trimEnd()}\n`); + }); + + it("leaves out the style hint without earlier commits", () => { + expect(commitMessagePrompt(PATCH, 72, [])).not.toContain("latest commits"); + }); +}); + +describe("commitMessageOf", () => { + it("keeps a plain message, subject and body", () => { + expect(commitMessageOf("Fix crash on save\n\nThe buffer was freed twice.\n")).toBe( + "Fix crash on save\n\nThe buffer was freed twice.", + ); + }); + + it("takes the text out of a code fence", () => { + expect(commitMessageOf("```\nAdd a button\n```")).toBe("Add a button"); + expect(commitMessageOf("Here it is:\n\n```text\nAdd a button\n\nBody.\n```\n\nAnything else?")).toBe( + "Add a button\n\nBody.", + ); + }); + + it("drops a label and wrapping quotes", () => { + expect(commitMessageOf("Commit message: Add a button")).toBe("Add a button"); + expect(commitMessageOf('"Add a button"')).toBe("Add a button"); + expect(commitMessageOf("`Add a button`")).toBe("Add a button"); + }); + + it("keeps a subject that merely starts with a word like a label", () => { + expect(commitMessageOf("Message: show the error text")).toBe("Message: show the error text"); + }); + + it("normalises line endings and blank lines", () => { + expect(commitMessageOf("Add a button \r\n\r\n\r\n\r\nBody.")).toBe("Add a button\n\nBody."); + }); + + it("is empty for a reply without text", () => { + expect(commitMessageOf(" \n")).toBe(""); + }); +}); + +describe("replyOf", () => { + const user: AgentEntry = { type: "user", text: "q", attachments: [] }; + const agent = (text: string): AgentEntry => ({ type: "agent", text }); + + it("is the last message the agent wrote after the last question", () => { + const entries = [ + user, + agent("old"), + user, + agent("Looking…"), + { type: "thought", text: "hm" } as AgentEntry, + agent("Fix it"), + ]; + expect(replyOf(entries)).toBe("Fix it"); + }); + + it("is empty when the agent wrote nothing yet", () => { + expect(replyOf([agent("old"), user])).toBe(""); + }); +}); + +describe("askingChoices", () => { + const option = (category: string, id: string, values: string[], current: string): AgentConfigOption => ({ + id, + name: id, + description: null, + category, + current, + values: values.map((value) => ({ value, name: value, description: null })), + via: "option", + }); + + it("moves a mode that approves everything to the one that asks", () => { + const claude = option("mode", "mode", ["acceptEdits", "plan", "bypassPermissions", "default"], "bypassPermissions"); + expect(askingChoices([claude])).toEqual([{ id: "mode", value: "default" }]); + }); + + it("takes the read-only mode of an agent that has no default one", () => { + const codex = option("mode", "mode", ["auto", "full-access", "read-only"], "full-access"); + expect(askingChoices([codex])).toEqual([{ id: "mode", value: "read-only" }]); + }); + + it("turns allow-all permissions and bypassed approvals off", () => { + const options = [ + option("permissions", "perm", ["on", "off"], "on"), + option("approval", "openidea.cursor.approval", ["ask", "bypass"], "bypass"), + ]; + expect(askingChoices(options)).toEqual([ + { id: "perm", value: "off" }, + { id: "openidea.cursor.approval", value: "ask" }, + ]); + }); + + it("leaves an agent without such settings alone", () => { + expect(askingChoices([modelOption("fast")])).toEqual([]); + expect(askingChoices([option("mode", "mode", ["bypassPermissions", "acceptEdits"], "acceptEdits")])).toEqual([]); + }); +}); + +describe("pickAgent", () => { + it("is the agent of the latest task, on its model", () => { + const tasks = [ + task("a", "codex", { updatedMs: 1 }), + task("b", "claude", { updatedMs: 5, config: [modelOption("smart")] }), + task("c", "gemini", { updatedMs: 9, status: "archived" }), + ]; + const providers = ["codex", "claude", "gemini"].map((id) => provider(id)); + expect(pickAgent(tasks, providers, draft("codex"))).toEqual({ + provider: "claude", + config: [{ id: "model", value: "smart" }], + }); + }); + + it("asks for approvals even when the latest task approves everything", () => { + const mode: AgentConfigOption = { + id: "mode", + name: "Mode", + description: null, + category: "mode", + current: "bypassPermissions", + values: ["default", "bypassPermissions"].map((value) => ({ value, name: value, description: null })), + via: "mode", + }; + const tasks = [task("b", "claude", { updatedMs: 5, config: [modelOption("smart"), mode] })]; + expect(pickAgent(tasks, [provider("claude")], draft("claude"))?.config).toEqual([ + { id: "model", value: "smart" }, + { id: "mode", value: "default" }, + ]); + }); + + it("passes over a task whose agent is not installed", () => { + const tasks = [task("a", "codex", { updatedMs: 1 }), task("b", "claude", { updatedMs: 5 })]; + const providers = [provider("codex"), provider("claude", false)]; + expect(pickAgent(tasks, providers, draft("claude"))?.provider).toBe("codex"); + }); + + it("falls back to the New Task page's agent and its model", () => { + const providers = [provider("codex"), provider("claude", true, [modelOption("fast")])]; + expect(pickAgent([], providers, draft("claude"))).toEqual({ + provider: "claude", + config: [{ id: "model", value: "fast" }], + }); + }); + + it("takes any installed agent when the selected one is missing, and none without one", () => { + expect(pickAgent([], [provider("claude", false), provider("codex")], draft("claude"))).toEqual({ + provider: "codex", + config: [], + }); + expect(pickAgent([], [provider("claude", false)], draft("claude"))).toBeNull(); + }); +}); + +describe("generateCommitMessage", () => { + const changes = { revision: 3, roots: ["/p"], patch: PATCH }; + const notified = () => backend.notify.mock.calls.map(([n]) => n as { level: string; title: string; body?: string }); + + /** The created task ends its turn with `status` right after it is created. */ + function createdTask(status: AgentTask["status"], reply = "Fix the thing\n\nBecause.") { + backend.create.mockImplementation((request: { provider: string }) => { + setTimeout(() => { + useAgents.setState((s) => ({ tasks: new Map(s.tasks).set("new", task("new", request.provider, { status })) })); + }, 0); + return ok(task("new", request.provider, { status: "starting" })); + }); + backend.entries.mockImplementation(() => + ok([ + { type: "user", text: "q", attachments: [] }, + { type: "agent", text: reply }, + ]), + ); + } + + beforeEach(() => { + vi.clearAllMocks(); + backend.changes.mockResolvedValue(changes); + backend.setMessage.mockReturnValue(true); + backend.log.mockImplementation(() => ok([{ summary: "feat: earlier" }])); + backend.cancel.mockImplementation(() => ok(null)); + backend.remove.mockImplementation(() => ok(null)); + useAgents.setState({ + providers: [provider("claude")], + tasks: new Map([["t1", task("t1", "claude", { updatedMs: 4, config: [modelOption("smart")] })]]), + unread: new Set(), + draft: draft("claude"), + }); + }); + + it("asks the agent of the latest task, fills the commit field and removes the task", async () => { + createdTask("ready", "```\nFix the thing\n\nBecause.\n```"); + await generateCommitMessage(); + + expect(backend.create).toHaveBeenCalledOnce(); + const request = backend.create.mock.calls[0]![0] as { + provider: string; + config: unknown; + isolation: string; + prompt: { text: string }; + }; + expect(request).toMatchObject({ + provider: "claude", + config: [{ id: "model", value: "smart" }], + isolation: "local", + }); + expect(request.prompt.text).toContain(PATCH.trimEnd()); + expect(request.prompt.text).toContain("- feat: earlier"); + expect(backend.setMessage).toHaveBeenCalledWith(3, "Fix the thing\n\nBecause."); + expect(backend.remove).toHaveBeenCalledWith("new", false); + expect(backend.cancel).not.toHaveBeenCalled(); + expect(notified()).toEqual([]); + expect(useAgents.getState().unread.has("new")).toBe(false); + }); + + it("does not bother the agent when nothing is included", async () => { + backend.changes.mockResolvedValue({ ...changes, patch: " \n" }); + await generateCommitMessage(); + expect(backend.create).not.toHaveBeenCalled(); + expect(notified()).toEqual([expect.objectContaining({ level: "info", title: "No changes to describe" })]); + }); + + it("points to the settings when no agent is installed", async () => { + useAgents.setState({ providers: [], tasks: new Map() }); + await generateCommitMessage(); + expect(backend.create).not.toHaveBeenCalled(); + expect(notified()).toEqual([expect.objectContaining({ level: "warning", title: "No coding agent available" })]); + }); + + it("stops and removes a task that asks for permission", async () => { + createdTask("needsInput"); + await generateCommitMessage(); + expect(backend.setMessage).not.toHaveBeenCalled(); + expect(backend.cancel).toHaveBeenCalledWith("new", null); + expect(backend.remove).toHaveBeenCalledWith("new", false); + expect(notified()).toEqual([ + expect.objectContaining({ + level: "error", + title: "Couldn't generate the commit message", + body: "The agent asked for permission to continue", + }), + ]); + }); + + it("reports a failed task with the reason it gave", async () => { + backend.create.mockImplementation((request: { provider: string }) => { + setTimeout(() => { + useAgents.setState((s) => ({ + tasks: new Map(s.tasks).set( + "new", + task("new", request.provider, { status: "failed", error: "not signed in" }), + ), + })); + }, 0); + return ok(task("new", request.provider, { status: "starting" })); + }); + await generateCommitMessage(); + expect(notified()).toEqual([expect.objectContaining({ level: "error", body: "not signed in" })]); + expect(backend.remove).toHaveBeenCalledWith("new", false); + }); + + it("reports a reply without a commit message", async () => { + createdTask("ready", " "); + await generateCommitMessage(); + expect(backend.setMessage).not.toHaveBeenCalled(); + expect(notified()).toEqual([ + expect.objectContaining({ level: "error", body: "The agent did not reply with a commit message" }), + ]); + }); + + it("does not overwrite a message or inclusion edited while the agent worked", async () => { + createdTask("ready"); + backend.setMessage.mockReturnValue(false); + await generateCommitMessage(); + expect(notified()).toEqual([expect.objectContaining({ level: "info", title: "Commit message not replaced" })]); + expect(backend.remove).toHaveBeenCalledWith("new", false); + }); + + it("runs once at a time", async () => { + createdTask("ready"); + await Promise.all([generateCommitMessage(), generateCommitMessage()]); + expect(backend.create).toHaveBeenCalledOnce(); + expect(backend.setMessage).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/features/agents/commitMessage.ts b/src/features/agents/commitMessage.ts new file mode 100644 index 0000000000..f2f4be9e25 --- /dev/null +++ b/src/features/agents/commitMessage.ts @@ -0,0 +1,294 @@ +/** + * Generate Commit Message with Agent: the coding agent the user works with reads the + * changes about to be committed and writes their message. It runs as a short task that + * is deleted once the message is in the commit field. + */ +import type { AgentConfigChoice, AgentConfigOption, AgentEntry, AgentProvider, AgentTask } from "@/bindings"; +import { executeAction } from "@/platform/actions"; +import { tx } from "@/platform/i18n"; +import { call, commands } from "@/platform/ipc"; +import { workflowSettings } from "@/platform/workflowSettings"; +import { maybeCommitService, notifications, type NotificationService } from "@/workbench/contributions"; +import { REGISTRY_PAGE, isBusy } from "./model"; +import { modeIcon, modeOption } from "./composerModel"; +import { cancelTask, deleteTask, draftConfig, runQuietly, useAgents, type Draft } from "./store"; + +const PATCH_BUDGET = 48_000; +const FILE_BUDGET = 8_000; +const RECENT_SUBJECTS = 5; +const TIMEOUT_MS = 180_000; +const NOTIFICATION_KEY = "agents.commitMessage"; + +/** + * `patch` within `budget` characters: files too long for `perFile` keep their beginning, + * and the files that no longer fit are listed by name. + */ +export function fitPatch(patch: string, budget = PATCH_BUDGET, perFile = FILE_BUDGET): string { + if (patch.length <= budget) return patch; + let left = budget; + let out = ""; + const omitted: string[] = []; + for (const file of patch.split(/^(?=diff --git )/m)) { + const head = file.split("\n", 1)[0]!; + if (file.length <= perFile && file.length <= left) { + out += file; + left -= file.length; + } else if (left >= 1_000) { + const part = file.slice(0, Math.min(perFile, left)).replace(/\n[^\n]*$/, ""); + out += `${part}\n… (rest of this file's diff omitted)\n`; + left -= part.length; + } else { + omitted.push(/ b\/(.*)$/.exec(head)?.[1] ?? head); + } + } + return omitted.length ? `${out}\nDiff omitted for: ${omitted.join(", ")}\n` : out; +} + +export function commitMessagePrompt(patch: string, subjectLimit: number, recentSubjects: readonly string[]): string { + const lines = [ + "Write a commit message", + "", + "Write the commit message for the changes below, which are about to be committed:", + `- A subject line of at most ${subjectLimit} characters, in the imperative mood ("Add …", "Fix …"), without a trailing period.`, + "- Only when the subject can't say it all: a blank line and a short body on what changed and why.", + "- 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.", + ]; + if (recentSubjects.length) { + lines.push( + "", + "Subjects of the latest commits here, for the style to follow:", + ...recentSubjects.map((s) => `- ${s}`), + ); + } + lines.push("", "", fitPatch(patch).trimEnd(), ""); + return lines.join("\n"); +} + +/** The commit message in an agent's reply, without the quotes, fence or label it may have wrapped around it. */ +export function commitMessageOf(reply: string): string { + let text = reply.replace(/\r\n?/g, "\n").trim(); + const fenced = /^```[^\n]*\n([\s\S]*?)\n```/m.exec(text); + if (fenced) text = fenced[1]!.trim(); + text = text.replace(/^commit message\s*:\s*/i, ""); + const quote = text[0]; + if (text.length > 1 && (quote === '"' || quote === "'" || quote === "`") && text.endsWith(quote)) { + text = text.slice(1, -1); + } + return text + .split("\n") + .map((l) => l.trimEnd()) + .join("\n") + .replace(/\n{3,}/g, "\n\n") + .trim(); +} + +/** The agent's answer to the last message: its final reply. */ +export function replyOf(entries: readonly AgentEntry[]): string { + for (let i = entries.length - 1; i >= 0; i--) { + const entry = entries[i]!; + if (entry.type === "user") break; + if (entry.type === "agent" && entry.text.trim()) return entry.text; + } + return ""; +} + +export interface CommitAgent { + provider: string; + config: AgentConfigChoice[]; +} + +/** The model of `options` as a choice for a new task, when it is one the agent offers. */ +function modelChoice(options: readonly AgentConfigOption[]): AgentConfigChoice[] { + const model = options.find((o) => o.category === "model"); + return model?.current && model.values.some((v) => v.value === model.current) + ? [{ id: model.id, value: model.current }] + : []; +} + +/** + * The settings that make the agent ask before it edits or runs anything. New tasks start + * in the mode that approves everything unless the user chose otherwise, and the changes + * the agent reads here are text from the repository: they must not be able to run commands. + */ +export function askingChoices(options: readonly AgentConfigOption[]): AgentConfigChoice[] { + const out: AgentConfigChoice[] = []; + const mode = modeOption(options); + if (mode) { + const asking = mode.values.filter((v) => ["lock", "eye"].includes(modeIcon(v.value))); + const value = ["default", "ask"].map((p) => asking.find((v) => v.value === p)).find(Boolean) ?? asking[0]; + if (value) out.push({ id: mode.id, value: value.value }); + } + const permissions = options.find((o) => o.category === "permissions"); + const off = permissions?.values.find((v) => /^(off|false)$/i.test(v.value)); + if (permissions && off) out.push({ id: permissions.id, value: off.value }); + const approval = options.find((o) => o.category === "approval"); + if (approval?.values.some((v) => v.value === "ask")) out.push({ id: approval.id, value: "ask" }); + return out; +} + +const choicesFor = (options: readonly AgentConfigOption[]) => [...modelChoice(options), ...askingChoices(options)]; + +/** + * The agent that wrote the code: the one of the project's latest task, on the model it + * ran with. Without a task, the one the New Task page has selected. + */ +export function pickAgent( + tasks: Iterable, + providers: readonly AgentProvider[], + draft: Draft, +): CommitAgent | null { + const installed = providers.filter((p) => p.installed); + const latest = [...tasks] + .filter((t) => t.status !== "archived" && installed.some((p) => p.id === t.provider)) + .sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0))[0]; + if (latest) return { provider: latest.provider, config: choicesFor(latest.config) }; + const provider = installed.find((p) => p.id === draft.provider) ?? installed[0]; + if (!provider) return null; + return { + provider: provider.id, + config: choicesFor(provider.id === draft.provider ? draftConfig(provider, draft) : provider.config), + }; +} + +/** Resolves when the task's turn ends; rejects when it can't produce an answer. */ +function turnEnd(task: string): Promise { + return new Promise((resolve, reject) => { + const off = useAgents.subscribe(check); + const timer = setTimeout(() => settle(tx("The agent did not answer in time")), TIMEOUT_MS); + function settle(error?: string) { + off(); + clearTimeout(timer); + if (error === undefined) resolve(); + else reject(new Error(error)); + } + function check() { + const current = useAgents.getState().tasks.get(task); + if (!current) return settle(tx("The agent task was removed")); + switch (current.status) { + case "ready": + return settle(); + case "failed": + return settle(current.error ?? tx("The agent stopped")); + case "limited": + return settle(tx("The agent's usage limit was reached")); + case "needsInput": + return settle(tx("The agent asked for permission to continue")); + case "archived": + return settle(tx("The agent task was archived")); + } + } + check(); + }); +} + +async function recentSubjects(repo: string | undefined): Promise { + try { + const commits = await call( + commands.vcsLog(repo ?? null, { + branch: "HEAD", + path: null, + author: null, + text: null, + range: null, + skip: 0, + limit: RECENT_SUBJECTS, + }), + ); + return commits.map((c) => c.summary).filter(Boolean); + } catch { + return []; + } +} + +function notify(n: Omit[0], "key" | "group" | "userInitiated">) { + notifications().notify({ ...n, key: NOTIFICATION_KEY, group: "vcs", userInitiated: true }); +} + +let running = false; + +/** Asks the agent for the message of the commit being prepared and puts it in the commit field. */ +export async function generateCommitMessage(): Promise { + if (running) return; + running = true; + try { + await generate(); + } finally { + running = false; + } +} + +async function generate(): Promise { + const service = maybeCommitService(); + if (!service) return; + let changes; + try { + changes = await service.changes(); + } catch (e) { + notify({ level: "error", title: "Couldn't read the changes", body: e instanceof Error ? e.message : String(e) }); + return; + } + if (!changes) return; + if (!changes.patch.trim()) { + notify({ level: "info", title: "No changes to describe", body: "Include changes in the commit first." }); + return; + } + const { tasks, providers, draft } = useAgents.getState(); + const agent = pickAgent(tasks.values(), providers, draft); + if (!agent) { + notify({ + level: "warning", + title: "No coding agent available", + body: "Set one up in Settings › Agents. Agents don't run in projects you haven't trusted.", + actions: [{ label: "Open Settings", run: () => void executeAction("file.settings", REGISTRY_PAGE) }], + }); + return; + } + + const { commit } = workflowSettings().vcs; + const subjects = await recentSubjects(changes.roots[0]); + const prompt = commitMessagePrompt(changes.patch, commit.limitSubject ? commit.subjectLimit : 72, subjects); + let task: AgentTask | undefined; + let release = () => {}; + try { + const created = await call( + commands.agentCreate({ + projectRoot: null, + prompt: { text: prompt, files: [], images: [] }, + provider: agent.provider, + config: agent.config, + isolation: "local", + base: null, + }), + ); + task = created; + release = runQuietly(created.id); + // Its events can arrive before this reply: keep the newer state they carried. + useAgents.setState((s) => ({ + tasks: s.tasks.has(created.id) ? s.tasks : new Map(s.tasks).set(created.id, created), + })); + 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)) { + notify({ + level: "info", + title: "Commit message not replaced", + body: "The message or the included changes were edited meanwhile.", + }); + } + } catch (e) { + notify({ + level: "error", + title: "Couldn't generate the commit message", + body: e instanceof Error ? e.message : String(e), + }); + } finally { + if (task) { + const status = useAgents.getState().tasks.get(task.id)?.status; + if (status && isBusy(status)) await cancelTask(task.id).catch(() => {}); + await deleteTask(task.id, false).catch(() => {}); + } + release(); + } +} diff --git a/src/features/agents/index.ts b/src/features/agents/index.ts index c886dfd3b6..af3c03ff80 100644 --- a/src/features/agents/index.ts +++ b/src/features/agents/index.ts @@ -15,6 +15,7 @@ import { registerEditorDropHandler, registerEditorKind, registerMenuGroup, + registerMenuSlotItem, registerOverlay, registerSettingsPage, registerStatusItem, @@ -195,6 +196,13 @@ export function activate(): () => void { accepts: (type) => type === TASK_DRAG, drop: ({ payload }) => void executeAction("agents.openTaskInEditor", payload), }), + // The button above the commit message (the Commit tool window and dialog). + registerMenuSlotItem("commitMessage", { + action: "agents.generateCommitMessage", + label: "Generate Commit Message with Agent", + icon: "toolwindow-agents", + when: "projectOpen && vcsAvailable", + }), registerStatusItem({ id: "agents.status", align: "right", priority: 3, title: "Agents", component: AgentsStatus }), registerMenuGroup({ id: "agents.send", @@ -304,6 +312,21 @@ export function activate(): () => void { else sendSelection(); }, }, + { + id: "agents.generateCommitMessage", + title: "Generate Commit Message with Agent", + description: + "Has the coding agent you work with review the changes about to be committed and write the commit message.", + category: "Agents", + icon: "toolwindow-agents", + when: "projectOpen && vcsAvailable", + keywords: ["agent", "commit", "message", "ai", "copilot", "generate"], + indicatesRunning: true, + run: async () => { + const { generateCommitMessage } = await import("./commitMessage"); + await generateCommitMessage(); + }, + }, { id: "agents.showToolWindow", title: "Agents", diff --git a/src/features/agents/store.ts b/src/features/agents/store.ts index a1ecfb386f..fc8e763667 100644 --- a/src/features/agents/store.ts +++ b/src/features/agents/store.ts @@ -335,7 +335,16 @@ function setUnread(task: string, value: boolean) { function markUnread(task: string) { const current = useAgents.getState().tasks.get(task); - if (current && current.status !== "archived" && !viewing(task)) setUnread(task, true); + if (current && current.status !== "archived" && !viewing(task) && !quietTasks.has(task)) setUnread(task, true); +} + +/** Tasks the IDE runs on its own account (a generated commit message): no notifications, no unread mark. */ +const quietTasks = new Set(); + +export function runQuietly(task: string): () => void { + quietTasks.add(task); + setUnread(task, false); + return () => void quietTasks.delete(task); } export function markVisible(task: string): () => void { @@ -642,7 +651,7 @@ function onEvent(e: AgentEvent) { /** In-app balloon for an Attention event; OS delivery goes through the general balloon path. */ function notifyAttention(taskId: string, reason: "finished" | "input" | "failed") { - if (viewing(taskId)) return; + if (viewing(taskId) || quietTasks.has(taskId)) return; const task = useAgents.getState().tasks.get(taskId); const title = task?.title ?? "Agent"; const body = diff --git a/src/features/vcs/__tests__/pluginCommit.test.ts b/src/features/vcs/__tests__/pluginCommit.test.ts index 89c836dca0..614e38ce95 100644 --- a/src/features/vcs/__tests__/pluginCommit.test.ts +++ b/src/features/vcs/__tests__/pluginCommit.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; const commit = vi.hoisted(() => vi.fn()); +const createPatch = vi.hoisted(() => vi.fn()); vi.mock("@/platform/ipc", async (importOriginal) => { const real = await importOriginal(); @@ -9,7 +10,11 @@ vi.mock("@/platform/ipc", async (importOriginal) => { ...real, isTauri: () => false, call: async (p: Promise<{ status: "ok"; data: unknown }>) => (await p).data, - commands: { ...real.commands, vcsCommit: commit.mockImplementation(() => ok("commit1")) }, + commands: { + ...real.commands, + vcsCommit: commit.mockImplementation(() => ok("commit1")), + vcsCreatePatch: createPatch.mockImplementation(() => ok("diff --git a/p b/p\n")), + }, }; }); @@ -33,6 +38,7 @@ let disposers: Array<() => void> = []; beforeEach(() => { localStorage.clear(); commit.mockClear(); + createPatch.mockClear(); useVcs.setState({ available: false, root: "/p", @@ -96,8 +102,36 @@ describe("the commit plugins see", () => { it("is null without a repository", async () => { useVcs.setState({ root: null }); expect(await maybeCommitService()!.selection()).toBeNull(); + expect(await maybeCommitService()!.changes()).toBeNull(); expect(maybeCommitService()!.setMessage(draftRevision(), "x")).toBe(false); }); + + it("reads the diff of the included files only, 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(changes).toEqual({ revision: draftRevision(), roots: ["/p"], patch: "diff --git a/p b/p\n" }); + expect(maybeCommitService()!.setMessage(changes.revision, "generated")).toBe(true); + }); + + it("reads one diff per repository with included files", async () => { + const other: FileStatus = { ...files[0]!, path: "/w/b/Bar.java", relPath: "Bar.java" }; + const changed: FileStatus = { ...files[0]!, path: "/w/a/Foo.java", relPath: "Foo.java" }; + useVcs.setState({ root: "/w", repo: "/w/a", roots: ["/w/a", "/w/b"], status: [changed, other] }); + 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 }], + ]); + 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"); + }); + + it("is an empty diff when nothing is included", async () => { + useCommit.setState({ checks: new Map(files.map((f) => [f.path, "none" as const])) }); + expect((await maybeCommitService()!.changes())!.patch).toBe(""); + expect(createPatch).not.toHaveBeenCalled(); + }); }); describe("contributed before-commit checks", () => { diff --git a/src/features/vcs/commitSelection.ts b/src/features/vcs/commitSelection.ts index dc079b708e..fa89785b7e 100644 --- a/src/features/vcs/commitSelection.ts +++ b/src/features/vcs/commitSelection.ts @@ -7,14 +7,19 @@ import type { CommitOptions, CommitSelection, PartialCommitFile } from "@/bindings"; import { call, commands } from "@/platform/ipc"; import { workflowSettings } from "@/platform/workflowSettings"; -import { maybeEditorService, provideCommitService, useCommitCheckProviders } from "@/workbench/contributions"; +import { + maybeEditorService, + provideCommitService, + useCommitCheckProviders, + type CommitChanges, +} from "@/workbench/contributions"; import { commitRepos, planCommit, type CommitPlan } from "./changes"; import type { CommitProblem } from "./commitChecks"; import { useChangelists } from "./changelists"; import { inclusionChecks, stagingAreaOn } from "./staging"; import { useCommit } from "./commitStore"; import { hunkKeys } from "./hunks"; -import { baseName, rootOf } from "./model"; +import { baseName, rootOf, stripSlash } from "./model"; import { saveAll } from "./ops"; import { currentRepo, refreshNow, useVcs } from "./store"; @@ -119,9 +124,35 @@ async function pendingSelection(): Promise { return { ...selection, revision: rev }; } +/** The included files' local changes, one patch per repository. */ +async function pendingChanges(): Promise { + if (!useVcs.getState().root) return null; + await saveAll(); + await refreshNow(); + const { root, roots } = useVcs.getState(); + if (!root) return null; + const rev = revision; + const { included } = currentPlan(); + const repos = commitRepos(included, roots, currentRepo()); + 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 })); + if (patch.trim()) patches.push(patch); + } + return { revision: rev, roots: repos.map((r) => r ?? root), patch: patches.join("\n") }; +} + export function provideCommit(): () => void { provideCommitService({ selection: pendingSelection, + changes: pendingChanges, setMessage: (rev, message) => { if (rev !== revision || !useVcs.getState().root) return false; useCommit.setState({ message }); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 1a8c9e5ab4..5870aa6272 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2163,5 +2163,22 @@ "Minimum run time of a long-running command": "Minimum run time of a long-running command", "Exited with code {code}": "Exited with code {code}", "Finished": "Finished", - "Only while the tab cannot be seen. A command stopped with Ctrl-C, shell startup and short commands stay quiet; a non-zero exit always reports its code.": "Only while the tab cannot be seen. A command stopped with Ctrl-C, shell startup and short commands stay quiet; a non-zero exit always reports its code." + "Only while the tab cannot be seen. A command stopped with Ctrl-C, shell startup and short commands stay quiet; a non-zero exit always reports its code.": "Only while the tab cannot be seen. A command stopped with Ctrl-C, shell startup and short commands stay quiet; a non-zero exit always reports its code.", + "Generate Commit Message with Agent": "Generate Commit Message with Agent", + "Has the coding agent you work with review the changes about to be committed and write the commit message.": "Has the coding agent you work with review the changes about to be committed and write the commit message.", + "No changes to describe": "No changes to describe", + "Include changes in the commit first.": "Include changes in the commit first.", + "No coding agent available": "No coding agent available", + "Set one up in Settings › Agents. Agents don't run in projects you haven't trusted.": "Set one up in Settings › Agents. Agents don't run in projects you haven't trusted.", + "Open Settings": "Open Settings", + "Commit message not replaced": "Commit message not replaced", + "The message or the included changes were edited meanwhile.": "The message or the included changes were edited meanwhile.", + "Couldn't generate the commit message": "Couldn't generate the commit message", + "Couldn't read the changes": "Couldn't read the changes", + "The agent task was removed": "The agent task was removed", + "The agent's usage limit was reached": "The agent's usage limit was reached", + "The agent asked for permission to continue": "The agent asked for permission to continue", + "The agent task was archived": "The agent task was archived", + "The agent did not answer in time": "The agent did not answer in time", + "The agent did not reply with a commit message": "The agent did not reply with a commit message" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 9efbc156c9..1055bf8b71 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -8550,5 +8550,22 @@ "All commands": "所有命令", "Minimum run time of a long-running command": "长时间运行命令的最短运行时间", "Exited with code {code}": "退出代码 {code}", - "Only while the tab cannot be seen. A command stopped with Ctrl-C, shell startup and short commands stay quiet; a non-zero exit always reports its code.": "仅当标签页不可见时通知。用 Ctrl-C 停止的命令、shell 启动和短命令保持安静;非零退出始终报告退出代码。" + "Only while the tab cannot be seen. A command stopped with Ctrl-C, shell startup and short commands stay quiet; a non-zero exit always reports its code.": "仅当标签页不可见时通知。用 Ctrl-C 停止的命令、shell 启动和短命令保持安静;非零退出始终报告退出代码。", + "Generate Commit Message with Agent": "使用智能体生成提交消息", + "Has the coding agent you work with review the changes about to be committed and write the commit message.": "让您正在使用的编程智能体审查即将提交的更改并撰写提交消息。", + "No changes to describe": "没有可描述的更改", + "Include changes in the commit first.": "请先在提交中包含更改。", + "No coding agent available": "没有可用的编程智能体", + "Set one up in Settings › Agents. Agents don't run in projects you haven't trusted.": "请在“设置 › 智能体”中配置一个。智能体不会在未受信任的项目中运行。", + "Open Settings": "打开设置", + "Commit message not replaced": "提交消息未被替换", + "The message or the included changes were edited meanwhile.": "在此期间,消息或包含的更改已被修改。", + "Couldn't generate the commit message": "无法生成提交消息", + "Couldn't read the changes": "无法读取更改", + "The agent task was removed": "智能体任务已被移除", + "The agent's usage limit was reached": "智能体已达到使用上限", + "The agent asked for permission to continue": "智能体请求许可以继续", + "The agent task was archived": "智能体任务已归档", + "The agent did not answer in time": "智能体未在限定时间内回复", + "The agent did not reply with a commit message": "智能体没有返回提交消息" } diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index e8feaa2736..f328a7e5f2 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -873,10 +873,24 @@ export interface CommitService { * Commit does); `null` without a repository. */ selection(): Promise; + /** + * The included changes as a unified diff against HEAD (unsaved editors saved first); + * `null` without a repository. + */ + changes(): Promise; /** Replaces the message if the draft is still at `revision`; false when it changed. */ setMessage(revision: number, message: string): boolean; } +export interface CommitChanges { + /** The draft's revision the diff was read at, for `CommitService.setMessage`. */ + revision: number; + /** Repositories the commit goes to. */ + roots: string[]; + /** Untracked files included; empty when nothing is included. */ + patch: string; +} + let commitServiceImpl: CommitService | undefined; export const provideCommitService = (s: CommitService | undefined) => void (commitServiceImpl = s); export const maybeCommitService = (): CommitService | undefined => commitServiceImpl;