diff --git a/apps/vscode-e2e/src/visual/__screenshots__/electron-scm-title-dark-header.png b/apps/vscode-e2e/src/visual/__screenshots__/electron-scm-title-dark-header.png new file mode 100644 index 0000000000..d057f3f35f Binary files /dev/null and b/apps/vscode-e2e/src/visual/__screenshots__/electron-scm-title-dark-header.png differ diff --git a/apps/vscode-e2e/src/visual/electron.visual.ts b/apps/vscode-e2e/src/visual/electron.visual.ts index a71fe80d2e..b0e22a0861 100644 --- a/apps/vscode-e2e/src/visual/electron.visual.ts +++ b/apps/vscode-e2e/src/visual/electron.visual.ts @@ -5,6 +5,7 @@ import { attachFailureArtifacts, CHAT_RESULT, extensionDevelopmentPath, + SCM_ACTION_TITLE, startScene, stopScene, vscodeVersion, @@ -119,3 +120,32 @@ for (const scenario of scenarios) { } }) } + +const scmScenario: VisualScenario = { + name: "scm-title-dark", + scene: "scm", + themeId: "Default Dark Modern", + landmark: SCM_ACTION_TITLE, +} + +test("renders the Generate Commit Message action in the Source Control title bar", async ({ + browserName: _browserName, +}, testInfo) => { + const running = await startScene(vscodeExecutablePath, scmScenario, testInfo) + try { + // Keep the pointer away from the sidebar so no action shows a hover state or tooltip. + await running.page.mouse.move(900, 400) + // `has` takes a locator relative to each header, so it names only the action itself. + const header = running.page + .locator(".part.sidebar .pane-header") + .filter({ has: running.page.locator(`[aria-label="${SCM_ACTION_TITLE}"]`) }) + await expect(header).toHaveCount(1) + await expect(header.locator(`[aria-label="${SCM_ACTION_TITLE}"]`)).toBeVisible() + await expect(header).toHaveScreenshot("electron-scm-title-dark-header.png") + } catch (error) { + await attachFailureArtifacts(running, testInfo) + throw error + } finally { + await stopScene(running, testInfo) + } +}) diff --git a/apps/vscode-e2e/src/visual/electronHarness.ts b/apps/vscode-e2e/src/visual/electronHarness.ts index 96bab3dd0f..d6fd7e4a46 100644 --- a/apps/vscode-e2e/src/visual/electronHarness.ts +++ b/apps/vscode-e2e/src/visual/electronHarness.ts @@ -1,7 +1,9 @@ +import { execFile } from "child_process" import fs from "fs/promises" import { readFileSync } from "fs" import os from "os" import path from "path" +import { promisify } from "util" import { LLMock } from "@copilotkit/aimock" import { _electron, expect, type ElectronApplication, type Page, type TestInfo } from "@playwright/test" @@ -18,10 +20,26 @@ export const vscodeVersion = packageJson.devDependencies["@types/vscode"] const CHAT_PROMPT = "electron-visual-smoke: render a deterministic completion" export const CHAT_RESULT = "Electron visual smoke response rendered inside the real VS Code webview." +export const SCM_ACTION_TITLE = "Generate Commit Message (Zoo Code)" + +const execFileAsync = promisify(execFile) + +/** + * Makes the workspace a Git repository with one staged file, so the Source Control view shows the + * Git provider and its title actions. The branch name, author, and file are fixed for a stable scene. + */ +async function initGitWorkspace(workspacePath: string) { + const git = (...args: string[]) => execFileAsync("git", args, { cwd: workspacePath }) + await git("init", "--initial-branch=main") + await git("config", "user.name", "Zoo Code Visual") + await git("config", "user.email", "visual@example.invalid") + await fs.writeFile(path.join(workspacePath, "notes.md"), "# Notes\n", "utf8") + await git("add", "notes.md") +} export interface VisualScenario { name: string - scene: "welcome" | "chat" + scene: "welcome" | "chat" | "scm" themeId: "Default Dark Modern" | "Default High Contrast" landmark: string webviewSnapshot?: string @@ -105,6 +123,9 @@ export async function startScene( for (const result of directories) { if (result.status === "rejected") throw result.reason } + if (scenario.scene === "scm") { + await initGitWorkspace(workspacePath) + } if (scenario.startMock) { mock = new LLMock({ port: 0 }) mock.addFixture({ @@ -147,6 +168,7 @@ export async function startScene( ROO_CODE_VISUAL_READY_PATH: readyPath, ROO_CODE_VISUAL_SCENE: scenario.scene, ROO_CODE_VISUAL_THEME: scenario.themeId, + ROO_CODE_VISUAL_SCM_ACTION_TITLE: SCM_ACTION_TITLE, ROO_CODE_THEME_FIXTURE_PROBE: "1", }, locale: "en-US", diff --git a/apps/vscode-e2e/src/visual/sceneController.ts b/apps/vscode-e2e/src/visual/sceneController.ts index d8857ae043..25f43a62d4 100644 --- a/apps/vscode-e2e/src/visual/sceneController.ts +++ b/apps/vscode-e2e/src/visual/sceneController.ts @@ -13,6 +13,11 @@ import { import { isCompletedAsk } from "../suite/utils" const POLL_INTERVAL_MS = 100 + +/** The parts of the built-in Git extension API (`vscode.git`, version 1) that the scm scene reads. */ +interface GitExtension { + getAPI(version: 1): { repositories: Array<{ state: { indexChanges: unknown[] } }> } +} const SCENE_TIMEOUT_MS = 60_000 const themeKinds: Record = { @@ -68,7 +73,9 @@ export async function run(): Promise { } const log = (message: string) => fs.appendFile(logPath, `${message}\n`, "utf8") await log(`scene=${scene} theme=${themeId}`) - if (scene !== "welcome" && scene !== "chat") throw new Error(`Unknown Electron visual scene: ${scene}`) + if (scene !== "welcome" && scene !== "chat" && scene !== "scm") { + throw new Error(`Unknown Electron visual scene: ${scene}`) + } if (!themeKinds[themeId]) throw new Error(`Unsupported Electron visual theme: ${themeId}`) const extension = vscode.extensions.getExtension("ZooCodeOrganization.zoo-code") @@ -145,6 +152,25 @@ export async function run(): Promise { landmark = result } + if (scene === "scm") { + // Show view title actions without hover, so the screenshot does not depend on the pointer. + await vscode.workspace + .getConfiguration("workbench.view") + .update("alwaysShowHeaderActions", true, vscode.ConfigurationTarget.Global) + const gitExtension = vscode.extensions.getExtension("vscode.git") + if (!gitExtension) throw new Error("The built-in Git extension is not available") + const git = (gitExtension.isActive ? gitExtension.exports : await gitExtension.activate()).getAPI(1) + await poll( + async () => git.repositories.map((repository) => repository.state.indexChanges.length), + (stagedCounts) => stagedCounts.length === 1 && stagedCounts[0] === 1, + "one Git repository with one staged file", + ) + await vscode.commands.executeCommand("workbench.view.scm") + await log("scm-ready") + landmark = process.env.ROO_CODE_VISUAL_SCM_ACTION_TITLE ?? "" + if (!landmark) throw new Error("The Source Control action title is required for the scm scene") + } + await fs.writeFile( readyPath, `${JSON.stringify({ scene, themeId, landmark, themeFixture, taskIds: api.getCurrentTaskStack() }, null, 2)}\n`, diff --git a/packages/types/src/vscode.ts b/packages/types/src/vscode.ts index 811ceda165..fbb343ce82 100644 --- a/packages/types/src/vscode.ts +++ b/packages/types/src/vscode.ts @@ -48,6 +48,8 @@ export const commandIds = [ "retryWebviewRecovery", "toggleAutoApprove", + "generateGitCommitMessage", + "showRipgrepDiagnostic", "createDiagnosticsReport", ] as const diff --git a/src/activate/__tests__/registerCommands.spec.ts b/src/activate/__tests__/registerCommands.spec.ts index c59933a7c1..c68be5a052 100644 --- a/src/activate/__tests__/registerCommands.spec.ts +++ b/src/activate/__tests__/registerCommands.spec.ts @@ -100,6 +100,10 @@ vi.mock("../../services/diagnostics", () => ({ createDiagnosticsReport: vi.fn().mockResolvedValue(undefined), })) +vi.mock("../../services/git/commitMessageGenerator", () => ({ + generateCommitMessage: vi.fn().mockResolvedValue(undefined), +})) + describe("getVisibleProviderOrLog", () => { let mockOutputChannel: vscode.OutputChannel @@ -282,6 +286,32 @@ describe("registerCommands handlers", () => { }) }) + it("generateGitCommitMessage calls generateCommitMessage with visible provider and context", async () => { + const { generateCommitMessage } = await import("../../services/git/commitMessageGenerator") + const mockScmContext = { rootUri: { fsPath: "/mock/repo" } } + + await handlers["zoo-code.generateGitCommitMessage"](mockScmContext) + + expect(generateCommitMessage).toHaveBeenCalledWith({ + provider: mockVisibleProviderInstance, + outputChannel: mockOutputChannel, + context: mockScmContext, + }) + }) + + it("generateGitCommitMessage falls back to default provider when no visible provider", async () => { + const { generateCommitMessage } = await import("../../services/git/commitMessageGenerator") + ;(ClineProvider.getVisibleInstance as Mock).mockReturnValue(undefined) + + await handlers["zoo-code.generateGitCommitMessage"]() + + expect(generateCommitMessage).toHaveBeenCalledWith({ + provider: mockProvider, + outputChannel: mockOutputChannel, + context: undefined, + }) + }) + it("settingsButtonClicked posts both settingsButtonClicked and didBecomeVisible actions", () => { handlers["zoo-code.settingsButtonClicked"]() diff --git a/src/activate/registerCommands.ts b/src/activate/registerCommands.ts index f0f4747eee..2e483c4de0 100644 --- a/src/activate/registerCommands.ts +++ b/src/activate/registerCommands.ts @@ -14,6 +14,7 @@ import { importSettingsWithFeedback } from "../core/config/importExport" import { MdmService } from "../services/mdm/MdmService" import { registerRipgrepDiagnosticCommand } from "../services/ripgrep/diagnostic" import { createDiagnosticsReport } from "../services/diagnostics" +import { generateCommitMessage } from "../services/git/commitMessageGenerator" /** * Helper to get the visible ClineProvider instance or log if not found. @@ -225,6 +226,14 @@ const getCommandsMap = ({ outputChannel.appendLine(`[toggleAutoApprove] postMessageToWebview failed: ${error}`) } }, + generateGitCommitMessage: async (context?: unknown) => { + const visibleProvider = ClineProvider.getVisibleInstance() ?? provider + await generateCommitMessage({ + provider: visibleProvider, + outputChannel, + context, + }) + }, }) type OpenClineInNewTabOptions = { diff --git a/src/package.json b/src/package.json index 6c59828b1d..3b3b4406eb 100644 --- a/src/package.json +++ b/src/package.json @@ -179,9 +179,21 @@ "command": "zoo-code.toggleAutoApprove", "title": "%command.toggleAutoApprove.title%", "category": "%configuration.title%" + }, + { + "command": "zoo-code.generateGitCommitMessage", + "title": "%command.generateGitCommitMessage.title%", + "icon": "$(wand)" } ], "menus": { + "scm/title": [ + { + "command": "zoo-code.generateGitCommitMessage", + "group": "navigation", + "when": "scmProvider == git" + } + ], "editor/context": [ { "submenu": "zoo-code.contextMenu", diff --git a/src/package.nls.ca.json b/src/package.nls.ca.json index d6b40efba3..231c0b2e55 100644 --- a/src/package.nls.ca.json +++ b/src/package.nls.ca.json @@ -18,6 +18,7 @@ "command.showRipgrepDiagnostic.title": "Mostra el diagnòstic de Ripgrep", "command.createDiagnosticsReport.title": "Crea un informe de diagnòstic", "command.toggleAutoApprove.title": "Alternar Auto-Aprovació", + "command.generateGitCommitMessage.title": "Generar Missatge de Commit (Zoo Code)", "views.activitybar.title": "Zoo Code", "views.contextMenu.label": "Zoo Code", "views.terminalMenu.label": "Zoo Code", diff --git a/src/package.nls.de.json b/src/package.nls.de.json index a8bbadbf15..05a57bdf5b 100644 --- a/src/package.nls.de.json +++ b/src/package.nls.de.json @@ -18,6 +18,7 @@ "command.showRipgrepDiagnostic.title": "Ripgrep-Diagnose anzeigen", "command.createDiagnosticsReport.title": "Diagnosebericht erstellen", "command.toggleAutoApprove.title": "Auto-Genehmigung Umschalten", + "command.generateGitCommitMessage.title": "Commit-Nachricht generieren (Zoo Code)", "views.activitybar.title": "Zoo Code", "views.contextMenu.label": "Zoo Code", "views.terminalMenu.label": "Zoo Code", diff --git a/src/package.nls.es.json b/src/package.nls.es.json index 26d9f87e9d..175a53e9be 100644 --- a/src/package.nls.es.json +++ b/src/package.nls.es.json @@ -18,6 +18,7 @@ "command.showRipgrepDiagnostic.title": "Mostrar diagnóstico de Ripgrep", "command.createDiagnosticsReport.title": "Crear informe de diagnóstico", "command.toggleAutoApprove.title": "Alternar Auto-Aprobación", + "command.generateGitCommitMessage.title": "Generar mensaje de confirmación (Zoo Code)", "views.activitybar.title": "Zoo Code", "views.contextMenu.label": "Zoo Code", "views.terminalMenu.label": "Zoo Code", diff --git a/src/package.nls.fr.json b/src/package.nls.fr.json index 364a8878c4..9e71eb9a94 100644 --- a/src/package.nls.fr.json +++ b/src/package.nls.fr.json @@ -18,6 +18,7 @@ "command.showRipgrepDiagnostic.title": "Afficher le diagnostic Ripgrep", "command.createDiagnosticsReport.title": "Créer un rapport de diagnostic", "command.toggleAutoApprove.title": "Basculer Auto-Approbation", + "command.generateGitCommitMessage.title": "Générer un message de commit (Zoo Code)", "views.activitybar.title": "Zoo Code", "views.contextMenu.label": "Zoo Code", "views.terminalMenu.label": "Zoo Code", diff --git a/src/package.nls.hi.json b/src/package.nls.hi.json index db70bc8417..62a352cd81 100644 --- a/src/package.nls.hi.json +++ b/src/package.nls.hi.json @@ -18,6 +18,7 @@ "command.showRipgrepDiagnostic.title": "Ripgrep डायग्नोस्टिक दिखाएं", "command.createDiagnosticsReport.title": "डायग्नोस्टिक रिपोर्ट बनाएं", "command.toggleAutoApprove.title": "ऑटो-अनुमोदन टॉगल करें", + "command.generateGitCommitMessage.title": "कमिट संदेश बनाएं (Zoo Code)", "views.activitybar.title": "Zoo Code", "views.contextMenu.label": "Zoo Code", "views.terminalMenu.label": "Zoo Code", diff --git a/src/package.nls.id.json b/src/package.nls.id.json index b7e150ee53..31ac13fcc6 100644 --- a/src/package.nls.id.json +++ b/src/package.nls.id.json @@ -27,6 +27,7 @@ "command.showRipgrepDiagnostic.title": "Tampilkan Diagnostik Ripgrep", "command.createDiagnosticsReport.title": "Buat Laporan Diagnostik", "command.toggleAutoApprove.title": "Alihkan Persetujuan Otomatis", + "command.generateGitCommitMessage.title": "Buat Pesan Commit (Zoo Code)", "configuration.title": "Zoo Code", "commands.allowedCommands.description": "Perintah yang dapat dijalankan secara otomatis ketika 'Selalu setujui operasi eksekusi' diaktifkan", "commands.deniedCommands.description": "Awalan perintah yang akan otomatis ditolak tanpa meminta persetujuan. Jika terjadi konflik dengan perintah yang diizinkan, pencocokan awalan terpanjang akan diprioritaskan. Tambahkan * untuk menolak semua perintah.", diff --git a/src/package.nls.it.json b/src/package.nls.it.json index 6d50b96bc4..ef3a0ff2dc 100644 --- a/src/package.nls.it.json +++ b/src/package.nls.it.json @@ -18,6 +18,7 @@ "command.showRipgrepDiagnostic.title": "Mostra diagnostica Ripgrep", "command.createDiagnosticsReport.title": "Crea rapporto di diagnostica", "command.toggleAutoApprove.title": "Attiva/Disattiva Auto-Approvazione", + "command.generateGitCommitMessage.title": "Genera Messaggio di Commit (Zoo Code)", "views.activitybar.title": "Zoo Code", "views.contextMenu.label": "Zoo Code", "views.terminalMenu.label": "Zoo Code", diff --git a/src/package.nls.ja.json b/src/package.nls.ja.json index 22f4f0dfce..d2ce85c395 100644 --- a/src/package.nls.ja.json +++ b/src/package.nls.ja.json @@ -27,6 +27,7 @@ "command.showRipgrepDiagnostic.title": "Ripgrep 診断を表示", "command.createDiagnosticsReport.title": "診断レポートを作成", "command.toggleAutoApprove.title": "自動承認を切替", + "command.generateGitCommitMessage.title": "コミットメッセージの生成 (Zoo Code)", "configuration.title": "Zoo Code", "commands.allowedCommands.description": "'常に実行操作を承認する'が有効な場合に自動実行できるコマンド", "commands.deniedCommands.description": "承認を求めずに自動的に拒否されるコマンドプレフィックス。許可されたコマンドとの競合がある場合、最長プレフィックスマッチが優先されます。すべてのコマンドを拒否するには * を追加してください。", diff --git a/src/package.nls.json b/src/package.nls.json index d1f9afbc39..cc0c7fd454 100644 --- a/src/package.nls.json +++ b/src/package.nls.json @@ -27,6 +27,7 @@ "command.showRipgrepDiagnostic.title": "Show Ripgrep Diagnostic", "command.createDiagnosticsReport.title": "Create Diagnostics Report", "command.toggleAutoApprove.title": "Toggle Auto-Approve", + "command.generateGitCommitMessage.title": "Generate Commit Message (Zoo Code)", "configuration.title": "Zoo Code", "commands.allowedCommands.description": "Commands that can be auto-executed when 'Always approve execute operations' is enabled", "commands.deniedCommands.description": "Command prefixes that will be automatically denied without asking for approval. In case of conflicts with allowed commands, the longest prefix match takes precedence. Add * to deny all commands.", diff --git a/src/package.nls.ko.json b/src/package.nls.ko.json index 48d8695a1d..9397f4d752 100644 --- a/src/package.nls.ko.json +++ b/src/package.nls.ko.json @@ -18,6 +18,7 @@ "command.showRipgrepDiagnostic.title": "Ripgrep 진단 표시", "command.createDiagnosticsReport.title": "진단 보고서 만들기", "command.toggleAutoApprove.title": "자동 승인 전환", + "command.generateGitCommitMessage.title": "커밋 메시지 생성 (Zoo Code)", "views.activitybar.title": "Zoo Code", "views.contextMenu.label": "Zoo Code", "views.terminalMenu.label": "Zoo Code", diff --git a/src/package.nls.nl.json b/src/package.nls.nl.json index 81113c4b5a..c2c9699ce5 100644 --- a/src/package.nls.nl.json +++ b/src/package.nls.nl.json @@ -27,6 +27,7 @@ "command.showRipgrepDiagnostic.title": "Ripgrep-diagnose weergeven", "command.createDiagnosticsReport.title": "Diagnoserapport maken", "command.toggleAutoApprove.title": "Auto-Goedkeuring Schakelen", + "command.generateGitCommitMessage.title": "Commitbericht genereren (Zoo Code)", "configuration.title": "Zoo Code", "commands.allowedCommands.description": "Commando's die automatisch kunnen worden uitgevoerd wanneer 'Altijd goedkeuren uitvoerbewerkingen' is ingeschakeld", "commands.deniedCommands.description": "Commando-prefixen die automatisch worden geweigerd zonder om goedkeuring te vragen. Bij conflicten met toegestane commando's heeft de langste prefix-match voorrang. Voeg * toe om alle commando's te weigeren.", diff --git a/src/package.nls.pl.json b/src/package.nls.pl.json index 267ddff277..b4d0c54539 100644 --- a/src/package.nls.pl.json +++ b/src/package.nls.pl.json @@ -18,6 +18,7 @@ "command.showRipgrepDiagnostic.title": "Pokaż diagnostykę Ripgrep", "command.createDiagnosticsReport.title": "Utwórz raport diagnostyczny", "command.toggleAutoApprove.title": "Przełącz Auto-Zatwierdzanie", + "command.generateGitCommitMessage.title": "Wygeneruj komunikat commita (Zoo Code)", "views.activitybar.title": "Zoo Code", "views.contextMenu.label": "Zoo Code", "views.terminalMenu.label": "Zoo Code", diff --git a/src/package.nls.pt-BR.json b/src/package.nls.pt-BR.json index 853832b699..7ec732d98c 100644 --- a/src/package.nls.pt-BR.json +++ b/src/package.nls.pt-BR.json @@ -18,6 +18,7 @@ "command.showRipgrepDiagnostic.title": "Mostrar diagnóstico do Ripgrep", "command.createDiagnosticsReport.title": "Criar relatório de diagnóstico", "command.toggleAutoApprove.title": "Alternar Auto-Aprovação", + "command.generateGitCommitMessage.title": "Gerar mensagem de commit (Zoo Code)", "views.activitybar.title": "Zoo Code", "views.contextMenu.label": "Zoo Code", "views.terminalMenu.label": "Zoo Code", diff --git a/src/package.nls.ru.json b/src/package.nls.ru.json index d46ea14245..3ad4f5ada0 100644 --- a/src/package.nls.ru.json +++ b/src/package.nls.ru.json @@ -27,6 +27,7 @@ "command.showRipgrepDiagnostic.title": "Показать диагностику Ripgrep", "command.createDiagnosticsReport.title": "Создать диагностический отчёт", "command.toggleAutoApprove.title": "Переключить Авто-Подтверждение", + "command.generateGitCommitMessage.title": "Сгенерировать сообщение коммита (Zoo Code)", "configuration.title": "Zoo Code", "commands.allowedCommands.description": "Команды, которые могут быть автоматически выполнены, когда включена опция 'Всегда подтверждать операции выполнения'", "commands.deniedCommands.description": "Префиксы команд, которые будут автоматически отклонены без запроса подтверждения. В случае конфликтов с разрешенными командами приоритет имеет самое длинное совпадение префикса. Добавьте * чтобы отклонить все команды.", diff --git a/src/package.nls.tr.json b/src/package.nls.tr.json index cbc81d959f..799f8c0d2c 100644 --- a/src/package.nls.tr.json +++ b/src/package.nls.tr.json @@ -18,6 +18,7 @@ "command.showRipgrepDiagnostic.title": "Ripgrep Tanılamasını Göster", "command.createDiagnosticsReport.title": "Tanılama Raporu Oluştur", "command.toggleAutoApprove.title": "Otomatik Onayı Değiştir", + "command.generateGitCommitMessage.title": "Commit Mesajı Oluştur (Zoo Code)", "views.activitybar.title": "Zoo Code", "views.contextMenu.label": "Zoo Code", "views.terminalMenu.label": "Zoo Code", diff --git a/src/package.nls.vi.json b/src/package.nls.vi.json index 1ee4eabd70..36d255e048 100644 --- a/src/package.nls.vi.json +++ b/src/package.nls.vi.json @@ -18,6 +18,7 @@ "command.showRipgrepDiagnostic.title": "Hiển thị chẩn đoán Ripgrep", "command.createDiagnosticsReport.title": "Tạo báo cáo chẩn đoán", "command.toggleAutoApprove.title": "Bật/Tắt Tự Động Phê Duyệt", + "command.generateGitCommitMessage.title": "Tạo thông điệp commit (Zoo Code)", "views.activitybar.title": "Zoo Code", "views.contextMenu.label": "Zoo Code", "views.terminalMenu.label": "Zoo Code", diff --git a/src/package.nls.zh-CN.json b/src/package.nls.zh-CN.json index 85dafc3bc7..5005fd0b5d 100644 --- a/src/package.nls.zh-CN.json +++ b/src/package.nls.zh-CN.json @@ -18,6 +18,7 @@ "command.showRipgrepDiagnostic.title": "显示 Ripgrep 诊断", "command.createDiagnosticsReport.title": "创建诊断报告", "command.toggleAutoApprove.title": "切换自动批准", + "command.generateGitCommitMessage.title": "生成提交信息 (Zoo Code)", "views.activitybar.title": "Zoo Code", "views.contextMenu.label": "Zoo Code", "views.terminalMenu.label": "Zoo Code", diff --git a/src/package.nls.zh-TW.json b/src/package.nls.zh-TW.json index cda075e306..1b4a7ec91b 100644 --- a/src/package.nls.zh-TW.json +++ b/src/package.nls.zh-TW.json @@ -18,6 +18,7 @@ "command.showRipgrepDiagnostic.title": "顯示 Ripgrep 診斷", "command.createDiagnosticsReport.title": "建立診斷報告", "command.toggleAutoApprove.title": "切換自動批准", + "command.generateGitCommitMessage.title": "產生提交訊息 (Zoo Code)", "views.activitybar.title": "Zoo Code", "views.contextMenu.label": "Zoo Code", "views.terminalMenu.label": "Zoo Code", diff --git a/src/services/git/__tests__/commitMessageGenerator.spec.ts b/src/services/git/__tests__/commitMessageGenerator.spec.ts new file mode 100644 index 0000000000..a36595b8f7 --- /dev/null +++ b/src/services/git/__tests__/commitMessageGenerator.spec.ts @@ -0,0 +1,1873 @@ +import fs, { mkdir, mkdtemp, rm, symlink, writeFile } from "fs/promises" +import { tmpdir } from "os" +import * as path from "path" +import * as vscode from "vscode" +import type { Mock } from "vitest" +import { providerIdentifiers } from "@roo-code/types" + +import { + buildCommitMessagePrompt, + cleanCommitMessage, + COMMIT_MESSAGE_SYSTEM_PROMPT, + commitMessageRequestStateSize, + DIFF_CHARACTER_LIMIT, + DIFF_LINE_LIMIT, + DIFF_TRUNCATED_MESSAGE, + DRAFT_CHANGED_MESSAGE, + generateCommitMessage, + getGitApi, + getRepositoryDiff, + IGNORED_FILE_NOTE, + NO_CHANGES_MESSAGE, + omitIgnoredFiles, + ROOIGNORE_UNREADABLE_MESSAGE, + resetCommitMessageRequestState, + resolveGitRepository, + PREVIOUS_REQUEST_WAIT_MS, + WAITING_FOR_PREVIOUS_REQUEST_MESSAGE, + PREVIOUS_REQUEST_STILL_RUNNING_MESSAGE, + type GitAPI, + type GitRepository, +} from "../commitMessageGenerator" +import { ClineProvider } from "../../../core/webview/ClineProvider" +import { singleCompletionHandler } from "../../../utils/single-completion-handler" +import { makeUri } from "../../../test-utils/vscode" + +// RooIgnoreController watches `.rooignore`. The watcher double provides the three events and dispose. +const { watcherDispose, makeWatcher } = vi.hoisted(() => { + const watcherDispose = vi.fn() + const makeWatcher = () => ({ + onDidChange: vi.fn(() => ({ dispose: vi.fn() })), + onDidCreate: vi.fn(() => ({ dispose: vi.fn() })), + onDidDelete: vi.fn(() => ({ dispose: vi.fn() })), + dispose: watcherDispose, + }) + return { watcherDispose, makeWatcher } +}) + +vi.mock("vscode", () => ({ + ProgressLocation: { + Notification: 15, + }, + RelativePattern: class { + constructor( + readonly base: string, + readonly pattern: string, + ) {} + }, + workspace: { + createFileSystemWatcher: vi.fn(makeWatcher), + }, + extensions: { + getExtension: vi.fn(), + }, + window: { + activeTextEditor: undefined, + showErrorMessage: vi.fn(), + showInformationMessage: vi.fn(), + showWarningMessage: vi.fn(), + withProgress: vi.fn(), + }, + Uri: { + file: (path: string) => makeUri(path), + parse: (uri: string) => makeUri(uri), + }, +})) + +vi.mock("../../../utils/single-completion-handler", () => ({ + singleCompletionHandler: vi.fn(), +})) + +function makeRepo(root: string, overrides: Partial = {}): GitRepository { + return { + rootUri: makeUri(root), + inputBox: { value: "" }, + diff: vi.fn().mockResolvedValue("diff content"), + ...overrides, + } +} + +/** Makes `repository` the only repository of the Git API that the generator reads. */ +function useOnlyRepository(repository: GitRepository): void { + const gitApi: GitAPI = { repositories: [repository] } + ;(vscode.extensions.getExtension as Mock).mockReturnValue({ isActive: true, exports: { getAPI: () => gitApi } }) +} + +function deferred() { + let resolve: (value: T) => void = () => {} + const promise = new Promise((r) => { + resolve = r + }) + return { promise, resolve } +} + +/** + * Installs a withProgress mock whose token can be cancelled from the test. Every registered + * cancellation listener runs on cancel(), like a real vscode.CancellationTokenSource. + */ +function useCancellableProgress({ once = false }: { once?: boolean } = {}) { + let cancelled = false + const listeners: Array<() => void> = [] + const disposable = { dispose: vi.fn() } + const withProgress = vscode.window.withProgress as Mock + // With `once`, only the next withProgress call gets this token; later calls use the default mock. + const install = once + ? withProgress.mockImplementationOnce.bind(withProgress) + : withProgress.mockImplementation.bind(withProgress) + install((_opts: unknown, callback: (progress: unknown, token: unknown) => unknown) => { + const token = { + get isCancellationRequested() { + return cancelled + }, + onCancellationRequested: vi.fn((fn: () => void) => { + listeners.push(fn) + return disposable + }), + } + return callback({ report: vi.fn() }, token) + }) + return { + disposable, + cancel: () => { + cancelled = true + listeners.forEach((fn) => fn()) + }, + } +} + +describe("commitMessageGenerator", () => { + beforeEach(() => { + vi.clearAllMocks() + resetCommitMessageRequestState() + ;(vscode.window as unknown as { activeTextEditor?: vscode.TextEditor }).activeTextEditor = undefined + }) + + describe("cleanCommitMessage", () => { + it("removes markdown code fences and backticks", () => { + const input = "```markdown\nfeat(auth): add login flow\n```" + expect(cleanCommitMessage(input)).toBe("feat(auth): add login flow") + }) + + it("removes surrounding quotes", () => { + expect(cleanCommitMessage('"feat: simple commit"')).toBe("feat: simple commit") + expect(cleanCommitMessage("'feat: simple commit'")).toBe("feat: simple commit") + }) + + it("trims whitespace", () => { + expect(cleanCommitMessage(" fix: bug \n")).toBe("fix: bug") + }) + }) + + describe("buildCommitMessagePrompt", () => { + it("includes diff and instructions", () => { + const { prompt, truncated } = buildCommitMessagePrompt("diff --git a/file b/file\n+test") + expect(prompt).toContain("diff --git a/file b/file\n+test") + expect(prompt).toContain("Conventional Commits") + expect(truncated).toBe(false) + }) + + it.each([ + ["character", "x".repeat(DIFF_CHARACTER_LIMIT + 1)], + ["line", Array.from({ length: DIFF_LINE_LIMIT + 1 }, (_, i) => `+line ${i}`).join("\n")], + ])("reports truncation when the diff exceeds the %s limit", (_label, diff) => { + const { prompt, truncated } = buildCommitMessagePrompt(diff) + expect(truncated).toBe(true) + expect(prompt).toContain(COMMIT_MESSAGE_SYSTEM_PROMPT) + expect(prompt).toMatch(/\[\.\.\.\d+ (?:characters|lines) omitted\.\.\.\]/) + }) + + it("does not report truncation at exactly the character limit", () => { + const { truncated } = buildCommitMessagePrompt("x".repeat(DIFF_CHARACTER_LIMIT)) + expect(truncated).toBe(false) + }) + }) + + describe("omitIgnoredFiles", () => { + const blocked = new Set([".env", "keys/a b.pem", "conf/.env.pröd", 'conf/a"b.env', "conf/a\tb.env"]) + const isAllowed = (relativePath: string) => !blocked.has(relativePath) + const section = (header: string, ...rest: string[]) => [header, ...rest].join("\n") + const app = section("diff --git a/app.ts b/app.ts", "--- a/app.ts", "+++ b/app.ts", "@@ -1 +1 @@", "+x = 1") + + it.each([ + ["a changed file", section("diff --git a/.env b/.env", "--- a/.env", "+++ b/.env", "@@ -1 +1 @@", "+A=1")], + [ + "an added file", + section("diff --git a/.env b/.env", "--- /dev/null", "+++ b/.env", "@@ -0,0 +1 @@", "+A=1"), + ], + [ + "a deleted file", + section("diff --git a/.env b/.env", "--- a/.env", "+++ /dev/null", "@@ -1 +0,0 @@", "-A=1"), + ], + [ + "a file renamed from a blocked path", + section( + "diff --git a/.env b/x", + "rename from .env", + "rename to x", + "--- a/.env", + "+++ b/x", + "@@ -1 +1 @@", + "-A=1", + ), + ], + [ + "a pure rename", + section("diff --git a/x b/.env", "similarity index 100%", "rename from x", "rename to .env"), + ], + ["a copy", section("diff --git a/.env b/y", "copy from .env", "copy to y")], + [ + "a path with a space (Git adds a tab)", + section( + "diff --git a/keys/a b.pem b/keys/a b.pem", + "--- a/keys/a b.pem\t", + "+++ b/keys/a b.pem\t", + "@@ -1 +1 @@", + "+k", + ), + ], + [ + "a quoted path with octal escapes", + section( + 'diff --git "a/conf/.env.pr\\303\\266d" "b/conf/.env.pr\\303\\266d"', + '--- "a/conf/.env.pr\\303\\266d"', + '+++ "b/conf/.env.pr\\303\\266d"', + "@@ -1 +1 @@", + "+A=1", + ), + ], + [ + "a quoted path with an escaped quote", + section( + 'diff --git "a/conf/a\\"b.env" "b/conf/a\\"b.env"', + '--- "a/conf/a\\"b.env"', + '+++ "b/conf/a\\"b.env"', + "@@ -1 +1 @@", + "+A=1", + ), + ], + [ + "a quoted path with a C escape", + section( + 'diff --git "a/conf/a\\tb.env" "b/conf/a\\tb.env"', + '--- "a/conf/a\\tb.env"', + '+++ "b/conf/a\\tb.env"', + "@@ -1 +1 @@", + "+A=1", + ), + ], + [ + "custom prefixes (diff.srcPrefix and diff.dstPrefix)", + section("diff --git old/.env new/.env", "--- old/.env", "+++ new/.env", "@@ -1 +1 @@", "+A=1"), + ], + [ + "custom prefixes with more than one folder", + section("diff --git x/old/.env y/new/.env", "--- x/old/.env", "+++ y/new/.env", "@@ -1 +1 @@", "+A=1"), + ], + [ + "mnemonic prefixes", + section("diff --git i/.env w/.env", "--- i/.env", "+++ w/.env", "@@ -1 +1 @@", "+A=1"), + ], + ["no prefixes", section("diff --git .env .env", "--- .env", "+++ .env", "@@ -1 +1 @@", "+A=1")], + [ + "a CRLF diff", + section("diff --git a/.env b/.env\r", "--- a/.env\r", "+++ b/.env\r", "@@ -1 +1 @@\r", "+A=1\r"), + ], + [ + "a combined diff of a merge conflict", + section( + "diff --cc .env", + "index 1,2..3", + "--- a/.env", + "+++ b/.env", + "@@@ -1,1 -1,1 +1,1 @@@", + "++A=1", + ), + ], + ])("leaves out the content of %s and keeps its first line", (_label, ignored) => { + const [header = ""] = ignored.split("\n") + expect(omitIgnoredFiles(`${app}\n${ignored}\n${app}`, isAllowed)).toBe( + `${app}\n${header}\n${IGNORED_FILE_NOTE}\n${app}`, + ) + }) + + it.each([ + ["a diff without blocked files", app], + // The removed line `-- a/.env` and the added line `++ b/.env` look like path lines. + ["a file whose content has path lines after its first hunk", section(app, "--- a/.env", "+++ b/.env")], + ["the list of untracked files", "Untracked files:\n.env\nsrc/app.ts"], + ["an empty diff", ""], + [ + "a file with more lines than a call can take as arguments", + `${app}\n${Array(200_000).fill("+x").join("\n")}`, + ], + ])("keeps %s unchanged", (_label, diff) => { + expect(omitIgnoredFiles(diff, isAllowed)).toBe(diff) + }) + + it("leaves out a file with custom prefixes without a slash when the Git extension lists it", () => { + const ignored = section( + "diff --git old-.env new-.env", + "--- old-.env", + "+++ new-.env", + "@@ -1 +1 @@", + "+A=1", + ) + expect(omitIgnoredFiles(ignored, isAllowed, new Set([".env"]))).toBe( + `diff --git old-.env new-.env\n${IGNORED_FILE_NOTE}`, + ) + }) + + it.each([ + ["a changed file", ["--- a/src/x", "+++ b/src/y"], ["a/src/x", "src/x", "x", "b/src/y", "src/y", "y"]], + ["an added file", ["--- /dev/null", "+++ b/y"], ["b/y", "y"]], + [ + "a file with custom prefixes", + ["--- old-src/x", "+++ new-src/x"], + ["old-src/x", "x", "src/x", "new-src/x"], + ], + ])("checks each path of %s once, by folder and by listed path", (_label, pathLines, expected) => { + const checked: string[] = [] + const diff = section("diff --git a/x b/y", ...pathLines, "@@ -0,0 +1 @@", "--- a/z") + omitIgnoredFiles( + diff, + (relativePath) => { + checked.push(relativePath) + return true + }, + new Set(["src/x"]), + ) + expect(checked).toEqual(expected) + }) + + it("checks a bounded number of paths for a diff of many files", () => { + const files = Array.from({ length: 500 }, (_, i) => `src/feature/file${i}.ts`) + const diff = files + .map((file) => + section(`diff --git a/${file} b/${file}`, `--- a/${file}`, `+++ b/${file}`, "@@ -1 +1 @@", "+x"), + ) + .join("\n") + let checks = 0 + omitIgnoredFiles( + diff, + () => { + checks++ + return true + }, + new Set(files), + ) + // Each file: a/src/feature/fileN.ts and b/..., then src/feature/fileN.ts, feature/fileN.ts, fileN.ts. + expect(checks).toBe(files.length * 5) + }) + }) + + describe("getGitApi", () => { + it("returns undefined if git extension not found", async () => { + ;(vscode.extensions.getExtension as Mock).mockReturnValue(undefined) + const api = await getGitApi() + expect(api).toBeUndefined() + }) + + it("activates git extension if not active and returns API", async () => { + const mockApi = { repositories: [] } + const mockExt = { + isActive: false, + activate: vi.fn().mockResolvedValue(undefined), + exports: { + getAPI: vi.fn().mockReturnValue(mockApi), + }, + } + ;(vscode.extensions.getExtension as Mock).mockReturnValue(mockExt) + + const api = await getGitApi() + expect(mockExt.activate).toHaveBeenCalled() + expect(mockExt.exports.getAPI).toHaveBeenCalledWith(1) + expect(api).toBe(mockApi) + }) + }) + + describe("resolveGitRepository", () => { + it("returns undefined if repositories list is empty", () => { + const git: GitAPI = { repositories: [] } + expect(resolveGitRepository(git)).toBeUndefined() + }) + + it("resolves from repository object context directly", () => { + const repo: GitRepository = { + rootUri: makeUri("/workspace/repo"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const git: GitAPI = { repositories: [repo] } + + expect(resolveGitRepository(git, repo)).toBe(repo) + }) + + it("resolves a SourceControl context from the scm/title menu by rootUri", () => { + const repo1 = makeRepo("/workspace/repo1") + const repo2 = makeRepo("/workspace/repo2") + const git: GitAPI = { repositories: [repo1, repo2] } + const sourceControl = { id: "git", rootUri: makeUri("/workspace/repo2"), inputBox: { value: "" } } + + expect(resolveGitRepository(git, sourceControl)).toBe(repo2) + }) + + it("rejects a repository-shaped context that is not a known repository", () => { + const known = makeRepo("/workspace/repo1") + const other = makeRepo("/workspace/repo2") + const git: GitAPI = { repositories: [known, other] } + const fake = makeRepo("/workspace/attacker") + + expect(resolveGitRepository(git, fake)).toBeUndefined() + expect(fake.diff).not.toHaveBeenCalled() + }) + + it("returns the known repository, not the context object, when a fake context reuses its rootUri", () => { + const known = makeRepo("/workspace/repo") + const git: GitAPI = { repositories: [known, makeRepo("/workspace/other")] } + const fake = makeRepo("/workspace/repo") + + const resolved = resolveGitRepository(git, fake) + expect(resolved).toBe(known) + expect(resolved).not.toBe(fake) + }) + + it.each([ + ["a bare Uri", (root: vscode.Uri) => root], + ["a SourceControl rootUri", (root: vscode.Uri) => ({ rootUri: root })], + ])("matches %s by its scheme and fsPath without calling its methods", (_label, wrap) => { + const known = makeRepo("/workspace/repo") + const git: GitAPI = { repositories: [makeRepo("/workspace/other"), known] } + const forgedToString = vi.fn(() => "/workspace/repo") + const forged = { scheme: "file", fsPath: "/workspace/repo", toString: forgedToString } + + expect(resolveGitRepository(git, wrap(forged as unknown as vscode.Uri))).toBe(known) + expect(forgedToString).not.toHaveBeenCalled() + }) + + it.each([ + ["a different fsPath", { scheme: "file", fsPath: "/workspace/attacker" }], + ["a different scheme", { scheme: "untitled", fsPath: "/workspace/repo" }], + ])("rejects a forged Uri with %s even when its toString matches", (_label, fields) => { + const git: GitAPI = { repositories: [makeRepo("/workspace/repo"), makeRepo("/workspace/other")] } + const forgedToString = vi.fn(() => "/workspace/repo") + + expect(resolveGitRepository(git, { ...fields, toString: forgedToString })).toBeUndefined() + expect(forgedToString).not.toHaveBeenCalled() + }) + + it("rejects a fake context with a matching-looking inputBox", () => { + const git: GitAPI = { repositories: [makeRepo("/workspace/repo1"), makeRepo("/workspace/repo2")] } + const fake = { inputBox: { value: "" }, diff: vi.fn() } + + expect(resolveGitRepository(git, fake)).toBeUndefined() + expect(fake.diff).not.toHaveBeenCalled() + }) + + it("resolves from bare vscode.Uri context", () => { + const repo1: GitRepository = { + rootUri: makeUri("/workspace/repo1"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const repo2: GitRepository = { + rootUri: makeUri("/workspace/repo2"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const git: GitAPI = { repositories: [repo1, repo2] } + + expect(resolveGitRepository(git, makeUri("/workspace/repo2"))).toBe(repo2) + }) + + it("resolves from scm context with rootUri", () => { + const repo1: GitRepository = { + rootUri: makeUri("/workspace/repo1"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const repo2: GitRepository = { + rootUri: makeUri("/workspace/repo2"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const git: GitAPI = { repositories: [repo1, repo2] } + + expect(resolveGitRepository(git, { rootUri: makeUri("/workspace/repo2") })).toBe(repo2) + }) + + it("resolves from scm context with inputBox", () => { + const inputBox1 = { value: "" } + const inputBox2 = { value: "" } + const repo1: GitRepository = { + rootUri: makeUri("/workspace/repo1"), + inputBox: inputBox1, + diff: vi.fn(), + } + const repo2: GitRepository = { + rootUri: makeUri("/workspace/repo2"), + inputBox: inputBox2, + diff: vi.fn(), + } + const git: GitAPI = { repositories: [repo1, repo2] } + + expect(resolveGitRepository(git, { inputBox: inputBox2 })).toBe(repo2) + }) + + it("falls back to first repository when only one exists", () => { + const repo: GitRepository = { + rootUri: makeUri("/workspace/repo"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const git: GitAPI = { repositories: [repo] } + + expect(resolveGitRepository(git)).toBe(repo) + }) + + it("matches active editor URI if multiple repositories exist", () => { + const repo1: GitRepository = { + rootUri: makeUri("/workspace/repo1"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const repo2: GitRepository = { + rootUri: makeUri("/workspace/repo2"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const git: GitAPI = { repositories: [repo1, repo2] } + + const mutableWindow = vscode.window as unknown as { activeTextEditor?: vscode.TextEditor } + mutableWindow.activeTextEditor = { + document: { + uri: makeUri("/workspace/repo2/src/file.ts"), + }, + } as unknown as vscode.TextEditor // Structural test double providing document.uri + + expect(resolveGitRepository(git)).toBe(repo2) + }) + + it("returns undefined if bare vscode.Uri context does not match any repository", () => { + const repo1: GitRepository = { + rootUri: makeUri("/workspace/repo1"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const repo2: GitRepository = { + rootUri: makeUri("/workspace/repo2"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const git: GitAPI = { repositories: [repo1, repo2] } + + expect(resolveGitRepository(git, makeUri("/workspace/unknown"))).toBeUndefined() + }) + + it("returns undefined if scm context rootUri does not match any repository", () => { + const repo1: GitRepository = { + rootUri: makeUri("/workspace/repo1"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const repo2: GitRepository = { + rootUri: makeUri("/workspace/repo2"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const git: GitAPI = { repositories: [repo1, repo2] } + + expect(resolveGitRepository(git, { rootUri: makeUri("/workspace/unknown") })).toBeUndefined() + }) + + it("returns undefined if scm context inputBox does not match any repository", () => { + const repo1: GitRepository = { + rootUri: makeUri("/workspace/repo1"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const repo2: GitRepository = { + rootUri: makeUri("/workspace/repo2"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const git: GitAPI = { repositories: [repo1, repo2] } + + expect(resolveGitRepository(git, { inputBox: { value: "other" } })).toBeUndefined() + }) + + it("falls back to first repository when active editor does not match any repository", () => { + const repo1: GitRepository = { + rootUri: makeUri("/workspace/repo1"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const repo2: GitRepository = { + rootUri: makeUri("/workspace/repo2"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const git: GitAPI = { repositories: [repo1, repo2] } + + const mutableWindow = vscode.window as unknown as { activeTextEditor?: vscode.TextEditor } + mutableWindow.activeTextEditor = { + document: { + uri: makeUri("/workspace/other/file.ts"), + }, + } as unknown as vscode.TextEditor // Structural test double providing document.uri + + expect(resolveGitRepository(git)).toBe(repo1) + }) + + it("distinguishes repository roots on path segment boundaries", () => { + const repo1: GitRepository = { + rootUri: makeUri("/workspace/repo"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const repo2: GitRepository = { + rootUri: makeUri("/workspace/repo-other"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const git: GitAPI = { repositories: [repo1, repo2] } + + const mutableWindow = vscode.window as unknown as { activeTextEditor?: vscode.TextEditor } + mutableWindow.activeTextEditor = { + document: { + uri: makeUri("/workspace/repo-other/file.ts"), + }, + } as unknown as vscode.TextEditor + + expect(resolveGitRepository(git)).toBe(repo2) + }) + + it("matches longest root when repositories are nested", () => { + const parentRepo: GitRepository = { + rootUri: makeUri("/workspace/monorepo"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const childRepo: GitRepository = { + rootUri: makeUri("/workspace/monorepo/packages/nested"), + inputBox: { value: "" }, + diff: vi.fn(), + } + const git: GitAPI = { repositories: [parentRepo, childRepo] } + + const mutableWindow = vscode.window as unknown as { activeTextEditor?: vscode.TextEditor } + mutableWindow.activeTextEditor = { + document: { + uri: makeUri("/workspace/monorepo/packages/nested/src/index.ts"), + }, + } as unknown as vscode.TextEditor + + expect(resolveGitRepository(git)).toBe(childRepo) + }) + }) + + describe("getRepositoryDiff", () => { + it("prioritizes staged diff", async () => { + const repo: GitRepository = { + rootUri: makeUri("/workspace/repo"), + inputBox: { value: "" }, + diff: vi.fn().mockImplementation((cached?: boolean) => { + if (cached) return Promise.resolve("staged diff") + return Promise.resolve("working diff") + }), + } + + const diff = await getRepositoryDiff(repo) + expect(diff).toBe("staged diff") + expect(repo.diff).toHaveBeenCalledWith(true) + }) + + it("falls back to working tree diff if staged diff is empty", async () => { + const repo: GitRepository = { + rootUri: makeUri("/workspace/repo"), + inputBox: { value: "" }, + diff: vi.fn().mockImplementation((cached?: boolean) => { + if (cached) return Promise.resolve("") + return Promise.resolve("working diff") + }), + } + + const diff = await getRepositoryDiff(repo) + expect(diff).toBe("working diff") + expect(repo.diff).toHaveBeenCalledWith(true) + expect(repo.diff).toHaveBeenCalledWith(false) + }) + + it.each([ + ["the working tree", 1], + ["untracked files", 2], + ])("does not read %s after the signal aborts", async (_label, abortAfterCall) => { + // The signal aborts while the Git read with this call number is pending. + const controller = new AbortController() + const diff = vi.fn().mockImplementation(async () => { + if (diff.mock.calls.length === abortAfterCall) { + controller.abort() + } + return "" + }) + const workingTreeChanges = vi.fn(() => [{ uri: makeUri("/workspace/repo/new.ts"), status: 7 }]) + const repo = makeRepo("/workspace/repo", { + diff, + state: { + get workingTreeChanges() { + return workingTreeChanges() + }, + }, + }) + + await expect(getRepositoryDiff(repo, controller.signal)).resolves.toBeUndefined() + expect(diff).toHaveBeenCalledTimes(abortAfterCall) + expect(workingTreeChanges).not.toHaveBeenCalled() + }) + + it("rejects without reading the working tree when the staged diff fails", async () => { + const repo = makeRepo("/workspace/repo", { + diff: vi.fn().mockImplementation((cached?: boolean) => { + if (cached) return Promise.reject(new Error("Git diff staged failed")) + return Promise.resolve("working diff fallback") + }), + }) + + await expect(getRepositoryDiff(repo)).rejects.toThrow("Git diff staged failed") + expect(repo.diff).not.toHaveBeenCalledWith(false) + }) + + it("rejects with the staged error when both staged and working tree diffs fail", async () => { + const repo = makeRepo("/workspace/repo", { + diff: vi + .fn() + .mockImplementation((cached?: boolean) => + Promise.reject(new Error(cached ? "staged failed" : "working failed")), + ), + }) + + await expect(getRepositoryDiff(repo)).rejects.toThrow("staged failed") + }) + + it("returns undefined if both staged and working diffs are empty", async () => { + const repo: GitRepository = { + rootUri: makeUri("/workspace/repo"), + inputBox: { value: "" }, + diff: vi.fn().mockResolvedValue(""), + } + + const diff = await getRepositoryDiff(repo) + expect(diff).toBeUndefined() + }) + + it("rejects if working diff fails after empty staged diff", async () => { + const repo = makeRepo("/workspace/repo", { + diff: vi.fn().mockImplementation((cached?: boolean) => { + if (cached) return Promise.resolve("") + return Promise.reject(new Error("Git working tree diff failed")) + }), + }) + + await expect(getRepositoryDiff(repo)).rejects.toThrow("Git working tree diff failed") + }) + + it("lists untracked files relative to the repository root", async () => { + const repo = makeRepo("/home/alice/workspace/repo", { + diff: vi.fn().mockResolvedValue(""), + state: { + workingTreeChanges: [{ uri: makeUri("/home/alice/workspace/repo/src/new-file.ts"), status: 7 }], + }, + }) + + const diff = await getRepositoryDiff(repo) + // path.relative uses the platform separator. + expect(diff).toMatch(/^Untracked files:\nsrc[\\/]new-file\.ts$/) + }) + + it("lists untracked files from the separate untrackedChanges group", async () => { + const repo = makeRepo("/workspace/repo", { + diff: vi.fn().mockResolvedValue(""), + state: { + workingTreeChanges: [], + untrackedChanges: [{ uri: makeUri("/workspace/repo/brand-new.ts"), status: 7 }], + }, + }) + + expect(await getRepositoryDiff(repo)).toBe("Untracked files:\nbrand-new.ts") + }) + + it("de-duplicates a file listed in both untracked locations", async () => { + const repo = makeRepo("/workspace/repo", { + diff: vi.fn().mockResolvedValue(""), + state: { + workingTreeChanges: [ + { uri: makeUri("/workspace/repo/a.ts"), status: 7 }, + { uri: makeUri("/workspace/repo/modified.ts"), status: 5 }, + ], + untrackedChanges: [ + { uri: makeUri("/workspace/repo/a.ts"), status: 7 }, + { uri: makeUri("/workspace/repo/b.ts"), status: 7 }, + ], + }, + }) + + expect(await getRepositoryDiff(repo)).toBe("Untracked files:\na.ts\nb.ts") + }) + + it("returns undefined when both untracked locations are empty", async () => { + const repo = makeRepo("/workspace/repo", { + diff: vi.fn().mockResolvedValue(""), + state: { workingTreeChanges: [], untrackedChanges: [] }, + }) + + expect(await getRepositoryDiff(repo)).toBeUndefined() + }) + + it("surfaces untracked files when both diffs are empty", async () => { + const repo: GitRepository = { + rootUri: makeUri("/workspace/repo"), + inputBox: { value: "" }, + diff: vi.fn().mockResolvedValue(""), + state: { + workingTreeChanges: [ + { uri: makeUri("/workspace/repo/new-file.ts"), status: 7 }, // UNTRACKED + { uri: makeUri("/workspace/repo/modified.ts"), status: 5 }, // MODIFIED + ], + }, + } + + const diff = await getRepositoryDiff(repo) + expect(diff).toContain("Untracked files:") + expect(diff).toContain("new-file.ts") + expect(diff).not.toContain("modified.ts") + }) + + it("surfaces all untracked files when mixed with tracked changes", async () => { + const repo: GitRepository = { + rootUri: makeUri("/workspace/repo"), + inputBox: { value: "" }, + diff: vi.fn().mockResolvedValue(""), + state: { + workingTreeChanges: [ + { uri: makeUri("/workspace/repo/new-a.ts"), status: 7 }, // UNTRACKED + { uri: makeUri("/workspace/repo/new-b.ts"), status: 7 }, // UNTRACKED + { uri: makeUri("/workspace/repo/modified.ts"), status: 5 }, // MODIFIED (not untracked) + ], + }, + } + + const diff = await getRepositoryDiff(repo) + expect(diff).toContain("Untracked files:") + expect(diff).toContain("new-a.ts") + expect(diff).toContain("new-b.ts") + expect(diff).not.toContain("modified.ts") + }) + + it("returns undefined when both diffs are empty and no untracked files exist", async () => { + const repo: GitRepository = { + rootUri: makeUri("/workspace/repo"), + inputBox: { value: "" }, + diff: vi.fn().mockResolvedValue(""), + state: { + workingTreeChanges: [ + { uri: makeUri("/workspace/repo/modified.ts"), status: 5 }, // MODIFIED (not untracked) + ], + }, + } + + const diff = await getRepositoryDiff(repo) + expect(diff).toBeUndefined() + }) + }) + + describe("generateCommitMessage", () => { + let mockProvider: ClineProvider + let mockOutputChannel: vscode.OutputChannel + let mockRepo: GitRepository + + beforeEach(() => { + mockOutputChannel = { + appendLine: vi.fn(), + append: vi.fn(), + clear: vi.fn(), + hide: vi.fn(), + name: "test", + replace: vi.fn(), + show: vi.fn(), + dispose: vi.fn(), + } + + mockRepo = { + rootUri: makeUri("/workspace/repo"), + inputBox: { value: "" }, + diff: vi.fn().mockResolvedValue("diff content"), + } + + // Structural test double providing getState for generateCommitMessage + mockProvider = { + getState: vi.fn().mockResolvedValue({ + apiConfiguration: { + apiProvider: providerIdentifiers.anthropic, + apiKey: "test-key", + }, + }), + } as unknown as ClineProvider + + const mockGitApi: GitAPI = { + repositories: [mockRepo], + } + ;(vscode.extensions.getExtension as Mock).mockReturnValue({ + isActive: true, + exports: { + getAPI: () => mockGitApi, + }, + }) + + // Default withProgress mock: runs the callback immediately with a non-cancelled token. + // Individual tests may override this for cancellation or error scenarios. + ;(vscode.window.withProgress as Mock).mockImplementation((_opts, callback) => { + const progress = { report: vi.fn() } + const token = { + isCancellationRequested: false, + onCancellationRequested: vi.fn().mockReturnValue({ dispose: vi.fn() }), + } + return callback(progress, token) + }) + }) + + it("shows error if git extension is unavailable", async () => { + ;(vscode.extensions.getExtension as Mock).mockReturnValue(undefined) + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("Git extension not found or not enabled.") + }) + + it("shows error if no git repository found", async () => { + ;(vscode.extensions.getExtension as Mock).mockReturnValue({ + isActive: true, + exports: { + getAPI: () => ({ repositories: [] }), + }, + }) + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("No Git repository found.") + }) + + it("shows info if no diff is found", async () => { + mockRepo.diff = vi.fn().mockResolvedValue("") + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith(NO_CHANGES_MESSAGE) + }) + + it("reports a Git diff failure as an error instead of 'no changes'", async () => { + mockRepo.diff = vi.fn().mockRejectedValue(new Error("fatal: bad index file")) + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(vscode.window.showInformationMessage).not.toHaveBeenCalledWith(NO_CHANGES_MESSAGE) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "Failed to generate commit message: fatal: bad index file", + ) + expect(singleCompletionHandler).not.toHaveBeenCalled() + }) + + it("never reads from or writes to a command context that is not a known repository", async () => { + const fake = makeRepo("/workspace/attacker") + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + context: fake, + }) + + expect(fake.diff).not.toHaveBeenCalled() + expect(singleCompletionHandler).not.toHaveBeenCalled() + expect(fake.inputBox.value).toBe("") + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("No Git repository found.") + }) + + it("generates for the repository named by an scm/title SourceControl context", async () => { + ;(singleCompletionHandler as Mock).mockResolvedValue("fix: second repo") + const second = makeRepo("/workspace/second") + ;(vscode.extensions.getExtension as Mock).mockReturnValue({ + isActive: true, + exports: { getAPI: () => ({ repositories: [mockRepo, second] }) }, + }) + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + context: { rootUri: makeUri("/workspace/second"), inputBox: { value: "" } }, + }) + + expect(second.inputBox.value).toBe("fix: second repo") + expect(mockRepo.inputBox.value).toBe("") + }) + + it("warns after writing when the diff was truncated", async () => { + mockRepo.diff = vi.fn().mockResolvedValue("x".repeat(DIFF_CHARACTER_LIMIT + 1)) + ;(singleCompletionHandler as Mock).mockResolvedValue("feat: large change") + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(mockRepo.inputBox.value).toBe("feat: large change") + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(DIFF_TRUNCATED_MESSAGE) + }) + + it("does not warn about truncation for a diff within the limits", async () => { + ;(singleCompletionHandler as Mock).mockResolvedValue("feat: small change") + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(mockRepo.inputBox.value).toBe("feat: small change") + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + }) + + it("keeps text the user typed while the request was pending", async () => { + mockRepo.inputBox.value = "draft" + ;(singleCompletionHandler as Mock).mockImplementation(async () => { + mockRepo.inputBox.value = "typed by user" + return "feat: generated" + }) + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(mockRepo.inputBox.value).toBe("typed by user") + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith(DRAFT_CHANGED_MESSAGE) + }) + + it("replaces an unchanged draft with the generated message", async () => { + mockRepo.inputBox.value = "draft" + ;(singleCompletionHandler as Mock).mockResolvedValue("feat: generated") + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(mockRepo.inputBox.value).toBe("feat: generated") + expect(vscode.window.showInformationMessage).not.toHaveBeenCalledWith(DRAFT_CHANGED_MESSAGE) + }) + + it("aborts an older request for the same repository and sends the newer one after it settles", async () => { + const first = deferred() + let olderSignal: AbortSignal | undefined + ;(singleCompletionHandler as Mock) + .mockImplementationOnce((_config, _prompt, options: { abortSignal: AbortSignal }) => { + olderSignal = options.abortSignal + // This provider ignores the abort signal and settles later. + return first.promise + }) + .mockResolvedValueOnce("feat: newer") + + const older = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(singleCompletionHandler).toHaveBeenCalledTimes(1)) + const newer = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await older + expect(olderSignal?.aborted).toBe(true) + + await vi.waitFor(() => expect(mockProvider.getState).toHaveBeenCalledTimes(2)) + await new Promise((resolve) => setTimeout(resolve, 0)) + // No second provider request while the older one still runs. + expect(singleCompletionHandler).toHaveBeenCalledTimes(1) + + first.resolve("feat: older") + await newer + + expect(singleCompletionHandler).toHaveBeenCalledTimes(2) + expect(mockRepo.inputBox.value).toBe("feat: newer") + expect(vscode.window.showInformationMessage).not.toHaveBeenCalledWith(DRAFT_CHANGED_MESSAGE) + }) + + it("treats new Git API wrappers for one repository as the same repository", async () => { + // The VS Code Git API creates a new repository wrapper on each read of `repositories`. + // The wrappers share one underlying input box. + const sharedInputBox = { value: "" } + ;(vscode.extensions.getExtension as Mock).mockReturnValue({ + isActive: true, + exports: { + getAPI: () => ({ + get repositories() { + return [makeRepo("/workspace/repo", { inputBox: sharedInputBox })] + }, + }), + }, + }) + const first = deferred() + ;(singleCompletionHandler as Mock) + .mockImplementationOnce(() => first.promise) + .mockResolvedValueOnce("feat: newer") + + const older = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(singleCompletionHandler).toHaveBeenCalledTimes(1)) + const newer = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await older + first.resolve("feat: older") + await newer + + expect(singleCompletionHandler).toHaveBeenCalledTimes(2) + expect(sharedInputBox.value).toBe("feat: newer") + expect(vscode.window.showInformationMessage).not.toHaveBeenCalledWith(DRAFT_CHANGED_MESSAGE) + }) + + it("never runs two provider requests for one repository, even with several waiting requests", async () => { + const first = deferred() + ;(singleCompletionHandler as Mock) + .mockImplementationOnce(() => first.promise) + .mockResolvedValueOnce("feat: latest") + + const a = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(singleCompletionHandler).toHaveBeenCalledTimes(1)) + const b = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(mockProvider.getState).toHaveBeenCalledTimes(2)) + const c = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(mockProvider.getState).toHaveBeenCalledTimes(3)) + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(singleCompletionHandler).toHaveBeenCalledTimes(1) + + first.resolve("feat: first") + await Promise.all([a, b, c]) + + // The middle request is no longer the newest after the wait, so it sends nothing. + expect(singleCompletionHandler).toHaveBeenCalledTimes(2) + expect(mockRepo.inputBox.value).toBe("feat: latest") + }) + + it("keeps the latest request of each repository independent", async () => { + const otherRepo = makeRepo("/workspace/other") + ;(vscode.extensions.getExtension as Mock).mockReturnValue({ + isActive: true, + exports: { getAPI: () => ({ repositories: [mockRepo, otherRepo] }) }, + }) + const first = deferred() + const second = deferred() + ;(singleCompletionHandler as Mock) + .mockImplementationOnce(() => first.promise) + .mockImplementationOnce(() => second.promise) + + const forMockRepo = generateCommitMessage({ provider: mockProvider, context: mockRepo }) + const forOtherRepo = generateCommitMessage({ provider: mockProvider, context: otherRepo }) + await vi.waitFor(() => expect(singleCompletionHandler).toHaveBeenCalledTimes(2)) + + second.resolve("feat: other") + await forOtherRepo + first.resolve("feat: mock") + await forMockRepo + + expect(mockRepo.inputBox.value).toBe("feat: mock") + expect(otherRepo.inputBox.value).toBe("feat: other") + }) + + it("closes the progress immediately when cancelled while the LLM call is pending", async () => { + const { cancel, disposable } = useCancellableProgress() + let capturedSignal: AbortSignal | undefined + // The provider ignores the abort signal and never settles. + ;(singleCompletionHandler as Mock).mockImplementation((_config, _prompt, options) => { + capturedSignal = options.abortSignal as AbortSignal + return new Promise(() => {}) + }) + + const run = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(singleCompletionHandler).toHaveBeenCalled()) + cancel() + await run + + expect(capturedSignal?.aborted).toBe(true) + expect(disposable.dispose).toHaveBeenCalled() + expect(mockRepo.inputBox.value).toBe("") + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + }) + + it.each([ + ["a staged diff", true], + ["a working-tree diff", false], + ])("leaves files in .rooignore out of the prompt for %s", async (_label, staged) => { + const root = await mkdtemp(path.join(tmpdir(), "zoo-commit-")) + try { + await writeFile(path.join(root, ".rooignore"), ".env\nconfig/private/\n") + // The Git extension lists the changed files. It finds `.env` also behind custom prefixes. + const changes = [".env", "config/private/keys.json", "src/app.ts"].map((file) => ({ + uri: vscode.Uri.file(path.join(root, file)), + status: 5, + })) + mockRepo = makeRepo(root, { state: { indexChanges: changes, workingTreeChanges: changes } }) + useOnlyRepository(mockRepo) + const diff = [ + "diff --git a/.env b/.env", + "--- a/.env", + "+++ b/.env", + "@@ -1 +1 @@", + "-DB=old", + "+DB=hunter2", + "diff --git a/config/private/keys.json b/config/private/keys.json", + "new file mode 100644", + "--- /dev/null", + "+++ b/config/private/keys.json", + "@@ -0,0 +1 @@", + '+{"key":"hunter3"}', + "diff --git a/src/app.ts b/src/app.ts", + "--- a/src/app.ts", + "+++ b/src/app.ts", + "@@ -1 +1 @@", + "+export const port = 8080", + // With diff.srcPrefix=old- and diff.dstPrefix=new- + "diff --git old-.env new-.env", + "--- old-.env", + "+++ new-.env", + "@@ -1 +1 @@", + "+SESSION=hunter4", + ].join("\n") + mockRepo.diff = vi.fn((cached?: boolean) => Promise.resolve(cached === staged ? diff : "")) + ;(singleCompletionHandler as Mock).mockResolvedValue("chore: update config") + + await generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + + const prompt = (singleCompletionHandler as Mock).mock.calls[0][1] as string + expect(prompt).not.toContain("hunter2") + expect(prompt).not.toContain("hunter3") + expect(prompt).not.toContain("hunter4") + expect(prompt).toContain(`diff --git a/.env b/.env\n${IGNORED_FILE_NOTE}`) + expect(prompt).toContain( + `diff --git a/config/private/keys.json b/config/private/keys.json\n${IGNORED_FILE_NOTE}`, + ) + expect(prompt).toContain("+export const port = 8080") + // The controller watches `.rooignore` only for this run. + expect(watcherDispose).toHaveBeenCalledTimes(1) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it("stops before reading the provider settings when the user cancels while .rooignore is read", async () => { + const { cancel } = useCancellableProgress() + ;(vscode.workspace.createFileSystemWatcher as Mock).mockImplementationOnce(() => { + cancel() + return makeWatcher() + }) + + await generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + + expect(mockProvider.getState).not.toHaveBeenCalled() + expect(singleCompletionHandler).not.toHaveBeenCalled() + await vi.waitFor(() => expect(watcherDispose).toHaveBeenCalledTimes(1)) + }) + + it("stops without a provider request when .rooignore exists but cannot be read", async () => { + const root = await mkdtemp(path.join(tmpdir(), "zoo-commit-")) + try { + // A folder named .rooignore exists, but reading it as a file fails. + await mkdir(path.join(root, ".rooignore")) + vi.spyOn(console, "error").mockImplementation(() => {}) + mockRepo = makeRepo(root) + useOnlyRepository(mockRepo) + mockRepo.diff = vi.fn().mockResolvedValue("diff --git a/.env b/.env\n@@ -1 +1 @@\n+DB=hunter2") + + await generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + + expect(singleCompletionHandler).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + `Failed to generate commit message: ${ROOIGNORE_UNREADABLE_MESSAGE}`, + ) + expect(mockRepo.inputBox.value).toBe("") + } finally { + vi.restoreAllMocks() + await rm(root, { recursive: true, force: true }) + } + }) + + it("stops without a provider request when checking for .rooignore fails with EACCES", async () => { + const root = await mkdtemp(path.join(tmpdir(), "zoo-commit-")) + const accessDenied = Object.assign(new Error("permission denied"), { code: "EACCES" }) + const stat = vi.spyOn(fs, "lstat").mockRejectedValue(accessDenied) + try { + mockRepo = makeRepo(root) + useOnlyRepository(mockRepo) + mockRepo.diff = vi.fn().mockResolvedValue("diff --git a/.env b/.env\n@@ -1 +1 @@\n+DB=hunter2") + + await generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + + expect(stat).toHaveBeenCalledWith(path.join(root, ".rooignore")) + expect(singleCompletionHandler).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + `Failed to generate commit message: ${ROOIGNORE_UNREADABLE_MESSAGE}`, + ) + } finally { + stat.mockRestore() + await rm(root, { recursive: true, force: true }) + } + }) + + it("finds a renamed file by its original path behind custom prefixes", async () => { + const root = await mkdtemp(path.join(tmpdir(), "zoo-commit-")) + try { + await writeFile(path.join(root, ".rooignore"), ".env\n") + const renamed = { + uri: vscode.Uri.file(path.join(root, "moved.txt")), + originalUri: vscode.Uri.file(path.join(root, ".env")), + status: 3, + } + mockRepo = makeRepo(root, { state: { indexChanges: [renamed] } }) + useOnlyRepository(mockRepo) + // Without rename detection, the diff shows the old file as deleted. + const diff = "diff --git old-.env new-.env\n--- old-.env\n+++ /dev/null\n@@ -1 +0,0 @@\n-DB=hunter5" + mockRepo.diff = vi.fn().mockResolvedValue(diff) + ;(singleCompletionHandler as Mock).mockResolvedValue("chore: move config") + + await generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + + expect((singleCompletionHandler as Mock).mock.calls[0][1]).not.toContain("hunter5") + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it.skipIf(process.platform === "win32")( + "stops without a provider request when .rooignore is a link to a missing file", + async () => { + const root = await mkdtemp(path.join(tmpdir(), "zoo-commit-")) + try { + await symlink(path.join(root, "missing-rules"), path.join(root, ".rooignore")) + mockRepo = makeRepo(root) + useOnlyRepository(mockRepo) + mockRepo.diff = vi.fn().mockResolvedValue("diff --git a/.env b/.env\n@@ -1 +1 @@\n+DB=hunter2") + + await generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + + expect(singleCompletionHandler).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + `Failed to generate commit message: ${ROOIGNORE_UNREADABLE_MESSAGE}`, + ) + } finally { + await rm(root, { recursive: true, force: true }) + } + }, + ) + + it("sends the diff unchanged when the repository has no .rooignore", async () => { + const root = await mkdtemp(path.join(tmpdir(), "zoo-commit-")) + try { + mockRepo = makeRepo(root) + useOnlyRepository(mockRepo) + const diff = "diff --git a/.env b/.env\n--- a/.env\n+++ b/.env\n@@ -1 +1 @@\n+DB=example" + mockRepo.diff = vi.fn().mockResolvedValue(diff) + ;(singleCompletionHandler as Mock).mockResolvedValue("chore: update config") + + await generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + + expect((singleCompletionHandler as Mock).mock.calls[0][1]).toContain(diff) + } finally { + await rm(root, { recursive: true, force: true }) + } + }) + + it("does not read the working tree when cancelled while the staged diff is pending", async () => { + const { cancel } = useCancellableProgress() + const stagedDiff = deferred() + mockRepo.diff = vi.fn((cached?: boolean) => (cached ? stagedDiff.promise : Promise.resolve("working diff"))) + + const run = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(mockRepo.diff).toHaveBeenCalledWith(true)) + cancel() + await run + stagedDiff.resolve("") + await new Promise((resolve) => setTimeout(resolve, 0)) + + expect(mockRepo.diff).toHaveBeenCalledTimes(1) + expect(mockProvider.getState).not.toHaveBeenCalled() + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() + }) + + it("waits for a cancelled request that ignores the abort before it sends the retry", async () => { + const { cancel } = useCancellableProgress({ once: true }) + const cancelledRequest = deferred() + ;(singleCompletionHandler as Mock) + .mockImplementationOnce(() => cancelledRequest.promise) + .mockResolvedValueOnce("feat: retry") + + const first = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(singleCompletionHandler).toHaveBeenCalledTimes(1)) + cancel() + await first + + const retry = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(mockProvider.getState).toHaveBeenCalledTimes(2)) + await new Promise((resolve) => setTimeout(resolve, 0)) + // The retry does not start a second provider request while the cancelled one runs. + expect(singleCompletionHandler).toHaveBeenCalledTimes(1) + + cancelledRequest.resolve("feat: cancelled") + await retry + + expect(singleCompletionHandler).toHaveBeenCalledTimes(2) + expect(mockRepo.inputBox.value).toBe("feat: retry") + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + }) + + it("lets the user cancel a retry while it waits for the cancelled request", async () => { + const firstProgress = useCancellableProgress({ once: true }) + const retryProgress = useCancellableProgress({ once: true }) + const cancelledRequest = deferred() + ;(singleCompletionHandler as Mock).mockImplementationOnce(() => cancelledRequest.promise) + + const first = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(singleCompletionHandler).toHaveBeenCalledTimes(1)) + firstProgress.cancel() + await first + + const retry = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(mockProvider.getState).toHaveBeenCalledTimes(2)) + retryProgress.cancel() + await retry + + expect(singleCompletionHandler).toHaveBeenCalledTimes(1) + expect(mockRepo.inputBox.value).toBe("") + // A user cancel ends the wait quietly, without the "previous request is still running" warning. + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + cancelledRequest.resolve("feat: cancelled") + }) + + it("stops the retry with a message, without a second request, when the cancelled request outlasts the wait limit", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + try { + const { cancel } = useCancellableProgress({ once: true }) + const report = vi.fn() + ;(singleCompletionHandler as Mock).mockImplementationOnce(() => new Promise(() => {})) + + const first = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(singleCompletionHandler).toHaveBeenCalledTimes(1)) + cancel() + await first + + ;(vscode.window.withProgress as Mock).mockImplementationOnce((_opts, callback) => + callback( + { report }, + { isCancellationRequested: false, onCancellationRequested: () => ({ dispose: vi.fn() }) }, + ), + ) + const retry = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + // vi.waitFor advances fake timers by its poll interval, so keep a margin below the limit. + await vi.waitFor( + () => expect(report).toHaveBeenCalledWith({ message: WAITING_FOR_PREVIOUS_REQUEST_MESSAGE }), + { interval: 1 }, + ) + await vi.advanceTimersByTimeAsync(PREVIOUS_REQUEST_WAIT_MS - 1_000) + expect(singleCompletionHandler).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(1_000) + await retry + + expect(singleCompletionHandler).toHaveBeenCalledTimes(1) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith(PREVIOUS_REQUEST_STILL_RUNNING_MESSAGE) + expect(mockRepo.inputBox.value).toBe("") + } finally { + vi.useRealTimers() + } + }) + + it("clears the wait timer when the user cancels the wait", async () => { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }) + try { + const first = useCancellableProgress({ once: true }) + ;(singleCompletionHandler as Mock).mockImplementationOnce(() => new Promise(() => {})) + const firstRun = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(singleCompletionHandler).toHaveBeenCalledTimes(1)) + first.cancel() + await firstRun + + const retryProgress = useCancellableProgress({ once: true }) + const retry = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(vi.getTimerCount()).toBe(1), { interval: 1 }) + retryProgress.cancel() + await retry + + await vi.waitFor(() => expect(vi.getTimerCount()).toBe(0), { interval: 1 }) + expect(singleCompletionHandler).toHaveBeenCalledTimes(1) + } finally { + vi.useRealTimers() + } + }) + + it.each([ + ["succeeds", () => (singleCompletionHandler as Mock).mockResolvedValue("feat: done")], + ["fails", () => (singleCompletionHandler as Mock).mockRejectedValue(new Error("provider failed"))], + ["finds no Git extension", () => (vscode.extensions.getExtension as Mock).mockReturnValue(undefined)], + ])("removes the per-repository request state when the last request %s", async (_label, arrange) => { + arrange() + + await generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + + await vi.waitFor(() => expect(commitMessageRequestStateSize()).toBe(0)) + }) + + it("removes the request state after runs that stop before they find a repository", async () => { + const noRepositories: GitAPI = { repositories: [] } + ;(vscode.extensions.getExtension as Mock) + .mockReturnValueOnce(undefined) + .mockReturnValueOnce({ isActive: true, exports: { getAPI: () => noRepositories } }) + ;(singleCompletionHandler as Mock).mockResolvedValue("feat: done") + + await generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + expect(vscode.window.showErrorMessage).toHaveBeenNthCalledWith(1, "Git extension not found or not enabled.") + expect(vscode.window.showErrorMessage).toHaveBeenNthCalledWith(2, "No Git repository found.") + await generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + + expect(mockRepo.inputBox.value).toBe("feat: done") + await vi.waitFor(() => expect(commitMessageRequestStateSize()).toBe(0)) + }) + + it("does not let an older request that is still resolving Git replace a newer result", async () => { + const activation = deferred() + const gitApi: GitAPI = { repositories: [mockRepo] } + ;(vscode.extensions.getExtension as Mock).mockReturnValueOnce({ + isActive: false, + activate: () => activation.promise, + exports: { getAPI: () => gitApi }, + }) + ;(singleCompletionHandler as Mock).mockResolvedValue("feat: newer") + + const older = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + expect(mockRepo.inputBox.value).toBe("feat: newer") + mockRepo.inputBox.value = "typed after the newer result" + activation.resolve() + await older + + expect(singleCompletionHandler).toHaveBeenCalledTimes(1) + expect(mockRepo.inputBox.value).toBe("typed after the newer result") + await vi.waitFor(() => expect(commitMessageRequestStateSize()).toBe(0)) + }) + + it("does not wait when the cancelled request already settled", async () => { + const { cancel } = useCancellableProgress({ once: true }) + const cancelledRequest = deferred() + ;(singleCompletionHandler as Mock) + .mockImplementationOnce(() => cancelledRequest.promise) + .mockResolvedValueOnce("feat: retry") + + const first = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(singleCompletionHandler).toHaveBeenCalledTimes(1)) + cancel() + await first + cancelledRequest.resolve("feat: cancelled") + await new Promise((resolve) => setTimeout(resolve, 0)) + + await generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + + expect(singleCompletionHandler).toHaveBeenCalledTimes(2) + expect(mockRepo.inputBox.value).toBe("feat: retry") + }) + + it("does not report a provider rejection that arrives after cancellation", async () => { + const { cancel } = useCancellableProgress() + let rejectCompletion: (error: Error) => void = () => {} + ;(singleCompletionHandler as Mock).mockImplementation( + () => + new Promise((_resolve, reject) => { + rejectCompletion = reject + }), + ) + + const run = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(singleCompletionHandler).toHaveBeenCalled()) + cancel() + await run + rejectCompletion(new Error("late provider failure")) + await Promise.resolve() + + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + expect(mockRepo.inputBox.value).toBe("") + }) + + it("shows error if no valid API provider is configured", async () => { + mockProvider.getState = vi.fn().mockResolvedValue({ + apiConfiguration: {}, + }) + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "No valid API provider configured. Please configure an API provider in Zoo Code settings.", + ) + }) + + it("generates commit message and assigns it to inputBox.value", async () => { + const apiConfiguration = { + apiProvider: providerIdentifiers.anthropic, + apiModelId: "claude-sonnet-4-5", + apiKey: "test-key", + } + ;(mockProvider.getState as Mock).mockResolvedValue({ apiConfiguration }) + ;(singleCompletionHandler as Mock).mockResolvedValue("feat(core): implement git commit message") + ;(vscode.window.withProgress as Mock).mockImplementation((_opts, callback) => { + const progress = { report: vi.fn() } + const token = { + isCancellationRequested: false, + onCancellationRequested: vi.fn().mockReturnValue({ dispose: vi.fn() }), + } + return callback(progress, token) + }) + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + // The configured provider and model reach the request unchanged, with the diff and an abort signal. + expect(singleCompletionHandler).toHaveBeenCalledWith( + apiConfiguration, + expect.stringContaining("diff content"), + { + abortSignal: expect.any(AbortSignal), + }, + ) + expect(mockRepo.inputBox.value).toBe("feat(core): implement git commit message") + }) + + it("does not update inputBox if cancelled", async () => { + ;(singleCompletionHandler as Mock).mockResolvedValue("feat: should be cancelled") + ;(vscode.window.withProgress as Mock).mockImplementation((_opts, callback) => { + const progress = { report: vi.fn() } + let cancellationHandler: () => void = () => {} + let isCancelled = false + const token = { + get isCancellationRequested() { + return isCancelled + }, + onCancellationRequested: vi.fn((fn: () => void) => { + cancellationHandler = fn + return { dispose: vi.fn() } + }), + } + cancellationHandler() + isCancelled = true + return callback(progress, token) + }) + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(mockRepo.inputBox.value).toBe("") + }) + + it("skips provider and LLM call when cancelled while diff is pending", async () => { + let isCancelled = false + const cancellationHandlers: Array<() => void> = [] + // diff never resolves on its own — simulates a slow/stuck git process + mockRepo.diff = vi.fn().mockImplementation(() => new Promise(() => {})) + ;(vscode.window.withProgress as Mock).mockImplementation((_opts, callback) => { + const progress = { report: vi.fn() } + const token = { + get isCancellationRequested() { + return isCancelled + }, + onCancellationRequested: vi.fn((fn: () => void) => { + cancellationHandlers.push(fn) + return { dispose: vi.fn() } + }), + } + // Trigger cancellation after the race has started (next microtask) + void Promise.resolve().then(() => { + isCancelled = true + cancellationHandlers.forEach((fn) => fn()) + }) + return callback(progress, token) + }) + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(mockProvider.getState).not.toHaveBeenCalled() + expect(singleCompletionHandler).not.toHaveBeenCalled() + expect(mockRepo.inputBox.value).toBe("") + }) + + it("skips LLM call when cancelled after provider state resolves", async () => { + let isCancelled = false + ;(vscode.window.withProgress as Mock).mockImplementation((_opts, callback) => { + const progress = { report: vi.fn() } + const token = { + get isCancellationRequested() { + return isCancelled + }, + onCancellationRequested: vi.fn().mockReturnValue({ dispose: vi.fn() }), + } + return callback(progress, token) + }) + // Set cancelled = true inside getState so the guard after getState fires + mockProvider.getState = vi.fn().mockImplementation(async () => { + isCancelled = true + return { apiConfiguration: { apiProvider: providerIdentifiers.openai, apiKey: "sk-test" } } + }) + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(singleCompletionHandler).not.toHaveBeenCalled() + expect(mockRepo.inputBox.value).toBe("") + }) + + it("aborts the in-flight provider request when cancellation is requested", async () => { + // Collect ALL registered cancellation handlers so both abortController.abort() + // and the cancelPromise resolver are called when the test triggers cancellation. + const registeredHandlers: Array<() => void> = [] + let triggerCancellation: () => void = () => {} + let capturedSignal: AbortSignal | undefined + ;(singleCompletionHandler as Mock).mockImplementation((_config, _prompt, options) => { + capturedSignal = options.abortSignal as AbortSignal + triggerCancellation() + return Promise.resolve("feat: should be cancelled") + }) + ;(vscode.window.withProgress as Mock).mockImplementation((_opts, callback) => { + const progress = { report: vi.fn() } + const token = { + isCancellationRequested: false, + onCancellationRequested: vi.fn((fn: () => void) => { + registeredHandlers.push(fn) + triggerCancellation = () => registeredHandlers.forEach((h) => h()) + return { dispose: vi.fn() } + }), + } + return callback(progress, token) + }) + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(capturedSignal?.aborted).toBe(true) + expect(mockRepo.inputBox.value).toBe("") + }) + + it("does not update inputBox and shows warning if generated message is empty", async () => { + mockRepo.inputBox.value = "preserved value" + const mockDisposable = { dispose: vi.fn() } + ;(singleCompletionHandler as Mock).mockResolvedValue(" ") + ;(vscode.window.withProgress as Mock).mockImplementation((_opts, callback) => { + const progress = { report: vi.fn() } + const token = { + isCancellationRequested: false, + onCancellationRequested: vi.fn().mockReturnValue(mockDisposable), + } + return callback(progress, token) + }) + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(mockRepo.inputBox.value).toBe("preserved value") + expect(mockDisposable.dispose).toHaveBeenCalled() + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith("No commit message generated.") + }) + + it("stays quiet when the provider rejects synchronously on the user's cancel", async () => { + const { cancel } = useCancellableProgress() + ;(singleCompletionHandler as Mock).mockImplementation( + (_config, _prompt, options: { abortSignal: AbortSignal }) => + new Promise((_resolve, reject) => { + options.abortSignal.addEventListener("abort", () => { + const abortError = new Error("This operation was aborted") + abortError.name = "AbortError" + reject(abortError) + }) + }), + ) + + const run = generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + await vi.waitFor(() => expect(singleCompletionHandler).toHaveBeenCalled()) + cancel() + await run + + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled() + expect(mockOutputChannel.appendLine).not.toHaveBeenCalled() + expect(mockRepo.inputBox.value).toBe("") + }) + + it.each([ + ["a message that mentions 'aborted'", "request aborted by server", "Error"], + ["a provider timeout", "The operation was aborted due to timeout", "TimeoutError"], + ["an AbortError the user did not cause", "This operation was aborted", "AbortError"], + ])("reports %s when the user did not cancel", async (_label, message, name) => { + const error = new Error(message) + error.name = name + ;(singleCompletionHandler as Mock).mockRejectedValue(error) + + await generateCommitMessage({ provider: mockProvider, outputChannel: mockOutputChannel }) + + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(`Failed to generate commit message: ${message}`) + expect(mockOutputChannel.appendLine).toHaveBeenCalledWith(`[generateGitCommitMessage] failed: ${message}`) + expect(mockRepo.inputBox.value).toBe("") + }) + + it("handles non-Error objects gracefully and shows error message", async () => { + ;(vscode.window.withProgress as Mock).mockRejectedValue("String-based error") + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( + expect.stringContaining("[generateGitCommitMessage] failed: String-based error"), + ) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "Failed to generate commit message: String-based error", + ) + }) + + it("handles errors gracefully and shows error message", async () => { + ;(vscode.window.withProgress as Mock).mockRejectedValue(new Error("Network error")) + + await generateCommitMessage({ + provider: mockProvider, + outputChannel: mockOutputChannel, + }) + + expect(mockOutputChannel.appendLine).toHaveBeenCalledWith( + expect.stringContaining("[generateGitCommitMessage] failed: Network error"), + ) + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( + "Failed to generate commit message: Network error", + ) + }) + }) +}) diff --git a/src/services/git/commitMessageGenerator.ts b/src/services/git/commitMessageGenerator.ts new file mode 100644 index 0000000000..86afd3e487 --- /dev/null +++ b/src/services/git/commitMessageGenerator.ts @@ -0,0 +1,660 @@ +import fs from "fs/promises" +import * as path from "path" +import * as vscode from "vscode" +import type { ProviderSettings } from "@roo-code/types" + +import { RooIgnoreController } from "../../core/ignore/RooIgnoreController" +import { ClineProvider } from "../../core/webview/ClineProvider" +import { truncateOutput } from "../../integrations/misc/extract-text" +import { singleCompletionHandler } from "../../utils/single-completion-handler" + +export interface GitRepositoryChange { + readonly uri: vscode.Uri + readonly originalUri?: vscode.Uri + readonly status: number +} + +export interface GitRepositoryState { + readonly indexChanges?: ReadonlyArray + readonly mergeChanges?: ReadonlyArray + readonly workingTreeChanges?: ReadonlyArray + readonly untrackedChanges?: ReadonlyArray +} + +export interface GitRepository { + readonly rootUri: vscode.Uri + readonly inputBox: { + value: string + } + readonly state?: GitRepositoryState + diff(cached?: boolean): Promise +} + +export interface GitAPI { + readonly repositories: readonly GitRepository[] +} + +export interface GitExtension { + readonly enabled?: boolean + getAPI(version: 1): GitAPI +} + +export interface GenerateCommitMessageOptions { + provider: ClineProvider + outputChannel?: vscode.OutputChannel + context?: unknown +} + +export interface CommitMessagePrompt { + prompt: string + truncated: boolean +} + +export const COMMIT_MESSAGE_SYSTEM_PROMPT = `You are an expert developer specializing in Git commit messages. +Generate a concise, meaningful Git commit message for the provided diff following the Conventional Commits specification (v1.0.0). + +Guidelines: +1. Format: (): + [optional body] + [optional footer(s)] +2. Common types: + - feat: A new feature + - fix: A bug fix + - docs: Documentation changes + - style: Formatting or code style changes (no logic change) + - refactor: Refactoring code without changing behavior + - perf: Performance improvements + - test: Adding or updating tests + - build: Changes affecting build systems or dependencies + - ci: CI/CD configuration changes + - chore: Other maintenance changes +3. Use imperative, present tense ("add" not "added", "fix" not "fixes"). +4. Keep the subject line within 72 characters and do not end with a period. +5. If the changes warrant explanation, include a blank line followed by a concise body or bullet points detailing what changed and why. +6. Return ONLY the commit message. Do NOT include markdown code blocks, quotes, or any introductory or concluding text. +7. Never output secrets, passwords, or personal identifiable information in commit messages.` + +export const DIFF_LINE_LIMIT = 1000 +export const DIFF_CHARACTER_LIMIT = 50_000 + +const GENERATING_TITLE = "Generating commit message..." +const NO_PROVIDER_MESSAGE = "No valid API provider configured. Please configure an API provider in Zoo Code settings." +const ignore = (): undefined => undefined +export const NO_CHANGES_MESSAGE = "No staged or working directory changes found to generate commit message." +export const DRAFT_CHANGED_MESSAGE = + "The commit message box changed while Zoo Code generated a message. Your text was kept. Run the command again to replace it." +export const DIFF_TRUNCATED_MESSAGE = + "The diff was too large and Zoo Code shortened it before generation. Make sure the commit message covers all changes." + +// vscode.git Status.UNTRACKED +const UNTRACKED_STATUS = 7 + +// The first line of each file in a diff, also of a combined diff during a merge conflict. +const DIFF_HEADER = /^diff --(?:git|cc|combined) / +// A line before the first hunk that names one path of the file. A renamed or copied file has two. +// Git adds a tab after a `---` or `+++` path that contains a space. +const DIFF_PATH_LINE = /^(?:--- |\+\+\+ |rename from |rename to |copy from |copy to )([^\t\r\n]+)/ +const GIT_PATH_ESCAPES: Record = { a: "\x07", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v" } +export const IGNORED_FILE_NOTE = "(Content left out: the file is in .rooignore.)" +export const ROOIGNORE_UNREADABLE_MESSAGE = "Cannot read .rooignore. No diff was sent." + +/** + * Accesses the VS Code Git extension API. + */ +export async function getGitApi(): Promise { + const gitExtension = vscode.extensions.getExtension("vscode.git") + if (!gitExtension) { + return undefined + } + if (!gitExtension.isActive) { + await gitExtension.activate() + } + return gitExtension.exports?.getAPI(1) +} + +interface UriFields { + scheme: string + fsPath: string +} + +/** + * Reads `scheme` and `fsPath` from an untrusted Uri-like value once, as plain strings. No method of + * the value is called, so a forged `toString` cannot run. + */ +function readUriFields(value: unknown): UriFields | undefined { + if (typeof value !== "object" || value === null) { + return undefined + } + const { scheme, fsPath } = value as { scheme?: unknown; fsPath?: unknown } + return typeof scheme === "string" && typeof fsPath === "string" ? { scheme, fsPath } : undefined +} + +function findRepositoryByRoot(git: GitAPI, root: UriFields): GitRepository | undefined { + return git.repositories.find((r) => r.rootUri.scheme === root.scheme && r.rootUri.fsPath === root.fsPath) +} + +/** + * Resolves the Git repository for an optional SCM command context. + * + * The command is public, so the context is untrusted. The result is always an entry of + * `git.repositories`. The function never returns the context object and never calls its methods. + */ +export function resolveGitRepository(git: GitAPI, context?: unknown): GitRepository | undefined { + if (!git.repositories || git.repositories.length === 0) { + return undefined + } + + if (context && typeof context === "object") { + const known = git.repositories.find((r) => r === context) + if (known) { + return known + } + + // A bare Uri, or a SourceControl from the scm/title menu (rootUri + inputBox). + // When an explicit context matches no repository, return undefined instead of + // silently picking a different repository. + const contextUri = readUriFields(context) + if (contextUri) { + return findRepositoryByRoot(git, contextUri) + } + + const sc = context as { rootUri?: unknown; inputBox?: unknown } + const sourceControlRoot = readUriFields(sc.rootUri) + if (sourceControlRoot) { + return findRepositoryByRoot(git, sourceControlRoot) + } + + if (sc.inputBox) { + return git.repositories.find((r) => r.inputBox === sc.inputBox) + } + } + + if (git.repositories.length === 1) { + return git.repositories[0] + } + + const activeDocUri = vscode.window.activeTextEditor?.document.uri + if (activeDocUri) { + const matchingRepos = git.repositories.filter((r) => { + const root = r.rootUri.fsPath + return ( + activeDocUri.fsPath === root || + activeDocUri.fsPath.startsWith(root + "/") || + activeDocUri.fsPath.startsWith(root + "\\") + ) + }) + if (matchingRepos.length > 0) { + matchingRepos.sort((a, b) => b.rootUri.fsPath.length - a.rootUri.fsPath.length) + return matchingRepos[0] + } + } + + return git.repositories[0] +} + +/** + * Retrieves the diff from the repository. Staged changes come first. Working tree changes are used + * only when nothing is staged, and untracked files only when both diffs are empty. + * + * A failed `git diff` rejects. It is not reported as "no changes", because a failed staged read + * would otherwise make the message describe unstaged changes that the next commit does not include. + * + * When `signal` is aborted, no further Git read starts and the result is undefined. + */ +export async function getRepositoryDiff(repository: GitRepository, signal?: AbortSignal): Promise { + const staged = (await repository.diff(true))?.trim() + if (staged) { + return staged + } + if (signal?.aborted) { + return undefined + } + + const workingTree = (await repository.diff(false))?.trim() + if (workingTree) { + return workingTree + } + if (signal?.aborted) { + return undefined + } + + // `git diff` omits untracked files; surface them as a plain listing so the + // LLM can still generate an "initial commit" or "add files" message. + // With `git.untrackedChanges: "separate"` they are in `untrackedChanges`, otherwise in + // `workingTreeChanges`. Read both and de-duplicate by path. + // Paths are relative to the repository root so absolute local paths are not sent. + const state = repository.state + const untrackedPaths = new Set( + [ + ...(state?.workingTreeChanges ?? []).filter((c) => c.status === UNTRACKED_STATUS), + ...(state?.untrackedChanges ?? []), + ].map((c) => c.uri.fsPath), + ) + if (untrackedPaths.size > 0) { + const rootPath = repository.rootUri.fsPath + const fileList = [...untrackedPaths].map((p) => path.relative(rootPath, p) || p).join("\n") + return `Untracked files:\n${fileList}` + } + + return undefined +} + +/** + * Reads a path as Git writes it. A path with special characters is quoted, and its special and + * non-ASCII characters are C escapes (`"b/.env.pr\303\266d"` is `b/.env.pröd`). + */ +function unquoteGitPath(value: string): string { + if (!value.startsWith('"') || !value.endsWith('"')) { + return value + } + const quoted = value.slice(1, -1) + const bytes: Buffer[] = [] + let copiedUpTo = 0 + for (const escape of quoted.matchAll(/\\([0-7]{3}|.)/g)) { + const [sequence, code = ""] = escape + bytes.push(Buffer.from(quoted.slice(copiedUpTo, escape.index), "utf8")) + const isOctal = code.length === 3 + bytes.push(isOctal ? Buffer.from([parseInt(code, 8)]) : Buffer.from(GIT_PATH_ESCAPES[code] ?? code, "utf8")) + copiedUpTo = escape.index + sequence.length + } + bytes.push(Buffer.from(quoted.slice(copiedUpTo), "utf8")) + return Buffer.concat(bytes).toString("utf8") +} + +/** + * True when `.rooignore` blocks a path of the diff section (paths are read before its first hunk). + * `changedPaths` are the repository-relative paths of the changed files that the Git extension lists. + */ +function isSectionBlocked( + section: string[], + isAllowed: (relativePath: string) => boolean, + changedPaths: ReadonlySet, +): boolean { + const firstHunk = section.findIndex((line) => line.startsWith("@@")) + const candidates = new Set() + for (const line of section.slice(0, firstHunk === -1 ? section.length : firstHunk)) { + const [, written] = DIFF_PATH_LINE.exec(line) ?? [] + if (written === undefined || written === "/dev/null") { + continue + } + // The path can start with a prefix that is not part of it: `a/` and `b/` by default, `i/` or `w/` with + // diff.mnemonicPrefix, any text with diff.srcPrefix and diff.dstPrefix (`old-.env`), or none with + // diff.noPrefix. The path is checked as written, without each number of leading folders, and as + // each listed changed path that it ends with. A file can then be left out by a rule for another + // path (`/.env` for `src/.env`), but a blocked file is never kept. + const gitPath = unquoteGitPath(written) + const segments = gitPath.split("/") + segments.forEach((_, start) => candidates.add(segments.slice(start).join("/"))) + for (let start = 0; start < gitPath.length; start++) { + const suffix = gitPath.slice(start) + if (changedPaths.has(suffix)) { + candidates.add(suffix) + } + } + } + return [...candidates].some((candidate) => !isAllowed(candidate)) +} + +/** + * Leaves out the content of each file in the diff that `.rooignore` blocks, the same rule that keeps + * these files out of the chat. The first line of the file stays, so the commit message can name it. + * The list of untracked files has no path lines, so it is kept as it is. + */ +export function omitIgnoredFiles( + diff: string, + isAllowed: (relativePath: string) => boolean, + changedPaths: ReadonlySet = new Set(), +): string { + const kept: string[] = [] + let section: string[] = [] + const closeSection = () => { + const [header = ""] = section + // One push per line: spreading a large file into push() would exceed the argument limit. + for (const line of isSectionBlocked(section, isAllowed, changedPaths) ? [header, IGNORED_FILE_NOTE] : section) { + kept.push(line) + } + section = [] + } + for (const line of diff.split("\n")) { + if (DIFF_HEADER.test(line)) { + closeSection() + } + section.push(line) + } + closeSection() + return kept.join("\n") +} + +/** + * True only when nothing is at `filePath`. Any other error (for example EACCES) counts as present, so + * the caller stops instead of sending files that the unread `.rooignore` could block. + */ +async function isMissing(filePath: string): Promise { + try { + // lstat: a symbolic link to a missing file is present, and the controller cannot read it. + await fs.lstat(filePath) + return false + } catch (error) { + const code = error instanceof Error && "code" in error ? error.code : undefined + return code === "ENOENT" || code === "ENOTDIR" + } +} + +/** + * The diff without the content of files that `.rooignore` in the repository root blocks. Rejects when + * `.rooignore` exists but cannot be read, because the controller then allows every file. + */ +async function withoutIgnoredFiles(repository: GitRepository, diff: string): Promise { + const root = repository.rootUri.fsPath + const rooIgnore = new RooIgnoreController(root) + try { + await rooIgnore.initialize() + if (rooIgnore.rooIgnoreContent === undefined && !(await isMissing(path.join(root, ".rooignore")))) { + throw new Error(ROOIGNORE_UNREADABLE_MESSAGE) + } + const state = repository.state + const changes = [state?.indexChanges, state?.mergeChanges, state?.workingTreeChanges, state?.untrackedChanges] + const changedPaths = new Set( + changes + .flatMap((group) => group ?? []) + .flatMap((change) => [change.uri, change.originalUri ?? change.uri]) + .map((uri) => path.relative(root, uri.fsPath).split(path.sep).join("/")), + ) + return omitIgnoredFiles(diff, (relativePath) => rooIgnore.validateAccess(relativePath), changedPaths) + } finally { + rooIgnore.dispose() + } +} + +/** + * Cleans the commit message output from LLM completions. + */ +export function cleanCommitMessage(message: string): string { + let cleaned = message.trim() + if (cleaned.startsWith("```")) { + cleaned = cleaned.replace(/^```[a-zA-Z]*\r?\n?/, "") + cleaned = cleaned.replace(/\r?\n?```$/, "") + cleaned = cleaned.trim() + } + if ((cleaned.startsWith('"') && cleaned.endsWith('"')) || (cleaned.startsWith("'") && cleaned.endsWith("'"))) { + cleaned = cleaned.slice(1, -1).trim() + } + return cleaned +} + +/** + * Builds the full prompt to generate a commit message from a git diff. + * `truncated` is true when the diff exceeded the line or character limit and was shortened. + */ +export function buildCommitMessagePrompt(diff: string): CommitMessagePrompt { + const truncatedDiff = truncateOutput(diff, DIFF_LINE_LIMIT, DIFF_CHARACTER_LIMIT) + return { + prompt: `${COMMIT_MESSAGE_SYSTEM_PROMPT}\n\nDiff:\n\`\`\`diff\n${truncatedDiff}\n\`\`\`\n\nCommit Message:`, + truncated: truncatedDiff !== diff, + } +} + +// Invocation order for the stale-write check. Numbers are assigned before the first await, so they +// follow call order. The latest number is tracked per repository so that a request for one +// repository never discards the result for another. +let invocationCounter = 0 +// The newest invocation per repository, and how many running invocations hold the entry. Keyed by scheme +// and root path, not by the repository object: the Git API returns new wrapper objects for the same +// repository on each read of `repositories`. +interface RepositoryOwner { + latest: number + holders: number +} +const ownersByRepository = new Map() +// Invocations that have a number but no repository yet. An entry is removed only when no invocation holds +// it and none is still resolving Git: a removed entry would let such an older invocation claim the repository. +let resolvingInvocations = 0 + +function repositoryKey(repository: GitRepository): string { + return `${repository.rootUri.scheme}:${repository.rootUri.fsPath}` +} + +// The provider requests in flight, per repository, until each one settles. At most one provider request +// per repository runs at a time: a newer request first aborts the older ones (their results would be +// discarded anyway) and waits until they settle, because a provider that ignores the abort signal keeps +// working after the abort. The wait is capped: when an older request is still running after the cap, +// the newer request stops with a message and starts no provider request. +interface InFlightRequest { + settled: Promise + cancel: () => void +} +const inFlightRequestsByRepository = new Map>() +export const PREVIOUS_REQUEST_WAIT_MS = 30_000 +export const WAITING_FOR_PREVIOUS_REQUEST_MESSAGE = "Waiting for the previous request to finish..." +export const PREVIOUS_REQUEST_STILL_RUNNING_MESSAGE = + "The previous request is still running, so Zoo Code did not start a new one. Try again when it finishes." + +/** + * Clears the per-repository request state, so that tests do not share it. + * @internal + */ +export function resetCommitMessageRequestState(): void { + ownersByRepository.clear() + inFlightRequestsByRepository.clear() + resolvingInvocations = 0 +} + +/** + * The number of repositories with request state, for tests that check the cleanup. + * @internal + */ +export function commitMessageRequestStateSize(): number { + return ownersByRepository.size + inFlightRequestsByRepository.size +} + +/** Resolves to true when `work` settles, or to false after `ms` milliseconds or on abort, whichever comes first. */ +function settlesWithin(work: Promise, ms: number, signal: AbortSignal): Promise { + let timer: ReturnType | undefined + const timeout = new Promise((resolve) => { + timer = setTimeout(() => resolve(false), ms) + signal.addEventListener("abort", () => resolve(false), { once: true }) + }) + return Promise.race([work.then(() => true), timeout]).finally(() => clearTimeout(timer)) +} + +/** Tracks a provider request for the repository until it settles. */ +function trackInFlight(key: string, request: InFlightRequest) { + let requests = inFlightRequestsByRepository.get(key) + if (!requests) { + requests = new Set() + inFlightRequestsByRepository.set(key, requests) + } + requests.add(request) + void request.settled.then(() => { + requests.delete(request) + if (requests.size === 0 && inFlightRequestsByRepository.get(key) === requests) { + inFlightRequestsByRepository.delete(key) + } + }) +} + +interface GenerationRun { + repository: GitRepository + provider: ClineProvider + ownerKey: string + owner: RepositoryOwner + invocationId: number + draft: string +} + +/** The steps inside the cancellable progress notification. Errors reach the caller's catch. */ +async function runGeneration( + { repository, provider, ownerKey, owner, invocationId, draft }: GenerationRun, + progress: vscode.Progress<{ message?: string }>, + token: vscode.CancellationToken, +): Promise { + // One listener aborts the provider request and ends every pending wait below, so the + // notification closes as soon as the user cancels, even when Git or the provider + // ignores the abort signal. + const abortController = new AbortController() + let resolveCancelled: () => void = () => {} + const cancelled = new Promise((resolve) => { + resolveCancelled = () => resolve(undefined) + }) + const cancel = () => { + abortController.abort() + resolveCancelled() + } + const cancellationListener = token.onCancellationRequested(cancel) + if (token.isCancellationRequested) { + cancel() + } + const isCancelled = () => token.isCancellationRequested || abortController.signal.aborted + // A rejection caused by the user's cancel (for example, a provider that rejects synchronously on + // abort and wins the race) ends the step quietly. Any other rejection reaches the caller's catch. + function untilCancelled(work: Promise): Promise { + const guarded = work.catch((error: unknown) => (isCancelled() ? undefined : Promise.reject(error))) + return Promise.race([guarded, cancelled]) + } + + try { + if (isCancelled()) { + return + } + + const diff = await untilCancelled(getRepositoryDiff(repository, abortController.signal)) + if (isCancelled()) { + return + } + if (!diff) { + vscode.window.showInformationMessage(NO_CHANGES_MESSAGE) + return + } + // The filter step never resolves to undefined, so undefined means the user cancelled. + const visibleDiff = await untilCancelled(withoutIgnoredFiles(repository, diff)) + if (visibleDiff === undefined) { + return + } + + const state = await untilCancelled(provider.getState()) + if (isCancelled()) { + return + } + const apiConfiguration = state?.apiConfiguration + if (!apiConfiguration || !apiConfiguration.apiProvider) { + vscode.window.showErrorMessage(NO_PROVIDER_MESSAGE) + return + } + + // Only the newest request for a repository calls the provider. + if (owner.latest !== invocationId) { + return + } + + // Abort older provider requests for this repository and wait until they settle, so that + // provider requests for one repository never overlap. The wait itself can be cancelled. + const older = inFlightRequestsByRepository.get(ownerKey) + if (older && older.size > 0) { + const olderRequests = [...older] + olderRequests.forEach((request) => request.cancel()) + progress.report({ message: WAITING_FOR_PREVIOUS_REQUEST_MESSAGE }) + const olderSettled = Promise.all(olderRequests.map((request) => request.settled)).then(ignore) + const settled = await untilCancelled( + settlesWithin(olderSettled, PREVIOUS_REQUEST_WAIT_MS, abortController.signal), + ) + if (isCancelled()) { + return + } + if (!settled) { + vscode.window.showWarningMessage(PREVIOUS_REQUEST_STILL_RUNNING_MESSAGE) + return + } + // A newer request for this repository came in during the wait and owns the input box. + if (owner.latest !== invocationId) { + return + } + } + + const { prompt, truncated } = buildCommitMessagePrompt(visibleDiff) + const completion = singleCompletionHandler(apiConfiguration as ProviderSettings, prompt, { + abortSignal: abortController.signal, + }) + trackInFlight(ownerKey, { settled: completion.then(ignore, ignore), cancel }) + const rawMessage = await untilCancelled(completion) + if (isCancelled() || rawMessage === undefined) { + return + } + + // A newer request for this repository owns the input box now. + if (owner.latest !== invocationId) { + return + } + + const commitMessage = cleanCommitMessage(rawMessage) + if (!commitMessage) { + vscode.window.showWarningMessage("No commit message generated.") + return + } + + // Do not overwrite text the user typed while the request was pending. + if (repository.inputBox.value !== draft) { + vscode.window.showInformationMessage(DRAFT_CHANGED_MESSAGE) + return + } + + repository.inputBox.value = commitMessage + if (truncated) { + vscode.window.showWarningMessage(DIFF_TRUNCATED_MESSAGE) + } + } finally { + cancellationListener.dispose() + } +} + +/** + * Generates a commit message using the active LLM provider and populates the SCM input box. + */ +export async function generateCommitMessage(options: GenerateCommitMessageOptions): Promise { + const { provider, outputChannel, context } = options + const invocationId = ++invocationCounter + resolvingInvocations++ + let owner: RepositoryOwner | undefined + + try { + const git = await getGitApi() + if (!git) { + vscode.window.showErrorMessage("Git extension not found or not enabled.") + return + } + + const repository = resolveGitRepository(git, context) + if (!repository) { + vscode.window.showErrorMessage("No Git repository found.") + return + } + + const ownerKey = repositoryKey(repository) + owner = ownersByRepository.get(ownerKey) ?? { latest: 0, holders: 0 } + ownersByRepository.set(ownerKey, owner) + owner.latest = Math.max(owner.latest, invocationId) + owner.holders++ + resolvingInvocations-- + const draft = repository.inputBox.value + + const run: GenerationRun = { repository, provider, ownerKey, owner, invocationId, draft } + const options = { location: vscode.ProgressLocation.Notification, title: GENERATING_TITLE, cancellable: true } + await vscode.window.withProgress(options, (progress, token) => runGeneration(run, progress, token)) + } catch (error) { + // The cancel path is handled inside the progress callback, so every error here is a real + // failure, including provider timeouts and errors whose text mentions "aborted". + const errorMessage = error instanceof Error ? error.message : String(error) + outputChannel?.appendLine(`[generateGitCommitMessage] failed: ${errorMessage}`) + vscode.window.showErrorMessage(`Failed to generate commit message: ${errorMessage}`) + } finally { + if (owner) { + owner.holders-- + } else { + resolvingInvocations-- + } + for (const [key, entry] of ownersByRepository) { + if (resolvingInvocations === 0 && entry.holders === 0) { + ownersByRepository.delete(key) + } + } + } +}