Run long GitHub issue commands reliably (#583)

This commit is contained in:
Brennan Benson
2026-04-13 16:05:48 -07:00
committed by GitHub
parent 3793125319
commit 7cdc866f96
15 changed files with 718 additions and 30 deletions
+43
View File
@@ -172,3 +172,46 @@ describe('createSetupRunnerScript', () => {
}
})
})
describe('createIssueCommandRunnerScript', () => {
const makeRepo = () =>
({
id: 'test-id',
path: '/test/repo',
displayName: 'Test Repo',
badgeColor: '#000',
addedAt: Date.now()
}) as unknown as Repo
it('writes a POSIX runner under the worktree git dir for long issue commands', async () => {
const fs = await import('fs')
execFileSyncMock.mockReturnValue(
'/test/repo/.git/worktrees/feature/orca/issue-command-runner.sh'
)
const { createIssueCommandRunnerScript } = await import('./hooks')
const result = createIssueCommandRunnerScript(
makeRepo(),
'/test/repo-feature',
'codex exec "long command"\nclaude -p "review it"'
)
expect(result).toEqual({
runnerScriptPath: '/test/repo/.git/worktrees/feature/orca/issue-command-runner.sh',
envVars: expect.objectContaining({
ORCA_ROOT_PATH: '/test/repo',
ORCA_WORKTREE_PATH: '/test/repo-feature'
})
})
expect(vi.mocked(fs.writeFileSync)).toHaveBeenCalledWith(
'/test/repo/.git/worktrees/feature/orca/issue-command-runner.sh',
'#!/usr/bin/env bash\nset -e\ncodex exec "long command"\nclaude -p "review it"\n',
'utf-8'
)
expect(vi.mocked(fs.chmodSync)).toHaveBeenCalledWith(
'/test/repo/.git/worktrees/feature/orca/issue-command-runner.sh',
0o755
)
})
})
+23 -1
View File
@@ -357,6 +357,28 @@ export function createSetupRunnerScript(
repo: Repo,
worktreePath: string,
script: string
): WorktreeSetupLaunch {
return createWorktreeRunnerScript(repo, worktreePath, script, 'setup-runner')
}
export function createIssueCommandRunnerScript(
repo: Repo,
worktreePath: string,
command: string
): WorktreeSetupLaunch {
// Why: long issue-automation commands are user-visible shell input when
// written directly to the PTY, so terminal line editors can wrap or truncate
// them before execution. Writing the real command into a runner script keeps
// the shell startup path short and mirrors the already-stable setup runner
// flow instead of inventing a second launch mechanism.
return createWorktreeRunnerScript(repo, worktreePath, command, 'issue-command-runner')
}
function createWorktreeRunnerScript(
repo: Repo,
worktreePath: string,
script: string,
runnerBaseName: 'setup-runner' | 'issue-command-runner'
): WorktreeSetupLaunch {
const envVars = getSetupEnvVars(repo, worktreePath)
// Why: WSL worktrees run on a Linux filesystem even though process.platform
@@ -369,7 +391,7 @@ export function createSetupRunnerScript(
// Why: linked git worktrees use a `.git` file that points at the real gitdir,
// so writing under `${worktreePath}/.git/...` fails. `git rev-parse --git-path`
// resolves the actual per-worktree git storage path safely across platforms.
const gitRelPath = useWindowsFormat ? 'orca/setup-runner.cmd' : 'orca/setup-runner.sh'
const gitRelPath = useWindowsFormat ? `orca/${runnerBaseName}.cmd` : `orca/${runnerBaseName}.sh`
let runnerScriptPath = getGitPath(worktreePath, gitRelPath)
// Why: for WSL worktrees, getGitPath returns a Linux path (e.g. /home/user/...)
+176
View File
@@ -11,6 +11,10 @@ const {
existsSyncMock,
statSyncMock,
accessSyncMock,
mkdirSyncMock,
writeFileSyncMock,
chmodSyncMock,
getPathMock,
spawnMock,
openCodeBuildPtyEnvMock,
openCodeClearPtyMock,
@@ -24,6 +28,10 @@ const {
existsSyncMock: vi.fn(),
statSyncMock: vi.fn(),
accessSyncMock: vi.fn(),
mkdirSyncMock: vi.fn(),
writeFileSyncMock: vi.fn(),
chmodSyncMock: vi.fn(),
getPathMock: vi.fn(),
spawnMock: vi.fn(),
openCodeBuildPtyEnvMock: vi.fn(),
openCodeClearPtyMock: vi.fn(),
@@ -32,6 +40,9 @@ const {
}))
vi.mock('electron', () => ({
app: {
getPath: getPathMock
},
ipcMain: {
handle: handleMock,
on: onMock,
@@ -44,6 +55,9 @@ vi.mock('fs', () => ({
existsSync: existsSyncMock,
statSync: statSyncMock,
accessSync: accessSyncMock,
mkdirSync: mkdirSyncMock,
writeFileSync: writeFileSyncMock,
chmodSync: chmodSyncMock,
constants: {
X_OK: 1
}
@@ -92,6 +106,10 @@ describe('registerPtyHandlers', () => {
existsSyncMock.mockReset()
statSyncMock.mockReset()
accessSyncMock.mockReset()
mkdirSyncMock.mockReset()
writeFileSyncMock.mockReset()
chmodSyncMock.mockReset()
getPathMock.mockReset()
spawnMock.mockReset()
openCodeBuildPtyEnvMock.mockReset()
openCodeClearPtyMock.mockReset()
@@ -103,6 +121,7 @@ describe('registerPtyHandlers', () => {
handleMock.mockImplementation((channel, handler) => {
handlers.set(channel, handler)
})
getPathMock.mockReturnValue('/tmp/orca-user-data')
existsSyncMock.mockReturnValue(true)
statSyncMock.mockReturnValue({ isDirectory: () => true })
openCodeBuildPtyEnvMock.mockReturnValue({
@@ -125,6 +144,33 @@ describe('registerPtyHandlers', () => {
})
})
function createMockProc() {
let dataHandler: ((data: string) => void) | null = null
let exitHandler: ((event: { exitCode: number }) => void) | null = null
return {
proc: {
onData: vi.fn((handler: (data: string) => void) => {
dataHandler = handler
return makeDisposable()
}),
onExit: vi.fn((handler: (event: { exitCode: number }) => void) => {
exitHandler = handler
return makeDisposable()
}),
write: vi.fn(),
resize: vi.fn(),
kill: vi.fn()
},
emitData(data: string) {
dataHandler?.(data)
},
emitExit(exitCode = 0) {
exitHandler?.({ exitCode })
}
}
}
/** Helper: trigger pty:spawn and return the env passed to node-pty. */
function spawnAndGetEnv(
argsEnv?: Record<string, string>,
@@ -166,6 +212,25 @@ describe('registerPtyHandlers', () => {
}
}
function spawnAndGetCall(args?: {
cwd?: string
env?: Record<string, string>
command?: string
}): [string, string[], { cwd: string; env: Record<string, string> }] {
handlers.clear()
registerPtyHandlers(mainWindow as never)
handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
...args
})
return spawnMock.mock.calls.at(-1) as [
string,
string[],
{ cwd: string; env: Record<string, string> }
]
}
describe('spawn environment', () => {
it('defaults LANG to en_US.UTF-8 when not inherited from process.env', () => {
const env = spawnAndGetEnv(undefined, { LANG: undefined })
@@ -256,6 +321,117 @@ describe('registerPtyHandlers', () => {
}
})
it('spawns a plain POSIX login shell and queues startup commands for the live session', () => {
const originalPlatform = process.platform
const originalShell = process.env.SHELL
Object.defineProperty(process, 'platform', {
configurable: true,
value: 'darwin'
})
process.env.SHELL = '/bin/zsh'
try {
const [shell, args, options] = spawnAndGetCall({ cwd: '/tmp', command: 'printf "hello"' })
expect(shell).toBe('/bin/zsh')
expect(args).toEqual(['-l'])
expect(options.env.ZDOTDIR).toBe('/tmp/orca-user-data/shell-ready/zsh')
expect(options.env.ORCA_ORIG_ZDOTDIR).toBe(process.env.HOME)
} finally {
Object.defineProperty(process, 'platform', {
configurable: true,
value: originalPlatform
})
if (originalShell === undefined) {
delete process.env.SHELL
} else {
process.env.SHELL = originalShell
}
}
})
it('does not force ~/.bashrc after sourcing bash login files in the shell-ready rcfile', async () => {
const originalPlatform = process.platform
const originalShell = process.env.SHELL
Object.defineProperty(process, 'platform', {
configurable: true,
value: 'darwin'
})
process.env.SHELL = '/bin/bash'
try {
spawnAndGetCall({ cwd: '/tmp', command: 'echo hello' })
const { getBashShellReadyRcfileContent } = await import('./pty')
const bashRcContent = getBashShellReadyRcfileContent()
expect(bashRcContent).toContain('source "$HOME/.bash_profile"')
expect(bashRcContent).not.toContain('source "$HOME/.bashrc"')
} finally {
Object.defineProperty(process, 'platform', {
configurable: true,
value: originalPlatform
})
if (originalShell === undefined) {
delete process.env.SHELL
} else {
process.env.SHELL = originalShell
}
}
})
it('does not write the startup command before the shell-ready marker arrives', async () => {
vi.useFakeTimers()
const mockProc = createMockProc()
spawnMock.mockReturnValue(mockProc.proc)
try {
registerPtyHandlers(mainWindow as never)
handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/tmp',
command: 'claude'
})
expect(mockProc.proc.write).not.toHaveBeenCalled()
mockProc.emitData('last login: today\r\n')
vi.runOnlyPendingTimers()
expect(mockProc.proc.write).not.toHaveBeenCalled()
mockProc.emitData('\x1b]133;A\x07% ')
await Promise.resolve()
vi.runAllTimers()
expect(mockProc.proc.write).toHaveBeenCalledWith('claude\n')
} finally {
vi.useRealTimers()
}
})
it('falls back to a max wait when the shell emits no readiness output', async () => {
vi.useFakeTimers()
const mockProc = createMockProc()
spawnMock.mockReturnValue(mockProc.proc)
try {
registerPtyHandlers(mainWindow as never)
handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/tmp',
command: 'codex'
})
vi.advanceTimersByTime(1500)
await Promise.resolve()
vi.runAllTimers()
expect(mockProc.proc.write).toHaveBeenCalledWith('codex\n')
} finally {
vi.useRealTimers()
}
})
it('falls back to a system shell when SHELL points to a missing binary', () => {
const originalShell = process.env.SHELL
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+298 -7
View File
@@ -4,8 +4,16 @@ foreground-process inspection, and renderer IPC stay behind a single audited
boundary. Splitting it by line count would scatter tightly coupled terminal
process behavior across files without a cleaner ownership seam. */
import { basename } from 'path'
import { existsSync, accessSync, statSync, chmodSync, constants as fsConstants } from 'fs'
import { type BrowserWindow, ipcMain } from 'electron'
import {
existsSync,
accessSync,
statSync,
chmodSync,
mkdirSync,
writeFileSync,
constants as fsConstants
} from 'fs'
import { app, type BrowserWindow, ipcMain } from 'electron'
import * as pty from 'node-pty'
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
import { parseWslPath } from '../wsl'
@@ -32,6 +40,217 @@ const ptyDisposables = new Map<string, { dispose: () => void }[]>()
let loadGeneration = 0
const ptyLoadGeneration = new Map<string, number>()
let didEnsureSpawnHelperExecutable = false
let didEnsureShellReadyWrappers = false
function quotePosixSingle(value: string): string {
return `'${value.replace(/'/g, `'\\''`)}'`
}
const STARTUP_COMMAND_READY_MAX_WAIT_MS = 1500
const OSC_133_A = '\x1b]133;A'
type ShellReadyScanState = {
matchPos: number
heldBytes: string
}
function createShellReadyScanState(): ShellReadyScanState {
return { matchPos: 0, heldBytes: '' }
}
function scanForShellReady(
state: ShellReadyScanState,
data: string
): { output: string; matched: boolean } {
let output = ''
for (let i = 0; i < data.length; i += 1) {
const ch = data[i] as string
if (state.matchPos < OSC_133_A.length) {
if (ch === OSC_133_A[state.matchPos]) {
state.heldBytes += ch
state.matchPos += 1
} else {
output += state.heldBytes
state.heldBytes = ''
state.matchPos = 0
if (ch === OSC_133_A[0]) {
state.heldBytes = ch
state.matchPos = 1
} else {
output += ch
}
}
} else if (ch === '\x07') {
const remaining = data.slice(i + 1)
state.heldBytes = ''
state.matchPos = 0
return { output: output + remaining, matched: true }
} else {
state.heldBytes += ch
}
}
return { output, matched: false }
}
function getShellReadyWrapperRoot(): string {
return `${app.getPath('userData')}/shell-ready`
}
export function getBashShellReadyRcfileContent(): string {
return `# Orca bash shell-ready wrapper
[[ -f /etc/profile ]] && source /etc/profile
if [[ -f "$HOME/.bash_profile" ]]; then
source "$HOME/.bash_profile"
elif [[ -f "$HOME/.bash_login" ]]; then
source "$HOME/.bash_login"
elif [[ -f "$HOME/.profile" ]]; then
source "$HOME/.profile"
fi
# Why: preserve bash's normal login-shell contract. Many users already source
# ~/.bashrc from ~/.bash_profile; forcing ~/.bashrc again here would duplicate
# PATH edits, hooks, and prompt init in Orca startup-command shells.
# Why: append the marker through PROMPT_COMMAND so it fires after the login
# startup files have rebuilt the prompt, matching Superset's "shell ready"
# contract without re-running user rc files.
__orca_prompt_mark() {
printf "\\033]133;A\\007"
}
if [[ "$(declare -p PROMPT_COMMAND 2>/dev/null)" == "declare -a"* ]]; then
PROMPT_COMMAND=("\${PROMPT_COMMAND[@]}" "__orca_prompt_mark")
else
_orca_prev_prompt_command="\${PROMPT_COMMAND}"
if [[ -n "\${_orca_prev_prompt_command}" ]]; then
PROMPT_COMMAND="\${_orca_prev_prompt_command};__orca_prompt_mark"
else
PROMPT_COMMAND="__orca_prompt_mark"
fi
fi
`
}
function ensureShellReadyWrappers(): void {
if (didEnsureShellReadyWrappers || process.platform === 'win32') {
return
}
didEnsureShellReadyWrappers = true
const root = getShellReadyWrapperRoot()
const zshDir = `${root}/zsh`
const bashDir = `${root}/bash`
const zshEnv = `# Orca zsh shell-ready wrapper
export ORCA_ORIG_ZDOTDIR="\${ORCA_ORIG_ZDOTDIR:-$HOME}"
[[ -f "$ORCA_ORIG_ZDOTDIR/.zshenv" ]] && source "$ORCA_ORIG_ZDOTDIR/.zshenv"
export ZDOTDIR=${quotePosixSingle(zshDir)}
`
const zshProfile = `# Orca zsh shell-ready wrapper
_orca_home="\${ORCA_ORIG_ZDOTDIR:-$HOME}"
[[ -f "$_orca_home/.zprofile" ]] && source "$_orca_home/.zprofile"
`
const zshRc = `# Orca zsh shell-ready wrapper
_orca_home="\${ORCA_ORIG_ZDOTDIR:-$HOME}"
if [[ -o interactive && -f "$_orca_home/.zshrc" ]]; then
source "$_orca_home/.zshrc"
fi
`
const zshLogin = `# Orca zsh shell-ready wrapper
_orca_home="\${ORCA_ORIG_ZDOTDIR:-$HOME}"
if [[ -o interactive && -f "$_orca_home/.zlogin" ]]; then
source "$_orca_home/.zlogin"
fi
# Why: emit OSC 133;A only after the user's startup hooks finish so Orca knows
# the prompt is actually ready for a long startup command paste.
__orca_prompt_mark() {
printf "\\033]133;A\\007"
}
precmd_functions=(\${precmd_functions[@]} __orca_prompt_mark)
`
const bashRc = getBashShellReadyRcfileContent()
const files = [
[`${zshDir}/.zshenv`, zshEnv],
[`${zshDir}/.zprofile`, zshProfile],
[`${zshDir}/.zshrc`, zshRc],
[`${zshDir}/.zlogin`, zshLogin],
[`${bashDir}/rcfile`, bashRc]
] as const
for (const [path, content] of files) {
const dir = path.slice(0, path.lastIndexOf('/'))
mkdirSync(dir, { recursive: true })
writeFileSync(path, content, 'utf8')
chmodSync(path, 0o644)
}
}
function getShellReadyLaunchConfig(shellPath: string): {
args: string[] | null
env: Record<string, string>
supportsReadyMarker: boolean
} {
const shellName = basename(shellPath).toLowerCase()
if (shellName === 'zsh') {
ensureShellReadyWrappers()
return {
args: ['-l'],
env: {
ORCA_ORIG_ZDOTDIR: process.env.ZDOTDIR || process.env.HOME || '',
ZDOTDIR: `${getShellReadyWrapperRoot()}/zsh`
},
supportsReadyMarker: true
}
}
if (shellName === 'bash') {
ensureShellReadyWrappers()
return {
args: ['--rcfile', `${getShellReadyWrapperRoot()}/bash/rcfile`],
env: {},
supportsReadyMarker: true
}
}
return {
args: null,
env: {},
supportsReadyMarker: false
}
}
function writeStartupCommandWhenShellReady(
readyPromise: Promise<void>,
proc: pty.IPty,
startupCommand: string,
onExit: (cleanup: () => void) => void
): void {
let sent = false
const cleanup = (): void => {
sent = true
}
const flush = (): void => {
if (sent) {
return
}
sent = true
// Why: run startup commands inside the same interactive shell Orca keeps
// open for the pane. Spawning `shell -c <command>; exec shell -l` would
// avoid the race, but it would also replace the session after the agent
// exits and break "stay in this terminal" workflows.
const payload = startupCommand.endsWith('\n') ? startupCommand : `${startupCommand}\n`
// Why: startup commands are usually long, quoted agent launches. Writing
// them in one PTY call after the shell-ready barrier avoids the incremental
// paste behavior that still dropped characters in practice.
proc.write(payload)
}
readyPromise.then(flush)
onExit(cleanup)
}
function disposePtyListeners(id: string): void {
const disposables = ptyDisposables.get(id)
@@ -198,7 +417,16 @@ export function registerPtyHandlers(
ipcMain.handle(
'pty:spawn',
(_event, args: { cols: number; rows: number; cwd?: string; env?: Record<string, string> }) => {
(
_event,
args: {
cols: number
rows: number
cwd?: string
env?: Record<string, string>
command?: string
}
) => {
const id = String(++ptyCounter)
const defaultCwd =
@@ -218,6 +446,11 @@ export function registerPtyHandlers(
let shellArgs: string[]
let effectiveCwd: string
let validationCwd: string
let shellReadyLaunch: {
args: string[] | null
env: Record<string, string>
supportsReadyMarker: boolean
} | null = null
if (wslInfo) {
// Why: use `bash -c "cd ... && exec bash -l"` instead of `--cd` because
// wsl.exe's --cd flag fails with ERROR_PATH_NOT_FOUND in some Node
@@ -244,7 +477,8 @@ export function registerPtyHandlers(
// exactly like the inherited process shell so stale config can't brick
// terminal creation.
shellPath = args.env?.SHELL || process.env.SHELL || '/bin/zsh'
shellArgs = ['-l']
shellReadyLaunch = args.command ? getShellReadyLaunchConfig(shellPath) : null
shellArgs = shellReadyLaunch?.args ?? ['-l']
effectiveCwd = cwd
validationCwd = cwd
}
@@ -265,6 +499,7 @@ export function registerPtyHandlers(
const spawnEnv = {
...process.env,
...args.env,
...shellReadyLaunch?.env,
TERM: 'xterm-256color',
COLORTERM: 'truecolor',
TERM_PROGRAM: 'Orca',
@@ -295,7 +530,6 @@ export function registerPtyHandlers(
if (selectedCodexHomePath) {
spawnEnv.CODEX_HOME = selectedCodexHomePath
}
// Why: When Electron is launched from Finder (not a terminal), the process
// does not inherit the user's shell locale settings. Without an explicit
// UTF-8 locale, multi-byte characters (e.g. em dashes U+2014) are
@@ -344,8 +578,10 @@ export function registerPtyHandlers(
// process inherits the correct value. Leaving the stale original
// SHELL in the env would confuse shell startup logic and any
// subprocesses that inspect $SHELL.
shellReadyLaunch = args.command ? getShellReadyLaunchConfig(fallback) : null
spawnEnv.SHELL = fallback
ptyProcess = pty.spawn(fallback, ['-l'], {
Object.assign(spawnEnv, shellReadyLaunch?.env ?? {})
ptyProcess = pty.spawn(fallback, shellReadyLaunch?.args ?? ['-l'], {
name: 'xterm-256color',
cols: args.cols,
rows: args.rows,
@@ -390,7 +626,51 @@ export function registerPtyHandlers(
ptyLoadGeneration.set(id, loadGeneration)
runtime?.onPtySpawned(id)
const onDataDisposable = proc.onData((data) => {
let resolveShellReady: (() => void) | null = null
let shellReadyTimeout: ReturnType<typeof setTimeout> | null = null
const shellReadyScanState = shellReadyLaunch?.supportsReadyMarker
? createShellReadyScanState()
: null
const shellReadyPromise = args.command
? new Promise<void>((resolve) => {
resolveShellReady = resolve
})
: Promise.resolve()
const finishShellReady = (): void => {
if (!resolveShellReady) {
return
}
if (shellReadyTimeout) {
clearTimeout(shellReadyTimeout)
shellReadyTimeout = null
}
const resolve = resolveShellReady
resolveShellReady = null
resolve()
}
if (args.command) {
if (shellReadyLaunch?.supportsReadyMarker) {
shellReadyTimeout = setTimeout(() => {
finishShellReady()
}, STARTUP_COMMAND_READY_MAX_WAIT_MS)
} else {
finishShellReady()
}
}
let startupCommandCleanup: (() => void) | null = null
const onDataDisposable = proc.onData((rawData) => {
let data = rawData
if (shellReadyScanState && resolveShellReady) {
const scanned = scanForShellReady(shellReadyScanState, rawData)
data = scanned.output
if (scanned.matched) {
finishShellReady()
}
}
if (data.length === 0) {
return
}
runtime?.onPtyData(id, data, Date.now())
if (!mainWindow.isDestroyed()) {
mainWindow.webContents.send('pty:data', { id, data })
@@ -398,6 +678,11 @@ export function registerPtyHandlers(
})
const onExitDisposable = proc.onExit(({ exitCode }) => {
if (shellReadyTimeout) {
clearTimeout(shellReadyTimeout)
shellReadyTimeout = null
}
startupCommandCleanup?.()
clearPtyState(id)
clearProviderPtyState(id)
runtime?.onPtyExit(id, exitCode)
@@ -408,6 +693,12 @@ export function registerPtyHandlers(
ptyDisposables.set(id, [onDataDisposable, onExitDisposable])
if (args.command) {
writeStartupCommandWhenShellReady(shellReadyPromise, proc, args.command, (cleanup) => {
startupCommandCleanup = cleanup
})
}
return { id }
}
)
+4
View File
@@ -11,6 +11,7 @@ const {
getBranchConflictKindMock,
getPRForBranchMock,
getEffectiveHooksMock,
createIssueCommandRunnerScriptMock,
createSetupRunnerScriptMock,
shouldRunSetupForCreateMock,
runHookMock,
@@ -29,6 +30,7 @@ const {
getBranchConflictKindMock: vi.fn(),
getPRForBranchMock: vi.fn(),
getEffectiveHooksMock: vi.fn(),
createIssueCommandRunnerScriptMock: vi.fn(),
createSetupRunnerScriptMock: vi.fn(),
shouldRunSetupForCreateMock: vi.fn(),
runHookMock: vi.fn(),
@@ -62,6 +64,7 @@ vi.mock('../github/client', () => ({
}))
vi.mock('../hooks', () => ({
createIssueCommandRunnerScript: createIssueCommandRunnerScriptMock,
createSetupRunnerScript: createSetupRunnerScriptMock,
getEffectiveHooks: getEffectiveHooksMock,
loadHooks: loadHooksMock,
@@ -111,6 +114,7 @@ describe('registerWorktreeHandlers – Windows path handling', () => {
getBranchConflictKindMock.mockReset()
getPRForBranchMock.mockReset()
getEffectiveHooksMock.mockReset()
createIssueCommandRunnerScriptMock.mockReset()
createSetupRunnerScriptMock.mockReset()
shouldRunSetupForCreateMock.mockReset()
runHookMock.mockReset()
+32
View File
@@ -12,6 +12,7 @@ const {
getBranchConflictKindMock,
getPRForBranchMock,
getEffectiveHooksMock,
createIssueCommandRunnerScriptMock,
createSetupRunnerScriptMock,
shouldRunSetupForCreateMock,
runHookMock,
@@ -31,6 +32,7 @@ const {
getBranchConflictKindMock: vi.fn(),
getPRForBranchMock: vi.fn(),
getEffectiveHooksMock: vi.fn(),
createIssueCommandRunnerScriptMock: vi.fn(),
createSetupRunnerScriptMock: vi.fn(),
shouldRunSetupForCreateMock: vi.fn(),
runHookMock: vi.fn(),
@@ -70,6 +72,7 @@ vi.mock('../github/client', () => ({
}))
vi.mock('../hooks', () => ({
createIssueCommandRunnerScript: createIssueCommandRunnerScriptMock,
createSetupRunnerScript: createSetupRunnerScriptMock,
getEffectiveHooks: getEffectiveHooksMock,
loadHooks: loadHooksMock,
@@ -120,6 +123,7 @@ describe('registerWorktreeHandlers', () => {
getBranchConflictKindMock,
getPRForBranchMock,
getEffectiveHooksMock,
createIssueCommandRunnerScriptMock,
createSetupRunnerScriptMock,
shouldRunSetupForCreateMock,
runHookMock,
@@ -177,6 +181,13 @@ describe('registerWorktreeHandlers', () => {
ORCA_WORKTREE_PATH: '/workspace/improve-dashboard'
}
})
createIssueCommandRunnerScriptMock.mockReturnValue({
runnerScriptPath: '/workspace/repo/.git/orca/issue-command-runner.sh',
envVars: {
ORCA_ROOT_PATH: '/workspace/repo',
ORCA_WORKTREE_PATH: '/workspace/improve-dashboard'
}
})
computeWorktreePathMock.mockImplementation(
(
sanitizedName: string,
@@ -216,6 +227,27 @@ describe('registerWorktreeHandlers', () => {
expect(addWorktreeMock).not.toHaveBeenCalled()
})
it('creates an issue-command runner for an existing repo/worktree pair', async () => {
const result = await handlers['hooks:createIssueCommandRunner'](null, {
repoId: 'repo-1',
worktreePath: '/workspace/improve-dashboard',
command: 'codex exec "long command"'
})
expect(createIssueCommandRunnerScriptMock).toHaveBeenCalledWith(
expect.objectContaining({ id: 'repo-1' }),
'/workspace/improve-dashboard',
'codex exec "long command"'
)
expect(result).toEqual({
runnerScriptPath: '/workspace/repo/.git/orca/issue-command-runner.sh',
envVars: {
ORCA_ROOT_PATH: '/workspace/repo',
ORCA_WORKTREE_PATH: '/workspace/improve-dashboard'
}
})
})
it('lists a synthetic worktree for folder-mode repos', async () => {
store.getRepos.mockReturnValue([
{
+14
View File
@@ -17,6 +17,7 @@ import { isWslPath, parseWslPath, getWslHome } from '../wsl'
import { join } from 'path'
import { listRepoWorktrees } from '../repo-worktrees'
import {
createIssueCommandRunnerScript,
createSetupRunnerScript,
getEffectiveHooks,
loadHooks,
@@ -51,6 +52,7 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store
ipcMain.removeHandler('worktrees:updateMeta')
ipcMain.removeHandler('worktrees:persistSortOrder')
ipcMain.removeHandler('hooks:check')
ipcMain.removeHandler('hooks:createIssueCommandRunner')
ipcMain.removeHandler('hooks:readIssueCommand')
ipcMain.removeHandler('hooks:writeIssueCommand')
@@ -319,6 +321,18 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store
}
})
ipcMain.handle(
'hooks:createIssueCommandRunner',
(_event, args: { repoId: string; worktreePath: string; command: string }) => {
const repo = store.getRepo(args.repoId)
if (!repo) {
throw new Error(`Repo not found: ${args.repoId}`)
}
return createIssueCommandRunnerScript(repo, args.worktreePath, args.command)
}
)
ipcMain.handle('hooks:readIssueCommand', (_event, args: { repoId: string }) => {
const repo = store.getRepo(args.repoId)
if (!repo || isFolderRepo(repo)) {
+6
View File
@@ -242,6 +242,7 @@ export type PreloadApi = {
rows: number
cwd?: string
env?: Record<string, string>
command?: string
}) => Promise<{ id: string }>
write: (id: string, data: string) => void
resize: (id: string, cols: number, rows: number) => void
@@ -318,6 +319,11 @@ export type PreloadApi = {
check: (args: {
repoId: string
}) => Promise<{ hasHooks: boolean; hooks: OrcaHooks | null; mayNeedUpdate: boolean }>
createIssueCommandRunner: (args: {
repoId: string
worktreePath: string
command: string
}) => Promise<WorktreeSetupLaunch>
readIssueCommand: (args: { repoId: string }) => Promise<{
localContent: string | null
sharedContent: string | null
+8
View File
@@ -185,6 +185,7 @@ const api = {
rows: number
cwd?: string
env?: Record<string, string>
command?: string
}): Promise<{ id: string }> => ipcRenderer.invoke('pty:spawn', opts),
write: (id: string, data: string): void => {
@@ -591,6 +592,13 @@ const api = {
}): Promise<{ hasHooks: boolean; hooks: unknown; mayNeedUpdate: boolean }> =>
ipcRenderer.invoke('hooks:check', args),
createIssueCommandRunner: (args: {
repoId: string
worktreePath: string
command: string
}): Promise<{ runnerScriptPath: string; envVars: Record<string, string> }> =>
ipcRenderer.invoke('hooks:createIssueCommandRunner', args),
readIssueCommand: (args: {
repoId: string
}): Promise<{
@@ -4,7 +4,12 @@ import React, { useState, useCallback, useMemo, useRef, useEffect } from 'react'
import { toast } from 'sonner'
import { ChevronRight } from 'lucide-react'
import { useAppStore } from '@/store'
import type { OrcaHooks, SetupDecision, SetupRunPolicy } from '../../../../shared/types'
import type {
OrcaHooks,
SetupDecision,
SetupRunPolicy,
WorktreeSetupLaunch
} from '../../../../shared/types'
import {
Dialog,
DialogContent,
@@ -205,11 +210,28 @@ const AddWorktreeDialog = React.memo(function AddWorktreeDialog() {
// 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
let issueCommand: WorktreeSetupLaunch | undefined
if (shouldRunIssueAutomation) {
const interpolatedIssueCommand = issueCommandTemplate.replace(
/\{\{issue\}\}/g,
String(parsedLinkedIssueNumber)
)
try {
// Why: issue automation is an optional post-create convenience. If
// runner preparation fails after git has already created the worktree,
// keep the success path intact and surface the automation failure
// separately instead of claiming the whole create operation failed.
issueCommand = await window.api.hooks.createIssueCommandRunner({
repoId,
worktreePath: wt.path,
command: interpolatedIssueCommand
})
} catch (error) {
console.error('Failed to prepare issue command runner after worktree creation', error)
toast.error('Worktree created, but failed to prepare the GitHub issue command.')
}
}
activateAndRevealWorktree(wt.id, {
setup: result.setup,
@@ -149,6 +149,7 @@ export function connectPanePty(
const transport = createIpcPtyTransport({
cwd: deps.cwd,
env: paneStartup?.env,
command: paneStartup?.command,
onPtyExit: onExit,
onTitleChange,
onPtySpawn,
@@ -237,14 +238,6 @@ export function connectPanePty(
cols,
rows,
callbacks: {
onConnect: () => {
if (paneStartup?.command) {
// Why: setup commands are injected only after the PTY reports a live
// shell connection. Writing earlier is racy with shell startup files
// and can drop characters on slower shells.
transport.sendInput(`${paneStartup.command}\r`)
}
},
onData: dataCallback,
onError: reportError
}
@@ -116,4 +116,65 @@ describe('createIpcPtyTransport', () => {
expect(onAgentBecameIdle).not.toHaveBeenCalled()
expect(onBell).not.toHaveBeenCalled()
})
it('passes startup commands through PTY spawn instead of writing them after connect', async () => {
const { createIpcPtyTransport } = await import('./pty-transport')
const spawnMock = vi.fn().mockResolvedValue({ id: 'pty-1' })
const writeMock = vi.fn()
;(globalThis as { window: typeof window }).window = {
...originalWindow,
api: {
...originalWindow?.api,
pty: {
...originalWindow?.api?.pty,
spawn: spawnMock,
write: writeMock,
resize: vi.fn(),
kill: vi.fn(),
onData: vi.fn((callback: (payload: { id: string; data: string }) => void) => {
onData = callback
return () => {}
}),
onExit: vi.fn((callback: (payload: { id: string; code: number }) => void) => {
onExit = callback
return () => {}
}),
onOpenCodeStatus: vi.fn(
(
callback: (payload: {
ptyId: string
status: 'working' | 'idle' | 'permission'
}) => void
) => {
onOpenCodeStatus = callback
return () => {}
}
)
}
}
} as unknown as typeof window
const transport = createIpcPtyTransport({
cwd: '/tmp/worktree',
env: { FOO: 'bar' },
command: 'echo hello'
})
await transport.connect({
url: '',
cols: 120,
rows: 40,
callbacks: {}
})
expect(spawnMock).toHaveBeenCalledWith({
cols: 120,
rows: 40,
cwd: '/tmp/worktree',
env: { FOO: 'bar' },
command: 'echo hello'
})
expect(writeMock).not.toHaveBeenCalled()
})
})
@@ -150,6 +150,7 @@ export { extractLastOscTitle } from '../../../../shared/agent-detection'
export type IpcPtyTransportOptions = {
cwd?: string
env?: Record<string, string>
command?: string
onPtyExit?: (ptyId: string) => void
onTitleChange?: (title: string, rawTitle: string) => void
onPtySpawn?: (ptyId: string) => void
@@ -163,6 +164,7 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra
const {
cwd,
env,
command,
onPtyExit,
onTitleChange,
onPtySpawn,
@@ -274,7 +276,8 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra
cols: options.cols ?? 80,
rows: options.rows ?? 24,
cwd,
env
env,
command
})
// If destroyed while spawn was in flight, kill the new pty and bail
@@ -65,14 +65,22 @@ describe('ensureWorktreeHasInitialTerminal', () => {
const store = createMockStore()
ensureWorktreeHasInitialTerminal(store, 'wt-1', undefined, {
command: 'claude "Fix issue #42"'
runnerScriptPath: '/tmp/repo/.git/orca/issue-command-runner.sh',
envVars: {
ORCA_ROOT_PATH: '/tmp/repo',
ORCA_WORKTREE_PATH: '/tmp/worktrees/wt-1'
}
})
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"'
command: 'bash /tmp/repo/.git/orca/issue-command-runner.sh',
env: {
ORCA_ROOT_PATH: '/tmp/repo',
ORCA_WORKTREE_PATH: '/tmp/worktrees/wt-1'
}
})
})
@@ -87,7 +95,8 @@ describe('ensureWorktreeHasInitialTerminal', () => {
envVars: { ORCA_ROOT_PATH: '/tmp/repo' }
},
{
command: 'claude "Fix issue #42"'
runnerScriptPath: '/tmp/repo/.git/orca/issue-command-runner.sh',
envVars: { ORCA_ROOT_PATH: '/tmp/repo' }
}
)
@@ -96,7 +105,8 @@ describe('ensureWorktreeHasInitialTerminal', () => {
env: { ORCA_ROOT_PATH: '/tmp/repo' }
})
expect(store.queueTabIssueCommandSplit).toHaveBeenCalledWith('tab-1', {
command: 'claude "Fix issue #42"'
command: 'bash /tmp/repo/.git/orca/issue-command-runner.sh',
env: { ORCA_ROOT_PATH: '/tmp/repo' }
})
})
+6 -3
View File
@@ -31,7 +31,7 @@ export function activateAndRevealWorktree(
worktreeId: string,
opts?: {
setup?: WorktreeSetupLaunch
issueCommand?: { command: string; env?: Record<string, string> }
issueCommand?: WorktreeSetupLaunch
}
): boolean {
const state = useAppStore.getState()
@@ -83,7 +83,7 @@ export function ensureWorktreeHasInitialTerminal(
store: WorktreeActivationStore,
worktreeId: string,
setup?: WorktreeSetupLaunch,
issueCommand?: { command: string; env?: Record<string, string> }
issueCommand?: WorktreeSetupLaunch
): void {
const existingTabs = store.tabsByWorktree[worktreeId] ?? []
if (existingTabs.length > 0) {
@@ -110,6 +110,9 @@ export function ensureWorktreeHasInitialTerminal(
// 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)
store.queueTabIssueCommandSplit(terminalTab.id, {
command: buildSetupRunnerCommand(issueCommand.runnerScriptPath),
env: issueCommand.envVars
})
}
}