diff --git a/config/scripts/rebuild-native-deps.mjs b/config/scripts/rebuild-native-deps.mjs index 7f223a944..80e8b3c74 100644 --- a/config/scripts/rebuild-native-deps.mjs +++ b/config/scripts/rebuild-native-deps.mjs @@ -22,7 +22,7 @@ import { rebuild } from '@electron/rebuild' import { execFileSync, spawnSync } from 'node:child_process' import { createRequire } from 'node:module' -import { existsSync, globSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' +import { existsSync, globSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { platform as osPlatform } from 'node:os' import { resolve } from 'node:path' @@ -139,6 +139,7 @@ function ensureElectronPackageInstalled() { // Why: CI has observed Electron's postinstall exiting cleanly without // writing path.txt; native rebuild and tests both need the binary path. console.log('[rebuild] Electron package binary is missing; rerunning Electron install.') + resetPartialElectronInstall() try { execFileSync(process.execPath, [require.resolve('electron/install.js')], { cwd: projectDir, @@ -184,6 +185,14 @@ function ensureElectronPackageInstalled() { } } +function resetPartialElectronInstall() { + const electronPackageDir = resolve(projectDir, 'node_modules/electron') + // Why: Electron's installer can leave a partial dist/ tree behind after + // skipped or interrupted postinstall runs; retry from a clean target. + rmSync(resolve(electronPackageDir, 'dist'), { recursive: true, force: true }) + rmSync(resolve(electronPackageDir, 'path.txt'), { force: true }) +} + function continuePostinstallWithoutElectron() { if (!isPostinstall() || process.env.ORCA_STRICT_ELECTRON_INSTALL === '1') { return false diff --git a/config/scripts/rebuild-native-deps.test.mjs b/config/scripts/rebuild-native-deps.test.mjs index e4ce43890..7dbb96f29 100644 --- a/config/scripts/rebuild-native-deps.test.mjs +++ b/config/scripts/rebuild-native-deps.test.mjs @@ -65,6 +65,32 @@ describe('rebuild-native-deps Electron install fallback', () => { rmSync(projectDir, { recursive: true, force: true }) } }) + + it('clears partial Electron package contents before retrying install', () => { + const projectDir = mkTempProject() + + try { + writeFakeElectronPackage(projectDir, { + installExitsWith: 1, + logPartialStateBeforeInstall: true + }) + writeFakeElectronRebuild(projectDir) + mkdirSync(join(projectDir, 'node_modules', 'electron', 'dist', 'locales'), { recursive: true }) + writeFileSync(join(projectDir, 'node_modules', 'electron', 'dist', 'locales', 'stale.pak'), '') + writeFileSync(join(projectDir, 'node_modules', 'electron', 'path.txt'), 'stale-path') + + const result = runRebuildScript(projectDir, { + ORCA_STRICT_ELECTRON_INSTALL: '1' + }) + + expect(result.status).toBe(1) + expect(readFileSync(join(projectDir, 'electron-install.log'), 'utf8')).toBe( + 'partial cleared\ninstall attempted\n' + ) + } finally { + rmSync(projectDir, { recursive: true, force: true }) + } + }) }) function mkTempProject() { @@ -85,7 +111,10 @@ function runRebuildScript(projectDir, extraEnv = {}) { }) } -function writeFakeElectronPackage(projectDir, { installExitsWith }) { +function writeFakeElectronPackage( + projectDir, + { installExitsWith, logPartialStateBeforeInstall = false } +) { const electronDir = join(projectDir, 'node_modules', 'electron') mkdirSync(electronDir, { recursive: true }) writeFileSync(join(electronDir, 'package.json'), JSON.stringify({ version: '41.5.0' })) @@ -96,7 +125,15 @@ function writeFakeElectronPackage(projectDir, { installExitsWith }) { writeFileSync( join(electronDir, 'install.js'), ` -const { appendFileSync } = require('node:fs') +const { appendFileSync, existsSync } = require('node:fs') +if (${JSON.stringify(logPartialStateBeforeInstall)}) { + appendFileSync( + 'electron-install.log', + existsSync('node_modules/electron/dist') || existsSync('node_modules/electron/path.txt') + ? 'partial still present\\n' + : 'partial cleared\\n' + ) +} appendFileSync('electron-install.log', 'install attempted\\n') process.exit(${installExitsWith}) ` diff --git a/src/main/agent-hooks/first-work-branch-rename.test.ts b/src/main/agent-hooks/first-work-branch-rename.test.ts index 1014df87e..80d5c4938 100644 --- a/src/main/agent-hooks/first-work-branch-rename.test.ts +++ b/src/main/agent-hooks/first-work-branch-rename.test.ts @@ -147,6 +147,12 @@ describe('maybeAutoRenameBranchOnFirstWork', () => { ['branch', '-m', 'you/fix-auth'], expect.objectContaining({ cwd: '/repo/wt' }) ) + expect(resolveTextGenerationParamsMock).toHaveBeenCalledWith( + expect.anything(), + 'local', + 'branchName', + expect.objectContaining({ id: REPO_ID }) + ) expect(setDisplayName).toHaveBeenCalledWith(WORKTREE_ID, 'Fix auth') expect(onRenamed).toHaveBeenCalledWith(REPO_ID) }) diff --git a/src/main/agent-hooks/first-work-branch-rename.ts b/src/main/agent-hooks/first-work-branch-rename.ts index 37ee24515..ac4271727 100644 --- a/src/main/agent-hooks/first-work-branch-rename.ts +++ b/src/main/agent-hooks/first-work-branch-rename.ts @@ -174,7 +174,7 @@ async function runAutoRename( const settings = deps.getSettings() const hostKey = getCommitMessageModelDiscoveryHostKey(repo.connectionId ?? null) - const resolvedParams = resolveTextGenerationParams(settings, hostKey) + const resolvedParams = resolveTextGenerationParams(settings, hostKey, 'branchName', repo) if (!resolvedParams.ok) { return stop(`no generation agent: ${resolvedParams.error}`) } diff --git a/src/main/github/client-create-pr.test.ts b/src/main/github/client-create-pr.test.ts index 453a6a174..8051163c1 100644 --- a/src/main/github/client-create-pr.test.ts +++ b/src/main/github/client-create-pr.test.ts @@ -1,19 +1,33 @@ +/* eslint-disable max-lines -- Why: create-PR tests share gh/SSH mocks across + template, CLI, and error-path cases; keeping them together prevents drift. */ import { beforeEach, describe, expect, it, vi } from 'vitest' +import { readFile } from 'fs/promises' -const { ghExecFileAsyncMock, getOwnerRepoMock, extractExecErrorMock, acquireMock, releaseMock } = - vi.hoisted(() => ({ - ghExecFileAsyncMock: vi.fn(), - getOwnerRepoMock: vi.fn(), - extractExecErrorMock: vi.fn((error: unknown) => { - const value = error as { stderr?: string; stdout?: string; message?: string } - return { - stderr: value?.stderr ?? value?.message ?? '', - stdout: value?.stdout ?? '' - } - }), - acquireMock: vi.fn(), - releaseMock: vi.fn() - })) +const { + ghExecFileAsyncMock, + getOwnerRepoMock, + extractExecErrorMock, + acquireMock, + releaseMock, + getSshFilesystemProviderMock +} = vi.hoisted(() => ({ + ghExecFileAsyncMock: vi.fn(), + getOwnerRepoMock: vi.fn(), + extractExecErrorMock: vi.fn((error: unknown) => { + const value = error as { stderr?: string; stdout?: string; message?: string } + return { + stderr: value?.stderr ?? value?.message ?? '', + stdout: value?.stdout ?? '' + } + }), + acquireMock: vi.fn(), + releaseMock: vi.fn(), + getSshFilesystemProviderMock: vi.fn() +})) + +vi.mock('../providers/ssh-filesystem-dispatch', () => ({ + getSshFilesystemProvider: getSshFilesystemProviderMock +})) vi.mock('./gh-utils', () => ({ execFileAsync: vi.fn(), @@ -49,6 +63,7 @@ describe('createGitHubPullRequest', () => { extractExecErrorMock.mockClear() acquireMock.mockReset() releaseMock.mockReset() + getSshFilesystemProviderMock.mockReset() acquireMock.mockResolvedValue(undefined) }) @@ -149,6 +164,76 @@ describe('createGitHubPullRequest', () => { expect(options).not.toHaveProperty('cwd') }) + it.each([ + ['.github/pull_request_template.md', ['.github/pull_request_template.md']], + [ + '.github/PULL_REQUEST_TEMPLATE.md', + ['.github/pull_request_template.md', '.github/PULL_REQUEST_TEMPLATE.md'] + ], + [ + 'docs/PULL_REQUEST_TEMPLATE.md', + [ + '.github/pull_request_template.md', + '.github/PULL_REQUEST_TEMPLATE.md', + 'pull_request_template.md', + 'PULL_REQUEST_TEMPLATE.md', + 'docs/pull_request_template.md', + 'docs/PULL_REQUEST_TEMPLATE.md' + ] + ] + ] as [string, string[]][])( + 'reads PR templates from the SSH filesystem provider at %s', + async (relativeTemplatePath, expectedRelativeLookups) => { + const templateBody = `Remote template body from ${relativeTemplatePath}` + const readRemoteFile = vi.fn(async (path: string) => { + if (path === `/remote/repo-root/${relativeTemplatePath}`) { + return { + content: templateBody, + isBinary: false + } + } + throw new Error('missing template') + }) + getSshFilesystemProviderMock.mockReturnValue({ readFile: readRemoteFile }) + getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) + const writtenBodies: string[] = [] + ghExecFileAsyncMock.mockImplementationOnce(async (args: string[]) => { + const bodyPath = args[args.indexOf('--body-file') + 1] + writtenBodies.push(await readFile(bodyPath, 'utf8')) + return { + stdout: JSON.stringify({ + number: 46, + url: 'https://github.com/acme/widgets/pull/46' + }) + } + }) + + await expect( + createGitHubPullRequest( + '/remote/repo-root', + { + provider: 'github', + base: 'main', + head: 'feature/ssh-template', + title: 'SSH Template PR', + body: '', + useTemplate: true + }, + 'ssh-1' + ) + ).resolves.toEqual({ + ok: true, + number: 46, + url: 'https://github.com/acme/widgets/pull/46' + }) + + expect(readRemoteFile.mock.calls.map(([path]) => path)).toEqual( + expectedRelativeLookups.map((relativeLookup) => `/remote/repo-root/${relativeLookup}`) + ) + expect(writtenBodies).toEqual([templateBody]) + } + ) + it('falls back to parsing the PR URL for older gh output', async () => { getOwnerRepoMock.mockResolvedValueOnce({ owner: 'acme', repo: 'widgets' }) ghExecFileAsyncMock.mockResolvedValueOnce({ diff --git a/src/main/github/client.ts b/src/main/github/client.ts index 6e3b2a61e..c6edafcdd 100644 --- a/src/main/github/client.ts +++ b/src/main/github/client.ts @@ -29,10 +29,12 @@ import { GITHUB_WORK_ITEMS_SSH_REMOTE_REQUIRED_MESSAGE, sortWorkItemsByUpdatedAt } from '../../shared/work-items' -import { mkdtemp, rm, writeFile } from 'fs/promises' +import { mkdtemp, readFile, rm, writeFile } from 'fs/promises' import { join } from 'path' import { tmpdir } from 'os' import { getPRConflictSummary } from './conflict-summary' +import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch' +import { joinWorktreeRelativePath } from '../runtime/runtime-relative-paths' import { execFileAsync, ghExecFileAsync, @@ -1391,6 +1393,41 @@ async function findOpenPRByHeadBase(args: { return { number: list[0].number, url: list[0].url } } +async function readPullRequestTemplate( + repoPath: string, + connectionId?: string | null +): Promise { + const relativeCandidates = [ + '.github/pull_request_template.md', + '.github/PULL_REQUEST_TEMPLATE.md', + 'pull_request_template.md', + 'PULL_REQUEST_TEMPLATE.md', + 'docs/pull_request_template.md', + 'docs/PULL_REQUEST_TEMPLATE.md' + ] + const remoteProvider = connectionId ? getSshFilesystemProvider(connectionId) : undefined + if (connectionId && !remoteProvider) { + return '' + } + for (const relativeCandidate of relativeCandidates) { + try { + if (remoteProvider) { + const result = await remoteProvider.readFile( + joinWorktreeRelativePath(repoPath, relativeCandidate) + ) + if (result.isBinary) { + continue + } + return result.content + } + return await readFile(join(repoPath, relativeCandidate), 'utf8') + } catch { + // Try the next conventional PR template path. + } + } + return '' +} + export async function createGitHubPullRequest( repoPath: string, input: CreateHostedReviewInput, @@ -1435,7 +1472,11 @@ export async function createGitHubPullRequest( await acquire() const bodyPath = join(tempDir, 'body.md') try { - await writeFile(bodyPath, input.body ?? '', 'utf8') + const body = + input.useTemplate && !input.body?.trim() + ? await readPullRequestTemplate(repoPath, connectionId) + : (input.body ?? '') + await writeFile(bodyPath, body, 'utf8') const createArgs = [ 'pr', 'create', diff --git a/src/main/ipc/filesystem.ts b/src/main/ipc/filesystem.ts index b3e03ba73..e33c2ce39 100644 --- a/src/main/ipc/filesystem.ts +++ b/src/main/ipc/filesystem.ts @@ -1,7 +1,7 @@ /* eslint-disable max-lines */ import { ipcMain, shell } from 'electron' import { readdir, readFile, writeFile, stat, lstat, open } from 'fs/promises' -import { extname, join } from 'path' +import { extname, join, resolve } from 'path' import type { ChildProcess } from 'child_process' import { gitExecFileAsync, wslAwareSpawn } from '../git/runner' import { parseWslPath, toWindowsWslPath } from '../wsl' @@ -18,6 +18,7 @@ import type { MarkdownDocument, SearchOptions, SearchResult, + Repo, TuiAgent } from '../../shared/types' import type { GitHistoryOptions, GitHistoryResult } from '../../shared/git-history' @@ -92,6 +93,8 @@ import { prepareLocalCommitMessageAgentEnv, type CommitMessageAgentEnvironmentResolvers } from '../text-generation/commit-message-agent-environment' +import { listRepoWorktrees } from '../repo-worktrees' +import { splitWorktreeId } from '../../shared/worktree-id' // Why: Monaco has large-file optimizations like VS Code; blocking at 5MB makes // ordinary JSON/log files inaccessible before the editor can degrade features. @@ -118,6 +121,133 @@ const PREVIEWABLE_BINARY_MIME_TYPES: Record = { '.pdf': 'application/pdf' } +function comparableLocalPath(value: string): string { + const normalized = resolve(value) + return process.platform === 'win32' ? normalized.toLowerCase() : normalized +} + +function comparableRemotePath(value: string): string { + return value.replace(/[/\\]+$/g, '') +} + +function getCandidateLocalWorktreePaths( + worktreePath: string, + resolvedWorktreePath: string +): Set { + return new Set([worktreePath, resolvedWorktreePath].map(comparableLocalPath)) +} + +function hasRegisteredWorktreeMetaForRepo( + store: Store, + repoId: string, + candidatePaths: Set +): boolean { + for (const worktreeId of Object.keys(store.getAllWorktreeMeta())) { + const parsed = splitWorktreeId(worktreeId) + if (parsed?.repoId === repoId && candidatePaths.has(comparableLocalPath(parsed.worktreePath))) { + return true + } + } + return false +} + +function hasRegisteredRemoteWorktreeMetaForRepo( + store: Store, + repoId: string, + worktreePath: string +): boolean { + const comparableWorktreePath = comparableRemotePath(worktreePath) + for (const worktreeId of Object.keys(store.getAllWorktreeMeta())) { + const parsed = splitWorktreeId(worktreeId) + if ( + parsed?.repoId === repoId && + comparableRemotePath(parsed.worktreePath) === comparableWorktreePath + ) { + return true + } + } + return false +} + +async function localRepoOwnsWorktree( + store: Store, + repo: Repo, + worktreePath: string +): Promise { + let resolvedWorktreePath: string + try { + resolvedWorktreePath = await resolveRegisteredWorktreePath(worktreePath, store) + } catch { + return false + } + const candidatePaths = getCandidateLocalWorktreePaths(worktreePath, resolvedWorktreePath) + if (candidatePaths.has(comparableLocalPath(repo.path))) { + return true + } + if (hasRegisteredWorktreeMetaForRepo(store, repo.id, candidatePaths)) { + return true + } + try { + const worktrees = await listRepoWorktrees(repo) + return worktrees.some((worktree) => candidatePaths.has(comparableLocalPath(worktree.path))) + } catch { + return false + } +} + +async function remoteRepoOwnsWorktree( + store: Store, + repo: Repo, + worktreePath: string, + connectionId: string +): Promise { + const comparableWorktreePath = comparableRemotePath(worktreePath) + if (comparableRemotePath(repo.path) === comparableWorktreePath) { + return true + } + const provider = getSshGitProvider(connectionId) + if (!provider) { + return hasRegisteredRemoteWorktreeMetaForRepo(store, repo.id, worktreePath) + } + try { + const worktrees = await provider.listWorktrees(repo.path) + return worktrees.some( + (worktree) => comparableRemotePath(worktree.path) === comparableWorktreePath + ) + } catch { + return false + } +} + +async function getRepoForSourceControlAi( + store: Store, + args: { repoId?: string; worktreePath: string; connectionId?: string } +): Promise { + if (!args.repoId) { + return null + } + const repo = store.getRepo(args.repoId) + if (!repo) { + return null + } + if (args.connectionId) { + if (repo.connectionId !== args.connectionId) { + return null + } + // Why: a single SSH connection can host several repos; repo-scoped AI + // overrides only apply when the requested worktree belongs to that repo. + return (await remoteRepoOwnsWorktree(store, repo, args.worktreePath, args.connectionId)) + ? repo + : null + } + if (repo.connectionId) { + return null + } + // Why: renderer-supplied repoId is advisory; only apply repo overrides when + // the requested local worktree is known to belong to that repo. + return (await localRepoOwnsWorktree(store, repo, args.worktreePath)) ? repo : null +} + function validateFullGitObjectId(value: string, label: string): string { if (!FULL_GIT_OBJECT_ID_PATTERN.test(value)) { throw new Error(`${label} must be a full git object id`) @@ -641,11 +771,17 @@ export function registerFilesystemHandlers( _event, args: { worktreePath: string + repoId?: string connectionId?: string } ): Promise => { const discoveryHostKey = getCommitMessageModelDiscoveryHostKey(args.connectionId ?? null) - const resolvedSettings = resolveCommitMessageSettings(store.getSettings(), discoveryHostKey) + const resolvedSettings = resolveCommitMessageSettings( + store.getSettings(), + discoveryHostKey, + 'commitMessage', + await getRepoForSourceControlAi(store, args) + ) if (!resolvedSettings.ok) { return { success: false, error: resolvedSettings.error } } @@ -767,6 +903,7 @@ export function registerFilesystemHandlers( _event, args: { worktreePath: string + repoId?: string base: string title: string body: string @@ -775,7 +912,12 @@ export function registerFilesystemHandlers( } ): Promise => { const discoveryHostKey = getCommitMessageModelDiscoveryHostKey(args.connectionId ?? null) - const resolvedSettings = resolveCommitMessageSettings(store.getSettings(), discoveryHostKey) + const resolvedSettings = resolveCommitMessageSettings( + store.getSettings(), + discoveryHostKey, + 'pullRequest', + await getRepoForSourceControlAi(store, args) + ) if (!resolvedSettings.ok) { return { success: false, error: resolvedSettings.error } } diff --git a/src/main/ipc/hosted-review.ts b/src/main/ipc/hosted-review.ts index a26560ce7..fe23909ab 100644 --- a/src/main/ipc/hosted-review.ts +++ b/src/main/ipc/hosted-review.ts @@ -119,7 +119,8 @@ export function registerHostedReviewHandlers(store: Store, stats: StatsCollector head: args.head, title: args.title, body: args.body, - draft: args.draft + draft: args.draft, + useTemplate: args.useTemplate }, repo.connectionId ?? null ) diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index edc339fe1..06d5c4166 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -14,6 +14,7 @@ import type { import { isFolderRepo } from '../../shared/repo-kind' import { DEFAULT_REPO_BADGE_COLOR } from '../../shared/constants' import { sanitizeRepoIcon } from '../../shared/repo-icon' +import { normalizeRepoSourceControlAiOverrides } from '../../shared/source-control-ai' import { invalidateAuthorizedRootsCache } from './filesystem-auth' import type { ChildProcess } from 'child_process' import { access, mkdir, readdir, rm } from 'fs/promises' @@ -496,6 +497,7 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v | 'issueSourcePreference' | 'externalWorktreeVisibility' | 'externalWorktreeVisibilityPromptDismissedAt' + | 'sourceControlAi' > > } @@ -552,6 +554,16 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v ) { delete updates.externalWorktreeVisibilityPromptDismissedAt } + if ('sourceControlAi' in updates && updates.sourceControlAi !== undefined) { + const normalizedSourceControlAi = normalizeRepoSourceControlAiOverrides( + updates.sourceControlAi + ) + if (normalizedSourceControlAi === undefined) { + delete updates.sourceControlAi + } else { + updates.sourceControlAi = normalizedSourceControlAi + } + } const updated = store.updateRepo(args.repoId, updates) if (updated) { notifyReposChanged(mainWindow) diff --git a/src/main/persistence.test.ts b/src/main/persistence.test.ts index f3e6e0da0..11d33e014 100644 --- a/src/main/persistence.test.ts +++ b/src/main/persistence.test.ts @@ -755,6 +755,143 @@ describe('Store', () => { expect(store.getRepos()).toHaveLength(1) }) + it('migrates legacy commit-message AI settings to source-control AI on load', async () => { + writeDataFile({ + schemaVersion: 1, + repos: [], + worktreeMeta: {}, + settings: { + commitMessageAi: { + enabled: true, + agentId: 'cursor', + selectedModelByAgent: { cursor: 'gpt-5.2' }, + selectedModelByAgentByHost: { 'ssh:conn-1': { cursor: 'remote-model' } }, + discoveredModelsByAgent: { + cursor: [{ id: 'gpt-5.2', label: 'GPT 5.2' }] + }, + discoveredModelsByAgentByHost: { + 'ssh:conn-1': { + cursor: [{ id: 'remote-model', label: 'Remote Model' }] + } + }, + selectedThinkingByModel: { 'gpt-5.2': 'high' }, + customPrompt: 'Use Conventional Commits.', + customAgentCommand: 'cursor-agent' + } + }, + ui: {}, + githubCache: { pr: {}, issue: {} }, + workspaceSession: {} + }) + + const store = await createStore() + const sourceControlAi = store.getSettings().sourceControlAi + + expect(sourceControlAi).toMatchObject({ + enabled: true, + agentId: 'cursor', + selectedModelByAgent: { cursor: 'gpt-5.2' }, + selectedThinkingByModel: { 'gpt-5.2': 'high' }, + customAgentCommand: 'cursor-agent', + instructionsByOperation: { + commitMessage: 'Use Conventional Commits.', + pullRequest: '', + branchName: 'Use Conventional Commits.' + } + }) + expect(sourceControlAi?.selectedModelByAgentByHost?.['ssh:conn-1']?.cursor).toBe('remote-model') + expect(sourceControlAi?.discoveredModelsByAgent?.cursor?.[0]?.id).toBe('gpt-5.2') + expect(sourceControlAi?.discoveredModelsByAgentByHost?.['ssh:conn-1']?.cursor?.[0]?.id).toBe( + 'remote-model' + ) + expect(store.getSettings().commitMessageAi?.customPrompt).toBe('Use Conventional Commits.') + }) + + it('merges rollback commit-message AI writes into existing source-control AI on load', async () => { + writeDataFile({ + schemaVersion: 1, + repos: [], + worktreeMeta: {}, + settings: { + sourceControlAi: { + enabled: true, + agentId: 'codex', + selectedModelByAgent: { codex: 'source-model' }, + selectedModelByAgentByHost: {}, + discoveredModelsByAgent: {}, + discoveredModelsByAgentByHost: {}, + selectedThinkingByModel: { 'source-model': 'medium' }, + customAgentCommand: 'codex', + instructionsByOperation: { + commitMessage: 'Source commit prompt', + pullRequest: 'Preserve PR prompt' + }, + modelOverridesByOperation: { + pullRequest: { + selectedModelByAgent: { claude: 'pr-model' }, + selectedThinkingByModel: { 'pr-model': 'high' } + } + }, + prCreationDefaults: { + draft: true, + openAfterCreate: true + } + }, + commitMessageAi: { + enabled: false, + agentId: 'claude', + selectedModelByAgent: { claude: 'legacy-model' }, + selectedModelByAgentByHost: { 'ssh:conn-1': { claude: 'remote-legacy-model' } }, + discoveredModelsByAgent: {}, + discoveredModelsByAgentByHost: {}, + selectedThinkingByModel: { 'legacy-model': 'high' }, + customPrompt: 'Rollback commit prompt', + customAgentCommand: 'claude' + } + }, + ui: {}, + githubCache: { pr: {}, issue: {} }, + workspaceSession: {} + }) + + const store = await createStore() + const sourceControlAi = store.getSettings().sourceControlAi + + expect(sourceControlAi).toMatchObject({ + enabled: false, + agentId: 'claude', + selectedModelByAgent: { codex: 'source-model' }, + selectedThinkingByModel: { 'source-model': 'medium' }, + customAgentCommand: 'claude', + instructionsByOperation: { + commitMessage: 'Rollback commit prompt', + pullRequest: 'Preserve PR prompt', + branchName: 'Rollback commit prompt' + }, + prCreationDefaults: { + draft: true, + openAfterCreate: true + } + }) + expect(sourceControlAi?.selectedModelByAgentByHost?.['ssh:conn-1']).toBeUndefined() + expect(sourceControlAi?.modelOverridesByOperation?.commitMessage).toEqual({ + selectedModelByAgent: { claude: 'legacy-model' }, + selectedModelByAgentByHost: { 'ssh:conn-1': { claude: 'remote-legacy-model' } }, + selectedThinkingByModel: { 'legacy-model': 'high' } + }) + expect(sourceControlAi?.modelOverridesByOperation?.pullRequest).toEqual({ + selectedModelByAgent: { claude: 'pr-model' }, + selectedThinkingByModel: { 'pr-model': 'high' } + }) + expect(store.getSettings().commitMessageAi).toMatchObject({ + enabled: false, + agentId: 'claude', + selectedModelByAgent: { claude: 'legacy-model' }, + customPrompt: 'Rollback commit prompt', + customAgentCommand: 'claude' + }) + }) + it('normalizes malformed visible task providers on load', async () => { writeDataFile({ schemaVersion: 1, @@ -1462,6 +1599,94 @@ describe('Store', () => { expect(updated!.externalWorktreeVisibilityLegacy).toBe(true) }) + it('updateRepo clears source-control AI overrides independently from other clearable fields', async () => { + const store = await createStore() + store.addRepo( + makeRepo({ + issueSourcePreference: 'origin', + sourceControlAi: { + instructionsByOperation: { commitMessage: 'Repo style' }, + prCreationDefaults: { draft: true } + } + }) + ) + + store.updateRepo('r1', { + issueSourcePreference: undefined, + sourceControlAi: undefined + }) + + expect(store.getRepo('r1')!.issueSourcePreference).toBeUndefined() + expect(store.getRepo('r1')!.sourceControlAi).toBeUndefined() + + store.flush() + const reloaded = await createStore() + expect(reloaded.getRepo('r1')!.issueSourcePreference).toBeUndefined() + expect(reloaded.getRepo('r1')!.sourceControlAi).toBeUndefined() + }) + + it('updateRepo normalizes source-control AI overrides before storing', async () => { + const store = await createStore() + store.addRepo(makeRepo()) + + const updated = store.updateRepo('r1', { + sourceControlAi: { + instructionsByOperation: { + commitMessage: 'Repo style', + pullRequest: 42, + unknown: 'ignored' + }, + prCreationDefaults: { + draft: true, + useTemplate: null, + openAfterCreate: 'yes' + }, + modelOverridesByOperation: { + commitMessage: { + selectedModelByAgent: { codex: 'gpt-5.4', claude: false }, + selectedThinkingByModel: { 'gpt-5.4': 'high', bad: true } + }, + unknown: { + selectedModelByAgent: { codex: 'ignored' } + } + } + } as never + }) + + expect(updated!.sourceControlAi).toEqual({ + instructionsByOperation: { + commitMessage: 'Repo style' + }, + prCreationDefaults: { + draft: true, + useTemplate: null + }, + modelOverridesByOperation: { + commitMessage: { + selectedModelByAgent: { codex: 'gpt-5.4' }, + selectedThinkingByModel: { 'gpt-5.4': 'high' } + } + } + }) + }) + + it('updateRepo ignores malformed source-control AI overrides without clearing existing overrides', async () => { + const store = await createStore() + store.addRepo( + makeRepo({ + sourceControlAi: { + instructionsByOperation: { commitMessage: 'Keep me' } + } + }) + ) + + const updated = store.updateRepo('r1', { sourceControlAi: 'bad' as never }) + + expect(updated!.sourceControlAi).toEqual({ + instructionsByOperation: { commitMessage: 'Keep me' } + }) + }) + // ── 8. setWorktreeMeta and getWorktreeMeta ───────────────────────── it('setWorktreeMeta creates meta with defaults for missing fields', async () => { @@ -1509,6 +1734,68 @@ describe('Store', () => { expect(updated.branchPrefix).toBe('git-username') }) + it('updateSettings keeps the legacy commit-message AI projection in sync', async () => { + const store = await createStore() + const current = store.getSettings().sourceControlAi! + + const updated = store.updateSettings({ + sourceControlAi: { + ...current, + enabled: true, + agentId: 'codex', + selectedModelByAgent: { codex: 'gpt-5.4' }, + selectedThinkingByModel: { 'gpt-5.4': 'high' }, + instructionsByOperation: { + commitMessage: 'Write concise commit messages.', + pullRequest: 'Write release-note-ready PR details.' + }, + customAgentCommand: '' + } + }) + + expect(updated.commitMessageAi).toMatchObject({ + enabled: true, + agentId: 'codex', + selectedModelByAgent: { codex: 'gpt-5.4' }, + selectedThinkingByModel: { 'gpt-5.4': 'high' }, + customPrompt: 'Write concise commit messages.', + customAgentCommand: '' + }) + }) + + it('updateSettings keeps source-control AI in sync for legacy commit-message updates', async () => { + const store = await createStore() + const current = store.getSettings().commitMessageAi! + + const updated = store.updateSettings({ + commitMessageAi: { + ...current, + enabled: false, + agentId: 'claude', + selectedModelByAgent: { claude: 'sonnet' }, + selectedThinkingByModel: { sonnet: 'medium' }, + customPrompt: 'Legacy settings update', + customAgentCommand: 'claude' + } + }) + + expect(updated.sourceControlAi).toMatchObject({ + enabled: false, + agentId: 'claude', + selectedModelByAgent: {}, + selectedThinkingByModel: {}, + customAgentCommand: 'claude', + instructionsByOperation: { + commitMessage: 'Legacy settings update', + branchName: 'Legacy settings update' + } + }) + expect(updated.sourceControlAi?.modelOverridesByOperation?.commitMessage).toEqual({ + selectedModelByAgent: { claude: 'sonnet' }, + selectedThinkingByModel: { sonnet: 'medium' } + }) + }) + it('updateSettings normalizes open-in applications', async () => { const store = await createStore() const updated = store.updateSettings({ diff --git a/src/main/persistence.ts b/src/main/persistence.ts index a2b4f86d9..27940c902 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -94,6 +94,13 @@ import { } from '../shared/workspace-statuses' import { isLegacyRepoForExternalWorktreeVisibility } from '../shared/worktree-ownership' import { sanitizeRepoIcon } from '../shared/repo-icon' +import { + mergeLegacyCommitMessageAiIntoSourceControlAi, + normalizeRepoSourceControlAiOverrides, + normalizeSourceControlAiSettings, + projectSourceControlAiToLegacyCommitMessageAi, + sourceControlAiSettingsFromLegacy +} from '../shared/source-control-ai' function encrypt(plaintext: string): string { if (!plaintext || !safeStorage.isEncryptionAvailable()) { @@ -1401,6 +1408,19 @@ export class Store { // Merge with defaults in case new fields were added const homeDir = homedir() const defaults = getDefaultPersistedState(homeDir) + const rawSourceControlAiMissing = parsed.settings?.sourceControlAi === undefined + if (rawSourceControlAiMissing) { + this.loadNeedsSave = true + } + const legacyCommitMessageAi = parsed.settings?.commitMessageAi + const migratedSourceControlAi = rawSourceControlAiMissing + ? sourceControlAiSettingsFromLegacy( + legacyCommitMessageAi ?? defaults.settings.commitMessageAi + ) + : mergeLegacyCommitMessageAiIntoSourceControlAi( + parsed.settings?.sourceControlAi, + legacyCommitMessageAi + ) // Why: before the layout-aware 'auto' mode shipped (issue #903), // terminalMacOptionAsAlt defaulted to 'true' globally. That silently // broke Option-layer characters (@ on Turkish via Option+Q, @ on @@ -1544,6 +1564,14 @@ export class Store { ), openInApplications: normalizeOpenInApplications(parsed.settings?.openInApplications), notifications: normalizeNotificationSettings(parsed.settings?.notifications), + sourceControlAi: migratedSourceControlAi, + // Why: new builds read sourceControlAi, but rollback builds still + // write commitMessageAi; after merging those writes, refresh the + // legacy projection for continued rollback compatibility. + commitMessageAi: projectSourceControlAiToLegacyCommitMessageAi( + migratedSourceControlAi, + parsed.settings?.commitMessageAi ?? defaults.settings.commitMessageAi + ), voice: { ...getDefaultVoiceSettings(), ...parsed.settings?.voice @@ -2089,9 +2117,11 @@ export class Store { | 'hookSettings' | 'worktreeBaseRef' | 'kind' + | 'symlinkPaths' | 'issueSourcePreference' | 'externalWorktreeVisibility' | 'externalWorktreeVisibilityPromptDismissedAt' + | 'sourceControlAi' > > ): Repo | null { @@ -2105,20 +2135,14 @@ export class Store { repo.externalWorktreeVisibilityLegacy === undefined ? isLegacyRepoForExternalWorktreeVisibility(repo) : undefined - // Why: `issueSourcePreference === undefined` in the patch means "reset to - // auto" (and the persisted record should drop the key, not preserve a - // stale explicit value via Object.assign's skip-on-undefined behavior). - // Without this delete branch, toggling explicit → auto would silently - // leave the old preference in place on disk. + // Why: selected repo fields use `undefined` as an explicit clear signal, + // so delete them before assigning the rest of the patch. if ( 'issueSourcePreference' in sanitizedUpdates && sanitizedUpdates.issueSourcePreference === undefined ) { delete repo.issueSourcePreference - const { issueSourcePreference: _drop, ...rest } = sanitizedUpdates - Object.assign(repo, rest) - } else { - Object.assign(repo, sanitizedUpdates) + delete sanitizedUpdates.issueSourcePreference } if ( 'externalWorktreeVisibility' in sanitizedUpdates && @@ -2128,6 +2152,20 @@ export class Store { // time visibility changes so later hide/show choices keep legacy safety. repo.externalWorktreeVisibilityLegacy = externalWorktreeVisibilityLegacy } + if ('sourceControlAi' in sanitizedUpdates && sanitizedUpdates.sourceControlAi === undefined) { + delete repo.sourceControlAi + delete sanitizedUpdates.sourceControlAi + } else if ('sourceControlAi' in sanitizedUpdates) { + const normalizedSourceControlAi = normalizeRepoSourceControlAiOverrides( + sanitizedUpdates.sourceControlAi + ) + if (normalizedSourceControlAi === undefined) { + delete sanitizedUpdates.sourceControlAi + } else { + sanitizedUpdates.sourceControlAi = normalizedSourceControlAi + } + } + Object.assign(repo, sanitizedUpdates) this.scheduleSave() return this.hydrateRepo(repo) } @@ -2514,6 +2552,22 @@ export class Store { sanitizedUpdates.telemetry !== undefined ? { ...this.state.settings.telemetry, ...sanitizedUpdates.telemetry } : this.state.settings.telemetry + if ('sourceControlAi' in sanitizedUpdates) { + const normalizedSourceControlAi = normalizeSourceControlAiSettings( + sanitizedUpdates.sourceControlAi, + this.state.settings.commitMessageAi + ) + sanitizedUpdates.sourceControlAi = normalizedSourceControlAi + sanitizedUpdates.commitMessageAi = projectSourceControlAiToLegacyCommitMessageAi( + normalizedSourceControlAi, + this.state.settings.commitMessageAi + ) + } else if ('commitMessageAi' in sanitizedUpdates) { + sanitizedUpdates.sourceControlAi = mergeLegacyCommitMessageAiIntoSourceControlAi( + this.state.settings.sourceControlAi, + sanitizedUpdates.commitMessageAi + ) + } this.state.settings = { ...this.state.settings, ...sanitizedUpdates, diff --git a/src/main/runtime/orca-runtime-git.test.ts b/src/main/runtime/orca-runtime-git.test.ts index 23e356994..3f228f5b4 100644 --- a/src/main/runtime/orca-runtime-git.test.ts +++ b/src/main/runtime/orca-runtime-git.test.ts @@ -150,7 +150,9 @@ describe('RuntimeGitCommands', () => { expect.objectContaining({ commitMessageAi: { enabled: true, agentId: 'codex' } }), - 'local' + 'local', + 'commitMessage', + null ) expect(mocks.generateCommitMessageFromContext).toHaveBeenCalledWith( context, @@ -203,7 +205,9 @@ describe('RuntimeGitCommands', () => { expect(mocks.resolveCommitMessageSettings).toHaveBeenCalledWith( expect.any(Object), - 'ssh:conn-1' + 'ssh:conn-1', + 'commitMessage', + null ) expect(mocks.generateCommitMessageFromContext).toHaveBeenCalledWith( context, diff --git a/src/main/runtime/orca-runtime-git.ts b/src/main/runtime/orca-runtime-git.ts index 928362092..0c81af3df 100644 --- a/src/main/runtime/orca-runtime-git.ts +++ b/src/main/runtime/orca-runtime-git.ts @@ -9,12 +9,15 @@ import type { GitUpstreamStatus, GitWorktreeInfo, GlobalSettings, + Repo, TuiAgent, Worktree } from '../../shared/types' import type { CommitMessageDraftContext } from '../../shared/commit-message-generation' import { getCommitMessageModelDiscoveryHostKey } from '../../shared/commit-message-host-key' import type { GitHistoryOptions, GitHistoryResult } from '../../shared/git-history' +import { mergeLegacyCommitMessageAiIntoSourceControlAi } from '../../shared/source-control-ai' +import type { SourceControlAiOperation } from '../../shared/source-control-ai-types' import { getRemoteFileUrl } from '../git/repo' import { abortMerge, @@ -62,11 +65,36 @@ import { gitExecFileAsync } from '../git/runner' export type ResolvedRuntimeGitWorktree = Worktree & { git: GitWorktreeInfo } type RuntimeCommitMessageSettingsOverride = Partial< - Pick + Pick< + GlobalSettings, + 'commitMessageAi' | 'sourceControlAi' | 'agentCmdOverrides' | 'enableGitHubAttribution' + > > & { commitMessageDiscoveryHostKey?: string } +function getRuntimeGitGenerationSettings( + settings: GlobalSettings, + settingsOverride: RuntimeCommitMessageSettingsOverride | undefined, + operation: SourceControlAiOperation +): GlobalSettings { + const mergedSettings = { + ...settings, + ...settingsOverride + } + if ( + settingsOverride?.commitMessageAi !== undefined && + settingsOverride.sourceControlAi === undefined + ) { + mergedSettings.sourceControlAi = mergeLegacyCommitMessageAiIntoSourceControlAi( + settings.sourceControlAi, + settingsOverride.commitMessageAi, + { pullRequestInstructionsFromLegacy: operation === 'pullRequest' } + ) + } + return mergedSettings +} + function normalizeRuntimeGitRelativePath(filePath: string): string { const relativePath = normalizeRuntimeRelativePath(filePath) if (relativePath === '') { @@ -80,7 +108,7 @@ function normalizeRuntimeGitRelativePath(filePath: string): string { export type RuntimeGitCommandHost = { resolveRuntimeGitTarget( selector: string - ): Promise<{ worktree: ResolvedRuntimeGitWorktree; connectionId?: string }> + ): Promise<{ worktree: ResolvedRuntimeGitWorktree; repo?: Repo; connectionId?: string }> getRuntimeSettings(): GlobalSettings getCommitMessageAgentEnvironment?(): CommitMessageAgentEnvironmentResolvers | undefined } @@ -388,11 +416,14 @@ export class RuntimeGitCommands { settingsOverride?.commitMessageDiscoveryHostKey ?? getCommitMessageModelDiscoveryHostKey(target.connectionId ?? null) const resolvedSettings = resolveCommitMessageSettings( - { - ...this.host.getRuntimeSettings(), - ...settingsOverride - }, - discoveryHostKey + getRuntimeGitGenerationSettings( + this.host.getRuntimeSettings(), + settingsOverride, + 'commitMessage' + ), + discoveryHostKey, + 'commitMessage', + target.repo ?? null ) if (!resolvedSettings.ok) { return { success: false, error: resolvedSettings.error } @@ -469,11 +500,14 @@ export class RuntimeGitCommands { settingsOverride?.commitMessageDiscoveryHostKey ?? getCommitMessageModelDiscoveryHostKey(target.connectionId ?? null) const resolvedSettings = resolveCommitMessageSettings( - { - ...this.host.getRuntimeSettings(), - ...settingsOverride - }, - discoveryHostKey + getRuntimeGitGenerationSettings( + this.host.getRuntimeSettings(), + settingsOverride, + 'pullRequest' + ), + discoveryHostKey, + 'pullRequest', + target.repo ?? null ) if (!resolvedSettings.ok) { return { success: false, error: resolvedSettings.error } diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 4c427565f..c05407c57 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -2102,11 +2102,11 @@ export class OrcaRuntimeService { private async resolveRuntimeGitTarget( worktreeSelector: string - ): Promise<{ worktree: ResolvedWorktree; connectionId?: string }> { + ): Promise<{ worktree: ResolvedWorktree; repo?: Repo; connectionId?: string }> { const store = this.requireStore() const worktree = await this.resolveWorktreeSelector(worktreeSelector) const repo = store.getRepo(worktree.repoId) - return { worktree, connectionId: repo?.connectionId ?? undefined } + return { worktree, repo, connectionId: repo?.connectionId ?? undefined } } onMobileSessionTabsChanged( @@ -5367,6 +5367,7 @@ export class OrcaRuntimeService { | 'issueSourcePreference' | 'externalWorktreeVisibility' | 'externalWorktreeVisibilityPromptDismissedAt' + | 'sourceControlAi' > > ): Promise { @@ -5722,7 +5723,8 @@ export class OrcaRuntimeService { head: args.head, title: args.title, body: args.body, - draft: args.draft + draft: args.draft, + useTemplate: args.useTemplate }, repo.connectionId ?? null ) diff --git a/src/main/runtime/rpc/methods/git-params.ts b/src/main/runtime/rpc/methods/git-params.ts index 87b5e09ff..6cb85a426 100644 --- a/src/main/runtime/rpc/methods/git-params.ts +++ b/src/main/runtime/rpc/methods/git-params.ts @@ -99,8 +99,33 @@ const CommitMessageAiSettings = z.object({ customAgentCommand: z.string() }) +const SourceControlAiSettings = CommitMessageAiSettings.omit({ customPrompt: true }).extend({ + instructionsByOperation: z.record(z.string(), z.string()).optional(), + modelOverridesByOperation: z + .record( + z.string(), + z.object({ + selectedModelByAgent: z.record(z.string(), z.string()).optional(), + selectedModelByAgentByHost: z + .record(z.string(), z.record(z.string(), z.string())) + .optional(), + selectedThinkingByModel: z.record(z.string(), z.string()).optional() + }) + ) + .optional(), + prCreationDefaults: z + .object({ + draft: z.boolean().optional(), + useTemplate: z.boolean().optional(), + generateDetailsOnOpen: z.boolean().optional(), + openAfterCreate: z.boolean().optional() + }) + .optional() +}) + export const GitGenerateCommitMessage = WorktreeSelector.extend({ commitMessageAi: CommitMessageAiSettings.optional(), + sourceControlAi: SourceControlAiSettings.optional(), agentCmdOverrides: z.record(z.string(), z.string()).optional(), enableGitHubAttribution: z.boolean().optional(), commitMessageDiscoveryHostKey: z.string().optional() diff --git a/src/main/runtime/rpc/methods/git.ts b/src/main/runtime/rpc/methods/git.ts index 00549101e..c84216e61 100644 --- a/src/main/runtime/rpc/methods/git.ts +++ b/src/main/runtime/rpc/methods/git.ts @@ -154,6 +154,7 @@ export const GIT_METHODS: RpcMethod[] = [ handler: async (params, { runtime }) => { if ( params.commitMessageAi === undefined && + params.sourceControlAi === undefined && params.agentCmdOverrides === undefined && params.enableGitHubAttribution === undefined && params.commitMessageDiscoveryHostKey === undefined @@ -164,6 +165,9 @@ export const GIT_METHODS: RpcMethod[] = [ ...(params.commitMessageAi !== undefined ? { commitMessageAi: params.commitMessageAi as GlobalSettings['commitMessageAi'] } : {}), + ...(params.sourceControlAi !== undefined + ? { sourceControlAi: params.sourceControlAi as GlobalSettings['sourceControlAi'] } + : {}), ...(params.agentCmdOverrides !== undefined ? { agentCmdOverrides: params.agentCmdOverrides as GlobalSettings['agentCmdOverrides'] @@ -210,6 +214,7 @@ export const GIT_METHODS: RpcMethod[] = [ } if ( params.commitMessageAi === undefined && + params.sourceControlAi === undefined && params.agentCmdOverrides === undefined && params.enableGitHubAttribution === undefined && params.commitMessageDiscoveryHostKey === undefined @@ -220,6 +225,9 @@ export const GIT_METHODS: RpcMethod[] = [ ...(params.commitMessageAi !== undefined ? { commitMessageAi: params.commitMessageAi as GlobalSettings['commitMessageAi'] } : {}), + ...(params.sourceControlAi !== undefined + ? { sourceControlAi: params.sourceControlAi as GlobalSettings['sourceControlAi'] } + : {}), ...(params.agentCmdOverrides !== undefined ? { agentCmdOverrides: params.agentCmdOverrides as GlobalSettings['agentCmdOverrides'] diff --git a/src/main/runtime/rpc/methods/hosted-review.ts b/src/main/runtime/rpc/methods/hosted-review.ts index f03f5193d..c556b348c 100644 --- a/src/main/runtime/rpc/methods/hosted-review.ts +++ b/src/main/runtime/rpc/methods/hosted-review.ts @@ -38,7 +38,8 @@ const HostedReviewCreate = z.object({ head: z.string().optional(), title: requiredString('Missing title'), body: z.string().optional(), - draft: z.boolean().optional() + draft: z.boolean().optional(), + useTemplate: z.boolean().optional() }) export const HOSTED_REVIEW_METHODS: RpcMethod[] = [ @@ -96,7 +97,8 @@ export const HOSTED_REVIEW_METHODS: RpcMethod[] = [ head: params.head, title: params.title, body: params.body, - draft: params.draft + draft: params.draft, + useTemplate: params.useTemplate }) }) ] diff --git a/src/main/runtime/rpc/methods/repo.ts b/src/main/runtime/rpc/methods/repo.ts index 951156eea..d3c999aa1 100644 --- a/src/main/runtime/rpc/methods/repo.ts +++ b/src/main/runtime/rpc/methods/repo.ts @@ -2,6 +2,7 @@ import { z } from 'zod' import { defineMethod, type RpcMethod } from '../core' import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas' import { sanitizeRepoIcon } from '../../../../shared/repo-icon' +import { normalizeRepoSourceControlAiOverrides } from '../../../../shared/source-control-ai' const RepoSelector = z.object({ repo: requiredString('Missing repo selector') @@ -28,6 +29,13 @@ const RepoSetBaseRef = z.object({ ref: requiredString('Missing base ref') }) +const RepoSourceControlAiOverrides = z + .unknown() + .optional() + .transform((value) => + value === undefined ? undefined : normalizeRepoSourceControlAiOverrides(value) + ) + const RepoUpdate = RepoSelector.extend({ updates: z.object({ displayName: OptionalString, @@ -42,7 +50,8 @@ const RepoUpdate = RepoSelector.extend({ symlinkPaths: z.array(z.string()).optional(), issueSourcePreference: z.enum(['auto', 'upstream', 'origin']).optional(), externalWorktreeVisibility: z.enum(['hide', 'show']).optional(), - externalWorktreeVisibilityPromptDismissedAt: z.number().finite().optional() + externalWorktreeVisibilityPromptDismissedAt: z.number().finite().optional(), + sourceControlAi: RepoSourceControlAiOverrides }) }) diff --git a/src/main/text-generation/commit-message-text-generation.test.ts b/src/main/text-generation/commit-message-text-generation.test.ts index 6e135e296..d267ce153 100644 --- a/src/main/text-generation/commit-message-text-generation.test.ts +++ b/src/main/text-generation/commit-message-text-generation.test.ts @@ -5,6 +5,8 @@ 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 { sourceControlAiSettingsFromLegacy } from '../../shared/source-control-ai' +import type { GlobalSettings } from '../../shared/types' import { cancelGenerateCommitMessageLocal, cancelGeneratePullRequestFieldsLocal, @@ -27,6 +29,10 @@ vi.mock('child_process', async (importOriginal) => { const spawnMock = vi.mocked(spawn) +function syncSourceControlAiFromLegacy(settings: GlobalSettings): void { + settings.sourceControlAi = sourceControlAiSettingsFromLegacy(settings.commitMessageAi) +} + function withPlatform(platform: NodeJS.Platform, fn: () => T): T { const original = process.platform Object.defineProperty(process, 'platform', { configurable: true, value: platform }) @@ -53,6 +59,7 @@ describe('resolveCommitMessageSettings', () => { customPrompt: 'Use Conventional Commits.', customAgentCommand: '' } + settings.sourceControlAi = undefined const result = resolveCommitMessageSettings(settings) @@ -77,6 +84,7 @@ describe('resolveCommitMessageSettings', () => { customPrompt: '', customAgentCommand: '' } + syncSourceControlAiFromLegacy(settings) const result = resolveCommitMessageSettings(settings) @@ -126,6 +134,7 @@ describe('resolveCommitMessageSettings', () => { customPrompt: '', customAgentCommand: '' } + syncSourceControlAiFromLegacy(settings) const result = resolveCommitMessageSettings(settings) @@ -154,6 +163,7 @@ describe('resolveCommitMessageSettings', () => { customPrompt: '', customAgentCommand: '' } + syncSourceControlAiFromLegacy(settings) const result = resolveCommitMessageSettings(settings, 'ssh:conn-1') @@ -176,6 +186,7 @@ describe('resolveCommitMessageSettings', () => { customPrompt: '', customAgentCommand: '' } + syncSourceControlAiFromLegacy(settings) const result = resolveCommitMessageSettings(settings) @@ -200,6 +211,7 @@ describe('resolveCommitMessageSettings', () => { customPrompt: '', customAgentCommand: '' } + syncSourceControlAiFromLegacy(settings) const result = resolveCommitMessageSettings(settings) @@ -222,6 +234,7 @@ describe('resolveCommitMessageSettings', () => { customPrompt: '', customAgentCommand: '' } + syncSourceControlAiFromLegacy(settings) const result = resolveCommitMessageSettings(settings) @@ -244,10 +257,11 @@ describe('resolveCommitMessageSettings', () => { customPrompt: '', customAgentCommand: ' ' } + syncSourceControlAiFromLegacy(settings) expect(resolveCommitMessageSettings(settings)).toEqual({ ok: false, - error: 'Custom command is empty. Add one in Settings -> Git -> AI Commit Messages.' + error: 'Custom command is empty. Add one in Settings -> Git -> Source Control AI.' }) }) }) @@ -1032,6 +1046,36 @@ describe('generateBranchNameFromContext', () => { error: 'Generated branch name was empty after sanitization.' }) }) + + it('includes branch-name custom instructions in the generated prompt', async () => { + let prompt = '' + await generateBranchNameFromContext( + { firstPrompt: 'Fix login flow' }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'agent', + customPrompt: 'Prefer auth terminology.' + }, + { + kind: 'remote', + cwd: '/repo', + missingBinaryLocation: 'remote PATH', + execute: async (plan) => { + prompt = plan.stdinPayload ?? '' + return { + stdout: 'fix-login-flow\n', + stderr: '', + exitCode: 0, + timedOut: false + } + } + } + ) + + expect(prompt).toContain('Additional user instructions:') + expect(prompt).toContain('Prefer auth terminology.') + }) }) describe('trimGeneratedCommitMessage', () => { diff --git a/src/main/text-generation/commit-message-text-generation.ts b/src/main/text-generation/commit-message-text-generation.ts index 85af201b3..c56d309b5 100644 --- a/src/main/text-generation/commit-message-text-generation.ts +++ b/src/main/text-generation/commit-message-text-generation.ts @@ -2,7 +2,7 @@ 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 type { GlobalSettings, Repo, TuiAgent } from '../../shared/types' import { buildCommitMessagePrompt, splitGeneratedCommitMessage, @@ -25,11 +25,7 @@ import { type BranchNameWorkContext } from '../../shared/branch-name-from-work' import { - CUSTOM_AGENT_ID, getCommitMessageAgentSpec, - getCommitMessageModel, - isCustomAgentId, - resolveCommitMessageAgentChoice, type CommitMessageAgentCapability, type CommitMessageModelCapability } from '../../shared/commit-message-agent-spec' @@ -39,6 +35,11 @@ import { type CommitMessagePlan } from '../../shared/commit-message-plan' import { LOCAL_COMMIT_MESSAGE_HOST_KEY } from '../../shared/commit-message-host-key' +import { + resolveSourceControlAiForOperation, + type ResolvedSourceControlAiGenerationParams +} from '../../shared/source-control-ai' +import type { SourceControlAiOperation } from '../../shared/source-control-ai-types' import { resolveCliCommand } from '../codex-cli/command' import { getSpawnArgsForWindows, @@ -50,14 +51,7 @@ import { withMacTailscaleDnsHint } from '../network/macos-tailscale-dns-diagnost 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 -} +export type GenerateCommitMessageParams = ResolvedSourceControlAiGenerationParams export type GenerateCommitMessageResult = | { success: true; message: string; agentLabel?: string } @@ -117,97 +111,26 @@ export function trimGeneratedCommitMessage(message: string): string { export function resolveCommitMessageSettings( settings: GlobalSettings, - discoveryHostKey = LOCAL_COMMIT_MESSAGE_HOST_KEY + discoveryHostKey = LOCAL_COMMIT_MESSAGE_HOST_KEY, + operation: SourceControlAiOperation = 'commitMessage', + repo?: Pick | null ): ResolveCommitMessageSettingsResult { - if (!settings.commitMessageAi?.enabled) { - return { ok: false, error: 'Enable AI commit messages in Settings -> Git.' } - } - return resolveTextGenerationParams(settings, discoveryHostKey) + const resolved = resolveSourceControlAiForOperation({ + settings, + repo, + operation, + discoveryHostKey + }) + return resolved.ok ? { ok: true, params: resolved.value.params } : resolved } -/** - * Resolve the agent/model generation parameters from the user's AI-commit-message - * configuration, without requiring that feature to be enabled. Other text-gen - * features (e.g. auto-rename branch from work) reuse the same configured agent. - */ export function resolveTextGenerationParams( settings: GlobalSettings, - discoveryHostKey = LOCAL_COMMIT_MESSAGE_HOST_KEY + discoveryHostKey = LOCAL_COMMIT_MESSAGE_HOST_KEY, + operation: SourceControlAiOperation = 'commitMessage', + repo?: Pick | null ): ResolveCommitMessageSettingsResult { - const config = settings.commitMessageAi - if (!config) { - return { ok: false, error: 'No text-generation agent is configured.' } - } - - const agentChoice = resolveCommitMessageAgentChoice(config.agentId, settings.defaultTuiAgent) - if (!agentChoice) { - return { - ok: false, - error: - `Default agent "${settings.defaultTuiAgent}" does not support AI commit messages. ` + - 'Choose Claude or Codex in Settings -> Git -> AI Commit Messages.' - } - } - - if (isCustomAgentId(agentChoice)) { - 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 - } - } - } - - const agentId = agentChoice - const spec = getCommitMessageAgentSpec(agentId) - if (!spec) { - return { ok: false, error: `Agent "${agentId}" does not support AI commit messages.` } - } - - const hostSelectedModels = config.selectedModelByAgentByHost?.[discoveryHostKey] - const legacySelectedModels = - discoveryHostKey === LOCAL_COMMIT_MESSAGE_HOST_KEY ? config.selectedModelByAgent : undefined - const persistedModelId = - hostSelectedModels?.[agentId] ?? legacySelectedModels?.[agentId] ?? spec.defaultModelId - const discoveredModels = - config.discoveredModelsByAgentByHost?.[discoveryHostKey]?.[agentId] ?? - (discoveryHostKey === LOCAL_COMMIT_MESSAGE_HOST_KEY - ? (config.discoveredModelsByAgent?.[agentId] ?? []) - : []) - const model = - spec.models.find((candidate) => candidate.id === persistedModelId) ?? - discoveredModels.find((candidate) => candidate.id === 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 } : {}) - } - } + return resolveCommitMessageSettings(settings, discoveryHostKey, operation, repo) } function sanitizeAgentFailureDetail(detail: string | null): string | null { @@ -857,7 +780,7 @@ export async function generateBranchNameFromContext( params: GenerateCommitMessageParams, target: CommitMessageGenerationTarget ): Promise { - const prompt = buildBranchNamePrompt(context) + const prompt = buildBranchNamePrompt(context, params.customPrompt ?? '') const planned = planCommitMessageGeneration(params, prompt) if (!planned.ok) { return { success: false, error: planned.error } diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index d778a44e7..6de1345b7 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -629,6 +629,7 @@ export type PreloadApi = { | 'issueSourcePreference' | 'externalWorktreeVisibility' | 'externalWorktreeVisibilityPromptDismissedAt' + | 'sourceControlAi' > > }) => Promise @@ -1643,6 +1644,7 @@ export type PreloadApi = { }) => Promise<{ success: boolean; error?: string }> generateCommitMessage: (args: { worktreePath: string + repoId?: string connectionId?: string }) => Promise< | { success: true; message: string; agentLabel?: string } @@ -1667,6 +1669,7 @@ export type PreloadApi = { }) => Promise generatePullRequestFields: (args: { worktreePath: string + repoId?: string base: string title: string body: string diff --git a/src/renderer/src/components/right-sidebar/CreatePullRequestDialog.tsx b/src/renderer/src/components/right-sidebar/CreatePullRequestDialog.tsx index c37d4ffe4..d97c74da8 100644 --- a/src/renderer/src/components/right-sidebar/CreatePullRequestDialog.tsx +++ b/src/renderer/src/components/right-sidebar/CreatePullRequestDialog.tsx @@ -21,6 +21,13 @@ import type { } from '../../../../shared/hosted-review' import { normalizeHostedReviewHeadRef } from '../../../../shared/hosted-review-refs' import { stripBaseRef, useCreatePullRequestDialogFields } from './useCreatePullRequestDialogFields' +import { + DEFAULT_SOURCE_CONTROL_AI_PR_CREATION_DEFAULTS, + resolveSourceControlAiForOperation, + resolveSourceControlAiPrCreationDefaults +} from '../../../../shared/source-control-ai' +import { getCommitMessageModelDiscoveryHostKeyForScope } from '../../../../shared/commit-message-host-key' +import { getRuntimeGitScope } from '@/runtime/runtime-git-client' type CreatePullRequestDialogProps = { open: boolean @@ -62,10 +69,33 @@ export function CreatePullRequestDialog({ onCreated }: CreatePullRequestDialogProps): React.JSX.Element { const settings = useAppStore((s) => s.settings) + const repo = useAppStore((s) => s.repos.find((candidate) => candidate.id === repoId) ?? null) const createHostedReview = useAppStore((s) => s.createHostedReview) const submitInFlightRef = useRef(false) const [submitting, setSubmitting] = useState(false) const [error, setError] = useState(null) + const prCreationDefaults = React.useMemo(() => { + if (!settings) { + return DEFAULT_SOURCE_CONTROL_AI_PR_CREATION_DEFAULTS + } + const hostKey = getCommitMessageModelDiscoveryHostKeyForScope( + getRuntimeGitScope(settings, repo?.connectionId) + ) + const resolved = resolveSourceControlAiForOperation({ + settings, + repo, + operation: 'pullRequest', + discoveryHostKey: hostKey, + prCreationProductDefaults: DEFAULT_SOURCE_CONTROL_AI_PR_CREATION_DEFAULTS + }) + return resolved.ok + ? resolved.value.prCreationDefaults + : resolveSourceControlAiPrCreationDefaults({ + settings, + repo, + prCreationProductDefaults: DEFAULT_SOURCE_CONTROL_AI_PR_CREATION_DEFAULTS + }) + }, [repo, settings]) const { aiGenerationEnabled, base, @@ -96,6 +126,7 @@ export function CreatePullRequestDialog({ eligibility, settings, submitting, + prCreationDefaults, onBranchChangedByGeneration }) @@ -139,10 +170,14 @@ export function CreatePullRequestDialog({ title: title.trim(), body, draft, - worktreePath + worktreePath, + useTemplate: prCreationDefaults.useTemplate }) if (result.ok) { await onCreated(result) + if (prCreationDefaults.openAfterCreate) { + window.api.shell.openUrl(result.url) + } onOpenChange(false) return } @@ -178,6 +213,8 @@ export function CreatePullRequestDialog({ onOpenChange, onPushBeforeCreate, pushBeforeCreate, + prCreationDefaults.openAfterCreate, + prCreationDefaults.useTemplate, repoPath, submitDisabled, title, diff --git a/src/renderer/src/components/right-sidebar/SourceControl.pr-generation-records.test.ts b/src/renderer/src/components/right-sidebar/SourceControl.pr-generation-records.test.ts index 69e452ed1..f7101d6bc 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.pr-generation-records.test.ts +++ b/src/renderer/src/components/right-sidebar/SourceControl.pr-generation-records.test.ts @@ -18,6 +18,13 @@ const seed = { draft: false } +const fieldRevisions = { + base: 0, + title: 0, + body: 0, + draft: 0 +} + function runningRecord(overrides: Partial = {}) { return { context: { @@ -29,6 +36,7 @@ function runningRecord(overrides: Partial = {}) { branch: 'feature-a' }, seed, + seedFieldRevisions: fieldRevisions, status: 'running' as const, result: null, error: null, @@ -59,28 +67,25 @@ describe('SourceControl pull request generation records', () => { ) }) - it('applies generated PR fields only to the original running request with unchanged seed', () => { + it('applies generated PR fields only to the original running request', () => { expect( shouldApplyPullRequestGenerationResult({ record: runningRecord(), - requestId: 3, - currentFields: seed + requestId: 3 }) ).toBe(true) expect( shouldApplyPullRequestGenerationResult({ record: runningRecord(), - requestId: 4, - currentFields: seed + requestId: 4 }) ).toBe(false) expect( shouldApplyPullRequestGenerationResult({ - record: runningRecord(), - requestId: 3, - currentFields: { ...seed, base: 'release' } + record: runningRecord({ status: 'succeeded' }), + requestId: 3 }) ).toBe(false) }) @@ -89,7 +94,7 @@ describe('SourceControl pull request generation records', () => { expect(arePullRequestGenerationFieldsEqual(seed, { ...seed, draft: true })).toBe(false) }) - it('rehydrates a completed result only when the seed still matches', () => { + it('rehydrates a completed result until it is marked hydrated', () => { const record = runningRecord({ status: 'succeeded', result: { ...seed, title: 'Generated title' } @@ -97,22 +102,13 @@ describe('SourceControl pull request generation records', () => { expect( shouldHydratePullRequestGenerationResult({ - record, - currentFields: seed + record }) ).toBe(true) expect( shouldHydratePullRequestGenerationResult({ - record, - currentFields: { ...seed, body: 'Edited body' } - }) - ).toBe(false) - - expect( - shouldHydratePullRequestGenerationResult({ - record: { ...record, hydrated: true }, - currentFields: seed + record: { ...record, hydrated: true } }) ).toBe(false) }) @@ -127,7 +123,8 @@ describe('SourceControl pull request generation records', () => { repoId: 'repo-1', branch: 'feature-a' }, - seed + seed, + fieldRevisions ) const records: Record = { 'wt-a': worktreeA @@ -147,7 +144,6 @@ describe('SourceControl pull request generation records', () => { const completedA = resolvePullRequestGenerationSuccess({ record: records['wt-a'], requestId: 1, - currentFields: seed, result: generated }) @@ -158,8 +154,7 @@ describe('SourceControl pull request generation records', () => { }) expect( shouldHydratePullRequestGenerationResult({ - record: completedA, - currentFields: seed + record: completedA }) ).toBe(true) }) diff --git a/src/renderer/src/components/right-sidebar/SourceControl.tsx b/src/renderer/src/components/right-sidebar/SourceControl.tsx index 66409f6c6..7a5006e99 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.tsx @@ -42,6 +42,7 @@ import { cn } from '@/lib/utils' import { WORKSPACE_FILE_PATH_MIME } from '@/lib/workspace-file-drag' import { isFolderRepo } from '../../../../shared/repo-kind' import { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from '@/components/ui/tooltip' +import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover' import { Button } from '@/components/ui/button' import { DropdownMenu, @@ -134,7 +135,11 @@ import { } from '@/runtime/runtime-git-client' import { getRuntimeRepoBaseRefDefault } from '@/runtime/runtime-repo-client' import { PullRequestIcon } from './checks-panel-content' -import { stripBaseRef, useCreatePullRequestDialogFields } from './useCreatePullRequestDialogFields' +import { + stripBaseRef, + useCreatePullRequestDialogFields, + type PullRequestFieldRevisions +} from './useCreatePullRequestDialogFields' import { GitHistoryPanel, type GitHistoryPanelState } from './GitHistoryPanel' import type { GitHistoryItem } from '../../../../shared/git-history' import { normalizeHostedReviewHeadRef } from '../../../../shared/hosted-review-refs' @@ -159,10 +164,26 @@ import { isCustomAgentId, resolveCommitMessageAgentChoice } from '../../../../shared/commit-message-agent-spec' +import { + DEFAULT_SOURCE_CONTROL_AI_PR_CREATION_DEFAULTS, + hasConfiguredSourceControlAiInstructions, + normalizeSourceControlAiSettings, + resolveSourceControlAiForOperation, + resolveSourceControlAiPrCreationDefaults +} from '../../../../shared/source-control-ai' +import type { SourceControlAiOperation } from '../../../../shared/source-control-ai-types' +import { getCommitMessageModelDiscoveryHostKeyForScope } from '../../../../shared/commit-message-host-key' +import { getRuntimeGitScope } from '@/runtime/runtime-git-client' +import { getRepositorySourceControlAiSectionId } from '@/components/settings/repository-settings-targets' import { hasExpandedCommitFailureDetails, summarizeCommitFailure } from './commit-failure-summary' export type SourceControlScope = 'all' | 'uncommitted' type SourceControlActionError = { kind: RemoteOpKind | 'abort_merge'; message: string } +type SourceControlAiInstructionGuidance = { + operation: SourceControlAiOperation + repoBacked: boolean + onOpenSettings: () => void +} const EMPTY_GIT_STATUS_ENTRIES: GitStatusEntry[] = [] const EMPTY_BRANCH_CHANGE_ENTRIES: GitBranchChangeEntry[] = [] @@ -242,6 +263,7 @@ export type PullRequestGenerationStatus = 'idle' | 'running' | 'canceled' | 'fai export type PullRequestGenerationRecord = { context: PullRequestGenerationContext seed: PullRequestGenerationFields + seedFieldRevisions: PullRequestFieldRevisions status: PullRequestGenerationStatus result: PullRequestGenerationFields | null error: string | null @@ -411,42 +433,31 @@ export function arePullRequestGenerationFieldsEqual( export function shouldApplyPullRequestGenerationResult({ record, - requestId, - currentFields + requestId }: { record: PullRequestGenerationRecord | null | undefined requestId: number - currentFields: PullRequestGenerationFields }): boolean { - return ( - record?.context.requestId === requestId && - record.status === 'running' && - arePullRequestGenerationFieldsEqual(record.seed, currentFields) - ) + return record?.context.requestId === requestId && record.status === 'running' } export function shouldHydratePullRequestGenerationResult({ - record, - currentFields + record }: { record: PullRequestGenerationRecord | null | undefined - currentFields: PullRequestGenerationFields }): boolean { - return ( - record?.status === 'succeeded' && - record.result !== null && - !record.hydrated && - arePullRequestGenerationFieldsEqual(record.seed, currentFields) - ) + return record?.status === 'succeeded' && record.result !== null && !record.hydrated } export function createRunningPullRequestGenerationRecord( context: PullRequestGenerationContext, - seed: PullRequestGenerationFields + seed: PullRequestGenerationFields, + seedFieldRevisions: PullRequestFieldRevisions ): PullRequestGenerationRecord { return { context, seed, + seedFieldRevisions, status: 'running', result: null, error: null, @@ -457,26 +468,15 @@ export function createRunningPullRequestGenerationRecord( export function resolvePullRequestGenerationSuccess({ record, requestId, - currentFields, result }: { record: PullRequestGenerationRecord | null | undefined requestId: number - currentFields: PullRequestGenerationFields result: PullRequestGenerationFields }): PullRequestGenerationRecord | null { if (!record || record.context.requestId !== requestId || record.status !== 'running') { return null } - if (!shouldApplyPullRequestGenerationResult({ record, requestId, currentFields })) { - return { - ...record, - status: 'failed', - result: null, - error: 'Fields changed while generating. Run generate again for a fresh draft.', - hydrated: false - } - } return { ...record, status: 'succeeded', @@ -927,6 +927,8 @@ function SourceControlInner(): React.JSX.Element { const inFlightRemoteOpKind = useAppStore((s) => s.inFlightRemoteOpKind) const settings = useAppStore((s) => s.settings) const updateSettings = useAppStore((s) => s.updateSettings) + const openSettingsTarget = useAppStore((s) => s.openSettingsTarget) + const openSettingsPage = useAppStore((s) => s.openSettingsPage) const hostedReviewCache = useAppStore((s) => s.hostedReviewCache) const fetchHostedReviewForBranch = useAppStore((s) => s.fetchHostedReviewForBranch) const getHostedReviewCreationEligibility = useAppStore( @@ -1156,12 +1158,17 @@ function SourceControlInner(): React.JSX.Element { const createPrError = createPrErrors[activeWorktreeId ?? ''] ?? null const prGenerationRequestSeqRef = useRef(0) const prGenerationInFlightRef = useRef>({}) - const prFieldsByGenerationKeyRef = useRef>({}) const [prGenerationRecords, setPrGenerationRecords] = useState({}) - const commitMessageAi = useAppStore((s) => s.settings?.commitMessageAi) + const sourceControlAi = useMemo(() => { + const normalized = normalizeSourceControlAiSettings( + settings?.sourceControlAi, + settings?.commitMessageAi + ) + return settings ? normalized : { ...normalized, enabled: false } + }, [settings]) const effectiveCommitMessageAgentId = useMemo( - () => resolveCommitMessageAgentChoice(commitMessageAi?.agentId, settings?.defaultTuiAgent), - [commitMessageAi?.agentId, settings?.defaultTuiAgent] + () => resolveCommitMessageAgentChoice(sourceControlAi.agentId, settings?.defaultTuiAgent), + [sourceControlAi.agentId, settings?.defaultTuiAgent] ) const filterInputRef = useRef(null) const commitMessage = readCommitDraftForWorktree(commitDrafts, activeWorktreeId) @@ -1180,6 +1187,62 @@ function SourceControlInner(): React.JSX.Element { const isFolder = activeRepo ? isFolderRepo(activeRepo) : false const worktreePath = activeWorktree?.path ?? null const branchName = activeWorktree?.branch.replace(/^refs\/heads\//, '') ?? 'HEAD' + const sourceControlAiDiscoveryHostKey = useMemo( + () => + getCommitMessageModelDiscoveryHostKeyForScope( + getRuntimeGitScope(settings, activeRepo?.connectionId) + ), + [activeRepo?.connectionId, settings] + ) + const resolvedPrCreationDefaults = useMemo(() => { + if (!settings) { + return DEFAULT_SOURCE_CONTROL_AI_PR_CREATION_DEFAULTS + } + const resolved = resolveSourceControlAiForOperation({ + settings, + repo: activeRepo ?? null, + operation: 'pullRequest', + discoveryHostKey: sourceControlAiDiscoveryHostKey, + prCreationProductDefaults: DEFAULT_SOURCE_CONTROL_AI_PR_CREATION_DEFAULTS + }) + return resolved.ok + ? resolved.value.prCreationDefaults + : resolveSourceControlAiPrCreationDefaults({ + settings, + repo: activeRepo ?? null, + prCreationProductDefaults: DEFAULT_SOURCE_CONTROL_AI_PR_CREATION_DEFAULTS + }) + }, [activeRepo, settings, sourceControlAiDiscoveryHostKey]) + const shouldShowCommitInstructionGuidance = + Boolean(settings) && + !hasConfiguredSourceControlAiInstructions({ + settings: settings!, + repo: activeRepo ?? null, + operation: 'commitMessage' + }) + const shouldShowPullRequestInstructionGuidance = + Boolean(settings) && + !hasConfiguredSourceControlAiInstructions({ + settings: settings!, + repo: activeRepo ?? null, + operation: 'pullRequest' + }) + const openSourceControlAiSettings = useCallback((): void => { + if (activeRepo) { + openSettingsTarget({ + pane: 'repo', + repoId: activeRepo.id, + sectionId: getRepositorySourceControlAiSectionId(activeRepo.id) + }) + } else { + openSettingsTarget({ + pane: 'git', + repoId: null, + sectionId: 'source-control-ai-settings' + }) + } + openSettingsPage() + }, [activeRepo, openSettingsPage, openSettingsTarget]) const activePullRequestGenerationKey = getPullRequestGenerationRecordKey({ worktreeId: activeWorktreeId, worktreePath, @@ -1840,17 +1903,17 @@ function SourceControlInner(): React.JSX.Element { if (generateInFlightRef.current[activeWorktreeId]) { return } - if (!commitMessageAi?.enabled || !effectiveCommitMessageAgentId) { + if (!sourceControlAi.enabled || !effectiveCommitMessageAgentId) { return } if (isCustomAgentId(effectiveCommitMessageAgentId)) { - const command = commitMessageAi.customAgentCommand?.trim() ?? '' + const command = sourceControlAi.customAgentCommand?.trim() ?? '' if (!command) { setGenerateErrors((prev) => ({ ...prev, [activeWorktreeId]: - 'Custom command is empty. Add one in Settings → Git → AI Commit Messages.' + 'Custom command is empty. Add one in Settings -> Git -> Source Control AI.' })) return } @@ -1903,7 +1966,7 @@ function SourceControlInner(): React.JSX.Element { setGenerateInFlightByWorktree((prev) => ({ ...prev, [activeWorktreeId]: false })) generateInFlightRef.current[activeWorktreeId] = false } - }, [activeWorktreeId, commitMessageAi, effectiveCommitMessageAgentId, worktreePath]) + }, [activeWorktreeId, effectiveCommitMessageAgentId, sourceControlAi, worktreePath]) const handleCancelGenerate = useCallback((): void => { if (!activeWorktreeId || !worktreePath) { @@ -2144,7 +2207,10 @@ function SourceControlInner(): React.JSX.Element { }, [refreshActiveGitStatusAfterMutation]) const handleGeneratePullRequestFieldsForActive = useCallback( - async (fields: PullRequestGenerationFields): Promise => { + async ( + fields: PullRequestGenerationFields, + fieldRevisions: PullRequestFieldRevisions + ): Promise => { if (!activeRepo || !activePullRequestGenerationKey || !worktreePath || !branchName) { return } @@ -2164,10 +2230,9 @@ function SourceControlInner(): React.JSX.Element { } const seed = { ...fields } prGenerationInFlightRef.current[generationKey] = true - prFieldsByGenerationKeyRef.current[generationKey] = seed setPrGenerationRecords((prev) => ({ ...prev, - [generationKey]: createRunningPullRequestGenerationRecord(context, seed) + [generationKey]: createRunningPullRequestGenerationRecord(context, seed, fieldRevisions) })) try { @@ -2208,11 +2273,9 @@ function SourceControlInner(): React.JSX.Element { if (!record) { return prev } - const currentFields = prFieldsByGenerationKeyRef.current[generationKey] ?? record.seed const nextRecord = resolvePullRequestGenerationSuccess({ record, requestId, - currentFields, result: { base: stripBaseRef(result.fields.base), title: result.fields.title, @@ -2327,7 +2390,8 @@ function SourceControlInner(): React.JSX.Element { generateDisabled: prGenerateDisabled, generateDisabledReason: prGenerateDisabledReason, handleGenerate: handleGeneratePullRequestFields, - handleCancelGenerate: handleCancelGeneratePullRequestFields + handleCancelGenerate: handleCancelGeneratePullRequestFields, + applyGeneratedFields: applyGeneratedPullRequestFields } = useCreatePullRequestDialogFields({ open: hostedReviewCreation?.canCreate === true, repoId: activeRepo?.id ?? '', @@ -2337,42 +2401,18 @@ function SourceControlInner(): React.JSX.Element { eligibility: hostedReviewCreation, settings, submitting: isCreatingPr, + prCreationDefaults: resolvedPrCreationDefaults, onBranchChangedByGeneration: handleBranchChangedByPullRequestGeneration, generation: { generating: activePullRequestGenerationRecord?.status === 'running', generateError: activePullRequestGenerationRecord?.error ?? null, - onGenerate: (fields) => { - void handleGeneratePullRequestFieldsForActive(fields) + onGenerate: (fields, fieldRevisions) => { + void handleGeneratePullRequestFieldsForActive(fields, fieldRevisions) }, onCancelGenerate: handleCancelGeneratePullRequestFieldsForActive } }) - useEffect(() => { - if (!activePullRequestGenerationKey) { - return - } - if ( - activePullRequestGenerationRecord?.status === 'succeeded' && - !activePullRequestGenerationRecord.hydrated - ) { - return - } - prFieldsByGenerationKeyRef.current[activePullRequestGenerationKey] = { - base: prBase, - title: prTitle, - body: prBody, - draft: prDraft - } - }, [ - activePullRequestGenerationKey, - activePullRequestGenerationRecord, - prBase, - prBody, - prDraft, - prTitle - ]) - useEffect(() => { if ( !activePullRequestGenerationKey || @@ -2383,37 +2423,15 @@ function SourceControlInner(): React.JSX.Element { ) { return } - const currentFields = prFieldsByGenerationKeyRef.current[activePullRequestGenerationKey] ?? { - base: prBase, - title: prTitle, - body: prBody, - draft: prDraft - } if ( !shouldHydratePullRequestGenerationResult({ - record: activePullRequestGenerationRecord, - currentFields + record: activePullRequestGenerationRecord }) ) { - setPrGenerationRecords((prev) => ({ - ...prev, - [activePullRequestGenerationKey]: { - ...activePullRequestGenerationRecord, - status: 'failed', - error: 'Fields changed while generating. Run generate again for a fresh draft.', - hydrated: false - } - })) return } const result = activePullRequestGenerationRecord.result - setPrBase(result.base) - setPrBaseQuery('') - setPrBaseResults([]) - setPrTitle(result.title) - setPrBody(result.body) - setPrDraft(result.draft) - prFieldsByGenerationKeyRef.current[activePullRequestGenerationKey] = result + applyGeneratedPullRequestFields(result, activePullRequestGenerationRecord.seedFieldRevisions) setPrGenerationRecords((prev) => ({ ...prev, [activePullRequestGenerationKey]: { @@ -2424,16 +2442,7 @@ function SourceControlInner(): React.JSX.Element { }, [ activePullRequestGenerationKey, activePullRequestGenerationRecord, - prBase, - prBody, - prDraft, - prTitle, - setPrBase, - setPrBaseQuery, - setPrBaseResults, - setPrBody, - setPrDraft, - setPrTitle + applyGeneratedPullRequestFields ]) useEffect(() => { @@ -2545,11 +2554,15 @@ function SourceControlInner(): React.JSX.Element { title, body: prBody, draft: prDraft, - worktreePath + worktreePath, + useTemplate: resolvedPrCreationDefaults.useTemplate }) if (result.ok) { await handlePullRequestCreated(result) + if (resolvedPrCreationDefaults.openAfterCreate) { + window.api.shell.openUrl(result.url) + } return } @@ -2592,6 +2605,8 @@ function SourceControlInner(): React.JSX.Element { prDraft, prGenerating, prTitle, + resolvedPrCreationDefaults.openAfterCreate, + resolvedPrCreationDefaults.useTemplate, worktreePath ]) @@ -4077,6 +4092,15 @@ function SourceControlInner(): React.JSX.Element { generateDisabled={prGenerateDisabled} generateDisabledReason={prGenerateDisabledReason} generateError={prGenerateError} + instructionGuidance={ + prAiGenerationEnabled && shouldShowPullRequestInstructionGuidance + ? { + operation: 'pullRequest', + repoBacked: Boolean(activeRepo), + onOpenSettings: openSourceControlAiSettings + } + : undefined + } createError={createPrError} isCreating={isCreatingPr} primaryAction={primaryAction} @@ -4097,18 +4121,27 @@ function SourceControlInner(): React.JSX.Element { isFixingCommitFailureWithAI={isLaunchingCommitFailureAgent} groupId={activeGroupId ?? activeWorktreeId} showComposer={!(scope === 'all' && showGenericEmptyState)} - aiEnabled={commitMessageAi?.enabled === true} + aiEnabled={sourceControlAi.enabled === true} aiAgentConfigured={ - commitMessageAi?.enabled === true && + sourceControlAi.enabled === true && effectiveCommitMessageAgentId !== 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. (!isCustomAgentId(effectiveCommitMessageAgentId) || - (commitMessageAi.customAgentCommand ?? '').trim().length > 0) + (sourceControlAi.customAgentCommand ?? '').trim().length > 0) } isGenerating={isGenerating} generateError={generateError} + instructionGuidance={ + sourceControlAi.enabled && shouldShowCommitInstructionGuidance + ? { + operation: 'commitMessage', + repoBacked: Boolean(activeRepo), + onOpenSettings: openSourceControlAiSettings + } + : undefined + } stagedCount={grouped.staged.length} hasUnresolvedConflicts={unresolvedConflicts.length > 0} isRemoteOperationActive={isRemoteOperationActive || isAbortingMerge} @@ -4566,6 +4599,7 @@ type PullRequestComposerProps = { generateDisabled: boolean generateDisabledReason?: string generateError: string | null + instructionGuidance?: SourceControlAiInstructionGuidance createError: string | null isCreating: boolean primaryAction: PrimaryAction @@ -4576,6 +4610,51 @@ type PullRequestComposerProps = { onDropdownAction: (kind: DropdownActionKind) => void } +function SourceControlAiInstructionGuidanceButton({ + guidance +}: { + guidance: SourceControlAiInstructionGuidance +}): React.JSX.Element { + const label = + guidance.operation === 'commitMessage' + ? 'Add commit message instructions' + : 'Add pull request instructions' + const target = guidance.repoBacked + ? 'Repo Settings > Source Control AI' + : 'Settings > Git > Source Control AI' + return ( + + + + + +
+

{label}

+

+ No instructions are configured for this generator. Add them in {target}. +

+
+ +
+
+ ) +} + function PullRequestComposer({ branch, base, @@ -4596,6 +4675,7 @@ function PullRequestComposer({ generateDisabled, generateDisabledReason, generateError, + instructionGuidance, createError, isCreating, primaryAction, @@ -4670,6 +4750,9 @@ function PullRequestComposer({ ) ) : null} + {instructionGuidance ? ( + + ) : null} {/* Why: a single line that shows the head→base flow plain-language so @@ -4986,6 +5069,7 @@ type CommitAreaProps = { aiAgentConfigured: boolean isGenerating: boolean generateError: string | null + instructionGuidance?: SourceControlAiInstructionGuidance stagedCount: number hasUnresolvedConflicts: boolean isRemoteOperationActive: boolean @@ -5015,6 +5099,7 @@ export function CommitArea({ aiAgentConfigured, isGenerating, generateError, + instructionGuidance, stagedCount, hasUnresolvedConflicts, isRemoteOperationActive, @@ -5126,7 +5211,7 @@ export function CommitArea({ } else if (isCommitting) { generateDisabledReason = 'Commit in progress…' } else if (!aiAgentConfigured) { - generateDisabledReason = 'Pick an agent in Settings → AI Commit Messages.' + generateDisabledReason = 'Pick an agent in Settings -> Git -> Source Control AI.' } else if (stagedCount === 0) { generateDisabledReason = 'Stage at least one file to generate a message.' } else if (hasMessage) { @@ -5154,7 +5239,7 @@ export function CommitArea({ // 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 ? (instructionGuidance ? 'pr-12' : 'pr-7') : '' }`} /> {showGenerate && @@ -5182,16 +5267,21 @@ export function CommitArea({ ) : ( - +
+ {instructionGuidance ? ( + + ) : null} + +
))} ) : null} diff --git a/src/renderer/src/components/right-sidebar/useCreatePullRequestDialogFields.ts b/src/renderer/src/components/right-sidebar/useCreatePullRequestDialogFields.ts index e9e5072d9..23ba2988e 100644 --- a/src/renderer/src/components/right-sidebar/useCreatePullRequestDialogFields.ts +++ b/src/renderer/src/components/right-sidebar/useCreatePullRequestDialogFields.ts @@ -18,6 +18,20 @@ import { } from '../../../../shared/commit-message-agent-spec' import type { HostedReviewCreationEligibility } from '../../../../shared/hosted-review' import { normalizeHostedReviewBaseRef } from '../../../../shared/hosted-review-refs' +import { + DEFAULT_SOURCE_CONTROL_AI_PR_CREATION_DEFAULTS, + normalizeSourceControlAiSettings +} from '../../../../shared/source-control-ai' +import type { SourceControlAiPrCreationDefaults } from '../../../../shared/source-control-ai-types' + +type PullRequestFieldName = 'base' | 'title' | 'body' | 'draft' +export type PullRequestFieldRevisions = Record +type PullRequestDraftFields = { + base: string + title: string + body: string + draft: boolean +} type UseCreatePullRequestDialogFieldsOptions = { open: boolean @@ -28,24 +42,31 @@ type UseCreatePullRequestDialogFieldsOptions = { eligibility: HostedReviewCreationEligibility | null settings: AppState['settings'] submitting: boolean + prCreationDefaults?: SourceControlAiPrCreationDefaults onBranchChangedByGeneration?: () => Promise generation?: { generating: boolean generateError: string | null - onGenerate: (fields: { base: string; title: string; body: string; draft: boolean }) => void + onGenerate: (fields: PullRequestDraftFields, fieldRevisions: PullRequestFieldRevisions) => void onCancelGenerate: () => void } } type GenerationSeed = { requestId: number - base: string - title: string - body: string - draft: boolean + fieldRevisions: PullRequestFieldRevisions context: RuntimeGitContext } +function createInitialPullRequestFieldRevisions(): PullRequestFieldRevisions { + return { + base: 0, + title: 0, + body: 0, + draft: 0 + } +} + export function stripBaseRef(ref: string): string { return normalizeHostedReviewBaseRef(ref) } @@ -59,24 +80,33 @@ export function useCreatePullRequestDialogFields({ eligibility, settings, submitting, + prCreationDefaults, onBranchChangedByGeneration, generation }: UseCreatePullRequestDialogFieldsOptions) { - const commitMessageAi = settings?.commitMessageAi + const normalizedSourceControlAi = normalizeSourceControlAiSettings( + settings?.sourceControlAi, + settings?.commitMessageAi + ) + const sourceControlAi = settings + ? normalizedSourceControlAi + : { ...normalizedSourceControlAi, enabled: false } const effectiveCommitMessageAgentId = resolveCommitMessageAgentChoice( - commitMessageAi?.agentId, + sourceControlAi.agentId, settings?.defaultTuiAgent ) + const resolvedPrDefaults = { + ...DEFAULT_SOURCE_CONTROL_AI_PR_CREATION_DEFAULTS, + ...prCreationDefaults + } const initializedFromEligibilityRef = useRef(null) + const autoGeneratedForKeyRef = useRef(null) const generateInFlightRef = useRef(false) const generationRequestIdRef = useRef(0) const generationSeedRef = useRef(null) - const latestFieldsRef = useRef({ - base: '', - title: '', - body: '', - draft: false - }) + const fieldRevisionsRef = useRef( + createInitialPullRequestFieldRevisions() + ) const [base, setBase] = useState('') const [title, setTitle] = useState('') const [body, setBody] = useState('') @@ -88,9 +118,73 @@ export function useCreatePullRequestDialogFields({ const [generateError, setGenerateError] = useState(null) const hasExternalGeneration = Boolean(generation) - useEffect(() => { - latestFieldsRef.current = { base, title, body, draft } - }, [base, body, draft, title]) + const markFieldDirty = useCallback((field: PullRequestFieldName): void => { + fieldRevisionsRef.current = { + ...fieldRevisionsRef.current, + [field]: fieldRevisionsRef.current[field] + 1 + } + }, []) + + const setUserBase = useCallback( + (value: string): void => { + markFieldDirty('base') + setBase(value) + }, + [markFieldDirty] + ) + const setUserTitle = useCallback( + (value: string): void => { + markFieldDirty('title') + setTitle(value) + }, + [markFieldDirty] + ) + const setUserBody = useCallback( + (value: string): void => { + markFieldDirty('body') + setBody(value) + }, + [markFieldDirty] + ) + const setUserDraft = useCallback( + (value: boolean): void => { + markFieldDirty('draft') + setDraft(value) + }, + [markFieldDirty] + ) + + const applyGeneratedFields = useCallback( + ( + fields: PullRequestDraftFields, + seedRevisions: PullRequestFieldRevisions + ): PullRequestDraftFields => { + const currentRevisions = fieldRevisionsRef.current + const nextFields = { base, title, body, draft } + // Why: AI generation runs asynchronously; only fields untouched since + // the request started are safe to replace with generated output. + if (currentRevisions.base === seedRevisions.base) { + nextFields.base = stripBaseRef(fields.base) + setBase(nextFields.base) + setBaseQuery('') + setBaseResults([]) + } + if (currentRevisions.title === seedRevisions.title) { + nextFields.title = fields.title + setTitle(fields.title) + } + if (currentRevisions.body === seedRevisions.body) { + nextFields.body = fields.body + setBody(fields.body) + } + if (currentRevisions.draft === seedRevisions.draft) { + nextFields.draft = fields.draft + setDraft(fields.draft) + } + return nextFields + }, + [base, body, draft, title] + ) useEffect(() => { if (!open) { @@ -105,6 +199,7 @@ export function useCreatePullRequestDialogFields({ generateInFlightRef.current = false generationSeedRef.current = null initializedFromEligibilityRef.current = null + autoGeneratedForKeyRef.current = null setGenerating(false) setGenerateError(null) } @@ -120,18 +215,27 @@ export function useCreatePullRequestDialogFields({ // Why: eligibility refreshes while the dialog is open; only seed fields // once per branch so late refreshes do not overwrite user edits. initializedFromEligibilityRef.current = initializationKey + autoGeneratedForKeyRef.current = null + fieldRevisionsRef.current = createInitialPullRequestFieldRevisions() const initialBase = eligibility.defaultBaseRef ?? '' setBase(stripBaseRef(initialBase)) - // Why: PR reviewer-facing copy should be explicit or AI-generated on - // request; commit-subject summaries were too noisy as automatic defaults. - setTitle('') - setBody('') - setDraft(false) + setTitle(eligibility.title ?? '') + setBody(eligibility.body ?? '') + setDraft(resolvedPrDefaults.draft) setBaseQuery('') setBaseResults([]) setBaseSearchError(null) setGenerateError(null) - }, [branch, eligibility, hasExternalGeneration, open, repoId, worktreeId, worktreePath]) + }, [ + branch, + eligibility, + hasExternalGeneration, + open, + repoId, + resolvedPrDefaults.draft, + worktreeId, + worktreePath + ]) const effectiveGenerating = generation?.generating ?? generating const effectiveGenerateError = generation?.generateError ?? generateError @@ -184,15 +288,15 @@ export function useCreatePullRequestDialogFields({ let generateDisabledReason: string | undefined if (submitting) { generateDisabledReason = 'Create PR in progress...' - } else if (!commitMessageAi?.enabled) { - generateDisabledReason = 'Enable AI commit messages in Settings -> Git.' + } else if (!sourceControlAi.enabled) { + generateDisabledReason = 'Enable Source Control AI in Settings -> Git.' } else if (!effectiveCommitMessageAgentId) { - generateDisabledReason = 'Pick an agent in Settings -> Git -> AI Commit Messages.' + generateDisabledReason = 'Pick an agent in Settings -> Git -> Source Control AI.' } else if (isCustomAgentId(effectiveCommitMessageAgentId)) { - const command = commitMessageAi.customAgentCommand?.trim() ?? '' + const command = sourceControlAi.customAgentCommand?.trim() ?? '' if (!command) { generateDisabledReason = - 'Custom command is empty. Add one in Settings -> Git -> AI Commit Messages.' + 'Custom command is empty. Add one in Settings -> Git -> Source Control AI.' } } else if (!base.trim()) { generateDisabledReason = 'Choose a base branch before generating.' @@ -204,7 +308,7 @@ export function useCreatePullRequestDialogFields({ return } if (generation) { - generation.onGenerate({ base, title, body, draft }) + generation.onGenerate({ base, title, body, draft }, { ...fieldRevisionsRef.current }) return } const requestId = generationRequestIdRef.current + 1 @@ -216,7 +320,11 @@ export function useCreatePullRequestDialogFields({ worktreePath, connectionId } - const seed = { requestId, base, title, body, draft, context: requestContext } + const seed = { + requestId, + fieldRevisions: { ...fieldRevisionsRef.current }, + context: requestContext + } generationSeedRef.current = seed generateInFlightRef.current = true setGenerating(true) @@ -245,24 +353,10 @@ export function useCreatePullRequestDialogFields({ } const currentSeed = generationSeedRef.current - const latestFields = latestFieldsRef.current - if ( - !currentSeed || - currentSeed.requestId !== requestId || - currentSeed.base !== latestFields.base || - currentSeed.title !== latestFields.title || - currentSeed.body !== latestFields.body || - currentSeed.draft !== latestFields.draft - ) { - setGenerateError('Fields changed while generating. Run generate again for a fresh draft.') + if (!currentSeed || currentSeed.requestId !== requestId) { return } - setBase(stripBaseRef(result.fields.base)) - setBaseQuery('') - setBaseResults([]) - setTitle(result.fields.title) - setBody(result.fields.body) - setDraft(result.fields.draft) + applyGeneratedFields(result.fields, currentSeed.fieldRevisions) setGenerateError(null) } catch (error) { if (generationRequestIdRef.current !== requestId) { @@ -283,6 +377,7 @@ export function useCreatePullRequestDialogFields({ body, draft, effectiveGenerating, + applyGeneratedFields, generation, generateDisabled, onBranchChangedByGeneration, @@ -308,16 +403,41 @@ export function useCreatePullRequestDialogFields({ void cancelRuntimeGeneratePullRequestFields(requestContext) }, [generation]) - return { - aiGenerationEnabled: commitMessageAi?.enabled === true, + useEffect(() => { + if ( + !open || + !resolvedPrDefaults.generateDetailsOnOpen || + !initializedFromEligibilityRef.current || + autoGeneratedForKeyRef.current === initializedFromEligibilityRef.current || + generateDisabled || + effectiveGenerating || + !base.trim() + ) { + return + } + autoGeneratedForKeyRef.current = initializedFromEligibilityRef.current + void handleGenerate() + }, [ base, - setBase, + effectiveGenerating, + generateDisabled, + handleGenerate, + open, + resolvedPrDefaults.generateDetailsOnOpen + ]) + + return { + aiGenerationEnabled: sourceControlAi.enabled === true, + base, + setBase: setUserBase, title, - setTitle, + setTitle: setUserTitle, body, - setBody, + setBody: setUserBody, draft, - setDraft, + setDraft: setUserDraft, + fieldRevisions: fieldRevisionsRef.current, + applyGeneratedFields, baseQuery, setBaseQuery, baseResults, diff --git a/src/renderer/src/components/settings/CommitMessageAiPane.test.tsx b/src/renderer/src/components/settings/CommitMessageAiPane.test.tsx index 4ab4a38b4..7b4da3104 100644 --- a/src/renderer/src/components/settings/CommitMessageAiPane.test.tsx +++ b/src/renderer/src/components/settings/CommitMessageAiPane.test.tsx @@ -1,7 +1,8 @@ import React from 'react' import { renderToStaticMarkup } from 'react-dom/server' import { beforeEach, describe, expect, it } from 'vitest' -import type { CommitMessageAiSettings, GlobalSettings } from '../../../../shared/types' +import type { GlobalSettings } from '../../../../shared/types' +import type { SourceControlAiSettings } from '../../../../shared/source-control-ai-types' import { getCommitMessageModelDiscoveryHostKey, getCommitMessageModelDiscoveryHostKeyForScope @@ -45,10 +46,10 @@ describe('CommitMessageAiPane', () => { 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('Source Control AI') + expect(markup).toContain('Enable Source Control AI') expect(markup).toContain('aria-checked="false"') - expect(markup).not.toContain('Which agent drafts your commit messages') + expect(markup).not.toContain('Orca invokes this CLI') expect(markup).not.toContain('Thinking effort') }) @@ -67,9 +68,12 @@ describe('CommitMessageAiPane', () => { ) expect(markup).toContain('aria-checked="true"') - expect(markup).toContain('Which agent drafts your commit messages') - expect(markup).toContain('Model') + expect(markup).toContain('Orca invokes this CLI') + expect(markup).toContain('Default model') expect(markup).toContain('Thinking effort') + expect(markup).toContain('Commit message model') + expect(markup).toContain('PR details model') + expect(markup).toContain('Branch name model') expect(markup).toContain('Higher effort produces more careful messages') expect(markup).toContain('Use Conventional Commits.') expect(markup).toContain('Save') @@ -108,7 +112,7 @@ describe('CommitMessageAiPane', () => { }) ) - expect(markup).toContain('AI Commit Messages') + expect(markup).toContain('Source Control AI') expect(markup).toContain('Custom command') expect(markup).toContain('ollama run llama3.1 {prompt}') }) @@ -150,8 +154,8 @@ describe('CommitMessageAiPane', () => { ) expect(markup).toContain('Gemini') - expect(markup).toContain('Gemini commit message generation is coming soon') - expect(markup).not.toContain('Which model the selected agent uses') + expect(markup).toContain('Gemini Source Control AI is coming soon') + expect(markup).not.toContain('Which model Source Control AI uses') }) it('keeps custom command discoverable in settings search metadata', () => { @@ -165,12 +169,12 @@ describe('CommitMessageAiPane', () => { }) it('merges discovered models without clobbering newer settings fields', () => { - const config: CommitMessageAiSettings = { + const config: SourceControlAiSettings = { enabled: true, agentId: 'cursor', selectedModelByAgent: { cursor: 'stale-model', codex: 'gpt-5.5' }, selectedThinkingByModel: { 'gpt-5.5': 'low' }, - customPrompt: 'Use Conventional Commits.', + instructionsByOperation: { commitMessage: 'Use Conventional Commits.' }, customAgentCommand: '', discoveredModelsByAgent: {} } @@ -182,7 +186,7 @@ describe('CommitMessageAiPane', () => { 'auto' ) - expect(merged.customPrompt).toBe('Use Conventional Commits.') + expect(merged.instructionsByOperation.commitMessage).toBe('Use Conventional Commits.') expect(merged.agentId).toBe('cursor') expect(merged.selectedModelByAgent).toEqual({ cursor: 'auto', @@ -195,12 +199,12 @@ describe('CommitMessageAiPane', () => { }) it('keeps SSH discovered models out of the legacy local cache', () => { - const config: CommitMessageAiSettings = { + const config: SourceControlAiSettings = { enabled: true, agentId: 'cursor', selectedModelByAgent: { cursor: 'auto' }, selectedThinkingByModel: {}, - customPrompt: '', + instructionsByOperation: {}, customAgentCommand: '', discoveredModelsByAgent: { cursor: [{ id: 'auto', label: 'Auto' }] }, selectedModelByAgentByHost: {}, diff --git a/src/renderer/src/components/settings/CommitMessageAiPane.tsx b/src/renderer/src/components/settings/CommitMessageAiPane.tsx index 900f4fe7b..f86e65393 100644 --- a/src/renderer/src/components/settings/CommitMessageAiPane.tsx +++ b/src/renderer/src/components/settings/CommitMessageAiPane.tsx @@ -4,7 +4,17 @@ the ~6 conditional render branches without making any of them clearer. */ import { useEffect, useMemo, useRef, useState } from 'react' import { RefreshCw, Terminal } from 'lucide-react' -import type { CommitMessageAiSettings, GlobalSettings, TuiAgent } from '../../../../shared/types' +import type { GlobalSettings, TuiAgent } from '../../../../shared/types' +import type { + SourceControlAiOperation, + SourceControlAiSettings +} from '../../../../shared/source-control-ai-types' +import { + clearSourceControlAiModelChoiceForHost, + normalizeSourceControlAiSettings, + readSourceControlAiModelChoiceForHost, + selectSourceControlAiModelChoiceForHost +} from '../../../../shared/source-control-ai' import { CUSTOM_AGENT_ID, getCommitMessageAgentCapability, @@ -40,15 +50,9 @@ type CommitMessageAiPaneProps = { customPromptDiscardSignal?: number } -const EMPTY_SETTINGS: CommitMessageAiSettings = { - enabled: false, - agentId: null, - selectedModelByAgent: {}, - discoveredModelsByAgent: {}, - selectedThinkingByModel: {}, - customPrompt: '', - customAgentCommand: '' -} +type SourceControlAiConfigPatch = + | Partial + | ((current: SourceControlAiSettings) => Partial) type ModelDiscoveryState = { status: 'idle' | 'loading' | 'ready' | 'error' @@ -59,12 +63,13 @@ type ModelDiscoveryState = { } const UNCONFIGURED_AGENT_SELECT_VALUE = '' +const INHERIT_MODEL_SELECT_VALUE = '__inherit__' const COMING_SOON_COMMIT_MESSAGE_AGENTS: readonly { id: TuiAgent; label: string }[] = [ { id: 'gemini', label: 'Gemini' } ] -function readSettings(settings: GlobalSettings): CommitMessageAiSettings { - return settings.commitMessageAi ?? EMPTY_SETTINGS +function readSettings(settings: GlobalSettings): SourceControlAiSettings { + return normalizeSourceControlAiSettings(settings.sourceControlAi, settings.commitMessageAi) } function agentLabel(agentId: TuiAgent, capability: CommitMessageAgentCapability): string { @@ -72,18 +77,22 @@ function agentLabel(agentId: TuiAgent, capability: CommitMessageAgentCapability) } function readSelectedModelId( - config: CommitMessageAiSettings, + config: SourceControlAiSettings, hostKey: string, agentId: TuiAgent ): string | undefined { - return ( - config.selectedModelByAgentByHost?.[hostKey]?.[agentId] ?? - (hostKey === LOCAL_COMMIT_MESSAGE_HOST_KEY ? config.selectedModelByAgent[agentId] : undefined) + return readSourceControlAiModelChoiceForHost( + { + selectedModelByAgent: config.selectedModelByAgent, + selectedModelByAgentByHost: config.selectedModelByAgentByHost + }, + hostKey, + agentId ) } function resolveSelectedModel( - config: CommitMessageAiSettings, + config: SourceControlAiSettings, capability: CommitMessageAgentCapability, hostKey: string ): CommitMessageModelCapability { @@ -99,7 +108,7 @@ function resolveSelectedModel( } function resolveSelectedThinking( - config: CommitMessageAiSettings, + config: SourceControlAiSettings, model: CommitMessageModelCapability ): string | undefined { if (!model.thinkingLevels) { @@ -113,22 +122,29 @@ function resolveSelectedThinking( } export function mergeDiscoveredModelsIntoCommitMessageConfig( - config: CommitMessageAiSettings, + config: SourceControlAiSettings, agentId: TuiAgent, models: CommitMessageModelCapability[], defaultModelId: string, hostKey = LOCAL_COMMIT_MESSAGE_HOST_KEY -): CommitMessageAiSettings { - const hostSelectedModels = config.selectedModelByAgentByHost?.[hostKey] ?? {} +): SourceControlAiSettings { const persisted = readSelectedModelId(config, hostKey, agentId) const nextModelId = models.some((model) => model.id === persisted) ? persisted : defaultModelId - const nextHostSelectedModels = + const selectedModelChoice = nextModelId && nextModelId !== persisted - ? { - ...hostSelectedModels, - [agentId]: nextModelId + ? selectSourceControlAiModelChoiceForHost( + { + selectedModelByAgent: config.selectedModelByAgent, + selectedModelByAgentByHost: config.selectedModelByAgentByHost + }, + hostKey, + agentId, + nextModelId + ) + : { + selectedModelByAgent: config.selectedModelByAgent, + selectedModelByAgentByHost: config.selectedModelByAgentByHost } - : hostSelectedModels const nextHostDiscoveredModels = { ...config.discoveredModelsByAgentByHost?.[hostKey], [agentId]: models @@ -142,47 +158,35 @@ export function mergeDiscoveredModelsIntoCommitMessageConfig( [agentId]: models }, selectedModelByAgent: - nextModelId && nextModelId !== persisted - ? { - ...config.selectedModelByAgent, - [agentId]: nextModelId - } - : config.selectedModelByAgent + selectedModelChoice.selectedModelByAgent ?? config.selectedModelByAgent } : {}), discoveredModelsByAgentByHost: { ...config.discoveredModelsByAgentByHost, [hostKey]: nextHostDiscoveredModels }, - selectedModelByAgentByHost: { - ...config.selectedModelByAgentByHost, - [hostKey]: nextHostSelectedModels - } + selectedModelByAgentByHost: selectedModelChoice.selectedModelByAgentByHost } } function selectModelForHost( - config: CommitMessageAiSettings, + config: SourceControlAiSettings, hostKey: string, agentId: TuiAgent, modelId: string -): Pick { - const hostSelectedModels = config.selectedModelByAgentByHost?.[hostKey] ?? {} +): Pick { + const choice = selectSourceControlAiModelChoiceForHost( + { + selectedModelByAgent: config.selectedModelByAgent, + selectedModelByAgentByHost: config.selectedModelByAgentByHost + }, + hostKey, + agentId, + modelId + ) return { - selectedModelByAgent: - hostKey === LOCAL_COMMIT_MESSAGE_HOST_KEY - ? { - ...config.selectedModelByAgent, - [agentId]: modelId - } - : config.selectedModelByAgent, - selectedModelByAgentByHost: { - ...config.selectedModelByAgentByHost, - [hostKey]: { - ...hostSelectedModels, - [agentId]: modelId - } - } + selectedModelByAgent: choice.selectedModelByAgent ?? config.selectedModelByAgent, + selectedModelByAgentByHost: choice.selectedModelByAgentByHost } } @@ -214,27 +218,70 @@ export function CommitMessageAiPane({ const config = readSettings(settings) const latestConfigRef = useRef(config) latestConfigRef.current = config + const settingsWriteQueueRef = useRef>(Promise.resolve()) const [modelDiscoveryByAgent, setModelDiscoveryByAgent] = useState< Partial> >({}) - const persistedCustomPrompt = config.customPrompt - const [customPromptDraft, setCustomPromptDraft] = useState(persistedCustomPrompt) - const [isSavingCustomPrompt, setIsSavingCustomPrompt] = useState(false) - const persistedCustomPromptRef = useRef(persistedCustomPrompt) - const isCustomPromptDirty = customPromptDraft !== persistedCustomPrompt + const persistedCommitInstructions = config.instructionsByOperation.commitMessage ?? '' + const persistedPullRequestInstructions = config.instructionsByOperation.pullRequest ?? '' + const persistedBranchNameInstructions = config.instructionsByOperation.branchName ?? '' + const [commitInstructionsDraft, setCommitInstructionsDraft] = useState( + persistedCommitInstructions + ) + const [pullRequestInstructionsDraft, setPullRequestInstructionsDraft] = useState( + persistedPullRequestInstructions + ) + const [branchNameInstructionsDraft, setBranchNameInstructionsDraft] = useState( + persistedBranchNameInstructions + ) + const [isSavingInstructions, setIsSavingInstructions] = useState(false) + const persistedInstructionsRef = useRef({ + commitMessage: persistedCommitInstructions, + pullRequest: persistedPullRequestInstructions, + branchName: persistedBranchNameInstructions + }) + const isCommitInstructionsDirty = commitInstructionsDraft !== persistedCommitInstructions + const isPullRequestInstructionsDirty = + pullRequestInstructionsDraft !== persistedPullRequestInstructions + const isBranchNameInstructionsDirty = + branchNameInstructionsDraft !== persistedBranchNameInstructions + const isCustomPromptDirty = + isCommitInstructionsDirty || isPullRequestInstructionsDirty || isBranchNameInstructionsDirty useEffect(() => { - persistedCustomPromptRef.current = persistedCustomPrompt - }, [persistedCustomPrompt]) - - useEffect(() => { - if (!isCustomPromptDirty) { - setCustomPromptDraft(persistedCustomPrompt) + persistedInstructionsRef.current = { + commitMessage: persistedCommitInstructions, + pullRequest: persistedPullRequestInstructions, + branchName: persistedBranchNameInstructions } - }, [isCustomPromptDirty, persistedCustomPrompt]) + }, [ + persistedBranchNameInstructions, + persistedCommitInstructions, + persistedPullRequestInstructions + ]) useEffect(() => { - setCustomPromptDraft(persistedCustomPromptRef.current) + if (!isCommitInstructionsDirty) { + setCommitInstructionsDraft(persistedCommitInstructions) + } + }, [isCommitInstructionsDirty, persistedCommitInstructions]) + + useEffect(() => { + if (!isPullRequestInstructionsDirty) { + setPullRequestInstructionsDraft(persistedPullRequestInstructions) + } + }, [isPullRequestInstructionsDirty, persistedPullRequestInstructions]) + + useEffect(() => { + if (!isBranchNameInstructionsDirty) { + setBranchNameInstructionsDraft(persistedBranchNameInstructions) + } + }, [isBranchNameInstructionsDirty, persistedBranchNameInstructions]) + + useEffect(() => { + setCommitInstructionsDraft(persistedInstructionsRef.current.commitMessage) + setPullRequestInstructionsDraft(persistedInstructionsRef.current.pullRequest) + setBranchNameInstructionsDraft(persistedInstructionsRef.current.branchName) // Why: parent navigation guards use this signal after the user confirms // they want to leave without saving the prompt draft. }, [customPromptDiscardSignal]) @@ -313,8 +360,17 @@ export function CommitMessageAiPane({ const activeDiscovery = rawActiveDiscovery?.hostKey === discoveryHostKey ? rawActiveDiscovery : undefined - const writeConfig = (patch: Partial): void => { - updateSettings({ commitMessageAi: { ...config, ...patch } }) + const writeConfig = (patch: SourceControlAiConfigPatch): Promise => { + const next = settingsWriteQueueRef.current + .catch(() => undefined) + .then(async () => { + const latestSettings = useAppStore.getState().settings + const latestConfig = latestSettings ? readSettings(latestSettings) : latestConfigRef.current + const resolvedPatch = typeof patch === 'function' ? patch(latestConfig) : patch + await updateSettings({ sourceControlAi: { ...latestConfig, ...resolvedPatch } }) + }) + settingsWriteQueueRef.current = next + return next } const refreshModels = async (agentId: TuiAgent): Promise => { @@ -369,16 +425,15 @@ export function CommitMessageAiPane({ defaultModelId: result.defaultModelId } })) - const latestConfig = latestConfigRef.current - updateSettings({ - commitMessageAi: mergeDiscoveredModelsIntoCommitMessageConfig( - latestConfig, + writeConfig((current) => + mergeDiscoveredModelsIntoCommitMessageConfig( + current, agentId, result.models, result.defaultModelId, discoveryHostKey ) - }) + ) } catch (error) { setModelDiscoveryByAgent((prev) => ({ ...prev, @@ -435,40 +490,44 @@ export function CommitMessageAiPane({ // so Generate works without maintaining a second agent preference. If the // user previously persisted 'custom', keep it and let them re-edit the // command — no implicit reset to a preset. - const seedAgentId = resolveCommitMessageAgentChoice(config.agentId, settings.defaultTuiAgent) + const defaultTuiAgent = settings.defaultTuiAgent + const seedAgentId = resolveCommitMessageAgentChoice(config.agentId, defaultTuiAgent) if (!seedAgentId) { writeConfig({ enabled: true, agentId: null }) return } - const seedCapability = isCustomAgentId(seedAgentId) - ? undefined - : getCommitMessageAgentCapability(seedAgentId) - const seedModel = seedCapability - ? resolveSelectedModel(config, seedCapability, discoveryHostKey) - : null - const seedThinking = seedModel ? resolveSelectedThinking(config, seedModel) : undefined - - const selectedModelPatch = seedCapability - ? selectModelForHost( - config, - discoveryHostKey, - seedCapability.id, - readSelectedModelId(config, discoveryHostKey, seedCapability.id) ?? - seedCapability.defaultModelId - ) - : { - selectedModelByAgent: config.selectedModelByAgent, - selectedModelByAgentByHost: config.selectedModelByAgentByHost - } - const nextSelectedThinkingByModel = { ...config.selectedThinkingByModel } - if (seedModel && seedThinking && !nextSelectedThinkingByModel[seedModel.id]) { - nextSelectedThinkingByModel[seedModel.id] = seedThinking - } - writeConfig({ - enabled: true, - agentId: seedAgentId, - ...selectedModelPatch, - selectedThinkingByModel: nextSelectedThinkingByModel + writeConfig((current) => { + const currentSeedAgentId = resolveCommitMessageAgentChoice(current.agentId, defaultTuiAgent) + const agentId = currentSeedAgentId ?? seedAgentId + const currentCapability = isCustomAgentId(agentId) + ? undefined + : getCommitMessageAgentCapability(agentId) + const seedModel = currentCapability + ? resolveSelectedModel(current, currentCapability, discoveryHostKey) + : null + const seedThinking = seedModel ? resolveSelectedThinking(current, seedModel) : undefined + const selectedModelPatch = currentCapability + ? selectModelForHost( + current, + discoveryHostKey, + currentCapability.id, + readSelectedModelId(current, discoveryHostKey, currentCapability.id) ?? + currentCapability.defaultModelId + ) + : { + selectedModelByAgent: current.selectedModelByAgent, + selectedModelByAgentByHost: current.selectedModelByAgentByHost + } + const nextSelectedThinkingByModel = { ...current.selectedThinkingByModel } + if (seedModel && seedThinking && !nextSelectedThinkingByModel[seedModel.id]) { + nextSelectedThinkingByModel[seedModel.id] = seedThinking + } + return { + enabled: true, + agentId, + ...selectedModelPatch, + selectedThinkingByModel: nextSelectedThinkingByModel + } }) } @@ -484,29 +543,31 @@ export function CommitMessageAiPane({ if (!capability) { return } - const selectedModelPatch = selectModelForHost( - config, - discoveryHostKey, - capability.id, - readSelectedModelId(config, discoveryHostKey, capability.id) ?? capability.defaultModelId - ) - const newModel = resolveSelectedModel( - { ...config, ...selectedModelPatch, agentId: capability.id }, - capability, - discoveryHostKey - ) - const nextSelectedThinkingByModel = { ...config.selectedThinkingByModel } - if ( - newModel.thinkingLevels && - newModel.defaultThinkingLevel && - !nextSelectedThinkingByModel[newModel.id] - ) { - nextSelectedThinkingByModel[newModel.id] = newModel.defaultThinkingLevel - } - writeConfig({ - agentId: capability.id, - ...selectedModelPatch, - selectedThinkingByModel: nextSelectedThinkingByModel + writeConfig((current) => { + const selectedModelPatch = selectModelForHost( + current, + discoveryHostKey, + capability.id, + readSelectedModelId(current, discoveryHostKey, capability.id) ?? capability.defaultModelId + ) + const newModel = resolveSelectedModel( + { ...current, ...selectedModelPatch, agentId: capability.id }, + capability, + discoveryHostKey + ) + const nextSelectedThinkingByModel = { ...current.selectedThinkingByModel } + if ( + newModel.thinkingLevels && + newModel.defaultThinkingLevel && + !nextSelectedThinkingByModel[newModel.id] + ) { + nextSelectedThinkingByModel[newModel.id] = newModel.defaultThinkingLevel + } + return { + agentId: capability.id, + ...selectedModelPatch, + selectedThinkingByModel: nextSelectedThinkingByModel + } }) } @@ -522,23 +583,25 @@ export function CommitMessageAiPane({ if (!model) { return } - const selectedModelPatch = selectModelForHost( - config, - discoveryHostKey, - activeCapability.id, - model.id - ) - const nextSelectedThinkingByModel = { ...config.selectedThinkingByModel } - if ( - model.thinkingLevels && - model.defaultThinkingLevel && - !nextSelectedThinkingByModel[model.id] - ) { - nextSelectedThinkingByModel[model.id] = model.defaultThinkingLevel - } - writeConfig({ - ...selectedModelPatch, - selectedThinkingByModel: nextSelectedThinkingByModel + writeConfig((current) => { + const selectedModelPatch = selectModelForHost( + current, + discoveryHostKey, + activeCapability.id, + model.id + ) + const nextSelectedThinkingByModel = { ...current.selectedThinkingByModel } + if ( + model.thinkingLevels && + model.defaultThinkingLevel && + !nextSelectedThinkingByModel[model.id] + ) { + nextSelectedThinkingByModel[model.id] = model.defaultThinkingLevel + } + return { + ...selectedModelPatch, + selectedThinkingByModel: nextSelectedThinkingByModel + } }) } @@ -546,53 +609,174 @@ export function CommitMessageAiPane({ if (!activeModel) { return } - writeConfig({ + writeConfig((current) => ({ selectedThinkingByModel: { - ...config.selectedThinkingByModel, + ...current.selectedThinkingByModel, [activeModel.id]: newLevelId } + })) + } + + const readOperationOverrideModelId = ( + operation: SourceControlAiOperation + ): string | undefined => { + if (!activeCapability) { + return undefined + } + const choice = config.modelOverridesByOperation?.[operation] + return readSourceControlAiModelChoiceForHost(choice, discoveryHostKey, activeCapability.id) + } + + const onOperationModelChange = ( + operation: SourceControlAiOperation, + newModelId: string + ): void => { + if (!activeCapability) { + return + } + if (newModelId === INHERIT_MODEL_SELECT_VALUE) { + writeConfig((current) => { + const latestOverrides = { ...current.modelOverridesByOperation } + const nextChoice = clearSourceControlAiModelChoiceForHost( + latestOverrides[operation], + discoveryHostKey, + activeCapability.id + ) + if (nextChoice) { + latestOverrides[operation] = nextChoice + } else { + delete latestOverrides[operation] + } + return { modelOverridesByOperation: latestOverrides } + }) + return + } + const model = activeCapability.models.find((candidate) => candidate.id === newModelId) + if (!model) { + return + } + writeConfig((current) => { + const currentChoice = current.modelOverridesByOperation?.[operation] + const nextChoice = selectSourceControlAiModelChoiceForHost( + currentChoice, + discoveryHostKey, + activeCapability.id, + model.id + ) + if ( + model.thinkingLevels && + model.defaultThinkingLevel && + !nextChoice.selectedThinkingByModel?.[model.id] + ) { + nextChoice.selectedThinkingByModel = { + ...nextChoice.selectedThinkingByModel, + [model.id]: model.defaultThinkingLevel + } + } + return { + modelOverridesByOperation: { + ...current.modelOverridesByOperation, + [operation]: nextChoice + } + } }) } - const onSaveCustomPrompt = async (): Promise => { - if (!isCustomPromptDirty || isSavingCustomPrompt) { + const onOperationThinkingChange = ( + operation: SourceControlAiOperation, + modelId: string, + newLevelId: string + ): void => { + writeConfig((current) => ({ + modelOverridesByOperation: { + ...current.modelOverridesByOperation, + [operation]: { + ...current.modelOverridesByOperation?.[operation], + selectedThinkingByModel: { + ...current.modelOverridesByOperation?.[operation]?.selectedThinkingByModel, + [modelId]: newLevelId + } + } + } + })) + } + + const onSaveInstructions = async (operation: SourceControlAiOperation): Promise => { + const draft = + operation === 'commitMessage' + ? commitInstructionsDraft + : operation === 'pullRequest' + ? pullRequestInstructionsDraft + : branchNameInstructionsDraft + const dirty = + operation === 'commitMessage' + ? isCommitInstructionsDirty + : operation === 'pullRequest' + ? isPullRequestInstructionsDirty + : isBranchNameInstructionsDirty + if (!dirty || isSavingInstructions) { return } - setIsSavingCustomPrompt(true) + setIsSavingInstructions(true) try { - await updateSettings({ commitMessageAi: { ...config, customPrompt: customPromptDraft } }) + await writeConfig((current) => ({ + instructionsByOperation: { + ...current.instructionsByOperation, + [operation]: draft + } + })) } finally { - setIsSavingCustomPrompt(false) + setIsSavingInstructions(false) } } - const onDiscardCustomPrompt = (): void => { - setCustomPromptDraft(persistedCustomPrompt) + const onDiscardInstructions = (operation: SourceControlAiOperation): void => { + if (operation === 'commitMessage') { + setCommitInstructionsDraft(persistedCommitInstructions) + return + } + if (operation === 'branchName') { + setBranchNameInstructionsDraft(persistedBranchNameInstructions) + return + } + setPullRequestInstructionsDraft(persistedPullRequestInstructions) + } + + const onPrDefaultChange = ( + key: keyof NonNullable, + value: boolean + ): void => { + writeConfig((current) => ({ + prCreationDefaults: { + ...current.prCreationDefaults, + [key]: value + } + })) } const sections: React.ReactNode[] = [] if ( matchesSettingsSearch(searchQuery, { - title: 'Enable AI commit messages', - description: 'Adds a Generate button to the Source Control panel.', + title: 'Enable Source Control AI', + description: + 'Adds AI generation to Source Control commit, pull request, and branch-name flows.', keywords: ['ai', 'commit', 'message', 'generate', 'agent', 'enabled'] }) ) { sections.push(
- +

- 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. + Adds Generate controls for commit messages and pull request details. Runs the selected + agent CLI where the worktree is hosted.