feat(source-control): AI commit message generation (#1487)
Co-authored-by: Orca <help@stably.ai> Co-authored-by: brennanb2025 <brennankbenson@gmail.com>
This commit is contained in:
co-authored by
Orca
brennanb2025
parent
d4cf116d3f
commit
b030257c3b
@@ -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 <help@stably.ai>'
|
||||
const ORCA_GH_FOOTER = `Made with [Orca](${ORCA_PRODUCT_URL}) 🐋`
|
||||
const SHELL_DOLLAR = '$'
|
||||
const POWERSHELL_TICK = '`'
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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<CommitMessageDraftContext | null> {
|
||||
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
|
||||
|
||||
+12
-2
@@ -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)
|
||||
|
||||
@@ -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 })
|
||||
|
||||
+150
-1
@@ -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<string, string> = {
|
||||
'.pdf': 'application/pdf'
|
||||
}
|
||||
|
||||
export type CommitMessageAgentEnvironmentResolvers = {
|
||||
prepareForCodexLaunch?: () => string | null
|
||||
prepareForClaudeLaunch?: () => Promise<ClaudeRuntimeAuthPreparation>
|
||||
}
|
||||
|
||||
function cloneProcessEnv(): Record<string, string> {
|
||||
const env: Record<string, string> = {}
|
||||
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<string, ChildProcess>()
|
||||
|
||||
// ─── Filesystem ─────────────────────────────────────────
|
||||
@@ -557,6 +619,93 @@ export function registerFilesystemHandlers(store: Store): void {
|
||||
}
|
||||
)
|
||||
|
||||
ipcMain.handle(
|
||||
'git:generateCommitMessage',
|
||||
async (
|
||||
_event,
|
||||
args: {
|
||||
worktreePath: string
|
||||
connectionId?: string
|
||||
}
|
||||
): Promise<GenerateCommitMessageResult> => {
|
||||
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<void> => {
|
||||
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 (
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { IGitProvider } from './types'
|
||||
import type { SshGitProvider } from './ssh-git-provider'
|
||||
|
||||
const sshProviders = new Map<string, IGitProvider>()
|
||||
const sshProviders = new Map<string, SshGitProvider>()
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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<CommitMessageDraftContext | null> {
|
||||
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<RemoteCommitMessageExecResult> {
|
||||
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<void> {
|
||||
// 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,
|
||||
|
||||
@@ -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<GitStatusResult>
|
||||
commit(worktreePath: string, message: string): Promise<{ success: boolean; error?: string }>
|
||||
getStagedCommitContext(worktreePath: string): Promise<CommitMessageDraftContext | null>
|
||||
getDiff(
|
||||
worktreePath: string,
|
||||
filePath: string,
|
||||
|
||||
@@ -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<typeof ChildProcess>()
|
||||
return {
|
||||
...actual,
|
||||
spawn: vi.fn(actual.spawn)
|
||||
}
|
||||
})
|
||||
|
||||
const spawnMock = vi.mocked(spawn)
|
||||
|
||||
function withPlatform<T>(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 <help@stably.ai>',
|
||||
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<string, (value: unknown) => 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<string, (value: unknown) => 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<string, (value: unknown) => 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)
|
||||
})
|
||||
})
|
||||
@@ -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<RemoteCommitMessageExecResult>
|
||||
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<string, () => 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<InternalCommitMessageGenerationResult> {
|
||||
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<CommitMessageGenerationTarget, { kind: 'remote' }>
|
||||
): Promise<InternalCommitMessageGenerationResult> {
|
||||
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<GenerateCommitMessageResult> {
|
||||
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)
|
||||
}
|
||||
@@ -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', () => {
|
||||
|
||||
+25
-6
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -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<void>
|
||||
stage: (args: {
|
||||
worktreePath: string
|
||||
filePath: string
|
||||
|
||||
@@ -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<unknown> => ipcRenderer.invoke('git:generateCommitMessage', args),
|
||||
cancelGenerateCommitMessage: (args: {
|
||||
worktreePath: string
|
||||
connectionId?: string
|
||||
}): Promise<void> => ipcRenderer.invoke('git:cancelGenerateCommitMessage', args),
|
||||
stage: (args: {
|
||||
worktreePath: string
|
||||
filePath: string
|
||||
|
||||
@@ -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<typeof ChildProcess>()
|
||||
return {
|
||||
...actual,
|
||||
exec: vi.fn(),
|
||||
spawn: vi.fn()
|
||||
}
|
||||
})
|
||||
|
||||
const spawnMock = vi.mocked(spawn)
|
||||
const execMock = vi.mocked(exec)
|
||||
|
||||
function withPlatform<T>(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<typeof vi.fn>
|
||||
stdout: EventEmitter
|
||||
stderr: EventEmitter
|
||||
stdin: { end: ReturnType<typeof vi.fn> }
|
||||
}
|
||||
|
||||
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<string, MethodHandler> {
|
||||
const handlers = new Map<string, MethodHandler>()
|
||||
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 })
|
||||
})
|
||||
})
|
||||
@@ -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<string, { child: ChildProcess; markCanceled: () => 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<ExecResult> {
|
||||
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<string, string>)
|
||||
: null
|
||||
const spawnEnv = extraEnv ? { ...process.env, ...extraEnv } : process.env
|
||||
|
||||
return new Promise<ExecResult>((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()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<void> {
|
||||
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
|
||||
|
||||
@@ -85,11 +85,19 @@ function baseProps(overrides: Partial<PrimaryActionInputs> = {}) {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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<string, unknown>
|
||||
}
|
||||
|
||||
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> = {}): 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<PrimaryActionInputs> = {}) {
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -73,11 +73,19 @@ function baseProps(overrides: Partial<PrimaryActionInputs> = {}) {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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<PrimaryActionInputs> = {}) {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -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<Record<string, boolean>>({})
|
||||
const [generateInFlightByWorktree, setGenerateInFlightByWorktree] = useState<
|
||||
Record<string, boolean>
|
||||
>({})
|
||||
const [generateErrors, setGenerateErrors] = useState<Record<string, string | null>>({})
|
||||
const isGenerating = generateInFlightByWorktree[activeWorktreeId ?? ''] ?? false
|
||||
const generateError = generateErrors[activeWorktreeId ?? ''] ?? null
|
||||
const commitMessageAi = useAppStore((s) => s.settings?.commitMessageAi)
|
||||
const filterInputRef = useRef<HTMLInputElement>(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<void> => {
|
||||
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 (
|
||||
<div className="px-3 pb-2">
|
||||
<textarea
|
||||
rows={rows}
|
||||
value={commitMessage}
|
||||
onChange={(e) => onCommitMessageChange(e.target.value)}
|
||||
placeholder="Message"
|
||||
aria-label="Commit message"
|
||||
aria-describedby={commitError ? 'commit-area-error' : undefined}
|
||||
className="mt-0.5 w-full resize-none rounded-md border border-border bg-background px-2 py-1.5 text-xs text-foreground outline-none placeholder:text-muted-foreground/70 focus-visible:ring-1 focus-visible:ring-ring"
|
||||
/>
|
||||
<div className="relative">
|
||||
<textarea
|
||||
rows={rows}
|
||||
value={commitMessage}
|
||||
onChange={(e) => onCommitMessageChange(e.target.value)}
|
||||
placeholder="Message"
|
||||
aria-label="Commit message"
|
||||
aria-describedby={
|
||||
commitError
|
||||
? 'commit-area-error'
|
||||
: generateError
|
||||
? 'commit-area-generate-error'
|
||||
: undefined
|
||||
}
|
||||
// Why: reserve right padding so typed text does not slide under the
|
||||
// absolute-positioned Generate icon in the top-right corner.
|
||||
className={`mt-0.5 w-full resize-none rounded-md border border-border bg-background px-2 py-1.5 text-xs text-foreground outline-none placeholder:text-muted-foreground/70 focus-visible:ring-1 focus-visible:ring-ring ${
|
||||
showGenerate ? 'pr-7' : ''
|
||||
}`}
|
||||
/>
|
||||
{showGenerate &&
|
||||
(isGenerating ? (
|
||||
// Why: while generating the icon doubles as the cancel affordance.
|
||||
// Default state shows the spinning RefreshCw; on hover/focus we
|
||||
// swap to a Square ("stop") with a destructive tint so the user
|
||||
// sees that clicking will abort the run. Group/group-hover toggles
|
||||
// keep this stateless on the React side.
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onCancelGenerate()}
|
||||
title="Stop generating"
|
||||
aria-label="Stop generating commit message"
|
||||
className="group absolute right-1.5 top-1.5 inline-flex size-5 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive focus-visible:bg-destructive/10 focus-visible:text-destructive focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-destructive/40"
|
||||
>
|
||||
<RefreshCw className="size-3.5 animate-spin group-hover:hidden group-focus-visible:hidden" />
|
||||
<Square className="hidden size-3.5 fill-current group-hover:block group-focus-visible:block" />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
disabled={isGenerateDisabled}
|
||||
onClick={() => onGenerate()}
|
||||
title={generateDisabledReason ?? 'Generate commit message with AI'}
|
||||
aria-label="Generate commit message with AI"
|
||||
className="absolute right-1.5 top-1.5 inline-flex size-5 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-transparent disabled:hover:text-muted-foreground"
|
||||
>
|
||||
<Sparkles className="size-3.5" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{/* Why: primary + chevron sit together as a visual split button so the
|
||||
edit → commit → push loop stays in a single vertical band. The
|
||||
chevron exposes the full action surface (fetch, pull, sync,
|
||||
publish, compound commits) without forcing morphing labels to
|
||||
carry every possible intent. */}
|
||||
<div className="flex items-stretch">
|
||||
<div className="mt-1 flex items-stretch">
|
||||
{/* Why: match the "Squash and merge" button in PRActions
|
||||
(size="xs", px-3 text-[11px]) so the sidebar has a consistent
|
||||
action-button shape across Source Control and Checks. The primary
|
||||
@@ -2338,6 +2544,16 @@ export function CommitArea({
|
||||
{commitError}
|
||||
</p>
|
||||
)}
|
||||
{generateError && (
|
||||
<p
|
||||
id="commit-area-generate-error"
|
||||
role="alert"
|
||||
aria-live="polite"
|
||||
className="mt-1 text-[11px] text-destructive"
|
||||
>
|
||||
{generateError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import React from 'react'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import type { GlobalSettings } from '../../../../shared/types'
|
||||
import { useAppStore } from '../../store'
|
||||
import { CommitMessageAiPane } from './CommitMessageAiPane'
|
||||
import { COMMIT_MESSAGE_AI_PANE_SEARCH_ENTRIES } from './commit-message-ai-search'
|
||||
|
||||
function renderPane(settings: GlobalSettings): string {
|
||||
return renderToStaticMarkup(
|
||||
React.createElement(CommitMessageAiPane, {
|
||||
settings,
|
||||
updateSettings: () => {}
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
function buildSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings {
|
||||
return {
|
||||
commitMessageAi: {
|
||||
enabled: false,
|
||||
agentId: null,
|
||||
selectedModelByAgent: {},
|
||||
selectedThinkingByModel: {},
|
||||
customPrompt: '',
|
||||
customAgentCommand: ''
|
||||
},
|
||||
...overrides
|
||||
} as GlobalSettings
|
||||
}
|
||||
|
||||
describe('CommitMessageAiPane', () => {
|
||||
beforeEach(() => {
|
||||
useAppStore.setState({ settingsSearchQuery: '' })
|
||||
})
|
||||
|
||||
it('renders only the opt-in control before the feature is enabled', () => {
|
||||
const markup = renderPane(buildSettings())
|
||||
|
||||
expect(markup).toContain('AI Commit Messages')
|
||||
expect(markup).toContain('Enable AI commit messages')
|
||||
expect(markup).toContain('aria-checked="false"')
|
||||
expect(markup).not.toContain('Which agent drafts your commit messages')
|
||||
expect(markup).not.toContain('Thinking effort')
|
||||
})
|
||||
|
||||
it('renders model, thinking, and prompt controls for enabled preset agents', () => {
|
||||
const markup = renderPane(
|
||||
buildSettings({
|
||||
commitMessageAi: {
|
||||
enabled: true,
|
||||
agentId: 'codex',
|
||||
selectedModelByAgent: { codex: 'gpt-5.5' },
|
||||
selectedThinkingByModel: { 'gpt-5.5': 'medium' },
|
||||
customPrompt: 'Use Conventional Commits.',
|
||||
customAgentCommand: ''
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
expect(markup).toContain('aria-checked="true"')
|
||||
expect(markup).toContain('Which agent drafts your commit messages')
|
||||
expect(markup).toContain('Model')
|
||||
expect(markup).toContain('Thinking effort')
|
||||
expect(markup).toContain('Higher effort produces more careful messages')
|
||||
expect(markup).toContain('Use Conventional Commits.')
|
||||
})
|
||||
|
||||
it('renders custom command settings for custom agents', () => {
|
||||
const markup = renderPane(
|
||||
buildSettings({
|
||||
commitMessageAi: {
|
||||
enabled: true,
|
||||
agentId: 'custom',
|
||||
selectedModelByAgent: {},
|
||||
selectedThinkingByModel: {},
|
||||
customPrompt: '',
|
||||
customAgentCommand: 'ollama run llama3.1 {prompt}'
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
expect(markup).toContain('AI Commit Messages')
|
||||
expect(markup).toContain('Custom command')
|
||||
expect(markup).toContain('ollama run llama3.1 {prompt}')
|
||||
})
|
||||
|
||||
it('keeps custom command discoverable in settings search metadata', () => {
|
||||
const customCommandEntry = COMMIT_MESSAGE_AI_PANE_SEARCH_ENTRIES.find(
|
||||
(entry) => entry.title === 'Custom command'
|
||||
)
|
||||
|
||||
expect(customCommandEntry?.keywords).toEqual(
|
||||
expect.arrayContaining(['custom', 'command', 'ollama'])
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,480 @@
|
||||
/* eslint-disable max-lines -- Why: each agent setting (toggle, agent dropdown,
|
||||
model dropdown, thinking effort dropdown, custom command, custom prompt) is
|
||||
a SearchableSetting block, and splitting the pane across files would scatter
|
||||
the ~6 conditional render branches without making any of them clearer. */
|
||||
import { useMemo } from 'react'
|
||||
import { Terminal } from 'lucide-react'
|
||||
import type { CommitMessageAiSettings, GlobalSettings, TuiAgent } from '../../../../shared/types'
|
||||
import {
|
||||
CUSTOM_AGENT_ID,
|
||||
DEFAULT_COMMIT_MESSAGE_AGENT_ID,
|
||||
getCommitMessageAgentCapability,
|
||||
isCustomAgentId,
|
||||
listCommitMessageAgentCapabilities,
|
||||
type CommitMessageAgentChoice,
|
||||
type CommitMessageAgentCapability,
|
||||
type CommitMessageModelCapability
|
||||
} from '../../../../shared/commit-message-agent-spec'
|
||||
import { CUSTOM_PROMPT_PLACEHOLDER } from '../../../../shared/commit-message-prompt'
|
||||
import { AGENT_CATALOG, AgentIcon } from '@/lib/agent-catalog'
|
||||
import { Label } from '../ui/label'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select'
|
||||
import { useAppStore } from '../../store'
|
||||
import { SearchableSetting } from './SearchableSetting'
|
||||
import { matchesSettingsSearch } from './settings-search'
|
||||
|
||||
type CommitMessageAiPaneProps = {
|
||||
settings: GlobalSettings
|
||||
updateSettings: (updates: Partial<GlobalSettings>) => void
|
||||
}
|
||||
|
||||
const EMPTY_SETTINGS: CommitMessageAiSettings = {
|
||||
enabled: false,
|
||||
agentId: null,
|
||||
selectedModelByAgent: {},
|
||||
selectedThinkingByModel: {},
|
||||
customPrompt: '',
|
||||
customAgentCommand: ''
|
||||
}
|
||||
|
||||
function readSettings(settings: GlobalSettings): CommitMessageAiSettings {
|
||||
return settings.commitMessageAi ?? EMPTY_SETTINGS
|
||||
}
|
||||
|
||||
function agentLabel(agentId: TuiAgent, capability: CommitMessageAgentCapability): string {
|
||||
return AGENT_CATALOG.find((a) => a.id === agentId)?.label ?? capability.label
|
||||
}
|
||||
|
||||
function resolveSelectedModel(
|
||||
config: CommitMessageAiSettings,
|
||||
capability: CommitMessageAgentCapability
|
||||
): CommitMessageModelCapability {
|
||||
const persisted = config.selectedModelByAgent[capability.id]
|
||||
if (persisted) {
|
||||
const found = capability.models.find((m) => m.id === persisted)
|
||||
if (found) {
|
||||
return found
|
||||
}
|
||||
}
|
||||
// Why: defaultModelId is guaranteed to exist in provider capabilities by construction.
|
||||
return capability.models.find((m) => m.id === capability.defaultModelId) ?? capability.models[0]
|
||||
}
|
||||
|
||||
function resolveSelectedThinking(
|
||||
config: CommitMessageAiSettings,
|
||||
model: CommitMessageModelCapability
|
||||
): string | undefined {
|
||||
if (!model.thinkingLevels) {
|
||||
return undefined
|
||||
}
|
||||
const persisted = config.selectedThinkingByModel[model.id]
|
||||
if (persisted && model.thinkingLevels.some((l) => l.id === persisted)) {
|
||||
return persisted
|
||||
}
|
||||
return model.defaultThinkingLevel
|
||||
}
|
||||
|
||||
export function CommitMessageAiPane({
|
||||
settings,
|
||||
updateSettings
|
||||
}: CommitMessageAiPaneProps): React.JSX.Element {
|
||||
const searchQuery = useAppStore((s) => s.settingsSearchQuery)
|
||||
const config = readSettings(settings)
|
||||
|
||||
const agentCapabilities = useMemo(listCommitMessageAgentCapabilities, [])
|
||||
const activeAgentId: CommitMessageAgentChoice = config.agentId ?? DEFAULT_COMMIT_MESSAGE_AGENT_ID
|
||||
const isCustom = isCustomAgentId(activeAgentId)
|
||||
const activeCapability = isCustom ? undefined : getCommitMessageAgentCapability(activeAgentId)
|
||||
const activeModel = activeCapability ? resolveSelectedModel(config, activeCapability) : null
|
||||
const activeThinking = activeModel ? resolveSelectedThinking(config, activeModel) : undefined
|
||||
|
||||
const writeConfig = (patch: Partial<CommitMessageAiSettings>): void => {
|
||||
updateSettings({ commitMessageAi: { ...config, ...patch } })
|
||||
}
|
||||
|
||||
const onToggleEnabled = (): void => {
|
||||
const next = !config.enabled
|
||||
if (!next) {
|
||||
writeConfig({ enabled: false })
|
||||
return
|
||||
}
|
||||
// Why: when the user enables the feature for the first time, hydrate the
|
||||
// agent / model / thinking choices from provider capabilities so the
|
||||
// Generate button works immediately without forcing them to pick first.
|
||||
// If the user previously persisted 'custom', we keep that and let them
|
||||
// re-edit the command — no implicit reset to a preset.
|
||||
const seedAgentId: TuiAgent | 'custom' = config.agentId ?? DEFAULT_COMMIT_MESSAGE_AGENT_ID
|
||||
const seedCapability = isCustomAgentId(seedAgentId)
|
||||
? undefined
|
||||
: getCommitMessageAgentCapability(seedAgentId)
|
||||
const seedModel = seedCapability ? resolveSelectedModel(config, seedCapability) : null
|
||||
const seedThinking = seedModel ? resolveSelectedThinking(config, seedModel) : undefined
|
||||
|
||||
const nextSelectedModelByAgent = { ...config.selectedModelByAgent }
|
||||
if (seedCapability && !nextSelectedModelByAgent[seedCapability.id]) {
|
||||
nextSelectedModelByAgent[seedCapability.id] = seedCapability.defaultModelId
|
||||
}
|
||||
const nextSelectedThinkingByModel = { ...config.selectedThinkingByModel }
|
||||
if (seedModel && seedThinking && !nextSelectedThinkingByModel[seedModel.id]) {
|
||||
nextSelectedThinkingByModel[seedModel.id] = seedThinking
|
||||
}
|
||||
writeConfig({
|
||||
enabled: true,
|
||||
agentId: seedAgentId,
|
||||
selectedModelByAgent: nextSelectedModelByAgent,
|
||||
selectedThinkingByModel: nextSelectedThinkingByModel
|
||||
})
|
||||
}
|
||||
|
||||
const onAgentChange = (newAgentId: string): void => {
|
||||
if (isCustomAgentId(newAgentId)) {
|
||||
writeConfig({ agentId: CUSTOM_AGENT_ID })
|
||||
return
|
||||
}
|
||||
const capability = getCommitMessageAgentCapability(newAgentId as TuiAgent)
|
||||
if (!capability) {
|
||||
return
|
||||
}
|
||||
const nextSelectedModelByAgent = { ...config.selectedModelByAgent }
|
||||
if (!nextSelectedModelByAgent[capability.id]) {
|
||||
nextSelectedModelByAgent[capability.id] = capability.defaultModelId
|
||||
}
|
||||
const newModel = resolveSelectedModel({ ...config, agentId: capability.id }, capability)
|
||||
const nextSelectedThinkingByModel = { ...config.selectedThinkingByModel }
|
||||
if (
|
||||
newModel.thinkingLevels &&
|
||||
newModel.defaultThinkingLevel &&
|
||||
!nextSelectedThinkingByModel[newModel.id]
|
||||
) {
|
||||
nextSelectedThinkingByModel[newModel.id] = newModel.defaultThinkingLevel
|
||||
}
|
||||
writeConfig({
|
||||
agentId: capability.id,
|
||||
selectedModelByAgent: nextSelectedModelByAgent,
|
||||
selectedThinkingByModel: nextSelectedThinkingByModel
|
||||
})
|
||||
}
|
||||
|
||||
const onCustomCommandChange = (value: string): void => {
|
||||
writeConfig({ customAgentCommand: value })
|
||||
}
|
||||
|
||||
const onModelChange = (newModelId: string): void => {
|
||||
if (!activeCapability) {
|
||||
return
|
||||
}
|
||||
const model = activeCapability.models.find((m) => m.id === newModelId)
|
||||
if (!model) {
|
||||
return
|
||||
}
|
||||
const nextSelectedModelByAgent = {
|
||||
...config.selectedModelByAgent,
|
||||
[activeCapability.id]: model.id
|
||||
}
|
||||
const nextSelectedThinkingByModel = { ...config.selectedThinkingByModel }
|
||||
if (
|
||||
model.thinkingLevels &&
|
||||
model.defaultThinkingLevel &&
|
||||
!nextSelectedThinkingByModel[model.id]
|
||||
) {
|
||||
nextSelectedThinkingByModel[model.id] = model.defaultThinkingLevel
|
||||
}
|
||||
writeConfig({
|
||||
selectedModelByAgent: nextSelectedModelByAgent,
|
||||
selectedThinkingByModel: nextSelectedThinkingByModel
|
||||
})
|
||||
}
|
||||
|
||||
const onThinkingChange = (newLevelId: string): void => {
|
||||
if (!activeModel) {
|
||||
return
|
||||
}
|
||||
writeConfig({
|
||||
selectedThinkingByModel: {
|
||||
...config.selectedThinkingByModel,
|
||||
[activeModel.id]: newLevelId
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const onCustomPromptChange = (value: string): void => {
|
||||
writeConfig({ customPrompt: value })
|
||||
}
|
||||
|
||||
const sections: React.ReactNode[] = []
|
||||
|
||||
if (
|
||||
matchesSettingsSearch(searchQuery, {
|
||||
title: 'Enable AI commit messages',
|
||||
description: 'Adds a Generate button to the Source Control panel.',
|
||||
keywords: ['ai', 'commit', 'message', 'generate', 'agent', 'enabled']
|
||||
})
|
||||
) {
|
||||
sections.push(
|
||||
<SearchableSetting
|
||||
key="enabled"
|
||||
title="Enable AI commit messages"
|
||||
description="Adds a Generate button to the Source Control panel."
|
||||
keywords={['ai', 'commit', 'message', 'generate', 'agent', 'enabled']}
|
||||
className="flex items-center justify-between gap-4 px-1 py-2"
|
||||
>
|
||||
<div className="space-y-0.5">
|
||||
<Label>Enable AI commit messages</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Adds a Generate button to the Source Control panel that drafts a commit message from
|
||||
your staged changes. Runs the agent CLI locally (or on the SSH host when working
|
||||
remotely) and waits for the response.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
role="switch"
|
||||
aria-checked={config.enabled}
|
||||
onClick={onToggleEnabled}
|
||||
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent transition-colors ${
|
||||
config.enabled ? 'bg-foreground' : 'bg-muted-foreground/30'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className={`pointer-events-none block size-3.5 rounded-full bg-background shadow-sm transition-transform ${
|
||||
config.enabled ? 'translate-x-4' : 'translate-x-0.5'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
</SearchableSetting>
|
||||
)
|
||||
}
|
||||
|
||||
if (
|
||||
config.enabled &&
|
||||
matchesSettingsSearch(searchQuery, {
|
||||
title: 'Agent',
|
||||
description: 'Which agent to invoke when generating a commit message.',
|
||||
keywords: ['agent', 'claude', 'codex']
|
||||
})
|
||||
) {
|
||||
sections.push(
|
||||
<SearchableSetting
|
||||
key="agent"
|
||||
title="Agent"
|
||||
description="Which agent to invoke when generating a commit message."
|
||||
keywords={['agent', 'claude', 'codex']}
|
||||
className="flex items-center justify-between gap-4 px-1 py-2"
|
||||
>
|
||||
<div className="space-y-0.5">
|
||||
<Label>Agent</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Which agent drafts your commit messages. Orca invokes its CLI in the background, so the
|
||||
agent must be installed on the machine that hosts the worktree - your computer for local
|
||||
worktrees, or the SSH host for remote ones.
|
||||
</p>
|
||||
</div>
|
||||
<Select value={activeAgentId} onValueChange={onAgentChange}>
|
||||
<SelectTrigger size="sm" className="h-8 text-xs w-[180px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{agentCapabilities.map((capability) => {
|
||||
const id = capability.id
|
||||
return (
|
||||
<SelectItem key={id} value={id} className="cursor-pointer">
|
||||
<span className="flex items-center gap-2">
|
||||
<AgentIcon agent={id} size={14} />
|
||||
<span>{agentLabel(id, capability)}</span>
|
||||
</span>
|
||||
</SelectItem>
|
||||
)
|
||||
})}
|
||||
<SelectItem value={CUSTOM_AGENT_ID} className="cursor-pointer">
|
||||
<span className="flex items-center gap-2">
|
||||
<Terminal className="size-3.5" />
|
||||
<span>Custom</span>
|
||||
</span>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SearchableSetting>
|
||||
)
|
||||
}
|
||||
|
||||
if (
|
||||
config.enabled &&
|
||||
isCustom &&
|
||||
matchesSettingsSearch(searchQuery, {
|
||||
title: 'Custom command',
|
||||
description: 'Command line Orca runs to generate the commit message.',
|
||||
keywords: ['custom', 'command', 'cli', 'binary', 'prompt', 'placeholder']
|
||||
})
|
||||
) {
|
||||
sections.push(
|
||||
<SearchableSetting
|
||||
key="custom-command"
|
||||
title="Custom command"
|
||||
description="Command line Orca runs to generate the commit message."
|
||||
keywords={['custom', 'command', 'cli', 'binary', 'prompt', 'placeholder']}
|
||||
className="space-y-2 px-1 py-2"
|
||||
>
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="commit-message-ai-custom-command">Custom command</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Use{' '}
|
||||
<code className="rounded bg-muted/60 px-1 py-0.5 text-[10px]">
|
||||
{CUSTOM_PROMPT_PLACEHOLDER}
|
||||
</code>{' '}
|
||||
where the prompt should be substituted (passed as a single argument). Omit it and the
|
||||
prompt is piped via stdin instead - useful for CLIs like{' '}
|
||||
<code className="rounded bg-muted/60 px-1 py-0.5 text-[10px]">claude -p</code>. Quoting
|
||||
is for grouping arguments only; we never invoke a shell, so{' '}
|
||||
<code className="rounded bg-muted/60 px-1 py-0.5 text-[10px]">$VAR</code> and backticks
|
||||
are not expanded.
|
||||
</p>
|
||||
</div>
|
||||
<input
|
||||
id="commit-message-ai-custom-command"
|
||||
type="text"
|
||||
spellCheck={false}
|
||||
autoCorrect="off"
|
||||
autoCapitalize="off"
|
||||
value={config.customAgentCommand}
|
||||
onChange={(e) => onCustomCommandChange(e.target.value)}
|
||||
placeholder={`e.g. ollama run llama3.1 ${CUSTOM_PROMPT_PLACEHOLDER}`}
|
||||
className="w-full rounded-md border border-border bg-background px-2 py-1.5 font-mono text-xs text-foreground outline-none placeholder:text-muted-foreground/70 focus-visible:ring-1 focus-visible:ring-ring"
|
||||
/>
|
||||
</SearchableSetting>
|
||||
)
|
||||
}
|
||||
|
||||
if (
|
||||
config.enabled &&
|
||||
activeCapability &&
|
||||
activeModel &&
|
||||
matchesSettingsSearch(searchQuery, {
|
||||
title: 'Model',
|
||||
description: 'Which model the selected agent uses to generate the message.',
|
||||
keywords: ['model', 'haiku', 'sonnet', 'opus', 'gpt']
|
||||
})
|
||||
) {
|
||||
sections.push(
|
||||
<SearchableSetting
|
||||
key="model"
|
||||
title="Model"
|
||||
description="Which model the selected agent uses to generate the message."
|
||||
keywords={['model', 'haiku', 'sonnet', 'opus', 'gpt']}
|
||||
className="flex items-center justify-between gap-4 px-1 py-2"
|
||||
>
|
||||
<div className="space-y-0.5">
|
||||
<Label>Model</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Smaller models default to lower latency and cost. Pick a larger one if the diffs you
|
||||
review tend to need more reasoning.
|
||||
</p>
|
||||
</div>
|
||||
<Select value={activeModel.id} onValueChange={onModelChange}>
|
||||
<SelectTrigger size="sm" className="h-8 text-xs w-[200px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{activeCapability.models.map((m) => (
|
||||
<SelectItem key={m.id} value={m.id} className="cursor-pointer">
|
||||
{m.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SearchableSetting>
|
||||
)
|
||||
}
|
||||
|
||||
if (
|
||||
config.enabled &&
|
||||
activeModel?.thinkingLevels &&
|
||||
activeThinking &&
|
||||
matchesSettingsSearch(searchQuery, {
|
||||
title: 'Thinking effort',
|
||||
description: 'Reasoning effort level for the selected model. Higher levels are slower.',
|
||||
keywords: ['thinking', 'effort', 'reasoning']
|
||||
})
|
||||
) {
|
||||
sections.push(
|
||||
<SearchableSetting
|
||||
key="thinking"
|
||||
title="Thinking effort"
|
||||
description="Reasoning effort level for the selected model. Higher levels are slower."
|
||||
keywords={['thinking', 'effort', 'reasoning']}
|
||||
className="flex items-center justify-between gap-4 px-1 py-2"
|
||||
>
|
||||
<div className="space-y-0.5">
|
||||
<Label>Thinking effort</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Higher effort produces more careful messages but takes longer and costs more tokens.
|
||||
</p>
|
||||
</div>
|
||||
<Select value={activeThinking} onValueChange={onThinkingChange}>
|
||||
<SelectTrigger size="sm" className="h-8 text-xs w-[160px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{activeModel.thinkingLevels.map((level) => (
|
||||
<SelectItem key={level.id} value={level.id} className="cursor-pointer">
|
||||
{level.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SearchableSetting>
|
||||
)
|
||||
}
|
||||
|
||||
if (
|
||||
config.enabled &&
|
||||
matchesSettingsSearch(searchQuery, {
|
||||
title: 'Custom prompt',
|
||||
description:
|
||||
'Optional instructions appended to the base prompt (e.g. Conventional Commits style).',
|
||||
keywords: ['prompt', 'conventional commits', 'gitmoji', 'style']
|
||||
})
|
||||
) {
|
||||
sections.push(
|
||||
<SearchableSetting
|
||||
key="custom-prompt"
|
||||
title="Custom prompt"
|
||||
description="Optional instructions appended to the base prompt (e.g. Conventional Commits style)."
|
||||
keywords={['prompt', 'conventional commits', 'gitmoji', 'style']}
|
||||
className="space-y-2 px-1 py-2"
|
||||
>
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="commit-message-ai-custom-prompt">Custom prompt</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Appended verbatim to the base prompt. Use it to enforce Conventional Commits, gitmoji,
|
||||
ticket prefixes, or any other style your team prefers.
|
||||
</p>
|
||||
</div>
|
||||
<textarea
|
||||
id="commit-message-ai-custom-prompt"
|
||||
rows={4}
|
||||
value={config.customPrompt}
|
||||
onChange={(e) => onCustomPromptChange(e.target.value)}
|
||||
placeholder="Use Conventional Commits format (feat:, fix:, ...). Reference the ticket key when present."
|
||||
className="w-full resize-y rounded-md border border-border bg-background px-2 py-1.5 text-xs text-foreground outline-none placeholder:text-muted-foreground/70 focus-visible:ring-1 focus-visible:ring-ring"
|
||||
/>
|
||||
</SearchableSetting>
|
||||
)
|
||||
}
|
||||
|
||||
if (sections.length === 0) {
|
||||
return <div className="space-y-4" />
|
||||
}
|
||||
// Why: this pane lives nested inside the Git section, so we draw an explicit
|
||||
// sub-heading + top border to keep its toggles visually distinct from the
|
||||
// Branch Prefix / Refresh Local Base Ref / Orca Attribution rows above.
|
||||
return (
|
||||
<div className="space-y-4 border-t border-border/40 pt-4">
|
||||
<div className="space-y-0.5">
|
||||
<h3 className="text-sm font-semibold">AI Commit Messages</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Generate commit messages from staged changes using a local agent CLI.
|
||||
</p>
|
||||
</div>
|
||||
{sections}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -43,6 +43,8 @@ import ghosttyIcon from '../../../../../resources/ghostty.svg'
|
||||
import { RepositoryPane, getRepositoryPaneSearchEntries } from './RepositoryPane'
|
||||
import { getTerminalPaneSearchEntries } from './terminal-search'
|
||||
import { GitPane, GIT_PANE_SEARCH_ENTRIES } from './GitPane'
|
||||
import { CommitMessageAiPane } from './CommitMessageAiPane'
|
||||
import { COMMIT_MESSAGE_AI_PANE_SEARCH_ENTRIES } from './commit-message-ai-search'
|
||||
import { NotificationsPane, NOTIFICATIONS_PANE_SEARCH_ENTRIES } from './NotificationsPane'
|
||||
import { VoicePane } from './VoicePane'
|
||||
import { VOICE_PANE_SEARCH_ENTRIES } from './voice-pane-search'
|
||||
@@ -424,9 +426,12 @@ function Settings(): React.JSX.Element {
|
||||
{
|
||||
id: 'git',
|
||||
title: 'Git',
|
||||
description: 'Branch naming and local ref behavior.',
|
||||
description: 'Branch naming, local ref behavior, and AI commit messages.',
|
||||
icon: GitBranch,
|
||||
searchEntries: GIT_PANE_SEARCH_ENTRIES
|
||||
// Why: the AI commit messages pane is rendered inside the Git section,
|
||||
// so its search entries belong to Git too — that way a query like
|
||||
// "claude" or "thinking" still surfaces the section.
|
||||
searchEntries: [...GIT_PANE_SEARCH_ENTRIES, ...COMMIT_MESSAGE_AI_PANE_SEARCH_ENTRIES]
|
||||
},
|
||||
{
|
||||
id: 'appearance',
|
||||
@@ -759,14 +764,18 @@ function Settings(): React.JSX.Element {
|
||||
<SettingsSection
|
||||
id="git"
|
||||
title="Git"
|
||||
description="Branch naming and local ref behavior."
|
||||
searchEntries={GIT_PANE_SEARCH_ENTRIES}
|
||||
description="Branch naming, local ref behavior, and AI commit messages."
|
||||
searchEntries={[
|
||||
...GIT_PANE_SEARCH_ENTRIES,
|
||||
...COMMIT_MESSAGE_AI_PANE_SEARCH_ENTRIES
|
||||
]}
|
||||
>
|
||||
<GitPane
|
||||
settings={settings}
|
||||
updateSettings={updateSettings}
|
||||
displayedGitUsername={displayedGitUsername}
|
||||
/>
|
||||
<CommitMessageAiPane settings={settings} updateSettings={updateSettings} />
|
||||
</SettingsSection>
|
||||
|
||||
<SettingsSection
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { SettingsSearchEntry } from './settings-search'
|
||||
|
||||
export const COMMIT_MESSAGE_AI_PANE_SEARCH_ENTRIES: SettingsSearchEntry[] = [
|
||||
{
|
||||
title: 'Enable AI commit messages',
|
||||
description: 'Adds a Generate button to the Source Control panel.',
|
||||
keywords: [
|
||||
'ai',
|
||||
'commit',
|
||||
'message',
|
||||
'generate',
|
||||
'agent',
|
||||
'claude',
|
||||
'codex',
|
||||
'source control',
|
||||
'enabled'
|
||||
]
|
||||
},
|
||||
{
|
||||
title: 'Agent',
|
||||
description: 'Which agent to invoke when generating a commit message.',
|
||||
keywords: ['agent', 'claude', 'codex']
|
||||
},
|
||||
{
|
||||
title: 'Model',
|
||||
description: 'Which model the selected agent uses to generate the message.',
|
||||
keywords: ['model', 'haiku', 'sonnet', 'opus', 'gpt']
|
||||
},
|
||||
{
|
||||
title: 'Thinking effort',
|
||||
description: 'Reasoning effort level for the selected model. Higher levels are slower.',
|
||||
keywords: ['thinking', 'effort', 'reasoning']
|
||||
},
|
||||
{
|
||||
title: 'Custom prompt',
|
||||
description:
|
||||
'Optional instructions appended to the base prompt (e.g. Conventional Commits style).',
|
||||
keywords: ['prompt', 'conventional commits', 'gitmoji', 'style']
|
||||
},
|
||||
{
|
||||
title: 'Custom command',
|
||||
description: 'Command line Orca runs to generate the commit message.',
|
||||
keywords: ['custom', 'command', 'cli', 'binary', 'prompt', 'placeholder', 'ollama']
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,165 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
COMMIT_MESSAGE_AGENT_SPECS,
|
||||
CUSTOM_AGENT_ID,
|
||||
DEFAULT_COMMIT_MESSAGE_AGENT_ID,
|
||||
getCommitMessageAgentCapability,
|
||||
getCommitMessageAgentSpec,
|
||||
getCommitMessageModelCapability,
|
||||
getCommitMessageModel,
|
||||
isCustomAgentId,
|
||||
listCommitMessageAgentCapabilities,
|
||||
listCommitMessageAgentIds
|
||||
} from './commit-message-agent-spec'
|
||||
|
||||
describe('COMMIT_MESSAGE_AGENT_SPECS', () => {
|
||||
it('exposes Claude and Codex as the v1 agents', () => {
|
||||
const ids = listCommitMessageAgentIds().sort()
|
||||
expect(ids).toEqual(['claude', 'codex'])
|
||||
})
|
||||
|
||||
it('uses the smallest model as the default for each agent', () => {
|
||||
expect(COMMIT_MESSAGE_AGENT_SPECS.claude?.defaultModelId).toBe('claude-haiku-4-5')
|
||||
expect(COMMIT_MESSAGE_AGENT_SPECS.codex?.defaultModelId).toBe('gpt-5.4-mini')
|
||||
})
|
||||
|
||||
it('defaults the agent picker to Claude', () => {
|
||||
expect(DEFAULT_COMMIT_MESSAGE_AGENT_ID).toBe('claude')
|
||||
})
|
||||
|
||||
it('defaults every model with thinking levels to "low"', () => {
|
||||
for (const spec of Object.values(COMMIT_MESSAGE_AGENT_SPECS)) {
|
||||
if (!spec) {
|
||||
continue
|
||||
}
|
||||
for (const model of spec.models) {
|
||||
if (model.thinkingLevels) {
|
||||
expect(model.defaultThinkingLevel).toBe('low')
|
||||
expect(model.thinkingLevels.some((l) => l.id === 'low')).toBe(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('exposes thinking levels on the Spark variant (it accepts model_reasoning_effort)', () => {
|
||||
const spark = getCommitMessageModel('codex', 'gpt-5.3-codex-spark')
|
||||
expect(spark).toBeDefined()
|
||||
expect(spark?.thinkingLevels?.map((l) => l.id)).toEqual(['low', 'medium', 'high', 'xhigh'])
|
||||
expect(spark?.defaultThinkingLevel).toBe('low')
|
||||
})
|
||||
|
||||
it('omits thinking levels on Claude Haiku 4.5 (non-reasoning model)', () => {
|
||||
const haiku = getCommitMessageModel('claude', 'claude-haiku-4-5')
|
||||
expect(haiku).toBeDefined()
|
||||
expect(haiku?.thinkingLevels).toBeUndefined()
|
||||
expect(haiku?.defaultThinkingLevel).toBeUndefined()
|
||||
})
|
||||
|
||||
it('identifies the custom sentinel via isCustomAgentId', () => {
|
||||
expect(isCustomAgentId(CUSTOM_AGENT_ID)).toBe(true)
|
||||
expect(isCustomAgentId('claude')).toBe(false)
|
||||
expect(isCustomAgentId('codex')).toBe(false)
|
||||
expect(isCustomAgentId(null)).toBe(false)
|
||||
expect(isCustomAgentId(undefined)).toBe(false)
|
||||
})
|
||||
|
||||
it('does not list "custom" alongside preset agent ids', () => {
|
||||
expect(listCommitMessageAgentIds()).not.toContain(CUSTOM_AGENT_ID)
|
||||
})
|
||||
|
||||
it('orders Codex models by version descending to match the official picker', () => {
|
||||
const ids = COMMIT_MESSAGE_AGENT_SPECS.codex?.models.map((m) => m.id)
|
||||
expect(ids).toEqual([
|
||||
'gpt-5.5',
|
||||
'gpt-5.4',
|
||||
'gpt-5.4-mini',
|
||||
'gpt-5.3-codex',
|
||||
'gpt-5.3-codex-spark',
|
||||
'gpt-5.2'
|
||||
])
|
||||
})
|
||||
|
||||
it('exposes UI capabilities without spawn details', () => {
|
||||
const capabilities = listCommitMessageAgentCapabilities()
|
||||
expect(capabilities.map((capability) => capability.id).sort()).toEqual(['claude', 'codex'])
|
||||
const codex = getCommitMessageAgentCapability('codex')
|
||||
expect(codex).toMatchObject({
|
||||
id: 'codex',
|
||||
label: 'Codex',
|
||||
defaultModelId: 'gpt-5.4-mini'
|
||||
})
|
||||
expect(codex).not.toHaveProperty('binary')
|
||||
expect(codex).not.toHaveProperty('buildArgs')
|
||||
expect(getCommitMessageModelCapability('codex', 'gpt-5.4-mini')?.thinkingLevels).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildArgs (Claude)', () => {
|
||||
const spec = getCommitMessageAgentSpec('claude')!
|
||||
|
||||
it('passes -p, output format, and model on every call', () => {
|
||||
const args = spec.buildArgs({ prompt: '', model: 'claude-haiku-4-5' })
|
||||
expect(args).toEqual(['-p', '--output-format', 'text', '--model', 'claude-haiku-4-5'])
|
||||
})
|
||||
|
||||
it('appends --effort when a thinking level is supplied', () => {
|
||||
const args = spec.buildArgs({
|
||||
prompt: '',
|
||||
model: 'claude-sonnet-4-6',
|
||||
thinkingLevel: 'high'
|
||||
})
|
||||
expect(args).toEqual([
|
||||
'-p',
|
||||
'--output-format',
|
||||
'text',
|
||||
'--model',
|
||||
'claude-sonnet-4-6',
|
||||
'--effort',
|
||||
'high'
|
||||
])
|
||||
})
|
||||
|
||||
it('omits --effort when thinkingLevel is not provided', () => {
|
||||
const args = spec.buildArgs({ prompt: '', model: 'claude-opus-4-7' })
|
||||
expect(args).not.toContain('--effort')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildArgs (Codex)', () => {
|
||||
const spec = getCommitMessageAgentSpec('codex')!
|
||||
|
||||
it('runs `codex exec` without passing the prompt via argv', () => {
|
||||
const args = spec.buildArgs({
|
||||
prompt: 'PROMPT',
|
||||
model: 'gpt-5.4-mini'
|
||||
})
|
||||
expect(args[0]).toBe('exec')
|
||||
expect(args).toEqual([
|
||||
'exec',
|
||||
'--ephemeral',
|
||||
'--skip-git-repo-check',
|
||||
'-s',
|
||||
'read-only',
|
||||
'--model',
|
||||
'gpt-5.4-mini'
|
||||
])
|
||||
expect(args).toContain('--model')
|
||||
expect(args).not.toContain('PROMPT')
|
||||
expect(spec.promptDelivery).toBe('stdin')
|
||||
})
|
||||
|
||||
it('emits -c model_reasoning_effort=<level> when thinking level is supplied', () => {
|
||||
const args = spec.buildArgs({
|
||||
prompt: 'PROMPT',
|
||||
model: 'gpt-5.4',
|
||||
thinkingLevel: 'medium'
|
||||
})
|
||||
expect(args).toContain('-c')
|
||||
expect(args).toContain('model_reasoning_effort=medium')
|
||||
})
|
||||
|
||||
it('omits the -c flag when no thinking level is supplied', () => {
|
||||
const args = spec.buildArgs({ prompt: 'PROMPT', model: 'gpt-5.4-mini' })
|
||||
expect(args).not.toContain('-c')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,266 @@
|
||||
import type { TuiAgent } from './types'
|
||||
|
||||
// Why: this file is the source of truth for non-interactive agent invocation
|
||||
// (commit-message generation). It is intentionally separate from
|
||||
// `tui-agent-config.ts`, which describes interactive PTY launching — mixing
|
||||
// the two confuses both code paths.
|
||||
|
||||
export type ThinkingLevel = { id: string; label: string }
|
||||
|
||||
export type CommitMessageModel = {
|
||||
/** Value passed to the agent CLI's --model flag. */
|
||||
id: string
|
||||
/** Visible label in the model dropdown. */
|
||||
label: string
|
||||
/** Omit when the model does not expose an effort selector — the UI then hides the dropdown. */
|
||||
thinkingLevels?: ThinkingLevel[]
|
||||
/** Required when thinkingLevels is present. */
|
||||
defaultThinkingLevel?: string
|
||||
}
|
||||
|
||||
export type CommitMessageAgentSpec = {
|
||||
id: TuiAgent
|
||||
/** Visible label in the agent dropdown. */
|
||||
label: string
|
||||
/** Binary spawned in non-interactive mode. */
|
||||
binary: string
|
||||
/** Where the prompt is delivered. Large diffs go via stdin to avoid argv limits. */
|
||||
promptDelivery: 'argv' | 'stdin'
|
||||
buildArgs: (params: { prompt: string; model: string; thinkingLevel?: string }) => string[]
|
||||
models: CommitMessageModel[]
|
||||
defaultModelId: string
|
||||
}
|
||||
|
||||
export type CommitMessageModelCapability = {
|
||||
id: string
|
||||
label: string
|
||||
thinkingLevels?: ThinkingLevel[]
|
||||
defaultThinkingLevel?: string
|
||||
}
|
||||
|
||||
export type CommitMessageAgentCapability = {
|
||||
id: TuiAgent
|
||||
label: string
|
||||
models: CommitMessageModelCapability[]
|
||||
defaultModelId: string
|
||||
}
|
||||
|
||||
export const COMMIT_MESSAGE_AGENT_SPECS: Partial<Record<TuiAgent, CommitMessageAgentSpec>> = {
|
||||
claude: {
|
||||
id: 'claude',
|
||||
label: 'Claude',
|
||||
binary: 'claude',
|
||||
// Why: diffs can be large and `claude -p` reads from stdin natively when no
|
||||
// positional prompt is provided.
|
||||
promptDelivery: 'stdin',
|
||||
buildArgs: ({ model, thinkingLevel }) => [
|
||||
'-p',
|
||||
'--output-format',
|
||||
'text',
|
||||
'--model',
|
||||
model,
|
||||
...(thinkingLevel ? ['--effort', thinkingLevel] : [])
|
||||
],
|
||||
models: [
|
||||
{
|
||||
// Why: Haiku 4.5 is a non-reasoning model — `claude --effort` rejects
|
||||
// any value for it. Omit thinkingLevels so the UI hides the dropdown
|
||||
// and the buildArgs path skips passing --effort entirely.
|
||||
id: 'claude-haiku-4-5',
|
||||
label: 'Haiku 4.5'
|
||||
},
|
||||
{
|
||||
id: 'claude-sonnet-4-6',
|
||||
label: 'Sonnet 4.6',
|
||||
thinkingLevels: [
|
||||
{ id: 'low', label: 'Low' },
|
||||
{ id: 'medium', label: 'Medium' },
|
||||
{ id: 'high', label: 'High' },
|
||||
{ id: 'xhigh', label: 'Extra High' },
|
||||
{ id: 'max', label: 'Max' }
|
||||
],
|
||||
defaultThinkingLevel: 'low'
|
||||
},
|
||||
{
|
||||
id: 'claude-opus-4-7',
|
||||
label: 'Opus 4.7',
|
||||
thinkingLevels: [
|
||||
{ id: 'low', label: 'Low' },
|
||||
{ id: 'medium', label: 'Medium' },
|
||||
{ id: 'high', label: 'High' },
|
||||
{ id: 'xhigh', label: 'Extra High' },
|
||||
{ id: 'max', label: 'Max' }
|
||||
],
|
||||
defaultThinkingLevel: 'low'
|
||||
}
|
||||
],
|
||||
defaultModelId: 'claude-haiku-4-5'
|
||||
},
|
||||
codex: {
|
||||
id: 'codex',
|
||||
label: 'Codex',
|
||||
binary: 'codex',
|
||||
// Why: `codex exec` reads stdin when no prompt arg is supplied. Commit
|
||||
// prompts include large staged diffs, so argv would exceed Windows and
|
||||
// some SSH/POSIX command-line limits.
|
||||
promptDelivery: 'stdin',
|
||||
buildArgs: ({ model, thinkingLevel }) => [
|
||||
'exec',
|
||||
// Why: commit-message generation needs text only, not a persisted agent
|
||||
// session or workspace writes. Match T3 Code's safe git-text mode.
|
||||
'--ephemeral',
|
||||
'--skip-git-repo-check',
|
||||
'-s',
|
||||
'read-only',
|
||||
'--model',
|
||||
model,
|
||||
...(thinkingLevel ? ['-c', `model_reasoning_effort=${thinkingLevel}`] : [])
|
||||
],
|
||||
// Why: ordered to match the official `codex` model picker — descending
|
||||
// by version so the frontier model lands on top and legacy models trail.
|
||||
// Default still resolves by id (`gpt-5.4-mini`), independent of order.
|
||||
models: [
|
||||
{
|
||||
id: 'gpt-5.5',
|
||||
label: 'GPT-5.5',
|
||||
thinkingLevels: [
|
||||
{ id: 'low', label: 'Low' },
|
||||
{ id: 'medium', label: 'Medium' },
|
||||
{ id: 'high', label: 'High' },
|
||||
{ id: 'xhigh', label: 'Extra High' }
|
||||
],
|
||||
defaultThinkingLevel: 'low'
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.4',
|
||||
label: 'GPT-5.4',
|
||||
thinkingLevels: [
|
||||
{ id: 'low', label: 'Low' },
|
||||
{ id: 'medium', label: 'Medium' },
|
||||
{ id: 'high', label: 'High' },
|
||||
{ id: 'xhigh', label: 'Extra High' }
|
||||
],
|
||||
defaultThinkingLevel: 'low'
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.4-mini',
|
||||
label: 'GPT-5.4 Mini',
|
||||
thinkingLevels: [
|
||||
{ id: 'low', label: 'Low' },
|
||||
{ id: 'medium', label: 'Medium' },
|
||||
{ id: 'high', label: 'High' },
|
||||
{ id: 'xhigh', label: 'Extra High' }
|
||||
],
|
||||
defaultThinkingLevel: 'low'
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.3-codex',
|
||||
label: 'GPT-5.3 Codex',
|
||||
thinkingLevels: [
|
||||
{ id: 'low', label: 'Low' },
|
||||
{ id: 'medium', label: 'Medium' },
|
||||
{ id: 'high', label: 'High' },
|
||||
{ id: 'xhigh', label: 'Extra High' }
|
||||
],
|
||||
defaultThinkingLevel: 'low'
|
||||
},
|
||||
{
|
||||
// Why: Codex's Spark variant accepts `model_reasoning_effort` (the
|
||||
// CLI banner reports "reasoning effort: medium" by default); the
|
||||
// gating that surfaces "model not supported" is on the account
|
||||
// tier, not the effort flag.
|
||||
id: 'gpt-5.3-codex-spark',
|
||||
label: 'GPT-5.3 Codex Spark',
|
||||
thinkingLevels: [
|
||||
{ id: 'low', label: 'Low' },
|
||||
{ id: 'medium', label: 'Medium' },
|
||||
{ id: 'high', label: 'High' },
|
||||
{ id: 'xhigh', label: 'Extra High' }
|
||||
],
|
||||
defaultThinkingLevel: 'low'
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.2',
|
||||
label: 'GPT-5.2',
|
||||
thinkingLevels: [
|
||||
{ id: 'low', label: 'Low' },
|
||||
{ id: 'medium', label: 'Medium' },
|
||||
{ id: 'high', label: 'High' },
|
||||
{ id: 'xhigh', label: 'Extra High' }
|
||||
],
|
||||
defaultThinkingLevel: 'low'
|
||||
}
|
||||
],
|
||||
defaultModelId: 'gpt-5.4-mini'
|
||||
}
|
||||
}
|
||||
|
||||
export const DEFAULT_COMMIT_MESSAGE_AGENT_ID: TuiAgent = 'claude'
|
||||
|
||||
// Why: the "custom" choice is not a TuiAgent — it lets the user point Orca
|
||||
// at any CLI by typing a command template (see customAgentCommand setting +
|
||||
// planCustomCommand in commit-message-prompt.ts). Keeping it as its own
|
||||
// sentinel avoids polluting TuiAgent (which is shared with PTY launch /
|
||||
// new-workspace flows that have nothing to do with this feature).
|
||||
export const CUSTOM_AGENT_ID = 'custom' as const
|
||||
export type CustomAgentId = typeof CUSTOM_AGENT_ID
|
||||
export type CommitMessageAgentChoice = TuiAgent | CustomAgentId
|
||||
|
||||
export function isCustomAgentId(id: string | null | undefined): id is CustomAgentId {
|
||||
return id === CUSTOM_AGENT_ID
|
||||
}
|
||||
|
||||
export function getCommitMessageAgentSpec(agentId: TuiAgent): CommitMessageAgentSpec | undefined {
|
||||
return COMMIT_MESSAGE_AGENT_SPECS[agentId]
|
||||
}
|
||||
|
||||
export function getCommitMessageModel(
|
||||
agentId: TuiAgent,
|
||||
modelId: string
|
||||
): CommitMessageModel | undefined {
|
||||
return getCommitMessageAgentSpec(agentId)?.models.find((m) => m.id === modelId)
|
||||
}
|
||||
|
||||
function toCommitMessageAgentCapability(
|
||||
spec: CommitMessageAgentSpec
|
||||
): CommitMessageAgentCapability {
|
||||
return {
|
||||
id: spec.id,
|
||||
label: spec.label,
|
||||
defaultModelId: spec.defaultModelId,
|
||||
// Why: renderer/settings should consume provider capabilities, not the
|
||||
// spawn contract. Copy the model metadata so future dynamic probes can
|
||||
// swap this source without leaking binary/argv details into UI code.
|
||||
models: spec.models.map((model) => ({
|
||||
id: model.id,
|
||||
label: model.label,
|
||||
...(model.thinkingLevels ? { thinkingLevels: [...model.thinkingLevels] } : {}),
|
||||
...(model.defaultThinkingLevel ? { defaultThinkingLevel: model.defaultThinkingLevel } : {})
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
export function getCommitMessageAgentCapability(
|
||||
agentId: TuiAgent
|
||||
): CommitMessageAgentCapability | undefined {
|
||||
const spec = getCommitMessageAgentSpec(agentId)
|
||||
return spec ? toCommitMessageAgentCapability(spec) : undefined
|
||||
}
|
||||
|
||||
export function getCommitMessageModelCapability(
|
||||
agentId: TuiAgent,
|
||||
modelId: string
|
||||
): CommitMessageModelCapability | undefined {
|
||||
return getCommitMessageAgentCapability(agentId)?.models.find((m) => m.id === modelId)
|
||||
}
|
||||
|
||||
/** Ordered list of agents that have a non-interactive mode wired up. */
|
||||
export function listCommitMessageAgentIds(): TuiAgent[] {
|
||||
return Object.keys(COMMIT_MESSAGE_AGENT_SPECS) as TuiAgent[]
|
||||
}
|
||||
|
||||
export function listCommitMessageAgentCapabilities(): CommitMessageAgentCapability[] {
|
||||
return listCommitMessageAgentIds()
|
||||
.map((id) => getCommitMessageAgentCapability(id))
|
||||
.filter((capability): capability is CommitMessageAgentCapability => Boolean(capability))
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildCommitMessagePrompt, splitGeneratedCommitMessage } from './commit-message-generation'
|
||||
|
||||
describe('buildCommitMessagePrompt', () => {
|
||||
it('builds a prompt from staged context instead of asking the agent to inspect git', () => {
|
||||
const prompt = buildCommitMessagePrompt(
|
||||
{
|
||||
branch: 'feature/commit-drafts',
|
||||
stagedSummary: 'M\tsrc/main/ipc/filesystem.ts',
|
||||
stagedPatch: 'diff --git a/src/main/ipc/filesystem.ts b/src/main/ipc/filesystem.ts\n+hello'
|
||||
},
|
||||
''
|
||||
)
|
||||
|
||||
expect(prompt).toContain('Branch: feature/commit-drafts')
|
||||
expect(prompt).toContain('Staged files:\nM\tsrc/main/ipc/filesystem.ts')
|
||||
expect(prompt).toContain('Staged patch:\n```diff')
|
||||
expect(prompt).toContain('+hello')
|
||||
expect(prompt).toContain('Use only the staged changes below as context.')
|
||||
expect(prompt).not.toContain('Additional instructions from user:')
|
||||
})
|
||||
|
||||
it('keeps custom instructions in a separate bounded section', () => {
|
||||
const prompt = buildCommitMessagePrompt(
|
||||
{
|
||||
branch: null,
|
||||
stagedSummary: 'A\tREADME.md',
|
||||
stagedPatch: '+docs'
|
||||
},
|
||||
'Use Conventional Commits.'
|
||||
)
|
||||
|
||||
expect(prompt).toContain('Branch: (detached)')
|
||||
expect(prompt).toContain('Additional instructions from user:\nUse Conventional Commits.')
|
||||
})
|
||||
})
|
||||
|
||||
describe('splitGeneratedCommitMessage', () => {
|
||||
it('normalizes subject and preserves body text', () => {
|
||||
const result = splitGeneratedCommitMessage(
|
||||
'Fix source control generation.\n\n- Move planning into main'
|
||||
)
|
||||
|
||||
expect(result).toEqual({
|
||||
subject: 'Fix source control generation',
|
||||
body: '- Move planning into main',
|
||||
message: 'Fix source control generation\n\n- Move planning into main'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
import { cleanGeneratedCommitMessage, truncateDiffForPrompt } from './commit-message-prompt'
|
||||
import type { TuiAgent } from './types'
|
||||
|
||||
export type CommitMessageDraftAgent = TuiAgent | 'custom'
|
||||
|
||||
export type CommitMessageDraftContext = {
|
||||
branch: string | null
|
||||
stagedSummary: string
|
||||
stagedPatch: string
|
||||
}
|
||||
|
||||
export type CommitMessageDraftOptions = {
|
||||
agentId: CommitMessageDraftAgent
|
||||
model: string
|
||||
thinkingLevel?: string
|
||||
customPrompt?: string
|
||||
customAgentCommand?: string
|
||||
}
|
||||
|
||||
export type GeneratedCommitMessage = {
|
||||
subject: string
|
||||
body: string
|
||||
message: string
|
||||
}
|
||||
|
||||
function limitSection(value: string, maxChars: number): string {
|
||||
if (value.length <= maxChars) {
|
||||
return value
|
||||
}
|
||||
const omitted = value.length - maxChars
|
||||
return `${value.slice(0, maxChars)}\n\n[truncated: ${omitted} characters omitted]`
|
||||
}
|
||||
|
||||
export function buildCommitMessagePrompt(
|
||||
context: CommitMessageDraftContext,
|
||||
customInstructions: string
|
||||
): string {
|
||||
const patch = truncateDiffForPrompt(context.stagedPatch)
|
||||
const base = [
|
||||
'You are generating a single git commit message.',
|
||||
'Return only the commit message text. Do not include a preamble, quotes, or code fences.',
|
||||
'',
|
||||
'Rules:',
|
||||
'- First line: imperative mood, <= 72 chars, no trailing period.',
|
||||
'- Optional body: blank line, then short wrapped bullet points or prose explaining WHY.',
|
||||
'- Capture the primary user-visible or developer-visible change.',
|
||||
'- Use only the staged changes below as context.',
|
||||
'- Do not include "Co-authored-by" trailers - Orca appends them after generation when configured.',
|
||||
'',
|
||||
`Branch: ${context.branch ?? '(detached)'}`,
|
||||
'',
|
||||
'Staged files:',
|
||||
limitSection(context.stagedSummary, 6_000),
|
||||
'',
|
||||
'Staged patch:',
|
||||
'```diff',
|
||||
patch,
|
||||
'```'
|
||||
].join('\n')
|
||||
|
||||
const trimmedInstructions = customInstructions.trim()
|
||||
if (!trimmedInstructions) {
|
||||
return base
|
||||
}
|
||||
return [
|
||||
base,
|
||||
'',
|
||||
'Additional instructions from user:',
|
||||
limitSection(trimmedInstructions, 4_000)
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export function splitGeneratedCommitMessage(message: string): GeneratedCommitMessage {
|
||||
const normalized = cleanGeneratedCommitMessage(message)
|
||||
const [subjectLine = '', ...bodyLines] = normalized.split('\n')
|
||||
const subject = subjectLine.trim().replace(/[.]+$/g, '').slice(0, 72).trimEnd()
|
||||
const body = bodyLines.join('\n').trim()
|
||||
const safeSubject = subject.length > 0 ? subject : 'Update project files'
|
||||
return {
|
||||
subject: safeSubject,
|
||||
body,
|
||||
message: body.length > 0 ? `${safeSubject}\n\n${body}` : safeSubject
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { planCommitMessageGeneration } from './commit-message-plan'
|
||||
|
||||
describe('planCommitMessageGeneration', () => {
|
||||
it('plans Claude non-interactive generation with the prompt on stdin only', () => {
|
||||
const result = planCommitMessageGeneration(
|
||||
{
|
||||
agentId: 'claude',
|
||||
model: 'claude-sonnet-4-6',
|
||||
thinkingLevel: 'high'
|
||||
},
|
||||
'PROMPT'
|
||||
)
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
plan: {
|
||||
binary: 'claude',
|
||||
args: ['-p', '--output-format', 'text', '--model', 'claude-sonnet-4-6', '--effort', 'high'],
|
||||
stdinPayload: 'PROMPT',
|
||||
label: 'Claude'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('plans Codex exec as non-interactive read-only generation with the prompt on stdin only', () => {
|
||||
const result = planCommitMessageGeneration(
|
||||
{
|
||||
agentId: 'codex',
|
||||
model: 'gpt-5.4-mini',
|
||||
thinkingLevel: 'medium'
|
||||
},
|
||||
'PROMPT'
|
||||
)
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
plan: {
|
||||
binary: 'codex',
|
||||
args: [
|
||||
'exec',
|
||||
'--ephemeral',
|
||||
'--skip-git-repo-check',
|
||||
'-s',
|
||||
'read-only',
|
||||
'--model',
|
||||
'gpt-5.4-mini',
|
||||
'-c',
|
||||
'model_reasoning_effort=medium'
|
||||
],
|
||||
stdinPayload: 'PROMPT',
|
||||
label: 'Codex'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('uses preset agent command overrides as the spawn command prefix', () => {
|
||||
const result = planCommitMessageGeneration(
|
||||
{
|
||||
agentId: 'codex',
|
||||
model: 'gpt-5.4-mini',
|
||||
agentCommandOverride: 'npx codex'
|
||||
},
|
||||
'PROMPT'
|
||||
)
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
plan: {
|
||||
binary: 'npx',
|
||||
args: [
|
||||
'codex',
|
||||
'exec',
|
||||
'--ephemeral',
|
||||
'--skip-git-repo-check',
|
||||
'-s',
|
||||
'read-only',
|
||||
'--model',
|
||||
'gpt-5.4-mini'
|
||||
],
|
||||
stdinPayload: 'PROMPT'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects invalid preset agent command overrides before spawning', () => {
|
||||
const result = planCommitMessageGeneration(
|
||||
{
|
||||
agentId: 'claude',
|
||||
model: 'claude-haiku-4-5',
|
||||
agentCommandOverride: 'claude "unterminated'
|
||||
},
|
||||
'PROMPT'
|
||||
)
|
||||
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
error: 'Agent command override is invalid: Unclosed quote in command template.'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,127 @@
|
||||
import {
|
||||
getCommitMessageAgentSpec,
|
||||
getCommitMessageModel,
|
||||
isCustomAgentId
|
||||
} from './commit-message-agent-spec'
|
||||
import { planCustomCommand, tokenizeCustomCommandTemplate } from './commit-message-prompt'
|
||||
import type { TuiAgent } from './types'
|
||||
|
||||
// Why: planning is a pure transformation from "user request + prompt text"
|
||||
// into "spawn-ready binary + argv". Keeping it in shared lets both the local
|
||||
// generator (main process) and the SSH provider (which delegates to the
|
||||
// relay over JSON-RPC) reuse the exact same validation and arg-building
|
||||
// logic without duplicating the spec/model/thinking checks.
|
||||
|
||||
export type CommitMessagePlanInput = {
|
||||
agentId: TuiAgent | 'custom'
|
||||
model: string
|
||||
thinkingLevel?: string
|
||||
customAgentCommand?: string
|
||||
agentCommandOverride?: string
|
||||
}
|
||||
|
||||
export type CommitMessagePlan = {
|
||||
binary: string
|
||||
args: string[]
|
||||
/** Non-null when the prompt should be piped via stdin. */
|
||||
stdinPayload: string | null
|
||||
/** Human-readable label used in error prefixes (e.g. "Claude failed: ..."). */
|
||||
label: string
|
||||
}
|
||||
|
||||
export type CommitMessagePlanResult =
|
||||
| { ok: true; plan: CommitMessagePlan }
|
||||
| { ok: false; error: string }
|
||||
|
||||
function planAgentBinary(
|
||||
defaultBinary: string,
|
||||
commandOverride: string | undefined
|
||||
): { ok: true; binary: string; prefixArgs: string[] } | { ok: false; error: string } {
|
||||
const command = commandOverride?.trim()
|
||||
if (!command) {
|
||||
return { ok: true, binary: defaultBinary, prefixArgs: [] }
|
||||
}
|
||||
|
||||
const tokenized = tokenizeCustomCommandTemplate(command)
|
||||
if (!tokenized.ok) {
|
||||
return { ok: false, error: `Agent command override is invalid: ${tokenized.error}` }
|
||||
}
|
||||
const [binary, ...prefixArgs] = tokenized.tokens
|
||||
if (!binary) {
|
||||
return { ok: false, error: 'Agent command override must start with a binary name.' }
|
||||
}
|
||||
return { ok: true, binary, prefixArgs }
|
||||
}
|
||||
|
||||
export function planCommitMessageGeneration(
|
||||
input: CommitMessagePlanInput,
|
||||
prompt: string
|
||||
): CommitMessagePlanResult {
|
||||
if (isCustomAgentId(input.agentId)) {
|
||||
const command = input.customAgentCommand?.trim() ?? ''
|
||||
if (!command) {
|
||||
return {
|
||||
ok: false,
|
||||
error: 'Custom command is empty. Add one in Settings → Git → AI Commit Messages.'
|
||||
}
|
||||
}
|
||||
const planned = planCustomCommand(command, prompt)
|
||||
if (!planned.ok) {
|
||||
return { ok: false, error: planned.error }
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
plan: {
|
||||
binary: planned.binary,
|
||||
args: planned.args,
|
||||
stdinPayload: planned.stdinPayload,
|
||||
// Why: a custom command has no friendly name, so the binary doubles
|
||||
// as the label in error prefixes ("ollama failed: ...").
|
||||
label: planned.binary
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const spec = getCommitMessageAgentSpec(input.agentId)
|
||||
if (!spec) {
|
||||
return { ok: false, error: `Agent "${input.agentId}" does not support AI commit messages.` }
|
||||
}
|
||||
const model = getCommitMessageModel(input.agentId, input.model)
|
||||
if (!model) {
|
||||
return { ok: false, error: `Model "${input.model}" is not available for ${spec.label}.` }
|
||||
}
|
||||
if (input.thinkingLevel) {
|
||||
if (!model.thinkingLevels) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Model "${model.label}" does not support a thinking effort level.`
|
||||
}
|
||||
}
|
||||
if (!model.thinkingLevels.some((l) => l.id === input.thinkingLevel)) {
|
||||
return {
|
||||
ok: false,
|
||||
error: `Thinking level "${input.thinkingLevel}" is not valid for ${model.label}.`
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const argvPrompt = spec.promptDelivery === 'argv' ? prompt : ''
|
||||
const args = spec.buildArgs({
|
||||
prompt: argvPrompt,
|
||||
model: input.model,
|
||||
thinkingLevel: input.thinkingLevel
|
||||
})
|
||||
const command = planAgentBinary(spec.binary, input.agentCommandOverride)
|
||||
if (!command.ok) {
|
||||
return { ok: false, error: command.error }
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
plan: {
|
||||
binary: command.binary,
|
||||
args: [...command.prefixArgs, ...args],
|
||||
stdinPayload: spec.promptDelivery === 'stdin' ? prompt : null,
|
||||
label: spec.label
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildCommitPrompt,
|
||||
cleanGeneratedCommitMessage,
|
||||
extractAgentErrorMessage,
|
||||
planCustomCommand,
|
||||
STAGED_DIFF_BYTE_BUDGET,
|
||||
tokenizeCustomCommandTemplate,
|
||||
truncateDiffForPrompt
|
||||
} from './commit-message-prompt'
|
||||
|
||||
describe('buildCommitPrompt', () => {
|
||||
it('embeds the diff into the base prompt', () => {
|
||||
const prompt = buildCommitPrompt('diff --git a/foo b/foo\n+hello', '')
|
||||
expect(prompt).toContain('diff --git a/foo b/foo')
|
||||
expect(prompt).toContain('+hello')
|
||||
expect(prompt).toContain('First line: imperative mood')
|
||||
})
|
||||
|
||||
it('appends a custom suffix when non-empty', () => {
|
||||
const prompt = buildCommitPrompt('diff', 'Use Conventional Commits.')
|
||||
expect(prompt).toContain('Additional instructions from user:')
|
||||
expect(prompt.endsWith('Use Conventional Commits.')).toBe(true)
|
||||
})
|
||||
|
||||
it('does not append the suffix block for whitespace-only suffixes', () => {
|
||||
const prompt = buildCommitPrompt('diff', ' \n ')
|
||||
expect(prompt).not.toContain('Additional instructions from user:')
|
||||
})
|
||||
})
|
||||
|
||||
describe('truncateDiffForPrompt', () => {
|
||||
it('returns the diff unchanged when within budget', () => {
|
||||
const diff = 'line\n'.repeat(10)
|
||||
expect(truncateDiffForPrompt(diff)).toBe(diff)
|
||||
})
|
||||
|
||||
it('truncates and appends a marker when over budget', () => {
|
||||
const oversized = 'A'.repeat(STAGED_DIFF_BYTE_BUDGET + 100)
|
||||
const result = truncateDiffForPrompt(oversized)
|
||||
expect(result.length).toBeLessThan(oversized.length)
|
||||
expect(result).toMatch(/diff truncated, 100 bytes omitted/)
|
||||
})
|
||||
|
||||
it('honors a custom budget', () => {
|
||||
const result = truncateDiffForPrompt('abcdefghij', 5)
|
||||
expect(result.startsWith('abcde')).toBe(true)
|
||||
expect(result).toMatch(/diff truncated, 5 bytes omitted/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('cleanGeneratedCommitMessage', () => {
|
||||
it('trims whitespace', () => {
|
||||
expect(cleanGeneratedCommitMessage(' feat: hello \n')).toBe('feat: hello')
|
||||
})
|
||||
|
||||
it('strips a single enclosing fenced code block', () => {
|
||||
const raw = '```\nfeat: hello\n```'
|
||||
expect(cleanGeneratedCommitMessage(raw)).toBe('feat: hello')
|
||||
})
|
||||
|
||||
it('strips a fenced block with a language tag', () => {
|
||||
const raw = '```text\nfix: bug\n```'
|
||||
expect(cleanGeneratedCommitMessage(raw)).toBe('fix: bug')
|
||||
})
|
||||
|
||||
it('drops a leading "Generating…" preamble line', () => {
|
||||
const raw = 'Generating…\nfeat: hello world'
|
||||
expect(cleanGeneratedCommitMessage(raw)).toBe('feat: hello world')
|
||||
})
|
||||
|
||||
it('normalizes CRLF line endings', () => {
|
||||
expect(cleanGeneratedCommitMessage('feat: a\r\nbody line\r\n')).toBe('feat: a\nbody line')
|
||||
})
|
||||
|
||||
it('returns empty string when input is whitespace', () => {
|
||||
expect(cleanGeneratedCommitMessage(' \n\t')).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('extractAgentErrorMessage', () => {
|
||||
it('returns the inner message from a Codex JSON error payload', () => {
|
||||
const stderr = [
|
||||
'--------',
|
||||
'workdir: C:\\Storage\\Projects\\bagplanner',
|
||||
'model: gpt-5.3-codex-spark',
|
||||
'reasoning effort: medium',
|
||||
'--------',
|
||||
'user',
|
||||
'You are generating a single git commit message...',
|
||||
'hook: SessionStart',
|
||||
'hook: SessionStart Completed',
|
||||
'ERROR: {"type":"error","status":400,"error":{"type":"invalid_request_error","message":"The \'gpt-5.3-codex-spark\' model is not supported when using Codex with a ChatGPT account."}}'
|
||||
].join('\n')
|
||||
expect(extractAgentErrorMessage('', stderr)).toBe(
|
||||
"The 'gpt-5.3-codex-spark' model is not supported when using Codex with a ChatGPT account."
|
||||
)
|
||||
})
|
||||
|
||||
it('returns the payload for non-JSON error lines', () => {
|
||||
const out = 'preamble line\nERROR: {bad json oops'
|
||||
expect(extractAgentErrorMessage(out, '')).toBe('{bad json oops')
|
||||
})
|
||||
|
||||
it('uses the last ERROR line when several are emitted', () => {
|
||||
const out = ['ERROR: first failure', 'retry message', 'ERROR: second failure'].join('\n')
|
||||
expect(extractAgentErrorMessage(out, '')).toBe('second failure')
|
||||
})
|
||||
|
||||
it('matches an `Error:` line emitted on stdout', () => {
|
||||
expect(extractAgentErrorMessage('Error: model unavailable\n', '')).toBe('model unavailable')
|
||||
})
|
||||
|
||||
it('returns null when no ERROR line is present', () => {
|
||||
expect(extractAgentErrorMessage('plain log\nmore log\n', '')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns the JSON payload `message` field when no nested error is set', () => {
|
||||
const out = 'ERROR: {"message":"top-level only"}'
|
||||
expect(extractAgentErrorMessage(out, '')).toBe('top-level only')
|
||||
})
|
||||
})
|
||||
|
||||
describe('tokenizeCustomCommandTemplate', () => {
|
||||
it('splits on whitespace', () => {
|
||||
const r = tokenizeCustomCommandTemplate('claude -p')
|
||||
expect(r).toEqual({ ok: true, tokens: ['claude', '-p'] })
|
||||
})
|
||||
|
||||
it('groups double-quoted segments with spaces', () => {
|
||||
const r = tokenizeCustomCommandTemplate('claude --msg "hello world"')
|
||||
expect(r).toEqual({ ok: true, tokens: ['claude', '--msg', 'hello world'] })
|
||||
})
|
||||
|
||||
it('groups single-quoted segments verbatim', () => {
|
||||
const r = tokenizeCustomCommandTemplate(`agent --json '{"k":"v"}'`)
|
||||
expect(r).toEqual({ ok: true, tokens: ['agent', '--json', '{"k":"v"}'] })
|
||||
})
|
||||
|
||||
it('honors backslash escapes inside double quotes', () => {
|
||||
const r = tokenizeCustomCommandTemplate('claude --msg "she said \\"hi\\""')
|
||||
expect(r).toEqual({ ok: true, tokens: ['claude', '--msg', 'she said "hi"'] })
|
||||
})
|
||||
|
||||
it('keeps adjacent quoted/unquoted regions in one token (a"b"c → abc)', () => {
|
||||
const r = tokenizeCustomCommandTemplate('foo a"b"c')
|
||||
expect(r).toEqual({ ok: true, tokens: ['foo', 'abc'] })
|
||||
})
|
||||
|
||||
it('returns an error for an unclosed quote', () => {
|
||||
const r = tokenizeCustomCommandTemplate('claude --msg "no end')
|
||||
expect(r.ok).toBe(false)
|
||||
if (!r.ok) {
|
||||
expect(r.error).toMatch(/unclosed/i)
|
||||
}
|
||||
})
|
||||
|
||||
it('returns an empty token list for whitespace-only input', () => {
|
||||
const r = tokenizeCustomCommandTemplate(' \t ')
|
||||
expect(r).toEqual({ ok: true, tokens: [] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('planCustomCommand', () => {
|
||||
it('routes prompt via stdin when {prompt} is absent', () => {
|
||||
const r = planCustomCommand('claude -p', 'COMMIT MSG')
|
||||
expect(r).toEqual({ ok: true, binary: 'claude', args: ['-p'], stdinPayload: 'COMMIT MSG' })
|
||||
})
|
||||
|
||||
it('substitutes {prompt} as a whole token via argv', () => {
|
||||
const r = planCustomCommand('codex exec {prompt}', 'PROMPT')
|
||||
expect(r).toEqual({ ok: true, binary: 'codex', args: ['exec', 'PROMPT'], stdinPayload: null })
|
||||
})
|
||||
|
||||
it('treats "{prompt}" identically to bare {prompt} (no shell, no double-quoting)', () => {
|
||||
const a = planCustomCommand('codex exec {prompt}', 'PROMPT')
|
||||
const b = planCustomCommand('codex exec "{prompt}"', 'PROMPT')
|
||||
expect(a).toEqual(b)
|
||||
})
|
||||
|
||||
it('substitutes {prompt} embedded inside a token', () => {
|
||||
const r = planCustomCommand('agent --msg={prompt}', 'PROMPT')
|
||||
expect(r).toEqual({
|
||||
ok: true,
|
||||
binary: 'agent',
|
||||
args: ['--msg=PROMPT'],
|
||||
stdinPayload: null
|
||||
})
|
||||
})
|
||||
|
||||
it('errors on empty templates', () => {
|
||||
const r = planCustomCommand(' ', 'PROMPT')
|
||||
expect(r.ok).toBe(false)
|
||||
})
|
||||
|
||||
it('propagates tokenizer errors', () => {
|
||||
const r = planCustomCommand('agent "unclosed', 'PROMPT')
|
||||
expect(r.ok).toBe(false)
|
||||
if (!r.ok) {
|
||||
expect(r.error).toMatch(/unclosed/i)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,231 @@
|
||||
// Why: keeping the base prompt and assembly here (in shared) lets both the
|
||||
// renderer (preview/tests) and main (actual generation) reach the exact same
|
||||
// string without duplicating the wording.
|
||||
|
||||
export const COMMIT_MESSAGE_BASE_PROMPT = `You are generating a single git commit message.
|
||||
Read the staged diff below and produce the message.
|
||||
|
||||
Rules:
|
||||
- First line: imperative mood, <= 72 chars, no trailing period.
|
||||
- Optional body: blank line, then wrapped at 72 chars explaining WHY.
|
||||
- Output ONLY the commit message - no preamble, no code fences, no quotes.
|
||||
- Do not include "Co-authored-by" trailers - Orca appends them after generation when configured.
|
||||
|
||||
Staged diff:
|
||||
\`\`\`diff
|
||||
{{DIFF}}
|
||||
\`\`\`
|
||||
`
|
||||
|
||||
/** Builds the final prompt sent to the agent. The custom suffix is appended verbatim
|
||||
* when non-empty so the user can override style (Conventional Commits, gitmoji, …). */
|
||||
export function buildCommitPrompt(diff: string, customSuffix: string): string {
|
||||
const base = COMMIT_MESSAGE_BASE_PROMPT.replace('{{DIFF}}', diff)
|
||||
const trimmedSuffix = customSuffix.trim()
|
||||
if (!trimmedSuffix) {
|
||||
return base
|
||||
}
|
||||
return `${base}\n\nAdditional instructions from user:\n${trimmedSuffix}`
|
||||
}
|
||||
|
||||
export const STAGED_DIFF_BYTE_BUDGET = 200_000
|
||||
|
||||
/** Truncates a diff that exceeds the byte budget; appends a marker so the agent
|
||||
* knows the input was clipped. */
|
||||
export function truncateDiffForPrompt(
|
||||
diff: string,
|
||||
budget: number = STAGED_DIFF_BYTE_BUDGET
|
||||
): string {
|
||||
if (diff.length <= budget) {
|
||||
return diff
|
||||
}
|
||||
const omitted = diff.length - budget
|
||||
return `${diff.slice(0, budget)}\n...(diff truncated, ${omitted} bytes omitted)`
|
||||
}
|
||||
|
||||
/** Strips noise around the agent's output: surrounding whitespace, a single
|
||||
* enclosing fenced code block, and lone "Generating…" preamble lines some
|
||||
* CLIs print before the real answer. */
|
||||
export function cleanGeneratedCommitMessage(raw: string): string {
|
||||
let text = raw.replace(/\r\n/g, '\n').trim()
|
||||
|
||||
// Why: real commit messages never start with an ellipsis or the word
|
||||
// "Generating"/"Thinking" — those leak from CLIs that print a status line
|
||||
// before the actual response.
|
||||
const firstNewline = text.indexOf('\n')
|
||||
if (firstNewline !== -1) {
|
||||
const firstLine = text.slice(0, firstNewline)
|
||||
if (/^(generating|thinking)\b/i.test(firstLine) || /^[.…]+$/.test(firstLine.trim())) {
|
||||
text = text.slice(firstNewline + 1).trim()
|
||||
}
|
||||
}
|
||||
|
||||
const fence = /^```[a-zA-Z0-9_-]*\n([\s\S]*?)\n```$/
|
||||
const fenced = text.match(fence)
|
||||
if (fenced) {
|
||||
text = fenced[1].trim()
|
||||
}
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
export const CUSTOM_PROMPT_PLACEHOLDER = '{prompt}'
|
||||
|
||||
export type TokenizeCustomCommandResult =
|
||||
| { ok: true; tokens: string[] }
|
||||
| { ok: false; error: string }
|
||||
|
||||
// Why: deliberately POSIX-shell-style only for *grouping* (single + double
|
||||
// quotes, backslash escapes inside double quotes). We do NOT expand `$VAR`,
|
||||
// command substitution, backticks, globs, or `~`. The user's intent is
|
||||
// "spawn this exact CLI" — adding shell semantics on top would create
|
||||
// surprising behavior across platforms (especially Windows) and a security
|
||||
// surface we don't need.
|
||||
export function tokenizeCustomCommandTemplate(template: string): TokenizeCustomCommandResult {
|
||||
const tokens: string[] = []
|
||||
let current = ''
|
||||
let inToken = false
|
||||
let quote: '"' | "'" | null = null
|
||||
let i = 0
|
||||
|
||||
while (i < template.length) {
|
||||
const ch = template[i]
|
||||
if (quote) {
|
||||
if (ch === '\\' && quote === '"' && i + 1 < template.length) {
|
||||
current += template[i + 1]
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
if (ch === quote) {
|
||||
quote = null
|
||||
i++
|
||||
// Why: leaving a quoted region still keeps the token open — `a"b"c`
|
||||
// tokenizes as a single arg `abc`.
|
||||
inToken = true
|
||||
continue
|
||||
}
|
||||
current += ch
|
||||
i++
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === '"' || ch === "'") {
|
||||
quote = ch
|
||||
inToken = true
|
||||
i++
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === '\\' && i + 1 < template.length) {
|
||||
current += template[i + 1]
|
||||
inToken = true
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
|
||||
if (/\s/.test(ch)) {
|
||||
if (inToken) {
|
||||
tokens.push(current)
|
||||
current = ''
|
||||
inToken = false
|
||||
}
|
||||
i++
|
||||
continue
|
||||
}
|
||||
|
||||
current += ch
|
||||
inToken = true
|
||||
i++
|
||||
}
|
||||
|
||||
if (quote) {
|
||||
return { ok: false, error: 'Unclosed quote in command template.' }
|
||||
}
|
||||
if (inToken) {
|
||||
tokens.push(current)
|
||||
}
|
||||
return { ok: true, tokens }
|
||||
}
|
||||
|
||||
export type CustomCommandPlan =
|
||||
| { ok: true; binary: string; args: string[]; stdinPayload: string | null }
|
||||
| { ok: false; error: string }
|
||||
|
||||
/**
|
||||
* Parses a user-supplied command template into a spawn-ready binary + argv,
|
||||
* substituting `{prompt}` with the agent prompt. When the template contains
|
||||
* no `{prompt}`, the prompt is delivered via stdin (mirrors `claude -p`).
|
||||
*
|
||||
* Quoting is a tokenizer-level concern only — we use argv (no shell), so the
|
||||
* substituted prompt is always passed as a single argument regardless of
|
||||
* whether the template wrote `{prompt}` or `"{prompt}"`.
|
||||
*/
|
||||
export function planCustomCommand(template: string, prompt: string): CustomCommandPlan {
|
||||
const tokenized = tokenizeCustomCommandTemplate(template)
|
||||
if (!tokenized.ok) {
|
||||
return { ok: false, error: tokenized.error }
|
||||
}
|
||||
if (tokenized.tokens.length === 0) {
|
||||
return { ok: false, error: 'Custom command is empty.' }
|
||||
}
|
||||
const [binary, ...rest] = tokenized.tokens
|
||||
if (!binary) {
|
||||
return { ok: false, error: 'Custom command must start with a binary name.' }
|
||||
}
|
||||
|
||||
const substitute = (token: string): string =>
|
||||
token.includes(CUSTOM_PROMPT_PLACEHOLDER)
|
||||
? token.split(CUSTOM_PROMPT_PLACEHOLDER).join(prompt)
|
||||
: token
|
||||
const usesPlaceholder = tokenized.tokens.some((t) => t.includes(CUSTOM_PROMPT_PLACEHOLDER))
|
||||
if (usesPlaceholder) {
|
||||
return {
|
||||
ok: true,
|
||||
binary: substitute(binary),
|
||||
args: rest.map(substitute),
|
||||
stdinPayload: null
|
||||
}
|
||||
}
|
||||
return { ok: true, binary, args: rest, stdinPayload: prompt }
|
||||
}
|
||||
|
||||
// Why: agent CLIs (Codex, Claude) prefix their stdout/stderr with config
|
||||
// preamble, the echoed prompt, and hook lifecycle messages. When something
|
||||
// fails, the actionable error is buried far below all of that. This pulls
|
||||
// out the real message so the user sees something legible instead of a
|
||||
// dump of the agent's runtime state.
|
||||
export function extractAgentErrorMessage(stdout: string, stderr: string): string | null {
|
||||
const combined = `${stdout}\n${stderr}`
|
||||
const lines = combined.split(/\r?\n/)
|
||||
|
||||
// Pass 1: look for an `ERROR:`/`Error:` line carrying a JSON payload.
|
||||
// Walk from the end so the most recent (and usually most meaningful)
|
||||
// error wins when an agent prints multiple.
|
||||
for (let i = lines.length - 1; i >= 0; i--) {
|
||||
const line = lines[i]
|
||||
const match = /^\s*(?:ERROR|Error)\s*:\s*(.+)$/.exec(line)
|
||||
if (!match) {
|
||||
continue
|
||||
}
|
||||
const payload = match[1].trim()
|
||||
if (payload.startsWith('{')) {
|
||||
try {
|
||||
const parsed = JSON.parse(payload) as {
|
||||
message?: string
|
||||
error?: { message?: string }
|
||||
}
|
||||
const inner = parsed.error?.message ?? parsed.message
|
||||
if (typeof inner === 'string' && inner.trim().length > 0) {
|
||||
return inner.trim()
|
||||
}
|
||||
} catch {
|
||||
// Fall through to using the raw payload below.
|
||||
}
|
||||
}
|
||||
if (payload.length > 0) {
|
||||
return payload
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -265,6 +265,18 @@ export function getDefaultSettings(homedir: string): GlobalSettings {
|
||||
lastViewByProject: {},
|
||||
activeProject: null
|
||||
},
|
||||
// Why: opt-in feature — `enabled: false` keeps the Generate button hidden
|
||||
// for existing users until they discover and turn it on in Settings. The
|
||||
// per-agent / per-model maps stay empty until the user activates the
|
||||
// toggle, at which point the pane fills them with the spec defaults.
|
||||
commitMessageAi: {
|
||||
enabled: false,
|
||||
agentId: null,
|
||||
selectedModelByAgent: {},
|
||||
selectedThinkingByModel: {},
|
||||
customPrompt: '',
|
||||
customAgentCommand: ''
|
||||
},
|
||||
voice: getDefaultVoiceSettings()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
// Why: single source of truth for the commit trailer Orca appends when the
|
||||
// "Orca Attribution" toggle (`enableGitHubAttribution`) is on. Used by both
|
||||
// the terminal git/gh shim and the AI commit-message generator so the two
|
||||
// code paths agree on the exact string.
|
||||
|
||||
export const ORCA_GIT_COMMIT_TRAILER = 'Co-authored-by: Orca <help@stably.ai>'
|
||||
@@ -1403,6 +1403,10 @@ export type GlobalSettings = {
|
||||
* landed won't have the key; `getDefaultSettings()` hydrates the empty
|
||||
* default via the persistence merge. */
|
||||
githubProjects?: GitHubProjectSettings
|
||||
/** AI-generated commit messages: agent + model + per-model thinking +
|
||||
* user-customizable prompt suffix. Optional so existing profiles do not
|
||||
* require a migration step before this feature lands. */
|
||||
commitMessageAi?: CommitMessageAiSettings
|
||||
/** GitLab project preferences — pinned + recent project paths.
|
||||
* Optional for backward compatibility with profiles saved before
|
||||
* GitLab support; the persistence merge fills the empty default. */
|
||||
@@ -1442,6 +1446,22 @@ export type GlobalSettings = {
|
||||
voice?: VoiceSettings
|
||||
}
|
||||
|
||||
export type CommitMessageAiSettings = {
|
||||
enabled: boolean
|
||||
/** A TuiAgent id, the literal `'custom'` for a user-supplied command, or null. */
|
||||
agentId: TuiAgent | 'custom' | null
|
||||
/** Per-agent: switching agents preserves the previously-picked model. */
|
||||
selectedModelByAgent: Partial<Record<TuiAgent, string>>
|
||||
/** Per-model: thinking effort depends on the model, not the agent. Keyed by model id. */
|
||||
selectedThinkingByModel: Record<string, string>
|
||||
/** Optional user-provided suffix appended to the base prompt (style overrides, etc.). */
|
||||
customPrompt: string
|
||||
/** Command template used when `agentId === 'custom'`. Tokenized POSIX-style;
|
||||
* `{prompt}` is substituted with the diff prompt (argv delivery). When the
|
||||
* template has no `{prompt}`, the prompt is piped via stdin. */
|
||||
customAgentCommand: string
|
||||
}
|
||||
|
||||
export type GhosttyImportPreview = {
|
||||
found: boolean
|
||||
configPath?: string
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { execFileSync } from 'child_process'
|
||||
import { rmSync, writeFileSync } from 'fs'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { test, expect } from './helpers/orca-app'
|
||||
import { waitForSessionReady } from './helpers/store'
|
||||
|
||||
function createWorktreeWithStagedChange(repoPath: string): {
|
||||
branchName: string
|
||||
worktreePath: string
|
||||
} {
|
||||
const branchName = `e2e-ai-commit-${Date.now()}-${Math.random().toString(16).slice(2)}`
|
||||
const worktreePath = path.join(os.tmpdir(), branchName)
|
||||
execFileSync('git', ['worktree', 'add', worktreePath, '-b', branchName], {
|
||||
cwd: repoPath,
|
||||
stdio: 'pipe'
|
||||
})
|
||||
writeFileSync(
|
||||
path.join(worktreePath, 'README.md'),
|
||||
'# AI Commit Message E2E\n\nGenerated flow.\n'
|
||||
)
|
||||
execFileSync('git', ['add', 'README.md'], { cwd: worktreePath, stdio: 'pipe' })
|
||||
return { branchName, worktreePath }
|
||||
}
|
||||
|
||||
function cleanupWorktree(repoPath: string, worktreePath: string, branchName: string): void {
|
||||
try {
|
||||
execFileSync('git', ['worktree', 'remove', '--force', worktreePath], {
|
||||
cwd: repoPath,
|
||||
stdio: 'pipe'
|
||||
})
|
||||
} catch {
|
||||
rmSync(worktreePath, { recursive: true, force: true })
|
||||
}
|
||||
try {
|
||||
execFileSync('git', ['branch', '-D', branchName], { cwd: repoPath, stdio: 'pipe' })
|
||||
} catch {
|
||||
// The branch is already gone when git prunes it with the worktree.
|
||||
}
|
||||
}
|
||||
|
||||
test.describe('Source Control AI commit messages', () => {
|
||||
test('generates a commit message from staged changes through the Source Control UI', async ({
|
||||
orcaPage,
|
||||
testRepoPath
|
||||
}) => {
|
||||
const { branchName, worktreePath } = createWorktreeWithStagedChange(testRepoPath)
|
||||
const agentCommand =
|
||||
'node -e "setTimeout(() => process.stdout.write(\'Add generated E2E message\'), 250)"'
|
||||
|
||||
try {
|
||||
await waitForSessionReady(orcaPage)
|
||||
await orcaPage.evaluate(
|
||||
async ({ repoPath, worktreePath: targetWorktreePath, agentCommand: command }) => {
|
||||
const store = window.__store
|
||||
if (!store) {
|
||||
throw new Error('window.__store is not available')
|
||||
}
|
||||
const state = store.getState()
|
||||
await state.fetchRepos()
|
||||
const repo = store.getState().repos.find((entry) => entry.path === repoPath)
|
||||
if (!repo) {
|
||||
throw new Error(`Seeded E2E repo was not registered: ${repoPath}`)
|
||||
}
|
||||
const listedWorktrees = await window.api.worktrees.list({ repoId: repo.id })
|
||||
store.setState((current) => ({
|
||||
worktreesByRepo: {
|
||||
...current.worktreesByRepo,
|
||||
[repo.id]: listedWorktrees
|
||||
}
|
||||
}))
|
||||
const normalizeMacTmpPath = (value: string): string =>
|
||||
value.startsWith('/private/var/') ? value.slice('/private'.length) : value
|
||||
const worktree = listedWorktrees.find(
|
||||
(entry) => normalizeMacTmpPath(entry.path) === normalizeMacTmpPath(targetWorktreePath)
|
||||
)
|
||||
if (!worktree) {
|
||||
throw new Error(
|
||||
`E2E worktree was not loaded: ${targetWorktreePath}; listed=${listedWorktrees
|
||||
.map((entry) => entry.path)
|
||||
.join(', ')}`
|
||||
)
|
||||
}
|
||||
|
||||
store.getState().setActiveWorktree(worktree.id)
|
||||
await store.getState().updateSettings({
|
||||
commitMessageAi: {
|
||||
enabled: true,
|
||||
agentId: 'custom',
|
||||
selectedModelByAgent: {},
|
||||
selectedThinkingByModel: {},
|
||||
customPrompt: '',
|
||||
customAgentCommand: command
|
||||
}
|
||||
})
|
||||
const status = await window.api.git.status({ worktreePath: worktree.path })
|
||||
store.getState().setGitStatus(worktree.id, status)
|
||||
store.getState().setRightSidebarTab('source-control')
|
||||
store.getState().setRightSidebarOpen(true)
|
||||
},
|
||||
{ repoPath: testRepoPath, worktreePath, agentCommand }
|
||||
)
|
||||
|
||||
await expect
|
||||
.poll(
|
||||
async () =>
|
||||
orcaPage.evaluate(() => {
|
||||
const state = window.__store?.getState()
|
||||
return Boolean(state?.rightSidebarOpen && state?.rightSidebarTab === 'source-control')
|
||||
}),
|
||||
{ timeout: 5_000 }
|
||||
)
|
||||
.toBe(true)
|
||||
|
||||
const textarea = orcaPage.getByRole('textbox', { name: 'Commit message' })
|
||||
await expect(textarea).toBeVisible({ timeout: 10_000 })
|
||||
await expect(textarea).toHaveValue('')
|
||||
|
||||
const generate = orcaPage.getByRole('button', { name: 'Generate commit message with AI' })
|
||||
await expect(generate).toBeVisible()
|
||||
await expect(generate).toBeEnabled()
|
||||
await generate.click()
|
||||
|
||||
await expect(
|
||||
orcaPage.getByRole('button', { name: 'Stop generating commit message' })
|
||||
).toBeVisible()
|
||||
await expect(textarea).toHaveValue('Add generated E2E message', { timeout: 10_000 })
|
||||
} finally {
|
||||
cleanupWorktree(testRepoPath, worktreePath, branchName)
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user