Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
a8f3368
Stop retrying final native agent startup refusals
brennanb2025 Nov 1, 2026
66dbdd7
Retire startup opens after exit and keep final answers across exit or…
brennanb2025 Nov 1, 2026
991b57a
Keep saving the last turn when a Claude process exits after startup
brennanb2025 Nov 1, 2026
557f19e
Merge duplicate test imports
brennanb2025 Nov 1, 2026
8bc59be
Bound resumed Claude starts that exit during catch-up and keep untype…
brennanb2025 Nov 2, 2026
2a19787
Merge origin/main into brennanb2025/sta-12982-start-refusal
brennanb2025 Nov 2, 2026
8773078
test: pin the fake clock in the resumed-exit start test
brennanb2025 Nov 2, 2026
e23686c
test: bound startup answer parsing by candidates at N and 10N records
brennanb2025 Nov 2, 2026
e8b00de
test: shape startup fixtures like the real providers
brennanb2025 Nov 2, 2026
f21eac9
test: use the real Codex canonical-filename refusal wire capture
brennanb2025 Nov 2, 2026
4843f9f
Merge origin/main into brennanb2025/sta-12982-start-refusal
brennanb2025 Nov 2, 2026
ec075ac
Merge origin/main into brennanb2025/sta-12982-start-refusal
brennanb2025 Nov 2, 2026
eb89353
Merge origin/main into brennanb2025/sta-12982-start-refusal
brennanb2025 Nov 2, 2026
2cd77e2
Merge origin/main into brennanb2025/sta-12982-start-refusal
brennanb2025 Nov 2, 2026
3950a7f
test(claude): align merged startup tests with answer-wins and final g…
brennanb2025 Nov 2, 2026
69aac89
fix(claude): let a final initialize answer outrank a physical exit re…
brennanb2025 Nov 2, 2026
625e0c5
test(claude): await a macrotask instead of real time in the exit-answ…
brennanb2025 Nov 2, 2026
eebfbc6
test(claude): replace casts in the exit-answer start test with an ann…
brennanb2025 Nov 2, 2026
8117c12
Merge origin/main into brennanb2025/sta-12982-start-refusal
brennanb2025 Nov 2, 2026
9704293
fix(agent-session): let each adapter decide a failed start, and give …
brennanb2025 Nov 3, 2026
185ee48
fix(agent-session): bound a failed start's lifetime and keep Orca's o…
brennanb2025 Nov 3, 2026
a8e3da9
fix(agent-session): let a start's owner, not its live route, keep and…
brennanb2025 Nov 3, 2026
2690728
Merge origin/main into brennanb2025/sta-12982-start-refusal
brennanb2025 Nov 3, 2026
334fd19
test(agent-session): give the worker retry fake the Codex adapter's t…
brennanb2025 Nov 3, 2026
9f43dd0
fix(agent-session): let Claude's own exit record decide a start the S…
brennanb2025 Nov 3, 2026
f394bed
perf(agent-session): stop parsing Claude's startup output once its fa…
brennanb2025 Nov 3, 2026
2be8d5b
fix(agent-session): decide a failed start once from everything its ad…
brennanb2025 Nov 3, 2026
eeac0fc
fix(acp): keep a missed saved-session load deadline instead of openin…
brennanb2025 Nov 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 37 additions & 6 deletions src/main/acp/acp-agent-connection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import {
type AcpAgentConnection,
type AcpAgentConnectionOptions
} from './acp-agent-connection'
import { AcpAuthRequiredError } from './acp-errors'
import { AcpAgentExitedError, AcpAuthRequiredError } from './acp-errors'
import { acpStartFailure } from './acp-startup-outcome'
import captures from '../native-chat/agent-session-wire/__fixtures__/startup-protocol-rejections.json'
import { PROVIDER_SPAWN_FAILURE_MARKER } from '../provider-process/provider-spawn-failure-report'
import { providerExecutableMissing } from '../provider-process/provider-executable-missing'
import { AcpScriptedAgent, deferred, tick } from './acp-scripted-agent.test-support'
Expand Down Expand Up @@ -236,6 +238,8 @@ describe('ACP process-owning connection', () => {
const rejected = expect(connection.prompt([...prompt])).rejects.toThrow('broken pipe')
child.stdin.emit('error', new Error('broken pipe'))
child.emit('close', 0, null)
// The call waits the drain bound for an answer the agent may already have written.
await vi.advanceTimersByTimeAsync(1_000)
await rejected
expect(connection.closed).toBe(true)
expect(connection.rootVerdict).toBe('live')
Expand Down Expand Up @@ -307,6 +311,33 @@ describe('ACP process-owning connection', () => {
}
)

it('keeps the final answer an agent wrote just before it exited, and only then reads its exit', async () => {
const { response } = captures.acp
const onExit = vi.fn()
const { connection, agent, child } = fixture({ onExit }, { exitOnEnd: false })
// The recorded refusal answers this start's session request just after the agent exited.
agent.on('session/new', (frame) => {
child.emit('exit', 0, null)
setImmediate(() => agent.send({ ...response, jsonrpc: '2.0', id: frame.id }))
})
const loaded = connection.start(start).catch((error: unknown) => error)
expect(await loaded).toMatchObject({ code: response.error.code, data: response.error.data })
expect(acpStartFailure(await loaded).retry).toBe('never')
agent.stdout.end()
await vi.waitFor(() => expect(onExit).toHaveBeenCalledOnce())
})

it('answers an unanswered call with the drained exit, which may start once more', async () => {
const { connection, agent, child } = fixture({}, { exitOnEnd: false })
agent.on('session/new', () => {
child.emit('exit', 1, null)
agent.stdout.end()
})
const loaded = connection.start(start).catch((error: unknown) => error)
expect(await loaded).toBeInstanceOf(AcpAgentExitedError)
expect(acpStartFailure(await loaded).retry).toBe('safe')
})

it('isolates early and late exit subscribers and continues delivering exit', () => {
const onDiagnostic = vi.fn(() => {
throw new Error('diagnostic')
Expand All @@ -319,11 +350,11 @@ describe('ACP process-owning connection', () => {
connection.onExit(failing)
connection.onExit(early)
expect(() => child.emit('exit', 0, null)).not.toThrow()
expect(early).toHaveBeenCalledExactlyOnceWith({
code: 0,
signal: null,
processless: false
})
expect(early).toHaveBeenCalledExactlyOnceWith(
{ code: 0, signal: null, processless: false },
false,
undefined
)
expect(() => connection.onExit(failing)).not.toThrow()
const late = vi.fn()
connection.onExit(late)
Expand Down
90 changes: 74 additions & 16 deletions src/main/acp/acp-agent-connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ import {
type ProviderProcessExit
} from '../provider-process/managed-provider-process'
import type { ProviderProcessLaunch } from '../provider-process/provider-process-launch'
import {
afterProviderOutputDrains,
PROVIDER_EXIT_OUTPUT_DRAIN_MS
} from '../provider-process/provider-exit-output-drain'
import {
withProviderSpawnAbsence,
type ProviderSpawnAbsence
} from '../provider-process/provider-executable-missing'
import { AcpConnectionClosedError, AcpSignInPromptError } from './acp-errors'
import { AcpAgentExitedError, AcpConnectionClosedError, AcpSignInPromptError } from './acp-errors'
import { resolveAcpPeerOptions, type AcpPeerOptions } from './acp-peer-limits'
import { AcpSessionRuntime, type AcpSessionRuntimeOptions } from './acp-session-runtime'

Expand Down Expand Up @@ -42,9 +46,21 @@ export function createAcpAgentConnection(
return new AcpAgentConnection(launch, options, spawnImpl)
}

type AcpConnectionLifecycle = {
closing: boolean
error?: Error
/** The process's own failure, such as its spawn; it is no refusal by Orca. */
processError?: Error
/** Why the connection closed before the process exited, unless Orca closed it or the process
* itself failed. Taken when it closed. */
lost?: Error
finishExit?: () => void
outputEndTimer?: ReturnType<typeof setTimeout>
}

export class AcpAgentConnection extends AcpSessionRuntime {
private readonly managed: ManagedProviderProcess
private readonly lifecycle: { closing: boolean; error?: Error }
private readonly lifecycle: AcpConnectionLifecycle
private readonly diagnoseLifecycle: (message: string) => void
readonly spawned: Promise<void>

Expand Down Expand Up @@ -86,7 +102,7 @@ export class AcpAgentConnection extends AcpSessionRuntime {
}
: {})
})
const lifecycle: { closing: boolean; error?: Error } = { closing: false }
const lifecycle: AcpConnectionLifecycle = { closing: false }
const diagnose = (message: string): void => {
try {
options.onDiagnostic?.(message)
Expand All @@ -99,7 +115,21 @@ export class AcpAgentConnection extends AcpSessionRuntime {
peer,
onOtherLine: (line, cut) => signInLine(line, 'stdout', cut),
onAuthAnswered: (signedIn) => signIn?.answered?.(signedIn),
// A closed stdin usually means the agent is exiting; its exit settles calls once its output
// drained, so the bound only covers an agent that stopped reading without exiting.
onOutputEnd: (_error, finish) => {
lifecycle.outputEndTimer = setTimeout(finish, PROVIDER_EXIT_OUTPUT_DRAIN_MS)
lifecycle.outputEndTimer.unref()
},
onClose: (error) => {
if (
!lifecycle.error &&
!lifecycle.closing &&
managed.rootVerdict !== 'exited' &&
error !== lifecycle.processError
) {
lifecycle.lost = error
}
lifecycle.error ??= error
if (lifecycle.closing || managed.rootVerdict === 'exited') {
return
Expand Down Expand Up @@ -132,7 +162,10 @@ export class AcpAgentConnection extends AcpSessionRuntime {
child.once('spawn', done)
child.once('error', done)
})
child.on('error', (error) => super.close(error))
child.on('error', (error) => {
lifecycle.processError ??= error
super.close(error)
})
signedOut = () => {
signIn?.answered?.(false)
super.close(new AcpSignInPromptError('The agent asked to sign in in a browser'))
Expand All @@ -142,16 +175,31 @@ export class AcpAgentConnection extends AcpSessionRuntime {
super.close(new AcpConnectionClosedError('The agent printed a sign-in link Orca cannot read'))
child.stderr.on('error', (error) => super.close(error))
managed.onExit((exit) => {
const error = withProviderSpawnAbsence(
lifecycle.error ??
new AcpConnectionClosedError(managed.stderrTail().trim() || `${launch.command} exited`),
managed.spawnAbsence
)
super.close(error)
try {
options.onExit?.(error, { expected: lifecycle.closing, exit })
} catch (failure) {
diagnose(`ACP exit listener failed: ${String(failure)}`)
const expected = lifecycle.closing
const finish = (): void => {
clearTimeout(lifecycle.outputEndTimer)
const detail = managed.stderrTail().trim() || `${launch.command} exited`
// Only an exit Orca neither caused nor preceded with its own refusal leaves calls unanswered.
const error = withProviderSpawnAbsence(
lifecycle.error ??
(expected
? new AcpConnectionClosedError(detail)
: new AcpAgentExitedError(detail, managed.stderrTail().trim())),
managed.spawnAbsence
)
super.close(error)
try {
options.onExit?.(error, { expected, exit })
} catch (failure) {
diagnose(`ACP exit listener failed: ${String(failure)}`)
}
}
// A closed connection has no call left for the agent's output to answer.
if (lifecycle.closing || exit.processless || this.closed) {
finish()
} else {
// An answer written just before exit must still settle its call.
lifecycle.finishExit = afterProviderOutputDrains(child.stdout, finish, child)
}
})
}
Expand Down Expand Up @@ -193,10 +241,18 @@ export class AcpAgentConnection extends AcpSessionRuntime {
return this.managed.exitStatus
}

onExit(listener: (exit: ProviderProcessExit) => void): void {
/** Why the connection closed before the process exited, such as Orca refusing what the agent
* wrote; never the process's own failure or its exit. Kept from the moment it closed. */
get lostBeforeExit(): Error | undefined {
return this.lifecycle.lost
}

/** `requested`: Orca was closing the agent when it exited. `lost`: why the connection had
* already closed before the exit, such as Orca refusing what the agent wrote. */
onExit(listener: (exit: ProviderProcessExit, requested?: boolean, lost?: Error) => void): void {
this.managed.onExit((exit) => {
try {
listener(exit)
listener(exit, this.lifecycle.closing, this.lifecycle.lost)
} catch (failure) {
this.diagnoseLifecycle(`ACP exit listener failed: ${String(failure)}`)
}
Expand All @@ -213,6 +269,8 @@ export class AcpAgentConnection extends AcpSessionRuntime {

override close(error?: Error): Promise<boolean> {
this.lifecycle.closing ||= this.managed.rootVerdict !== 'exited'
clearTimeout(this.lifecycle.outputEndTimer)
this.lifecycle.finishExit?.()
this.drainNotifications(error)
return this.managed
.close()
Expand Down
16 changes: 16 additions & 0 deletions src/main/acp/acp-errors.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import type { AuthMethod } from './generated/acp-protocol.generated'
import { withProviderRequestTimeout } from '../provider-process/provider-request-timeout'
import {
providerDiagnostic,
withProviderDiagnostic
} from '../../shared/agent-session/failures/agent-session-failure'

export class AcpRpcError extends Error {
constructor(
Expand Down Expand Up @@ -76,6 +80,18 @@ export class AcpConnectionClosedError extends Error {
}
}

/** The agent's process ended on its own and its output drained with the call still unanswered.
* Its stderr is the agent's own account, shown behind Details. */
export class AcpAgentExitedError extends AcpConnectionClosedError {
constructor(message: string, stderr = '') {
super(message)
this.name = 'AcpAgentExitedError'
if (stderr) {
withProviderDiagnostic(this, providerDiagnostic(stderr, 'person'))
}
}
}

export class AcpRequestTimeoutError extends Error {
constructor(
readonly method: string,
Expand Down
43 changes: 43 additions & 0 deletions src/main/acp/acp-json-rpc-peer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
} from './acp-errors'
import { AcpScriptedAgent, deferred, tick } from './acp-scripted-agent.test-support'
import { providerRequestTimeoutOf } from '../provider-process/provider-request-timeout'
import captures from '../native-chat/agent-session-wire/__fixtures__/startup-protocol-rejections.json'

const peers: AcpJsonRpcPeer[] = []
const agents: AcpScriptedAgent[] = []
Expand Down Expand Up @@ -382,4 +383,46 @@ describe('ACP JSON-RPC peer', () => {
expect(peer.closed).toBe(true)
input.destroy()
})

it('settles a call with the final answer the agent wrote after it stopped reading', async () => {
const { response } = captures.acp
const { peer, agent } = fixture()
const asked = deferred<unknown>()
agent.on(captures.acp.request.method, asked.resolve)
const load = peer.request(captures.acp.request.method, {}).catch((error: unknown) => error)
await asked.promise
// The agent closes its stdin before the last chunk of its answer reaches Orca.
agent.stdin.emit('finish')
await expect(peer.request('late', {})).rejects.toBeInstanceOf(AcpConnectionClosedError)
agent.stdout.write(`${JSON.stringify({ ...response, id: 1 })}\n`)
expect(await load).toMatchObject({ code: response.error.code, data: response.error.data })
expect(peer.closed).toBe(true)
})

it('keeps an earlier call answerable when a later write fails', async () => {
const input = new PassThrough()
let writes = 0
const output = new Writable({
write(_chunk, _encoding, callback) {
writes += 1
if (writes === 1) {
callback()
} else {
setImmediate(() => callback(new Error('Broken pipe from write')))
}
}
})
const peer = new AcpJsonRpcPeer(input, output)
peers.push(peer)
const first = peer.request('session/new', {}).catch((error: unknown) => error)
await tick()
const second = peer.request('session/set_mode', {}).catch((error: unknown) => error)
await tick()
input.write(
`${JSON.stringify({ jsonrpc: '2.0', id: 1, error: { code: -32600, message: 'refused' } })}\n`
)
expect(await first).toBeInstanceOf(AcpRpcError)
input.end()
expect(await second).toMatchObject({ message: 'Broken pipe from write' })
})
})
Loading
Loading