Skip to content

Commit e463aea

Browse files
committed
fix(agent-launch): keep a short-lined multi-line prompt on a local zsh launch line, as main did
#24257 moved every multi-line or over-512-byte prompt off the typed launch line and pasted it after readiness. The phone's AI buttons and review notes, whose multi-line prompts main typed whole into zsh, then reached Claude 0.5-3 s later and their RPC reply waited for the paste. The host now names the shell a local macOS or Linux line is typed into, the way the spawn picks it, and a multi-line prompt rides a zsh line when every line is at most 512 bytes and the whole line at most 8 KB. A real-zsh test types such a line through Orca's own ready barrier and startup write, including when a slow user config makes the write land early. Elsewhere the measured unsafe cases keep the paste: bash 3.2 runs multi-line lines piecemeal, fish drops an early multi-line write, and any shell loses a line over 1 KB written early.
1 parent d268089 commit e463aea

10 files changed

Lines changed: 374 additions & 14 deletions
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
/**
2+
* Real-zsh proof for the typed launch lines `startup-line-prompt-carry.ts` lets a prompt ride: a
3+
* multi-line line whose every line fits the per-line budget, up to the whole-line budget, reaches
4+
* zsh intact through Orca's own wrapper, ready marker and startup write.
5+
*
6+
* Why a slow user config too: the write is released 1.5 s after spawn even without the marker, and
7+
* then lands while the terminal is still line-buffered, where macOS keeps at most MAX_CANON bytes of
8+
* one line. The per-line budget is what survives that; a single 1.1 KB line did not.
9+
*/
10+
import { spawnSync } from 'node:child_process'
11+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
12+
import { tmpdir } from 'node:os'
13+
import { join } from 'node:path'
14+
import * as pty from 'node-pty'
15+
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
16+
import {
17+
createShellStartupOutputScanState,
18+
scanShellStartupOutput
19+
} from '../shell-startup-output-scanner'
20+
import { selectShellStartupFeatures } from '../shell-startup-features'
21+
import { isBracketedPasteSafeShell } from '../../shared/startup-command-submission'
22+
import {
23+
TYPED_STARTUP_LINE_PROMPT_BUDGET_BYTES,
24+
ZSH_MULTI_LINE_STARTUP_LINE_BUDGET_BYTES
25+
} from '../../shared/startup-line-prompt-carry'
26+
import {
27+
restoreUserDataPathAfterEach,
28+
setTestUserDataPath
29+
} from './local-pty-shell-ready-test-harness'
30+
31+
const ZSH_PATH =
32+
process.platform === 'win32'
33+
? ''
34+
: (spawnSync('sh', ['-c', 'command -v zsh'], { encoding: 'utf8' }).stdout ?? '').trim()
35+
36+
/** Lines of prompt text, each `perLine` bytes. */
37+
function promptLines(lineCount: number, perLine: number): string {
38+
const words = 'Fix the failing checks on this branch, then explain what changed and why.'
39+
return Array.from({ length: lineCount }, (_unused, index) => {
40+
let line = `L${index}:`
41+
while (line.length < perLine) {
42+
line += ` ${words}`
43+
}
44+
return line.slice(0, perLine)
45+
}).join('\n')
46+
}
47+
48+
let home = ''
49+
50+
beforeEach(() => {
51+
home = mkdtempSync(join(tmpdir(), 'orca-typed-line-home-'))
52+
setTestUserDataPath(mkdtempSync(join(tmpdir(), 'orca-typed-line-ud-')))
53+
})
54+
55+
afterEach(() => {
56+
rmSync(home, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })
57+
})
58+
59+
restoreUserDataPathAfterEach()
60+
61+
/** Types `printf '%s' '<text>' > out` the way a local pane types a launch line; returns what ran. */
62+
async function typeIntoZsh(text: string, userConfigSeconds: number): Promise<string | null> {
63+
if (userConfigSeconds > 0) {
64+
writeFileSync(join(home, '.zshrc'), `sleep ${userConfigSeconds}\n`)
65+
}
66+
const out = join(home, 'out.txt')
67+
const done = join(home, 'done.txt')
68+
const { ensureShellReadyWrappers } = await import('./local-pty-shell-ready-wrapper-generation')
69+
const { getShellLaunchConfig } = await import('./local-pty-shell-ready')
70+
const { writeStartupCommandWhenShellReady, STARTUP_COMMAND_READY_MAX_WAIT_MS } =
71+
await import('./local-pty-shell-ready-startup-command')
72+
ensureShellReadyWrappers()
73+
const env: Record<string, string> = { PATH: '/usr/bin:/bin', HOME: home }
74+
const launch = getShellLaunchConfig(
75+
ZSH_PATH,
76+
selectShellStartupFeatures({
77+
shellPath: ZSH_PATH,
78+
env,
79+
hasStartupCommand: true,
80+
waitsForShellReady: true,
81+
emitsStartupIdentity: false
82+
})
83+
)
84+
expect(launch.supportsReadyMarker).toBe(true)
85+
const proc = pty.spawn(ZSH_PATH, launch.args ?? [], {
86+
name: 'xterm-256color',
87+
cols: 200,
88+
rows: 40,
89+
cwd: home,
90+
// Why ORCA_ORIG_ZDOTDIR: the user's config is read from the sandbox home, not the real one.
91+
env: { ...env, ...launch.env, ORCA_ORIG_ZDOTDIR: home, TERM: 'xterm-256color' }
92+
})
93+
const scan = createShellStartupOutputScanState()
94+
let resolveReady: ((signal: { postMarkerBytesObserved: boolean }) => void) | null = null
95+
const ready = new Promise<{ postMarkerBytesObserved: boolean }>((resolve) => {
96+
resolveReady = resolve
97+
})
98+
// The provider's cap (local-pty-shell-readiness-session.ts): a later marker releases the write.
99+
const cap = setTimeout(() => {
100+
resolveReady?.({ postMarkerBytesObserved: false })
101+
resolveReady = null
102+
}, STARTUP_COMMAND_READY_MAX_WAIT_MS)
103+
proc.onData((data) => {
104+
if (resolveReady && scanShellStartupOutput(scan, data).ready) {
105+
resolveReady({ postMarkerBytesObserved: true })
106+
resolveReady = null
107+
}
108+
})
109+
writeStartupCommandWhenShellReady(
110+
ready,
111+
proc,
112+
`printf '%s' '${text}' > '${out}'; printf ok > '${done}'`,
113+
() => {},
114+
{
115+
bracketedPasteSafe: isBracketedPasteSafeShell({
116+
shellName: 'zsh',
117+
waitsForShellReady: launch.supportsReadyMarker === true
118+
})
119+
}
120+
)
121+
const deadline = Date.now() + 20_000 + userConfigSeconds * 1000
122+
while (!existsSync(done) && Date.now() < deadline) {
123+
await new Promise((resolve) => setTimeout(resolve, 50))
124+
}
125+
clearTimeout(cap)
126+
const ran = existsSync(out) ? readFileSync(out, 'utf8') : null
127+
const exited = new Promise<void>((resolve) => proc.onExit(() => resolve()))
128+
proc.kill()
129+
await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 2000))])
130+
return ran
131+
}
132+
133+
describe.skipIf(!ZSH_PATH)('a multi-line launch line typed into zsh', () => {
134+
// Lines at the per-line budget, as many as the whole-line budget leaves room for.
135+
const perLine = TYPED_STARTUP_LINE_PROMPT_BUDGET_BYTES - 1
136+
const text = promptLines(
137+
Math.floor((ZSH_MULTI_LINE_STARTUP_LINE_BUDGET_BYTES - 200) / (perLine + 1)),
138+
perLine
139+
)
140+
141+
it('arrives whole through the ready barrier', async () => {
142+
expect(await typeIntoZsh(text, 0)).toBe(text)
143+
}, 60_000)
144+
145+
it('arrives whole when the user config outlasts the barrier and the write lands early', async () => {
146+
expect(await typeIntoZsh(text, 3)).toBe(text)
147+
}, 60_000)
148+
})
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { nameLocalTypedLineShell } from './agent-launch-typed-line-shell'
3+
4+
describe('naming the shell a local launch line is typed into', () => {
5+
it('takes the request’s shell first, then the setting, then SHELL, as the spawn does', () => {
6+
const base = { isRemote: false, platform: 'darwin' as const, envShell: '/bin/bash' }
7+
expect(
8+
nameLocalTypedLineShell({
9+
...base,
10+
shellOverride: '/opt/homebrew/bin/fish',
11+
defaultShellSetting: '/bin/zsh'
12+
})
13+
).toBe('fish')
14+
expect(nameLocalTypedLineShell({ ...base, defaultShellSetting: ' /bin/zsh ' })).toBe('zsh')
15+
expect(nameLocalTypedLineShell(base)).toBe('bash')
16+
expect(nameLocalTypedLineShell({ ...base, envShell: '' })).toBe('zsh')
17+
})
18+
19+
it('names none for a remote host, whose relay picks its own login shell', () => {
20+
expect(
21+
nameLocalTypedLineShell({ isRemote: true, platform: 'darwin', envShell: '/bin/zsh' })
22+
).toBeUndefined()
23+
})
24+
25+
it('names none on Windows, where the pane may be cmd, PowerShell, Git Bash or WSL', () => {
26+
expect(
27+
nameLocalTypedLineShell({ isRemote: false, platform: 'win32', envShell: '/bin/zsh' })
28+
).toBeUndefined()
29+
})
30+
})
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { basename } from 'node:path'
2+
3+
/**
4+
* The shell a local pane's startup line gets typed into, named before the spawn the way the spawn
5+
* picks it: the request's shell, the default-shell setting, then `SHELL`
6+
* (`ipc/pty/runtime/spawn-preflight.ts`, then the local or daemon launch plan).
7+
*
8+
* Undefined where the host cannot name it: a remote host, whose relay picks its own login shell,
9+
* and Windows, whose pane may be cmd, PowerShell, Git Bash or a WSL distro.
10+
*/
11+
export function nameLocalTypedLineShell(args: {
12+
isRemote: boolean
13+
shellOverride?: string
14+
defaultShellSetting?: string
15+
platform?: NodeJS.Platform
16+
envShell?: string
17+
}): string | undefined {
18+
if (args.isRemote || (args.platform ?? process.platform) === 'win32') {
19+
return undefined
20+
}
21+
const shellPath =
22+
args.shellOverride?.trim() ||
23+
args.defaultShellSetting?.trim() ||
24+
(args.envShell ?? process.env.SHELL) ||
25+
'/bin/zsh'
26+
return basename(shellPath).toLowerCase()
27+
}

‎src/main/runtime/agent-terminal-startup-prompt.test.ts‎

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,10 @@ vi.mock('electron', () => ({
1717
app: { getPath: vi.fn(() => '/tmp') }
1818
}))
1919

20-
function runtimeWithAgentLaunch(): {
20+
// The shell the host names for a local line; bash takes no multi-line line, zsh does.
21+
function runtimeWithAgentLaunch(
22+
options: { terminalDefaultShell?: string; connectionId?: string } = {}
23+
): {
2124
runtime: OrcaRuntimeService
2225
spawn: ReturnType<typeof vi.fn>
2326
} {
@@ -27,11 +30,13 @@ function runtimeWithAgentLaunch(): {
2730
store: { getSettings: () => Record<string, unknown> }
2831
resolveTerminalWorkspaceLaunchScope: (selector: string) => Promise<unknown>
2932
}
30-
internal.store = { getSettings: () => ({}) }
33+
internal.store = {
34+
getSettings: () => ({ terminalDefaultShell: options.terminalDefaultShell ?? '/bin/bash' })
35+
}
3136
vi.spyOn(internal, 'resolveTerminalWorkspaceLaunchScope').mockResolvedValue({
3237
id: 'wt-1',
3338
path: '/repo/app',
34-
connectionId: null,
39+
connectionId: options.connectionId ?? null,
3540
repo: null,
3641
folderWorkspace: null
3742
})
@@ -83,6 +88,37 @@ describe('a terminal create that is handed a launch prompt', () => {
8388
expect(onStartupPromptCarry).toHaveBeenCalledWith(false)
8489
})
8590

91+
it('carries a short-lined multi-line prompt on a local zsh line, so the agent starts with it', async () => {
92+
const { runtime, spawn } = runtimeWithAgentLaunch({ terminalDefaultShell: '/bin/zsh' })
93+
const onStartupPromptCarry = vi.fn()
94+
95+
await runtime.createTerminal('id:wt-1', {
96+
startupAgent: 'claude',
97+
startupPrompt: 'summarize the diff\nthen list the risks',
98+
onStartupPromptCarry
99+
})
100+
101+
expect(spawnedCommand(spawn)).toContain('summarize the diff\nthen list the risks')
102+
expect(onStartupPromptCarry).toHaveBeenCalledWith(true)
103+
})
104+
105+
it('starts clean on a remote host, whose shell this host cannot name', async () => {
106+
const { runtime, spawn } = runtimeWithAgentLaunch({
107+
terminalDefaultShell: '/bin/zsh',
108+
connectionId: 'ssh-1'
109+
})
110+
const onStartupPromptCarry = vi.fn()
111+
112+
await runtime.createTerminal('id:wt-1', {
113+
startupAgent: 'claude',
114+
startupPrompt: 'summarize the diff\nthen list the risks',
115+
onStartupPromptCarry
116+
})
117+
118+
expect(spawnedCommand(spawn)).not.toContain('summarize')
119+
expect(onStartupPromptCarry).toHaveBeenCalledWith(false)
120+
})
121+
86122
it('starts Hermes clean instead of refusing when its env budget cannot hold the prompt', async () => {
87123
const { runtime, spawn } = runtimeWithAgentLaunch()
88124
const onStartupPromptCarry = vi.fn()

‎src/main/runtime/orca-runtime-resolve-worktree-removal-target.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { resolveLocalProjectRuntimeForWorktreeId } from '../local-project-runtim
2121
import { resolveBareAgentLaunchCommand } from './runtime-agent-launch-resolution'
2222
import { agentPromptRidesLaunchCommand } from '../../shared/tui-agent-startup'
2323
import { planStartupWithPromptCandidate } from '../../shared/startup-line-prompt-carry'
24+
import { nameLocalTypedLineShell } from './agent-launch-typed-line-shell'
2425
import { resolveAgentStartupPlanInputs } from '../../shared/agent-startup-plan-inputs'
2526
import { agentStartedTelemetry } from '../agent-launch/agent-started-telemetry'
2627

@@ -232,7 +233,14 @@ export class OrcaRuntimeWithResolveWorktreeRemovalTarget extends OrcaRuntimeWith
232233
windowsShellOverride: opts.shellOverride,
233234
sessionOptions: this.toAgentSessionOptions(opts.launchPreferences)
234235
}),
235-
opts.startupPrompt ?? ''
236+
opts.startupPrompt ?? '',
237+
nameLocalTypedLineShell({
238+
isRemote,
239+
...(opts.shellOverride ? { shellOverride: opts.shellOverride } : {}),
240+
...(settings.terminalDefaultShell
241+
? { defaultShellSetting: settings.terminalDefaultShell }
242+
: {})
243+
})
236244
)
237245
if (!startupPlan) {
238246
// Why: an explicit agent that yields no plan would otherwise spawn a bare

‎src/main/runtime/runtime-store-contract.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,8 @@ export type RuntimeStore = {
8686
agentDefaultArgs?: GlobalSettings['agentDefaultArgs']
8787
agentDefaultEnv?: GlobalSettings['agentDefaultEnv']
8888
terminalWindowsShell?: GlobalSettings['terminalWindowsShell']
89+
// Read by the launch-line carry rule to name the shell a local line is typed into.
90+
terminalDefaultShell?: GlobalSettings['terminalDefaultShell']
8991
floatingTerminalEnabled?: GlobalSettings['floatingTerminalEnabled']
9092
agentStatusHooksEnabled?: GlobalSettings['agentStatusHooksEnabled']
9193
terminalCopyTrimsGutter?: GlobalSettings['terminalCopyTrimsGutter']

‎src/main/runtime/runtime-worktree-agent-startup.test.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,10 +109,10 @@ describe('buildWorktreeStartupForAgent host resolution', () => {
109109
})
110110

111111
describe('buildWorktreeStartupForAgent prompt carry', () => {
112-
const build = (onPromptCarry?: (carried: boolean) => void) =>
112+
const build = (onPromptCarry?: (carried: boolean) => void, terminalDefaultShell = '/bin/bash') =>
113113
buildWorktreeStartupForAgent({
114114
repo: makeRepo({}),
115-
settings,
115+
settings: Object.assign({}, settings, { terminalDefaultShell }),
116116
agent: 'claude',
117117
prompt: 'summarize the diff\nthen list the risks',
118118
getLaunchPlatform: () => 'linux',
@@ -129,6 +129,14 @@ describe('buildWorktreeStartupForAgent prompt carry', () => {
129129
expect(onPromptCarry).toHaveBeenCalledWith(false)
130130
})
131131

132+
it('carries a short-lined multi-line prompt on a local zsh line, as main typed it', () => {
133+
const onPromptCarry = vi.fn()
134+
const result = build(onPromptCarry, '/bin/zsh')
135+
136+
expect(result.startup.command).toContain('summarize the diff\nthen list the risks')
137+
expect(onPromptCarry).toHaveBeenCalledWith(true)
138+
})
139+
132140
it('keeps folding the prompt for a caller that delivers nothing afterwards', () => {
133141
// `orca worktree create --prompt` has no post-start paste of its own for an argv agent.
134142
expect(build().startup.command).toContain('summarize the diff')

‎src/main/runtime/runtime-worktree-agent-startup.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { isTuiAgentEnabled, pickTuiAgent } from '../../shared/tui-agent-selectio
1010
import { resolveAgentStartupPlanInputs } from '../../shared/agent-startup-plan-inputs'
1111
import { buildAgentDraftLaunchPlan, buildAgentStartupPlan } from '../../shared/tui-agent-startup'
1212
import { planStartupWithPromptCandidate } from '../../shared/startup-line-prompt-carry'
13+
import { nameLocalTypedLineShell } from './agent-launch-typed-line-shell'
1314
import {
1415
detectInstalledAgentsWithShellPathHydration,
1516
detectRemoteAgents
@@ -152,7 +153,16 @@ export function buildWorktreeStartupForAgent(
152153
const prompt = environment.prompt ?? ''
153154
let startupPlan: ReturnType<typeof buildAgentStartupPlan>
154155
if (environment.onPromptCarry) {
155-
const offered = planStartupWithPromptCandidate(planInputs, prompt)
156+
const offered = planStartupWithPromptCandidate(
157+
planInputs,
158+
prompt,
159+
nameLocalTypedLineShell({
160+
isRemote: repoIsRemote(repo),
161+
...(settings.terminalDefaultShell
162+
? { defaultShellSetting: settings.terminalDefaultShell }
163+
: {})
164+
})
165+
)
156166
startupPlan = offered.plan
157167
if (startupPlan && prompt.trim()) {
158168
environment.onPromptCarry(offered.promptCarried)

0 commit comments

Comments
 (0)