Keep unsent browser forks definitive and offer accurate retry guidance

This commit is contained in:
Brennan Benson
2026-11-08 05:55:08 -08:00
parent 1e777ca1a6
commit ddeee1b191
8 changed files with 120 additions and 40 deletions
@@ -43,7 +43,10 @@ import {
inheritedForkCreateOptions,
refuseUnsentInheritedFork
} from './structured-agent-session-launch-fork-support'
import { RuntimeRpcCallError } from '@/runtime/rpc/calls/runtime-rpc-result'
import {
RuntimeConnectionChangedBeforeSendError,
RuntimeRpcCallError
} from '@/runtime/rpc/calls/runtime-rpc-result'
export { STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL } from './structured-agent-session-launch-fork-support'
type LaunchSeed = Readonly<Record<string, string>> | undefined
@@ -147,8 +150,8 @@ export async function launchStructuredAgentSession(
if (intent.params.forkFrom) {
try {
forkOptions = await inheritedForkCreateOptions(intent)
} catch {
refuseUnsentInheritedFork(intent, priorCreateOutcomeUnknown)
} catch (error) {
refuseUnsentInheritedFork(intent, priorCreateOutcomeUnknown, error)
}
}
await requireHostForkSupport(intent)
@@ -204,8 +207,8 @@ export async function launchStructuredAgentSession(
} catch (error) {
if (
forkOptions?.expectedEnvironmentRuntimeId &&
error instanceof RuntimeRpcCallError &&
error.code === 'runtime_environment_changed'
(error instanceof RuntimeConnectionChangedBeforeSendError ||
(error instanceof RuntimeRpcCallError && error.code === 'runtime_environment_changed'))
) {
refuseUnsentInheritedFork(intent, priorCreateOutcomeUnknown)
}
@@ -58,7 +58,8 @@ export async function requireHostForkSupport(
/** A no-send this attempt cannot settle a preceding lost create. */
export function refuseUnsentInheritedFork(
intent: StructuredAgentSessionLaunchIntent,
priorUnknown: boolean
priorUnknown: boolean,
error?: unknown
): never {
if (priorUnknown) {
throw new StructuredAgentSessionCreateUnknownOutcomeError(
@@ -66,11 +67,13 @@ export function refuseUnsentInheritedFork(
'runtime_unavailable'
)
}
const code =
error instanceof StructuredAgentSessionCreateRefusalError &&
error.code === STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL
? STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL
: 'runtime_unavailable'
abandonStructuredAgentSessionLaunchIntent(intent)
throw new StructuredAgentSessionCreateRefusalError(
STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL,
STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL
)
throw new StructuredAgentSessionCreateRefusalError(code, code)
}
/** Restored intents have no row context; read only the requested child's saved journal. */
@@ -141,26 +144,33 @@ export async function inheritedForkCreateOptions(
if (!required) {
return undefined
}
if (intent.target.kind === 'local') {
if (
(await structuredAgentSessionHostCapabilityState(
intent.target,
AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY
)) !== 'supported'
) {
throw new Error('Original fork support is unavailable')
}
return undefined
}
const proof = await runtimeEnvironmentCapabilityProof(
intent.target.environmentId,
AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY
)
if (!proof.supported) {
const support =
intent.target.kind === 'local'
? await structuredAgentSessionHostCapabilityState(
intent.target,
AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY
)
: undefined
if (support === 'unknown') {
throw new Error('Original fork support is unavailable')
}
return {
expectedEnvironmentRuntimeId: proof.runtimeId,
expectedEnvironmentPairingRevision: proof.pairingRevision
const proof =
intent.target.kind === 'environment'
? await runtimeEnvironmentCapabilityProof(
intent.target.environmentId,
AGENT_SESSION_CREATE_FORK_ORIGINAL_RUNTIME_CAPABILITY
)
: undefined
if (support === 'unsupported' || proof?.supported === false) {
throw new StructuredAgentSessionCreateRefusalError(
STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL,
STRUCTURED_LAUNCH_FORK_UNSUPPORTED_REFUSAL
)
}
return proof
? {
expectedEnvironmentRuntimeId: proof.runtimeId,
expectedEnvironmentPairingRevision: proof.pairingRevision
}
: undefined
}
@@ -11,6 +11,20 @@ import {
} from './structured-agent-session-launch-create-message.test-fixture'
import { startStructuredAgentLaunch } from './structured-agent-session-launch'
const browserSession = vi.hoisted(() => ({
client: { connectionEpoch: 1, call: vi.fn() },
environment: { id: 'paired', createdAt: 7, pairingRevision: 7 }
}))
vi.mock('@/web/preload-api/web-runtime-session', () => ({
getClientForEnvironment: () => browserSession.client,
manuallyDisconnectedEnvironmentIds: new Set<string>(),
manuallyDisconnectedResponse: () => ({ ok: false }),
resolveEnvironment: () => browserSession.environment,
runtimeCallQueuePool: { enqueue: (_id: string, _method: string, run: () => unknown) => run() },
updateEnvironmentFromResponse: () => undefined
}))
import { callWebRuntimeEnvironment } from '@/web/preload-api/web-runtime-calls'
let restore: (() => void) | undefined
beforeEach(() => {
restore = resetCreateMessageFixture()
@@ -231,7 +245,7 @@ it('settles a pinned pre-dispatch runtime replacement definitively, and keeps th
forkRequiresInheritedOriginal: true
})
await expect(launch.launchResult).rejects.toMatchObject({
code: 'structured_agent_session_fork_unsupported'
code: 'runtime_unavailable'
})
expect(launch.isVisibilityUnknown()).toBe(false)
expect(getStructuredAgentSessionLaunchLifecycle('workspace-fork', launch.sessionId)).toBe(
@@ -377,3 +391,46 @@ it('rederives a restored tip fork requirement from the child before resubmitting
})
)
})
it('settles a browser pin refusal before dispatch but keeps a lost browser reply uncertain', async () => {
const call = await remoteForkTransport()
call.mockImplementation(callWebRuntimeEnvironment)
browserSession.client.connectionEpoch = 1
browserSession.client.call.mockReset()
browserSession.client.call.mockImplementation(async (method) => {
if (method !== 'status.get') {
throw new Error('Unexpected create dispatch')
}
return { id: 'status', ok: true, result: {}, _meta: { runtimeId: 'runtime-b' } }
})
const state = recoveryState()
await expect(launchAndReconcile(state)).rejects.toMatchObject({
code: 'runtime_unavailable'
})
expect(state.visibilityUnknown).toBe(false)
expect(browserSession.client.call.mock.calls.map(([method]) => method)).not.toContain(
'agentSession.create'
)
// The same words in a failed reply are not pre-dispatch evidence.
browserSession.client.connectionEpoch = 2
browserSession.client.call.mockImplementation(async (method) => {
if (method === 'status.get') {
return { id: 'status', ok: true, result: {}, _meta: { runtimeId: 'runtime-a' } }
}
throw new Error('Runtime connection changed; try again.')
})
const lost = recoveryState()
await expect(launchAndReconcile(lost)).rejects.toThrow()
expect(lost.visibilityUnknown).toBe(true)
})
it('keeps a failed capability read definitive without classifying the host as unsupported', async () => {
const call = await remoteForkTransport()
clearRuntimeCompatibilityCache()
call.mockRejectedValue(new Error('status read failed'))
const state = recoveryState()
await expect(launchAndReconcile(state)).rejects.toMatchObject({ code: 'runtime_unavailable' })
expect(state.visibilityUnknown).toBe(false)
expect(call.mock.calls.map(([request]) => request.method)).not.toContain('agentSession.create')
})
@@ -5,6 +5,14 @@ import type {
// Why: the CLI reads the same flattened tokens, so the matcher lives in shared and both clients use one copy.
/** A local identity guard rejected the request before dispatch, not a lost reply. */
export class RuntimeConnectionChangedBeforeSendError extends Error {
constructor(message: string) {
super(message)
this.name = 'RuntimeConnectionChangedBeforeSendError'
}
}
export class RuntimeRpcCallError extends Error {
readonly code: string
readonly response: RuntimeRpcFailure
@@ -20,7 +20,7 @@ vi.mock('./web-runtime-session', () => ({
}))
import { callEnvironmentEnvelope } from './web-runtime-calls'
import { RUNTIME_CONNECTION_CHANGED_MESSAGE } from '../web-runtime-request-registry'
import { RuntimeConnectionChangedBeforeSendError } from '../../runtime/rpc/calls/runtime-rpc-result'
describe('web runtime call pinned to the probed runtime', () => {
beforeEach(() => {
@@ -43,7 +43,7 @@ describe('web runtime call pinned to the probed runtime', () => {
await expect(
callEnvironmentEnvelope('env-1', 'files.write', {}, 15_000, undefined, 'runtime-a')
).rejects.toThrow(RUNTIME_CONNECTION_CHANGED_MESSAGE)
).rejects.toBeInstanceOf(RuntimeConnectionChangedBeforeSendError)
expect(session.client.call).not.toHaveBeenCalledWith(
'files.write',
expect.anything(),
@@ -1,3 +1,4 @@
import { RuntimeConnectionChangedBeforeSendError } from '../../runtime/rpc/calls/runtime-rpc-result'
import type { PreloadApi } from '../../../../preload/api-types'
import type { WebRuntimeSubscribeOptions } from '../web-runtime-subscription-contract'
import { parseExecutionHostId, toRuntimeExecutionHostId } from '../../../../shared/execution-host'
@@ -58,7 +59,9 @@ export function assertEnvironmentPairing(selector: string, expectedRevision?: nu
expectedRevision !== undefined &&
(current.pairingRevision ?? current.createdAt) !== expectedRevision
) {
throw new Error('The paired Orca server changed while the request was in progress.')
throw new RuntimeConnectionChangedBeforeSendError(
'The paired Orca server changed while the request was in progress.'
)
}
}
@@ -112,7 +115,7 @@ async function callPinnedToRuntime(
}
const probed = probedConnections.get(client)
if (probed?.runtimeId !== expectedEnvironmentRuntimeId) {
throw new Error(RUNTIME_CONNECTION_CHANGED_MESSAGE)
throw new RuntimeConnectionChangedBeforeSendError(RUNTIME_CONNECTION_CHANGED_MESSAGE)
}
return client.call(method, params, { timeoutMs, expectedConnectionEpoch: probed.epoch })
}
@@ -1,8 +1,6 @@
import { RuntimeConnectionChangedBeforeSendError } from '../runtime/rpc/calls/runtime-rpc-result'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
RUNTIME_CONNECTION_CHANGED_MESSAGE,
WebRuntimeRequestRegistry
} from './web-runtime-request-registry'
import { WebRuntimeRequestRegistry } from './web-runtime-request-registry'
describe('web runtime request connection pin', () => {
beforeEach(() => {
@@ -37,7 +35,7 @@ describe('web runtime request connection pin', () => {
const write = registry.call('files.write', {}, { expectedConnectionEpoch: probedEpoch })
reconnect()
await expect(write).rejects.toThrow(RUNTIME_CONNECTION_CHANGED_MESSAGE)
await expect(write).rejects.toBeInstanceOf(RuntimeConnectionChangedBeforeSendError)
expect(sendEncrypted).not.toHaveBeenCalled()
})
})
@@ -1,3 +1,4 @@
import { RuntimeConnectionChangedBeforeSendError } from '../runtime/rpc/calls/runtime-rpc-result'
import type { RuntimeRpcResponse } from '../../../shared/runtime-rpc-envelope'
import type { WebRuntimePendingRequest } from './web-runtime-connection-frame-router'
@@ -55,7 +56,7 @@ export class WebRuntimeRequestRegistry {
callOptions?.expectedConnectionEpoch !== undefined &&
callOptions.expectedConnectionEpoch !== this.connectionEpoch
) {
throw new Error(RUNTIME_CONNECTION_CHANGED_MESSAGE)
throw new RuntimeConnectionChangedBeforeSendError(RUNTIME_CONNECTION_CHANGED_MESSAGE)
}
return new Promise((resolve, reject) => {
const id = this.options.nextId()