From b030257c3b6fe98fc5d8b28daeaf5954e9d1ca69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leynier=20Guti=C3=A9rrez=20Gonz=C3=A1lez?= Date: Fri, 15 May 2026 03:18:46 -0600 Subject: [PATCH] feat(source-control): AI commit message generation (#1487) Co-authored-by: Orca Co-authored-by: brennanb2025 --- src/main/attribution/terminal-attribution.ts | 2 +- src/main/codex-cli/command.ts | 9 +- src/main/git/status.test.ts | 34 ++ src/main/git/status.ts | 37 ++ src/main/index.ts | 14 +- src/main/ipc/filesystem.test.ts | 307 +++++++++++ src/main/ipc/filesystem.ts | 151 +++++- src/main/ipc/register-core-handlers.ts | 14 +- src/main/providers/ssh-git-dispatch.ts | 8 +- src/main/providers/ssh-git-provider.test.ts | 76 +++ src/main/providers/ssh-git-provider.ts | 55 ++ src/main/providers/types.ts | 2 + .../commit-message-text-generation.test.ts | 473 +++++++++++++++++ .../commit-message-text-generation.ts | 450 ++++++++++++++++ src/main/win32-utils.test.ts | 14 +- src/main/win32-utils.ts | 31 +- src/preload/api-types.ts | 11 + src/preload/index.ts | 8 + src/relay/agent-exec-handler.test.ts | 259 ++++++++++ src/relay/agent-exec-handler.ts | 254 +++++++++ src/relay/git-exec-validator.test.ts | 17 + src/relay/git-exec-validator.ts | 22 + src/relay/relay.ts | 8 + .../CommitArea.chevron-spinner.test.tsx | 8 + .../CommitArea.generate.test.tsx | 213 ++++++++ .../CommitArea.primary-icons.test.tsx | 8 + .../right-sidebar/CommitArea.test.tsx | 11 + .../right-sidebar/SourceControl.tsx | 236 ++++++++- .../settings/CommitMessageAiPane.test.tsx | 97 ++++ .../settings/CommitMessageAiPane.tsx | 480 ++++++++++++++++++ .../src/components/settings/Settings.tsx | 17 +- .../settings/commit-message-ai-search.ts | 45 ++ src/shared/commit-message-agent-spec.test.ts | 165 ++++++ src/shared/commit-message-agent-spec.ts | 266 ++++++++++ src/shared/commit-message-generation.test.ts | 50 ++ src/shared/commit-message-generation.ts | 84 +++ src/shared/commit-message-plan.test.ts | 101 ++++ src/shared/commit-message-plan.ts | 127 +++++ src/shared/commit-message-prompt.test.ts | 203 ++++++++ src/shared/commit-message-prompt.ts | 231 +++++++++ src/shared/constants.ts | 12 + src/shared/orca-attribution.ts | 6 + src/shared/types.ts | 20 + .../source-control-commit-message-ai.spec.ts | 132 +++++ 44 files changed, 4731 insertions(+), 37 deletions(-) create mode 100644 src/main/text-generation/commit-message-text-generation.test.ts create mode 100644 src/main/text-generation/commit-message-text-generation.ts create mode 100644 src/relay/agent-exec-handler.test.ts create mode 100644 src/relay/agent-exec-handler.ts create mode 100644 src/renderer/src/components/right-sidebar/CommitArea.generate.test.tsx create mode 100644 src/renderer/src/components/settings/CommitMessageAiPane.test.tsx create mode 100644 src/renderer/src/components/settings/CommitMessageAiPane.tsx create mode 100644 src/renderer/src/components/settings/commit-message-ai-search.ts create mode 100644 src/shared/commit-message-agent-spec.test.ts create mode 100644 src/shared/commit-message-agent-spec.ts create mode 100644 src/shared/commit-message-generation.test.ts create mode 100644 src/shared/commit-message-generation.ts create mode 100644 src/shared/commit-message-plan.test.ts create mode 100644 src/shared/commit-message-plan.ts create mode 100644 src/shared/commit-message-prompt.test.ts create mode 100644 src/shared/commit-message-prompt.ts create mode 100644 src/shared/orca-attribution.ts create mode 100644 tests/e2e/source-control-commit-message-ai.spec.ts diff --git a/src/main/attribution/terminal-attribution.ts b/src/main/attribution/terminal-attribution.ts index 22c7af94b..4162e15e3 100644 --- a/src/main/attribution/terminal-attribution.ts +++ b/src/main/attribution/terminal-attribution.ts @@ -4,11 +4,11 @@ to the env injection code makes the attribution behavior auditable as one unit instead of scattering generated shell fragments across files. */ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs' import { join } from 'path' +import { ORCA_GIT_COMMIT_TRAILER } from '../../shared/orca-attribution' const ATTRIBUTION_ROOT_DIR = 'orca-terminal-attribution' const ATTRIBUTION_SHIM_VERSION = '6' const ORCA_PRODUCT_URL = 'https://github.com/stablyai/orca' -const ORCA_GIT_COMMIT_TRAILER = 'Co-authored-by: Orca ' const ORCA_GH_FOOTER = `Made with [Orca](${ORCA_PRODUCT_URL}) πŸ‹` const SHELL_DOLLAR = '$' const POWERSHELL_TICK = '`' diff --git a/src/main/codex-cli/command.ts b/src/main/codex-cli/command.ts index ccdb7981d..2215583ac 100644 --- a/src/main/codex-cli/command.ts +++ b/src/main/codex-cli/command.ts @@ -121,7 +121,10 @@ function getVersionManagerDirectories( return directories } -function resolveCommand(commandName: string, options: ResolveCommandOptions = {}): string { +export function resolveCliCommand( + commandName: string, + options: ResolveCommandOptions = {} +): string { const platform = options.platform ?? process.platform const executableNames = getExecutableNames(platform, commandName) const pathEnv = options.pathEnv ?? process.env.PATH ?? process.env.Path ?? null @@ -139,11 +142,11 @@ function resolveCommand(commandName: string, options: ResolveCommandOptions = {} } export function resolveCodexCommand(options: ResolveCommandOptions = {}): string { - return resolveCommand('codex', options) + return resolveCliCommand('codex', options) } export function resolveClaudeCommand(options: ResolveCommandOptions = {}): string { - return resolveCommand('claude', options) + return resolveCliCommand('claude', options) } // Why: GUI-launched Electron apps inherit a minimal PATH that excludes Node diff --git a/src/main/git/status.test.ts b/src/main/git/status.test.ts index 3a815558c..24f2648d7 100644 --- a/src/main/git/status.test.ts +++ b/src/main/git/status.test.ts @@ -33,6 +33,7 @@ import { discardChanges, getBranchCompare, getDiff, + getStagedCommitContext, getStatus, isWithinWorktree } from './status' @@ -406,6 +407,39 @@ describe('getStatus', () => { }) }) +describe('getStagedCommitContext', () => { + beforeEach(() => { + gitExecFileAsyncMock.mockReset() + }) + + it('uses explicit large buffers before prompt truncation', async () => { + gitExecFileAsyncMock + .mockResolvedValueOnce({ stdout: 'feature/ai\n' }) + .mockResolvedValueOnce({ stdout: 'M\tREADME.md\n' }) + .mockResolvedValueOnce({ stdout: 'diff --git a/README.md b/README.md\n+hello\n' }) + + const result = await getStagedCommitContext('/repo') + + expect(result).toEqual({ + branch: 'feature/ai', + stagedSummary: 'M\tREADME.md', + stagedPatch: 'diff --git a/README.md b/README.md\n+hello\n' + }) + expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['diff', '--cached', '--name-status'], { + cwd: '/repo', + maxBuffer: 10 * 1024 * 1024 + }) + expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith( + 3, + ['diff', '--cached', '--patch', '--minimal', '--no-color', '--no-ext-diff'], + { + cwd: '/repo', + maxBuffer: 10 * 1024 * 1024 + } + ) + }) +}) + describe('detectConflictOperation', () => { beforeEach(() => { readFileMock.mockReset() diff --git a/src/main/git/status.ts b/src/main/git/status.ts index b24535d44..1b74904fd 100644 --- a/src/main/git/status.ts +++ b/src/main/git/status.ts @@ -14,9 +14,11 @@ import type { GitStatusEntry, GitStatusResult } from '../../shared/types' +import type { CommitMessageDraftContext } from '../../shared/commit-message-generation' import { gitExecFileAsync, gitExecFileAsyncBuffer } from './runner' const MAX_GIT_SHOW_BYTES = 10 * 1024 * 1024 +const MAX_STAGED_COMMIT_CONTEXT_BYTES = MAX_GIT_SHOW_BYTES const BULK_CHUNK_SIZE = 100 /** @@ -728,6 +730,41 @@ export async function unstageFile(worktreePath: string, filePath: string): Promi await gitExecFileAsync(['restore', '--staged', '--', filePath], { cwd: worktreePath }) } +export async function getStagedCommitContext( + worktreePath: string +): Promise { + const branchPromise = gitExecFileAsync(['branch', '--show-current'], { + cwd: worktreePath + }).catch(() => ({ stdout: '' })) + const summaryPromise = gitExecFileAsync(['diff', '--cached', '--name-status'], { + cwd: worktreePath, + maxBuffer: MAX_STAGED_COMMIT_CONTEXT_BYTES + }) + + const [branchResult, summaryResult] = await Promise.all([branchPromise, summaryPromise]) + const stagedSummary = summaryResult.stdout.trim() + if (!stagedSummary) { + return null + } + + const { stdout: stagedPatch } = await gitExecFileAsync( + ['diff', '--cached', '--patch', '--minimal', '--no-color', '--no-ext-diff'], + { + cwd: worktreePath, + // Why: the prompt builder truncates large staged patches later. Give git + // enough buffer room to reach that truncation step instead of failing at + // Node's default execFile limit first. + maxBuffer: MAX_STAGED_COMMIT_CONTEXT_BYTES + } + ) + + return { + branch: branchResult.stdout.trim() || null, + stagedSummary, + stagedPatch + } +} + export async function commitChanges( worktreePath: string, message: string diff --git a/src/main/index.ts b/src/main/index.ts index 19c20b07e..d16fdb2f1 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -269,7 +269,14 @@ function openMainWindow(): BrowserWindow { claudeAccounts, rateLimits, window.webContents.id, - automations + automations, + { + prepareForCodexLaunch: () => + store!.getSettings().activeCodexManagedAccountId + ? codexRuntimeHome!.prepareForCodexLaunch() + : null, + prepareForClaudeLaunch: () => claudeRuntimeAuth!.prepareForClaudeLaunch() + } ) automations.setWebContents(window.webContents) automations.start() @@ -277,7 +284,10 @@ function openMainWindow(): BrowserWindow { window, store, runtime, - () => codexRuntimeHome!.prepareForCodexLaunch(), + () => + store!.getSettings().activeCodexManagedAccountId + ? codexRuntimeHome!.prepareForCodexLaunch() + : null, () => claudeRuntimeAuth!.prepareForClaudeLaunch() ) rateLimits.attach(window) diff --git a/src/main/ipc/filesystem.test.ts b/src/main/ipc/filesystem.test.ts index b0c267f62..5196bdb47 100644 --- a/src/main/ipc/filesystem.test.ts +++ b/src/main/ipc/filesystem.test.ts @@ -18,6 +18,7 @@ const { getDiffMock, getBranchCompareMock, getBranchDiffMock, + getStagedCommitContextMock, stageFileMock, bulkStageFilesMock, unstageFileMock, @@ -25,6 +26,9 @@ const { bulkDiscardChangesMock, discardChangesMock, listWorktreesMock, + resolveCommitMessageSettingsMock, + generateCommitMessageFromContextMock, + cancelGenerateCommitMessageLocalMock, getSshFilesystemProviderMock, getSshGitProviderMock } = vi.hoisted(() => ({ @@ -42,6 +46,7 @@ const { getDiffMock: vi.fn(), getBranchCompareMock: vi.fn(), getBranchDiffMock: vi.fn(), + getStagedCommitContextMock: vi.fn(), stageFileMock: vi.fn(), bulkStageFilesMock: vi.fn(), unstageFileMock: vi.fn(), @@ -49,6 +54,9 @@ const { bulkDiscardChangesMock: vi.fn(), discardChangesMock: vi.fn(), listWorktreesMock: vi.fn(), + resolveCommitMessageSettingsMock: vi.fn(), + generateCommitMessageFromContextMock: vi.fn(), + cancelGenerateCommitMessageLocalMock: vi.fn(), getSshFilesystemProviderMock: vi.fn(), getSshGitProviderMock: vi.fn() })) @@ -78,6 +86,7 @@ vi.mock('../git/status', () => ({ getDiff: getDiffMock, getBranchCompare: getBranchCompareMock, getBranchDiff: getBranchDiffMock, + getStagedCommitContext: getStagedCommitContextMock, stageFile: stageFileMock, bulkStageFiles: bulkStageFilesMock, unstageFile: unstageFileMock, @@ -98,6 +107,12 @@ vi.mock('../providers/ssh-git-dispatch', () => ({ getSshGitProvider: getSshGitProviderMock })) +vi.mock('../text-generation/commit-message-text-generation', () => ({ + resolveCommitMessageSettings: resolveCommitMessageSettingsMock, + generateCommitMessageFromContext: generateCommitMessageFromContextMock, + cancelGenerateCommitMessageLocal: cancelGenerateCommitMessageLocalMock +})) + import { registerFilesystemHandlers } from './filesystem' import { invalidateAuthorizedRootsCache, registerWorktreeRootsForRepo } from './filesystem-auth' @@ -161,6 +176,7 @@ describe('registerFilesystemHandlers', () => { getDiffMock, getBranchCompareMock, getBranchDiffMock, + getStagedCommitContextMock, stageFileMock, bulkStageFilesMock, unstageFileMock, @@ -168,6 +184,9 @@ describe('registerFilesystemHandlers', () => { bulkDiscardChangesMock, discardChangesMock, listWorktreesMock, + resolveCommitMessageSettingsMock, + generateCommitMessageFromContextMock, + cancelGenerateCommitMessageLocalMock, getSshFilesystemProviderMock, getSshGitProviderMock ]) { @@ -720,6 +739,294 @@ describe('registerFilesystemHandlers', () => { ).resolves.toEqual({ success: false, error: 'hook failed' }) }) + it('generates a local commit message from main-process staged context', async () => { + const context = { + branch: 'feature/ai', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + } + const params = { agentId: 'codex', model: 'gpt-5.4-mini', thinkingLevel: 'low' } + resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params }) + getStagedCommitContextMock.mockResolvedValue(context) + generateCommitMessageFromContextMock.mockResolvedValue({ + success: true, + message: 'Update README' + }) + + registerFilesystemHandlers(store as never) + + await expect( + handlers.get('git:generateCommitMessage')!(null, { + worktreePath: WORKTREE_FEATURE_PATH + }) + ).resolves.toEqual({ success: true, message: 'Update README' }) + + expect(getStagedCommitContextMock).toHaveBeenCalledWith(WORKTREE_FEATURE_PATH) + expect(generateCommitMessageFromContextMock).toHaveBeenCalledWith(context, params, { + kind: 'local', + cwd: WORKTREE_FEATURE_PATH + }) + }) + + it('prepares the selected Codex account home before local generation', async () => { + const context = { + branch: 'feature/ai', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + } + const params = { agentId: 'codex', model: 'gpt-5.4-mini', thinkingLevel: 'low' } + resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params }) + getStagedCommitContextMock.mockResolvedValue(context) + generateCommitMessageFromContextMock.mockResolvedValue({ + success: true, + message: 'Update README' + }) + + registerFilesystemHandlers(store as never, { + prepareForCodexLaunch: () => '/managed/codex-home' + }) + + await handlers.get('git:generateCommitMessage')!(null, { + worktreePath: WORKTREE_FEATURE_PATH + }) + + expect(generateCommitMessageFromContextMock).toHaveBeenCalledWith( + context, + params, + expect.objectContaining({ + kind: 'local', + cwd: WORKTREE_FEATURE_PATH, + env: expect.objectContaining({ CODEX_HOME: '/managed/codex-home' }) + }) + ) + }) + + it('preserves the inherited Codex environment when no managed account is selected', async () => { + const previousCodexHome = process.env.CODEX_HOME + process.env.CODEX_HOME = '/system/codex-home' + const context = { + branch: 'feature/ai', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + } + const params = { agentId: 'codex', model: 'gpt-5.4-mini', thinkingLevel: 'low' } + resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params }) + getStagedCommitContextMock.mockResolvedValue(context) + generateCommitMessageFromContextMock.mockResolvedValue({ + success: true, + message: 'Update README' + }) + + try { + registerFilesystemHandlers(store as never, { + prepareForCodexLaunch: () => null + }) + + await handlers.get('git:generateCommitMessage')!(null, { + worktreePath: WORKTREE_FEATURE_PATH + }) + + expect(generateCommitMessageFromContextMock).toHaveBeenCalledWith(context, params, { + kind: 'local', + cwd: WORKTREE_FEATURE_PATH + }) + } finally { + if (previousCodexHome === undefined) { + delete process.env.CODEX_HOME + } else { + process.env.CODEX_HOME = previousCodexHome + } + } + }) + + it('returns a sanitized error when local agent account preparation fails', async () => { + const context = { + branch: 'feature/ai', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + } + const params = { agentId: 'codex', model: 'gpt-5.4-mini', thinkingLevel: 'low' } + resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params }) + getStagedCommitContextMock.mockResolvedValue(context) + + registerFilesystemHandlers(store as never, { + prepareForCodexLaunch: () => { + throw new Error('failed to read /Users/alice/.codex/auth.json') + } + }) + + await expect( + handlers.get('git:generateCommitMessage')!(null, { + worktreePath: WORKTREE_FEATURE_PATH + }) + ).resolves.toEqual({ + success: false, + error: 'Failed to prepare the selected agent account for commit message generation.' + }) + expect(generateCommitMessageFromContextMock).not.toHaveBeenCalled() + }) + + it('prepares the selected Claude auth environment before local generation', async () => { + const previousAnthropicApiKey = process.env.ANTHROPIC_API_KEY + process.env.ANTHROPIC_API_KEY = 'do-not-leak-managed-auth-conflict' + const context = { + branch: 'feature/ai', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + } + const params = { agentId: 'claude', model: 'claude-haiku-4-5' } + resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params }) + getStagedCommitContextMock.mockResolvedValue(context) + generateCommitMessageFromContextMock.mockResolvedValue({ + success: true, + message: 'Update README' + }) + + try { + registerFilesystemHandlers(store as never, { + prepareForClaudeLaunch: async () => ({ + configDir: '/managed/claude', + envPatch: { CLAUDE_CONFIG_DIR: '/managed/claude' }, + stripAuthEnv: true, + provenance: 'managed:account-1' + }) + }) + + await handlers.get('git:generateCommitMessage')!(null, { + worktreePath: WORKTREE_FEATURE_PATH + }) + + const target = generateCommitMessageFromContextMock.mock.calls[0]?.[2] as + | { env?: NodeJS.ProcessEnv } + | undefined + expect(target?.env).toEqual( + expect.objectContaining({ + CLAUDE_CONFIG_DIR: '/managed/claude' + }) + ) + expect(target?.env?.ANTHROPIC_API_KEY).toBeUndefined() + } finally { + if (previousAnthropicApiKey === undefined) { + delete process.env.ANTHROPIC_API_KEY + } else { + process.env.ANTHROPIC_API_KEY = previousAnthropicApiKey + } + } + }) + + it('generates an SSH commit message using remote staged context and relay execution', async () => { + const context = { + branch: 'main', + stagedSummary: 'A\tremote.txt', + stagedPatch: '+remote' + } + const params = { agentId: 'custom', model: '', customAgentCommand: 'agent' } + const executeCommitMessagePlan = vi.fn() + const prepareForCodexLaunch = vi.fn(() => '/managed/codex-home') + const prepareForClaudeLaunch = vi.fn() + resolveCommitMessageSettingsMock.mockReturnValue({ ok: true, params }) + getSshGitProviderMock.mockReturnValue({ + getStagedCommitContext: vi.fn().mockResolvedValue(context), + executeCommitMessagePlan + }) + generateCommitMessageFromContextMock.mockResolvedValue({ + success: true, + message: 'Add remote file' + }) + + registerFilesystemHandlers(store as never, { + prepareForCodexLaunch, + prepareForClaudeLaunch + }) + + await expect( + handlers.get('git:generateCommitMessage')!(null, { + worktreePath: '/remote/repo', + connectionId: 'conn-1' + }) + ).resolves.toEqual({ success: true, message: 'Add remote file' }) + + expect(generateCommitMessageFromContextMock).toHaveBeenCalledWith( + context, + params, + expect.objectContaining({ + kind: 'remote', + cwd: '/remote/repo', + missingBinaryLocation: 'remote PATH' + }) + ) + const target = generateCommitMessageFromContextMock.mock.calls[0]?.[2] + await target.execute( + { binary: 'agent', args: [], stdinPayload: null, label: 'agent' }, + '/cwd', + 1 + ) + expect(executeCommitMessagePlan).toHaveBeenCalledWith( + { binary: 'agent', args: [], stdinPayload: null, label: 'agent' }, + '/cwd', + 1 + ) + expect(prepareForCodexLaunch).not.toHaveBeenCalled() + expect(prepareForClaudeLaunch).not.toHaveBeenCalled() + }) + + it('does not call the generator when no staged changes exist', async () => { + resolveCommitMessageSettingsMock.mockReturnValue({ + ok: true, + params: { agentId: 'codex', model: 'gpt-5.4-mini' } + }) + getStagedCommitContextMock.mockResolvedValue(null) + + registerFilesystemHandlers(store as never) + + await expect( + handlers.get('git:generateCommitMessage')!(null, { + worktreePath: WORKTREE_FEATURE_PATH + }) + ).resolves.toEqual({ success: false, error: 'No staged changes to summarize.' }) + + expect(generateCommitMessageFromContextMock).not.toHaveBeenCalled() + }) + + it('sanitizes local staged-context read failures before returning to the renderer', async () => { + resolveCommitMessageSettingsMock.mockReturnValue({ + ok: true, + params: { agentId: 'codex', model: 'gpt-5.4-mini' } + }) + getStagedCommitContextMock.mockRejectedValue(new Error('fatal: /secret/repo failed')) + + registerFilesystemHandlers(store as never) + + await expect( + handlers.get('git:generateCommitMessage')!(null, { + worktreePath: WORKTREE_FEATURE_PATH + }) + ).resolves.toEqual({ success: false, error: 'Failed to read staged changes.' }) + + expect(generateCommitMessageFromContextMock).not.toHaveBeenCalled() + }) + + it('sanitizes SSH staged-context read failures before returning to the renderer', async () => { + resolveCommitMessageSettingsMock.mockReturnValue({ + ok: true, + params: { agentId: 'codex', model: 'gpt-5.4-mini' } + }) + getSshGitProviderMock.mockReturnValue({ + getStagedCommitContext: vi.fn().mockRejectedValue(new Error('fatal: /remote/secret failed')) + }) + + registerFilesystemHandlers(store as never) + + await expect( + handlers.get('git:generateCommitMessage')!(null, { + worktreePath: '/remote/repo', + connectionId: 'conn-1' + }) + ).resolves.toEqual({ success: false, error: 'Failed to read staged changes.' }) + + expect(generateCommitMessageFromContextMock).not.toHaveBeenCalled() + }) + it('routes ssh git:commit through the SSH provider instead of local commitChanges', async () => { const sshCommitMock = vi.fn().mockResolvedValue({ success: true }) getSshGitProviderMock.mockReturnValue({ commit: sshCommitMock }) diff --git a/src/main/ipc/filesystem.ts b/src/main/ipc/filesystem.ts index 817668dec..f35adbca5 100644 --- a/src/main/ipc/filesystem.ts +++ b/src/main/ipc/filesystem.ts @@ -37,9 +37,16 @@ import { bulkUnstageFiles, bulkDiscardChanges, discardChanges, + getStagedCommitContext, getBranchCompare, getBranchDiff } from '../git/status' +import { + cancelGenerateCommitMessageLocal, + generateCommitMessageFromContext, + resolveCommitMessageSettings, + type GenerateCommitMessageResult +} from '../text-generation/commit-message-text-generation' import { getUpstreamStatus } from '../git/upstream' import { gitFetch, gitPull, gitPush } from '../git/remote' import { assertGitPushTargetShape } from '../../shared/git-push-target-validation' @@ -59,6 +66,8 @@ import { listMarkdownDocuments, markdownDocumentsFromRelativePaths } from './mar import { checkRgAvailable } from './rg-availability' import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' import { getSshGitProvider } from '../providers/ssh-git-dispatch' +import type { ClaudeRuntimeAuthPreparation } from '../claude-accounts/runtime-auth-service' +import { applyClaudeEnvPatch } from '../claude-accounts/environment' // Why: Monaco has large-file optimizations like VS Code; blocking at 5MB makes // ordinary JSON/log files inaccessible before the editor can degrade features. @@ -84,6 +93,56 @@ const PREVIEWABLE_BINARY_MIME_TYPES: Record = { '.pdf': 'application/pdf' } +export type CommitMessageAgentEnvironmentResolvers = { + prepareForCodexLaunch?: () => string | null + prepareForClaudeLaunch?: () => Promise +} + +function cloneProcessEnv(): Record { + const env: Record = {} + for (const [key, value] of Object.entries(process.env)) { + if (value !== undefined) { + env[key] = value + } + } + return env +} + +async function prepareLocalCommitMessageAgentEnv( + agentId: string, + resolvers: CommitMessageAgentEnvironmentResolvers | undefined +): Promise<{ ok: true; env?: NodeJS.ProcessEnv } | { ok: false; error: string }> { + if (!resolvers) { + return { ok: true } + } + + try { + if (agentId === 'codex' && resolvers.prepareForCodexLaunch) { + const codexHomePath = resolvers.prepareForCodexLaunch() + return { + ok: true, + env: codexHomePath ? { ...cloneProcessEnv(), CODEX_HOME: codexHomePath } : undefined + } + } + + if (agentId === 'claude' && resolvers.prepareForClaudeLaunch) { + const preparation = await resolvers.prepareForClaudeLaunch() + const env = applyClaudeEnvPatch(cloneProcessEnv(), preparation.envPatch, { + stripAuthEnv: preparation.stripAuthEnv + }) + return { ok: true, env } + } + } catch (error) { + console.error('[filesystem] Failed to prepare commit message agent environment:', error) + return { + ok: false, + error: 'Failed to prepare the selected agent account for commit message generation.' + } + } + + return { ok: true } +} + /** * Check if a buffer appears to be binary (contains null bytes in first 8KB). */ @@ -129,7 +188,10 @@ async function isDirectoryEntry( } } -export function registerFilesystemHandlers(store: Store): void { +export function registerFilesystemHandlers( + store: Store, + commitMessageAgentEnv?: CommitMessageAgentEnvironmentResolvers +): void { const activeTextSearches = new Map() // ─── Filesystem ───────────────────────────────────────── @@ -557,6 +619,93 @@ export function registerFilesystemHandlers(store: Store): void { } ) + ipcMain.handle( + 'git:generateCommitMessage', + async ( + _event, + args: { + worktreePath: string + connectionId?: string + } + ): Promise => { + const resolvedSettings = resolveCommitMessageSettings(store.getSettings()) + if (!resolvedSettings.ok) { + return { success: false, error: resolvedSettings.error } + } + if (args.connectionId) { + const provider = getSshGitProvider(args.connectionId) + if (!provider) { + return { + success: false, + error: `No git provider for connection "${args.connectionId}"` + } + } + let context + try { + context = await provider.getStagedCommitContext(args.worktreePath) + } catch (error) { + console.error('[filesystem] Failed to read remote staged commit context:', error) + return { + success: false, + error: 'Failed to read staged changes.' + } + } + if (!context) { + return { success: false, error: 'No staged changes to summarize.' } + } + return generateCommitMessageFromContext(context, resolvedSettings.params, { + kind: 'remote', + cwd: args.worktreePath, + execute: (plan, cwd, timeoutMs) => + provider.executeCommitMessagePlan(plan, cwd, timeoutMs), + missingBinaryLocation: 'remote PATH' + }) + } + const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store) + let context + try { + context = await getStagedCommitContext(worktreePath) + } catch (error) { + console.error('[filesystem] Failed to read staged commit context:', error) + return { + success: false, + error: 'Failed to read staged changes.' + } + } + if (!context) { + return { success: false, error: 'No staged changes to summarize.' } + } + const localEnv = await prepareLocalCommitMessageAgentEnv( + resolvedSettings.params.agentId, + commitMessageAgentEnv + ) + if (!localEnv.ok) { + return { success: false, error: localEnv.error } + } + return generateCommitMessageFromContext(context, resolvedSettings.params, { + kind: 'local', + cwd: worktreePath, + ...(localEnv.env ? { env: localEnv.env } : {}) + }) + } + ) + + ipcMain.handle( + 'git:cancelGenerateCommitMessage', + async (_event, args: { worktreePath: string; connectionId?: string }): Promise => { + if (args.connectionId) { + const provider = getSshGitProvider(args.connectionId) + if (!provider) { + return + } + await provider.cancelGenerateCommitMessage(args.worktreePath) + return + } + const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store) + cancelGenerateCommitMessageLocal(worktreePath) + } + ) + ipcMain.handle( 'git:branchCompare', async ( diff --git a/src/main/ipc/register-core-handlers.ts b/src/main/ipc/register-core-handlers.ts index 74c08a40f..2bfb4c71d 100644 --- a/src/main/ipc/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers.ts @@ -4,7 +4,10 @@ import { registerPreflightHandlers } from './preflight' import type { Store } from '../persistence' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import type { StatsCollector } from '../stats/collector' -import { registerFilesystemHandlers } from './filesystem' +import { + registerFilesystemHandlers, + type CommitMessageAgentEnvironmentResolvers +} from './filesystem' import { registerFilesystemWatcherHandlers } from './filesystem-watcher' import { registerClaudeUsageHandlers } from './claude-usage' import { registerCodexUsageHandlers } from './codex-usage' @@ -65,7 +68,8 @@ export function registerCoreHandlers( claudeAccounts: ClaudeAccountService, rateLimits: RateLimitService, mainWindowWebContentsId: number | null = null, - automations?: AutomationService + automations?: AutomationService, + commitMessageAgentEnv?: CommitMessageAgentEnvironmentResolvers ): void { // Why: on macOS the app can stay alive after all windows close, then // openMainWindow() is called again on 'activate'. ipcMain.handle() throws @@ -118,7 +122,11 @@ export function registerCoreHandlers( registerSessionHandlers(store) registerUIHandlers(store) registerWorkspaceSpaceHandlers(store) - registerFilesystemHandlers(store) + if (commitMessageAgentEnv) { + registerFilesystemHandlers(store, commitMessageAgentEnv) + } else { + registerFilesystemHandlers(store) + } registerFilesystemWatcherHandlers() registerRuntimeHandlers(runtime) registerRuntimeEnvironmentHandlers() diff --git a/src/main/providers/ssh-git-dispatch.ts b/src/main/providers/ssh-git-dispatch.ts index b4e462a3a..74afe7700 100644 --- a/src/main/providers/ssh-git-dispatch.ts +++ b/src/main/providers/ssh-git-dispatch.ts @@ -1,8 +1,8 @@ -import type { IGitProvider } from './types' +import type { SshGitProvider } from './ssh-git-provider' -const sshProviders = new Map() +const sshProviders = new Map() -export function registerSshGitProvider(connectionId: string, provider: IGitProvider): void { +export function registerSshGitProvider(connectionId: string, provider: SshGitProvider): void { sshProviders.set(connectionId, provider) } @@ -10,6 +10,6 @@ export function unregisterSshGitProvider(connectionId: string): void { sshProviders.delete(connectionId) } -export function getSshGitProvider(connectionId: string): IGitProvider | undefined { +export function getSshGitProvider(connectionId: string): SshGitProvider | undefined { return sshProviders.get(connectionId) } diff --git a/src/main/providers/ssh-git-provider.test.ts b/src/main/providers/ssh-git-provider.test.ts index 5643c3c2d..636fa229d 100644 --- a/src/main/providers/ssh-git-provider.test.ts +++ b/src/main/providers/ssh-git-provider.test.ts @@ -54,6 +54,82 @@ describe('SshGitProvider', () => { expect(result).toEqual(commitResult) }) + it('getStagedCommitContext reads branch, staged summary, and staged patch remotely', async () => { + mux.request.mockImplementation(async (method, payload) => { + expect(method).toBe('git.exec') + if (payload.args[1] === '--show-current') { + return { stdout: 'feature/ai-commit\n' } + } + if (payload.args[2] === '--name-status') { + return { stdout: 'M\tREADME.md\n' } + } + if (payload.args[2] === '--patch') { + return { stdout: 'diff --git a/README.md b/README.md\n+hello' } + } + throw new Error(`unexpected args: ${payload.args.join(' ')}`) + }) + + const result = await provider.getStagedCommitContext('/home/user/repo') + + expect(result).toEqual({ + branch: 'feature/ai-commit', + stagedSummary: 'M\tREADME.md', + stagedPatch: 'diff --git a/README.md b/README.md\n+hello' + }) + expect(mux.request).toHaveBeenCalledWith('git.exec', { + args: ['diff', '--cached', '--patch', '--minimal', '--no-color', '--no-ext-diff'], + cwd: '/home/user/repo' + }) + }) + + it('getStagedCommitContext returns null when nothing is staged', async () => { + mux.request.mockImplementation(async (_method, payload) => { + if (payload.args[1] === '--show-current') { + return { stdout: 'main\n' } + } + return { stdout: '' } + }) + + await expect(provider.getStagedCommitContext('/home/user/repo')).resolves.toBeNull() + expect(mux.request).toHaveBeenCalledTimes(2) + }) + + it('executeCommitMessagePlan delegates the prepared plan to the relay', async () => { + const execResult = { + stdout: 'Update docs', + stderr: '', + exitCode: 0, + timedOut: false + } + mux.request.mockResolvedValue(execResult) + + const result = await provider.executeCommitMessagePlan( + { + binary: 'codex', + args: ['exec', 'PROMPT'], + stdinPayload: null, + label: 'Codex' + }, + '/home/user/repo', + 60_000 + ) + + expect(mux.request).toHaveBeenCalledWith('agent.execNonInteractive', { + binary: 'codex', + args: ['exec', 'PROMPT'], + cwd: '/home/user/repo', + stdin: null, + timeoutMs: 60_000 + }) + expect(result).toEqual(execResult) + }) + + it('cancelGenerateCommitMessage sends best-effort relay cancellation', async () => { + await provider.cancelGenerateCommitMessage('/home/user/repo') + + expect(mux.request).toHaveBeenCalledWith('agent.cancelExec', { cwd: '/home/user/repo' }) + }) + it('getDiff sends git.diff request', async () => { const diffResult = { kind: 'text', originalContent: '', modifiedContent: 'hello' } mux.request.mockResolvedValue(diffResult) diff --git a/src/main/providers/ssh-git-provider.ts b/src/main/providers/ssh-git-provider.ts index 45dec93c7..e73e92f76 100644 --- a/src/main/providers/ssh-git-provider.ts +++ b/src/main/providers/ssh-git-provider.ts @@ -1,3 +1,7 @@ +/* eslint-disable max-lines -- Why: this provider mirrors IGitProvider one + method per RPC call (~16 methods). Splitting it would only add + indirection β€” every method is a 1:1 forwarder to a relay RPC plus a + small amount of param plumbing. */ import type { SshChannelMultiplexer } from '../ssh/ssh-channel-multiplexer' import type { IGitProvider } from './types' import hostedGitInfo from 'hosted-git-info' @@ -10,6 +14,9 @@ import type { GitUpstreamStatus, GitWorktreeInfo } from '../../shared/types' +import type { CommitMessageDraftContext } from '../../shared/commit-message-generation' +import type { CommitMessagePlan } from '../../shared/commit-message-plan' +import type { RemoteCommitMessageExecResult } from '../text-generation/commit-message-text-generation' export class SshGitProvider implements IGitProvider { private connectionId: string @@ -38,6 +45,54 @@ export class SshGitProvider implements IGitProvider { })) as { success: boolean; error?: string } } + async getStagedCommitContext(worktreePath: string): Promise { + const branchPromise = this.exec(['branch', '--show-current'], worktreePath).catch(() => ({ + stdout: '' + })) + const [branchResult, summaryResult] = await Promise.all([ + branchPromise, + this.exec(['diff', '--cached', '--name-status'], worktreePath) + ]) + const stagedSummary = summaryResult.stdout.trim() + if (!stagedSummary) { + return null + } + const { stdout: stagedPatch } = await this.exec( + ['diff', '--cached', '--patch', '--minimal', '--no-color', '--no-ext-diff'], + worktreePath + ) + return { + branch: branchResult.stdout.trim() || null, + stagedSummary, + stagedPatch + } + } + + async executeCommitMessagePlan( + plan: CommitMessagePlan, + cwd: string, + timeoutMs: number + ): Promise { + return (await this.mux.request('agent.execNonInteractive', { + binary: plan.binary, + args: plan.args, + cwd, + stdin: plan.stdinPayload, + timeoutMs + })) as RemoteCommitMessageExecResult + } + + async cancelGenerateCommitMessage(worktreePath: string): Promise { + // Why: best-effort β€” the relay returns `{canceled: false}` when there is + // nothing in flight. Callers should not block UI updates on this. + try { + await this.mux.request('agent.cancelExec', { cwd: worktreePath }) + } catch { + // Swallow: cancellation is a fire-and-forget user intent. The pending + // generateCommitMessage promise will still resolve with the kill result. + } + } + async getDiff( worktreePath: string, filePath: string, diff --git a/src/main/providers/types.ts b/src/main/providers/types.ts index 3e091ea1f..da8e8758a 100644 --- a/src/main/providers/types.ts +++ b/src/main/providers/types.ts @@ -11,6 +11,7 @@ import type { SearchOptions, SearchResult } from '../../shared/types' +import type { CommitMessageDraftContext } from '../../shared/commit-message-generation' import type { WorkspaceSpaceDirectoryScanResult } from '../../shared/workspace-space-types' // ─── PTY Provider ─────────────────────────────────────────────────── @@ -143,6 +144,7 @@ export type IFilesystemProvider = { export type IGitProvider = { getStatus(worktreePath: string): Promise commit(worktreePath: string, message: string): Promise<{ success: boolean; error?: string }> + getStagedCommitContext(worktreePath: string): Promise getDiff( worktreePath: string, filePath: string, diff --git a/src/main/text-generation/commit-message-text-generation.test.ts b/src/main/text-generation/commit-message-text-generation.test.ts new file mode 100644 index 000000000..77665b899 --- /dev/null +++ b/src/main/text-generation/commit-message-text-generation.test.ts @@ -0,0 +1,473 @@ +/* eslint-disable max-lines -- Why: local/remote generation, cancellation, and + env propagation share subprocess mocks; splitting would obscure the + cross-path invariants these tests protect. */ +import { spawn } from 'child_process' +import type * as ChildProcess from 'child_process' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { getDefaultSettings } from '../../shared/constants' +import { + applyOrcaAttribution, + generateCommitMessageFromContext, + resolveCommitMessageSettings +} from './commit-message-text-generation' + +vi.mock('child_process', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + spawn: vi.fn(actual.spawn) + } +}) + +const spawnMock = vi.mocked(spawn) + +function withPlatform(platform: NodeJS.Platform, fn: () => T): T { + const original = process.platform + Object.defineProperty(process, 'platform', { configurable: true, value: platform }) + try { + return fn() + } finally { + Object.defineProperty(process, 'platform', { configurable: true, value: original }) + } +} + +beforeEach(() => { + spawnMock.mockClear() +}) + +describe('resolveCommitMessageSettings', () => { + it('falls back to the agent default model when a persisted model is stale', () => { + const settings = getDefaultSettings('/tmp') + settings.enableGitHubAttribution = true + settings.commitMessageAi = { + enabled: true, + agentId: 'codex', + selectedModelByAgent: { codex: 'retired-model' }, + selectedThinkingByModel: {}, + customPrompt: 'Use Conventional Commits.', + customAgentCommand: '' + } + + const result = resolveCommitMessageSettings(settings) + + expect(result).toEqual({ + ok: true, + params: { + agentId: 'codex', + model: 'gpt-5.4-mini', + thinkingLevel: 'low', + customPrompt: 'Use Conventional Commits.', + attributionEnabled: true + } + }) + }) + + it('falls back to the model default thinking level when a persisted level is stale', () => { + const settings = getDefaultSettings('/tmp') + settings.commitMessageAi = { + enabled: true, + agentId: 'codex', + selectedModelByAgent: { codex: 'gpt-5.5' }, + selectedThinkingByModel: { 'gpt-5.5': 'turbo' }, + customPrompt: '', + customAgentCommand: '' + } + + const result = resolveCommitMessageSettings(settings) + + expect(result).toMatchObject({ + ok: true, + params: { + agentId: 'codex', + model: 'gpt-5.5', + thinkingLevel: 'low' + } + }) + }) + + it('passes the per-agent command override into non-interactive planning', () => { + const settings = getDefaultSettings('/tmp') + settings.agentCmdOverrides.codex = 'npx codex' + settings.commitMessageAi = { + enabled: true, + agentId: 'codex', + selectedModelByAgent: { codex: 'gpt-5.4-mini' }, + selectedThinkingByModel: {}, + customPrompt: '', + customAgentCommand: '' + } + + const result = resolveCommitMessageSettings(settings) + + expect(result).toMatchObject({ + ok: true, + params: { + agentId: 'codex', + agentCommandOverride: 'npx codex' + } + }) + }) + + it('requires a non-empty custom command for custom agents', () => { + const settings = getDefaultSettings('/tmp') + settings.commitMessageAi = { + enabled: true, + agentId: 'custom', + selectedModelByAgent: {}, + selectedThinkingByModel: {}, + customPrompt: '', + customAgentCommand: ' ' + } + + expect(resolveCommitMessageSettings(settings)).toEqual({ + ok: false, + error: 'Custom command is empty. Add one in Settings -> Git -> AI Commit Messages.' + }) + }) +}) + +describe('generateCommitMessageFromContext', () => { + it('uses a prepared remote execution plan instead of running git on the remote side', async () => { + const result = await generateCommitMessageFromContext( + { + branch: 'main', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'agent --message {prompt}' + }, + { + kind: 'remote', + cwd: '/repo', + missingBinaryLocation: 'remote PATH', + execute: async (plan, cwd, timeoutMs) => { + expect(cwd).toBe('/repo') + expect(timeoutMs).toBe(60_000) + expect(plan.binary).toBe('agent') + expect(plan.args).toHaveLength(2) + expect(plan.args[0]).toBe('--message') + expect(plan.args[1]).toContain('Staged files:\nM\tREADME.md') + return { + stdout: 'Add README note.\n', + stderr: '', + exitCode: 0, + timedOut: false + } + } + } + ) + + expect(result).toEqual({ + success: true, + message: 'Add README note', + agentLabel: 'agent' + }) + }) + + it('does not fall back to raw agent stdout or stderr on failures', async () => { + const result = await generateCommitMessageFromContext( + { + branch: 'main', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'agent' + }, + { + kind: 'remote', + cwd: '/repo', + missingBinaryLocation: 'remote PATH', + execute: async () => ({ + stdout: 'You are generating a single git commit message for /secret/repo', + stderr: 'raw failure output with /secret/repo', + exitCode: 1, + timedOut: false + }) + } + ) + + expect(result).toEqual({ + success: false, + error: 'agent failed. Check the agent CLI configuration and try again.' + }) + }) + + it('does not expose extracted agent error details to the renderer', async () => { + const result = await generateCommitMessageFromContext( + { + branch: 'main', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'agent' + }, + { + kind: 'remote', + cwd: '/repo', + missingBinaryLocation: 'remote PATH', + execute: async () => ({ + stdout: 'ERROR: fatal: /secret/repo/config failed', + stderr: '', + exitCode: 1, + timedOut: false + }) + } + ) + + expect(result).toEqual({ + success: false, + error: 'agent failed. Check the agent CLI configuration and try again.' + }) + }) + + it('preserves the structured subject and body when formatting the final response', async () => { + const result = await generateCommitMessageFromContext( + { + branch: 'main', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'agent', + attributionEnabled: true + }, + { + kind: 'remote', + cwd: '/repo', + missingBinaryLocation: 'remote PATH', + execute: async () => ({ + stdout: 'Update README.\n\n- Explain the generated commit-message flow\n', + stderr: '', + exitCode: 0, + timedOut: false + }) + } + ) + + expect(result).toEqual({ + success: true, + message: + 'Update README\n\n- Explain the generated commit-message flow\n\nCo-authored-by: Orca ', + agentLabel: 'agent' + }) + }) + + it('sanitizes remote execution transport failures', async () => { + const result = await generateCommitMessageFromContext( + { + branch: 'main', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'agent' + }, + { + kind: 'remote', + cwd: '/repo', + missingBinaryLocation: 'remote PATH', + execute: async () => { + throw new Error('relay disconnected while reading /secret/repo') + } + } + ) + + expect(result).toEqual({ + success: false, + error: + 'agent could not be reached on the remote PATH. Try again after the SSH connection recovers.' + }) + }) + + it('caps local agent output before buffering unbounded data', async () => { + const listeners = new Map void>() + const child = { + pid: 123, + kill: vi.fn(), + stdout: { on: vi.fn((event, callback) => listeners.set(`stdout:${event}`, callback)) }, + stderr: { on: vi.fn((event, callback) => listeners.set(`stderr:${event}`, callback)) }, + stdin: { end: vi.fn() }, + on: vi.fn((event, callback) => listeners.set(event, callback)) + } + spawnMock.mockReturnValue(child as never) + + const pending = generateCommitMessageFromContext( + { + branch: 'main', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'agent' + }, + { + kind: 'local', + cwd: '/repo' + } + ) + + listeners.get('stdout:data')?.(Buffer.alloc(4 * 1024 * 1024 + 1)) + listeners.get('close')?.(null) + + await expect(pending).resolves.toEqual({ + success: false, + error: 'agent failed. Check the agent CLI configuration and try again.' + }) + expect(child.kill).toHaveBeenCalledWith('SIGKILL') + }) + + it('passes prepared provider environment to local agent subprocesses', async () => { + const listeners = new Map void>() + const child = { + pid: 123, + kill: vi.fn(), + stdout: { on: vi.fn((event, callback) => listeners.set(`stdout:${event}`, callback)) }, + stderr: { on: vi.fn((event, callback) => listeners.set(`stderr:${event}`, callback)) }, + stdin: { end: vi.fn() }, + on: vi.fn((event, callback) => listeners.set(event, callback)) + } + spawnMock.mockReturnValue(child as never) + + const pending = generateCommitMessageFromContext( + { + branch: 'main', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'orca-test-agent-nope' + }, + { + kind: 'local', + cwd: '/repo', + env: { ...process.env, CODEX_HOME: '/managed/codex-home' } + } + ) + + listeners.get('stdout:data')?.(Buffer.from('Add README note\n')) + listeners.get('close')?.(0) + + await expect(pending).resolves.toMatchObject({ + success: true, + message: 'Add README note' + }) + expect(spawnMock).toHaveBeenCalledWith( + 'orca-test-agent-nope', + [], + expect.objectContaining({ + env: expect.objectContaining({ CODEX_HOME: '/managed/codex-home' }) + }) + ) + }) + + it('routes Windows batch-script agent commands through cmd.exe', async () => { + const originalComSpec = process.env.ComSpec + process.env.ComSpec = 'C:\\Windows\\System32\\cmd.exe' + try { + await withPlatform('win32', async () => { + const listeners = new Map void>() + const child = { + pid: 123, + kill: vi.fn(), + stdout: { on: vi.fn((event, callback) => listeners.set(`stdout:${event}`, callback)) }, + stderr: { on: vi.fn((event, callback) => listeners.set(`stderr:${event}`, callback)) }, + stdin: { end: vi.fn() }, + on: vi.fn((event, callback) => listeners.set(event, callback)) + } + spawnMock.mockReturnValue(child as never) + + const pending = generateCommitMessageFromContext( + { + branch: 'main', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello' + }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'C:/tools/agent.cmd' + }, + { + kind: 'local', + cwd: 'C:\\repo' + } + ) + + listeners.get('stdout:data')?.(Buffer.from('Update README\n')) + listeners.get('close')?.(0) + + await expect(pending).resolves.toMatchObject({ + success: true, + message: 'Update README' + }) + expect(spawnMock).toHaveBeenCalledWith( + 'C:\\Windows\\System32\\cmd.exe', + ['/d', '/s', '/c', '"C:/tools/agent.cmd"'], + expect.objectContaining({ + cwd: 'C:\\repo', + windowsHide: true + }) + ) + }) + } finally { + if (originalComSpec === undefined) { + delete process.env.ComSpec + } else { + process.env.ComSpec = originalComSpec + } + } + }) + + it('rejects unsafe argv prompts for Windows batch-script agent commands', async () => { + await withPlatform('win32', async () => { + const result = await generateCommitMessageFromContext( + { + branch: 'main', + stagedSummary: 'M\tREADME.md', + stagedPatch: '+hello & goodbye' + }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'C:/tools/agent.cmd {prompt}' + }, + { + kind: 'local', + cwd: 'C:\\repo' + } + ) + + expect(result).toEqual({ + success: false, + error: + 'C:/tools/agent.cmd cannot be run as a Windows batch command with the prompt in argv. Remove {prompt} so Orca sends the prompt on stdin.' + }) + expect(spawnMock).not.toHaveBeenCalled() + }) + }) +}) + +describe('applyOrcaAttribution', () => { + it('does not duplicate the Orca trailer', () => { + const message = applyOrcaAttribution('Update docs', true) + + expect(applyOrcaAttribution(message, true)).toBe(message) + }) +}) diff --git a/src/main/text-generation/commit-message-text-generation.ts b/src/main/text-generation/commit-message-text-generation.ts new file mode 100644 index 000000000..e056270f8 --- /dev/null +++ b/src/main/text-generation/commit-message-text-generation.ts @@ -0,0 +1,450 @@ +/* eslint-disable max-lines -- Why: local and SSH generation share cancellation, + spawn failure handling, and output normalization; keeping them together + prevents those paths from drifting. */ +import { exec, spawn, type ChildProcess } from 'child_process' +import type { GlobalSettings, TuiAgent } from '../../shared/types' +import { + buildCommitMessagePrompt, + splitGeneratedCommitMessage, + type CommitMessageDraftContext, + type GeneratedCommitMessage +} from '../../shared/commit-message-generation' +import { + cleanGeneratedCommitMessage, + extractAgentErrorMessage +} from '../../shared/commit-message-prompt' +import { + CUSTOM_AGENT_ID, + DEFAULT_COMMIT_MESSAGE_AGENT_ID, + getCommitMessageAgentSpec, + getCommitMessageModel, + isCustomAgentId +} from '../../shared/commit-message-agent-spec' +import { + planCommitMessageGeneration, + type CommitMessagePlan +} from '../../shared/commit-message-plan' +import { ORCA_GIT_COMMIT_TRAILER } from '../../shared/orca-attribution' +import { resolveCliCommand } from '../codex-cli/command' +import { + getSpawnArgsForWindows, + UnsafeWindowsBatchArgumentsError, + WINDOWS_BATCH_UNSAFE_ARGUMENTS_ERROR +} from '../win32-utils' + +const GENERATION_TIMEOUT_MS = 60_000 +const MAX_AGENT_OUTPUT_BYTES = 4 * 1024 * 1024 + +export type GenerateCommitMessageParams = { + agentId: TuiAgent | 'custom' + model: string + thinkingLevel?: string + customPrompt?: string + customAgentCommand?: string + agentCommandOverride?: string + /** When true, append `Co-authored-by: Orca ...` after the cleaned message. */ + attributionEnabled?: boolean +} + +export type GenerateCommitMessageResult = + | { success: true; message: string; agentLabel?: string } + | { success: false; error: string; canceled?: boolean } + +export type RemoteCommitMessageExecResult = { + stdout: string + stderr: string + exitCode: number | null + timedOut: boolean + canceled?: boolean + spawnError?: string +} + +export type CommitMessageGenerationTarget = + | { kind: 'local'; cwd: string; env?: NodeJS.ProcessEnv } + | { + kind: 'remote' + cwd: string + execute: ( + plan: CommitMessagePlan, + cwd: string, + timeoutMs: number + ) => Promise + missingBinaryLocation: string + } + +type ResolveCommitMessageSettingsResult = + | { ok: true; params: GenerateCommitMessageParams } + | { ok: false; error: string } + +type InternalCommitMessageGenerationResult = + | { success: true; commitMessage: GeneratedCommitMessage; agentLabel?: string } + | { success: false; error: string; canceled?: boolean } + +/** Appends the Orca trailer if the message does not already include it. */ +export function applyOrcaAttribution(message: string, enabled: boolean): string { + if (!enabled) { + // Why: trim trailing whitespace even on the no-attribution path so a + // stray "\n" from the agent's output never reaches the textarea as a + // visible blank line. + return message.replace(/\s+$/, '') + } + const stripped = message.replace(/\s+$/, '') + if (stripped.includes(ORCA_GIT_COMMIT_TRAILER)) { + return stripped + } + // Why: a blank line separates the trailer block from the body so `git + // interpret-trailers` and most parsers treat it as a real trailer instead + // of a paragraph continuation. + return `${stripped}\n\n${ORCA_GIT_COMMIT_TRAILER}` +} + +export function resolveCommitMessageSettings( + settings: GlobalSettings +): ResolveCommitMessageSettingsResult { + const config = settings.commitMessageAi + if (!config?.enabled || !config.agentId) { + return { ok: false, error: 'Enable AI commit messages and choose an agent in Settings -> Git.' } + } + + if (isCustomAgentId(config.agentId)) { + const customAgentCommand = config.customAgentCommand.trim() + if (!customAgentCommand) { + return { + ok: false, + error: 'Custom command is empty. Add one in Settings -> Git -> AI Commit Messages.' + } + } + return { + ok: true, + params: { + agentId: CUSTOM_AGENT_ID, + model: '', + customPrompt: config.customPrompt, + customAgentCommand, + attributionEnabled: settings.enableGitHubAttribution === true + } + } + } + + const agentId = config.agentId ?? DEFAULT_COMMIT_MESSAGE_AGENT_ID + const spec = getCommitMessageAgentSpec(agentId) + if (!spec) { + return { ok: false, error: `Agent "${agentId}" does not support AI commit messages.` } + } + + const persistedModelId = config.selectedModelByAgent[agentId] ?? spec.defaultModelId + const model = + getCommitMessageModel(agentId, persistedModelId) ?? + getCommitMessageModel(agentId, spec.defaultModelId) + if (!model) { + return { ok: false, error: `No model is available for ${spec.label}.` } + } + + const persistedThinking = config.selectedThinkingByModel[model.id] + const thinkingLevel = model.thinkingLevels?.some((level) => level.id === persistedThinking) + ? persistedThinking + : model.defaultThinkingLevel + + const agentCommandOverride = settings.agentCmdOverrides?.[agentId]?.trim() + return { + ok: true, + params: { + agentId, + model: model.id, + thinkingLevel, + customPrompt: config.customPrompt, + ...(agentCommandOverride ? { agentCommandOverride } : {}), + attributionEnabled: settings.enableGitHubAttribution === true + } + } +} + +function sanitizeAgentFailureDetail(detail: string | null): string | null { + const trimmed = detail?.replace(/\p{Cc}+/gu, ' ').trim() + if (!trimmed) { + return null + } + return trimmed.length > 240 ? `${trimmed.slice(0, 240).trimEnd()}...` : trimmed +} + +function userFacingAgentFailure(label: string): string { + return `${label} failed. Check the agent CLI configuration and try again.` +} + +function userFacingUnsafeWindowsBatchArgs(label: string): string { + return `${label} cannot be run as a Windows batch command with the prompt in argv. Remove {prompt} so Orca sends the prompt on stdin.` +} + +// Why: on Windows, npm-installed CLIs like `claude` and `codex` are usually +// `.cmd` shims. We route those through cmd.exe so Node can launch them, and +// `child.kill()` would only terminate the wrapper. `taskkill /T /F` walks the +// process tree from the wrapper PID and force-kills every descendant, which is +// what users expect when they hit "stop generating". +function killProcessTree(child: ChildProcess): void { + const pid = child.pid + if (!pid) { + return + } + if (process.platform === 'win32') { + exec(`taskkill /pid ${pid} /T /F`, () => { + // Best-effort; the spawn's `close` listener fires once the tree exits. + }) + return + } + try { + child.kill('SIGKILL') + } catch { + // The child may have already exited between the in-flight check and the + // kill - that race is benign and can be ignored. + } +} + +// Keying by `local:${cwd}` keeps local cancellation independent from any SSH +// worktree with the same remote path. +const cancelTokensByLane = new Map void>() + +function localLaneKey(cwd: string): string { + return `local:${cwd}` +} + +export function cancelGenerateCommitMessageLocal(cwd: string): void { + cancelTokensByLane.get(localLaneKey(cwd))?.() +} + +async function runLocalPlan( + plan: CommitMessagePlan, + cwd: string, + env: NodeJS.ProcessEnv | undefined +): Promise { + const { binary, args, stdinPayload, label } = plan + return new Promise((resolve) => { + let child: ChildProcess + try { + const spawnEnv = env ?? process.env + const resolvedBinary = + process.platform === 'win32' + ? resolveCliCommand(binary, { pathEnv: spawnEnv.PATH ?? spawnEnv.Path ?? null }) + : binary + const { spawnCmd, spawnArgs } = getSpawnArgsForWindows(resolvedBinary, args) + child = spawn(spawnCmd, spawnArgs, { + cwd, + env: spawnEnv, + stdio: ['pipe', 'pipe', 'pipe'], + windowsHide: true + }) + } catch (error) { + if (error instanceof UnsafeWindowsBatchArgumentsError) { + resolve({ + success: false, + error: userFacingUnsafeWindowsBatchArgs(label) + }) + return + } + console.error('[commit-message] Failed to spawn local generator:', error) + resolve({ + success: false, + error: `${label} could not be started. Check the agent command in Settings and try again.` + }) + return + } + + let stdout = '' + let stderr = '' + let stdoutBytes = 0 + let stderrBytes = 0 + let outputLimitExceeded = false + let settled = false + let canceledByUser = false + const laneKey = localLaneKey(cwd) + const finalize = (result: InternalCommitMessageGenerationResult): void => { + if (settled) { + return + } + settled = true + cancelTokensByLane.delete(laneKey) + resolve(result) + } + + cancelTokensByLane.set(laneKey, () => { + canceledByUser = true + killProcessTree(child) + }) + + const timer = setTimeout(() => { + killProcessTree(child) + finalize({ + success: false, + error: `Generation timed out after ${GENERATION_TIMEOUT_MS / 1000}s.` + }) + }, GENERATION_TIMEOUT_MS) + + child.stdout?.on('data', (chunk: Buffer) => { + stdoutBytes += chunk.byteLength + if (stdoutBytes > MAX_AGENT_OUTPUT_BYTES) { + outputLimitExceeded = true + killProcessTree(child) + return + } + stdout += chunk.toString('utf-8') + }) + child.stderr?.on('data', (chunk: Buffer) => { + stderrBytes += chunk.byteLength + if (stderrBytes > MAX_AGENT_OUTPUT_BYTES) { + outputLimitExceeded = true + killProcessTree(child) + return + } + stderr += chunk.toString('utf-8') + }) + child.on('error', (error) => { + clearTimeout(timer) + const code = (error as NodeJS.ErrnoException).code + if (code === 'ENOENT') { + finalize({ + success: false, + error: `${binary} not found on PATH. Install ${label} to use AI commit messages.` + }) + return + } + console.error('[commit-message] Local generator failed after spawn:', error) + finalize({ + success: false, + error: `${label} failed to start. Check the agent command in Settings and try again.` + }) + }) + child.on('close', (code) => { + clearTimeout(timer) + if (canceledByUser) { + finalize({ success: false, error: 'Generation canceled.', canceled: true }) + return + } + if (outputLimitExceeded) { + finalize({ success: false, error: userFacingAgentFailure(label) }) + return + } + finalizeFromAgentOutput({ code, stdout, stderr, label, finalize }) + }) + + child.stdin?.end(stdinPayload ?? undefined) + }) +} + +function finalizeFromAgentOutput(args: { + code: number | null + stdout: string + stderr: string + label: string + finalize: (result: InternalCommitMessageGenerationResult) => void +}): void { + const { code, stdout, stderr, label, finalize } = args + if (code !== 0) { + const safeDetail = sanitizeAgentFailureDetail(extractAgentErrorMessage(stdout, stderr)) + console.error('[commit-message] Generator failed:', { + label, + exitCode: code, + safeDetail, + stdout, + stderr + }) + finalize({ success: false, error: userFacingAgentFailure(label) }) + return + } + const cleaned = cleanGeneratedCommitMessage(stdout) + if (!cleaned) { + finalize({ success: false, error: `${label} returned an empty message.` }) + return + } + const commitMessage = splitGeneratedCommitMessage(cleaned) + finalize({ + success: true, + commitMessage, + agentLabel: label + }) +} + +async function runRemotePlan( + plan: CommitMessagePlan, + target: Extract +): Promise { + const { binary, label } = plan + let result: RemoteCommitMessageExecResult + try { + result = await target.execute(plan, target.cwd, GENERATION_TIMEOUT_MS) + } catch (error) { + console.error('[commit-message] Remote generator request failed:', error) + return { + success: false, + error: `${label} could not be reached on the ${target.missingBinaryLocation}. Try again after the SSH connection recovers.` + } + } + if (result.spawnError) { + if (result.spawnError === WINDOWS_BATCH_UNSAFE_ARGUMENTS_ERROR) { + return { + success: false, + error: userFacingUnsafeWindowsBatchArgs(label) + } + } + if (/ENOENT/i.test(result.spawnError)) { + return { + success: false, + error: `${binary} not found on the ${target.missingBinaryLocation}. Install ${label} there.` + } + } + console.error('[commit-message] Remote generator spawn failed:', result.spawnError) + return { + success: false, + error: `${label} could not be started on the ${target.missingBinaryLocation}. Check the agent command there and try again.` + } + } + if (result.canceled) { + return { success: false, error: 'Generation canceled.', canceled: true } + } + if (result.timedOut) { + return { + success: false, + error: `Generation timed out after ${GENERATION_TIMEOUT_MS / 1000}s.` + } + } + + return new Promise((resolve) => { + finalizeFromAgentOutput({ + code: result.exitCode, + stdout: result.stdout, + stderr: result.stderr, + label, + finalize: resolve + }) + }) +} + +function formatCommitMessageGenerationResult( + result: InternalCommitMessageGenerationResult, + attributionEnabled: boolean +): GenerateCommitMessageResult { + if (!result.success) { + return result + } + return { + success: true, + message: applyOrcaAttribution(result.commitMessage.message, attributionEnabled), + agentLabel: result.agentLabel + } +} + +export async function generateCommitMessageFromContext( + context: CommitMessageDraftContext, + params: GenerateCommitMessageParams, + target: CommitMessageGenerationTarget +): Promise { + const prompt = buildCommitMessagePrompt(context, params.customPrompt ?? '') + const planned = planCommitMessageGeneration(params, prompt) + if (!planned.ok) { + return { success: false, error: planned.error } + } + + const internalResult = + target.kind === 'remote' + ? await runRemotePlan(planned.plan, target) + : await runLocalPlan(planned.plan, target.cwd, target.env) + return formatCommitMessageGenerationResult(internalResult, params.attributionEnabled === true) +} diff --git a/src/main/win32-utils.test.ts b/src/main/win32-utils.test.ts index 621bfaaf7..cf4efb4cd 100644 --- a/src/main/win32-utils.test.ts +++ b/src/main/win32-utils.test.ts @@ -44,9 +44,9 @@ describe('getSpawnArgsForWindows', () => { '--foo' ]) expect(spawnCmd).toBe('C:\\Windows\\System32\\cmd.exe') - // Why: /d disables AutoRun; /c runs the given command and exits. Args - // follow the batch path literally without re-escaping. - expect(spawnArgs).toEqual(['/d', '/c', 'C:\\tools\\codex.cmd', 'login', '--foo']) + // Why: /d disables AutoRun; /s preserves quoted command-line parsing; + // /c runs the quoted batch command and exits. + expect(spawnArgs).toEqual(['/d', '/s', '/c', '"C:\\tools\\codex.cmd" "login" "--foo"']) }) } finally { if (originalComSpec === undefined) { @@ -72,6 +72,14 @@ describe('getSpawnArgsForWindows', () => { expect(spawnArgs).toEqual(['login']) }) }) + + it('rejects unsafe args for .cmd scripts on win32', () => { + withPlatform('win32', () => { + expect(() => getSpawnArgsForWindows('C:\\tools\\agent.cmd', ['hello & goodbye'])).toThrow( + 'UNSAFE_WINDOWS_BATCH_ARGUMENTS' + ) + }) + }) }) describe('isPermissionError', () => { diff --git a/src/main/win32-utils.ts b/src/main/win32-utils.ts index 4465fa223..edddf2eef 100644 --- a/src/main/win32-utils.ts +++ b/src/main/win32-utils.ts @@ -22,6 +22,26 @@ export function isWindowsBatchScript(commandPath: string): boolean { return process.platform === 'win32' && /\.(cmd|bat)$/i.test(commandPath) } +export const WINDOWS_BATCH_UNSAFE_ARGUMENTS_ERROR = 'UNSAFE_WINDOWS_BATCH_ARGUMENTS' + +export class UnsafeWindowsBatchArgumentsError extends Error { + constructor() { + super(WINDOWS_BATCH_UNSAFE_ARGUMENTS_ERROR) + this.name = 'UnsafeWindowsBatchArgumentsError' + } +} + +function hasUnsafeWindowsBatchSyntax(value: string): boolean { + return /[&|<>^"%!\r\n]/.test(value) +} + +function quoteWindowsBatchToken(value: string): string { + if (hasUnsafeWindowsBatchSyntax(value)) { + throw new UnsafeWindowsBatchArgumentsError() + } + return `"${value}"` +} + /** Check whether an error is a Windows permission error (EACCES or EPERM). */ export function isPermissionError(error: unknown): boolean { return ( @@ -103,18 +123,17 @@ export function grantDirAcl(dirPath: string, options?: { recursive?: boolean }): * Why /d: disables per-machine/user AutoRun registry commands so a background * spawn cannot inherit surprising side effects from the user's shell config. * - * SAFETY: when the .cmd/.bat branch is taken, cmd.exe re-parses the combined - * command line, so callers MUST only pass trusted/literal args. An arg - * containing `&`, `|`, `^`, `<`, `>`, or unbalanced `"` can escape the - * intended command and execute arbitrary cmd.exe syntax. Do not feed - * user-supplied strings through this helper without first validating them. + * SAFETY: when the .cmd/.bat branch is taken, cmd.exe re-parses the command + * line. Args with cmd metacharacters are rejected instead of escaped because + * the agent prompt may contain arbitrary staged diff text. */ export function getSpawnArgsForWindows( command: string, args: string[] ): { spawnCmd: string; spawnArgs: string[] } { if (isWindowsBatchScript(command)) { - return { spawnCmd: getCmdExePath(), spawnArgs: ['/d', '/c', command, ...args] } + const commandLine = [command, ...args].map(quoteWindowsBatchToken).join(' ') + return { spawnCmd: getCmdExePath(), spawnArgs: ['/d', '/s', '/c', commandLine] } } return { spawnCmd: command, spawnArgs: args } } diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index 73322f995..9eb7f202d 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -1214,6 +1214,17 @@ export type PreloadApi = { message: string connectionId?: string }) => Promise<{ success: boolean; error?: string }> + generateCommitMessage: (args: { + worktreePath: string + connectionId?: string + }) => Promise< + | { success: true; message: string; agentLabel?: string } + | { success: false; error: string; canceled?: boolean } + > + cancelGenerateCommitMessage: (args: { + worktreePath: string + connectionId?: string + }) => Promise stage: (args: { worktreePath: string filePath: string diff --git a/src/preload/index.ts b/src/preload/index.ts index 5e987664e..d26874832 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1807,6 +1807,14 @@ const api = { message: string connectionId?: string }): Promise<{ success: boolean; error?: string }> => ipcRenderer.invoke('git:commit', args), + generateCommitMessage: (args: { + worktreePath: string + connectionId?: string + }): Promise => ipcRenderer.invoke('git:generateCommitMessage', args), + cancelGenerateCommitMessage: (args: { + worktreePath: string + connectionId?: string + }): Promise => ipcRenderer.invoke('git:cancelGenerateCommitMessage', args), stage: (args: { worktreePath: string filePath: string diff --git a/src/relay/agent-exec-handler.test.ts b/src/relay/agent-exec-handler.test.ts new file mode 100644 index 000000000..18a9a5966 --- /dev/null +++ b/src/relay/agent-exec-handler.test.ts @@ -0,0 +1,259 @@ +import { EventEmitter } from 'events' +import { exec, spawn } from 'child_process' +import { mkdtempSync, rmSync, writeFileSync } from 'fs' +import { tmpdir } from 'os' +import { join } from 'path' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type * as ChildProcess from 'child_process' +import type { MethodHandler } from './dispatcher' +import { AgentExecHandler } from './agent-exec-handler' + +vi.mock('child_process', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + exec: vi.fn(), + spawn: vi.fn() + } +}) + +const spawnMock = vi.mocked(spawn) +const execMock = vi.mocked(exec) + +function withPlatform(platform: NodeJS.Platform, fn: () => T): T { + const original = process.platform + Object.defineProperty(process, 'platform', { configurable: true, value: platform }) + try { + return fn() + } finally { + Object.defineProperty(process, 'platform', { configurable: true, value: original }) + } +} + +type FakeChild = EventEmitter & { + pid: number + kill: ReturnType + stdout: EventEmitter + stderr: EventEmitter + stdin: { end: ReturnType } +} + +function createFakeChild(): FakeChild { + return Object.assign(new EventEmitter(), { + pid: 12345, + kill: vi.fn(), + stdout: new EventEmitter(), + stderr: new EventEmitter(), + stdin: { end: vi.fn() } + }) +} + +function createHandlers(): Map { + const handlers = new Map() + new AgentExecHandler({ + onRequest: (method: string, handler: MethodHandler): void => { + handlers.set(method, handler) + } + } as never) + return handlers +} + +describe('AgentExecHandler', () => { + beforeEach(() => { + spawnMock.mockReset() + execMock.mockReset() + }) + + it('executes a non-interactive command with captured output and stdin', async () => { + const child = createFakeChild() + spawnMock.mockReturnValue(child as never) + const handlers = createHandlers() + + const pending = handlers.get('agent.execNonInteractive')!( + { + binary: 'agent', + args: ['--flag', 42], + cwd: '/repo', + stdin: 'PROMPT', + timeoutMs: 5_000 + }, + { isStale: () => false } + ) + + child.stdout.emit('data', Buffer.from('message')) + child.stderr.emit('data', Buffer.from('warning')) + child.emit('close', 0) + + await expect(pending).resolves.toEqual({ + stdout: 'message', + stderr: 'warning', + exitCode: 0, + timedOut: false, + canceled: false + }) + expect(spawnMock).toHaveBeenCalledWith('agent', ['--flag', '42'], { + cwd: '/repo', + env: process.env, + stdio: ['pipe', 'pipe', 'pipe'], + windowsHide: true + }) + expect(child.stdin.end).toHaveBeenCalledWith('PROMPT') + }) + + it('merges caller-supplied provider environment into the spawned command environment', async () => { + const child = createFakeChild() + spawnMock.mockReturnValue(child as never) + const handlers = createHandlers() + + const pending = handlers.get('agent.execNonInteractive')!( + { + binary: 'codex', + args: ['exec'], + cwd: '/repo', + stdin: 'PROMPT', + timeoutMs: 5_000, + env: { + CODEX_HOME: '/managed/codex-home', + PATH: '/managed/bin' + } + }, + { isStale: () => false } + ) + + child.emit('close', 0) + + await expect(pending).resolves.toMatchObject({ + exitCode: 0, + timedOut: false + }) + expect(spawnMock).toHaveBeenCalledWith('codex', ['exec'], { + cwd: '/repo', + env: expect.objectContaining({ + ...process.env, + CODEX_HOME: '/managed/codex-home', + PATH: '/managed/bin' + }), + stdio: ['pipe', 'pipe', 'pipe'], + windowsHide: true + }) + }) + + it('resolves bare Windows agent commands to batch shims before spawning', async () => { + const tempDir = mkdtempSync(join(tmpdir(), 'orca-agent-exec-')) + const originalComSpec = process.env.ComSpec + process.env.ComSpec = 'C:\\Windows\\System32\\cmd.exe' + try { + await withPlatform('win32', async () => { + const codexShim = join(tempDir, 'codex.cmd') + writeFileSync(codexShim, '@echo off\r\n') + const child = createFakeChild() + spawnMock.mockReturnValue(child as never) + const handlers = createHandlers() + + const pending = handlers.get('agent.execNonInteractive')!( + { + binary: 'codex', + args: ['exec', '-s', 'read-only'], + cwd: 'C:\\repo', + stdin: 'PROMPT', + timeoutMs: 5_000, + env: { PATH: tempDir } + }, + { isStale: () => false } + ) + + child.emit('close', 0) + + await expect(pending).resolves.toMatchObject({ + exitCode: 0, + timedOut: false + }) + expect(spawnMock).toHaveBeenCalledWith( + 'C:\\Windows\\System32\\cmd.exe', + ['/d', '/s', '/c', `"${codexShim}" "exec" "-s" "read-only"`], + { + cwd: 'C:\\repo', + env: expect.objectContaining({ PATH: tempDir }), + stdio: ['pipe', 'pipe', 'pipe'], + windowsHide: true + } + ) + }) + } finally { + rmSync(tempDir, { recursive: true, force: true }) + if (originalComSpec === undefined) { + delete process.env.ComSpec + } else { + process.env.ComSpec = originalComSpec + } + } + }) + + it('rejects unsafe args when routing Windows batch shims through cmd.exe', async () => { + await withPlatform('win32', async () => { + const handlers = createHandlers() + + const result = await handlers.get('agent.execNonInteractive')!( + { + binary: 'C:\\tools\\agent.cmd', + args: ['hello & goodbye'], + cwd: 'C:\\repo', + stdin: null, + timeoutMs: 5_000 + }, + { isStale: () => false } + ) + + expect(result).toEqual({ + stdout: '', + stderr: '', + exitCode: null, + timedOut: false, + spawnError: 'UNSAFE_WINDOWS_BATCH_ARGUMENTS' + }) + expect(spawnMock).not.toHaveBeenCalled() + }) + }) + + it('cancels the in-flight command for the requested cwd', async () => { + const child = createFakeChild() + spawnMock.mockReturnValue(child as never) + const handlers = createHandlers() + + const pending = handlers.get('agent.execNonInteractive')!( + { + binary: 'agent', + args: [], + cwd: '/repo', + stdin: null, + timeoutMs: 5_000 + }, + { isStale: () => false } + ) + + await expect( + handlers.get('agent.cancelExec')!({ cwd: '/repo' }, { isStale: () => false }) + ).resolves.toEqual({ canceled: true }) + + if (process.platform === 'win32') { + expect(execMock).toHaveBeenCalledWith('taskkill /pid 12345 /T /F', expect.any(Function)) + } else { + expect(child.kill).toHaveBeenCalledWith('SIGKILL') + } + + child.emit('close', null) + await expect(pending).resolves.toMatchObject({ + exitCode: null, + timedOut: false, + canceled: true + }) + }) + + it('reports when cancellation has no matching in-flight command', async () => { + const handlers = createHandlers() + + await expect( + handlers.get('agent.cancelExec')!({ cwd: '/repo' }, { isStale: () => false }) + ).resolves.toEqual({ canceled: false }) + }) +}) diff --git a/src/relay/agent-exec-handler.ts b/src/relay/agent-exec-handler.ts new file mode 100644 index 000000000..38dc75601 --- /dev/null +++ b/src/relay/agent-exec-handler.ts @@ -0,0 +1,254 @@ +import { exec, spawn, type ChildProcess } from 'child_process' +import { existsSync } from 'fs' +import { delimiter, join } from 'path' +import type { RelayDispatcher } from './dispatcher' + +const DEFAULT_TIMEOUT_MS = 60_000 +const MAX_TIMEOUT_MS = 5 * 60 * 1000 +const MAX_OUTPUT_BYTES = 4 * 1024 * 1024 +const WINDOWS_BATCH_UNSAFE_ARGUMENTS_ERROR = 'UNSAFE_WINDOWS_BATCH_ARGUMENTS' + +function getCmdExePath(): string { + return process.env.ComSpec || `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\cmd.exe` +} + +function isWindowsBatchScript(commandPath: string): boolean { + return process.platform === 'win32' && /\.(cmd|bat)$/i.test(commandPath) +} + +function hasUnsafeWindowsBatchSyntax(value: string): boolean { + return /[&|<>^"%!\r\n]/.test(value) +} + +function quoteWindowsBatchToken(value: string): string { + if (hasUnsafeWindowsBatchSyntax(value)) { + throw new Error(WINDOWS_BATCH_UNSAFE_ARGUMENTS_ERROR) + } + return `"${value}"` +} + +function resolveWindowsCommand(binary: string, env: NodeJS.ProcessEnv): string { + if (process.platform !== 'win32') { + return binary + } + if (/[\\/]/.test(binary) || /\.[a-z0-9]+$/i.test(binary)) { + return binary + } + + const pathEnv = env.PATH ?? env.Path + if (!pathEnv) { + return binary + } + const names = [`${binary}.cmd`, `${binary}.exe`, `${binary}.bat`, binary] + for (const directory of pathEnv.split(delimiter).filter(Boolean)) { + for (const name of names) { + const candidate = join(directory, name) + if (existsSync(candidate)) { + return candidate + } + } + } + return binary +} + +function getWindowsSafeSpawn( + binary: string, + args: string[], + env: NodeJS.ProcessEnv +): { spawnCmd: string; spawnArgs: string[] } { + const resolvedBinary = resolveWindowsCommand(binary, env) + if (!isWindowsBatchScript(resolvedBinary)) { + return { spawnCmd: resolvedBinary, spawnArgs: args } + } + const commandLine = [resolvedBinary, ...args].map(quoteWindowsBatchToken).join(' ') + return { spawnCmd: getCmdExePath(), spawnArgs: ['/d', '/s', '/c', commandLine] } +} + +// Why: mirrors src/main/text-generation/commit-message-text-generation.ts. On +// Windows, npm-installed CLIs like `claude`/`codex` are usually `.cmd` shims. +// We route those through cmd.exe so Node can launch them, and taskkill is +// needed to terminate the whole wrapper + node.exe process tree. Kept +// duplicated rather than imported because the relay ships to remote hosts. +function killProcessTree(child: ChildProcess): void { + const pid = child.pid + if (!pid) { + return + } + if (process.platform === 'win32') { + exec(`taskkill /pid ${pid} /T /F`, () => { + // Best-effort; the spawn's `close` listener fires once the tree exits. + }) + return + } + try { + child.kill('SIGKILL') + } catch { + // Child may already have exited between the kill request and now. + } +} + +type ExecParams = { + binary: unknown + args: unknown + cwd: unknown + stdin: unknown + timeoutMs: unknown + env: unknown +} + +type CancelParams = { + cwd: unknown +} + +type ExecResult = { + stdout: string + stderr: string + exitCode: number | null + timedOut: boolean + /** Set when the user canceled the exec via `agent.cancelExec`. */ + canceled?: boolean + /** Set when the binary could not be spawned (e.g. ENOENT). */ + spawnError?: string +} + +/** + * Non-interactive subprocess exec on the remote host. Used by the AI commit + * message generator to spawn agent CLIs (claude, codex, …) with the staged + * diff piped via stdin and the output captured to stdout. Distinct from + * `pty.spawn` because we want no terminal allocation, no escape sequences, + * and a clean exit code instead of an interactive session. + */ +export class AgentExecHandler { + // Why: a single in-flight exec per cwd is enough β€” the renderer prevents + // double-clicks. Keying by cwd lets `agent.cancelExec({cwd})` find the + // child without the client having to track relay-internal request ids. + private inFlightByCwd = new Map void }>() + + constructor(dispatcher: RelayDispatcher) { + dispatcher.onRequest('agent.execNonInteractive', (p) => this.exec(p as ExecParams)) + dispatcher.onRequest('agent.cancelExec', (p) => this.cancel(p as CancelParams)) + } + + private async cancel(params: CancelParams): Promise<{ canceled: boolean }> { + const cwd = typeof params.cwd === 'string' ? params.cwd : '' + const entry = this.inFlightByCwd.get(cwd) + if (!entry) { + return { canceled: false } + } + entry.markCanceled() + killProcessTree(entry.child) + return { canceled: true } + } + + private async exec(params: ExecParams): Promise { + const binary = typeof params.binary === 'string' ? params.binary : '' + if (!binary) { + throw new Error('agent.execNonInteractive: binary is required') + } + const args = Array.isArray(params.args) ? params.args.map((a) => String(a)) : [] + const cwd = typeof params.cwd === 'string' && params.cwd.length > 0 ? params.cwd : undefined + const stdinPayload = typeof params.stdin === 'string' ? params.stdin : null + const requestedTimeout = + typeof params.timeoutMs === 'number' ? params.timeoutMs : DEFAULT_TIMEOUT_MS + const timeoutMs = Math.max(1_000, Math.min(MAX_TIMEOUT_MS, requestedTimeout)) + const extraEnv = + params.env && typeof params.env === 'object' && !Array.isArray(params.env) + ? (params.env as Record) + : null + const spawnEnv = extraEnv ? { ...process.env, ...extraEnv } : process.env + + return new Promise((resolve) => { + let child + try { + const { spawnCmd, spawnArgs } = getWindowsSafeSpawn(binary, args, spawnEnv) + child = spawn(spawnCmd, spawnArgs, { + cwd, + env: spawnEnv, + stdio: ['pipe', 'pipe', 'pipe'], + windowsHide: true + }) + } catch (error) { + resolve({ + stdout: '', + stderr: '', + exitCode: null, + timedOut: false, + spawnError: error instanceof Error ? error.message : String(error) + }) + return + } + + let stdout = '' + let stderr = '' + let stdoutBytes = 0 + let stderrBytes = 0 + let timedOut = false + let canceled = false + let settled = false + const laneKey = typeof cwd === 'string' ? cwd : '' + const finish = (result: ExecResult): void => { + if (settled) { + return + } + settled = true + if (laneKey) { + this.inFlightByCwd.delete(laneKey) + } + resolve(result) + } + if (laneKey) { + this.inFlightByCwd.set(laneKey, { + child, + markCanceled: () => { + canceled = true + } + }) + } + + const timer = setTimeout(() => { + timedOut = true + // Why: tree-kill because some CLIs trap SIGTERM and continue streaming; + // also Windows wraps `.cmd` shims in cmd.exe, so the immediate child + // is not the real node.exe process. + killProcessTree(child) + }, timeoutMs) + + child.stdout?.on('data', (chunk: Buffer) => { + stdoutBytes += chunk.byteLength + if (stdoutBytes > MAX_OUTPUT_BYTES) { + killProcessTree(child) + return + } + stdout += chunk.toString('utf-8') + }) + child.stderr?.on('data', (chunk: Buffer) => { + stderrBytes += chunk.byteLength + if (stderrBytes > MAX_OUTPUT_BYTES) { + killProcessTree(child) + return + } + stderr += chunk.toString('utf-8') + }) + child.on('error', (error) => { + clearTimeout(timer) + finish({ + stdout, + stderr, + exitCode: null, + timedOut, + spawnError: error.message + }) + }) + child.on('close', (code) => { + clearTimeout(timer) + finish({ stdout, stderr, exitCode: code, timedOut, canceled }) + }) + + if (stdinPayload !== null) { + child.stdin?.end(stdinPayload) + } else { + child.stdin?.end() + } + }) + } +} diff --git a/src/relay/git-exec-validator.test.ts b/src/relay/git-exec-validator.test.ts index 54039ebd7..b808e692b 100644 --- a/src/relay/git-exec-validator.test.ts +++ b/src/relay/git-exec-validator.test.ts @@ -23,6 +23,8 @@ describe('validateGitExecArgs', () => { [['symbolic-ref', 'HEAD']], [['symbolic-ref', '--short', 'HEAD']], [['merge-base', 'main', 'HEAD']], + [['diff', '--cached', '--name-status']], + [['diff', '--cached', '--patch', '--minimal', '--no-color', '--no-ext-diff']], [['ls-files', '--error-unmatch', 'foo.txt']], [['config', '--get', 'user.name']], [['config', '--get-all', 'remote.origin.url']], @@ -189,4 +191,19 @@ describe('validateGitExecArgs', () => { expectBlocked(['symbolic-ref', '--delete=HEAD'], 'git symbolic-ref write operations') }) }) + + describe('git diff', () => { + it('rejects unstaged diff reads', () => { + expectBlocked(['diff', '--name-status'], 'restricted to staged changes') + }) + + it('rejects arbitrary refs and pathspecs', () => { + expectBlocked(['diff', '--cached', 'HEAD~1'], 'git diff flag not allowed') + expectBlocked(['diff', '--cached', '--', 'src/file.ts'], 'git diff flag not allowed') + }) + + it('rejects no-index reads', () => { + expectBlocked(['diff', '--cached', '--no-index', '/etc/passwd'], 'git diff flag not allowed') + }) + }) }) diff --git a/src/relay/git-exec-validator.ts b/src/relay/git-exec-validator.ts index b881fbb6a..0c8df69a4 100644 --- a/src/relay/git-exec-validator.ts +++ b/src/relay/git-exec-validator.ts @@ -16,6 +16,7 @@ const ALLOWED_GIT_SUBCOMMANDS = new Set([ 'remote', 'symbolic-ref', 'merge-base', + 'diff', 'ls-files', 'for-each-ref', 'config' @@ -69,6 +70,15 @@ const REMOTE_WRITE_SUBCOMMANDS = new Set([ 'update' ]) const SYMBOLIC_REF_WRITE_FLAGS = new Set(['-d', '--delete', '-m']) +const DIFF_ALLOWED_FLAGS = new Set([ + '--cached', + '--staged', + '--name-status', + '--patch', + '--minimal', + '--no-color', + '--no-ext-diff' +]) // Why: git accepts --flag=value compound syntax (e.g. --file=/etc/passwd), // which bypasses exact-match Set.has() checks. This helper catches both forms. @@ -133,4 +143,16 @@ export function validateGitExecArgs(args: string[]): void { throw new Error('git symbolic-ref write operations are not allowed via exec') } } + if (subcommand === 'diff') { + // Why: SSH commit-message generation only needs read-only staged diffs. + // Keep this narrow so `git.exec` cannot become a general file reader via + // arbitrary revisions, pathspecs, or --no-index. + if (!restArgs.some((a) => a === '--cached' || a === '--staged')) { + throw new Error('git diff via exec is restricted to staged changes') + } + const unsupportedArg = restArgs.find((a) => !DIFF_ALLOWED_FLAGS.has(a)) + if (unsupportedArg) { + throw new Error(`git diff flag not allowed via exec: ${unsupportedArg}`) + } + } } diff --git a/src/relay/relay.ts b/src/relay/relay.ts index b1bc2df32..b221c7125 100644 --- a/src/relay/relay.ts +++ b/src/relay/relay.ts @@ -5,6 +5,10 @@ topological order. Splitting by line count would scatter ordered side- effects across modules and obscure the lifecycle. */ +/* eslint-disable max-lines -- Why: the relay entrypoint owns process startup, + daemon reconnect, and handler registration. Splitting the orchestration + would hide the startup order, which is the important invariant here. */ + // Orca Relay β€” lightweight daemon deployed to remote hosts. // Communicates over stdin/stdout using the framed JSON-RPC protocol. // The Electron app (client) deploys this script via SCP and launches @@ -28,6 +32,7 @@ import { FsHandler } from './fs-handler' import { GitHandler } from './git-handler' import { PreflightHandler } from './preflight-handler' import { PortScanHandler } from './port-scan-handler' +import { AgentExecHandler } from './agent-exec-handler' import { endpointDirForRelaySocket, RelayAgentHookServer } from './agent-hook-server' import { PluginOverlayManager } from './plugin-overlay' import { @@ -232,6 +237,9 @@ async function main(): Promise { const _portScanHandler = new PortScanHandler(dispatcher) void _portScanHandler + const _agentExecHandler = new AgentExecHandler(dispatcher) + void _agentExecHandler + // ── Agent-hook server ───────────────────────────────────────────── // Why: hosts a loopback HTTP receiver inside the relay process so agent // CLIs running in remote PTYs can post hook events without leaving the diff --git a/src/renderer/src/components/right-sidebar/CommitArea.chevron-spinner.test.tsx b/src/renderer/src/components/right-sidebar/CommitArea.chevron-spinner.test.tsx index 0d84e6517..bf85b0365 100644 --- a/src/renderer/src/components/right-sidebar/CommitArea.chevron-spinner.test.tsx +++ b/src/renderer/src/components/right-sidebar/CommitArea.chevron-spinner.test.tsx @@ -85,11 +85,19 @@ function baseProps(overrides: Partial = {}) { commitMessage: 'feat: add commit area', commitError: null as string | null, isCommitting: inputs.isCommitting, + aiEnabled: false, + aiAgentConfigured: false, + isGenerating: false, + generateError: null as string | null, + stagedCount: inputs.stagedCount, + hasUnresolvedConflicts: inputs.hasUnresolvedConflicts, isRemoteOperationActive: inputs.isRemoteOperationActive, inFlightRemoteOpKind: inputs.inFlightRemoteOpKind ?? null, primaryAction: resolvePrimaryAction(inputs), dropdownItems: resolveDropdownItems(inputs), onCommitMessageChange: vi.fn(), + onGenerate: vi.fn(), + onCancelGenerate: vi.fn(), onPrimaryAction: vi.fn(), onDropdownAction: vi.fn() as (kind: DropdownActionKind) => void } diff --git a/src/renderer/src/components/right-sidebar/CommitArea.generate.test.tsx b/src/renderer/src/components/right-sidebar/CommitArea.generate.test.tsx new file mode 100644 index 000000000..cce1ecae3 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/CommitArea.generate.test.tsx @@ -0,0 +1,213 @@ +import { describe, expect, it, vi } from 'vitest' +import { CommitArea } from './SourceControl' +import { Button } from '@/components/ui/button' +import { resolvePrimaryAction, type PrimaryActionInputs } from './source-control-primary-action' +import { resolveDropdownItems, type DropdownActionKind } from './source-control-dropdown-items' + +type ReactElementLike = { + type: unknown + props: Record +} + +function visit(node: unknown, cb: (node: ReactElementLike) => void): void { + if (node == null || typeof node === 'string' || typeof node === 'number') { + return + } + if (Array.isArray(node)) { + node.forEach((entry) => visit(entry, cb)) + return + } + const element = node as ReactElementLike + cb(element) + if (element.props?.children) { + visit(element.props.children, cb) + } +} + +function findNativeButtonByAriaLabel(node: unknown, ariaLabel: string): ReactElementLike { + let found: ReactElementLike | null = null + visit(node, (entry) => { + if (entry.type === 'button' && entry.props['aria-label'] === ariaLabel) { + found = entry + } + }) + if (!found) { + throw new Error(`button not found: ${ariaLabel}`) + } + return found +} + +function hasNativeButtonByAriaLabel(node: unknown, ariaLabel: string): boolean { + let found = false + visit(node, (entry) => { + if (entry.type === 'button' && entry.props['aria-label'] === ariaLabel) { + found = true + } + }) + return found +} + +function findTextarea(node: unknown): ReactElementLike { + let found: ReactElementLike | null = null + visit(node, (entry) => { + if (entry.type === 'textarea') { + found = entry + } + }) + if (!found) { + throw new Error('textarea not found') + } + return found +} + +function hasText(node: unknown, text: string): boolean { + let found = false + const walk = (value: unknown): void => { + if (typeof value === 'string') { + if (value.includes(text)) { + found = true + } + return + } + if (Array.isArray(value)) { + value.forEach(walk) + return + } + const element = value as ReactElementLike | null + if (element && typeof element === 'object' && 'props' in element) { + walk(element.props?.children) + } + } + visit(node, (entry) => { + walk(entry.props?.children) + }) + return found +} + +function buildInputs(overrides: Partial = {}): PrimaryActionInputs { + return { + stagedCount: 1, + hasUnstagedChanges: false, + hasMessage: true, + hasUnresolvedConflicts: false, + isCommitting: false, + isRemoteOperationActive: false, + upstreamStatus: { hasUpstream: true, ahead: 0, behind: 0 }, + ...overrides + } +} + +function baseProps(overrides: Partial = {}) { + const inputs = buildInputs(overrides) + return { + commitMessage: 'feat: add commit area', + commitError: null as string | null, + isCommitting: inputs.isCommitting, + aiEnabled: false, + aiAgentConfigured: false, + isGenerating: false, + generateError: null as string | null, + stagedCount: inputs.stagedCount, + hasUnresolvedConflicts: inputs.hasUnresolvedConflicts, + isRemoteOperationActive: inputs.isRemoteOperationActive, + inFlightRemoteOpKind: inputs.inFlightRemoteOpKind ?? null, + primaryAction: resolvePrimaryAction(inputs), + dropdownItems: resolveDropdownItems(inputs), + onCommitMessageChange: vi.fn(), + onGenerate: vi.fn(), + onCancelGenerate: vi.fn(), + onPrimaryAction: vi.fn(), + onDropdownAction: vi.fn() as (kind: DropdownActionKind) => void + } +} + +describe('CommitArea AI generation', () => { + it('does not render the AI generate affordance when the feature is disabled', () => { + const element = CommitArea(baseProps()) + expect(hasNativeButtonByAriaLabel(element, 'Generate commit message with AI')).toBe(false) + }) + + it('enables AI generation only when an agent is configured, changes are staged, and the message is empty', () => { + const onGenerate = vi.fn() + const props = baseProps({ hasMessage: false }) + const element = CommitArea({ + ...props, + commitMessage: '', + aiEnabled: true, + aiAgentConfigured: true, + onGenerate + }) + + const button = findNativeButtonByAriaLabel(element, 'Generate commit message with AI') + expect(button.props.disabled).toBe(false) + ;(button.props.onClick as () => void)() + expect(onGenerate).toHaveBeenCalledTimes(1) + }) + + it('disables AI generation when the textarea already has user text', () => { + const element = CommitArea({ + ...baseProps(), + aiEnabled: true, + aiAgentConfigured: true + }) + + const button = findNativeButtonByAriaLabel(element, 'Generate commit message with AI') + expect(button.props.disabled).toBe(true) + expect(button.props.title).toBe('Clear the message to regenerate.') + }) + + it('disables AI generation until the configured agent can actually run', () => { + const props = baseProps({ hasMessage: false }) + const element = CommitArea({ + ...props, + commitMessage: '', + aiEnabled: true, + aiAgentConfigured: false + }) + + const button = findNativeButtonByAriaLabel(element, 'Generate commit message with AI') + expect(button.props.disabled).toBe(true) + expect(button.props.title).toBe('Pick an agent in Settings β†’ AI Commit Messages.') + }) + + it('turns the generating icon into a stop affordance', () => { + const onCancelGenerate = vi.fn() + const props = baseProps({ hasMessage: false }) + const element = CommitArea({ + ...props, + commitMessage: '', + aiEnabled: true, + aiAgentConfigured: true, + isGenerating: true, + onCancelGenerate + }) + + const button = findNativeButtonByAriaLabel(element, 'Stop generating commit message') + expect(button.props.title).toBe('Stop generating') + ;(button.props.onClick as () => void)() + expect(onCancelGenerate).toHaveBeenCalledTimes(1) + }) + + it('shows generation errors separately from commit errors and links them to the textarea', () => { + const element = CommitArea({ + ...baseProps(), + commitError: null, + generateError: 'No staged changes to summarize.' + }) + + expect(hasText(element, 'No staged changes to summarize.')).toBe(true) + expect(findTextarea(element).props['aria-describedby']).toBe('commit-area-generate-error') + }) + + it('continues to render the split commit button alongside generation controls', () => { + const element = CommitArea({ ...baseProps(), aiEnabled: true, aiAgentConfigured: true }) + let primaryFound = false + visit(element, (entry) => { + if (entry.type === Button) { + primaryFound = true + } + }) + + expect(primaryFound).toBe(true) + }) +}) diff --git a/src/renderer/src/components/right-sidebar/CommitArea.primary-icons.test.tsx b/src/renderer/src/components/right-sidebar/CommitArea.primary-icons.test.tsx index 1ae4ef8fc..4cf98fcef 100644 --- a/src/renderer/src/components/right-sidebar/CommitArea.primary-icons.test.tsx +++ b/src/renderer/src/components/right-sidebar/CommitArea.primary-icons.test.tsx @@ -73,11 +73,19 @@ function baseProps(overrides: Partial = {}) { commitMessage: 'feat: add commit area', commitError: null as string | null, isCommitting: inputs.isCommitting, + aiEnabled: false, + aiAgentConfigured: false, + isGenerating: false, + generateError: null as string | null, + stagedCount: inputs.stagedCount, + hasUnresolvedConflicts: inputs.hasUnresolvedConflicts, isRemoteOperationActive: inputs.isRemoteOperationActive, inFlightRemoteOpKind: inputs.inFlightRemoteOpKind ?? null, primaryAction: resolvePrimaryAction(inputs), dropdownItems: resolveDropdownItems(inputs), onCommitMessageChange: vi.fn(), + onGenerate: vi.fn(), + onCancelGenerate: vi.fn(), onPrimaryAction: vi.fn(), onDropdownAction: vi.fn() as (kind: DropdownActionKind) => void } diff --git a/src/renderer/src/components/right-sidebar/CommitArea.test.tsx b/src/renderer/src/components/right-sidebar/CommitArea.test.tsx index cf4d95bcd..cf37df70c 100644 --- a/src/renderer/src/components/right-sidebar/CommitArea.test.tsx +++ b/src/renderer/src/components/right-sidebar/CommitArea.test.tsx @@ -1,3 +1,6 @@ +/* eslint-disable max-lines -- Why: these CommitArea regression tests share + element-tree helpers that keep the assertions independent from a DOM test + harness; splitting the remaining cases would mostly duplicate setup. */ import { describe, expect, it, vi } from 'vitest' import { Check, RefreshCw } from 'lucide-react' import { CommitArea } from './SourceControl' @@ -123,11 +126,19 @@ function baseProps(overrides: Partial = {}) { commitMessage: 'feat: add commit area', commitError: null as string | null, isCommitting: inputs.isCommitting, + aiEnabled: false, + aiAgentConfigured: false, + isGenerating: false, + generateError: null as string | null, + stagedCount: inputs.stagedCount, + hasUnresolvedConflicts: inputs.hasUnresolvedConflicts, isRemoteOperationActive: inputs.isRemoteOperationActive, inFlightRemoteOpKind: inputs.inFlightRemoteOpKind ?? null, primaryAction: resolvePrimaryAction(inputs), dropdownItems: resolveDropdownItems(inputs), onCommitMessageChange: vi.fn(), + onGenerate: vi.fn(), + onCancelGenerate: vi.fn(), onPrimaryAction: vi.fn(), onDropdownAction: vi.fn() as (kind: DropdownActionKind) => void } diff --git a/src/renderer/src/components/right-sidebar/SourceControl.tsx b/src/renderer/src/components/right-sidebar/SourceControl.tsx index a3aeea40c..296e13dd7 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.tsx @@ -9,6 +9,8 @@ import { Plus, RefreshCw, Settings2, + Sparkles, + Square, Undo2, FileEdit, FileMinus, @@ -338,6 +340,16 @@ function SourceControlInner(): React.JSX.Element { {} ) const isCommitting = commitInFlightByWorktree[activeWorktreeId ?? ''] ?? false + // Why: parallel state to commit. Same per-worktree shape so navigating between + // worktrees mid-generation never silently cancels the in-flight request. + const generateInFlightRef = useRef>({}) + const [generateInFlightByWorktree, setGenerateInFlightByWorktree] = useState< + Record + >({}) + const [generateErrors, setGenerateErrors] = useState>({}) + const isGenerating = generateInFlightByWorktree[activeWorktreeId ?? ''] ?? false + const generateError = generateErrors[activeWorktreeId ?? ''] ?? null + const commitMessageAi = useAppStore((s) => s.settings?.commitMessageAi) const filterInputRef = useRef(null) const commitMessage = readCommitDraftForWorktree(commitDrafts, activeWorktreeId) const commitError = commitErrors[activeWorktreeId ?? ''] ?? null @@ -572,12 +584,19 @@ function SourceControlInner(): React.JSX.Element { setCommitDrafts((prev) => pruneRecord(prev)) setCommitErrors((prev) => pruneRecord(prev)) setCommitInFlightByWorktree((prev) => pruneRecord(prev)) + setGenerateInFlightByWorktree((prev) => pruneRecord(prev)) + setGenerateErrors((prev) => pruneRecord(prev)) // Refs don't need setState β€” mutate in place to drop stale keys. for (const key of Object.keys(commitInFlightRef.current)) { if (!worktreeMap.has(key)) { delete commitInFlightRef.current[key] } } + for (const key of Object.keys(generateInFlightRef.current)) { + if (!worktreeMap.has(key)) { + delete generateInFlightRef.current[key] + } + } }, [worktreeMap]) // Why: the sidebar no longer uses key={activeWorktreeId} to force a full @@ -703,6 +722,92 @@ function SourceControlInner(): React.JSX.Element { worktreePath ]) + const handleGenerate = useCallback(async (): Promise => { + if (!activeWorktreeId || !worktreePath) { + return + } + if (generateInFlightRef.current[activeWorktreeId]) { + return + } + if (!commitMessageAi?.enabled || !commitMessageAi.agentId) { + return + } + + if (commitMessageAi.agentId === 'custom') { + const command = commitMessageAi.customAgentCommand?.trim() ?? '' + if (!command) { + setGenerateErrors((prev) => ({ + ...prev, + [activeWorktreeId]: + 'Custom command is empty. Add one in Settings β†’ Git β†’ AI Commit Messages.' + })) + return + } + } + + generateInFlightRef.current[activeWorktreeId] = true + const connectionId = getConnectionId(activeWorktreeId) ?? undefined + setGenerateInFlightByWorktree((prev) => ({ ...prev, [activeWorktreeId]: true })) + setGenerateErrors((prev) => ({ ...prev, [activeWorktreeId]: null })) + try { + const result = (await window.api.git.generateCommitMessage({ + worktreePath, + connectionId + })) as + | { success: true; message: string; agentLabel?: string } + | { success: false; error: string; canceled?: boolean } + + if (!result.success) { + // Why: cancellation is a deliberate user action, not a failure to + // surface. Clear any prior error and stay quiet. + if (result.canceled) { + setGenerateErrors((prev) => ({ ...prev, [activeWorktreeId]: null })) + return + } + setGenerateErrors((prev) => ({ + ...prev, + [activeWorktreeId]: result.error + })) + return + } + + // Why: race protection β€” the user may have started typing into the + // textarea while the agent was running. In that case we silently drop + // the generated message rather than overwrite their in-progress edits. + setCommitDrafts((prev) => { + const current = prev[activeWorktreeId] + if (current && current.length > 0) { + return prev + } + return writeCommitDraftForWorktree(prev, activeWorktreeId, result.message) + }) + setGenerateErrors((prev) => ({ ...prev, [activeWorktreeId]: null })) + } catch (error) { + setGenerateErrors((prev) => ({ + ...prev, + [activeWorktreeId]: + error instanceof Error ? error.message : 'Failed to generate commit message' + })) + } finally { + setGenerateInFlightByWorktree((prev) => ({ ...prev, [activeWorktreeId]: false })) + generateInFlightRef.current[activeWorktreeId] = false + } + }, [activeWorktreeId, commitMessageAi, worktreePath]) + + const handleCancelGenerate = useCallback((): void => { + if (!activeWorktreeId || !worktreePath) { + return + } + if (!generateInFlightRef.current[activeWorktreeId]) { + return + } + const connectionId = getConnectionId(activeWorktreeId) ?? undefined + // Why: fire-and-forget β€” the in-flight generateCommitMessage promise + // resolves with `{canceled: true}` once the kill propagates, which is + // where the spinner is cleared. Awaiting here would just delay UI feedback. + void window.api.git.cancelGenerateCommitMessage({ worktreePath, connectionId }) + }, [activeWorktreeId, worktreePath]) + // Why: a single dispatcher for every remote-only action the split button or // chevron dropdown can trigger. Keeps the error-swallow pattern in one // place β€” store slices already surface actionable toasts, so additional @@ -1873,6 +1978,20 @@ function SourceControlInner(): React.JSX.Element { commitMessage={commitMessage} commitError={commitError} isCommitting={isCommitting} + aiEnabled={commitMessageAi?.enabled === true} + aiAgentConfigured={ + commitMessageAi?.enabled === true && + commitMessageAi.agentId !== null && + // Why: 'custom' is configured only once the user types a command. + // Without this guard, Generate would spawn an empty command and + // fail with a confusing error. + (commitMessageAi.agentId !== 'custom' || + (commitMessageAi.customAgentCommand ?? '').trim().length > 0) + } + isGenerating={isGenerating} + generateError={generateError} + stagedCount={grouped.staged.length} + hasUnresolvedConflicts={unresolvedConflicts.length > 0} isRemoteOperationActive={isRemoteOperationActive} inFlightRemoteOpKind={inFlightRemoteOpKind} primaryAction={primaryAction} @@ -1885,6 +2004,10 @@ function SourceControlInner(): React.JSX.Element { writeCommitDraftForWorktree(prev, activeWorktreeId, value) ) }} + onGenerate={() => { + void handleGenerate() + }} + onCancelGenerate={handleCancelGenerate} onPrimaryAction={handlePrimaryClick} onDropdownAction={handleActionInvoke} /> @@ -2184,11 +2307,19 @@ type CommitAreaProps = { commitMessage: string commitError: string | null isCommitting: boolean + aiEnabled: boolean + aiAgentConfigured: boolean + isGenerating: boolean + generateError: string | null + stagedCount: number + hasUnresolvedConflicts: boolean isRemoteOperationActive: boolean inFlightRemoteOpKind: RemoteOpKind | null primaryAction: PrimaryAction dropdownItems: DropdownEntry[] onCommitMessageChange: (message: string) => void + onGenerate: () => void + onCancelGenerate: () => void onPrimaryAction: () => void onDropdownAction: (kind: DropdownActionKind) => void } @@ -2197,11 +2328,19 @@ export function CommitArea({ commitMessage, commitError, isCommitting, + aiEnabled, + aiAgentConfigured, + isGenerating, + generateError, + stagedCount, + hasUnresolvedConflicts, isRemoteOperationActive, inFlightRemoteOpKind, primaryAction, dropdownItems, onCommitMessageChange, + onGenerate, + onCancelGenerate, onPrimaryAction, onDropdownAction }: CommitAreaProps): React.JSX.Element { @@ -2239,23 +2378,90 @@ export function CommitArea({ // title attribute carry the meaning for assistive tech. const PrimaryIcon = PRIMARY_ICONS[primaryAction.kind] + const hasMessage = commitMessage.trim().length > 0 + + // Why: only render the Generate button when the user has opted into the + // feature. Mounting a perma-disabled button would leak space and add noise + // for users who never plan to use AI commit messages. + const showGenerate = aiEnabled + let generateDisabledReason: string | undefined + if (isGenerating) { + generateDisabledReason = 'Generating commit message…' + } else if (isCommitting) { + generateDisabledReason = 'Commit in progress…' + } else if (!aiAgentConfigured) { + generateDisabledReason = 'Pick an agent in Settings β†’ AI Commit Messages.' + } else if (stagedCount === 0) { + generateDisabledReason = 'Stage at least one file to generate a message.' + } else if (hasMessage) { + generateDisabledReason = 'Clear the message to regenerate.' + } + const isGenerateDisabled = + !aiAgentConfigured || + isGenerating || + isCommitting || + stagedCount === 0 || + hasMessage || + hasUnresolvedConflicts + return (
-