feat: auto-rename workspace branch from the first prompt (#2888)

Co-authored-by: brennanb2025 <brennankbenson@gmail.com>
This commit is contained in:
Trevin Chow
2026-05-27 14:09:43 -07:00
committed by GitHub
co-authored by brennanb2025
parent 770536ef7e
commit a65f7b4216
26 changed files with 1568 additions and 267 deletions
@@ -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<FirstWorkBranchRenameDeps> = {}): {
deps: FirstWorkBranchRenameDeps
onRenamed: ReturnType<typeof vi.fn>
setDisplayName: ReturnType<typeof vi.fn>
} {
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> = {}
): 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)
})
})
@@ -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<string>()
const settledWorktreeIds = new Set<string>()
/** 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<void> {
// 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<boolean> {
// 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<CommitMessageGenerationTarget | null> {
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 } : {}) }
}
+24
View File
@@ -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()
+1 -1
View File
@@ -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)
}
@@ -43,6 +43,7 @@ function createSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings
workspaceDir: testState.fakeHomeDir,
nestWorkspaces: false,
refreshLocalBaseRefOnWorktreeCreate: false,
autoRenameBranchFromWork: false,
branchPrefix: 'git-username',
branchPrefixCustom: '',
theme: 'system',
+1
View File
@@ -30,6 +30,7 @@ function createSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings
workspaceDir: testState.fakeHomeDir,
nestWorkspaces: false,
refreshLocalBaseRefOnWorktreeCreate: false,
autoRenameBranchFromWork: false,
branchPrefix: 'git-username',
branchPrefixCustom: '',
theme: 'system',
+103
View File
@@ -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'])
})
})
+74
View File
@@ -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<boolean> {
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<boolean> {
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<string | null> {
const isAvailable = async (candidate: string): Promise<boolean> =>
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 <newBranch>`). */
export async function renameCurrentBranch(exec: GitExec, newBranch: string): Promise<void> {
await exec(['branch', '-m', newBranch])
}
+57 -1
View File
@@ -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,
+6
View File
@@ -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)
@@ -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)
})
+4
View File
@@ -409,6 +409,10 @@ export class SshGitProvider implements IGitProvider {
}
}
async renameCurrentBranch(worktreePath: string, newBranch: string): Promise<void> {
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
+1
View File
@@ -205,6 +205,7 @@ export type IGitProvider = {
force?: boolean,
options?: { deleteBranch?: boolean }
): Promise<void>
renameCurrentBranch?(worktreePath: string, newBranch: string): Promise<void>
isGitRepo(path: string): boolean
isGitRepoAsync(dirPath: string): Promise<{ isRepo: boolean; rootPath: string | null }>
exec(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }>
+12
View File
@@ -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,
@@ -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')
@@ -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<GenerateBranchNameResult> {
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 }
}
+31
View File
@@ -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)
+20
View File
@@ -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<string, unknown>) {
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<string, unknown>) {
const dirPath = params.dirPath as string
try {
@@ -131,6 +131,47 @@ export function GitPane({
</button>
</SearchableSetting>
) : 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']
}) ? (
<SearchableSetting
key="auto-rename-branch-from-work"
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']}
className="flex items-center justify-between gap-4 py-2"
>
<div className="space-y-0.5">
<Label>Auto-Rename Branch From Work</Label>
<p className="text-xs text-muted-foreground">
When an agent starts working in a new workspace, Orca renames its auto-generated branch
(e.g. <code>Nautilus</code>) 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.
</p>
</div>
<button
role="switch"
aria-checked={settings.autoRenameBranchFromWork}
onClick={() =>
updateSettings({
autoRenameBranchFromWork: !settings.autoRenameBranchFromWork
})
}
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent transition-colors ${
settings.autoRenameBranchFromWork ? 'bg-foreground' : 'bg-muted-foreground/30'
}`}
>
<span
className={`pointer-events-none block size-3.5 rounded-full bg-background shadow-sm transition-transform ${
settings.autoRenameBranchFromWork ? 'translate-x-4' : 'translate-x-0.5'
}`}
/>
</button>
</SearchableSetting>
) : null,
matchesSettingsSearch(searchQuery, {
title: 'GitHub API Budget',
description: 'Current GitHub CLI REST, Search, and GraphQL rate limits.',
@@ -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.',
+4 -262
View File
@@ -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'
+76
View File
@@ -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.")
})
})
+92
View File
@@ -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')
}
+1
View File
@@ -153,6 +153,7 @@ export function getDefaultSettings(homedir: string): GlobalSettings {
nestWorkspaces: true,
workspaceDirHistory: [],
refreshLocalBaseRefOnWorktreeCreate: false,
autoRenameBranchFromWork: false,
branchPrefix: 'git-username',
branchPrefixCustom: '',
enableGitHubAttribution: false,
+265
View File
@@ -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
+4
View File
@@ -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