feat: GitHub issue command automation for worktree creation (#441)

* feat: add shared issue command config and worktree automation

- Add shared top-level issue command support in orca.yaml with per-user .orca override read/write paths
- Surface the issue command in repository settings and the create-worktree dialog
- Queue issue-command terminal splits independently from setup-runner splits
- Preserve user checkbox state and repo-switch draft saves for issue command configuration
- Add parser, activation, and terminal-state test coverage for the new flow

* fix: clarify custom issue command settings label

* docs: clarify issue command effect behavior

* docs: unify issue command examples

* fix: keep issue command examples on one line

* style: use direct useEffect import in add worktree dialog
This commit is contained in:
Brennan Benson
2026-04-10 13:52:46 -07:00
committed by GitHub
parent d0cee5f83e
commit 7b63288f68
15 changed files with 850 additions and 144 deletions
+127 -17
View File
@@ -7,7 +7,11 @@ import { parseOrcaYaml } from './hooks'
// Mock fs and path used by loadHooks
vi.mock('fs', () => ({
readFileSync: vi.fn(),
existsSync: vi.fn()
existsSync: vi.fn(),
mkdirSync: vi.fn(),
writeFileSync: vi.fn(),
rmSync: vi.fn(),
chmodSync: vi.fn()
}))
const { execMock, execFileMock } = vi.hoisted(() => ({
@@ -107,6 +111,123 @@ describe('parseOrcaYaml', () => {
it('returns null for empty string', () => {
expect(parseOrcaYaml('')).toBeNull()
})
it('parses a top-level issueCommand block scalar', () => {
const yaml = [
'issueCommand: |',
' claude -p "Read issue #{{issue}}"',
' codex exec "Review docs/design-{{issue}}.md"'
].join('\n')
const result = parseOrcaYaml(yaml)
expect(result).toEqual({
scripts: {},
issueCommand:
'claude -p "Read issue #{{issue}}"\ncodex exec "Review docs/design-{{issue}}.md"'
})
})
it('parses issueCommand alongside scripts', () => {
const yaml = [
'scripts:',
' setup: |',
' pnpm install',
'issueCommand: |',
' claude -p "Read issue #{{issue}}"'
].join('\n')
const result = parseOrcaYaml(yaml)
expect(result).toEqual({
scripts: {
setup: 'pnpm install'
},
issueCommand: 'claude -p "Read issue #{{issue}}"'
})
})
})
describe('readIssueCommand', () => {
it('prefers the local override over the shared orca.yaml command', async () => {
const fs = await import('fs')
vi.mocked(fs.existsSync).mockImplementation(
(path) => path === '/test/repo/.orca/issue-command' || path === '/test/repo/orca.yaml'
)
vi.mocked(fs.readFileSync).mockImplementation((path) => {
if (path === '/test/repo/.orca/issue-command') {
return 'local command\n'
}
if (path === '/test/repo/orca.yaml') {
return 'issueCommand: |\n shared command\n'
}
return ''
})
const { readIssueCommand } = await import('./hooks')
expect(readIssueCommand('/test/repo')).toEqual({
localContent: 'local command',
sharedContent: 'shared command',
effectiveContent: 'local command',
localFilePath: '/test/repo/.orca/issue-command',
source: 'local'
})
})
it('falls back to the shared orca.yaml command when no local override exists', async () => {
const fs = await import('fs')
vi.mocked(fs.existsSync).mockImplementation((path) => path === '/test/repo/orca.yaml')
vi.mocked(fs.readFileSync).mockImplementation((path) => {
if (path === '/test/repo/orca.yaml') {
return 'issueCommand: |\n shared command\n'
}
return ''
})
const { readIssueCommand } = await import('./hooks')
expect(readIssueCommand('/test/repo')).toEqual({
localContent: null,
sharedContent: 'shared command',
effectiveContent: 'shared command',
localFilePath: '/test/repo/.orca/issue-command',
source: 'shared'
})
})
})
describe('writeIssueCommand', () => {
it('writes only the local override file and keeps .orca ignored locally', async () => {
const fs = await import('fs')
vi.mocked(fs.existsSync).mockImplementation(
(path) => path === '/test/repo/.gitignore' || path === '/test/repo/.orca'
)
vi.mocked(fs.readFileSync).mockImplementation((path) => {
if (path === '/test/repo/.gitignore') {
return 'node_modules/\n'
}
return ''
})
const { writeIssueCommand } = await import('./hooks')
writeIssueCommand('/test/repo', 'local command')
expect(vi.mocked(fs.writeFileSync)).toHaveBeenCalledWith(
'/test/repo/.gitignore',
'node_modules/\n.orca\n',
'utf-8'
)
expect(vi.mocked(fs.writeFileSync)).toHaveBeenCalledWith(
'/test/repo/.orca/issue-command',
'local command\n',
'utf-8'
)
})
it('deletes the local override when the override is cleared', async () => {
const fs = await import('fs')
const { writeIssueCommand } = await import('./hooks')
writeIssueCommand('/test/repo', ' ')
expect(vi.mocked(fs.rmSync)).toHaveBeenCalledWith('/test/repo/.orca/issue-command', {
force: true
})
})
})
describe('getEffectiveHooks', () => {
@@ -347,26 +468,15 @@ describe('runHook', () => {
try {
const { runHook } = await import('./hooks')
const result = await runHook(
'setup',
'\\\\wsl.localhost\\Ubuntu\\home\\jin\\feature',
{
...makeRepo(),
path: 'C:\\Users\\jinwo\\git\\orca'
}
)
const result = await runHook('setup', '\\\\wsl.localhost\\Ubuntu\\home\\jin\\feature', {
...makeRepo(),
path: 'C:\\Users\\jinwo\\git\\orca'
})
expect(result).toEqual({ success: true, output: '' })
expect(execFileMock).toHaveBeenCalledWith(
'wsl.exe',
[
'-d',
'Ubuntu',
'--',
'bash',
'-c',
"cd '/home/jin/feature' && echo hello"
],
['-d', 'Ubuntu', '--', 'bash', '-c', "cd '/home/jin/feature' && echo hello"],
expect.any(Object),
expect.any(Function)
)
+168 -35
View File
@@ -1,4 +1,5 @@
import { readFileSync, existsSync, mkdirSync, writeFileSync, chmodSync } from 'fs'
/* eslint-disable max-lines -- Why: hook parsing, layered issue-command resolution, and cross-platform runner setup share one execution surface, so keeping them together avoids subtle drift across create/read/write paths. */
import { readFileSync, existsSync, mkdirSync, writeFileSync, chmodSync, rmSync } from 'fs'
import { dirname, join } from 'path'
import { exec, execFile } from 'child_process'
import { getDefaultRepoHookSettings } from '../shared/constants'
@@ -23,56 +24,84 @@ function getHookShell(): string | undefined {
}
/**
* Parse a simple orca.yaml file. Handles only the `scripts:` block with
* multiline string values (YAML block scalar `|`).
* Parse a simple orca.yaml file. Handles only the supported `scripts:` and
* `issueCommand:` keys with multiline string values (YAML block scalar `|`).
*/
export function parseOrcaYaml(content: string): OrcaHooks | null {
const hooks: OrcaHooks = { scripts: {} }
const lines = content.split(/\r?\n/)
// Match top-level "scripts:" block
const scriptsMatch = content.match(/^scripts:\s*$/m)
if (!scriptsMatch) {
return null
}
const afterScripts = content.slice(scriptsMatch.index! + scriptsMatch[0].length)
// [Fix]: Split using /\r?\n/ instead of '\n'. Otherwise, on Windows, trailing \r characters
// stay attached to script commands, which causes fatal '\r command not found' errors in WSL/bash.
const lines = afterScripts.split(/\r?\n/)
let currentSection: 'scripts' | 'issueCommand' | null = null
let currentKey: 'setup' | 'archive' | null = null
let currentValue = ''
let issueCommandValue = ''
for (const line of lines) {
// Another top-level key (not indented) — stop parsing scripts block
if (/^\S/.test(line) && line.trim().length > 0) {
break
}
// Indented key like " setup: |" or " archive: |" or " setup: echo hello"
const keyMatch = line.match(/^ (setup|archive):\s*(\|)?\s*(.*)$/)
if (keyMatch) {
// Save previous key
if (currentKey) {
hooks.scripts[currentKey] = currentValue.trimEnd()
const topLevelKeyMatch = line.match(/^([A-Za-z][A-Za-z0-9_-]*):\s*(\|)?\s*(.*)$/)
if (topLevelKeyMatch) {
if (currentSection === 'scripts' && currentKey) {
hooks.scripts[currentKey] = issueCommandValue.trimEnd()
} else if (currentSection === 'issueCommand') {
hooks.issueCommand = issueCommandValue.trimEnd() || undefined
}
currentKey = keyMatch[1] as 'setup' | 'archive'
currentValue = keyMatch[3] ? `${keyMatch[3]}\n` : ''
const [, key, blockScalar, rest] = topLevelKeyMatch
currentKey = null
issueCommandValue = ''
if (key === 'scripts') {
currentSection = 'scripts'
continue
}
if (key === 'issueCommand') {
currentSection = 'issueCommand'
if (blockScalar) {
continue
}
hooks.issueCommand = rest.trim() || undefined
currentSection = null
continue
}
currentSection = null
continue
}
// Content line (indented by 4+ spaces under a key)
if (currentKey && line.startsWith(' ')) {
currentValue += `${line.slice(4)}\n`
if (currentSection === 'scripts') {
// Indented key like " setup: |" or " archive: |" or " setup: echo hello"
const keyMatch = line.match(/^ (setup|archive):\s*(\|)?\s*(.*)$/)
if (keyMatch) {
// Save previous key
if (currentKey) {
hooks.scripts[currentKey] = issueCommandValue.trimEnd()
}
currentKey = keyMatch[1] as 'setup' | 'archive'
issueCommandValue = keyMatch[3] ? `${keyMatch[3]}\n` : ''
continue
}
// Content line (indented by 4+ spaces under a key)
if (currentKey && line.startsWith(' ')) {
issueCommandValue += `${line.slice(4)}\n`
}
continue
}
if (currentSection === 'issueCommand' && line.startsWith(' ')) {
// Why: `issueCommand` is a top-level scalar in `orca.yaml`, so its block
// content must stay separate from the `scripts:` parser rather than being
// shoehorned into that section's indentation rules.
issueCommandValue += `${line.slice(2)}\n`
}
}
// Save last key
if (currentKey) {
hooks.scripts[currentKey] = currentValue.trimEnd()
if (currentSection === 'scripts' && currentKey) {
hooks.scripts[currentKey] = issueCommandValue.trimEnd()
} else if (currentSection === 'issueCommand') {
hooks.issueCommand = issueCommandValue.trimEnd() || undefined
}
if (!hooks.scripts.setup && !hooks.scripts.archive) {
if (!hooks.scripts.setup && !hooks.scripts.archive && !hooks.issueCommand) {
return null
}
return hooks
@@ -102,6 +131,110 @@ export function hasHooksFile(repoPath: string): boolean {
return existsSync(join(repoPath, 'orca.yaml'))
}
// ─── Issue command files ────────────────────────────────────────────────
// Why: `orca.yaml` is the tracked, project-wide defaults surface, while
// `.orca/issue-command` remains the per-user override. Keeping the local file in
// `.orca/` lets users customize agent automation without editing committed config.
const ORCA_DIR = '.orca'
const ISSUE_COMMAND_FILENAME = 'issue-command'
export function getIssueCommandFilePath(repoPath: string): string {
return join(repoPath, ORCA_DIR, ISSUE_COMMAND_FILENAME)
}
export function getSharedIssueCommand(repoPath: string): string | null {
return loadHooks(repoPath)?.issueCommand?.trim() || null
}
export type ResolvedIssueCommand = {
localContent: string | null
sharedContent: string | null
effectiveContent: string | null
localFilePath: string
source: 'local' | 'shared' | 'none'
}
/**
* Resolve the GitHub issue command using local override first, then tracked repo config.
*/
export function readIssueCommand(repoPath: string): ResolvedIssueCommand {
const filePath = getIssueCommandFilePath(repoPath)
let localContent: string | null = null
if (existsSync(filePath)) {
try {
const content = readFileSync(filePath, 'utf-8').trim()
localContent = content || null
} catch {
localContent = null
}
}
const sharedContent = getSharedIssueCommand(repoPath)
const effectiveContent = localContent ?? sharedContent
return {
localContent,
sharedContent,
effectiveContent,
localFilePath: filePath,
source: localContent ? 'local' : sharedContent ? 'shared' : 'none'
}
}
/**
* Write the per-user issue command override to `{repoRoot}/.orca/issue-command`.
* Creates `.orca/` and ensures it is in `.gitignore` on first write.
* If content is empty, deletes only the override so the shared `orca.yaml`
* command becomes effective again.
*/
export function writeIssueCommand(repoPath: string, content: string): void {
const filePath = getIssueCommandFilePath(repoPath)
const trimmed = content.trim()
try {
if (!trimmed) {
rmSync(filePath, { force: true })
return
}
const orcaDir = join(repoPath, ORCA_DIR)
if (!existsSync(orcaDir)) {
mkdirSync(orcaDir, { recursive: true })
}
ensureOrcaDirIgnored(repoPath)
writeFileSync(filePath, `${trimmed}\n`, 'utf-8')
} catch (err) {
console.error('[hooks] Failed to write issue command:', err)
// Why: re-throw so the error propagates through the IPC handler to the
// renderer, which already has .catch() ready to surface write failures.
throw err
}
}
/**
* Ensure `.orca` is listed in the repo's `.gitignore` so the per-user
* directory is never accidentally committed.
*/
function ensureOrcaDirIgnored(repoPath: string): void {
const gitignorePath = join(repoPath, '.gitignore')
try {
if (existsSync(gitignorePath)) {
const content = readFileSync(gitignorePath, 'utf-8')
if (/^\.orca\/?$/m.test(content)) {
return
}
const separator = content.endsWith('\n') ? '' : '\n'
writeFileSync(gitignorePath, `${content}${separator}.orca\n`, 'utf-8')
} else {
writeFileSync(gitignorePath, '.orca\n', 'utf-8')
}
} catch {
console.warn('[hooks] Could not update .gitignore to exclude .orca')
}
}
export function getEffectiveHooks(repo: Repo): OrcaHooks | null {
const yamlHooks = loadHooks(repo.path)
const legacySetup = repo.hookSettings?.scripts.setup?.trim()
+27 -1
View File
@@ -20,9 +20,11 @@ import {
createSetupRunnerScript,
getEffectiveHooks,
loadHooks,
readIssueCommand,
runHook,
hasHooksFile,
shouldRunSetupForCreate
shouldRunSetupForCreate,
writeIssueCommand
} from '../hooks'
import {
sanitizeWorktreeName,
@@ -48,6 +50,8 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store
ipcMain.removeHandler('worktrees:updateMeta')
ipcMain.removeHandler('worktrees:persistSortOrder')
ipcMain.removeHandler('hooks:check')
ipcMain.removeHandler('hooks:readIssueCommand')
ipcMain.removeHandler('hooks:writeIssueCommand')
ipcMain.handle('worktrees:listAll', async () => {
// Why: use ensureAuthorizedRootsCache (not rebuild) to avoid redundantly
@@ -307,6 +311,28 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store
hooks
}
})
ipcMain.handle('hooks:readIssueCommand', (_event, args: { repoId: string }) => {
const repo = store.getRepo(args.repoId)
if (!repo || isFolderRepo(repo)) {
return {
localContent: null,
sharedContent: null,
effectiveContent: null,
localFilePath: '',
source: 'none' as const
}
}
return readIssueCommand(repo.path)
})
ipcMain.handle('hooks:writeIssueCommand', (_event, args: { repoId: string; content: string }) => {
const repo = store.getRepo(args.repoId)
if (!repo || isFolderRepo(repo)) {
return
}
writeIssueCommand(repo.path, args.content)
})
}
function notifyWorktreesChanged(mainWindow: BrowserWindow, repoId: string): void {
+8
View File
@@ -224,6 +224,14 @@ export type PreloadApi = {
browser: BrowserApi
hooks: {
check: (args: { repoId: string }) => Promise<{ hasHooks: boolean; hooks: OrcaHooks | null }>
readIssueCommand: (args: { repoId: string }) => Promise<{
localContent: string | null
sharedContent: string | null
effectiveContent: string | null
localFilePath: string
source: 'local' | 'shared' | 'none'
}>
writeIssueCommand: (args: { repoId: string; content: string }) => Promise<void>
}
cache: {
getGitHub: () => Promise<{
+14 -1
View File
@@ -335,7 +335,20 @@ const api = {
hooks: {
check: (args: { repoId: string }): Promise<{ hasHooks: boolean; hooks: unknown }> =>
ipcRenderer.invoke('hooks:check', args)
ipcRenderer.invoke('hooks:check', args),
readIssueCommand: (args: {
repoId: string
}): Promise<{
localContent: string | null
sharedContent: string | null
effectiveContent: string | null
localFilePath: string
source: 'local' | 'shared' | 'none'
}> => ipcRenderer.invoke('hooks:readIssueCommand', args),
writeIssueCommand: (args: { repoId: string; content: string }): Promise<void> =>
ipcRenderer.invoke('hooks:writeIssueCommand', args)
},
cache: {
@@ -1,7 +1,8 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type { OrcaHooks, Repo, SetupRunPolicy } from '../../../../shared/types'
import { AlertTriangle } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '../ui/button'
import { DEFAULT_REPO_HOOK_SETTINGS } from './SettingsConstants'
import { SearchableSetting } from './SearchableSetting'
type RepositoryHooksSectionProps = {
@@ -14,21 +15,11 @@ type RepositoryHooksSectionProps = {
onUpdateSetupRunPolicy: (policy: SetupRunPolicy) => void
}
const SETUP_RUN_POLICY_OPTIONS: {
policy: SetupRunPolicy
label: string
description: string
}[] = [
{
policy: 'ask',
label: 'Ask every time',
description: 'Prompt before running setup.'
},
{
policy: 'run-by-default',
label: 'Run by default',
description: 'Run setup automatically.'
},
type PolicyOption<P> = { policy: P; label: string; description: string }
const SETUP_RUN_POLICY_OPTIONS: PolicyOption<SetupRunPolicy>[] = [
{ policy: 'ask', label: 'Ask every time', description: 'Prompt before running setup.' },
{ policy: 'run-by-default', label: 'Run by default', description: 'Run setup automatically.' },
{
policy: 'skip-by-default',
label: 'Skip by default',
@@ -40,7 +31,50 @@ const EXAMPLE_TEMPLATE = `scripts:
setup: |
pnpm worktree:setup
archive: |
echo "Cleaning up before archive"`
echo "Cleaning up before archive"
issueCommand: |
claude -p "Read issue #{{issue}} and write a design doc to docs/design-{{issue}}.md covering the approach, edge cases, and test plan." && codex exec "Review docs/design-{{issue}}.md for gaps, missing edge cases, or unclear requirements. Add feedback at the bottom."`
/** Shared button grid for setup run-policy selectors. */
function PolicyOptionGrid<P extends string>({
options,
selected,
onSelect,
columns
}: {
options: PolicyOption<P>[]
selected: P
onSelect: (p: P) => void
columns: string
}): React.JSX.Element {
return (
<div className={`grid gap-2 ${columns}`}>
{options.map(({ policy, label, description }) => {
const active = selected === policy
return (
<button
key={policy}
onClick={() => onSelect(policy)}
className={`rounded-xl border px-3 py-2.5 text-center transition-colors ${
active
? 'border-foreground/15 bg-accent text-accent-foreground'
: 'border-border/60 bg-background text-foreground hover:border-border hover:bg-muted/40'
}`}
>
<span className={`block text-sm ${active ? 'font-semibold' : 'font-medium'}`}>
{label}
</span>
<p
className={`mt-1 text-[11px] leading-4 ${active ? 'text-accent-foreground/80' : 'text-muted-foreground'}`}
>
{description}
</p>
</button>
)
})}
</div>
)
}
function ExampleTemplateCard({
copiedTemplate,
@@ -84,11 +118,78 @@ export function RepositoryHooksSection({
onUpdateSetupRunPolicy
}: RepositoryHooksSectionProps): React.JSX.Element {
const yamlState = yamlHooks ? 'loaded' : hasHooksFile ? 'invalid' : 'missing'
const hs = repo.hookSettings
const legacyHookEntries = (['setup', 'archive'] as const)
.map((hookName) => [hookName, repo.hookSettings?.scripts[hookName]?.trim() ?? ''] as const)
.map((hookName) => [hookName, hs?.scripts[hookName]?.trim() ?? ''] as const)
.filter(([, script]) => Boolean(script))
const selectedSetupRunPolicy =
repo.hookSettings?.setupRunPolicy ?? DEFAULT_REPO_HOOK_SETTINGS.setupRunPolicy
// Why: the type allows `undefined` in persisted settings for backward compatibility,
// but the UI always needs a concrete value so the policy grid has an active selection.
const selectedSetupRunPolicy: SetupRunPolicy = hs?.setupRunPolicy ?? 'run-by-default'
const [issueCommandDraft, setIssueCommandDraft] = useState('')
const [hasSharedIssueCommand, setHasSharedIssueCommand] = useState(false)
const [issueCommandSaveError, setIssueCommandSaveError] = useState<string | null>(null)
// Why: track the latest draft across blur/unmount so repo switches still
// persist the user's local override without racing the next repo's state load.
const issueCommandDraftRef = useRef(issueCommandDraft)
issueCommandDraftRef.current = issueCommandDraft
const lastCommittedIssueCommandRef = useRef('')
// Keep the local override editor in sync with the selected repo and flush unsaved edits on exit.
useEffect(() => {
let cancelled = false
const repoId = repo.id
setIssueCommandDraft('')
setHasSharedIssueCommand(false)
setIssueCommandSaveError(null)
// Why: settings only edit the local override, but we still need to know
// whether `orca.yaml` defines a shared default so the helper copy can
// explain what happens when the override is blank.
void window.api.hooks
.readIssueCommand({ repoId })
.then((result) => {
if (cancelled) {
return
}
const localContent = result.localContent ?? ''
setIssueCommandDraft(localContent)
setHasSharedIssueCommand(Boolean(result.sharedContent))
lastCommittedIssueCommandRef.current = localContent
})
.catch(() => {
if (!cancelled) {
setIssueCommandDraft('')
setHasSharedIssueCommand(false)
lastCommittedIssueCommandRef.current = ''
}
})
return () => {
cancelled = true
const draft = issueCommandDraftRef.current.trim()
if (draft !== lastCommittedIssueCommandRef.current) {
void window.api.hooks.writeIssueCommand({ repoId, content: draft }).catch((err) => {
console.error('[RepositoryHooksSection] Failed to save issue command on unmount:', err)
})
}
}
}, [repo.id])
const commitIssueCommand = useCallback(async (): Promise<void> => {
const trimmed = issueCommandDraft.trim()
setIssueCommandDraft(trimmed)
try {
await window.api.hooks.writeIssueCommand({ repoId: repo.id, content: trimmed })
lastCommittedIssueCommandRef.current = trimmed
setIssueCommandSaveError(null)
} catch (err) {
console.error('[RepositoryHooksSection] Failed to write issue command:', err)
const message = err instanceof Error ? err.message : 'Failed to save GitHub issue command.'
setIssueCommandSaveError(message)
toast.error(message)
}
}, [issueCommandDraft, repo.id])
return (
<section className="space-y-6">
@@ -102,7 +203,7 @@ export function RepositoryHooksSection({
<SearchableSetting
title="orca.yaml hooks"
description="Shared setup and archive hook commands for this repository."
description="Shared setup, archive, and issue automation commands for this repository."
keywords={['hooks', 'setup', 'archive', 'yaml']}
>
<div
@@ -132,10 +233,10 @@ export function RepositoryHooksSection({
</p>
<p className="text-xs text-muted-foreground">
{yamlState === 'loaded'
? 'Hook commands are defined in the repo and shared with everyone who uses it.'
? 'Shared hook and issue-automation defaults are defined in the repo and available to everyone who uses it.'
: yamlState === 'invalid'
? 'The core configuration file exists in the repo root, but Orca could not parse the supported hook definitions yet.'
: 'Add an `orca.yaml` file to enable setup or archive hooks for this repo. Example template:'}
: 'Add an `orca.yaml` file to enable shared setup, archive, or issue-automation defaults for this repo. Example template:'}
</p>
</div>
@@ -147,7 +248,7 @@ export function RepositoryHooksSection({
</pre>
</div>
<p className="text-xs text-muted-foreground">
Edit `orca.yaml` in the repository if you need to change these commands.
Edit `orca.yaml` in the repository if you need to change these shared commands.
</p>
</div>
) : yamlState === 'invalid' ? (
@@ -165,7 +266,7 @@ export function RepositoryHooksSection({
{/* Why: once a repo has an `orca.yaml`, the failure mode is usually bad shape
rather than a missing concept. Showing a repair-oriented explanation and
template here lets maintainers fix the committed file without needing the doc. */}
The file is present, but Orca could not find valid `setup` or `archive` hook
The file is present, but Orca could not find valid `scripts` or `issueCommand`
definitions in the expected format.
</p>
</div>
@@ -252,33 +353,45 @@ export function RepositoryHooksSection({
</p>
</div>
<div className="grid gap-2 md:grid-cols-3">
{SETUP_RUN_POLICY_OPTIONS.map(({ policy, label, description }) => {
const selected = selectedSetupRunPolicy === policy
<PolicyOptionGrid
options={SETUP_RUN_POLICY_OPTIONS}
selected={selectedSetupRunPolicy}
onSelect={onUpdateSetupRunPolicy}
columns="md:grid-cols-3"
/>
</div>
</SearchableSetting>
return (
<button
key={policy}
onClick={() => onUpdateSetupRunPolicy(policy)}
className={`rounded-xl border px-3 py-2.5 text-center transition-colors ${
selected
? 'border-foreground/15 bg-accent text-accent-foreground'
: 'border-border/60 bg-background text-foreground hover:border-border hover:bg-muted/40'
}`}
>
<span className={`block text-sm ${selected ? 'font-semibold' : 'font-medium'}`}>
{label}
</span>
<p
className={`mt-1 text-[11px] leading-4 ${
selected ? 'text-accent-foreground/80' : 'text-muted-foreground'
}`}
>
{description}
</p>
</button>
)
})}
<SearchableSetting
title="Custom GitHub Issue Command"
description="Optional per-user override for the linked-issue command."
keywords={['github issue command', 'issue command', 'workflow', 'agent', 'github']}
>
<div className="space-y-3 rounded-2xl border border-border/50 bg-background/80 p-4 shadow-sm">
<div className="space-y-1">
<h5 className="text-sm font-semibold">Custom GitHub Issue Command</h5>
</div>
<div className="space-y-2">
<textarea
value={issueCommandDraft}
onChange={(e) => setIssueCommandDraft(e.target.value)}
onBlur={commitIssueCommand}
placeholder='claude -p "Read issue #{{issue}} and write a design doc to docs/design-{{issue}}.md covering the approach, edge cases, and test plan." && codex exec "Review docs/design-{{issue}}.md for gaps, missing edge cases, or unclear requirements. Add feedback at the bottom."'
rows={5}
className="w-full min-w-0 resize-y rounded-md border border-input bg-transparent px-3 py-2 font-mono text-xs shadow-xs transition-[color,box-shadow] outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"
/>
<p className="text-xs text-muted-foreground">
Use <code className="rounded bg-muted px-1 py-0.5">{'{{issue}}'}</code> for the issue
number.
</p>
<p className="text-xs text-muted-foreground">
Leave blank to use the repo default from{' '}
<code className="rounded bg-muted px-1 py-0.5">orca.yaml</code>
{hasSharedIssueCommand ? '.' : ' when one exists.'}
</p>
{issueCommandSaveError ? (
<p className="text-xs text-destructive">{issueCommandSaveError}</p>
) : null}
</div>
</div>
</SearchableSetting>
@@ -288,22 +401,14 @@ export function RepositoryHooksSection({
const PARSE_ERROR_FIXES = [
'Check the indentation under `scripts:`. Hook keys should use two spaces, and command lines should use four.',
'Define only the supported hook keys: `setup` and `archive`.',
'Define only the supported keys: `scripts`, `setup`, `archive`, and `issueCommand`.',
'Compare your file against the working template below and copy that shape if needed.'
]
function renderYamlScriptPreview(yamlHooks: OrcaHooks | null): string {
return `scripts:${
yamlHooks?.scripts.setup
? `
setup: |
${yamlHooks.scripts.setup.replace(/^/gm, ' ')}`
: ''
}${
yamlHooks?.scripts.archive
? `
archive: |
${yamlHooks.scripts.archive.replace(/^/gm, ' ')}`
: ''
}`
function renderYamlScriptPreview(hooks: OrcaHooks | null): string {
const fmt = (key: string, cmd?: string): string =>
cmd ? `\n ${key}: |\n${cmd.replace(/^/gm, ' ')}` : ''
const issueCommand = hooks?.issueCommand
? `\nissueCommand: |\n${hooks.issueCommand.replace(/^/gm, ' ')}`
: ''
return `scripts:${fmt('setup', hooks?.scripts.setup)}${fmt('archive', hooks?.scripts.archive)}${issueCommand}`
}
@@ -72,6 +72,20 @@ export function getRepositoryPaneSearchEntries(repo: Repo): SettingsSearchEntry[
'run by default',
'skip by default'
]
},
{
title: 'Custom GitHub Issue Command',
description:
'File-based linked-issue command configured via orca.yaml and optional local override.',
keywords: [
repo.displayName,
'github issue command',
'issue command',
'workflow',
'github',
'orca.yaml',
'.orca/issue-command'
]
}
])
]
@@ -149,7 +163,12 @@ export function RepositoryPane({
['Display Name', 'Badge Color', 'Default Worktree Base', 'Remove Repo'].includes(entry.title)
)
const hooksEntries = allEntries.filter((entry) =>
['orca.yaml hooks', 'Legacy Repo-Local Hooks', 'When to Run Setup'].includes(entry.title)
[
'orca.yaml hooks',
'Legacy Repo-Local Hooks',
'When to Run Setup',
'Custom GitHub Issue Command'
].includes(entry.title)
)
const visibleSections = [
@@ -64,6 +64,6 @@ export const GENERAL_PANE_SEARCH_ENTRIES: SettingsSearchEntry[] = [
...GENERAL_WORKSPACE_SEARCH_ENTRIES,
...GENERAL_EDITOR_SEARCH_ENTRIES,
...GENERAL_CLI_SEARCH_ENTRIES,
...GENERAL_UPDATE_SEARCH_ENTRIES,
...GENERAL_CACHE_TIMER_SEARCH_ENTRIES
...GENERAL_CACHE_TIMER_SEARCH_ENTRIES,
...GENERAL_UPDATE_SEARCH_ENTRIES
]
@@ -1,6 +1,6 @@
/* eslint-disable max-lines */
import React, { useState, useCallback, useMemo, useRef } from 'react'
import React, { useState, useCallback, useMemo, useRef, useEffect } from 'react'
import { toast } from 'sonner'
import { ChevronRight } from 'lucide-react'
import { useAppStore } from '@/store'
@@ -62,6 +62,9 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
const [yamlHooks, setYamlHooks] = useState<OrcaHooks | null>(null)
const [checkedHooksRepoId, setCheckedHooksRepoId] = useState<string | null>(null)
const [setupDecision, setSetupDecision] = useState<'run' | 'skip' | null>(null)
const [runIssueAutomation, setRunIssueAutomation] = useState(false)
const [issueCommandTemplate, setIssueCommandTemplate] = useState('')
const [hasLoadedIssueCommand, setHasLoadedIssueCommand] = useState(false)
const [createError, setCreateError] = useState<string | null>(null)
const [creating, setCreating] = useState(false)
const nameInputRef = useRef<HTMLInputElement>(null)
@@ -69,6 +72,13 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
const resetTimeoutRef = useRef<number | null>(null)
const prevIsOpenRef = useRef(false)
const prevSuggestedNameRef = useRef('')
// Why: tracks whether the user has explicitly toggled the "Run GitHub issue
// command" checkbox. The auto-enable useEffect should only pre-check the box
// on the first opportunity; once the user makes a deliberate choice we must
// not override it when canOfferIssueAutomation re-fires (e.g. because the
// user clears and re-enters the linked issue number).
const userToggledIssueAutomationRef = useRef(false)
const issueAutomationUserChoiceRef = useRef<boolean | null>(null)
const isOpen = activeModal === 'create-worktree'
const preselectedRepoId =
@@ -78,11 +88,23 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
[activeWorktreeId, worktreesByRepo]
)
const selectedRepo = eligibleRepos.find((r) => r.id === repoId)
const parsedLinkedIssueNumber = useMemo(
() => (linkedIssue.trim() ? parseGitHubIssueOrPRNumber(linkedIssue) : null),
[linkedIssue]
)
const setupConfig = useMemo(
() => getSetupConfig(selectedRepo, yamlHooks),
[selectedRepo, yamlHooks]
)
const setupPolicy: SetupRunPolicy = selectedRepo?.hookSettings?.setupRunPolicy ?? 'run-by-default'
const hasIssueAutomationConfig = issueCommandTemplate.length > 0
const canOfferIssueAutomation = parsedLinkedIssueNumber !== null && hasIssueAutomationConfig
const shouldRunIssueAutomation = canOfferIssueAutomation && runIssueAutomation
// Why: the GitHub issue command changes the create result, so once the
// user has entered a valid linked issue we must not let create race ahead of
// the async repo-local template read and silently skip the command split.
const shouldWaitForIssueAutomationCheck =
parsedLinkedIssueNumber !== null && !hasLoadedIssueCommand
const requiresExplicitSetupChoice = Boolean(setupConfig) && setupPolicy === 'ask'
const resolvedSetupDecision =
setupDecision ??
@@ -144,7 +166,13 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
)
const handleCreate = useCallback(async () => {
if (!repoId || !name.trim() || shouldWaitForSetupCheck || !selectedRepo) {
if (
!repoId ||
!name.trim() ||
shouldWaitForSetupCheck ||
shouldWaitForIssueAutomationCheck ||
!selectedRepo
) {
return
}
setCreateError(null)
@@ -165,11 +193,8 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
// block the success path if only the metadata write fails.
try {
const metaUpdates: Record<string, unknown> = {}
if (linkedIssue.trim()) {
const linkedIssueNumber = parseGitHubIssueOrPRNumber(linkedIssue)
if (linkedIssueNumber !== null) {
;(metaUpdates as { linkedIssue: number }).linkedIssue = linkedIssueNumber
}
if (parsedLinkedIssueNumber !== null) {
;(metaUpdates as { linkedIssue: number }).linkedIssue = parsedLinkedIssueNumber
}
if (comment.trim()) {
;(metaUpdates as { comment: string }).comment = comment.trim()
@@ -181,6 +206,16 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
console.error('Failed to update worktree meta after creation')
}
// Why: build the issue command payload before ensureWorktreeHasInitialTerminal
// so it can queue the split before TerminalPane mounts. The command template
// supports {{issue}} interpolation so the launched command gets the linked
// issue number without requiring a second, less-visible templating surface.
const issueCommand = shouldRunIssueAutomation
? {
command: issueCommandTemplate.replace(/\{\{issue\}\}/g, String(parsedLinkedIssueNumber))
}
: undefined
setActiveRepo(repoId)
setActiveView('terminal')
setSidebarOpen(true)
@@ -191,7 +226,7 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
setFilterRepoIds([])
}
setActiveWorktree(wt.id)
ensureWorktreeHasInitialTerminal(useAppStore.getState(), wt.id, result.setup)
ensureWorktreeHasInitialTerminal(useAppStore.getState(), wt.id, result.setup, issueCommand)
revealWorktreeInSidebar(wt.id)
if (settings?.rightSidebarOpenByDefault) {
setRightSidebarTab('explorer')
@@ -208,7 +243,6 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
}, [
repoId,
name,
linkedIssue,
comment,
createWorktree,
updateWorktreeMeta,
@@ -225,8 +259,12 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
setRightSidebarTab,
settings?.rightSidebarOpenByDefault,
handleOpenChange,
issueCommandTemplate,
resolvedSetupDecision,
parsedLinkedIssueNumber,
selectedRepo,
shouldRunIssueAutomation,
shouldWaitForIssueAutomationCheck,
shouldWaitForSetupCheck
])
@@ -246,6 +284,11 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
setYamlHooks(null)
setCheckedHooksRepoId(null)
setSetupDecision(null)
setRunIssueAutomation(false)
setIssueCommandTemplate('')
setHasLoadedIssueCommand(false)
userToggledIssueAutomationRef.current = false
issueAutomationUserChoiceRef.current = null
if (createError) {
setCreateError(null)
}
@@ -267,7 +310,7 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
}, [handleOpenChange, openSettingsTarget, selectedRepo, setActiveView])
// Auto-select repo when opening.
React.useEffect(() => {
useEffect(() => {
if (resetTimeoutRef.current !== null) {
window.clearTimeout(resetTimeoutRef.current)
resetTimeoutRef.current = null
@@ -285,8 +328,13 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
setYamlHooks(null)
setCheckedHooksRepoId(null)
setSetupDecision(null)
setRunIssueAutomation(false)
setIssueCommandTemplate('')
setHasLoadedIssueCommand(false)
setCreateError(null)
lastSuggestedNameRef.current = ''
userToggledIssueAutomationRef.current = false
issueAutomationUserChoiceRef.current = null
resetTimeoutRef.current = null
}, DIALOG_CLOSE_RESET_DELAY_MS)
@@ -299,7 +347,7 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
}, [isOpen])
// Focus and select name input when suggestion is applied
React.useEffect(() => {
useEffect(() => {
if (!isOpen || !repoId || !suggestedName) {
return
}
@@ -314,18 +362,28 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
}, [isOpen, repoId, suggestedName])
// Safety guard: creating a worktree requires at least one repo.
React.useEffect(() => {
useEffect(() => {
if (isOpen && repos.length === 0) {
handleOpenChange(false)
}
}, [eligibleRepos.length, handleOpenChange, isOpen, repos.length])
React.useEffect(() => {
// Load hook state and the effective issue-command template for the selected repo.
useEffect(() => {
if (!isOpen || !repoId) {
return
}
let cancelled = false
// Why: when the dialog reopens quickly (before DIALOG_CLOSE_RESET_DELAY_MS
// fires) or when repoId changes via a path other than handleRepoChange,
// issue-automation state from the previous session could persist. Reset all
// three fields here for consistency with handleRepoChange and the close timeout.
setHasLoadedIssueCommand(false)
setIssueCommandTemplate('')
setRunIssueAutomation(false)
userToggledIssueAutomationRef.current = false
issueAutomationUserChoiceRef.current = null
void window.api.hooks
.check({ repoId })
@@ -342,12 +400,31 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
}
})
// Why: issue automation now resolves from layered config: tracked
// `orca.yaml` first, then optional `.orca/issue-command` override. Fetch the
// effective command alongside hooks so the create dialog can offer the
// checkbox as soon as the user links a valid GitHub issue.
void window.api.hooks
.readIssueCommand({ repoId })
.then((result) => {
if (!cancelled) {
setIssueCommandTemplate(result.effectiveContent ?? '')
setHasLoadedIssueCommand(true)
}
})
.catch(() => {
if (!cancelled) {
setIssueCommandTemplate('')
setHasLoadedIssueCommand(true)
}
})
return () => {
cancelled = true
}
}, [isOpen, repoId])
React.useEffect(() => {
useEffect(() => {
if (shouldWaitForSetupCheck) {
setSetupDecision(null)
return
@@ -366,10 +443,36 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
setSetupDecision(setupPolicy === 'run-by-default' ? 'run' : 'skip')
}, [setupConfig, setupPolicy, shouldWaitForSetupCheck])
// Auto-enable issue automation when a valid linked issue can use the repo template.
useEffect(() => {
if (!canOfferIssueAutomation) {
setRunIssueAutomation(issueAutomationUserChoiceRef.current ?? false)
return
}
// Why: when a repo defines `{repoRoot}/.orca/issue-command`, the create
// dialog should surface it automatically and start checked so the common
// path is "link issue, create worktree, start work" with one click.
// However, if the user has explicitly toggled the checkbox we must respect
// their choice instead of re-enabling it every time canOfferIssueAutomation
// re-fires (e.g. after clearing and re-entering the linked issue number).
if (!userToggledIssueAutomationRef.current) {
setRunIssueAutomation(true)
issueAutomationUserChoiceRef.current = true
return
}
setRunIssueAutomation(issueAutomationUserChoiceRef.current ?? false)
}, [canOfferIssueAutomation])
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey && repoId && name.trim() && !creating) {
if (shouldWaitForSetupCheck || (requiresExplicitSetupChoice && !setupDecision)) {
if (
shouldWaitForSetupCheck ||
shouldWaitForIssueAutomationCheck ||
(requiresExplicitSetupChoice && !setupDecision)
) {
return
}
e.preventDefault()
@@ -383,6 +486,7 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
handleCreate,
requiresExplicitSetupChoice,
setupDecision,
shouldWaitForIssueAutomationCheck,
shouldWaitForSetupCheck
]
)
@@ -438,6 +542,9 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
{shouldWaitForSetupCheck ? (
<p className="text-[10px] text-muted-foreground">Checking setup configuration...</p>
) : null}
{shouldWaitForIssueAutomationCheck ? (
<p className="text-[10px] text-muted-foreground">Checking GitHub issue command...</p>
) : null}
</div>
{setupConfig ? (
@@ -545,8 +652,31 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
<p className="text-[10px] text-muted-foreground">
Paste an issue URL, or enter a number.
</p>
{linkedIssue.trim() && parsedLinkedIssueNumber === null ? (
<p className="text-[10px] text-muted-foreground">
Enter a valid GitHub issue number or URL to enable the GitHub issue command.
</p>
) : null}
</div>
{canOfferIssueAutomation ? (
<div className="space-y-2 rounded-xl border border-border/60 bg-muted/20 p-3">
<p className="text-[11px] font-medium text-foreground">GitHub Issue Command</p>
<label className="flex items-center gap-2 text-[11px] text-foreground">
<input
type="checkbox"
checked={runIssueAutomation}
onChange={(e) => {
userToggledIssueAutomationRef.current = true
issueAutomationUserChoiceRef.current = e.target.checked
setRunIssueAutomation(e.target.checked)
}}
/>
Run the repository&apos;s GitHub issue command after creating this worktree.
</label>
</div>
) : null}
{/* Comment */}
<div className="space-y-1">
<label className="text-[11px] font-medium text-muted-foreground">
@@ -579,6 +709,7 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
!name.trim() ||
creating ||
shouldWaitForSetupCheck ||
shouldWaitForIssueAutomationCheck ||
!selectedRepo ||
(requiresExplicitSetupChoice && !setupDecision)
}
@@ -97,6 +97,10 @@ export default function TerminalPane({
const consumeTabStartupCommand = useAppStore((store) => store.consumeTabStartupCommand)
const [setupSplit] = useState(() => useAppStore.getState().pendingSetupSplitByTabId[tabId])
const consumeTabSetupSplit = useAppStore((store) => store.consumeTabSetupSplit)
const [issueCommandSplit] = useState(
() => useAppStore.getState().pendingIssueCommandSplitByTabId[tabId]
)
const consumeTabIssueCommandSplit = useAppStore((store) => store.consumeTabIssueCommandSplit)
useEffect(() => {
if (startup) {
@@ -110,6 +114,13 @@ export default function TerminalPane({
}
}, [setupSplit, tabId, consumeTabSetupSplit])
// Clear the queued issue-command split once this tab has captured it for initial mount.
useEffect(() => {
if (issueCommandSplit) {
consumeTabIssueCommandSplit(tabId)
}
}, [issueCommandSplit, tabId, consumeTabIssueCommandSplit])
const settingsRef = useRef(settings)
settingsRef.current = settings
const onPtyExitRef = useRef(onPtyExit)
@@ -228,6 +239,7 @@ export default function TerminalPane({
cwd,
startup,
setupSplit,
issueCommandSplit,
isActive,
systemPrefersDark,
settings,
@@ -27,6 +27,9 @@ type UseTerminalPaneLifecycleDeps = {
/** When present, the initial pane boots clean and a right-side split pane is
* created to run the setup command — keeping the main terminal interactive. */
setupSplit?: { command: string; env?: Record<string, string> } | null
/** When present, a split pane is created to run the repo's configured
* issue-automation command with the linked issue number interpolated. */
issueCommandSplit?: { command: string; env?: Record<string, string> } | null
isActive: boolean
systemPrefersDark: boolean
settings: GlobalSettings | null | undefined
@@ -68,6 +71,7 @@ export function useTerminalPaneLifecycle({
cwd,
startup,
setupSplit,
issueCommandSplit,
isActive,
systemPrefersDark,
settings,
@@ -143,7 +147,6 @@ export function useTerminalPaneLifecycle({
pathExistsCache
}
let resizeRaf: number | null = null
const queueResizeAll = (focusActive: boolean): void => {
if (resizeRaf !== null) {
cancelAnimationFrame(resizeRaf)
@@ -358,17 +361,49 @@ export function useTerminalPaneLifecycle({
// into ptyDeps.startup right before splitting — connectPanePty (called from
// onPaneCreated) reads it synchronously and clears it, so only the new pane
// gets the command. The initial pane already consumed startup=null above.
let issueAutomationAnchorPaneId: number | null = null
// Why: capture the main shell pane *before* any splits mutate the pane list.
// Both the setup and issue-command paths need to restore focus back to this
// pane after creating their splits, so we save the reference once rather
// than relying on getPanes()[0] which returns insertion order, not visual order.
const initialPane = manager.getActivePane() ?? manager.getPanes()[0]
if (setupSplit) {
const initialPane = manager.getActivePane() ?? manager.getPanes()[0]
if (initialPane) {
ptyDeps.startup = { command: setupSplit.command, env: setupSplit.env }
manager.splitPane(initialPane.id, 'vertical')
const setupPane = manager.splitPane(initialPane.id, 'vertical')
issueAutomationAnchorPaneId = setupPane?.id ?? null
// Restore focus to the main (left) pane so the user's terminal
// receives keyboard input — the setup pane runs unattended.
manager.setActivePane(initialPane.id, { focus: isActive })
}
}
// Why: when the user links a GitHub issue during worktree creation and has
// enabled that repo's issue automation, spawn a separate split pane to run
// the agent command. This runs independently from setup: the issue command
// is a per-user prompt/template rather than repo bootstrap, so Orca should
// not guess at ordering requirements that vary by user workflow.
if (issueCommandSplit) {
const targetPane =
(issueAutomationAnchorPaneId !== null
? (manager.getPanes().find((pane) => pane.id === issueAutomationAnchorPaneId) ?? null)
: null) ??
manager.getActivePane() ??
manager.getPanes()[0]
if (targetPane) {
ptyDeps.startup = { command: issueCommandSplit.command, env: issueCommandSplit.env }
manager.splitPane(targetPane.id, 'vertical')
// Why: if setup already claimed the right half, nest issue automation
// inside that automation area instead of splitting the main shell again.
// This preserves the primary terminal as the dominant pane while setup
// and issue panes share the secondary column.
const focusPaneId =
issueAutomationAnchorPaneId !== null ? (initialPane?.id ?? targetPane.id) : targetPane.id
manager.setActivePane(focusPaneId, { focus: isActive })
}
}
shouldPersistLayout = true
syncCanExpandState()
applyAppearance(manager)
@@ -7,6 +7,7 @@ function createMockStore(overrides: Record<string, unknown> = {}) {
createTab: vi.fn(() => ({ id: 'tab-1' })),
setActiveTab: vi.fn(),
queueTabSetupSplit: vi.fn(),
queueTabIssueCommandSplit: vi.fn(),
...overrides
}
}
@@ -57,5 +58,53 @@ describe('ensureWorktreeHasInitialTerminal', () => {
expect(store.createTab).not.toHaveBeenCalled()
expect(store.setActiveTab).not.toHaveBeenCalled()
expect(store.queueTabSetupSplit).not.toHaveBeenCalled()
expect(store.queueTabIssueCommandSplit).not.toHaveBeenCalled()
})
it('queues an issue command split when issueCommand is provided', () => {
const store = createMockStore()
ensureWorktreeHasInitialTerminal(store, 'wt-1', undefined, {
command: 'claude "Fix issue #42"'
})
expect(store.createTab).toHaveBeenCalledWith('wt-1')
expect(store.setActiveTab).toHaveBeenCalledWith('tab-1')
expect(store.queueTabSetupSplit).not.toHaveBeenCalled()
expect(store.queueTabIssueCommandSplit).toHaveBeenCalledWith('tab-1', {
command: 'claude "Fix issue #42"'
})
})
it('queues both setup split and issue command split when both are provided', () => {
const store = createMockStore()
ensureWorktreeHasInitialTerminal(
store,
'wt-1',
{
runnerScriptPath: '/tmp/repo/.git/orca/setup-runner.sh',
envVars: { ORCA_ROOT_PATH: '/tmp/repo' }
},
{
command: 'claude "Fix issue #42"'
}
)
expect(store.queueTabSetupSplit).toHaveBeenCalledWith('tab-1', {
command: 'bash /tmp/repo/.git/orca/setup-runner.sh',
env: { ORCA_ROOT_PATH: '/tmp/repo' }
})
expect(store.queueTabIssueCommandSplit).toHaveBeenCalledWith('tab-1', {
command: 'claude "Fix issue #42"'
})
})
it('does not queue issue command split when issueCommand is not provided', () => {
const store = createMockStore()
ensureWorktreeHasInitialTerminal(store, 'wt-1')
expect(store.queueTabIssueCommandSplit).not.toHaveBeenCalled()
})
})
+15 -1
View File
@@ -9,12 +9,17 @@ type WorktreeActivationStore = {
tabId: string,
startup: { command: string; env?: Record<string, string> }
) => void
queueTabIssueCommandSplit: (
tabId: string,
startup: { command: string; env?: Record<string, string> }
) => void
}
export function ensureWorktreeHasInitialTerminal(
store: WorktreeActivationStore,
worktreeId: string,
setup?: WorktreeSetupLaunch
setup?: WorktreeSetupLaunch,
issueCommand?: { command: string; env?: Record<string, string> }
): void {
const existingTabs = store.tabsByWorktree[worktreeId] ?? []
if (existingTabs.length > 0) {
@@ -34,4 +39,13 @@ export function ensureWorktreeHasInitialTerminal(
env: setup.envVars
})
}
// Why: when the user links a GitHub issue and opts into that repo's
// per-user issue automation, spawn a separate split pane to run the
// agent command. Queued independently from setup so both can start in
// parallel; repo bootstrap and personal issue workflows are separate
// concerns, so Orca should not invent a dependency between them.
if (issueCommand) {
store.queueTabIssueCommandSplit(terminalTab.id, issueCommand)
}
}
+51 -1
View File
@@ -30,6 +30,10 @@ export type TerminalSlice = {
* initial pane clean, then splits right and runs the command in the new pane
* so the main terminal stays immediately interactive. */
pendingSetupSplitByTabId: Record<string, { command: string; env?: Record<string, string> }>
/** Queued issue-command-split requests — similar to setup splits but triggered
* when an issue is linked during worktree creation and the repo's issue
* automation command is enabled. */
pendingIssueCommandSplitByTabId: Record<string, { command: string; env?: Record<string, string> }>
tabBarOrderByWorktree: Record<string, string[]>
workspaceSessionReady: boolean
pendingReconnectWorktreeIds: string[]
@@ -61,6 +65,13 @@ export type TerminalSlice = {
startup: { command: string; env?: Record<string, string> }
) => void
consumeTabSetupSplit: (tabId: string) => { command: string; env?: Record<string, string> } | null
queueTabIssueCommandSplit: (
tabId: string,
issueCommand: { command: string; env?: Record<string, string> }
) => void
consumeTabIssueCommandSplit: (
tabId: string
) => { command: string; env?: Record<string, string> } | null
/** Per-pane timestamp (ms) when the prompt-cache countdown started (agent became idle).
* Keys are `${tabId}:${paneId}` composites so split-pane tabs can track each pane
* independently. null means no active timer for that pane. */
@@ -84,6 +95,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
terminalLayoutsByTabId: {},
pendingStartupByTabId: {},
pendingSetupSplitByTabId: {},
pendingIssueCommandSplitByTabId: {},
tabBarOrderByWorktree: {},
workspaceSessionReady: false,
pendingReconnectWorktreeIds: [],
@@ -194,6 +206,8 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
delete nextPendingStartupByTabId[tabId]
const nextPendingSetupSplitByTabId = { ...s.pendingSetupSplitByTabId }
delete nextPendingSetupSplitByTabId[tabId]
const nextPendingIssueCommandSplitByTabId = { ...s.pendingIssueCommandSplitByTabId }
delete nextPendingIssueCommandSplitByTabId[tabId]
const nextCacheTimer = { ...s.cacheTimerByKey }
// Why: cache timer keys are `${tabId}:${paneId}` composites. Remove all
// entries for the closing tab, regardless of how many panes it had.
@@ -222,6 +236,7 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
terminalLayoutsByTabId: nextLayouts,
pendingStartupByTabId: nextPendingStartupByTabId,
pendingSetupSplitByTabId: nextPendingSetupSplitByTabId,
pendingIssueCommandSplitByTabId: nextPendingIssueCommandSplitByTabId,
cacheTimerByKey: nextCacheTimer
}
})
@@ -426,11 +441,22 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
...s.suppressedPtyExitIds,
...Object.fromEntries(ptyIds.map((ptyId) => [ptyId, true] as const))
}
// Why: clear any queued setup and issue-command splits for the affected
// tabs so stale commands do not fire unintended splits when the worktree
// is later remounted.
const nextPendingSetupSplitByTabId = { ...s.pendingSetupSplitByTabId }
const nextPendingIssueCommandSplitByTabId = { ...s.pendingIssueCommandSplitByTabId }
for (const tab of tabs) {
delete nextPendingSetupSplitByTabId[tab.id]
delete nextPendingIssueCommandSplitByTabId[tab.id]
}
return {
tabsByWorktree: nextTabsByWorktree,
ptyIdsByTabId: nextPtyIdsByTabId,
suppressedPtyExitIds: nextSuppressedPtyExitIds
suppressedPtyExitIds: nextSuppressedPtyExitIds,
pendingSetupSplitByTabId: nextPendingSetupSplitByTabId,
pendingIssueCommandSplitByTabId: nextPendingIssueCommandSplitByTabId
}
})
@@ -527,6 +553,30 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
return pending
},
queueTabIssueCommandSplit: (tabId, issueCommand) => {
set((s) => ({
pendingIssueCommandSplitByTabId: {
...s.pendingIssueCommandSplitByTabId,
[tabId]: issueCommand
}
}))
},
consumeTabIssueCommandSplit: (tabId) => {
const pending = get().pendingIssueCommandSplitByTabId[tabId]
if (!pending) {
return null
}
set((s) => {
const next = { ...s.pendingIssueCommandSplitByTabId }
delete next[tabId]
return { pendingIssueCommandSplitByTabId: next }
})
return pending
},
hydrateWorkspaceSession: (session) => {
set((s) => {
const validWorktreeIds = new Set(
+1
View File
@@ -261,6 +261,7 @@ export type OrcaHooks = {
setup?: string // Runs after worktree is created
archive?: string // Runs before worktree is archived
}
issueCommand?: string // Shared default command for linked GitHub issues
}
export type RepoHookSettings = {