From a65f7b4216f8d4ed38d6540d7bbf15425eca9424 Mon Sep 17 00:00:00 2001 From: Trevin Chow Date: Wed, 27 May 2026 14:09:43 -0700 Subject: [PATCH] feat: auto-rename workspace branch from the first prompt (#2888) Co-authored-by: brennanb2025 --- .../first-work-branch-rename.test.ts | 360 ++++++++++++++++++ .../agent-hooks/first-work-branch-rename.ts | 262 +++++++++++++ src/main/agent-hooks/server.test.ts | 24 ++ src/main/agent-hooks/server.ts | 2 +- .../runtime-home-service.test.ts | 1 + src/main/codex-accounts/service.test.ts | 1 + src/main/git/branch-rename.test.ts | 103 +++++ src/main/git/branch-rename.ts | 74 ++++ src/main/index.ts | 58 ++- src/main/persistence.ts | 6 + src/main/providers/ssh-git-provider.test.ts | 8 + src/main/providers/ssh-git-provider.ts | 4 + src/main/providers/types.ts | 1 + src/main/runtime/orca-runtime.ts | 12 + .../commit-message-text-generation.test.ts | 58 +++ .../commit-message-text-generation.ts | 60 ++- src/relay/git-handler.test.ts | 31 ++ src/relay/git-handler.ts | 20 + .../src/components/settings/GitPane.tsx | 41 ++ .../src/components/settings/git-search.ts | 5 + .../src/constants/marine-creatures.ts | 266 +------------ src/shared/branch-name-from-work.test.ts | 76 ++++ src/shared/branch-name-from-work.ts | 92 +++++ src/shared/constants.ts | 1 + src/shared/marine-creatures.ts | 265 +++++++++++++ src/shared/types.ts | 4 + 26 files changed, 1568 insertions(+), 267 deletions(-) create mode 100644 src/main/agent-hooks/first-work-branch-rename.test.ts create mode 100644 src/main/agent-hooks/first-work-branch-rename.ts create mode 100644 src/main/git/branch-rename.test.ts create mode 100644 src/main/git/branch-rename.ts create mode 100644 src/shared/branch-name-from-work.test.ts create mode 100644 src/shared/branch-name-from-work.ts create mode 100644 src/shared/marine-creatures.ts diff --git a/src/main/agent-hooks/first-work-branch-rename.test.ts b/src/main/agent-hooks/first-work-branch-rename.test.ts new file mode 100644 index 000000000..1014df87e --- /dev/null +++ b/src/main/agent-hooks/first-work-branch-rename.test.ts @@ -0,0 +1,360 @@ +/* eslint-disable max-lines -- Why: the orchestrator tests cover local, SSH, + retry, and post-generation race guards; splitting would duplicate mocks. */ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { GlobalSettings, Repo } from '../../shared/types' +import { WORKTREE_ID_SEPARATOR } from '../../shared/worktree-id' + +const { + gitExecFileAsyncMock, + getGitUsernameMock, + getSshGitUsernameMock, + getSshGitProviderMock, + generateBranchNameMock, + resolveTextGenerationParamsMock, + prepareLocalEnvMock, + computeBranchNameMock +} = vi.hoisted(() => ({ + gitExecFileAsyncMock: vi.fn(), + getGitUsernameMock: vi.fn(() => 'you'), + getSshGitUsernameMock: vi.fn(async () => 'you'), + getSshGitProviderMock: vi.fn(() => undefined), + generateBranchNameMock: vi.fn(), + resolveTextGenerationParamsMock: vi.fn(), + prepareLocalEnvMock: vi.fn(async () => ({ ok: true as const })), + computeBranchNameMock: vi.fn((leaf: string) => `you/${leaf}`) +})) + +vi.mock('../git/runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock })) +vi.mock('../git/repo', () => ({ getGitUsername: getGitUsernameMock })) +vi.mock('../git/git-username', () => ({ getSshGitUsername: getSshGitUsernameMock })) +vi.mock('../providers/ssh-git-dispatch', () => ({ getSshGitProvider: getSshGitProviderMock })) +vi.mock('../text-generation/commit-message-text-generation', () => ({ + generateBranchNameFromContext: generateBranchNameMock, + resolveTextGenerationParams: resolveTextGenerationParamsMock +})) +vi.mock('../text-generation/commit-message-agent-environment', () => ({ + prepareLocalCommitMessageAgentEnv: prepareLocalEnvMock +})) +vi.mock('../ipc/worktree-logic', () => ({ computeBranchName: computeBranchNameMock })) + +import { + maybeAutoRenameBranchOnFirstWork, + resetFirstWorkBranchRenameState, + type FirstWorkBranchRenameDeps, + type FirstWorkBranchRenameEvent +} from './first-work-branch-rename' + +const REPO_ID = 'repo1' +const WORKTREE_ID = `${REPO_ID}${WORKTREE_ID_SEPARATOR}/repo/wt` +const TAB_ID = 'tab-1' +const PANE_KEY = `${TAB_ID}:leaf-1` + +const noUpstreamError = new Error("fatal: no upstream configured for branch 'Nautilus'") + +function gitResponder(opts: { + currentBranch: string + hasUpstream: boolean + existingRefs?: string[] +}) { + return async (args: string[]) => { + if (args[0] === 'rev-parse' && args.some((arg) => arg.includes('@{u}'))) { + if (opts.hasUpstream) { + return { stdout: 'origin/x\n', stderr: '' } + } + throw noUpstreamError + } + if (args[0] === 'rev-parse') { + return { stdout: `${opts.currentBranch}\n`, stderr: '' } + } + if (args[0] === 'show-ref') { + const ref = args.at(-1) ?? '' + if ((opts.existingRefs ?? []).includes(ref)) { + return { stdout: '', stderr: '' } + } + throw new Error('not found') + } + if (args[0] === 'branch' && args[1] === '-m') { + return { stdout: '', stderr: '' } + } + throw new Error(`unexpected git args: ${args.join(' ')}`) + } +} + +function makeDeps(overrides: Partial = {}): { + deps: FirstWorkBranchRenameDeps + onRenamed: ReturnType + setDisplayName: ReturnType +} { + const onRenamed = vi.fn() + const setDisplayName = vi.fn() + const settings = { autoRenameBranchFromWork: true } as unknown as GlobalSettings + const repo = { id: REPO_ID, path: '/repo', connectionId: undefined } as unknown as Repo + return { + onRenamed, + setDisplayName, + deps: { + getSettings: () => settings, + getRepo: () => repo, + getAgentEnvResolvers: () => undefined, + getCurrentDisplayName: () => 'Nautilus-8', + canRenameOrcaCreatedBranch: () => true, + setDisplayName, + resolveWorktreeIdForTab: () => WORKTREE_ID, + onRenamed, + ...overrides + } + } +} + +function workingEvent( + overrides: Partial = {} +): FirstWorkBranchRenameEvent { + return { + paneKey: PANE_KEY, + tabId: TAB_ID, + worktreeId: undefined, + state: 'working', + prompt: 'Fix the auth bug', + assistantMessage: undefined, + isReplay: false, + ...overrides + } +} + +describe('maybeAutoRenameBranchOnFirstWork', () => { + beforeEach(() => { + resetFirstWorkBranchRenameState() + vi.clearAllMocks() + getGitUsernameMock.mockReturnValue('you') + getSshGitUsernameMock.mockResolvedValue('you') + getSshGitProviderMock.mockReturnValue(undefined) + computeBranchNameMock.mockImplementation((leaf: string) => `you/${leaf}`) + prepareLocalEnvMock.mockResolvedValue({ ok: true }) + resolveTextGenerationParamsMock.mockReturnValue({ + ok: true, + params: { agentId: 'claude', model: 'm' } + }) + generateBranchNameMock.mockResolvedValue({ success: true, slug: 'fix-auth' }) + gitExecFileAsyncMock.mockImplementation( + gitResponder({ currentBranch: 'you/Nautilus', hasUpstream: false }) + ) + }) + + it('renames a fresh creature branch and its display name from the generated slug', async () => { + const { deps, onRenamed, setDisplayName } = makeDeps() + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + ['branch', '-m', 'you/fix-auth'], + expect.objectContaining({ cwd: '/repo/wt' }) + ) + expect(setDisplayName).toHaveBeenCalledWith(WORKTREE_ID, 'Fix auth') + expect(onRenamed).toHaveBeenCalledWith(REPO_ID) + }) + + it('leaves a user-customized display name untouched while still renaming the branch', async () => { + const { deps, setDisplayName } = makeDeps({ getCurrentDisplayName: () => 'My cool feature' }) + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + ['branch', '-m', 'you/fix-auth'], + expect.objectContaining({ cwd: '/repo/wt' }) + ) + expect(setDisplayName).not.toHaveBeenCalled() + }) + + it('resolves the worktree from the tab when the hook payload omits worktreeId', async () => { + // workingEvent() carries worktreeId: undefined; resolveWorktreeIdForTab supplies it. + const { deps, onRenamed } = makeDeps() + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(onRenamed).toHaveBeenCalledWith(REPO_ID) + }) + + it('skips when no worktree can be resolved for the tab', async () => { + const { deps } = makeDeps({ resolveWorktreeIdForTab: () => undefined }) + await maybeAutoRenameBranchOnFirstWork(workingEvent({ worktreeId: undefined }), deps) + expect(gitExecFileAsyncMock).not.toHaveBeenCalled() + }) + + it('does nothing when the setting is off', async () => { + const settings = { autoRenameBranchFromWork: false } as unknown as GlobalSettings + const { deps } = makeDeps({ getSettings: () => settings }) + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(gitExecFileAsyncMock).not.toHaveBeenCalled() + }) + + it('ignores replayed events and non-working states', async () => { + const { deps } = makeDeps() + await maybeAutoRenameBranchOnFirstWork(workingEvent({ isReplay: true }), deps) + await maybeAutoRenameBranchOnFirstWork(workingEvent({ state: 'done' }), deps) + await maybeAutoRenameBranchOnFirstWork(workingEvent({ prompt: ' ' }), deps) + expect(gitExecFileAsyncMock).not.toHaveBeenCalled() + }) + + it('does not re-attempt after a successful rename', async () => { + const { deps } = makeDeps() + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + generateBranchNameMock.mockClear() + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(generateBranchNameMock).not.toHaveBeenCalled() + }) + + it('retries on a later event after a transient failure (does not poison the worktree)', async () => { + generateBranchNameMock.mockResolvedValueOnce({ success: false, error: 'agent not ready' }) + const { deps, onRenamed } = makeDeps() + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(onRenamed).not.toHaveBeenCalled() + + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + ['branch', '-m', 'you/fix-auth'], + expect.objectContaining({ cwd: '/repo/wt' }) + ) + expect(onRenamed).toHaveBeenCalledWith(REPO_ID) + }) + + it('leaves a user-named branch untouched', async () => { + gitExecFileAsyncMock.mockImplementation( + gitResponder({ currentBranch: 'you/my-feature', hasUpstream: false }) + ) + const { deps, onRenamed } = makeDeps() + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(generateBranchNameMock).not.toHaveBeenCalled() + expect(onRenamed).not.toHaveBeenCalled() + }) + + it('refuses to rename a branch that already has an upstream', async () => { + gitExecFileAsyncMock.mockImplementation( + gitResponder({ currentBranch: 'you/Nautilus', hasUpstream: true }) + ) + const { deps, onRenamed } = makeDeps() + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(generateBranchNameMock).not.toHaveBeenCalled() + expect(onRenamed).not.toHaveBeenCalled() + }) + + it('leaves ineligible branches untouched even when their leaf is a creature name', async () => { + const { deps, onRenamed } = makeDeps({ canRenameOrcaCreatedBranch: () => false }) + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(generateBranchNameMock).not.toHaveBeenCalled() + expect(onRenamed).not.toHaveBeenCalled() + }) + + it('suffixes when the generated branch name already exists', async () => { + gitExecFileAsyncMock.mockImplementation( + gitResponder({ + currentBranch: 'you/Nautilus', + hasUpstream: false, + existingRefs: ['refs/heads/you/fix-auth'] + }) + ) + const { deps } = makeDeps() + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(gitExecFileAsyncMock).toHaveBeenCalledWith( + ['branch', '-m', 'you/fix-auth-2'], + expect.objectContaining({ cwd: '/repo/wt' }) + ) + }) + + it('does not rename when the branch changes while generation is running', async () => { + let branchReadCount = 0 + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args[0] === 'rev-parse' && args[1] === '--abbrev-ref' && args[2] === 'HEAD') { + branchReadCount += 1 + return { stdout: `${branchReadCount === 1 ? 'you/Nautilus' : 'you/manual'}\n`, stderr: '' } + } + if (args[0] === 'rev-parse' && args.some((arg) => arg.includes('@{u}'))) { + throw noUpstreamError + } + if (args[0] === 'symbolic-ref') { + return { stdout: 'you/Nautilus\n', stderr: '' } + } + if (args[0] === 'rev-parse' && args.includes('refs/remotes/origin/you/Nautilus')) { + throw new Error('not found') + } + throw new Error(`unexpected git args: ${args.join(' ')}`) + }) + const { deps, onRenamed } = makeDeps() + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(gitExecFileAsyncMock).not.toHaveBeenCalledWith( + ['branch', '-m', 'you/fix-auth'], + expect.anything() + ) + expect(onRenamed).not.toHaveBeenCalled() + }) + + it('does not rename when the branch gains an upstream while generation is running', async () => { + let upstreamReadCount = 0 + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args[0] === 'rev-parse' && args[1] === '--abbrev-ref' && args[2] === 'HEAD') { + return { stdout: 'you/Nautilus\n', stderr: '' } + } + if (args[0] === 'symbolic-ref') { + return { stdout: 'you/Nautilus\n', stderr: '' } + } + if (args[0] === 'rev-parse' && args.some((arg) => arg.includes('@{u}'))) { + upstreamReadCount += 1 + if (upstreamReadCount === 1) { + throw noUpstreamError + } + return { stdout: 'origin/you/Nautilus\n', stderr: '' } + } + if (args[0] === 'rev-parse' && args.includes('refs/remotes/origin/you/Nautilus')) { + throw new Error('not found') + } + throw new Error(`unexpected git args: ${args.join(' ')}`) + }) + const { deps, onRenamed } = makeDeps() + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(gitExecFileAsyncMock).not.toHaveBeenCalledWith( + ['branch', '-m', 'you/fix-auth'], + expect.anything() + ) + expect(onRenamed).not.toHaveBeenCalled() + }) + + it('uses the SSH git provider and remote generation target for remote worktrees', async () => { + getSshGitUsernameMock.mockResolvedValue('remote-user') + const provider = { + exec: vi.fn(gitResponder({ currentBranch: 'remote-user/Nautilus', hasUpstream: false })), + renameCurrentBranch: vi.fn(async () => undefined), + executeCommitMessagePlan: vi.fn() + } + getSshGitProviderMock.mockReturnValue(provider as never) + const repo = { id: REPO_ID, path: '/repo', connectionId: 'ssh-1' } as unknown as Repo + const { deps } = makeDeps({ getRepo: () => repo }) + + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + + expect(gitExecFileAsyncMock).not.toHaveBeenCalled() + expect(prepareLocalEnvMock).not.toHaveBeenCalled() + expect(generateBranchNameMock).toHaveBeenCalledWith( + { firstPrompt: 'Fix the auth bug', assistantMessage: undefined }, + { agentId: 'claude', model: 'm' }, + expect.objectContaining({ + kind: 'remote', + cwd: '/repo/wt', + missingBinaryLocation: 'remote PATH' + }) + ) + expect(computeBranchNameMock).toHaveBeenCalledWith('fix-auth', expect.anything(), 'remote-user') + expect(provider.exec).not.toHaveBeenCalledWith(['branch', '-m', 'you/fix-auth'], '/repo/wt') + expect(provider.renameCurrentBranch).toHaveBeenCalledWith('/repo/wt', 'you/fix-auth') + }) + + it('retries when the SSH provider is unavailable on the first working event', async () => { + const provider = { + exec: vi.fn(gitResponder({ currentBranch: 'you/Nautilus', hasUpstream: false })), + renameCurrentBranch: vi.fn(async () => undefined), + executeCommitMessagePlan: vi.fn() + } + getSshGitProviderMock.mockReturnValueOnce(undefined).mockReturnValue(provider as never) + const repo = { id: REPO_ID, path: '/repo', connectionId: 'ssh-1' } as unknown as Repo + const { deps, onRenamed } = makeDeps({ getRepo: () => repo }) + + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(onRenamed).not.toHaveBeenCalled() + + await maybeAutoRenameBranchOnFirstWork(workingEvent(), deps) + expect(provider.renameCurrentBranch).toHaveBeenCalledWith('/repo/wt', 'you/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 new file mode 100644 index 000000000..37ee24515 --- /dev/null +++ b/src/main/agent-hooks/first-work-branch-rename.ts @@ -0,0 +1,262 @@ +// Why: when "Auto-Rename Branch From Work" is on, the first time an agent +// starts working in a freshly-created workspace we replace the auto-generated +// creature branch (e.g. `you/Nautilus`) with a short, work-derived name. This +// module owns the orchestration: gate on the signal, enforce the safety +// guardrails, summarize the prompt via the configured agent, and rename. +import type { GlobalSettings, Repo } from '../../shared/types' +import { getRepoIdFromWorktreeId, splitWorktreeId } from '../../shared/worktree-id' +import { parsePaneKey } from '../../shared/stable-pane-id' +import { + humanizeBranchSlug, + isAutoGeneratedCreatureBranchName +} from '../../shared/branch-name-from-work' +import { getCommitMessageModelDiscoveryHostKey } from '../../shared/commit-message-host-key' +import { computeBranchName } from '../ipc/worktree-logic' +import { gitExecFileAsync } from '../git/runner' +import { getGitUsername } from '../git/repo' +import { getSshGitUsername } from '../git/git-username' +import { getSshGitProvider } from '../providers/ssh-git-dispatch' +import type { SshGitProvider } from '../providers/ssh-git-provider' +import { + branchHasUpstream, + renameCurrentBranch, + resolveUniqueBranchName, + type GitExec +} from '../git/branch-rename' +import { + generateBranchNameFromContext, + resolveTextGenerationParams, + type CommitMessageGenerationTarget +} from '../text-generation/commit-message-text-generation' +import { + prepareLocalCommitMessageAgentEnv, + type CommitMessageAgentEnvironmentResolvers +} from '../text-generation/commit-message-agent-environment' + +export type FirstWorkBranchRenameEvent = { + paneKey: string + /** Agent-echoed worktree id; unreliable, used only as a fallback. */ + worktreeId: string | undefined + tabId: string | undefined + state: string + prompt: string | undefined + assistantMessage: string | undefined + isReplay: boolean | undefined +} + +export type FirstWorkBranchRenameDeps = { + getSettings: () => GlobalSettings + getRepo: (repoId: string) => Repo | undefined + getAgentEnvResolvers: () => CommitMessageAgentEnvironmentResolvers | undefined + /** Current sidebar display name for the worktree, if one is stored. */ + getCurrentDisplayName: (worktreeId: string) => string | undefined + /** True only for Orca-created worktrees whose branch Orca is allowed to rename. */ + canRenameOrcaCreatedBranch: (worktreeId: string) => boolean + /** Persist a new sidebar display name for the worktree. */ + setDisplayName: (worktreeId: string, displayName: string) => void + /** Authoritative tab→worktree resolution from the session's tab map. */ + resolveWorktreeIdForTab: (tabId: string) => string | undefined + /** Invalidate caches + notify the renderer so the new branch name surfaces. */ + onRenamed: (repoId: string) => void +} + +// Why: `inFlight` guards against concurrent runs while generation (seconds) is +// pending; `settled` short-circuits worktrees we've reached a definitive verdict +// on (renamed, or permanently ineligible) so we never re-probe git on later +// `working` events — important because the hook fires every turn for every pane. +// A *transient* failure (agent not reachable yet, brief detached HEAD) is NOT +// settled, so the real first prompt can still succeed on a later event. +const inFlightWorktreeIds = new Set() +const settledWorktreeIds = new Set() + +/** Test seam: clear the per-process dedupe sets. */ +export function resetFirstWorkBranchRenameState(): void { + inFlightWorktreeIds.clear() + settledWorktreeIds.clear() +} + +export async function maybeAutoRenameBranchOnFirstWork( + event: FirstWorkBranchRenameEvent, + deps: FirstWorkBranchRenameDeps +): Promise { + // Cheap gates first — the signal must be a live "work has begun" event. + if (event.isReplay || event.state !== 'working') { + return + } + if (!deps.getSettings().autoRenameBranchFromWork) { + return + } + // Resolve the worktree from the tab (authoritative) rather than the + // agent-echoed worktreeId, which is not present on every hook event. + const tabId = parsePaneKey(event.paneKey)?.tabId ?? event.tabId + const worktreeId = (tabId ? deps.resolveWorktreeIdForTab(tabId) : undefined) ?? event.worktreeId + if (!worktreeId) { + return + } + // Short-circuit settled/in-flight worktrees before any logging or work. + if (settledWorktreeIds.has(worktreeId) || inFlightWorktreeIds.has(worktreeId)) { + return + } + const prompt = event.prompt?.trim() + if (!prompt) { + return + } + inFlightWorktreeIds.add(worktreeId) + try { + // `settled` true means a definitive verdict (renamed or permanently + // ineligible); false means a transient bail that should retry later. + const settled = await runAutoRename(worktreeId, prompt, event.assistantMessage, deps) + if (settled) { + settledWorktreeIds.add(worktreeId) + } + } catch (error) { + // Why: best-effort, opt-in convenience. A failure must never disrupt the + // agent the user actually launched, so swallow after logging. + console.warn('[auto-branch-rename] rename attempt failed:', error) + } finally { + inFlightWorktreeIds.delete(worktreeId) + } +} + +/** + * Returns true when a definitive verdict was reached (renamed, or permanently + * ineligible — so stop re-probing), false for a transient bail worth retrying. + */ +async function runAutoRename( + worktreeId: string, + prompt: string, + assistantMessage: string | undefined, + deps: FirstWorkBranchRenameDeps +): Promise { + // Why: when the feature appears not to fire, the question is always "which + // gate bailed?" — this names the gate so a single log line answers it. + // `stop` = permanent (don't retry); `retry` = transient (try again later). + const stop = (reason: string): true => { + console.info(`[auto-branch-rename] skip (${reason}) for ${worktreeId}`) + return true + } + const retry = (reason: string): false => { + console.info(`[auto-branch-rename] retry-later (${reason}) for ${worktreeId}`) + return false + } + + const repo = deps.getRepo(getRepoIdFromWorktreeId(worktreeId)) + const parsed = splitWorktreeId(worktreeId) + if (!repo || !parsed) { + return stop('unresolved repo or worktree id') + } + const worktreePath = parsed.worktreePath + + const provider = repo.connectionId ? (getSshGitProvider(repo.connectionId) ?? null) : null + if (repo.connectionId && !provider) { + return retry('ssh provider unavailable') + } + const exec: GitExec = provider + ? (args) => provider.exec(args, worktreePath) + : (args) => gitExecFileAsync(args, { cwd: worktreePath }) + + const currentBranch = (await exec(['rev-parse', '--abbrev-ref', 'HEAD'])).stdout.trim() + if (!currentBranch || currentBranch === 'HEAD') { + return retry(`no checked-out branch (${currentBranch || 'empty'})`) + } + if (!deps.canRenameOrcaCreatedBranch(worktreeId)) { + return stop(`worktree is not eligible for auto-rename`) + } + // Only rename a branch Orca auto-named — never one the user chose. + const leaf = currentBranch.slice(currentBranch.lastIndexOf('/') + 1) + if (!isAutoGeneratedCreatureBranchName(leaf)) { + return stop(`branch "${currentBranch}" is not an auto-generated name`) + } + // Never rewrite a branch that's already been published. + if (await branchHasUpstream(exec)) { + return stop(`branch "${currentBranch}" already has an upstream`) + } + + const settings = deps.getSettings() + const hostKey = getCommitMessageModelDiscoveryHostKey(repo.connectionId ?? null) + const resolvedParams = resolveTextGenerationParams(settings, hostKey) + if (!resolvedParams.ok) { + return stop(`no generation agent: ${resolvedParams.error}`) + } + const params = resolvedParams.params + + const target = await resolveGenerationTarget(worktreePath, params.agentId, provider, deps) + if (!target) { + return retry('could not prepare generation environment') + } + + const generated = await generateBranchNameFromContext( + { firstPrompt: prompt, assistantMessage }, + params, + target + ) + if (!generated.success) { + // Transient: the agent may be momentarily busy/unreachable — let a later + // event retry rather than permanently leaving the creature name. + return retry(`generation failed: ${generated.error}`) + } + + // Re-validate after generation (it can take seconds): the branch must be the + // same unpublished creature branch we started from, or we leave it alone. + const branchNow = (await exec(['rev-parse', '--abbrev-ref', 'HEAD'])).stdout.trim() + if (branchNow !== currentBranch) { + return retry(`branch changed during generation (${currentBranch} -> ${branchNow})`) + } + if (await branchHasUpstream(exec)) { + return retry(`branch "${currentBranch}" was pushed during generation`) + } + + const username = provider + ? (await getSshGitUsername(provider, repo.path)) || null + : getGitUsername(repo.path) || null + const newBranch = await resolveUniqueBranchName( + exec, + generated.slug, + (slugLeaf) => computeBranchName(slugLeaf, settings, username), + currentBranch + ) + if (!newBranch || newBranch === currentBranch) { + return stop(`no distinct unique branch name for slug "${generated.slug}"`) + } + + await (provider + ? provider.renameCurrentBranch(worktreePath, newBranch) + : renameCurrentBranch(exec, newBranch)) + + // Keep the sidebar name in sync with the branch — but only when it is still + // the auto-generated creature name, so a name the user typed is left alone. + const currentDisplayName = deps.getCurrentDisplayName(worktreeId) + const newDisplayName = humanizeBranchSlug(generated.slug) + const updateDisplay = !currentDisplayName || isAutoGeneratedCreatureBranchName(currentDisplayName) + if (updateDisplay) { + deps.setDisplayName(worktreeId, newDisplayName) + } + + deps.onRenamed(repo.id) + const displayLog = updateDisplay + ? `display "${currentDisplayName ?? ''}" -> "${newDisplayName}"` + : `display kept ("${currentDisplayName}")` + console.info(`[auto-branch-rename] renamed ${currentBranch} -> ${newBranch}; ${displayLog}`) + return true +} + +async function resolveGenerationTarget( + worktreePath: string, + agentId: string, + provider: SshGitProvider | null, + deps: FirstWorkBranchRenameDeps +): Promise { + if (provider) { + return { + kind: 'remote', + cwd: worktreePath, + execute: (plan, cwd, timeoutMs) => provider.executeCommitMessagePlan(plan, cwd, timeoutMs), + missingBinaryLocation: 'remote PATH' + } + } + const localEnv = await prepareLocalCommitMessageAgentEnv(agentId, deps.getAgentEnvResolvers()) + if (!localEnv.ok) { + return null + } + return { kind: 'local', cwd: worktreePath, ...(localEnv.env ? { env: localEnv.env } : {}) } +} diff --git a/src/main/agent-hooks/server.test.ts b/src/main/agent-hooks/server.test.ts index e71d5fa9a..5c265cdbf 100644 --- a/src/main/agent-hooks/server.test.ts +++ b/src/main/agent-hooks/server.test.ts @@ -973,6 +973,30 @@ describe('AgentHookServer listener replay', () => { expect(rendererListener).not.toHaveBeenCalled() }) + it('marks listener replay callbacks as replayed', () => { + const server = new AgentHookServer() + server.ingestRemote( + { + paneKey: PANE, + tabId: 'tab-1', + worktreeId: 'wt-1', + payload: { state: 'working', prompt: 'cached task', agentType: 'codex' } + }, + 'conn-1' + ) + + const listener = vi.fn() + server.setListener(listener) + + expect(listener).toHaveBeenCalledWith( + expect.objectContaining({ + paneKey: PANE, + isReplay: true, + payload: expect.objectContaining({ state: 'working', prompt: 'cached task' }) + }) + ) + }) + it('unsubscribes status-change listeners without removing the remaining listeners', () => { const server = new AgentHookServer() const removed = vi.fn() diff --git a/src/main/agent-hooks/server.ts b/src/main/agent-hooks/server.ts index 8bd026ad9..0ff58601d 100644 --- a/src/main/agent-hooks/server.ts +++ b/src/main/agent-hooks/server.ts @@ -402,7 +402,7 @@ export class AgentHookServer { // listener is the bare AgentHookEventPayload because the shared module // never reads from this map; only this class does, and only enriched // values are ever inserted. - listener(payload as EnrichedAgentHookEventPayload) + listener({ ...(payload as EnrichedAgentHookEventPayload), isReplay: true }) } catch (err) { console.error('[agent-hooks] replay listener threw', err) } diff --git a/src/main/codex-accounts/runtime-home-service.test.ts b/src/main/codex-accounts/runtime-home-service.test.ts index 1293f0749..abe456b73 100644 --- a/src/main/codex-accounts/runtime-home-service.test.ts +++ b/src/main/codex-accounts/runtime-home-service.test.ts @@ -43,6 +43,7 @@ function createSettings(overrides: Partial = {}): GlobalSettings workspaceDir: testState.fakeHomeDir, nestWorkspaces: false, refreshLocalBaseRefOnWorktreeCreate: false, + autoRenameBranchFromWork: false, branchPrefix: 'git-username', branchPrefixCustom: '', theme: 'system', diff --git a/src/main/codex-accounts/service.test.ts b/src/main/codex-accounts/service.test.ts index 8024f8242..7f9ed79c3 100644 --- a/src/main/codex-accounts/service.test.ts +++ b/src/main/codex-accounts/service.test.ts @@ -30,6 +30,7 @@ function createSettings(overrides: Partial = {}): GlobalSettings workspaceDir: testState.fakeHomeDir, nestWorkspaces: false, refreshLocalBaseRefOnWorktreeCreate: false, + autoRenameBranchFromWork: false, branchPrefix: 'git-username', branchPrefixCustom: '', theme: 'system', diff --git a/src/main/git/branch-rename.test.ts b/src/main/git/branch-rename.test.ts new file mode 100644 index 000000000..9b0917f7c --- /dev/null +++ b/src/main/git/branch-rename.test.ts @@ -0,0 +1,103 @@ +import { describe, expect, it, vi } from 'vitest' +import { + branchHasUpstream, + renameCurrentBranch, + resolveUniqueBranchName, + type GitExec +} from './branch-rename' + +const noUpstreamError = new Error( + "fatal: no upstream configured for branch 'feature'\n" + + 'To push the current branch and set the remote as upstream, use\n' + + ' git push --set-upstream origin feature' +) + +describe('branchHasUpstream', () => { + it('is true when @{u} resolves to a tracking ref', async () => { + const exec: GitExec = vi.fn(async (args: string[]) => { + if (args[0] === 'symbolic-ref') { + return { stdout: 'feature\n', stderr: '' } + } + if (args[0] === 'rev-parse' && args.includes('HEAD@{u}')) { + return { stdout: 'origin/feature\n', stderr: '' } + } + throw new Error(`unexpected git args: ${args.join(' ')}`) + }) + expect(await branchHasUpstream(exec)).toBe(true) + }) + + it('is false when there is no upstream', async () => { + const exec: GitExec = vi.fn(async (args: string[]) => { + if (args[0] === 'symbolic-ref') { + return { stdout: 'feature\n', stderr: '' } + } + if (args[0] === 'rev-parse' && args.includes('HEAD@{u}')) { + throw noUpstreamError + } + if (args[0] === 'rev-parse' && args.includes('refs/remotes/origin/feature')) { + throw new Error('not found') + } + throw new Error(`unexpected git args: ${args.join(' ')}`) + }) + expect(await branchHasUpstream(exec)).toBe(false) + }) + + it('is true when a same-name origin tracking ref exists without configured upstream', async () => { + const exec: GitExec = vi.fn(async (args: string[]) => { + if (args[0] === 'symbolic-ref') { + return { stdout: 'feature\n', stderr: '' } + } + if (args[0] === 'rev-parse' && args.includes('HEAD@{u}')) { + throw noUpstreamError + } + if (args[0] === 'rev-parse' && args.includes('refs/remotes/origin/feature')) { + return { stdout: '', stderr: '' } + } + throw new Error(`unexpected git args: ${args.join(' ')}`) + }) + expect(await branchHasUpstream(exec)).toBe(true) + }) + + it('is conservatively true on an unexpected failure', async () => { + const exec: GitExec = vi.fn().mockRejectedValue(new Error('fatal: not a git repository')) + expect(await branchHasUpstream(exec)).toBe(true) + }) +}) + +describe('resolveUniqueBranchName', () => { + const compute = (leaf: string): string => `you/${leaf}` + + it('returns the first candidate when no branch collides', async () => { + const exec: GitExec = vi.fn().mockRejectedValue(new Error('not found')) // show-ref misses + const result = await resolveUniqueBranchName(exec, 'fix-auth', compute, 'you/Nautilus') + expect(result).toBe('you/fix-auth') + }) + + it('suffixes when the first candidate already exists', async () => { + const exec: GitExec = vi.fn(async (args: string[]) => { + const ref = args.at(-1) + if (ref === 'refs/heads/you/fix-auth') { + return { stdout: '', stderr: '' } // exists + } + throw new Error('not found') + }) + const result = await resolveUniqueBranchName(exec, 'fix-auth', compute, 'you/Nautilus') + expect(result).toBe('you/fix-auth-2') + }) + + it('does not treat the branch being renamed away from as a collision', async () => { + // exec would report every ref as existing; only the currentBranch shortcut + // lets a candidate through. + const exec: GitExec = vi.fn().mockResolvedValue({ stdout: '', stderr: '' }) + const result = await resolveUniqueBranchName(exec, 'octopus', compute, 'you/octopus') + expect(result).toBe('you/octopus') + }) +}) + +describe('renameCurrentBranch', () => { + it('runs git branch -m with the new name', async () => { + const exec: GitExec = vi.fn().mockResolvedValue({ stdout: '', stderr: '' }) + await renameCurrentBranch(exec, 'you/fix-auth') + expect(exec).toHaveBeenCalledWith(['branch', '-m', 'you/fix-auth']) + }) +}) diff --git a/src/main/git/branch-rename.ts b/src/main/git/branch-rename.ts new file mode 100644 index 000000000..061f585f3 --- /dev/null +++ b/src/main/git/branch-rename.ts @@ -0,0 +1,74 @@ +import { isNoUpstreamError } from '../../shared/git-remote-error' +import { + resolveEffectiveGitUpstream, + type GitCommandRunner +} from '../../shared/git-effective-upstream' + +/** + * Git runner so branch-rename logic works identically for local worktrees + * (`gitExecFileAsync`) and SSH worktrees (`provider.exec`). Same contract the + * shared upstream-status helpers use. + */ +export type GitExec = GitCommandRunner + +/** + * True when the branch has a configured upstream — i.e. it has been pushed or + * is tracking a remote. Auto-rename refuses to touch such a branch because + * `git branch -m` would orphan the remote branch and break any open PR. + */ +export async function branchHasUpstream(exec: GitExec): Promise { + try { + return (await resolveEffectiveGitUpstream(exec)) !== null + } catch (error) { + if (isNoUpstreamError(error)) { + return false + } + // Why: an unexpected failure (detached HEAD, corruption, transport error) + // is not proof there's no upstream. Stay conservative and report "has + // upstream" so the caller skips the rename rather than risk a published branch. + return true + } +} + +async function localBranchExists(exec: GitExec, branch: string): Promise { + try { + await exec(['show-ref', '--verify', '--quiet', `refs/heads/${branch}`]) + return true + } catch { + return false + } +} + +/** + * Resolve a branch name that doesn't collide with an existing local branch by + * appending `-2`, `-3`, … to the leaf — the same suffixing worktree creation + * uses. `compute` applies the configured prefix to a leaf. The branch currently + * being renamed away from is never treated as a collision. + */ +export async function resolveUniqueBranchName( + exec: GitExec, + leaf: string, + compute: (leaf: string) => string, + currentBranch: string, + maxAttempts = 100 +): Promise { + const isAvailable = async (candidate: string): Promise => + candidate === currentBranch || !(await localBranchExists(exec, candidate)) + + const first = compute(leaf) + if (await isAvailable(first)) { + return first + } + for (let suffix = 2; suffix <= maxAttempts; suffix += 1) { + const candidate = compute(`${leaf}-${suffix}`) + if (await isAvailable(candidate)) { + return candidate + } + } + return null +} + +/** Rename the currently checked-out branch (`git branch -m `). */ +export async function renameCurrentBranch(exec: GitExec, newBranch: string): Promise { + await exec(['branch', '-m', newBranch]) +} diff --git a/src/main/index.ts b/src/main/index.ts index 028f7bb73..5b2b654bb 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -66,6 +66,7 @@ import { ClaudeAccountService } from './claude-accounts/service' import { ClaudeRuntimeAuthService } from './claude-accounts/runtime-auth-service' import { StarNagService } from './star-nag/service' import { agentHookServer } from './agent-hooks/server' +import { maybeAutoRenameBranchOnFirstWork } from './agent-hooks/first-work-branch-rename' import { setMigrationUnsupportedPtyListener } from './agent-hooks/migration-unsupported-pty-state' import { getPtyIdForPaneKey, @@ -123,6 +124,51 @@ let automations: AutomationService | null = null let keybindings: KeybindingService | null = null let expectedRendererReload: { webContentsId: number; until: number } | null = null const isServeMode = process.argv.includes('--serve') + +// Why: the store/runtime singletons live here in index.ts; injecting them keeps +// the rename orchestrator free of module-level state and unit-testable. +function maybeAutoRenameBranchOnFirstWorkFromHook(event: { + paneKey: string + tabId: string | undefined + worktreeId: string | undefined + payload: { state: string; prompt?: string; lastAssistantMessage?: string } + isReplay: boolean | undefined +}): void { + const currentStore = store + const currentRuntime = runtime + if (!currentStore || !currentRuntime) { + return + } + void maybeAutoRenameBranchOnFirstWork( + { + paneKey: event.paneKey, + tabId: event.tabId, + worktreeId: event.worktreeId, + state: event.payload.state, + prompt: event.payload.prompt, + assistantMessage: event.payload.lastAssistantMessage, + isReplay: event.isReplay + }, + { + getSettings: () => currentStore.getSettings(), + getRepo: (repoId) => currentStore.getRepo(repoId), + getAgentEnvResolvers: () => currentRuntime.getCommitMessageAgentEnvironmentResolvers(), + getCurrentDisplayName: (worktreeId) => currentStore.getWorktreeMeta(worktreeId)?.displayName, + canRenameOrcaCreatedBranch: (worktreeId) => { + const meta = currentStore.getWorktreeMeta(worktreeId) + // Why: a user/imported branch can coincidentally be named after a creature. + // Only worktrees Orca stamped at creation are safe to auto-rename. + return !!meta?.orcaCreationSource && meta.preserveBranchOnDelete !== true + }, + setDisplayName: (worktreeId, displayName) => { + currentStore.setWorktreeMeta(worktreeId, { displayName }) + }, + resolveWorktreeIdForTab: (tabId) => currentStore.getWorktreeIdForTab(tabId), + onRenamed: (repoId) => currentRuntime.notifyBranchRenamed(repoId) + } + ) +} + const devInstanceIdentity = getDevInstanceIdentity(is.dev) const devAgentHookEndpointNamespace = devInstanceIdentity.isDev ? devInstanceIdentity.appUserModelId @@ -478,10 +524,20 @@ function openMainWindow(): BrowserWindow { window.on('hide', stopSyntheticTitleSpinnerTimer) window.on('minimize', stopSyntheticTitleSpinnerTimer) agentHookServer.setListener( - ({ paneKey, tabId, worktreeId, connectionId, payload, receivedAt, stateStartedAt }) => { + ({ + paneKey, + tabId, + worktreeId, + connectionId, + payload, + receivedAt, + stateStartedAt, + isReplay + }) => { if (mainWindow?.isDestroyed()) { return } + maybeAutoRenameBranchOnFirstWorkFromHook({ paneKey, tabId, worktreeId, payload, isReplay }) const orchestration = runtime?.getAgentStatusOrchestrationContextForPaneKey(paneKey) mainWindow?.webContents.send('agentStatus:set', { ...payload, diff --git a/src/main/persistence.ts b/src/main/persistence.ts index 4941b4fbd..a2b4f86d9 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -2632,6 +2632,12 @@ export class Store { return this.state.workspaceSession ?? getDefaultWorkspaceSession() } + /** Resolve the worktree a terminal tab belongs to, from the session's + * tab→worktree map. More reliable than agent-echoed hook fields. */ + getWorktreeIdForTab(tabId: string): string | undefined { + return findWorktreeIdForTab(this.getWorkspaceSession(), tabId) + } + setWorkspaceSession(session: PersistedState['workspaceSession']): void { session = pruneWorkspaceSessionBrowserHistory( pruneLocalTerminalScrollbackBuffers(session, this.state.repos) diff --git a/src/main/providers/ssh-git-provider.test.ts b/src/main/providers/ssh-git-provider.test.ts index d5e0cb733..6e35f7d49 100644 --- a/src/main/providers/ssh-git-provider.test.ts +++ b/src/main/providers/ssh-git-provider.test.ts @@ -647,6 +647,14 @@ describe('SshGitProvider', () => { }) }) + it('renameCurrentBranch sends the narrow branch-rename request', async () => { + await provider.renameCurrentBranch('/home/user/feat', 'you/fix-auth') + expect(mux.request).toHaveBeenCalledWith('git.renameCurrentBranch', { + worktreePath: '/home/user/feat', + newBranch: 'you/fix-auth' + }) + }) + it('isGitRepo always returns true for remote paths', () => { expect(provider.isGitRepo('/any/path')).toBe(true) }) diff --git a/src/main/providers/ssh-git-provider.ts b/src/main/providers/ssh-git-provider.ts index b0d51e54e..c161c45bf 100644 --- a/src/main/providers/ssh-git-provider.ts +++ b/src/main/providers/ssh-git-provider.ts @@ -409,6 +409,10 @@ export class SshGitProvider implements IGitProvider { } } + async renameCurrentBranch(worktreePath: string, newBranch: string): Promise { + await this.mux.request('git.renameCurrentBranch', { worktreePath, newBranch }) + } + async exec(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }> { return (await this.mux.request('git.exec', { args, cwd })) as { stdout: string diff --git a/src/main/providers/types.ts b/src/main/providers/types.ts index 71942515e..4ce2c43b7 100644 --- a/src/main/providers/types.ts +++ b/src/main/providers/types.ts @@ -205,6 +205,7 @@ export type IGitProvider = { force?: boolean, options?: { deleteBranch?: boolean } ): Promise + renameCurrentBranch?(worktreePath: string, newBranch: string): Promise isGitRepo(path: string): boolean isGitRepoAsync(dirPath: string): Promise<{ isRepo: boolean; rootPath: string | null }> exec(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }> diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index af1071062..f6088a3c0 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -2764,6 +2764,10 @@ export class OrcaRuntimeService { this.commitMessageAgentEnv = resolvers } + getCommitMessageAgentEnvironmentResolvers(): CommitMessageAgentEnvironmentResolvers | undefined { + return this.commitMessageAgentEnv ?? undefined + } + async startMobileDictation(params: { dictationId: string modelId?: string @@ -10179,6 +10183,14 @@ export class OrcaRuntimeService { this.resolvedWorktreeCache = null } + /** Invalidate the worktree cache and tell the renderer to re-list, after an + * out-of-band branch change (e.g. auto-rename-from-work) so the new branch + * name surfaces without waiting for the next ambient refresh. */ + notifyBranchRenamed(repoId: string): void { + this.invalidateResolvedWorktreeCache() + this.notifier?.worktreesChanged(repoId) + } + private recordPtyWorktree( ptyId: string, worktreeId: string, diff --git a/src/main/text-generation/commit-message-text-generation.test.ts b/src/main/text-generation/commit-message-text-generation.test.ts index afebe18cb..6e135e296 100644 --- a/src/main/text-generation/commit-message-text-generation.test.ts +++ b/src/main/text-generation/commit-message-text-generation.test.ts @@ -10,6 +10,7 @@ import { cancelGeneratePullRequestFieldsLocal, discoverCommitMessageModelsLocal, discoverCommitMessageModelsRemote, + generateBranchNameFromContext, generateCommitMessageFromContext, generatePullRequestFieldsFromContext, resolveCommitMessageSettings, @@ -976,6 +977,63 @@ describe('generateCommitMessageFromContext', () => { }) }) +describe('generateBranchNameFromContext', () => { + it('sanitizes remote agent output into a short branch slug', async () => { + const result = await generateBranchNameFromContext( + { firstPrompt: 'Fix login flow' }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'agent' + }, + { + kind: 'remote', + cwd: '/repo', + missingBinaryLocation: 'remote PATH', + execute: async () => ({ + stdout: '"Fix/Login Flow now please"\n', + stderr: '', + exitCode: 0, + timedOut: false + }) + } + ) + + expect(result).toEqual({ + success: true, + slug: 'fix-login-flow-now', + agentLabel: 'agent' + }) + }) + + it('fails when remote agent output sanitizes to an empty branch slug', async () => { + const result = await generateBranchNameFromContext( + { firstPrompt: 'Fix login flow' }, + { + agentId: 'custom', + model: '', + customAgentCommand: 'agent' + }, + { + kind: 'remote', + cwd: '/repo', + missingBinaryLocation: 'remote PATH', + execute: async () => ({ + stdout: '!!! ___\n', + stderr: '', + exitCode: 0, + timedOut: false + }) + } + ) + + expect(result).toEqual({ + success: false, + error: 'Generated branch name was empty after sanitization.' + }) + }) +}) + describe('trimGeneratedCommitMessage', () => { it('removes trailing whitespace from generated messages', () => { const message = trimGeneratedCommitMessage('Update docs\n\n') diff --git a/src/main/text-generation/commit-message-text-generation.ts b/src/main/text-generation/commit-message-text-generation.ts index 5e2274845..85af201b3 100644 --- a/src/main/text-generation/commit-message-text-generation.ts +++ b/src/main/text-generation/commit-message-text-generation.ts @@ -19,6 +19,11 @@ import { cleanGeneratedCommitMessage, extractAgentErrorMessage } from '../../shared/commit-message-prompt' +import { + buildBranchNamePrompt, + sanitizeBranchSlug, + type BranchNameWorkContext +} from '../../shared/branch-name-from-work' import { CUSTOM_AGENT_ID, getCommitMessageAgentSpec, @@ -114,10 +119,25 @@ export function resolveCommitMessageSettings( settings: GlobalSettings, discoveryHostKey = LOCAL_COMMIT_MESSAGE_HOST_KEY ): ResolveCommitMessageSettingsResult { - const config = settings.commitMessageAi - if (!config?.enabled) { + if (!settings.commitMessageAi?.enabled) { return { ok: false, error: 'Enable AI commit messages in Settings -> Git.' } } + return resolveTextGenerationParams(settings, discoveryHostKey) +} + +/** + * 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 +): 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) { @@ -485,7 +505,7 @@ function killProcessTree(child: ChildProcess): void { } } -type LocalGenerationOperation = 'commit-message' | 'pull-request-fields' +type LocalGenerationOperation = 'commit-message' | 'pull-request-fields' | 'branch-name' // Keying by operation plus `local:${cwd}` keeps local cancellation independent // from SSH worktrees and from other generation features in the same worktree. @@ -822,3 +842,37 @@ export async function generatePullRequestFieldsFromContext( : await runLocalPlan(planned.plan, target.cwd, target.env, 'details', 'pull-request-fields') return formatPullRequestFieldsGenerationResult(internalResult, context) } + +export type GenerateBranchNameResult = + | { success: true; slug: string; agentLabel?: string } + | { success: false; error: string; canceled?: boolean } + +/** + * Generate a short kebab-case branch name from the work the agent is starting. + * Reuses the commit-message generation plan + spawn machinery; only the prompt + * and the post-processing (slug sanitization) differ. + */ +export async function generateBranchNameFromContext( + context: BranchNameWorkContext, + params: GenerateCommitMessageParams, + target: CommitMessageGenerationTarget +): Promise { + const prompt = buildBranchNamePrompt(context) + const planned = planCommitMessageGeneration(params, prompt) + if (!planned.ok) { + return { success: false, error: planned.error } + } + + const internalResult = + target.kind === 'remote' + ? await runRemotePlan(planned.plan, target, 'branch name') + : await runLocalPlan(planned.plan, target.cwd, target.env, 'branch name', 'branch-name') + if (!internalResult.success) { + return internalResult + } + const slug = sanitizeBranchSlug(internalResult.rawOutput) + if (!slug) { + return { success: false, error: 'Generated branch name was empty after sanitization.' } + } + return { success: true, slug, agentLabel: internalResult.agentLabel } +} diff --git a/src/relay/git-handler.test.ts b/src/relay/git-handler.test.ts index cc67cb8ef..fd87f31ba 100644 --- a/src/relay/git-handler.test.ts +++ b/src/relay/git-handler.test.ts @@ -59,10 +59,41 @@ describe('GitHandler', () => { expect(methods).toContain('git.listWorktrees') expect(methods).toContain('git.addWorktree') expect(methods).toContain('git.removeWorktree') + expect(methods).toContain('git.renameCurrentBranch') expect(methods).toContain('git.exec') expect(methods).toContain('git.isGitRepo') }) + describe('renameCurrentBranch', () => { + it('renames only the checked-out branch through the narrow RPC', async () => { + gitInit(tmpDir) + writeFileSync(path.join(tmpDir, 'file.txt'), 'hello') + gitCommit(tmpDir, 'initial') + execFileSync('git', ['checkout', '-b', 'you/Nautilus'], { cwd: tmpDir }) + + await dispatcher.callRequest('git.renameCurrentBranch', { + worktreePath: tmpDir, + newBranch: 'you/fix-auth' + }) + + const current = execFileSync('git', ['branch', '--show-current'], { + cwd: tmpDir, + encoding: 'utf-8' + }).trim() + expect(current).toBe('you/fix-auth') + }) + + it('rejects branch names that look like flags', async () => { + gitInit(tmpDir) + await expect( + dispatcher.callRequest('git.renameCurrentBranch', { + worktreePath: tmpDir, + newBranch: '-bad' + }) + ).rejects.toThrow('Branch name must not start with "-"') + }) + }) + describe('history', () => { it('returns bounded git history for a repo', async () => { gitInit(tmpDir) diff --git a/src/relay/git-handler.ts b/src/relay/git-handler.ts index 6bfda677e..e4f48f8cc 100644 --- a/src/relay/git-handler.ts +++ b/src/relay/git-handler.ts @@ -78,6 +78,7 @@ export class GitHandler { this.dispatcher.onRequest('git.addWorktree', (p) => this.addWorktree(p)) this.dispatcher.onRequest('git.removeWorktree', (p) => this.removeWorktree(p)) this.dispatcher.onRequest('git.worktreeIsClean', (p) => this.worktreeIsClean(p)) + this.dispatcher.onRequest('git.renameCurrentBranch', (p) => this.renameCurrentBranch(p)) this.dispatcher.onRequest('git.exec', (p) => this.exec(p)) this.dispatcher.onRequest('git.isGitRepo', (p) => this.isGitRepo(p)) } @@ -508,6 +509,25 @@ export class GitHandler { return { stdout, stderr } } + private async renameCurrentBranch(params: Record) { + const worktreePath = params.worktreePath + const newBranch = params.newBranch + if (typeof worktreePath !== 'string' || typeof newBranch !== 'string') { + throw new Error('Invalid branch rename request.') + } + if (newBranch.startsWith('-')) { + throw new Error('Branch name must not start with "-".') + } + try { + // Why: generic git.exec intentionally blocks destructive branch flags. + // This narrow RPC permits only the already-checked current-branch rename. + await this.git(['check-ref-format', '--branch', newBranch], worktreePath) + await this.git(['branch', '-m', newBranch], worktreePath) + } catch (error) { + throw new Error(normalizeGitErrorMessage(error)) + } + } + private async isGitRepo(params: Record) { const dirPath = params.dirPath as string try { diff --git a/src/renderer/src/components/settings/GitPane.tsx b/src/renderer/src/components/settings/GitPane.tsx index 5b8a03acf..ded7311d2 100644 --- a/src/renderer/src/components/settings/GitPane.tsx +++ b/src/renderer/src/components/settings/GitPane.tsx @@ -131,6 +131,47 @@ export function GitPane({ ) : null, + matchesSettingsSearch(searchQuery, { + title: 'Auto-Rename Branch From Work', + description: 'Rename the auto-generated branch based on the work once an agent starts.', + keywords: ['branch', 'rename', 'auto', 'creature name', 'agent', 'prompt', 'worktree'] + }) ? ( + +
+ +

+ When an agent starts working in a new workspace, Orca renames its auto-generated branch + (e.g. Nautilus) to a short name summarizing the task. Only branches Orca + named itself are renamed, and never after they have been pushed. Uses the agent + configured for AI commit messages. +

+
+ +
+ ) : null, matchesSettingsSearch(searchQuery, { title: 'GitHub API Budget', description: 'Current GitHub CLI REST, Search, and GraphQL rate limits.', diff --git a/src/renderer/src/components/settings/git-search.ts b/src/renderer/src/components/settings/git-search.ts index 7138fc205..6479f7a9a 100644 --- a/src/renderer/src/components/settings/git-search.ts +++ b/src/renderer/src/components/settings/git-search.ts @@ -20,6 +20,11 @@ export const GIT_PANE_SEARCH_ENTRIES: SettingsSearchEntry[] = [ 'worktree' ] }, + { + title: 'Auto-Rename Branch From Work', + description: 'Rename the auto-generated branch based on the work once an agent starts.', + keywords: ['branch', 'rename', 'auto', 'creature name', 'agent', 'prompt', 'worktree'] + }, { title: 'GitHub API Budget', description: 'Current GitHub CLI REST, Search, and GraphQL rate limits.', diff --git a/src/renderer/src/constants/marine-creatures.ts b/src/renderer/src/constants/marine-creatures.ts index c3f1df7f0..be42e3c32 100644 --- a/src/renderer/src/constants/marine-creatures.ts +++ b/src/renderer/src/constants/marine-creatures.ts @@ -1,262 +1,4 @@ -export const MARINE_CREATURES = [ - 'Nautilus', - 'Seahorse', - 'Starfish', - 'Coral', - 'Narwhal', - 'Jellyfish', - 'Octopus', - 'Manta', - 'Dolphin', - 'Manatee', - 'Cuttlefish', - 'Anemone', - 'Urchin', - 'Triton', - 'Nudibranch', - 'Coelacanth', - 'Oarfish', - 'Beluga', - 'Dugong', - 'Porpoise', - 'Stingray', - 'Hammerhead', - 'Wobbegong', - 'Sawfish', - 'Chimaera', - 'Anglerfish', - 'Viperfish', - 'Dragonfish', - 'Axolotl', - 'Otter', - 'Seadragon', - 'Seahare', - 'Squid', - 'Argonaut', - 'Sponge', - 'Barnacle', - 'Cowrie', - 'Guitarfish', - 'Lamprey', - 'Isopod', - 'Lionfish', - 'Clownfish', - 'Angelfish', - 'Butterflyfish', - 'Parrotfish', - 'Pufferfish', - 'Moonfish', - 'Firefish', - 'Unicornfish', - 'Rainbowfish', - 'Betta', - 'Discus', - 'Arowana', - 'Koi', - 'Piranha', - 'Barracuda', - 'Moray', - 'Sunfish', - 'Lanternfish', - 'Archerfish', - 'Mudskipper', - 'Hatchetfish', - 'Knifefish', - 'Leaffish', - 'Glassfish', - 'Ropefish', - 'Bichir', - 'Tigerfish', - 'Cardinalfish', - 'Lungfish', - 'Opah', - 'Frogfish', - 'Stonefish', - 'Cutlassfish', - 'Paddlefish', - 'Arapaima', - 'Mandarin', - 'Blobfish', - 'Thresher', - 'Vaquita', - 'Pipefish', - 'Guppy', - 'Tetra', - 'Danio', - 'Cichlid', - 'Oscar', - 'Gourami', - 'Killifish', - 'Rasbora', - 'Pleco', - 'Goldfish', - 'Molly', - 'Platy', - 'Barb', - 'Loach', - 'Medaka', - 'Pacu', - 'Filefish', - 'Boxfish', - 'Cowfish', - 'Surgeonfish', - 'Damselfish', - 'Wrasse', - 'Goby', - 'Blenny', - 'Conger', - 'Sculpin', - 'Darter', - 'Remora', - 'Pilotfish', - 'Trumpetfish', - 'Cornetfish', - 'Jawfish', - 'Toadfish', - 'Pearlfish', - 'Driftfish', - 'Lumpfish', - 'Snailfish', - 'Stickleback', - 'Halfbeak', - 'Snipefish', - 'Pencilfish', - 'Snakehead', - 'Tripletail', - 'Lookdown', - 'Sweetlips', - 'Squirrelfish', - 'Soldierfish', - 'Rabbitfish', - 'Hawkfish', - 'Bannerfish', - 'Batfish', - 'Chromis', - 'Anthias', - 'Fusilier', - 'Sweeper', - 'Emperor', - 'Ponyfish', - 'Kelpfish', - 'Weever', - 'Pearlside', - 'Opaleye', - 'Ballyhoo', - 'Needlefish', - 'Triggerfish', - 'Gar', - 'Tarpon', - 'Sailfish', - 'Conch', - 'Walrus', - 'Seal', - 'Penguin', - 'Hagfish', - 'Gulper', - 'Hydra', - 'Krill', - 'Salp', - 'Tunicate', - 'Crinoid', - 'Polyp', - 'Limpet', - 'Whelk', - 'Bowfin', - 'Minnow', - 'Gudgeon', - 'Goldeye', - 'Mooneye', - 'Soapfish', - 'Leatherjacket', - 'Rudderfish', - 'Sabrefish', - 'Puffin', - 'Albatross', - 'Osprey', - 'Pelican', - 'Petrel', - 'Gannet', - 'Tern', - 'Cormorant', - 'Leatherback', - 'Hawksbill', - 'Loggerhead', - 'Dottyback', - 'Basslet', - 'Gramma', - 'Hamlet', - 'Hogfish', - 'Dartfish', - 'Foxface', - 'Shrimpfish', - 'Pyrosome', - 'Seapen', - 'Medusa', - 'Candlefish', - 'Silverside', - 'Shiner', - 'Eelpout', - 'Madtom', - 'Shovelnose', - 'Sandlance', - 'Tubesnout', - 'Marlin', - 'Bonefish', - 'Dace', - 'Rudd', - 'Spirula', - 'Permit', - 'Grunt', - 'Trevally', - 'Croaker', - 'Drum', - 'Ladyfish', - 'Bullhead', - 'Torpedo', - 'Skate', - 'Hermit', - 'Fiddler', - 'Fireworm', - 'Tubeworm', - 'Amphipod', - 'Copepod', - 'Pteropod', - 'Seaslug', - 'Swordtail', - 'Bluegill', - 'Pickerel', - 'Redhorse', - 'Logperch', - 'Goblin', - 'Catshark', - 'Harlequin', - 'Murex', - 'Volute', - 'Wentletrap', - 'Nerite', - 'Stargazer', - 'Handfish', - 'Flyingfish', - 'Waspfish', - 'Skua', - 'Shearwater', - 'Guillemot', - 'Razorbill', - 'Auk', - 'Fulmar', - 'Murre', - 'Velvetfish', - 'Prowfish', - 'Sandperch', - 'Bobtail', - 'Chiton', - 'Featherstar', - 'Nereid', - 'Siren', - 'Kraken', - 'Selkie', - 'Leviathan', - 'Wolffish', - 'Wreckfish', - 'Horseshoe' -] as const +// Why: the canonical list lives in src/shared so the main process can use it +// too (auto-rename-from-work eligibility). Re-exported here to keep the +// existing `@/constants/marine-creatures` import path stable. +export { MARINE_CREATURES } from '../../../shared/marine-creatures' diff --git a/src/shared/branch-name-from-work.test.ts b/src/shared/branch-name-from-work.test.ts new file mode 100644 index 000000000..ec80d6abb --- /dev/null +++ b/src/shared/branch-name-from-work.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'vitest' +import { + buildBranchNamePrompt, + humanizeBranchSlug, + isAutoGeneratedCreatureBranchName, + sanitizeBranchSlug +} from './branch-name-from-work' + +describe('sanitizeBranchSlug', () => { + it('lowercases and kebab-cases free-form model output', () => { + expect(sanitizeBranchSlug('Fix the auth bug')).toBe('fix-the-auth-bug') + }) + + it('caps at four words', () => { + expect(sanitizeBranchSlug('add dark mode toggle to settings page')).toBe('add-dark-mode-toggle') + }) + + it('honors a custom word cap', () => { + expect(sanitizeBranchSlug('add dark mode toggle', 2)).toBe('add-dark') + }) + + it('collapses punctuation, quotes, and slashes into single hyphens', () => { + expect(sanitizeBranchSlug('"feat/login_flow!!"')).toBe('feat-login-flow') + }) + + it('returns empty string when nothing usable remains', () => { + expect(sanitizeBranchSlug(' !!! ___ ')).toBe('') + expect(sanitizeBranchSlug('')).toBe('') + }) +}) + +describe('isAutoGeneratedCreatureBranchName', () => { + it('matches a creature name case-insensitively', () => { + expect(isAutoGeneratedCreatureBranchName('Nautilus')).toBe(true) + expect(isAutoGeneratedCreatureBranchName('octopus')).toBe(true) + }) + + it('matches numbered collision variants', () => { + expect(isAutoGeneratedCreatureBranchName('Nautilus-2')).toBe(true) + expect(isAutoGeneratedCreatureBranchName('Seahorse-17')).toBe(true) + }) + + it('rejects user-chosen and work-derived names', () => { + expect(isAutoGeneratedCreatureBranchName('fix-auth-bug')).toBe(false) + expect(isAutoGeneratedCreatureBranchName('my-feature')).toBe(false) + expect(isAutoGeneratedCreatureBranchName('')).toBe(false) + }) +}) + +describe('humanizeBranchSlug', () => { + it('turns a kebab slug into a readable label', () => { + expect(humanizeBranchSlug('supported-models-list')).toBe('Supported models list') + expect(humanizeBranchSlug('fix-auth')).toBe('Fix auth') + }) + + it('returns empty string for an empty slug', () => { + expect(humanizeBranchSlug('')).toBe('') + }) +}) + +describe('buildBranchNamePrompt', () => { + it('includes the user prompt and omits the assistant section when absent', () => { + const prompt = buildBranchNamePrompt({ firstPrompt: 'Add a logout button' }) + expect(prompt).toContain('Add a logout button') + expect(prompt).not.toContain("Agent's initial response") + }) + + it('includes the assistant response when present', () => { + const prompt = buildBranchNamePrompt({ + firstPrompt: 'Add a logout button', + assistantMessage: "I'll wire it into the header." + }) + expect(prompt).toContain("Agent's initial response") + expect(prompt).toContain("I'll wire it into the header.") + }) +}) diff --git a/src/shared/branch-name-from-work.ts b/src/shared/branch-name-from-work.ts new file mode 100644 index 000000000..974c17ede --- /dev/null +++ b/src/shared/branch-name-from-work.ts @@ -0,0 +1,92 @@ +import { MARINE_CREATURES } from './marine-creatures' + +// Why: the work-derived branch name stays short on purpose — long, sentence-like +// branches read worse than the creature name they replace. Two-to-four words is +// the sweet spot the feature targets. +export const MAX_BRANCH_NAME_WORDS = 4 +const MIN_BRANCH_NAME_WORDS = 2 + +const CREATURE_NAMES_LOWER = new Set(MARINE_CREATURES.map((name) => name.toLowerCase())) + +function normalizeName(name: string): string { + return name.trim().toLowerCase() +} + +/** + * True when `branchLeaf` (the segment after any `prefix/`) is an Orca + * auto-generated creature name, e.g. `Nautilus` or `Octopus-2`. Used as the + * eligibility gate so auto-rename only ever overwrites a name Orca itself + * picked — never a branch the user named deliberately. + */ +export function isAutoGeneratedCreatureBranchName(branchLeaf: string): boolean { + const normalized = normalizeName(branchLeaf) + if (!normalized) { + return false + } + // Collision suffixes (`-2`, `-3`, …) are appended at creation; strip one + // before checking membership so numbered creatures still qualify. + const base = normalized.replace(/-\d+$/, '') + return CREATURE_NAMES_LOWER.has(base) +} + +/** + * Turn raw model output into a safe, short kebab-case branch leaf. Returns '' + * when nothing usable remains, which callers treat as "skip the rename". + */ +export function sanitizeBranchSlug(raw: string, maxWords = MAX_BRANCH_NAME_WORDS): string { + const words = raw + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .split('-') + .filter(Boolean) + if (words.length === 0) { + return '' + } + return words.slice(0, maxWords).join('-') +} + +/** + * Turn a branch slug into a readable workspace display label, e.g. + * `supported-models-list` → `Supported models list`. Used to update the + * sidebar name alongside the branch so the two stay in sync. + */ +export function humanizeBranchSlug(slug: string): string { + const joined = slug.split('-').filter(Boolean).join(' ') + if (!joined) { + return '' + } + return joined.charAt(0).toUpperCase() + joined.slice(1) +} + +export type BranchNameWorkContext = { + /** The user's first prompt to the agent in this workspace. */ + firstPrompt: string + /** The agent's first response, when it has already arrived. Optional because + * the rename fires as soon as work begins, before a reply may exist. */ + assistantMessage?: string +} + +/** + * Build the text-generation prompt that asks the configured agent to summarize + * the work into a branch name. Kept in shared so the prompt is identical across + * local and SSH generation targets. + */ +export function buildBranchNamePrompt(context: BranchNameWorkContext): string { + const sections = [ + 'Generate a git branch name that summarizes the coding task described below.', + 'Rules:', + `- Use between ${MIN_BRANCH_NAME_WORDS} and ${MAX_BRANCH_NAME_WORDS} words.`, + '- Lowercase kebab-case only (words joined by single hyphens).', + '- No slashes, no prefixes, no quotes, no trailing punctuation.', + '- Describe the work itself, not the agent or the repository.', + '- Output ONLY the branch name on a single line, nothing else.', + '', + 'User request:', + context.firstPrompt.trim() + ] + const assistant = context.assistantMessage?.trim() + if (assistant) { + sections.push('', "Agent's initial response:", assistant) + } + return sections.join('\n') +} diff --git a/src/shared/constants.ts b/src/shared/constants.ts index 924ba5219..055bae584 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -153,6 +153,7 @@ export function getDefaultSettings(homedir: string): GlobalSettings { nestWorkspaces: true, workspaceDirHistory: [], refreshLocalBaseRefOnWorktreeCreate: false, + autoRenameBranchFromWork: false, branchPrefix: 'git-username', branchPrefixCustom: '', enableGitHubAttribution: false, diff --git a/src/shared/marine-creatures.ts b/src/shared/marine-creatures.ts new file mode 100644 index 000000000..78e8c0714 --- /dev/null +++ b/src/shared/marine-creatures.ts @@ -0,0 +1,265 @@ +// Why: the auto-generated workspace name pool lives in shared (not renderer) +// so the main process can recognize an Orca-generated branch name when deciding +// whether auto-rename-from-work is allowed to overwrite it. +export const MARINE_CREATURES = [ + 'Nautilus', + 'Seahorse', + 'Starfish', + 'Coral', + 'Narwhal', + 'Jellyfish', + 'Octopus', + 'Manta', + 'Dolphin', + 'Manatee', + 'Cuttlefish', + 'Anemone', + 'Urchin', + 'Triton', + 'Nudibranch', + 'Coelacanth', + 'Oarfish', + 'Beluga', + 'Dugong', + 'Porpoise', + 'Stingray', + 'Hammerhead', + 'Wobbegong', + 'Sawfish', + 'Chimaera', + 'Anglerfish', + 'Viperfish', + 'Dragonfish', + 'Axolotl', + 'Otter', + 'Seadragon', + 'Seahare', + 'Squid', + 'Argonaut', + 'Sponge', + 'Barnacle', + 'Cowrie', + 'Guitarfish', + 'Lamprey', + 'Isopod', + 'Lionfish', + 'Clownfish', + 'Angelfish', + 'Butterflyfish', + 'Parrotfish', + 'Pufferfish', + 'Moonfish', + 'Firefish', + 'Unicornfish', + 'Rainbowfish', + 'Betta', + 'Discus', + 'Arowana', + 'Koi', + 'Piranha', + 'Barracuda', + 'Moray', + 'Sunfish', + 'Lanternfish', + 'Archerfish', + 'Mudskipper', + 'Hatchetfish', + 'Knifefish', + 'Leaffish', + 'Glassfish', + 'Ropefish', + 'Bichir', + 'Tigerfish', + 'Cardinalfish', + 'Lungfish', + 'Opah', + 'Frogfish', + 'Stonefish', + 'Cutlassfish', + 'Paddlefish', + 'Arapaima', + 'Mandarin', + 'Blobfish', + 'Thresher', + 'Vaquita', + 'Pipefish', + 'Guppy', + 'Tetra', + 'Danio', + 'Cichlid', + 'Oscar', + 'Gourami', + 'Killifish', + 'Rasbora', + 'Pleco', + 'Goldfish', + 'Molly', + 'Platy', + 'Barb', + 'Loach', + 'Medaka', + 'Pacu', + 'Filefish', + 'Boxfish', + 'Cowfish', + 'Surgeonfish', + 'Damselfish', + 'Wrasse', + 'Goby', + 'Blenny', + 'Conger', + 'Sculpin', + 'Darter', + 'Remora', + 'Pilotfish', + 'Trumpetfish', + 'Cornetfish', + 'Jawfish', + 'Toadfish', + 'Pearlfish', + 'Driftfish', + 'Lumpfish', + 'Snailfish', + 'Stickleback', + 'Halfbeak', + 'Snipefish', + 'Pencilfish', + 'Snakehead', + 'Tripletail', + 'Lookdown', + 'Sweetlips', + 'Squirrelfish', + 'Soldierfish', + 'Rabbitfish', + 'Hawkfish', + 'Bannerfish', + 'Batfish', + 'Chromis', + 'Anthias', + 'Fusilier', + 'Sweeper', + 'Emperor', + 'Ponyfish', + 'Kelpfish', + 'Weever', + 'Pearlside', + 'Opaleye', + 'Ballyhoo', + 'Needlefish', + 'Triggerfish', + 'Gar', + 'Tarpon', + 'Sailfish', + 'Conch', + 'Walrus', + 'Seal', + 'Penguin', + 'Hagfish', + 'Gulper', + 'Hydra', + 'Krill', + 'Salp', + 'Tunicate', + 'Crinoid', + 'Polyp', + 'Limpet', + 'Whelk', + 'Bowfin', + 'Minnow', + 'Gudgeon', + 'Goldeye', + 'Mooneye', + 'Soapfish', + 'Leatherjacket', + 'Rudderfish', + 'Sabrefish', + 'Puffin', + 'Albatross', + 'Osprey', + 'Pelican', + 'Petrel', + 'Gannet', + 'Tern', + 'Cormorant', + 'Leatherback', + 'Hawksbill', + 'Loggerhead', + 'Dottyback', + 'Basslet', + 'Gramma', + 'Hamlet', + 'Hogfish', + 'Dartfish', + 'Foxface', + 'Shrimpfish', + 'Pyrosome', + 'Seapen', + 'Medusa', + 'Candlefish', + 'Silverside', + 'Shiner', + 'Eelpout', + 'Madtom', + 'Shovelnose', + 'Sandlance', + 'Tubesnout', + 'Marlin', + 'Bonefish', + 'Dace', + 'Rudd', + 'Spirula', + 'Permit', + 'Grunt', + 'Trevally', + 'Croaker', + 'Drum', + 'Ladyfish', + 'Bullhead', + 'Torpedo', + 'Skate', + 'Hermit', + 'Fiddler', + 'Fireworm', + 'Tubeworm', + 'Amphipod', + 'Copepod', + 'Pteropod', + 'Seaslug', + 'Swordtail', + 'Bluegill', + 'Pickerel', + 'Redhorse', + 'Logperch', + 'Goblin', + 'Catshark', + 'Harlequin', + 'Murex', + 'Volute', + 'Wentletrap', + 'Nerite', + 'Stargazer', + 'Handfish', + 'Flyingfish', + 'Waspfish', + 'Skua', + 'Shearwater', + 'Guillemot', + 'Razorbill', + 'Auk', + 'Fulmar', + 'Murre', + 'Velvetfish', + 'Prowfish', + 'Sandperch', + 'Bobtail', + 'Chiton', + 'Featherstar', + 'Nereid', + 'Siren', + 'Kraken', + 'Selkie', + 'Leviathan', + 'Wolffish', + 'Wreckfish', + 'Horseshoe' +] as const diff --git a/src/shared/types.ts b/src/shared/types.ts index 7c67ad4b2..42e3e42a6 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -1575,6 +1575,10 @@ export type GlobalSettings = { nestWorkspaces: boolean workspaceDirHistory?: OrcaWorkspaceLayout[] refreshLocalBaseRefOnWorktreeCreate: boolean + /** When enabled, Orca renames a workspace's auto-generated creature branch to + * a short name derived from the first prompt once work begins. Opt-in; + * uses the same agent configured for AI commit messages. */ + autoRenameBranchFromWork: boolean branchPrefix: 'git-username' | 'custom' | 'none' branchPrefixCustom: string enableGitHubAttribution: boolean