Files
orca/src/main/runtime/orca-runtime-git.test.ts
T
JinjingandOrca 006a4ef3a5 Customizable Source Control AI action recipes with per-action agent and command templates (#4868)
* WIP: Changes before auto-review fixes

* Customize Source Control AI action recipes

- Add per-action CLI arguments for generation and launch flows so saved
  recipes can select model flags without putting prompts in argv.
- Share the text-generation dialog between commit messages and hosted-review
  details, with first-run defaults and repo/global recipe support.
- Launch fix-check agents directly from saved recipes and harden prompt/template
  handling for invalid args, blank prompts, and inherited variables.

* Allow custom commands for source control action recipes

- Let text action recipes save and resolve the custom-command sentinel
- Add settings UI for custom command recipes and preserve per-action defaults
- Split large source-control dialogs and direct launch helpers into focused modules
- Keep launch actions from treating custom text agents as runnable TUI agents

* Add per-repo Source Control AI enablement, custom command, and save-targ

- Repo overrides now support `enabled` and `customAgentCommand`, letting
  repositories opt in/out of Source Control AI independently and supply a
  repo-scoped custom command that takes precedence over the global one.
- Recipe-save dialogs gained a save-target selector ("Don't save / Save for
  this repo / Save as global default") replacing the old boolean checkbox,
  routing saves through the new `saveSourceControlActionRecipe` helper in
  `source-control-ai-recipe-save.ts`.
- `normalizeRepoSourceControlAiOverrides` now returns `undefined` for empty
  objects and passes the `null` sentinel through the IPC/RPC layer so the
  persistence layer can clear repo overrides cleanly.
- `resolveSourceControlLaunchPlatform` resolves the correct shell platform
  for SSH and WSL worktrees so agent launch commands are built correctly.
- Settings UI gained `RepositorySourceControlAiEnablement` and
  `RepositorySourceControlAiCustomCommand` rows; draft/label logic was
  extracted into focused modules to stay within lint line limits.

* Extract action recipe defaults into own component and use id-prefixed wo

- Move action recipe draft state and UI out of CommitMessageAiPane into SourceControlAiActionRecipeDefaults and source-control-ai-action-recipe-draft.ts to respect the max-lines lint rule
- Use toRuntimeWorktreeSelector() across all runtime git RPC calls so the runtime can resolve worktrees by ID rather than path
- Fix SSH launch platform resolution to use the repo's connection when the newly created worktree isn't hydrated yet
- Add edit and delete handlers for PR conversation comments with confirmation dialog
- Use text-status-success design token instead of hardcoded text-emerald-500

* add more search keyword

* Rename "Enable Source Control AI defaults" to "Show Source Control AI ac

* fix test

* Remove unused imports and variable assignment in launch-work-item-direct

* Fix test mocks to use `mocks.store` instead of `storeState.value` for di

* Extract Source Control AI logic into focused modules with fix-checks dia

---------

Co-authored-by: Orca <help@stably.ai>
2026-06-08 14:08:35 -07:00

387 lines
13 KiB
TypeScript

import { mkdtempSync, rmSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { GlobalSettings } from '../../shared/types'
import type * as GitStatusModule from '../git/status'
import type * as CommitMessageTextGenerationModule from '../text-generation/commit-message-text-generation'
import type * as PullRequestContextModule from '../text-generation/pull-request-context'
import { RuntimeGitCommands, type ResolvedRuntimeGitWorktree } from './orca-runtime-git'
const mocks = vi.hoisted(() => ({
abortMerge: vi.fn(),
abortRebase: vi.fn(),
getStagedCommitContext: vi.fn(),
getPullRequestDraftContext: vi.fn(),
generateCommitMessageFromContext: vi.fn(),
generatePullRequestFieldsFromContext: vi.fn(),
resolveCommitMessageSettings: vi.fn(),
getSshGitProvider: vi.fn()
}))
vi.mock('../git/status', async () => ({
...(await vi.importActual<typeof GitStatusModule>('../git/status')),
abortMerge: mocks.abortMerge,
abortRebase: mocks.abortRebase,
getStagedCommitContext: mocks.getStagedCommitContext
}))
vi.mock('../text-generation/commit-message-text-generation', async () => ({
...(await vi.importActual<typeof CommitMessageTextGenerationModule>(
'../text-generation/commit-message-text-generation'
)),
generateCommitMessageFromContext: mocks.generateCommitMessageFromContext,
generatePullRequestFieldsFromContext: mocks.generatePullRequestFieldsFromContext,
resolveCommitMessageSettings: mocks.resolveCommitMessageSettings
}))
vi.mock('../text-generation/pull-request-context', async () => ({
...(await vi.importActual<typeof PullRequestContextModule>(
'../text-generation/pull-request-context'
)),
getPullRequestDraftContext: mocks.getPullRequestDraftContext
}))
vi.mock('../providers/ssh-git-dispatch', () => ({
getSshGitProvider: mocks.getSshGitProvider
}))
const tempDirs: string[] = []
function makeWorktree(path: string): ResolvedRuntimeGitWorktree {
return {
id: 'wt-1',
repoId: 'repo-1',
path,
git: {
path,
branch: 'main',
bare: false,
detached: false,
head: 'a'.repeat(40)
}
} as unknown as ResolvedRuntimeGitWorktree
}
function makeCommands(worktreePath: string): RuntimeGitCommands {
return new RuntimeGitCommands({
resolveRuntimeGitTarget: async () => ({ worktree: makeWorktree(worktreePath) }),
getRuntimeSettings: () => ({}) as GlobalSettings
})
}
describe('RuntimeGitCommands', () => {
beforeEach(() => {
mocks.abortMerge.mockReset()
mocks.abortRebase.mockReset()
mocks.getStagedCommitContext.mockReset()
mocks.getPullRequestDraftContext.mockReset()
mocks.generateCommitMessageFromContext.mockReset()
mocks.generatePullRequestFieldsFromContext.mockReset()
mocks.resolveCommitMessageSettings.mockReset()
mocks.getSshGitProvider.mockReset()
})
afterEach(() => {
while (tempDirs.length > 0) {
rmSync(tempDirs.pop()!, { recursive: true, force: true })
}
})
it('aborts a local merge through the resolved worktree', async () => {
const worktreePath = mkdtempSync(join(tmpdir(), 'orca-runtime-git-'))
tempDirs.push(worktreePath)
const commands = makeCommands(worktreePath)
mocks.abortMerge.mockResolvedValue(undefined)
await expect(commands.abortRuntimeGitMerge('id:wt-1')).resolves.toEqual({ ok: true })
expect(mocks.abortMerge).toHaveBeenCalledWith(worktreePath)
})
it('aborts a remote merge through the SSH git provider', async () => {
const provider = { abortMerge: vi.fn().mockResolvedValue(undefined) }
mocks.getSshGitProvider.mockReturnValue(provider)
const commands = new RuntimeGitCommands({
resolveRuntimeGitTarget: async () => ({
worktree: makeWorktree('/remote/repo'),
connectionId: 'conn-1'
}),
getRuntimeSettings: () => ({}) as GlobalSettings
})
await expect(commands.abortRuntimeGitMerge('id:wt-1')).resolves.toEqual({ ok: true })
expect(provider.abortMerge).toHaveBeenCalledWith('/remote/repo')
expect(mocks.abortMerge).not.toHaveBeenCalled()
})
it('aborts a local rebase through the resolved worktree', async () => {
const worktreePath = mkdtempSync(join(tmpdir(), 'orca-runtime-git-'))
tempDirs.push(worktreePath)
const commands = makeCommands(worktreePath)
mocks.abortRebase.mockResolvedValue(undefined)
await expect(commands.abortRuntimeGitRebase('id:wt-1')).resolves.toEqual({ ok: true })
expect(mocks.abortRebase).toHaveBeenCalledWith(worktreePath)
})
it('aborts a remote rebase through the SSH git provider', async () => {
const provider = { abortRebase: vi.fn().mockResolvedValue(undefined) }
mocks.getSshGitProvider.mockReturnValue(provider)
const commands = new RuntimeGitCommands({
resolveRuntimeGitTarget: async () => ({
worktree: makeWorktree('/remote/repo'),
connectionId: 'conn-1'
}),
getRuntimeSettings: () => ({}) as GlobalSettings
})
await expect(commands.abortRuntimeGitRebase('id:wt-1')).resolves.toEqual({ ok: true })
expect(provider.abortRebase).toHaveBeenCalledWith('/remote/repo')
expect(mocks.abortRebase).not.toHaveBeenCalled()
})
it('rejects slash-only git mutation paths before they can target the worktree root', async () => {
const worktreePath = mkdtempSync(join(tmpdir(), 'orca-runtime-git-'))
tempDirs.push(worktreePath)
const commands = makeCommands(worktreePath)
await expect(commands.bulkDiscardRuntimeGitPaths('id:wt-1', ['///'])).rejects.toThrow(
'invalid_relative_path'
)
await expect(commands.discardRuntimeGitPath('id:wt-1', '///')).rejects.toThrow(
'invalid_relative_path'
)
})
it('prepares the selected local agent environment before generating commit messages', async () => {
const worktreePath = mkdtempSync(join(tmpdir(), 'orca-runtime-git-'))
tempDirs.push(worktreePath)
const context = {
branch: 'main',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello'
}
const params = { agentId: 'codex', model: 'gpt-5.4-mini', thinkingLevel: 'low' }
mocks.resolveCommitMessageSettings.mockReturnValue({ ok: true, params })
mocks.getStagedCommitContext.mockResolvedValue(context)
mocks.generateCommitMessageFromContext.mockResolvedValue({
success: true,
message: 'docs: update readme'
})
const commands = new RuntimeGitCommands({
resolveRuntimeGitTarget: async () => ({ worktree: makeWorktree(worktreePath) }),
getRuntimeSettings: () =>
({
commitMessageAi: { enabled: true, agentId: 'codex' },
agentCmdOverrides: {},
enableGitHubAttribution: false
}) as GlobalSettings,
getCommitMessageAgentEnvironment: () => ({
prepareForCodexLaunch: () => '/managed/codex-home'
})
})
await expect(commands.generateRuntimeCommitMessage('id:wt-1')).resolves.toEqual({
success: true,
message: 'docs: update readme'
})
expect(mocks.resolveCommitMessageSettings).toHaveBeenCalledWith(
expect.objectContaining({
commitMessageAi: { enabled: true, agentId: 'codex' }
}),
'local',
'commitMessage',
null
)
expect(mocks.generateCommitMessageFromContext).toHaveBeenCalledWith(
context,
params,
expect.objectContaining({
kind: 'local',
cwd: worktreePath,
env: expect.objectContaining({ CODEX_HOME: '/managed/codex-home' })
})
)
})
it('uses one-shot resolved params before runtime commit-message defaults', async () => {
const worktreePath = mkdtempSync(join(tmpdir(), 'orca-runtime-git-'))
tempDirs.push(worktreePath)
const context = {
branch: 'main',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello'
}
const sourceControlAiResolvedParams = {
agentId: 'codex' as const,
model: 'gpt-5.5',
thinkingLevel: 'high',
customPrompt: 'Use Conventional Commits.'
}
mocks.getStagedCommitContext.mockResolvedValue(context)
mocks.generateCommitMessageFromContext.mockResolvedValue({
success: true,
message: 'feat: update readme'
})
const commands = new RuntimeGitCommands({
resolveRuntimeGitTarget: async () => ({ worktree: makeWorktree(worktreePath) }),
getRuntimeSettings: () =>
({
sourceControlAi: {
commitMessage: {
enabled: true,
agentId: 'cursor',
customPrompt: 'Saved default that should not win.'
}
}
}) as unknown as GlobalSettings
})
await expect(
commands.generateRuntimeCommitMessage('id:wt-1', { sourceControlAiResolvedParams })
).resolves.toEqual({
success: true,
message: 'feat: update readme'
})
expect(mocks.resolveCommitMessageSettings).not.toHaveBeenCalled()
expect(mocks.generateCommitMessageFromContext).toHaveBeenCalledWith(
context,
sourceControlAiResolvedParams,
expect.objectContaining({
kind: 'local',
cwd: worktreePath
})
)
})
it('uses one-shot resolved params before runtime pull-request defaults', async () => {
const worktreePath = mkdtempSync(join(tmpdir(), 'orca-runtime-git-'))
tempDirs.push(worktreePath)
const context = {
base: 'main',
branch: 'feature/source-control-ai',
commitSummary: 'abc123 feat: test',
changeSummary: 'M README.md',
patch: '+hello',
currentTitle: '',
currentBody: '',
currentDraft: false
}
const sourceControlAiResolvedParams = {
agentId: 'codex' as const,
model: 'gpt-5.5',
thinkingLevel: 'high',
commandInputTemplate: '{basePrompt}\n\nUse release-note style.'
}
mocks.getPullRequestDraftContext.mockResolvedValue(context)
mocks.generatePullRequestFieldsFromContext.mockResolvedValue({
success: true,
fields: {
base: 'main',
title: 'Improve Source Control AI',
body: 'Body',
draft: false
}
})
const commands = new RuntimeGitCommands({
resolveRuntimeGitTarget: async () => ({ worktree: makeWorktree(worktreePath) }),
getRuntimeSettings: () =>
({
sourceControlAi: {
pullRequest: {
enabled: true,
agentId: 'cursor',
customPrompt: 'Saved default that should not win.'
}
}
}) as unknown as GlobalSettings
})
await expect(
commands.generateRuntimePullRequestFields(
'id:wt-1',
{ base: 'main', title: '', body: '', draft: false },
{ sourceControlAiResolvedParams }
)
).resolves.toEqual({
success: true,
fields: {
base: 'main',
title: 'Improve Source Control AI',
body: 'Body',
draft: false
}
})
expect(mocks.resolveCommitMessageSettings).not.toHaveBeenCalled()
expect(mocks.generatePullRequestFieldsFromContext).toHaveBeenCalledWith(
context,
sourceControlAiResolvedParams,
expect.objectContaining({
kind: 'local',
cwd: worktreePath
})
)
})
it('resolves remote commit-message settings against the SSH host cache', async () => {
const worktreePath = '/remote/repo'
const context = {
branch: 'main',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello'
}
const params = { agentId: 'cursor', model: 'remote-model' }
mocks.resolveCommitMessageSettings.mockReturnValue({ ok: true, params })
mocks.generateCommitMessageFromContext.mockResolvedValue({
success: true,
message: 'docs: update remote readme'
})
const provider = {
getStagedCommitContext: vi.fn().mockResolvedValue(context),
executeCommitMessagePlan: vi.fn()
}
mocks.getSshGitProvider.mockReturnValue(provider)
const commands = new RuntimeGitCommands({
resolveRuntimeGitTarget: async () => ({
worktree: makeWorktree(worktreePath),
connectionId: 'conn-1'
}),
getRuntimeSettings: () =>
({
commitMessageAi: {
enabled: true,
agentId: 'cursor',
selectedModelByAgentByHost: { 'ssh:conn-1': { cursor: 'remote-model' } }
}
}) as unknown as GlobalSettings
})
await expect(commands.generateRuntimeCommitMessage('id:wt-1')).resolves.toEqual({
success: true,
message: 'docs: update remote readme'
})
expect(mocks.resolveCommitMessageSettings).toHaveBeenCalledWith(
expect.any(Object),
'ssh:conn-1',
'commitMessage',
null
)
expect(mocks.generateCommitMessageFromContext).toHaveBeenCalledWith(
context,
params,
expect.objectContaining({
kind: 'remote',
cwd: worktreePath
})
)
})
})