Implement robust orchestration primitives and connected-server workers (#9925)
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../shared/protocol-version'
|
||||
import { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationDb } from '../../orchestration/db'
|
||||
import type { RpcRequest } from '../core'
|
||||
import { RpcDispatcher } from '../dispatcher'
|
||||
import { ORCHESTRATION_METHODS } from './orchestration'
|
||||
|
||||
describe('orchestration federated message targeting', () => {
|
||||
let db: OrchestrationDb | undefined
|
||||
let runtime: OrcaRuntimeService | undefined
|
||||
|
||||
afterEach(() => {
|
||||
runtime?.stopOrchestrationFederationRelay()
|
||||
db?.close()
|
||||
})
|
||||
|
||||
it('rejects explicit send and ask targets without enqueueing a relay', async () => {
|
||||
db = new OrchestrationDb(':memory:')
|
||||
runtime = new OrcaRuntimeService()
|
||||
runtime.setOrchestrationDb(db)
|
||||
const paneKey = 'tab_worker:leaf_worker'
|
||||
const processIncarnation = 'worker_epoch:pty:1'
|
||||
const dispatchId = 'ctx_remote_targeting'
|
||||
vi.spyOn(runtime, 'getTerminalPaneKey').mockReturnValue(paneKey)
|
||||
vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockReturnValue(processIncarnation)
|
||||
db.createRemoteDispatchAttachment({
|
||||
dispatchId,
|
||||
taskId: 'task_remote_targeting',
|
||||
homePeerFingerprint: 'home_peer',
|
||||
protocolVersion: 1,
|
||||
runtimeEpoch: runtime.getRuntimeId(),
|
||||
mutationReceipt: {
|
||||
callerFingerprint: 'home_peer',
|
||||
requestId: 'attach_request',
|
||||
method: 'orchestration.federationAttachStart',
|
||||
payloadHash: 'attach_payload'
|
||||
}
|
||||
})
|
||||
const capability = db.prepareRemoteAttachmentAuthority({
|
||||
dispatchId,
|
||||
paneKey,
|
||||
processIncarnation,
|
||||
worktreeId: 'repo::remote-worktree',
|
||||
terminalHandle: 'term_remote_worker',
|
||||
setupState: 'not_applicable',
|
||||
effects: []
|
||||
})
|
||||
db.markRemoteAttachmentReady(dispatchId)
|
||||
const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS })
|
||||
const requests: RpcRequest[] = [
|
||||
request('send_to', capability, 'orchestration.send', {
|
||||
from: 'term_remote_worker',
|
||||
to: 'run:explicit',
|
||||
subject: 'Wrong explicit target'
|
||||
}),
|
||||
request('send_run', capability, 'orchestration.send', {
|
||||
from: 'term_remote_worker',
|
||||
run: 'run_explicit',
|
||||
subject: 'Wrong explicit Run'
|
||||
}),
|
||||
request('ask_to', capability, 'orchestration.ask', {
|
||||
from: 'term_remote_worker',
|
||||
to: 'run:explicit',
|
||||
question: 'Wrong explicit target?'
|
||||
}),
|
||||
request('ask_run', capability, 'orchestration.ask', {
|
||||
from: 'term_remote_worker',
|
||||
run: 'run_explicit',
|
||||
question: 'Wrong explicit Run?'
|
||||
})
|
||||
]
|
||||
|
||||
for (const item of requests) {
|
||||
await expect(dispatcher.dispatch(item)).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
code: 'invalid_argument',
|
||||
message: 'Federated Dispatch messages route to their Run home; omit --to and --run.'
|
||||
}
|
||||
})
|
||||
}
|
||||
expect(
|
||||
db.listFederationRelay({ dispatchId, direction: 'to_home', afterSequence: 0 })
|
||||
).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
function request(
|
||||
id: string,
|
||||
capability: string,
|
||||
method: 'orchestration.send' | 'orchestration.ask',
|
||||
params: Record<string, unknown>
|
||||
): RpcRequest {
|
||||
return {
|
||||
id: `rpc_${id}`,
|
||||
authToken: 'worker-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: `request_${id}`,
|
||||
orchestrationCapability: capability,
|
||||
method,
|
||||
params
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
import { isTuiAgent } from '../../../../shared/tui-agent-config'
|
||||
import type { RuntimeStatus } from '../../../../shared/runtime-types'
|
||||
import {
|
||||
ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY,
|
||||
ORCHESTRATION_FEDERATION_CONTROL_MAIL_PROTOCOL_VERSION,
|
||||
ORCHESTRATION_FEDERATION_CONTROL_MAIL_RUNTIME_CAPABILITY,
|
||||
ORCHESTRATION_FEDERATION_RUNTIME_CAPABILITY
|
||||
} from '../../../../shared/protocol-version'
|
||||
import { orchestrationMigrationData } from '../../../../shared/orchestration-rpc-contract'
|
||||
import type { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import type { OrchestrationDb } from '../../orchestration/db'
|
||||
import { OrchestrationError } from '../../orchestration/orchestration-error'
|
||||
import type { WorkerStartInput } from './orchestration-worker-start-schema'
|
||||
|
||||
export async function startFederatedWorker(args: {
|
||||
params: WorkerStartInput
|
||||
runtime: OrcaRuntimeService
|
||||
db: OrchestrationDb
|
||||
runId: string
|
||||
task: { id: string; spec: string; status: string }
|
||||
orchestrationMutation?: {
|
||||
callerFingerprint: string
|
||||
requestId: string
|
||||
method: string
|
||||
payloadHash: string
|
||||
}
|
||||
}): Promise<unknown> {
|
||||
const { params, runtime, db, task, runId, orchestrationMutation } = args
|
||||
if (!orchestrationMutation) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'Remote worker-start requires a durable retry request.'
|
||||
)
|
||||
}
|
||||
const worktree = params.worktree ?? 'current'
|
||||
if (worktree === 'current' || worktree === 'new-child') {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'--on requires an exact remote worktree selector or new-top-level.'
|
||||
)
|
||||
}
|
||||
const createsWorktree = worktree === 'new-top-level'
|
||||
validateRemoteWorkerStart(params, createsWorktree)
|
||||
|
||||
const server = runtime.resolveOrchestrationWorkerServer(params.on as string)
|
||||
const status = (await runtime.callOrchestrationWorkerServer(
|
||||
server.environmentId,
|
||||
'status.get',
|
||||
undefined,
|
||||
params.timeoutMs
|
||||
)) as RuntimeStatus
|
||||
if (!status.capabilities?.includes(ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY)) {
|
||||
throw new OrchestrationError(
|
||||
'orchestration_migration_required',
|
||||
`Connected server ${server.name} does not support the current orchestration contract. No effects were applied.`,
|
||||
orchestrationMigrationData('runtime_capability_missing')
|
||||
)
|
||||
}
|
||||
if (!status.capabilities?.includes(ORCHESTRATION_FEDERATION_RUNTIME_CAPABILITY)) {
|
||||
throw new OrchestrationError(
|
||||
'capability_unsupported',
|
||||
`Connected server ${server.name} does not support orchestration federation.`
|
||||
)
|
||||
}
|
||||
const federationProtocolVersion = status.capabilities?.includes(
|
||||
ORCHESTRATION_FEDERATION_CONTROL_MAIL_RUNTIME_CAPABILITY
|
||||
)
|
||||
? ORCHESTRATION_FEDERATION_CONTROL_MAIL_PROTOCOL_VERSION
|
||||
: 1
|
||||
|
||||
const setupDecision = createsWorktree ? (params.setup ?? 'run') : 'not_applicable'
|
||||
const started = db.createStartingWorkerDispatch({
|
||||
taskId: task.id,
|
||||
retryOf: params.retryOf,
|
||||
startOptions: {
|
||||
on: server.environmentId,
|
||||
serverName: server.name,
|
||||
worktree,
|
||||
name: params.name ?? null,
|
||||
repo: params.repo ?? null,
|
||||
baseBranch: params.baseBranch ?? null,
|
||||
terminal: params.terminal ?? null,
|
||||
agent: params.agent ?? null,
|
||||
timeoutMs: params.timeoutMs ?? 60_000,
|
||||
setup: setupDecision,
|
||||
setupSource: createsWorktree
|
||||
? params.setup
|
||||
? 'explicit_request'
|
||||
: 'orchestration_default'
|
||||
: 'existing_worktree'
|
||||
},
|
||||
runtimeEpoch: runtime.getRuntimeId(),
|
||||
mutationReceipt: orchestrationMutation,
|
||||
federation: {
|
||||
environmentId: server.environmentId,
|
||||
environmentName: server.name,
|
||||
peerFingerprint: server.peerFingerprint,
|
||||
protocolVersion: federationProtocolVersion
|
||||
}
|
||||
})
|
||||
db.recordWorkerStage({ dispatchId: started.dispatch.id, stage: 'remote_attach_requested' })
|
||||
try {
|
||||
const remote = (await runtime.callOrchestrationWorkerServer(
|
||||
server.environmentId,
|
||||
'orchestration.federationAttachStart',
|
||||
{
|
||||
dispatchId: started.dispatch.id,
|
||||
taskId: task.id,
|
||||
taskSpec: task.spec,
|
||||
protocolVersion: federationProtocolVersion,
|
||||
worktree,
|
||||
name: params.name,
|
||||
repo: params.repo,
|
||||
baseBranch: params.baseBranch,
|
||||
displayName: params.displayName,
|
||||
comment: params.comment,
|
||||
setup: createsWorktree ? (params.setup ?? 'run') : undefined,
|
||||
setupSource: createsWorktree
|
||||
? params.setup
|
||||
? 'explicit_request'
|
||||
: 'orchestration_default'
|
||||
: undefined,
|
||||
terminal: params.terminal,
|
||||
agent: params.agent,
|
||||
timeoutMs: params.timeoutMs,
|
||||
devMode: params.devMode
|
||||
},
|
||||
(params.timeoutMs ?? 60_000) + 15_000,
|
||||
{ orchestrationRequestId: orchestrationMutation.requestId }
|
||||
)) as RemoteStartReceipt
|
||||
if (remote.dispatchId !== started.dispatch.id) {
|
||||
throw new OrchestrationError(
|
||||
'resource_server_mismatch',
|
||||
'The worker server returned a different Dispatch attachment.'
|
||||
)
|
||||
}
|
||||
if (remote.state === 'ready' && remote.worktreeId && remote.terminalHandle) {
|
||||
db.updateFederatedDispatchResources({
|
||||
dispatchId: started.dispatch.id,
|
||||
remoteRuntimeEpoch: remote.runtimeEpoch,
|
||||
worktreeId: remote.worktreeId,
|
||||
terminalHandle: remote.terminalHandle
|
||||
})
|
||||
db.recordWorkerStage({
|
||||
dispatchId: started.dispatch.id,
|
||||
stage: 'remote_input_accepted',
|
||||
worktreeId: remote.worktreeId,
|
||||
terminalHandle: remote.terminalHandle,
|
||||
setupState: remote.setup?.state,
|
||||
effects: remote.effects,
|
||||
residualResources: remote.residualResources
|
||||
})
|
||||
const readyWorker = db.markWorkerDispatchReady(started.dispatch.id)
|
||||
runtime.ensureOrchestrationFederationRelay(runId)
|
||||
return {
|
||||
runId,
|
||||
taskId: task.id,
|
||||
dispatchId: started.dispatch.id,
|
||||
state: 'ready',
|
||||
stage: readyWorker.stage,
|
||||
server: { environmentId: server.environmentId, name: server.name },
|
||||
setup: remote.setup,
|
||||
timeoutMs: params.timeoutMs ?? 60_000,
|
||||
effects: remote.effects ?? [],
|
||||
residualResources: remote.residualResources ?? []
|
||||
}
|
||||
}
|
||||
if (remote.state === 'outcome_unknown') {
|
||||
const worker = db.markWorkerStartUnknown(
|
||||
started.dispatch.id,
|
||||
remote.failedStage ?? 'remote_attach',
|
||||
remote.lastError ?? 'The worker server reported an unknown start outcome.'
|
||||
)
|
||||
return federatedUnknownReceipt(worker, task.id, server.name)
|
||||
}
|
||||
const worker = db.failWorkerStart(
|
||||
started.dispatch.id,
|
||||
remote.failedStage ?? 'remote_attach',
|
||||
remote.lastError ?? `The worker server returned ${remote.state}.`
|
||||
)
|
||||
return {
|
||||
runId,
|
||||
taskId: task.id,
|
||||
dispatchId: started.dispatch.id,
|
||||
state: worker.state,
|
||||
stage: worker.stage,
|
||||
server: { environmentId: server.environmentId, name: server.name },
|
||||
failedStage: worker.stage,
|
||||
lastError: worker.last_error,
|
||||
setup: remote.setup,
|
||||
effects: remote.effects ?? [],
|
||||
residualResources: remote.residualResources ?? []
|
||||
}
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
if (error instanceof OrchestrationError && isKnownRemoteStartFailure(error.code)) {
|
||||
const worker = db.failWorkerStart(started.dispatch.id, 'remote_attach', reason)
|
||||
return {
|
||||
runId,
|
||||
taskId: task.id,
|
||||
dispatchId: started.dispatch.id,
|
||||
state: worker.state,
|
||||
stage: worker.stage,
|
||||
server: { environmentId: server.environmentId, name: server.name },
|
||||
failedStage: worker.stage,
|
||||
lastError: worker.last_error,
|
||||
effects: [],
|
||||
residualResources: []
|
||||
}
|
||||
}
|
||||
const worker = db.markWorkerStartUnknown(started.dispatch.id, 'remote_attach', reason)
|
||||
return federatedUnknownReceipt(worker, task.id, server.name)
|
||||
}
|
||||
}
|
||||
|
||||
type RemoteStartReceipt = {
|
||||
dispatchId: string
|
||||
state: string
|
||||
runtimeEpoch: string
|
||||
worktreeId?: string
|
||||
terminalHandle?: string
|
||||
setup?: { state: string }
|
||||
effects?: unknown[]
|
||||
residualResources?: unknown[]
|
||||
failedStage?: string
|
||||
lastError?: string
|
||||
}
|
||||
|
||||
function validateRemoteWorkerStart(params: WorkerStartInput, createsWorktree: boolean): void {
|
||||
if (createsWorktree && (!params.name || !params.repo)) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'Remote new-top-level requires --name and an explicit --repo from remote discovery.'
|
||||
)
|
||||
}
|
||||
if (createsWorktree && params.terminal) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'--terminal cannot combine with remote new-worktree creation.'
|
||||
)
|
||||
}
|
||||
if (!createsWorktree && (params.name || params.repo || params.baseBranch || params.setup)) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'Creation and setup options apply only to remote new-top-level worktrees.'
|
||||
)
|
||||
}
|
||||
if (params.terminal && params.agent) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'--terminal reuses an existing agent and cannot combine with --agent.'
|
||||
)
|
||||
}
|
||||
if (!params.terminal && (!params.agent || !isTuiAgent(params.agent))) {
|
||||
throw new OrchestrationError(
|
||||
'agent_unconfigured',
|
||||
'A configured --agent is required when remote worker-start creates a terminal.'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function isKnownRemoteStartFailure(code: string): boolean {
|
||||
return [
|
||||
'invalid_argument',
|
||||
'agent_unconfigured',
|
||||
'worktree_not_found_on_server',
|
||||
'terminal_worktree_mismatch',
|
||||
'capability_unsupported'
|
||||
].includes(code)
|
||||
}
|
||||
|
||||
function federatedUnknownReceipt(
|
||||
worker: { dispatch_id: string; state: string; stage: string; last_error: string | null },
|
||||
taskId: string,
|
||||
serverName: string
|
||||
): unknown {
|
||||
return {
|
||||
taskId,
|
||||
dispatchId: worker.dispatch_id,
|
||||
state: 'outcome_unknown',
|
||||
stage: worker.stage,
|
||||
server: { name: serverName },
|
||||
failedStage: worker.stage,
|
||||
lastError: worker.last_error,
|
||||
effects: [],
|
||||
residualResources: [],
|
||||
nextCommands: [
|
||||
`orca orchestration worker-show --dispatch ${worker.dispatch_id} --json`,
|
||||
`orca orchestration worker-abandon --dispatch ${worker.dispatch_id} --json`
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../shared/protocol-version'
|
||||
import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope'
|
||||
import { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationDb } from '../../orchestration/db'
|
||||
import type { OrchestrationEnvironmentTransport } from '../../orchestration/environment-transport'
|
||||
import type { RpcRequest } from '../core'
|
||||
import { RpcDispatcher } from '../dispatcher'
|
||||
import { authenticatedCallerFingerprint } from '../orchestration-mutation-executor'
|
||||
import { ORCHESTRATION_METHODS } from './orchestration'
|
||||
|
||||
describe('orchestration federation control mail', () => {
|
||||
const homeToken = 'run-home-device-token'
|
||||
const workerToken = 'worker-local-token'
|
||||
const workerPeerFingerprint = 'worker-peer'
|
||||
const coordinatorPaneKey = 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
const workerPaneKey = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
|
||||
const processIncarnation = 'worker-runtime:pty:1'
|
||||
let homeDb: OrchestrationDb
|
||||
let workerDb: OrchestrationDb
|
||||
let homeRuntime: OrcaRuntimeService
|
||||
let workerRuntime: OrcaRuntimeService
|
||||
let homeDispatcher: RpcDispatcher
|
||||
let workerDispatcher: RpcDispatcher
|
||||
let dispatchId: string
|
||||
let runId: string
|
||||
|
||||
beforeEach(() => {
|
||||
workerDb = new OrchestrationDb(':memory:')
|
||||
workerRuntime = new OrcaRuntimeService()
|
||||
workerRuntime.setOrchestrationDb(workerDb)
|
||||
vi.spyOn(workerRuntime, 'getTerminalPaneKey').mockImplementation((handle) =>
|
||||
handle === 'term_worker' ? workerPaneKey : null
|
||||
)
|
||||
vi.spyOn(workerRuntime, 'getTerminalProcessIncarnation').mockImplementation((handle) =>
|
||||
handle === 'term_worker' ? processIncarnation : null
|
||||
)
|
||||
workerDispatcher = new RpcDispatcher({
|
||||
runtime: workerRuntime,
|
||||
methods: ORCHESTRATION_METHODS
|
||||
})
|
||||
|
||||
const transport: OrchestrationEnvironmentTransport = {
|
||||
resolve: () => ({
|
||||
environmentId: 'environment_worker',
|
||||
name: 'worker',
|
||||
peerFingerprint: workerPeerFingerprint
|
||||
}),
|
||||
call: async (_selector, method, params, _timeoutMs, envelope) => {
|
||||
if (method === 'status.get') {
|
||||
return {
|
||||
id: 'status',
|
||||
ok: true,
|
||||
result: workerRuntime.getStatus(),
|
||||
_meta: { runtimeId: workerRuntime.getRuntimeId() }
|
||||
}
|
||||
}
|
||||
const response = (await workerDispatcher.dispatch({
|
||||
id: `remote_${method}`,
|
||||
authToken: homeToken,
|
||||
method,
|
||||
params,
|
||||
orchestrationContractVersion: envelope?.orchestrationContractVersion,
|
||||
orchestrationRequestId: envelope?.orchestrationRequestId
|
||||
})) as RuntimeRpcResponse<unknown>
|
||||
return response
|
||||
}
|
||||
}
|
||||
homeDb = new OrchestrationDb(':memory:')
|
||||
homeRuntime = new OrcaRuntimeService(null, undefined, {
|
||||
orchestrationEnvironmentTransport: transport
|
||||
})
|
||||
homeRuntime.setOrchestrationDb(homeDb)
|
||||
vi.spyOn(homeRuntime, 'getTerminalPaneKey').mockImplementation((handle) =>
|
||||
handle === 'term_coord' ? coordinatorPaneKey : null
|
||||
)
|
||||
homeDispatcher = new RpcDispatcher({
|
||||
runtime: homeRuntime,
|
||||
methods: ORCHESTRATION_METHODS
|
||||
})
|
||||
|
||||
const run = homeDb.createRun({
|
||||
objective: 'Federated control mail',
|
||||
coordinatorHandle: 'term_coord',
|
||||
coordinatorPaneKey
|
||||
})
|
||||
runId = run.id
|
||||
const task = homeDb.createTask({ spec: 'Wait for coordinator guidance', runId })
|
||||
const started = homeDb.createStartingWorkerDispatch({
|
||||
taskId: task.id,
|
||||
startOptions: {},
|
||||
federation: {
|
||||
environmentId: 'environment_worker',
|
||||
environmentName: 'worker',
|
||||
peerFingerprint: workerPeerFingerprint,
|
||||
protocolVersion: 2
|
||||
}
|
||||
})
|
||||
dispatchId = started.dispatch.id
|
||||
homeDb.markWorkerDispatchReady(dispatchId)
|
||||
|
||||
const homeFingerprint = authenticatedCallerFingerprint({
|
||||
id: 'home',
|
||||
authToken: homeToken,
|
||||
method: 'orchestration.federationImport'
|
||||
})
|
||||
workerDb.createRemoteDispatchAttachment({
|
||||
dispatchId,
|
||||
taskId: task.id,
|
||||
homePeerFingerprint: homeFingerprint,
|
||||
protocolVersion: 2,
|
||||
runtimeEpoch: workerRuntime.getRuntimeId(),
|
||||
mutationReceipt: {
|
||||
callerFingerprint: homeFingerprint,
|
||||
requestId: 'attach-worker',
|
||||
method: 'orchestration.federationAttachStart',
|
||||
payloadHash: 'attach-worker-payload'
|
||||
}
|
||||
})
|
||||
workerDb.prepareRemoteAttachmentAuthority({
|
||||
dispatchId,
|
||||
paneKey: workerPaneKey,
|
||||
processIncarnation,
|
||||
worktreeId: 'repo::worker',
|
||||
terminalHandle: 'term_worker',
|
||||
setupState: 'not_applicable',
|
||||
effects: []
|
||||
})
|
||||
workerDb.markRemoteAttachmentReady(dispatchId)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
homeRuntime.stopOrchestrationFederationRelay()
|
||||
homeDb.close()
|
||||
workerDb.close()
|
||||
})
|
||||
|
||||
it('routes an exact Dispatch message through the durable relay', async () => {
|
||||
vi.spyOn(homeRuntime, 'ensureOrchestrationFederationRelay').mockImplementation(() => {})
|
||||
const sent = await homeDispatcher.dispatch({
|
||||
id: 'send-control',
|
||||
authToken: 'coordinator-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'send-control-request',
|
||||
method: 'orchestration.send',
|
||||
params: {
|
||||
from: 'term_coord',
|
||||
to: `dispatch:${dispatchId}`,
|
||||
subject: 'Continue',
|
||||
body: 'Run the focused follow-up.',
|
||||
type: 'status'
|
||||
}
|
||||
})
|
||||
|
||||
expect(sent).toMatchObject({
|
||||
ok: true,
|
||||
result: { relay: { dispatchId, accepted: true } }
|
||||
})
|
||||
expect(homeDb.listPendingFederationRelay(dispatchId, 'to_worker')).toHaveLength(1)
|
||||
|
||||
await homeRuntime.syncOrchestrationFederation()
|
||||
const checked = await workerDispatcher.dispatch(checkRequest('check-imported'))
|
||||
|
||||
expect(checked).toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
dispatchId,
|
||||
count: 1,
|
||||
messages: [
|
||||
{
|
||||
to_handle: `dispatch:${dispatchId}`,
|
||||
subject: 'Continue',
|
||||
body: 'Run the focused follow-up.'
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
expect(homeDb.listPendingFederationRelay(dispatchId, 'to_worker')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('wakes a remote worker waiter when control mail imports', async () => {
|
||||
const waiting = workerDispatcher.dispatch(checkRequest('wait-for-control', true))
|
||||
await Promise.resolve()
|
||||
|
||||
const imported = await workerDispatcher.dispatch(
|
||||
importRequest('import-control', 1, 'relay-control')
|
||||
)
|
||||
|
||||
expect(imported).toMatchObject({
|
||||
ok: true,
|
||||
result: { acknowledgedThrough: 1, imported: 1 }
|
||||
})
|
||||
await expect(waiting).resolves.toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
dispatchId,
|
||||
count: 1,
|
||||
messages: [{ id: 'relay-control', subject: 'Continue' }]
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('accepts a repeated import after a lost acknowledgment without duplicating mail', async () => {
|
||||
const first = await workerDispatcher.dispatch(importRequest('first-import', 1, 'relay-control'))
|
||||
const repeated = await workerDispatcher.dispatch(
|
||||
importRequest('repeated-import', 1, 'different-message-id')
|
||||
)
|
||||
|
||||
expect(first).toMatchObject({ ok: true, result: { imported: 1 } })
|
||||
expect(repeated).toMatchObject({ ok: true, result: { imported: 0 } })
|
||||
expect(workerDb.getUnreadMessages(`dispatch:${dispatchId}`)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('does not deliver pending control mail after worker completion', async () => {
|
||||
vi.spyOn(homeRuntime, 'ensureOrchestrationFederationRelay').mockImplementation(() => {})
|
||||
await homeDispatcher.dispatch({
|
||||
id: 'send-stale-control',
|
||||
authToken: 'coordinator-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'send-stale-control-request',
|
||||
method: 'orchestration.send',
|
||||
params: {
|
||||
from: 'term_coord',
|
||||
to: `dispatch:${dispatchId}`,
|
||||
subject: 'Stale follow-up',
|
||||
body: 'This must not arrive after completion.',
|
||||
type: 'status'
|
||||
}
|
||||
})
|
||||
const waiting = workerDispatcher.dispatch(checkRequest('wait-before-completion', true, 30))
|
||||
await Promise.resolve()
|
||||
|
||||
const taskId = homeDb.getDispatchContextById(dispatchId)!.task_id
|
||||
workerDb.enqueueFederationRelay({
|
||||
dispatchId,
|
||||
direction: 'to_home',
|
||||
kind: 'worker_done',
|
||||
payload: JSON.stringify({
|
||||
from: `dispatch:${dispatchId}`,
|
||||
subject: 'Done',
|
||||
body: 'Completed before the follow-up arrived.',
|
||||
type: 'worker_done',
|
||||
priority: 'normal',
|
||||
threadId: null,
|
||||
payload: JSON.stringify({
|
||||
taskId,
|
||||
dispatchId,
|
||||
outcome: 'succeeded',
|
||||
filesModified: []
|
||||
})
|
||||
}),
|
||||
settleRemoteOutcome: 'succeeded'
|
||||
})
|
||||
|
||||
await homeRuntime.syncOrchestrationFederation()
|
||||
|
||||
expect(homeDb.getWorkerDispatch(dispatchId)?.state).toBe('succeeded')
|
||||
expect(workerDb.getUnreadMessages(`dispatch:${dispatchId}`)).toHaveLength(0)
|
||||
expect(homeDb.listPendingFederationRelay(dispatchId, 'to_worker')).toHaveLength(1)
|
||||
await expect(
|
||||
workerDispatcher.dispatch(importRequest('late-direct-import', 1, 'late-control'))
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'dispatch_inactive' }
|
||||
})
|
||||
await expect(waiting).resolves.toMatchObject({
|
||||
ok: true,
|
||||
result: { count: 0, timedOut: true }
|
||||
})
|
||||
})
|
||||
|
||||
it('wakes only waiters whose filter matches an imported control message', async () => {
|
||||
const escalationWaiter = workerDispatcher.dispatch(
|
||||
checkRequest('wait-escalation', true, 1_000, 'escalation')
|
||||
)
|
||||
const statusWaiter = workerDispatcher.dispatch(checkRequest('wait-status', true, 30, 'status'))
|
||||
await Promise.resolve()
|
||||
|
||||
await workerDispatcher.dispatch(
|
||||
importRequest('import-escalation', 1, 'relay-escalation', 'escalation')
|
||||
)
|
||||
|
||||
await expect(escalationWaiter).resolves.toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
count: 1,
|
||||
messages: [{ id: 'relay-escalation', type: 'escalation' }]
|
||||
}
|
||||
})
|
||||
await expect(statusWaiter).resolves.toMatchObject({
|
||||
ok: true,
|
||||
result: { count: 0, timedOut: true }
|
||||
})
|
||||
})
|
||||
|
||||
function checkRequest(id: string, wait = false, timeoutMs = 5_000, types?: string): RpcRequest {
|
||||
return {
|
||||
id,
|
||||
authToken: workerToken,
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
method: 'orchestration.check',
|
||||
params: {
|
||||
terminal: 'term_worker',
|
||||
wait,
|
||||
timeoutMs,
|
||||
types
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function importRequest(
|
||||
id: string,
|
||||
sequence: number,
|
||||
messageId: string,
|
||||
type = 'status'
|
||||
): RpcRequest {
|
||||
return {
|
||||
id,
|
||||
authToken: homeToken,
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
method: 'orchestration.federationImport',
|
||||
params: {
|
||||
dispatchId,
|
||||
items: [
|
||||
{
|
||||
dispatch_id: dispatchId,
|
||||
direction: 'to_worker',
|
||||
sequence,
|
||||
message_id: messageId,
|
||||
kind: 'control_message',
|
||||
payload: JSON.stringify({
|
||||
from: `run:${runId}`,
|
||||
subject: 'Continue',
|
||||
body: 'Run the focused follow-up.',
|
||||
type,
|
||||
priority: 'normal',
|
||||
threadId: null,
|
||||
payload: null
|
||||
})
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,207 @@
|
||||
import { z } from 'zod'
|
||||
import { ORCHESTRATION_WORKER_READ_SOURCES } from '../../../../shared/orchestration-worker-output'
|
||||
import type { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationError } from '../../orchestration/orchestration-error'
|
||||
import type { RemoteDispatchAttachmentRow } from '../../orchestration/types'
|
||||
import { defineMethod, type RpcMethod } from '../core'
|
||||
import { OptionalFiniteNumber, requiredString } from '../schemas'
|
||||
import { readExactWorkerOutput } from './orchestration-worker-output'
|
||||
|
||||
const FederationDispatchParams = z.object({
|
||||
dispatchId: requiredString('Missing Dispatch ID')
|
||||
})
|
||||
const FederationReadParams = FederationDispatchParams.extend({
|
||||
cursor: OptionalFiniteNumber,
|
||||
limit: OptionalFiniteNumber
|
||||
})
|
||||
const FederationOutputReadParams = FederationDispatchParams.extend({
|
||||
cursor: z.union([z.number().int().nonnegative(), z.string().min(1).max(2_048)]).optional(),
|
||||
limit: OptionalFiniteNumber,
|
||||
source: z.enum(ORCHESTRATION_WORKER_READ_SOURCES).optional()
|
||||
})
|
||||
|
||||
export const ORCHESTRATION_FEDERATION_CONTROL_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.federationShow',
|
||||
params: FederationDispatchParams,
|
||||
handler: async (params, { runtime, authenticatedCallerFingerprint }) => {
|
||||
const attachment = requireHomeAttachment(
|
||||
runtime,
|
||||
params.dispatchId,
|
||||
authenticatedCallerFingerprint
|
||||
)
|
||||
const observation = await inspectRemoteAttachment(runtime, params.dispatchId)
|
||||
return {
|
||||
dispatchId: params.dispatchId,
|
||||
runtimeEpoch: runtime.getRuntimeId(),
|
||||
attachment: exposeRemoteAttachment(attachment),
|
||||
terminal: observation.exact ? observation.terminal : null,
|
||||
observation: { status: observation.status, exactWorker: observation.exact }
|
||||
}
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'orchestration.federationRead',
|
||||
params: FederationReadParams,
|
||||
handler: async (params, { runtime, authenticatedCallerFingerprint }) => {
|
||||
requireHomeAttachment(runtime, params.dispatchId, authenticatedCallerFingerprint)
|
||||
const observation = await inspectRemoteAttachment(runtime, params.dispatchId)
|
||||
if (!observation.exact || !observation.terminal || observation.status !== 'running') {
|
||||
throw new OrchestrationError(
|
||||
'worker_identity_changed',
|
||||
`Remote Dispatch ${params.dispatchId} no longer resolves to its exact process.`
|
||||
)
|
||||
}
|
||||
return {
|
||||
dispatchId: params.dispatchId,
|
||||
runtimeEpoch: runtime.getRuntimeId(),
|
||||
terminal: await runtime.readTerminal(observation.terminal.handle, {
|
||||
cursor: params.cursor,
|
||||
limit: params.limit
|
||||
})
|
||||
}
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'orchestration.federationReadOutput',
|
||||
params: FederationOutputReadParams,
|
||||
handler: async (params, { runtime, authenticatedCallerFingerprint }) => {
|
||||
const attachment = requireHomeAttachment(
|
||||
runtime,
|
||||
params.dispatchId,
|
||||
authenticatedCallerFingerprint
|
||||
)
|
||||
const observation = await inspectRemoteAttachment(runtime, params.dispatchId)
|
||||
if (!observation.exact || !observation.terminal) {
|
||||
throw new OrchestrationError(
|
||||
'worker_identity_changed',
|
||||
`Remote Dispatch ${params.dispatchId} no longer resolves to its exact process.`
|
||||
)
|
||||
}
|
||||
const output = await readExactWorkerOutput({
|
||||
runtime,
|
||||
dispatchId: params.dispatchId,
|
||||
terminalHandle: observation.terminal.handle,
|
||||
workerState: attachment.state,
|
||||
terminalStatus: observation.status === 'exited' ? 'exited' : 'running',
|
||||
attachedAt: attachment.created_at,
|
||||
source: params.source,
|
||||
cursor: params.cursor,
|
||||
limit: params.limit
|
||||
})
|
||||
const afterRead = await inspectRemoteAttachment(runtime, params.dispatchId)
|
||||
if (!afterRead.exact) {
|
||||
throw new OrchestrationError(
|
||||
'worker_identity_changed',
|
||||
`Remote Dispatch ${params.dispatchId} changed process while output was read.`
|
||||
)
|
||||
}
|
||||
return {
|
||||
dispatchId: params.dispatchId,
|
||||
runtimeEpoch: runtime.getRuntimeId(),
|
||||
output
|
||||
}
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'orchestration.federationStop',
|
||||
params: FederationDispatchParams,
|
||||
handler: async (params, { runtime, authenticatedCallerFingerprint }) => {
|
||||
requireHomeAttachment(runtime, params.dispatchId, authenticatedCallerFingerprint)
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const begun = db.beginRemoteAttachmentStop(params.dispatchId)
|
||||
if (['succeeded', 'failed', 'stopped', 'abandoned'].includes(begun.state)) {
|
||||
return {
|
||||
dispatchId: params.dispatchId,
|
||||
state: begun.state,
|
||||
alreadySettled: true,
|
||||
processAction: 'none'
|
||||
}
|
||||
}
|
||||
const observation = await inspectRemoteAttachment(runtime, params.dispatchId)
|
||||
if (!observation.exact || !observation.terminal) {
|
||||
const attachment = db.markRemoteAttachmentStopUnknown(
|
||||
params.dispatchId,
|
||||
`The recorded worker process is ${observation.status}; no terminal was closed.`
|
||||
)
|
||||
return {
|
||||
dispatchId: params.dispatchId,
|
||||
state: attachment.state,
|
||||
alreadySettled: false,
|
||||
processAction: 'none',
|
||||
lastError: attachment.last_error
|
||||
}
|
||||
}
|
||||
try {
|
||||
const close = await runtime.closeTerminal(observation.terminal.handle)
|
||||
const attachment = db.settleRemoteAttachmentStop(params.dispatchId)
|
||||
return {
|
||||
dispatchId: params.dispatchId,
|
||||
state: attachment.state,
|
||||
alreadySettled: false,
|
||||
processAction: 'closed_agent_terminal',
|
||||
close
|
||||
}
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
const attachment = db.markRemoteAttachmentStopUnknown(params.dispatchId, reason)
|
||||
return {
|
||||
dispatchId: params.dispatchId,
|
||||
state: attachment.state,
|
||||
alreadySettled: false,
|
||||
processAction: 'unknown',
|
||||
lastError: reason
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
]
|
||||
|
||||
function requireHomeAttachment(
|
||||
runtime: OrcaRuntimeService,
|
||||
dispatchId: string,
|
||||
callerFingerprint: string | undefined
|
||||
): RemoteDispatchAttachmentRow {
|
||||
const attachment = runtime.getOrchestrationDb().getRemoteDispatchAttachment(dispatchId)
|
||||
if (!attachment || attachment.home_peer_fingerprint !== callerFingerprint) {
|
||||
throw new OrchestrationError(
|
||||
'dispatch_not_found',
|
||||
`Remote Dispatch ${dispatchId} was not found for this Run home.`
|
||||
)
|
||||
}
|
||||
return attachment
|
||||
}
|
||||
|
||||
async function inspectRemoteAttachment(runtime: OrcaRuntimeService, dispatchId: string) {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const attachment = db.getRemoteDispatchAttachment(dispatchId)
|
||||
if (!attachment?.terminal_handle) {
|
||||
return { terminal: null, exact: false, status: 'unattached' as const }
|
||||
}
|
||||
const terminal = await runtime.showTerminal(attachment.terminal_handle).catch(() => null)
|
||||
if (!terminal) {
|
||||
return { terminal: null, exact: false, status: 'missing' as const }
|
||||
}
|
||||
const exact = db.isRemoteAttachmentProcessCurrent({
|
||||
dispatchId,
|
||||
paneKey: runtime.getTerminalPaneKey(attachment.terminal_handle),
|
||||
processIncarnation: runtime.getTerminalProcessIncarnation(attachment.terminal_handle)
|
||||
})
|
||||
return {
|
||||
terminal,
|
||||
exact,
|
||||
status: exact
|
||||
? terminal.connected === false
|
||||
? ('exited' as const)
|
||||
: ('running' as const)
|
||||
: ('identity_changed' as const)
|
||||
}
|
||||
}
|
||||
|
||||
function exposeRemoteAttachment(attachment: RemoteDispatchAttachmentRow) {
|
||||
return {
|
||||
...attachment,
|
||||
effects: JSON.parse(attachment.effects) as unknown[],
|
||||
residualResources: JSON.parse(attachment.residual_resources) as unknown[]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
appendFederationSetupEffect,
|
||||
appendFederationTerminalEffects,
|
||||
type FederationEffect
|
||||
} from './orchestration-federation-effects'
|
||||
|
||||
describe('orchestration federation effects', () => {
|
||||
it('uses exact terminal handles instead of display titles for setup identity', () => {
|
||||
const effects: FederationEffect[] = []
|
||||
|
||||
appendFederationTerminalEffects(
|
||||
effects,
|
||||
[
|
||||
{ handle: 'term_agent', title: 'Codex' },
|
||||
{ handle: 'term_configured', title: 'Setup' },
|
||||
{ handle: 'term_setup', title: 'PowerShell' }
|
||||
],
|
||||
'term_agent',
|
||||
'term_setup'
|
||||
)
|
||||
appendFederationSetupEffect(effects, {
|
||||
requested: 'run',
|
||||
effective: 'run',
|
||||
source: 'orchestration_default',
|
||||
hookFound: true,
|
||||
startupPolicy: 'start-immediately',
|
||||
state: 'running'
|
||||
})
|
||||
|
||||
expect(effects).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ id: 'term_configured', role: 'configured_tab' }),
|
||||
expect.objectContaining({ id: 'term_setup', role: 'setup' }),
|
||||
expect.objectContaining({ kind: 'setup', terminalId: 'term_setup' })
|
||||
])
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
export type FederationEffect = {
|
||||
kind: 'worktree' | 'terminal' | 'setup' | 'dispatch_input'
|
||||
action?: string
|
||||
role?: string
|
||||
id?: string
|
||||
state?: string
|
||||
tabId?: string
|
||||
leafId?: string
|
||||
requested?: string
|
||||
effective?: string
|
||||
source?: string
|
||||
hookFound?: boolean
|
||||
startupPolicy?: string
|
||||
terminalId?: string
|
||||
}
|
||||
|
||||
export function appendFederationTerminalEffects(
|
||||
effects: FederationEffect[],
|
||||
terminals: { handle: string; title: string | null; tabId?: string; leafId?: string }[],
|
||||
agentHandle: string,
|
||||
setupHandle?: string
|
||||
): void {
|
||||
for (const terminal of terminals) {
|
||||
effects.push({
|
||||
kind: 'terminal',
|
||||
role:
|
||||
terminal.handle === agentHandle
|
||||
? 'agent'
|
||||
: terminal.handle === setupHandle
|
||||
? 'setup'
|
||||
: 'configured_tab',
|
||||
action: terminal.handle === agentHandle ? 'reused_agent_terminal' : 'created',
|
||||
id: terminal.handle,
|
||||
tabId: terminal.tabId,
|
||||
leafId: terminal.leafId
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function appendFederationSetupEffect(
|
||||
effects: FederationEffect[],
|
||||
setup: {
|
||||
requested: string
|
||||
effective: string
|
||||
source: string
|
||||
hookFound: boolean
|
||||
startupPolicy: string
|
||||
state: string
|
||||
}
|
||||
): void {
|
||||
const setupTerminal = effects.find(
|
||||
(effect) => effect.kind === 'terminal' && effect.role === 'setup'
|
||||
)
|
||||
effects.push({
|
||||
kind: 'setup',
|
||||
action: setup.requested,
|
||||
...setup,
|
||||
terminalId: setupTerminal?.id
|
||||
})
|
||||
}
|
||||
|
||||
export function isFederationResidualEffect(effect: FederationEffect): boolean {
|
||||
return Boolean(effect.action?.startsWith('created') || effect.action === 'reused_agent_terminal')
|
||||
}
|
||||
|
||||
export function isFederationEffectUnknown(error: unknown, stage: string): boolean {
|
||||
const code =
|
||||
error && typeof error === 'object' && typeof (error as { code?: unknown }).code === 'string'
|
||||
? (error as { code: string }).code
|
||||
: ''
|
||||
if (code === 'operation_unknown') {
|
||||
return true
|
||||
}
|
||||
if (!['worktree_create', 'terminal_create', 'dispatch_input'].includes(stage)) {
|
||||
return false
|
||||
}
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return /connection|disconnect|timed?\s*out|runtime changed|outcome unknown/i.test(message)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationDb } from '../../orchestration/db'
|
||||
import { ORCHESTRATION_METHODS } from './orchestration'
|
||||
|
||||
describe('orchestration federated folder placement', () => {
|
||||
let db: OrchestrationDb | undefined
|
||||
|
||||
afterEach(() => db?.close())
|
||||
|
||||
it('rejects a new folder workspace before accepting the remote attachment', async () => {
|
||||
db = new OrchestrationDb(':memory:')
|
||||
const runtime = new OrcaRuntimeService()
|
||||
runtime.setOrchestrationDb(db)
|
||||
vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {})
|
||||
vi.spyOn(runtime, 'showRepo').mockResolvedValue({
|
||||
id: 'folder-repo',
|
||||
kind: 'folder'
|
||||
} as never)
|
||||
const method = ORCHESTRATION_METHODS.find(
|
||||
(candidate) => candidate.name === 'orchestration.federationAttachStart'
|
||||
)
|
||||
if (!method) {
|
||||
throw new Error('federationAttachStart method is not registered')
|
||||
}
|
||||
|
||||
await expect(
|
||||
method.handler(
|
||||
method.params!.parse({
|
||||
dispatchId: 'ctx_folder',
|
||||
taskId: 'task_folder',
|
||||
taskSpec: 'work in folder',
|
||||
protocolVersion: 1,
|
||||
worktree: 'new-top-level',
|
||||
repo: 'folder-repo',
|
||||
name: 'folder-worker',
|
||||
agent: 'codex'
|
||||
}),
|
||||
{
|
||||
runtime,
|
||||
orchestrationMutation: {
|
||||
callerFingerprint: 'home_peer',
|
||||
requestId: 'request_folder',
|
||||
method: 'orchestration.federationAttachStart',
|
||||
payloadHash: 'folder_payload'
|
||||
}
|
||||
}
|
||||
)
|
||||
).rejects.toMatchObject({
|
||||
code: 'invalid_argument',
|
||||
message:
|
||||
'Folder projects cannot create orchestration worktrees; use an exact existing folder workspace.'
|
||||
})
|
||||
expect(db.getRemoteDispatchAttachment('ctx_folder')).toBeUndefined()
|
||||
expect(db.getMutationReceipt('home_peer', 'request_folder')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { RpcMethod } from '../core'
|
||||
import { ORCHESTRATION_FEDERATION_CONTROL_METHODS } from './orchestration-federation-control'
|
||||
import { ORCHESTRATION_FEDERATION_RELAY_METHODS } from './orchestration-federation-relay'
|
||||
import { ORCHESTRATION_FEDERATION_ATTACH_METHODS } from './orchestration-federation'
|
||||
|
||||
export const ORCHESTRATION_FEDERATION_METHODS: RpcMethod[] = [
|
||||
...ORCHESTRATION_FEDERATION_ATTACH_METHODS,
|
||||
...ORCHESTRATION_FEDERATION_RELAY_METHODS,
|
||||
...ORCHESTRATION_FEDERATION_CONTROL_METHODS
|
||||
]
|
||||
@@ -0,0 +1,312 @@
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope'
|
||||
import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../shared/protocol-version'
|
||||
import { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationDb } from '../../orchestration/db'
|
||||
import type { OrchestrationEnvironmentTransport } from '../../orchestration/environment-transport'
|
||||
import type { RpcRequest } from '../core'
|
||||
import { RpcDispatcher } from '../dispatcher'
|
||||
import { ORCHESTRATION_METHODS } from './orchestration'
|
||||
|
||||
describe('orchestration federated worker output', () => {
|
||||
const databases: OrchestrationDb[] = []
|
||||
let homeDb: OrchestrationDb
|
||||
let workerDb: OrchestrationDb
|
||||
let homeRuntime: OrcaRuntimeService
|
||||
let workerRuntime: OrcaRuntimeService
|
||||
let homeDispatcher: RpcDispatcher
|
||||
let workerDispatcher: RpcDispatcher
|
||||
let workerSupportsStructuredRead: boolean
|
||||
|
||||
beforeEach(() => {
|
||||
homeDb = new OrchestrationDb(':memory:')
|
||||
workerDb = new OrchestrationDb(':memory:')
|
||||
databases.push(homeDb, workerDb)
|
||||
workerRuntime = new OrcaRuntimeService()
|
||||
workerRuntime.setOrchestrationDb(workerDb)
|
||||
workerDispatcher = new RpcDispatcher({
|
||||
runtime: workerRuntime,
|
||||
methods: ORCHESTRATION_METHODS
|
||||
})
|
||||
workerSupportsStructuredRead = true
|
||||
const transport: OrchestrationEnvironmentTransport = {
|
||||
resolve: () => ({
|
||||
environmentId: 'environment_windows',
|
||||
name: 'windows',
|
||||
peerFingerprint: 'windows_peer_fingerprint'
|
||||
}),
|
||||
call: async (_selector, method, params, _timeoutMs, envelope) => {
|
||||
if (method === 'status.get') {
|
||||
return {
|
||||
id: 'status',
|
||||
ok: true,
|
||||
result: workerRuntime.getStatus(),
|
||||
_meta: { runtimeId: workerRuntime.getRuntimeId() }
|
||||
}
|
||||
}
|
||||
if (method === 'orchestration.federationReadOutput' && !workerSupportsStructuredRead) {
|
||||
return {
|
||||
id: `remote_${method}`,
|
||||
ok: false,
|
||||
error: { code: 'method_not_found', message: `Unknown method: ${method}` }
|
||||
}
|
||||
}
|
||||
return (await workerDispatcher.dispatch({
|
||||
id: `remote_${method}`,
|
||||
authToken: 'run-home-device-token',
|
||||
method,
|
||||
params,
|
||||
orchestrationContractVersion: envelope?.orchestrationContractVersion,
|
||||
orchestrationRequestId: envelope?.orchestrationRequestId,
|
||||
orchestrationCapability: envelope?.orchestrationCapability
|
||||
})) as RuntimeRpcResponse<unknown>
|
||||
}
|
||||
}
|
||||
homeRuntime = new OrcaRuntimeService(null, undefined, {
|
||||
orchestrationEnvironmentTransport: transport
|
||||
})
|
||||
homeRuntime.setOrchestrationDb(homeDb)
|
||||
homeDispatcher = new RpcDispatcher({
|
||||
runtime: homeRuntime,
|
||||
methods: ORCHESTRATION_METHODS
|
||||
})
|
||||
vi.spyOn(homeRuntime, 'getTerminalPaneKey').mockImplementation((handle) =>
|
||||
handle === 'term_coord' ? 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' : null
|
||||
)
|
||||
configureWorkerRuntime(workerRuntime)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
homeRuntime.stopOrchestrationFederationRelay()
|
||||
for (const db of databases.splice(0)) {
|
||||
db.close()
|
||||
}
|
||||
})
|
||||
|
||||
function createHomeTask() {
|
||||
const run = homeDb.createRun({
|
||||
objective: 'Mac to Windows output',
|
||||
coordinatorHandle: 'term_coord',
|
||||
coordinatorPaneKey: 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
})
|
||||
return homeDb.createTask({ spec: 'Read Windows worker output', runId: run.id })
|
||||
}
|
||||
|
||||
function startRequest(taskId: string): RpcRequest {
|
||||
return {
|
||||
id: 'rpc_worker_start',
|
||||
authToken: 'coordinator-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'request_windows_worker',
|
||||
method: 'orchestration.workerStart',
|
||||
params: {
|
||||
task: taskId,
|
||||
from: 'term_coord',
|
||||
on: 'windows',
|
||||
worktree: 'new-top-level',
|
||||
repo: 'id:windows-repo',
|
||||
name: 'windows-output',
|
||||
agent: 'codex'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function configureWorkerRuntime(runtime: OrcaRuntimeService): void {
|
||||
vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {})
|
||||
vi.spyOn(runtime, 'showRepo').mockResolvedValue({
|
||||
id: 'windows-repo',
|
||||
kind: 'git'
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'createManagedWorktree').mockResolvedValue({
|
||||
worktree: { id: 'repo::windows-worktree', repoId: 'repo' },
|
||||
startupTerminal: { spawned: true, handle: 'term_windows_worker' },
|
||||
setupReceipt: {
|
||||
requested: 'run',
|
||||
hookFound: false,
|
||||
startupPolicy: 'start-immediately',
|
||||
state: 'not_configured'
|
||||
}
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'listTerminals').mockResolvedValue({
|
||||
terminals: [{ handle: 'term_windows_worker', title: 'Codex' }],
|
||||
totalCount: 1,
|
||||
truncated: false
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'waitForTerminal').mockResolvedValue({
|
||||
handle: 'term_windows_worker',
|
||||
condition: 'tui-idle',
|
||||
satisfied: true,
|
||||
status: 'running',
|
||||
exitCode: null
|
||||
})
|
||||
vi.spyOn(runtime, 'getTerminalPaneKey').mockReturnValue(
|
||||
'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
|
||||
)
|
||||
vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockReturnValue('windows_runtime:pty:1')
|
||||
vi.spyOn(runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca')
|
||||
vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({
|
||||
handle: 'term_windows_worker',
|
||||
accepted: true,
|
||||
bytesWritten: 1
|
||||
})
|
||||
vi.spyOn(runtime, 'showTerminal').mockResolvedValue({
|
||||
handle: 'term_windows_worker',
|
||||
worktreeId: 'repo::windows-worktree',
|
||||
status: 'running'
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'readTerminal').mockResolvedValue({
|
||||
handle: 'term_windows_worker',
|
||||
status: 'running',
|
||||
tail: ['remote output'],
|
||||
truncated: false,
|
||||
nextCursor: '1'
|
||||
})
|
||||
}
|
||||
|
||||
async function startRemoteWorker(): Promise<string> {
|
||||
const task = createHomeTask()
|
||||
await homeDispatcher.dispatch(startRequest(task.id))
|
||||
return homeDb.getDispatchContext(task.id)!.id
|
||||
}
|
||||
|
||||
it('routes show and read by Dispatch without repeating the worker server', async () => {
|
||||
const dispatchId = await startRemoteWorker()
|
||||
|
||||
const shown = await homeDispatcher.dispatch({
|
||||
id: 'rpc_remote_show',
|
||||
authToken: 'coordinator-token',
|
||||
method: 'orchestration.workerShow',
|
||||
params: { dispatch: dispatchId }
|
||||
})
|
||||
const read = await homeDispatcher.dispatch({
|
||||
id: 'rpc_remote_read',
|
||||
authToken: 'coordinator-token',
|
||||
method: 'orchestration.workerRead',
|
||||
params: { dispatch: dispatchId, limit: 20 }
|
||||
})
|
||||
|
||||
expect(shown).toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
server: { environmentId: 'environment_windows', name: 'windows' },
|
||||
observation: { status: 'running', exactWorker: true },
|
||||
terminal: { handle: 'term_windows_worker' }
|
||||
}
|
||||
})
|
||||
expect(read).toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
source: 'terminal',
|
||||
fallbackReason: 'session_not_reported',
|
||||
server: { environmentId: 'environment_windows', name: 'windows' },
|
||||
terminal: { tail: ['remote output'] }
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps an opaque terminal cursor across mixed server versions', async () => {
|
||||
const dispatchId = await startRemoteWorker()
|
||||
workerSupportsStructuredRead = false
|
||||
|
||||
const automatic = await homeDispatcher.dispatch({
|
||||
id: 'rpc_remote_legacy_read',
|
||||
authToken: 'coordinator-token',
|
||||
method: 'orchestration.workerRead',
|
||||
params: { dispatch: dispatchId }
|
||||
})
|
||||
const cursor = (automatic as { result: { cursor: string } }).result.cursor
|
||||
const continued = await homeDispatcher.dispatch({
|
||||
id: 'rpc_remote_legacy_continue',
|
||||
authToken: 'coordinator-token',
|
||||
method: 'orchestration.workerRead',
|
||||
params: { dispatch: dispatchId, cursor }
|
||||
})
|
||||
const required = await homeDispatcher.dispatch({
|
||||
id: 'rpc_remote_legacy_transcript',
|
||||
authToken: 'coordinator-token',
|
||||
method: 'orchestration.workerRead',
|
||||
params: { dispatch: dispatchId, source: 'transcript' }
|
||||
})
|
||||
|
||||
expect(automatic).toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
source: 'terminal',
|
||||
fallbackReason: 'remote_capability_unavailable',
|
||||
terminal: { tail: ['remote output'] }
|
||||
}
|
||||
})
|
||||
expect(cursor).toMatch(/^owr1_/)
|
||||
expect(continued).toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
source: 'terminal',
|
||||
fallbackReason: 'remote_capability_unavailable'
|
||||
}
|
||||
})
|
||||
expect((continued as { result: { cursor: string } }).result.cursor).toMatch(/^owr1_/)
|
||||
expect(required).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
code: 'transcript_required',
|
||||
data: { reason: 'remote_capability_unavailable' }
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('reads the exact transcript on the worker server without leaking its path home', async () => {
|
||||
const dispatchId = await startRemoteWorker()
|
||||
const directory = await mkdtemp(join(tmpdir(), 'orca-federated-worker-output-'))
|
||||
const transcriptPath = join(directory, 'windows-session.jsonl')
|
||||
await writeFile(
|
||||
transcriptPath,
|
||||
`${JSON.stringify({
|
||||
type: 'event_msg',
|
||||
payload: { id: 'remote-message', type: 'agent_message', message: 'Windows result' }
|
||||
})}\n`
|
||||
)
|
||||
vi.spyOn(workerRuntime, 'getExactWorkerProviderSession').mockReturnValue({
|
||||
paneKey: 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
|
||||
processIncarnation: 'windows_runtime:pty:1',
|
||||
agent: 'codex',
|
||||
providerSession: {
|
||||
key: 'session_id',
|
||||
id: 'windows-session',
|
||||
transcriptPath
|
||||
},
|
||||
observedAt: Date.now()
|
||||
})
|
||||
|
||||
try {
|
||||
const response = await homeDispatcher.dispatch({
|
||||
id: 'rpc_remote_transcript_read',
|
||||
authToken: 'coordinator-token',
|
||||
method: 'orchestration.workerRead',
|
||||
params: { dispatch: dispatchId }
|
||||
})
|
||||
|
||||
expect(response).toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
source: 'transcript',
|
||||
provider: 'codex',
|
||||
server: { environmentId: 'environment_windows' },
|
||||
transcript: {
|
||||
messages: [
|
||||
{
|
||||
id: 'remote-message',
|
||||
blocks: [{ type: 'text', text: 'Windows result' }]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
})
|
||||
expect(JSON.stringify(response)).not.toContain(transcriptPath)
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,179 @@
|
||||
import { z } from 'zod'
|
||||
import { ORCHESTRATION_FEDERATION_CONTROL_MAIL_PROTOCOL_VERSION } from '../../../../shared/protocol-version'
|
||||
import { importFederatedControlMessage } from '../../orchestration/federation-control-message'
|
||||
import { OrchestrationError } from '../../orchestration/orchestration-error'
|
||||
import { defineMethod, type RpcMethod } from '../core'
|
||||
import { OptionalFiniteNumber, requiredString } from '../schemas'
|
||||
|
||||
const FederationPullParams = z.object({
|
||||
dispatchId: requiredString('Missing Dispatch ID'),
|
||||
afterSequence: OptionalFiniteNumber,
|
||||
limit: OptionalFiniteNumber
|
||||
})
|
||||
|
||||
const FederationAckParams = z.object({
|
||||
dispatchId: requiredString('Missing Dispatch ID'),
|
||||
throughSequence: z.number().int().nonnegative()
|
||||
})
|
||||
|
||||
const FederationImportParams = z.object({
|
||||
dispatchId: requiredString('Missing Dispatch ID'),
|
||||
items: z.array(
|
||||
z.object({
|
||||
dispatch_id: requiredString('Missing item Dispatch ID'),
|
||||
direction: z.literal('to_worker'),
|
||||
sequence: z.number().int().positive(),
|
||||
message_id: requiredString('Missing relay message ID'),
|
||||
kind: requiredString('Missing relay kind'),
|
||||
payload: requiredString('Missing relay payload')
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
export const ORCHESTRATION_FEDERATION_RELAY_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.federationPull',
|
||||
params: FederationPullParams,
|
||||
handler: (params, { runtime, authenticatedCallerFingerprint }) => {
|
||||
requireHomeAttachment(runtime, params.dispatchId, authenticatedCallerFingerprint)
|
||||
return {
|
||||
dispatchId: params.dispatchId,
|
||||
runtimeEpoch: runtime.getRuntimeId(),
|
||||
items: runtime.getOrchestrationDb().listFederationRelay({
|
||||
dispatchId: params.dispatchId,
|
||||
direction: 'to_home',
|
||||
afterSequence: params.afterSequence ?? 0,
|
||||
limit: params.limit
|
||||
})
|
||||
}
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'orchestration.federationAck',
|
||||
params: FederationAckParams,
|
||||
handler: (params, { runtime, authenticatedCallerFingerprint }) => {
|
||||
requireHomeAttachment(runtime, params.dispatchId, authenticatedCallerFingerprint)
|
||||
runtime.getOrchestrationDb().acknowledgeFederationRelay({
|
||||
dispatchId: params.dispatchId,
|
||||
direction: 'to_home',
|
||||
throughSequence: params.throughSequence
|
||||
})
|
||||
return { dispatchId: params.dispatchId, acknowledgedThrough: params.throughSequence }
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'orchestration.federationImport',
|
||||
params: FederationImportParams,
|
||||
handler: (params, { runtime, authenticatedCallerFingerprint }) => {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const attachment = requireHomeAttachment(
|
||||
runtime,
|
||||
params.dispatchId,
|
||||
authenticatedCallerFingerprint
|
||||
)
|
||||
let cursor = attachment.to_worker_imported_sequence
|
||||
let imported = 0
|
||||
for (const item of params.items) {
|
||||
if (item.dispatch_id !== params.dispatchId || item.sequence > cursor + 1) {
|
||||
throw new OrchestrationError(
|
||||
'operation_unknown',
|
||||
`Home relay for ${params.dispatchId} is not contiguous after sequence ${cursor}.`
|
||||
)
|
||||
}
|
||||
if (item.sequence <= cursor) {
|
||||
continue
|
||||
}
|
||||
const currentAttachment = requireHomeAttachment(
|
||||
runtime,
|
||||
params.dispatchId,
|
||||
authenticatedCallerFingerprint
|
||||
)
|
||||
if (currentAttachment.state !== 'ready') {
|
||||
throw new OrchestrationError(
|
||||
'dispatch_inactive',
|
||||
`Remote Dispatch ${params.dispatchId} is not active.`
|
||||
)
|
||||
}
|
||||
if (item.kind === 'reply') {
|
||||
const reply = parseFederatedReply(item.payload)
|
||||
db.answerRemoteQuestion({
|
||||
messageId: reply.questionId,
|
||||
dispatchId: params.dispatchId,
|
||||
answerMessageId: reply.answerMessageId,
|
||||
body: reply.body
|
||||
})
|
||||
runtime.notifyMessageArrived(`dispatch:${params.dispatchId}`, 'status')
|
||||
} else if (item.kind === 'control_message') {
|
||||
if (
|
||||
currentAttachment.protocol_version <
|
||||
ORCHESTRATION_FEDERATION_CONTROL_MAIL_PROTOCOL_VERSION
|
||||
) {
|
||||
throw new OrchestrationError(
|
||||
'capability_unsupported',
|
||||
`Remote Dispatch ${params.dispatchId} does not support coordinator control mail.`
|
||||
)
|
||||
}
|
||||
const controlMessage = importFederatedControlMessage(db, {
|
||||
dispatchId: params.dispatchId,
|
||||
messageId: item.message_id,
|
||||
payload: item.payload
|
||||
})
|
||||
imported += controlMessage.imported ? 1 : 0
|
||||
if (controlMessage.imported) {
|
||||
runtime.notifyMessageArrived(`dispatch:${params.dispatchId}`, controlMessage.type)
|
||||
}
|
||||
} else {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
`Federated worker relay kind ${item.kind} is not supported.`
|
||||
)
|
||||
}
|
||||
cursor = item.sequence
|
||||
db.setRemoteWorkerImportSequence(params.dispatchId, cursor)
|
||||
}
|
||||
return { dispatchId: params.dispatchId, acknowledgedThrough: cursor, imported }
|
||||
}
|
||||
})
|
||||
]
|
||||
|
||||
function requireHomeAttachment(
|
||||
runtime: Parameters<RpcMethod['handler']>[1]['runtime'],
|
||||
dispatchId: string,
|
||||
callerFingerprint: string | undefined
|
||||
) {
|
||||
const attachment = runtime.getOrchestrationDb().getRemoteDispatchAttachment(dispatchId)
|
||||
if (!attachment || attachment.home_peer_fingerprint !== callerFingerprint) {
|
||||
throw new OrchestrationError(
|
||||
'dispatch_not_found',
|
||||
`Remote Dispatch ${dispatchId} was not found for this Run home.`
|
||||
)
|
||||
}
|
||||
return attachment
|
||||
}
|
||||
|
||||
function parseFederatedReply(payload: string): {
|
||||
questionId: string
|
||||
answerMessageId: string
|
||||
body: string
|
||||
} {
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(payload)
|
||||
} catch {
|
||||
throw new OrchestrationError('invalid_argument', 'Federated reply payload is invalid JSON.')
|
||||
}
|
||||
const reply = parsed as Record<string, unknown> | null
|
||||
if (
|
||||
!reply ||
|
||||
typeof reply.questionId !== 'string' ||
|
||||
typeof reply.answerMessageId !== 'string' ||
|
||||
typeof reply.body !== 'string'
|
||||
) {
|
||||
throw new OrchestrationError('invalid_argument', 'Federated reply payload is incomplete.')
|
||||
}
|
||||
return {
|
||||
questionId: reply.questionId,
|
||||
answerMessageId: reply.answerMessageId,
|
||||
body: reply.body
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationDb } from '../../orchestration/db'
|
||||
import { ORCHESTRATION_METHODS } from './orchestration'
|
||||
import { monitorFederatedSetup } from './orchestration-federation-setup'
|
||||
|
||||
describe('orchestration federated setup evidence', () => {
|
||||
const databases: OrchestrationDb[] = []
|
||||
const runtimes: OrcaRuntimeService[] = []
|
||||
|
||||
afterEach(() => {
|
||||
for (const runtime of runtimes.splice(0)) {
|
||||
runtime.stopOrchestrationFederationRelay()
|
||||
}
|
||||
for (const db of databases.splice(0)) {
|
||||
db.close()
|
||||
}
|
||||
})
|
||||
|
||||
function createRuntime(): { db: OrchestrationDb; runtime: OrcaRuntimeService } {
|
||||
const db = new OrchestrationDb(':memory:')
|
||||
const runtime = new OrcaRuntimeService()
|
||||
runtime.setOrchestrationDb(db)
|
||||
databases.push(db)
|
||||
runtimes.push(runtime)
|
||||
return { db, runtime }
|
||||
}
|
||||
|
||||
it('records remote setup evidence once without changing attachment lifecycle', async () => {
|
||||
const { db, runtime } = createRuntime()
|
||||
const dispatchId = 'ctx_remote_setup'
|
||||
const effects = [
|
||||
{
|
||||
kind: 'terminal' as const,
|
||||
role: 'setup',
|
||||
action: 'created',
|
||||
id: 'term_remote_setup'
|
||||
},
|
||||
{
|
||||
kind: 'setup' as const,
|
||||
action: 'run',
|
||||
state: 'running'
|
||||
},
|
||||
{
|
||||
kind: 'dispatch_input' as const,
|
||||
role: 'agent',
|
||||
id: 'term_remote_worker',
|
||||
state: 'accepted'
|
||||
}
|
||||
]
|
||||
db.createRemoteDispatchAttachment({
|
||||
dispatchId,
|
||||
taskId: 'task_remote_setup',
|
||||
homePeerFingerprint: 'home_peer',
|
||||
protocolVersion: 1,
|
||||
runtimeEpoch: runtime.getRuntimeId(),
|
||||
mutationReceipt: {
|
||||
callerFingerprint: 'home_peer',
|
||||
requestId: 'request_remote_setup',
|
||||
method: 'orchestration.federationAttachStart',
|
||||
payloadHash: 'remote_setup_payload'
|
||||
}
|
||||
})
|
||||
db.prepareRemoteAttachmentAuthority({
|
||||
dispatchId,
|
||||
paneKey: 'tab_worker:leaf_worker',
|
||||
processIncarnation: 'worker_epoch:pty:1',
|
||||
worktreeId: 'repo::remote-worktree',
|
||||
terminalHandle: 'term_remote_worker',
|
||||
setupState: 'running',
|
||||
effects
|
||||
})
|
||||
db.markRemoteAttachmentReady(dispatchId)
|
||||
vi.spyOn(runtime, 'waitForSetupTerminalCompletion').mockResolvedValue({ exitCode: 1 })
|
||||
const monitorArgs = {
|
||||
runtime,
|
||||
db,
|
||||
dispatchId,
|
||||
worktreeId: 'repo::remote-worktree',
|
||||
terminalHandle: 'term_remote_worker',
|
||||
setup: {
|
||||
requested: 'run' as const,
|
||||
effective: 'run' as const,
|
||||
source: 'orchestration_default',
|
||||
hookFound: true,
|
||||
startupPolicy: 'start-immediately' as const,
|
||||
state: 'running' as const
|
||||
},
|
||||
effects
|
||||
}
|
||||
|
||||
monitorFederatedSetup(monitorArgs)
|
||||
monitorFederatedSetup(monitorArgs)
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(db.getRemoteDispatchAttachment(dispatchId)).toMatchObject({
|
||||
state: 'ready',
|
||||
stage: 'input_accepted',
|
||||
setup_state: 'failed'
|
||||
})
|
||||
)
|
||||
expect(
|
||||
db.listFederationRelay({ dispatchId, direction: 'to_home', afterSequence: 0 })
|
||||
).toHaveLength(1)
|
||||
expect(JSON.parse(db.getRemoteDispatchAttachment(dispatchId)?.effects ?? '[]')).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'dispatch_input', state: 'accepted' })
|
||||
])
|
||||
)
|
||||
})
|
||||
|
||||
it('refreshes home setup evidence without changing a ready Dispatch lifecycle', async () => {
|
||||
const { db, runtime } = createRuntime()
|
||||
const run = db.createRun({
|
||||
objective: 'Observe remote setup',
|
||||
coordinatorHandle: 'term_coord',
|
||||
coordinatorPaneKey: 'tab_coord:leaf_coord'
|
||||
})
|
||||
const task = db.createTask({ spec: 'remote setup', runId: run.id })
|
||||
const started = db.createStartingWorkerDispatch({
|
||||
taskId: task.id,
|
||||
startOptions: {},
|
||||
runtimeEpoch: runtime.getRuntimeId(),
|
||||
federation: {
|
||||
environmentId: 'environment_windows',
|
||||
environmentName: 'windows',
|
||||
peerFingerprint: 'windows_peer',
|
||||
protocolVersion: 1
|
||||
}
|
||||
})
|
||||
db.recordWorkerStage({
|
||||
dispatchId: started.dispatch.id,
|
||||
stage: 'terminal_readying',
|
||||
setupState: 'running',
|
||||
effects: [
|
||||
{ kind: 'setup', action: 'run', state: 'running' },
|
||||
{
|
||||
kind: 'dispatch_input',
|
||||
role: 'agent',
|
||||
id: 'term_remote_worker',
|
||||
state: 'accepted'
|
||||
}
|
||||
]
|
||||
})
|
||||
db.markWorkerDispatchReady(started.dispatch.id)
|
||||
vi.spyOn(runtime, 'resolveOrchestrationWorkerServer').mockReturnValue({
|
||||
environmentId: 'environment_windows',
|
||||
name: 'windows',
|
||||
peerFingerprint: 'windows_peer'
|
||||
})
|
||||
vi.spyOn(runtime, 'callOrchestrationWorkerServer').mockResolvedValue({
|
||||
runtimeEpoch: 'windows_epoch',
|
||||
attachment: {
|
||||
state: 'ready',
|
||||
stage: 'input_accepted',
|
||||
last_error: null,
|
||||
worktree_id: 'repo::remote-worktree',
|
||||
terminal_handle: 'term_remote_worker',
|
||||
setup_state: 'failed',
|
||||
effects: [
|
||||
{ kind: 'setup', action: 'run', state: 'failed' },
|
||||
{
|
||||
kind: 'dispatch_input',
|
||||
role: 'agent',
|
||||
id: 'term_remote_worker',
|
||||
state: 'accepted'
|
||||
}
|
||||
],
|
||||
residualResources: []
|
||||
},
|
||||
terminal: { handle: 'term_remote_worker', connected: true },
|
||||
observation: { status: 'running', exactWorker: true }
|
||||
})
|
||||
const workerShow = ORCHESTRATION_METHODS.find(
|
||||
(method) => method.name === 'orchestration.workerShow'
|
||||
)
|
||||
if (!workerShow) {
|
||||
throw new Error('workerShow method is not registered')
|
||||
}
|
||||
|
||||
await expect(
|
||||
workerShow.handler(workerShow.params!.parse({ dispatch: started.dispatch.id }), { runtime })
|
||||
).resolves.toMatchObject({
|
||||
worker: {
|
||||
state: 'ready',
|
||||
stage: 'input_accepted',
|
||||
setup_state: 'failed',
|
||||
effects: expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'setup', state: 'failed' }),
|
||||
expect.objectContaining({ kind: 'dispatch_input', state: 'accepted' })
|
||||
])
|
||||
}
|
||||
})
|
||||
expect(db.getTask(task.id)?.status).toBe('dispatched')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import type { OrchestrationDb } from '../../orchestration/db'
|
||||
import { applyWaitForSetupOutcome, type WorkerSetupReceipt } from './orchestration-worker-topology'
|
||||
import {
|
||||
isFederationResidualEffect,
|
||||
type FederationEffect
|
||||
} from './orchestration-federation-effects'
|
||||
|
||||
type FederationSetupStageArgs = {
|
||||
db: OrchestrationDb
|
||||
dispatchId: string
|
||||
worktreeId: string
|
||||
terminalHandle: string
|
||||
setup: WorkerSetupReceipt
|
||||
effects: FederationEffect[]
|
||||
}
|
||||
|
||||
function recordStage(args: FederationSetupStageArgs, stage: string): void {
|
||||
args.db.recordRemoteAttachmentStage({
|
||||
dispatchId: args.dispatchId,
|
||||
stage,
|
||||
worktreeId: args.worktreeId,
|
||||
terminalHandle: args.terminalHandle,
|
||||
setupState: args.setup.state,
|
||||
effects: args.effects,
|
||||
residualResources: args.effects.filter(isFederationResidualEffect)
|
||||
})
|
||||
}
|
||||
|
||||
export function persistFederatedReadinessStage(args: FederationSetupStageArgs): void {
|
||||
recordStage(args, 'terminal_readying')
|
||||
}
|
||||
|
||||
export function persistFederatedSetupSpawnFailure(args: FederationSetupStageArgs): boolean {
|
||||
if (args.setup.startupPolicy !== 'wait-for-setup' || args.setup.state !== 'spawn_failed') {
|
||||
return false
|
||||
}
|
||||
recordStage(args, 'setup_start')
|
||||
return true
|
||||
}
|
||||
|
||||
export function persistFederatedSetupWaitOutcome(
|
||||
args: FederationSetupStageArgs & { wait: { satisfied: boolean; status: string } }
|
||||
): void {
|
||||
applyWaitForSetupOutcome(args.setup, args.effects, args.wait)
|
||||
if (args.setup.startupPolicy === 'wait-for-setup') {
|
||||
recordStage(args, args.setup.state === 'failed' ? 'setup_failed' : 'setup_settled')
|
||||
}
|
||||
}
|
||||
|
||||
export function monitorFederatedSetup(
|
||||
args: FederationSetupStageArgs & { runtime: OrcaRuntimeService }
|
||||
): void {
|
||||
const setupTerminal = args.effects.find(
|
||||
(effect) => effect.kind === 'terminal' && effect.role === 'setup' && effect.id
|
||||
)
|
||||
if (
|
||||
!setupTerminal?.id ||
|
||||
args.setup.startupPolicy !== 'start-immediately' ||
|
||||
args.setup.state !== 'running'
|
||||
) {
|
||||
return
|
||||
}
|
||||
void args.runtime
|
||||
.waitForSetupTerminalCompletion(setupTerminal.id)
|
||||
.then((completion) => {
|
||||
const setupState = completion.exitCode === 0 ? 'succeeded' : 'failed'
|
||||
const effects = args.effects.map((effect) =>
|
||||
effect.kind === 'setup' ? { ...effect, state: setupState } : effect
|
||||
)
|
||||
const evidence = args.db.updateRemoteAttachmentSetupEvidence({
|
||||
dispatchId: args.dispatchId,
|
||||
setupState,
|
||||
effects
|
||||
})
|
||||
if (!evidence.changed) {
|
||||
return
|
||||
}
|
||||
args.db.enqueueFederationRelay({
|
||||
dispatchId: args.dispatchId,
|
||||
direction: 'to_home',
|
||||
kind: 'status',
|
||||
payload: JSON.stringify({
|
||||
from: `dispatch:${args.dispatchId}`,
|
||||
subject: `Setup ${setupState} for worker ${args.dispatchId}`,
|
||||
body: '',
|
||||
type: 'status',
|
||||
priority: setupState === 'failed' ? 'high' : 'normal',
|
||||
threadId: null,
|
||||
payload: JSON.stringify({
|
||||
dispatchId: args.dispatchId,
|
||||
setupState,
|
||||
terminalHandle: setupTerminal.id
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { OrchestrationDb } from '../../orchestration/db'
|
||||
import { isFederationEffectUnknown } from './orchestration-federation-effects'
|
||||
import type { WorkerSetupReceipt } from './orchestration-worker-topology'
|
||||
|
||||
export function failFederatedAttachmentWithReceipt(args: {
|
||||
db: OrchestrationDb
|
||||
dispatchId: string
|
||||
runtimeEpoch: string
|
||||
failedStage: string
|
||||
error: unknown
|
||||
setup: WorkerSetupReceipt
|
||||
}): unknown {
|
||||
const reason = args.error instanceof Error ? args.error.message : String(args.error)
|
||||
const unknown = isFederationEffectUnknown(args.error, args.failedStage)
|
||||
const attachment = args.db.failRemoteAttachment(
|
||||
args.dispatchId,
|
||||
args.failedStage,
|
||||
reason,
|
||||
unknown
|
||||
)
|
||||
return {
|
||||
dispatchId: args.dispatchId,
|
||||
state: attachment.state === 'start_unknown' ? 'outcome_unknown' : attachment.state,
|
||||
stage: attachment.stage,
|
||||
runtimeEpoch: args.runtimeEpoch,
|
||||
failedStage: args.failedStage,
|
||||
lastError: reason,
|
||||
setup: args.setup,
|
||||
effects: JSON.parse(attachment.effects) as unknown[],
|
||||
residualResources: JSON.parse(attachment.residual_resources) as unknown[]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { z } from 'zod'
|
||||
import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas'
|
||||
|
||||
export const FederationAttachStartParams = z.object({
|
||||
dispatchId: requiredString('Missing Dispatch ID'),
|
||||
taskId: requiredString('Missing Task ID'),
|
||||
taskSpec: requiredString('Missing Task spec'),
|
||||
protocolVersion: z.union([z.literal(1), z.literal(2)]),
|
||||
worktree: requiredString('Missing remote worktree selector'),
|
||||
name: OptionalString,
|
||||
repo: OptionalString,
|
||||
baseBranch: OptionalString,
|
||||
displayName: OptionalString,
|
||||
comment: OptionalString,
|
||||
setup: z.enum(['run', 'skip', 'inherit']).optional(),
|
||||
setupSource: z.enum(['explicit_request', 'orchestration_default']).optional(),
|
||||
terminal: OptionalString,
|
||||
agent: OptionalString,
|
||||
timeoutMs: OptionalFiniteNumber,
|
||||
devMode: z.boolean().optional()
|
||||
})
|
||||
@@ -0,0 +1,862 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { RuntimeRpcResponse } from '../../../../shared/runtime-rpc-envelope'
|
||||
import {
|
||||
ORCHESTRATION_CONTRACT_VERSION,
|
||||
ORCHESTRATION_FEDERATION_CONTROL_MAIL_RUNTIME_CAPABILITY
|
||||
} from '../../../../shared/protocol-version'
|
||||
import { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationDb } from '../../orchestration/db'
|
||||
import type { OrchestrationEnvironmentTransport } from '../../orchestration/environment-transport'
|
||||
import { RpcDispatcher } from '../dispatcher'
|
||||
import type { RpcRequest } from '../core'
|
||||
import { ORCHESTRATION_METHODS } from './orchestration'
|
||||
|
||||
describe('orchestration federation', () => {
|
||||
const databases: OrchestrationDb[] = []
|
||||
let homeDb: OrchestrationDb
|
||||
let workerDb: OrchestrationDb
|
||||
let homeRuntime: OrcaRuntimeService
|
||||
let workerRuntime: OrcaRuntimeService
|
||||
let homeDispatcher: RpcDispatcher
|
||||
let workerDispatcher: RpcDispatcher
|
||||
let workerCapabilities: string[]
|
||||
let workerPeerFingerprint: string
|
||||
let loseNextAckResponse: boolean
|
||||
|
||||
beforeEach(() => {
|
||||
homeDb = new OrchestrationDb(':memory:')
|
||||
workerDb = new OrchestrationDb(':memory:')
|
||||
databases.push(homeDb, workerDb)
|
||||
workerRuntime = new OrcaRuntimeService()
|
||||
workerRuntime.setOrchestrationDb(workerDb)
|
||||
workerDispatcher = new RpcDispatcher({
|
||||
runtime: workerRuntime,
|
||||
methods: ORCHESTRATION_METHODS
|
||||
})
|
||||
workerCapabilities = [...(workerRuntime.getStatus().capabilities ?? [])]
|
||||
workerPeerFingerprint = 'windows_peer_fingerprint'
|
||||
loseNextAckResponse = false
|
||||
const transport: OrchestrationEnvironmentTransport = {
|
||||
resolve: () => ({
|
||||
environmentId: 'environment_windows',
|
||||
name: 'windows',
|
||||
peerFingerprint: workerPeerFingerprint
|
||||
}),
|
||||
call: async (_selector, method, params, _timeoutMs, envelope) => {
|
||||
if (method === 'status.get') {
|
||||
return {
|
||||
id: 'status',
|
||||
ok: true,
|
||||
result: { ...workerRuntime.getStatus(), capabilities: workerCapabilities },
|
||||
_meta: { runtimeId: workerRuntime.getRuntimeId() }
|
||||
}
|
||||
}
|
||||
const response = (await workerDispatcher.dispatch({
|
||||
id: `remote_${method}`,
|
||||
authToken: 'run-home-device-token',
|
||||
method,
|
||||
params,
|
||||
orchestrationContractVersion: envelope?.orchestrationContractVersion,
|
||||
orchestrationRequestId: envelope?.orchestrationRequestId,
|
||||
orchestrationCapability: envelope?.orchestrationCapability
|
||||
})) as RuntimeRpcResponse<unknown>
|
||||
if (method === 'orchestration.federationAck' && loseNextAckResponse) {
|
||||
loseNextAckResponse = false
|
||||
throw new Error('connection lost after acknowledgment')
|
||||
}
|
||||
return response
|
||||
}
|
||||
}
|
||||
homeRuntime = new OrcaRuntimeService(null, undefined, {
|
||||
orchestrationEnvironmentTransport: transport
|
||||
})
|
||||
homeRuntime.setOrchestrationDb(homeDb)
|
||||
homeDispatcher = new RpcDispatcher({
|
||||
runtime: homeRuntime,
|
||||
methods: ORCHESTRATION_METHODS
|
||||
})
|
||||
vi.spyOn(homeRuntime, 'getTerminalPaneKey').mockImplementation((handle) =>
|
||||
handle === 'term_coord' ? 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' : null
|
||||
)
|
||||
configureWorkerRuntime(workerRuntime)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
homeRuntime.stopOrchestrationFederationRelay()
|
||||
for (const db of databases.splice(0)) {
|
||||
db.close()
|
||||
}
|
||||
})
|
||||
|
||||
function createHomeTask() {
|
||||
const run = homeDb.createRun({
|
||||
objective: 'Mac to Windows',
|
||||
coordinatorHandle: 'term_coord',
|
||||
coordinatorPaneKey: 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
})
|
||||
return homeDb.createTask({ spec: 'Audit Windows behavior', runId: run.id })
|
||||
}
|
||||
|
||||
function startRequest(taskId: string, overrides: Record<string, unknown> = {}): RpcRequest {
|
||||
return {
|
||||
id: 'rpc_worker_start',
|
||||
authToken: 'coordinator-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'request_windows_worker',
|
||||
method: 'orchestration.workerStart',
|
||||
params: {
|
||||
task: taskId,
|
||||
from: 'term_coord',
|
||||
on: 'windows',
|
||||
worktree: 'new-top-level',
|
||||
repo: 'id:windows-repo',
|
||||
name: 'windows-audit',
|
||||
agent: 'codex',
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function configureWorkerRuntime(runtime: OrcaRuntimeService): void {
|
||||
vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {})
|
||||
vi.spyOn(runtime, 'showRepo').mockResolvedValue({
|
||||
id: 'windows-repo',
|
||||
kind: 'git'
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'createManagedWorktree').mockResolvedValue({
|
||||
worktree: { id: 'repo::windows-worktree', repoId: 'repo' },
|
||||
startupTerminal: { spawned: true, handle: 'term_windows_worker' },
|
||||
setupReceipt: {
|
||||
requested: 'run',
|
||||
hookFound: true,
|
||||
startupPolicy: 'start-immediately',
|
||||
state: 'running'
|
||||
}
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'listTerminals').mockResolvedValue({
|
||||
terminals: [
|
||||
{ handle: 'term_windows_worker', title: 'Codex' },
|
||||
{ handle: 'term_windows_setup', title: 'Setup' }
|
||||
],
|
||||
totalCount: 2,
|
||||
truncated: false
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'waitForTerminal').mockResolvedValue({
|
||||
handle: 'term_windows_worker',
|
||||
condition: 'tui-idle',
|
||||
satisfied: true,
|
||||
status: 'running',
|
||||
exitCode: null
|
||||
})
|
||||
vi.spyOn(runtime, 'getTerminalPaneKey').mockReturnValue(
|
||||
'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
|
||||
)
|
||||
vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockReturnValue('windows_runtime:pty:1')
|
||||
vi.spyOn(runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca')
|
||||
vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({
|
||||
handle: 'term_windows_worker',
|
||||
accepted: true,
|
||||
bytesWritten: 1
|
||||
})
|
||||
vi.spyOn(runtime, 'showTerminal').mockResolvedValue({
|
||||
handle: 'term_windows_worker',
|
||||
worktreeId: 'repo::windows-worktree',
|
||||
status: 'running'
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'readTerminal').mockResolvedValue({
|
||||
handle: 'term_windows_worker',
|
||||
status: 'running',
|
||||
entries: [{ cursor: 1, text: 'remote output' }],
|
||||
nextCursor: '1',
|
||||
limited: false
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'closeTerminal').mockResolvedValue({
|
||||
handle: 'term_windows_worker',
|
||||
closed: true
|
||||
} as never)
|
||||
}
|
||||
|
||||
function restartWorkerRuntime(): void {
|
||||
workerRuntime = new OrcaRuntimeService()
|
||||
workerRuntime.setOrchestrationDb(workerDb)
|
||||
configureWorkerRuntime(workerRuntime)
|
||||
workerDispatcher = new RpcDispatcher({
|
||||
runtime: workerRuntime,
|
||||
methods: ORCHESTRATION_METHODS
|
||||
})
|
||||
workerCapabilities = [...(workerRuntime.getStatus().capabilities ?? [])]
|
||||
}
|
||||
|
||||
it('starts a remote worker while keeping authoritative Task state at home', async () => {
|
||||
const task = createHomeTask()
|
||||
|
||||
const response = await homeDispatcher.dispatch(startRequest(task.id))
|
||||
|
||||
expect(response).toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
taskId: task.id,
|
||||
state: 'ready',
|
||||
server: { environmentId: 'environment_windows', name: 'windows' },
|
||||
setup: { source: 'orchestration_default' },
|
||||
mutation: { requestId: 'request_windows_worker' }
|
||||
}
|
||||
})
|
||||
const dispatch = homeDb.getDispatchContext(task.id)!
|
||||
expect(homeDb.getTask(task.id)?.status).toBe('dispatched')
|
||||
expect(homeDb.getFederatedDispatch(dispatch.id)).toMatchObject({
|
||||
environment_id: 'environment_windows',
|
||||
environment_name: 'windows',
|
||||
peer_fingerprint: 'windows_peer_fingerprint',
|
||||
remote_worktree_id: 'repo::windows-worktree',
|
||||
remote_terminal_handle: 'term_windows_worker'
|
||||
})
|
||||
expect(workerDb.getRemoteDispatchAttachment(dispatch.id)).toMatchObject({
|
||||
task_id: task.id,
|
||||
protocol_version: 2,
|
||||
state: 'ready',
|
||||
worktree_id: 'repo::windows-worktree',
|
||||
terminal_handle: 'term_windows_worker'
|
||||
})
|
||||
expect(JSON.parse(workerDb.getRemoteDispatchAttachment(dispatch.id)?.effects ?? '[]')).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'dispatch_input', state: 'accepted' })
|
||||
])
|
||||
)
|
||||
expect(workerDb.listTasks()).toHaveLength(0)
|
||||
expect(workerRuntime.sendTerminalAgentPrompt).toHaveBeenCalledWith(
|
||||
'term_windows_worker',
|
||||
expect.stringContaining(`Your task ID is: ${task.id}`)
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves wait-for-setup gating on the connected worker server', async () => {
|
||||
vi.mocked(workerRuntime.createManagedWorktree).mockResolvedValueOnce({
|
||||
worktree: { id: 'repo::windows-worktree', repoId: 'repo' },
|
||||
startupTerminal: { spawned: true, handle: 'term_windows_worker' },
|
||||
setupReceipt: {
|
||||
requested: 'run',
|
||||
hookFound: true,
|
||||
startupPolicy: 'wait-for-setup',
|
||||
state: 'running'
|
||||
}
|
||||
} as never)
|
||||
const task = createHomeTask()
|
||||
|
||||
const response = await homeDispatcher.dispatch(startRequest(task.id, { setup: 'run' }))
|
||||
|
||||
expect(response).toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
state: 'ready',
|
||||
setup: { startupPolicy: 'wait-for-setup', state: 'succeeded' },
|
||||
effects: expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'setup', state: 'succeeded' }),
|
||||
expect.objectContaining({ kind: 'dispatch_input', state: 'accepted' })
|
||||
])
|
||||
}
|
||||
})
|
||||
expect(response).toHaveProperty('result.setup.source', 'explicit_request')
|
||||
expect(workerRuntime.sendTerminalAgentPrompt).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('fails before remote task input when wait-for-setup fails', async () => {
|
||||
vi.mocked(workerRuntime.createManagedWorktree).mockResolvedValueOnce({
|
||||
worktree: { id: 'repo::windows-worktree', repoId: 'repo' },
|
||||
startupTerminal: { spawned: true, handle: 'term_windows_worker' },
|
||||
setupReceipt: {
|
||||
requested: 'run',
|
||||
hookFound: true,
|
||||
startupPolicy: 'wait-for-setup',
|
||||
state: 'running'
|
||||
}
|
||||
} as never)
|
||||
vi.mocked(workerRuntime.waitForTerminal).mockResolvedValueOnce({
|
||||
handle: 'term_windows_worker',
|
||||
condition: 'tui-idle',
|
||||
satisfied: false,
|
||||
status: 'exited',
|
||||
exitCode: 1
|
||||
})
|
||||
const task = createHomeTask()
|
||||
|
||||
const response = await homeDispatcher.dispatch(startRequest(task.id))
|
||||
|
||||
expect(response).toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
state: 'failed',
|
||||
failedStage: 'setup_wait',
|
||||
setup: { state: 'failed' },
|
||||
effects: expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'setup', state: 'failed' })
|
||||
])
|
||||
}
|
||||
})
|
||||
expect(homeDb.getTask(task.id)?.status).toBe('failed')
|
||||
expect(workerRuntime.sendTerminalAgentPrompt).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects control mail before queueing when the worker lacks that capability', async () => {
|
||||
workerCapabilities = workerCapabilities.filter(
|
||||
(capability) => capability !== ORCHESTRATION_FEDERATION_CONTROL_MAIL_RUNTIME_CAPABILITY
|
||||
)
|
||||
const task = createHomeTask()
|
||||
const started = await homeDispatcher.dispatch(startRequest(task.id))
|
||||
expect(started).toMatchObject({ ok: true, result: { state: 'ready' } })
|
||||
const dispatch = homeDb.getDispatchContext(task.id)!
|
||||
|
||||
const sent = await homeDispatcher.dispatch({
|
||||
id: 'send-control-to-old-worker',
|
||||
authToken: 'coordinator-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'send-control-to-old-worker-request',
|
||||
method: 'orchestration.send',
|
||||
params: {
|
||||
from: 'term_coord',
|
||||
to: `dispatch:${dispatch.id}`,
|
||||
subject: 'Continue',
|
||||
body: 'This worker cannot receive control mail yet.',
|
||||
type: 'status'
|
||||
}
|
||||
})
|
||||
|
||||
expect(sent).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'capability_unsupported' }
|
||||
})
|
||||
expect(homeDb.listPendingFederationRelay(dispatch.id, 'to_worker')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('durably relays remote completion into the home Run and acknowledges it', async () => {
|
||||
const task = createHomeTask()
|
||||
const started = await homeDispatcher.dispatch(startRequest(task.id))
|
||||
expect(started.ok).toBe(true)
|
||||
const dispatch = homeDb.getDispatchContext(task.id)!
|
||||
const prompt = vi.mocked(workerRuntime.sendTerminalAgentPrompt).mock.calls[0]?.[1] ?? ''
|
||||
const capability = prompt.match(/--dispatch-capability (dcap_[A-Za-z0-9_-]+)/)?.[1]
|
||||
expect(capability).toBeTruthy()
|
||||
|
||||
const sent = await workerDispatcher.dispatch({
|
||||
id: 'rpc_worker_done',
|
||||
authToken: 'worker-local-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'worker_done_request',
|
||||
orchestrationCapability: capability,
|
||||
method: 'orchestration.send',
|
||||
params: {
|
||||
from: 'term_windows_worker',
|
||||
subject: 'Windows audit complete',
|
||||
body: 'Audited Windows behavior. Found no blocker. Nothing remains.',
|
||||
type: 'worker_done',
|
||||
payload: JSON.stringify({
|
||||
taskId: task.id,
|
||||
dispatchId: dispatch.id,
|
||||
outcome: 'succeeded',
|
||||
filesModified: []
|
||||
})
|
||||
}
|
||||
})
|
||||
expect(sent).toMatchObject({
|
||||
ok: true,
|
||||
result: { relay: { dispatchId: dispatch.id, accepted: true } }
|
||||
})
|
||||
expect(homeDb.getTask(task.id)?.status).toBe('dispatched')
|
||||
|
||||
await homeRuntime.syncOrchestrationFederation()
|
||||
|
||||
expect(homeDb.getTask(task.id)?.status).toBe('completed')
|
||||
expect(homeDb.getWorkerDispatch(dispatch.id)?.state).toBe('succeeded')
|
||||
expect(homeDb.getRunMailboxHistory(task.run_id, 10)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
id: expect.stringMatching(/^relay_/),
|
||||
type: 'worker_done',
|
||||
subject: 'Windows audit complete'
|
||||
})
|
||||
])
|
||||
)
|
||||
expect(
|
||||
workerDb.listFederationRelay({
|
||||
dispatchId: dispatch.id,
|
||||
direction: 'to_home',
|
||||
afterSequence: 0
|
||||
})[0]
|
||||
).toMatchObject({ acked_at: expect.any(String) })
|
||||
})
|
||||
|
||||
it('relays a worker question home and the coordinator answer back', async () => {
|
||||
const task = createHomeTask()
|
||||
await homeDispatcher.dispatch(startRequest(task.id))
|
||||
const dispatch = homeDb.getDispatchContext(task.id)!
|
||||
const prompt = vi.mocked(workerRuntime.sendTerminalAgentPrompt).mock.calls[0]?.[1] ?? ''
|
||||
const capability = prompt.match(/--dispatch-capability (dcap_[A-Za-z0-9_-]+)/)?.[1]
|
||||
const ask = workerDispatcher.dispatch({
|
||||
id: 'rpc_remote_ask',
|
||||
authToken: 'worker-local-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'remote_question_request',
|
||||
orchestrationCapability: capability,
|
||||
method: 'orchestration.ask',
|
||||
params: {
|
||||
from: 'term_windows_worker',
|
||||
question: 'Should I include slow integration tests?',
|
||||
options: 'yes,no',
|
||||
timeoutMs: 60_000
|
||||
}
|
||||
})
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
workerDb.listFederationRelay({
|
||||
dispatchId: dispatch.id,
|
||||
direction: 'to_home',
|
||||
afterSequence: 0
|
||||
})
|
||||
).toHaveLength(1)
|
||||
)
|
||||
|
||||
await homeRuntime.syncOrchestrationFederation()
|
||||
const question = homeDb
|
||||
.getRunMailboxHistory(task.run_id, 10)
|
||||
.find((message) => message.type === 'question')
|
||||
expect(question).toMatchObject({
|
||||
body: 'Should I include slow integration tests?'
|
||||
})
|
||||
|
||||
const reply = await homeDispatcher.dispatch({
|
||||
id: 'rpc_home_reply',
|
||||
authToken: 'coordinator-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'home_reply_request',
|
||||
method: 'orchestration.reply',
|
||||
params: {
|
||||
id: question!.id,
|
||||
body: 'yes',
|
||||
from: 'term_coord'
|
||||
}
|
||||
})
|
||||
expect(reply).toMatchObject({ ok: true, result: { question: { status: 'answered' } } })
|
||||
await homeRuntime.syncOrchestrationFederation()
|
||||
|
||||
await expect(ask).resolves.toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
answer: 'yes',
|
||||
messageId: question!.id,
|
||||
timedOut: false
|
||||
}
|
||||
})
|
||||
expect(
|
||||
homeDb.listFederationRelay({
|
||||
dispatchId: dispatch.id,
|
||||
direction: 'to_worker',
|
||||
afterSequence: 0
|
||||
})[0]
|
||||
).toMatchObject({ acked_at: expect.any(String) })
|
||||
})
|
||||
|
||||
it('keeps a timed-out remote question resumable', async () => {
|
||||
const task = createHomeTask()
|
||||
await homeDispatcher.dispatch(startRequest(task.id))
|
||||
const prompt = vi.mocked(workerRuntime.sendTerminalAgentPrompt).mock.calls[0]?.[1] ?? ''
|
||||
const capability = prompt.match(/--dispatch-capability (dcap_[A-Za-z0-9_-]+)/)?.[1]
|
||||
const timedOut = await workerDispatcher.dispatch({
|
||||
id: 'rpc_remote_ask_timeout',
|
||||
authToken: 'worker-local-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'remote_question_timeout_request',
|
||||
orchestrationCapability: capability,
|
||||
method: 'orchestration.ask',
|
||||
params: {
|
||||
from: 'term_windows_worker',
|
||||
question: 'Resume this later?',
|
||||
timeoutMs: 1
|
||||
}
|
||||
})
|
||||
expect(timedOut).toMatchObject({
|
||||
ok: true,
|
||||
result: { timedOut: true, messageId: expect.stringMatching(/^relay_/) }
|
||||
})
|
||||
const questionId = (timedOut as { result: { messageId: string } }).result.messageId
|
||||
|
||||
await homeRuntime.syncOrchestrationFederation()
|
||||
await homeDispatcher.dispatch({
|
||||
id: 'rpc_home_late_reply',
|
||||
authToken: 'coordinator-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'home_late_reply_request',
|
||||
method: 'orchestration.reply',
|
||||
params: { id: questionId, body: 'yes', from: 'term_coord' }
|
||||
})
|
||||
restartWorkerRuntime()
|
||||
const resumed = workerDispatcher.dispatch({
|
||||
id: 'rpc_remote_ask_resume',
|
||||
authToken: 'worker-local-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'remote_question_resume_request',
|
||||
orchestrationCapability: capability,
|
||||
method: 'orchestration.ask',
|
||||
params: { from: 'term_windows_worker', resume: questionId, timeoutMs: 5_000 }
|
||||
})
|
||||
await homeRuntime.syncOrchestrationFederation()
|
||||
|
||||
await expect(resumed).resolves.toMatchObject({
|
||||
ok: true,
|
||||
result: { answer: 'yes', messageId: questionId, timedOut: false }
|
||||
})
|
||||
})
|
||||
|
||||
it('retries a lost relay acknowledgment without duplicating the home message', async () => {
|
||||
const task = createHomeTask()
|
||||
await homeDispatcher.dispatch(startRequest(task.id))
|
||||
const dispatch = homeDb.getDispatchContext(task.id)!
|
||||
const prompt = vi.mocked(workerRuntime.sendTerminalAgentPrompt).mock.calls[0]?.[1] ?? ''
|
||||
const capability = prompt.match(/--dispatch-capability (dcap_[A-Za-z0-9_-]+)/)?.[1]
|
||||
await workerDispatcher.dispatch({
|
||||
id: 'rpc_remote_status',
|
||||
authToken: 'worker-local-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'remote_status_request',
|
||||
orchestrationCapability: capability,
|
||||
method: 'orchestration.send',
|
||||
params: {
|
||||
from: 'term_windows_worker',
|
||||
subject: 'Checkpoint',
|
||||
body: 'One durable update',
|
||||
type: 'status'
|
||||
}
|
||||
})
|
||||
loseNextAckResponse = true
|
||||
|
||||
await expect(homeRuntime.syncOrchestrationFederation()).resolves.toBeUndefined()
|
||||
await homeRuntime.syncOrchestrationFederation()
|
||||
|
||||
expect(
|
||||
homeDb
|
||||
.getRunMailboxHistory(task.run_id, 10)
|
||||
.filter((message) => message.subject === 'Checkpoint')
|
||||
).toHaveLength(1)
|
||||
expect(homeDb.getFederatedDispatch(dispatch.id)?.to_home_imported_sequence).toBe(1)
|
||||
})
|
||||
|
||||
it('rejects a reordered relay gap, then converges without loss or duplication', async () => {
|
||||
const task = createHomeTask()
|
||||
await homeDispatcher.dispatch(startRequest(task.id))
|
||||
const dispatch = homeDb.getDispatchContext(task.id)!
|
||||
|
||||
expect(() =>
|
||||
homeDb.importFederatedRelayItem({
|
||||
dispatchId: dispatch.id,
|
||||
sequence: 2,
|
||||
message: {
|
||||
id: 'relay_gap',
|
||||
runId: task.run_id,
|
||||
from: `dispatch:${dispatch.id}`,
|
||||
to: `run:${task.run_id}`,
|
||||
subject: 'Gap',
|
||||
body: 'Out of order',
|
||||
type: 'status',
|
||||
priority: 'normal'
|
||||
},
|
||||
lifecycle: { kind: 'none' }
|
||||
})
|
||||
).toThrow(/not contiguous/)
|
||||
expect(homeDb.getMessageById('relay_gap')).toBeUndefined()
|
||||
expect(homeDb.getFederatedDispatch(dispatch.id)?.to_home_imported_sequence).toBe(0)
|
||||
|
||||
homeDb.importFederatedRelayItem({
|
||||
dispatchId: dispatch.id,
|
||||
sequence: 1,
|
||||
message: {
|
||||
id: 'relay_first',
|
||||
runId: task.run_id,
|
||||
from: `dispatch:${dispatch.id}`,
|
||||
to: `run:${task.run_id}`,
|
||||
subject: 'First',
|
||||
body: 'Arrived after the gap was rejected',
|
||||
type: 'status',
|
||||
priority: 'normal'
|
||||
},
|
||||
lifecycle: { kind: 'none' }
|
||||
})
|
||||
const recovered = homeDb.importFederatedRelayItem({
|
||||
dispatchId: dispatch.id,
|
||||
sequence: 2,
|
||||
message: {
|
||||
id: 'relay_gap',
|
||||
runId: task.run_id,
|
||||
from: `dispatch:${dispatch.id}`,
|
||||
to: `run:${task.run_id}`,
|
||||
subject: 'Gap',
|
||||
body: 'Out of order',
|
||||
type: 'status',
|
||||
priority: 'normal'
|
||||
},
|
||||
lifecycle: { kind: 'none' }
|
||||
})
|
||||
const duplicate = homeDb.importFederatedRelayItem({
|
||||
dispatchId: dispatch.id,
|
||||
sequence: 2,
|
||||
message: {
|
||||
id: 'relay_gap',
|
||||
runId: task.run_id,
|
||||
from: `dispatch:${dispatch.id}`,
|
||||
to: `run:${task.run_id}`,
|
||||
subject: 'Gap',
|
||||
body: 'Out of order',
|
||||
type: 'status',
|
||||
priority: 'normal'
|
||||
},
|
||||
lifecycle: { kind: 'none' }
|
||||
})
|
||||
|
||||
expect(recovered.duplicate).toBe(false)
|
||||
expect(duplicate.duplicate).toBe(true)
|
||||
expect(homeDb.getFederatedDispatch(dispatch.id)?.to_home_imported_sequence).toBe(2)
|
||||
expect(
|
||||
homeDb
|
||||
.getRunMailboxHistory(task.run_id, 10)
|
||||
.filter((message) => ['relay_first', 'relay_gap'].includes(message.id))
|
||||
).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('restarts relay polling when a federated worker is shown', async () => {
|
||||
const task = createHomeTask()
|
||||
await homeDispatcher.dispatch(startRequest(task.id))
|
||||
const dispatch = homeDb.getDispatchContext(task.id)!
|
||||
const prompt = vi.mocked(workerRuntime.sendTerminalAgentPrompt).mock.calls[0]?.[1] ?? ''
|
||||
const capability = prompt.match(/--dispatch-capability (dcap_[A-Za-z0-9_-]+)/)?.[1]
|
||||
homeRuntime.stopOrchestrationFederationRelay()
|
||||
await workerDispatcher.dispatch({
|
||||
id: 'rpc_restart_status',
|
||||
authToken: 'worker-local-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'restart_status_request',
|
||||
orchestrationCapability: capability,
|
||||
method: 'orchestration.send',
|
||||
params: {
|
||||
from: 'term_windows_worker',
|
||||
subject: 'After home restart',
|
||||
body: 'Relay me after worker-show',
|
||||
type: 'status'
|
||||
}
|
||||
})
|
||||
|
||||
await homeDispatcher.dispatch({
|
||||
id: 'rpc_restart_show',
|
||||
authToken: 'coordinator-token',
|
||||
method: 'orchestration.workerShow',
|
||||
params: { dispatch: dispatch.id }
|
||||
})
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(
|
||||
homeDb
|
||||
.getRunMailboxHistory(task.run_id, 10)
|
||||
.some((message) => message.subject === 'After home restart')
|
||||
).toBe(true)
|
||||
)
|
||||
})
|
||||
|
||||
it('treats a worker runtime ID change as an epoch, not a new server', async () => {
|
||||
const task = createHomeTask()
|
||||
await homeDispatcher.dispatch(startRequest(task.id))
|
||||
const dispatch = homeDb.getDispatchContext(task.id)!
|
||||
const oldEpoch = homeDb.getFederatedDispatch(dispatch.id)?.remote_runtime_epoch
|
||||
restartWorkerRuntime()
|
||||
|
||||
const shown = await homeDispatcher.dispatch({
|
||||
id: 'rpc_worker_restart_show',
|
||||
authToken: 'coordinator-token',
|
||||
method: 'orchestration.workerShow',
|
||||
params: { dispatch: dispatch.id }
|
||||
})
|
||||
|
||||
expect(shown).toMatchObject({
|
||||
ok: true,
|
||||
result: { observation: { status: 'running', exactWorker: true } }
|
||||
})
|
||||
expect(homeDb.getFederatedDispatch(dispatch.id)?.remote_runtime_epoch).not.toBe(oldEpoch)
|
||||
expect(homeDb.getFederatedDispatch(dispatch.id)?.peer_fingerprint).toBe(
|
||||
'windows_peer_fingerprint'
|
||||
)
|
||||
})
|
||||
|
||||
it('stops only the exact remote agent terminal', async () => {
|
||||
const task = createHomeTask()
|
||||
await homeDispatcher.dispatch(startRequest(task.id))
|
||||
const dispatch = homeDb.getDispatchContext(task.id)!
|
||||
|
||||
const stopped = await homeDispatcher.dispatch({
|
||||
id: 'rpc_remote_stop',
|
||||
authToken: 'coordinator-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'request_remote_stop',
|
||||
method: 'orchestration.workerStop',
|
||||
params: { dispatch: dispatch.id }
|
||||
})
|
||||
|
||||
expect(stopped).toMatchObject({
|
||||
ok: true,
|
||||
result: { state: 'stopped', processAction: 'closed_agent_terminal' }
|
||||
})
|
||||
expect(workerRuntime.closeTerminal).toHaveBeenCalledTimes(1)
|
||||
expect(workerRuntime.closeTerminal).toHaveBeenCalledWith('term_windows_worker')
|
||||
expect(homeDb.getTask(task.id)?.status).toBe('blocked')
|
||||
|
||||
vi.mocked(workerRuntime.showTerminal).mockResolvedValue({
|
||||
handle: 'term_windows_worker',
|
||||
worktreeId: 'repo::windows-worktree',
|
||||
connected: false,
|
||||
writable: false
|
||||
} as never)
|
||||
const shown = await homeDispatcher.dispatch({
|
||||
id: 'rpc_remote_show_after_stop',
|
||||
authToken: 'coordinator-token',
|
||||
method: 'orchestration.workerShow',
|
||||
params: { dispatch: dispatch.id }
|
||||
})
|
||||
expect(shown).toMatchObject({
|
||||
ok: true,
|
||||
result: { observation: { status: 'exited', exactWorker: true } }
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects a re-paired server before show or stop effects', async () => {
|
||||
const task = createHomeTask()
|
||||
await homeDispatcher.dispatch(startRequest(task.id))
|
||||
const dispatch = homeDb.getDispatchContext(task.id)!
|
||||
workerPeerFingerprint = 'replacement_windows_peer'
|
||||
|
||||
const shown = await homeDispatcher.dispatch({
|
||||
id: 'rpc_changed_peer_show',
|
||||
authToken: 'coordinator-token',
|
||||
method: 'orchestration.workerShow',
|
||||
params: { dispatch: dispatch.id }
|
||||
})
|
||||
const stopped = await homeDispatcher.dispatch({
|
||||
id: 'rpc_changed_peer_stop',
|
||||
authToken: 'coordinator-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'request_changed_peer_stop',
|
||||
method: 'orchestration.workerStop',
|
||||
params: { dispatch: dispatch.id }
|
||||
})
|
||||
|
||||
expect(shown).toMatchObject({ ok: false, error: { code: 'peer_changed' } })
|
||||
expect(stopped).toMatchObject({ ok: false, error: { code: 'peer_changed' } })
|
||||
expect(homeDb.getWorkerDispatch(dispatch.id)?.state).toBe('ready')
|
||||
expect(workerRuntime.closeTerminal).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('coalesces overlapping relay polls for the same Dispatch', async () => {
|
||||
const task = createHomeTask()
|
||||
await homeDispatcher.dispatch(startRequest(task.id))
|
||||
await homeRuntime.syncOrchestrationFederation()
|
||||
homeRuntime.stopOrchestrationFederationRelay()
|
||||
|
||||
let releasePull!: () => void
|
||||
const blockedPull = new Promise<void>((resolve) => {
|
||||
releasePull = resolve
|
||||
})
|
||||
let pullCount = 0
|
||||
vi.spyOn(homeRuntime, 'callOrchestrationWorkerServer').mockImplementation(
|
||||
async (_selector, method) => {
|
||||
if (method !== 'orchestration.federationPull') {
|
||||
throw new Error(`Unexpected relay method ${method}`)
|
||||
}
|
||||
pullCount += 1
|
||||
await blockedPull
|
||||
return { runtimeEpoch: workerRuntime.getRuntimeId(), items: [] }
|
||||
}
|
||||
)
|
||||
|
||||
const first = homeRuntime.syncOrchestrationFederation()
|
||||
const second = homeRuntime.syncOrchestrationFederation()
|
||||
await vi.waitFor(() => expect(pullCount).toBe(1))
|
||||
releasePull()
|
||||
await Promise.all([first, second])
|
||||
|
||||
expect(pullCount).toBe(1)
|
||||
})
|
||||
|
||||
it('warns once while a federated Dispatch remains unreachable', async () => {
|
||||
const task = createHomeTask()
|
||||
await homeDispatcher.dispatch(startRequest(task.id))
|
||||
await homeRuntime.syncOrchestrationFederation()
|
||||
homeRuntime.stopOrchestrationFederationRelay()
|
||||
vi.spyOn(homeRuntime, 'callOrchestrationWorkerServer').mockRejectedValue(
|
||||
new Error('worker server offline')
|
||||
)
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
|
||||
await homeRuntime.syncOrchestrationFederation()
|
||||
await homeRuntime.syncOrchestrationFederation()
|
||||
|
||||
expect(warn).toHaveBeenCalledTimes(1)
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Federation sync failed'),
|
||||
expect.any(Error)
|
||||
)
|
||||
warn.mockRestore()
|
||||
})
|
||||
|
||||
it('returns stop_unknown when the worker server disconnects after the home fence', async () => {
|
||||
const task = createHomeTask()
|
||||
await homeDispatcher.dispatch(startRequest(task.id))
|
||||
const dispatch = homeDb.getDispatchContext(task.id)!
|
||||
vi.spyOn(homeRuntime, 'callOrchestrationWorkerServer').mockRejectedValueOnce(
|
||||
new Error('connection lost')
|
||||
)
|
||||
|
||||
const stopped = await homeDispatcher.dispatch({
|
||||
id: 'rpc_disconnected_stop',
|
||||
authToken: 'coordinator-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'request_disconnected_stop',
|
||||
method: 'orchestration.workerStop',
|
||||
params: { dispatch: dispatch.id }
|
||||
})
|
||||
|
||||
expect(stopped).toMatchObject({
|
||||
ok: true,
|
||||
result: { state: 'stop_unknown', processAction: 'unknown' }
|
||||
})
|
||||
expect(homeDb.getTask(task.id)?.status).toBe('blocked')
|
||||
expect(workerRuntime.closeTerminal).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('never reads or closes a same-looking replacement process', async () => {
|
||||
const task = createHomeTask()
|
||||
await homeDispatcher.dispatch(startRequest(task.id))
|
||||
const dispatch = homeDb.getDispatchContext(task.id)!
|
||||
vi.mocked(workerRuntime.getTerminalProcessIncarnation).mockReturnValue(
|
||||
'windows_runtime:pty:replacement'
|
||||
)
|
||||
|
||||
const read = await homeDispatcher.dispatch({
|
||||
id: 'rpc_replacement_read',
|
||||
authToken: 'coordinator-token',
|
||||
method: 'orchestration.workerRead',
|
||||
params: { dispatch: dispatch.id }
|
||||
})
|
||||
const stopped = await homeDispatcher.dispatch({
|
||||
id: 'rpc_replacement_stop',
|
||||
authToken: 'coordinator-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'request_replacement_stop',
|
||||
method: 'orchestration.workerStop',
|
||||
params: { dispatch: dispatch.id }
|
||||
})
|
||||
|
||||
expect(read).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'worker_identity_changed' }
|
||||
})
|
||||
expect(stopped).toMatchObject({
|
||||
ok: true,
|
||||
result: { state: 'stop_unknown', processAction: 'none' }
|
||||
})
|
||||
expect(workerRuntime.closeTerminal).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,297 @@
|
||||
import { isTuiAgent } from '../../../../shared/tui-agent-config'
|
||||
import type { TuiAgent } from '../../../../shared/types'
|
||||
import { buildDispatchPreamble } from '../../orchestration/preamble'
|
||||
import { OrchestrationError } from '../../orchestration/orchestration-error'
|
||||
import { defineMethod, type RpcMethod } from '../core'
|
||||
import { assertOrchestrationWorktreeCreationSupported } from './orchestration-folder-worktree-placement'
|
||||
import {
|
||||
appendFederationSetupEffect,
|
||||
appendFederationTerminalEffects,
|
||||
type FederationEffect
|
||||
} from './orchestration-federation-effects'
|
||||
import type { WorkerSetupReceipt } from './orchestration-worker-topology'
|
||||
import {
|
||||
monitorFederatedSetup,
|
||||
persistFederatedReadinessStage,
|
||||
persistFederatedSetupSpawnFailure,
|
||||
persistFederatedSetupWaitOutcome
|
||||
} from './orchestration-federation-setup'
|
||||
import { FederationAttachStartParams } from './orchestration-federation-start-schema'
|
||||
import { failFederatedAttachmentWithReceipt } from './orchestration-federation-start-receipt'
|
||||
|
||||
export const ORCHESTRATION_FEDERATION_ATTACH_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.federationAttachStart',
|
||||
params: FederationAttachStartParams,
|
||||
handler: async (params, { runtime, orchestrationMutation }) => {
|
||||
if (!orchestrationMutation) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'Federated worker attachment requires a durable retry request.'
|
||||
)
|
||||
}
|
||||
if (params.worktree === 'current' || params.worktree === 'new-child') {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'A remote worker requires an exact existing worktree or new-top-level.'
|
||||
)
|
||||
}
|
||||
const createsWorktree = params.worktree === 'new-top-level'
|
||||
if (createsWorktree && (!params.name || !params.repo)) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'A remote new-top-level worktree requires --name and an explicit --repo.'
|
||||
)
|
||||
}
|
||||
if (createsWorktree && params.terminal) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'--terminal cannot combine with remote new-worktree creation.'
|
||||
)
|
||||
}
|
||||
if (
|
||||
!createsWorktree &&
|
||||
(params.name || params.repo || params.baseBranch || params.setup || params.setupSource)
|
||||
) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'Creation and setup options apply only to remote new-top-level worktrees.'
|
||||
)
|
||||
}
|
||||
if (params.terminal && params.agent) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'--terminal reuses an existing agent and cannot combine with --agent.'
|
||||
)
|
||||
}
|
||||
const agent = params.agent
|
||||
if (!params.terminal && (!agent || !isTuiAgent(agent))) {
|
||||
throw new OrchestrationError(
|
||||
'agent_unconfigured',
|
||||
'A configured --agent is required when federated worker-start creates a terminal.'
|
||||
)
|
||||
}
|
||||
if (agent) {
|
||||
runtime.validateOrchestrationAgentLauncher(agent as TuiAgent)
|
||||
}
|
||||
if (createsWorktree) {
|
||||
await assertOrchestrationWorktreeCreationSupported({
|
||||
runtime,
|
||||
repoSelector: params.repo as string,
|
||||
existingPlacement: 'an exact existing folder workspace'
|
||||
})
|
||||
}
|
||||
|
||||
const db = runtime.getOrchestrationDb()
|
||||
db.createRemoteDispatchAttachment({
|
||||
dispatchId: params.dispatchId,
|
||||
taskId: params.taskId,
|
||||
homePeerFingerprint: orchestrationMutation.callerFingerprint,
|
||||
protocolVersion: params.protocolVersion,
|
||||
runtimeEpoch: runtime.getRuntimeId(),
|
||||
mutationReceipt: orchestrationMutation
|
||||
})
|
||||
const effects: FederationEffect[] = []
|
||||
let failedStage = createsWorktree ? 'worktree_create' : 'worktree_resolve'
|
||||
let worktree
|
||||
let terminalHandle = params.terminal
|
||||
const setupSource = createsWorktree
|
||||
? (params.setupSource ?? (params.setup ? 'explicit_request' : 'orchestration_default'))
|
||||
: 'existing_worktree'
|
||||
let setup: WorkerSetupReceipt = {
|
||||
requested: createsWorktree ? (params.setup ?? 'run') : 'not_applicable',
|
||||
effective: createsWorktree ? (params.setup ?? 'run') : 'not_applicable',
|
||||
source: setupSource,
|
||||
hookFound: false,
|
||||
startupPolicy: 'start-immediately',
|
||||
state: createsWorktree ? 'not_configured' : 'not_applicable'
|
||||
}
|
||||
try {
|
||||
if (createsWorktree) {
|
||||
db.recordRemoteAttachmentStage({
|
||||
dispatchId: params.dispatchId,
|
||||
stage: 'worktree_creating'
|
||||
})
|
||||
const setupDecision = params.setup ?? 'run'
|
||||
const created = await runtime.createManagedWorktree({
|
||||
repoSelector: params.repo as string,
|
||||
name: params.name as string,
|
||||
baseBranch: params.baseBranch,
|
||||
displayName: params.displayName,
|
||||
comment: params.comment,
|
||||
runHooks: setupDecision === 'run',
|
||||
setupDecision,
|
||||
awaitTerminalProvisioning: true,
|
||||
observeSetupCompletion: true,
|
||||
createdWithAgent: agent as TuiAgent,
|
||||
startupAgent: agent as TuiAgent,
|
||||
activate: false,
|
||||
lineage: { noParent: true }
|
||||
})
|
||||
worktree = created.worktree
|
||||
terminalHandle = created.startupTerminal?.handle
|
||||
effects.push({
|
||||
kind: 'worktree',
|
||||
action: 'created_top_level',
|
||||
id: created.worktree.id
|
||||
})
|
||||
setup = {
|
||||
requested: setupDecision,
|
||||
effective: setupDecision,
|
||||
source: setupSource,
|
||||
hookFound: created.setupReceipt?.hookFound ?? false,
|
||||
startupPolicy: created.setupReceipt?.startupPolicy ?? 'start-immediately',
|
||||
state: created.setupReceipt?.state ?? 'not_configured'
|
||||
}
|
||||
if (!terminalHandle) {
|
||||
throw new Error(
|
||||
created.warning ?? 'Agent-first worktree creation returned no terminal.'
|
||||
)
|
||||
}
|
||||
const listed = await runtime.listTerminals(`id:${created.worktree.id}`)
|
||||
appendFederationTerminalEffects(
|
||||
effects,
|
||||
listed.terminals,
|
||||
terminalHandle,
|
||||
created.setupReceipt?.terminalHandle
|
||||
)
|
||||
appendFederationSetupEffect(effects, setup)
|
||||
} else {
|
||||
worktree = await runtime.showManagedWorktree(params.worktree).catch(() => {
|
||||
throw new OrchestrationError(
|
||||
'worktree_not_found_on_server',
|
||||
`Worktree ${params.worktree} was not found on the selected worker server.`
|
||||
)
|
||||
})
|
||||
effects.push(
|
||||
{ kind: 'worktree', action: 'reused', id: worktree.id },
|
||||
{ kind: 'setup', action: 'not_applicable', state: 'not_applicable' }
|
||||
)
|
||||
if (terminalHandle) {
|
||||
const terminal = await runtime.showTerminal(terminalHandle)
|
||||
if (terminal.worktreeId !== worktree.id) {
|
||||
throw new OrchestrationError(
|
||||
'terminal_worktree_mismatch',
|
||||
`Terminal ${terminalHandle} does not belong to worktree ${worktree.id}.`
|
||||
)
|
||||
}
|
||||
if (!(await runtime.isTerminalRunningAgent(terminalHandle))) {
|
||||
throw new OrchestrationError(
|
||||
'agent_unconfigured',
|
||||
`Terminal ${terminalHandle} is not running a recognized agent.`
|
||||
)
|
||||
}
|
||||
effects.push({
|
||||
kind: 'terminal',
|
||||
role: 'agent',
|
||||
action: 'reused',
|
||||
id: terminalHandle
|
||||
})
|
||||
} else {
|
||||
failedStage = 'terminal_create'
|
||||
const terminal = await runtime.createTerminal(`id:${worktree.id}`, {
|
||||
command: agent,
|
||||
title: `worker-${params.taskId}`,
|
||||
presentation: 'background'
|
||||
})
|
||||
terminalHandle = terminal.handle
|
||||
effects.push({
|
||||
kind: 'terminal',
|
||||
role: 'agent',
|
||||
action: 'created',
|
||||
id: terminal.handle
|
||||
})
|
||||
}
|
||||
}
|
||||
if (!worktree || !terminalHandle) {
|
||||
throw new Error('Federated worker topology did not resolve.')
|
||||
}
|
||||
const setupStage = {
|
||||
db,
|
||||
dispatchId: params.dispatchId,
|
||||
worktreeId: worktree.id,
|
||||
terminalHandle,
|
||||
setup,
|
||||
effects
|
||||
}
|
||||
if (persistFederatedSetupSpawnFailure(setupStage)) {
|
||||
failedStage = 'setup_start'
|
||||
throw new Error('Setup terminal failed to start before the gated agent launch.')
|
||||
}
|
||||
persistFederatedReadinessStage(setupStage)
|
||||
failedStage = 'agent_readiness'
|
||||
const wait = await runtime.waitForTerminal(terminalHandle, {
|
||||
condition: 'tui-idle',
|
||||
timeoutMs: params.timeoutMs ?? 60_000
|
||||
})
|
||||
persistFederatedSetupWaitOutcome({ ...setupStage, wait })
|
||||
if (!wait.satisfied) {
|
||||
if (setup.state === 'failed') {
|
||||
failedStage = 'setup_wait'
|
||||
}
|
||||
throw new Error(
|
||||
wait.blockedReason
|
||||
? `Agent startup blocked: ${wait.blockedReason}`
|
||||
: `Agent did not become ready (${wait.status}).`
|
||||
)
|
||||
}
|
||||
const paneKey = runtime.getTerminalPaneKey(terminalHandle)
|
||||
const processIncarnation = runtime.getTerminalProcessIncarnation(terminalHandle)
|
||||
if (!paneKey || !processIncarnation) {
|
||||
throw new Error('stable_pane_required')
|
||||
}
|
||||
const capability = db.prepareRemoteAttachmentAuthority({
|
||||
dispatchId: params.dispatchId,
|
||||
paneKey,
|
||||
processIncarnation,
|
||||
worktreeId: worktree.id,
|
||||
terminalHandle,
|
||||
setupState: setup.state,
|
||||
effects
|
||||
})
|
||||
failedStage = 'dispatch_input'
|
||||
await runtime.sendTerminalAgentPrompt(
|
||||
terminalHandle,
|
||||
buildDispatchPreamble({
|
||||
taskId: params.taskId,
|
||||
dispatchId: params.dispatchId,
|
||||
taskSpec: params.taskSpec,
|
||||
coordinatorHandle: 'Run home (relayed by Orca)',
|
||||
workerHandle: terminalHandle,
|
||||
dispatchCapability: capability,
|
||||
devMode: params.devMode,
|
||||
cliCommand: runtime.getTerminalOrchestrationCliCommand(terminalHandle)
|
||||
})
|
||||
)
|
||||
effects.push({
|
||||
kind: 'dispatch_input',
|
||||
role: 'agent',
|
||||
id: terminalHandle,
|
||||
state: 'accepted'
|
||||
})
|
||||
const attachment = db.markRemoteAttachmentReady(params.dispatchId, effects)
|
||||
monitorFederatedSetup({ ...setupStage, runtime })
|
||||
return {
|
||||
dispatchId: params.dispatchId,
|
||||
state: attachment.state,
|
||||
stage: attachment.stage,
|
||||
runtimeEpoch: runtime.getRuntimeId(),
|
||||
worktreeId: worktree.id,
|
||||
terminalHandle,
|
||||
setup,
|
||||
effects,
|
||||
residualResources: []
|
||||
}
|
||||
} catch (error) {
|
||||
return failFederatedAttachmentWithReceipt({
|
||||
db,
|
||||
dispatchId: params.dispatchId,
|
||||
runtimeEpoch: runtime.getRuntimeId(),
|
||||
failedStage,
|
||||
error,
|
||||
setup
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
]
|
||||
@@ -0,0 +1,17 @@
|
||||
import { isFolderRepo } from '../../../../shared/repo-kind'
|
||||
import type { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationError } from '../../orchestration/orchestration-error'
|
||||
|
||||
export async function assertOrchestrationWorktreeCreationSupported(args: {
|
||||
runtime: OrcaRuntimeService
|
||||
repoSelector: string
|
||||
existingPlacement: string
|
||||
}): Promise<void> {
|
||||
if (!isFolderRepo(await args.runtime.showRepo(args.repoSelector))) {
|
||||
return
|
||||
}
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
`Folder projects cannot create orchestration worktrees; use ${args.existingPlacement}.`
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY,
|
||||
ORCHESTRATION_FEDERATION_RUNTIME_CAPABILITY
|
||||
} from '../../../../shared/protocol-version'
|
||||
import { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationDb } from '../../orchestration/db'
|
||||
import { RpcDispatcher } from '../dispatcher'
|
||||
import { ORCHESTRATION_METHODS } from './orchestration'
|
||||
import { startFederatedWorker } from './orchestration-federated-worker-start'
|
||||
|
||||
describe('orchestration migration behavior', () => {
|
||||
const databases: OrchestrationDb[] = []
|
||||
|
||||
afterEach(() => {
|
||||
for (const database of databases.splice(0)) {
|
||||
database.close()
|
||||
}
|
||||
})
|
||||
|
||||
function createRuntime(): { db: OrchestrationDb; runtime: OrcaRuntimeService } {
|
||||
const db = new OrchestrationDb(':memory:')
|
||||
const runtime = new OrcaRuntimeService()
|
||||
runtime.setOrchestrationDb(db)
|
||||
databases.push(db)
|
||||
return { db, runtime }
|
||||
}
|
||||
|
||||
it('lists an explicitly selected legacy Run without binding or mutation', async () => {
|
||||
const { db, runtime } = createRuntime()
|
||||
const task = db.createTask({ spec: 'pre-upgrade work' })
|
||||
const taskList = ORCHESTRATION_METHODS.find(
|
||||
(method) => method.name === 'orchestration.taskList'
|
||||
)!
|
||||
|
||||
const listed = (await taskList.handler(taskList.params!.parse({ run: 'run_legacy_local' }), {
|
||||
runtime
|
||||
})) as {
|
||||
runId: string
|
||||
legacyReadOnly: boolean
|
||||
tasks: { id: string }[]
|
||||
}
|
||||
|
||||
expect(listed).toMatchObject({
|
||||
runId: 'run_legacy_local',
|
||||
legacyReadOnly: true,
|
||||
tasks: [{ id: task.id }]
|
||||
})
|
||||
expect(db.getTask(task.id)?.status).toBe('ready')
|
||||
})
|
||||
|
||||
it('rejects a pre-contract worker_done before message or lifecycle mutation', async () => {
|
||||
const { db, runtime } = createRuntime()
|
||||
const run = db.createRun({
|
||||
objective: 'legacy worker',
|
||||
coordinatorHandle: 'term_coord',
|
||||
coordinatorPaneKey: 'tab_coord:leaf_coord'
|
||||
})
|
||||
const task = db.createTask({ spec: 'legacy worker', runId: run.id })
|
||||
const dispatch = db.createDispatchContext(task.id, 'term_worker', 'tab_worker:leaf_worker')
|
||||
const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS })
|
||||
|
||||
const response = await dispatcher.dispatch({
|
||||
id: 'legacy_worker_done',
|
||||
authToken: 'worker-token',
|
||||
method: 'orchestration.send',
|
||||
params: {
|
||||
from: 'term_worker',
|
||||
subject: 'done',
|
||||
type: 'worker_done',
|
||||
payload: JSON.stringify({
|
||||
taskId: task.id,
|
||||
dispatchId: dispatch.id,
|
||||
outcome: 'succeeded'
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
expect(response).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
code: 'orchestration_migration_required',
|
||||
data: { effectsApplied: false }
|
||||
}
|
||||
})
|
||||
expect(db.getInbox(100)).toHaveLength(0)
|
||||
expect(db.getTask(task.id)?.status).toBe('dispatched')
|
||||
expect(db.getDispatchContextById(dispatch.id)?.status).toBe('dispatched')
|
||||
})
|
||||
|
||||
it('rejects a connected server missing the contract before home or remote effects', async () => {
|
||||
const { db, runtime } = createRuntime()
|
||||
const run = db.createRun({
|
||||
objective: 'mixed-version worker',
|
||||
coordinatorHandle: 'term_coord',
|
||||
coordinatorPaneKey: 'tab_coord:leaf_coord'
|
||||
})
|
||||
const task = db.createTask({ spec: 'remote work', runId: run.id })
|
||||
vi.spyOn(runtime, 'resolveOrchestrationWorkerServer').mockReturnValue({
|
||||
environmentId: 'environment_windows',
|
||||
name: 'windows',
|
||||
peerFingerprint: 'windows_peer'
|
||||
})
|
||||
vi.spyOn(runtime, 'callOrchestrationWorkerServer').mockResolvedValue({
|
||||
capabilities: [ORCHESTRATION_FEDERATION_RUNTIME_CAPABILITY]
|
||||
})
|
||||
|
||||
await expect(
|
||||
startFederatedWorker({
|
||||
params: {
|
||||
task: task.id,
|
||||
from: 'term_coord',
|
||||
on: 'windows',
|
||||
worktree: 'new-top-level',
|
||||
repo: 'id:windows-repo',
|
||||
name: 'remote-work',
|
||||
agent: 'codex'
|
||||
},
|
||||
runtime,
|
||||
db,
|
||||
runId: run.id,
|
||||
task,
|
||||
orchestrationMutation: {
|
||||
callerFingerprint: 'caller',
|
||||
requestId: 'remote_start',
|
||||
method: 'orchestration.workerStart',
|
||||
payloadHash: 'payload'
|
||||
}
|
||||
})
|
||||
).rejects.toMatchObject({
|
||||
code: 'orchestration_migration_required',
|
||||
data: { reason: 'runtime_capability_missing', effectsApplied: false }
|
||||
})
|
||||
expect(db.getTask(task.id)?.status).toBe('ready')
|
||||
expect(db.getDispatchContext(task.id)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects a connected server missing federation support before Task mutation', async () => {
|
||||
const { db, runtime } = createRuntime()
|
||||
const run = db.createRun({
|
||||
objective: 'unsupported worker',
|
||||
coordinatorHandle: 'term_coord',
|
||||
coordinatorPaneKey: 'tab_coord:leaf_coord'
|
||||
})
|
||||
const task = db.createTask({ spec: 'remote work', runId: run.id })
|
||||
vi.spyOn(runtime, 'resolveOrchestrationWorkerServer').mockReturnValue({
|
||||
environmentId: 'environment_windows',
|
||||
name: 'windows',
|
||||
peerFingerprint: 'windows_peer'
|
||||
})
|
||||
vi.spyOn(runtime, 'callOrchestrationWorkerServer').mockResolvedValue({
|
||||
capabilities: [ORCHESTRATION_CONTRACT_RUNTIME_CAPABILITY]
|
||||
})
|
||||
|
||||
await expect(
|
||||
startFederatedWorker({
|
||||
params: {
|
||||
task: task.id,
|
||||
from: 'term_coord',
|
||||
on: 'windows',
|
||||
worktree: 'new-top-level',
|
||||
repo: 'id:windows-repo',
|
||||
name: 'remote-work',
|
||||
agent: 'codex'
|
||||
},
|
||||
runtime,
|
||||
db,
|
||||
runId: run.id,
|
||||
task,
|
||||
orchestrationMutation: {
|
||||
callerFingerprint: 'caller',
|
||||
requestId: 'remote_start',
|
||||
method: 'orchestration.workerStart',
|
||||
payloadHash: 'payload'
|
||||
}
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'capability_unsupported' })
|
||||
expect(db.getTask(task.id)?.status).toBe('ready')
|
||||
expect(db.getDispatchContext(task.id)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,100 @@
|
||||
import { z } from 'zod'
|
||||
import { defineMethod, type RpcMethod } from '../core'
|
||||
import { OptionalString, requiredString } from '../schemas'
|
||||
import type { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationError } from '../../orchestration/orchestration-error'
|
||||
|
||||
const RunCreateParams = z.object({
|
||||
objective: requiredString('Missing --objective'),
|
||||
from: requiredString('Missing coordinator terminal')
|
||||
})
|
||||
|
||||
const RunUseParams = z.object({
|
||||
id: requiredString('Missing --id'),
|
||||
from: requiredString('Missing coordinator terminal')
|
||||
})
|
||||
|
||||
const RunCurrentParams = z.object({ from: requiredString('Missing coordinator terminal') })
|
||||
const RunListParams = z.object({})
|
||||
const RunShowParams = z.object({ id: requiredString('Missing --id'), from: OptionalString })
|
||||
|
||||
function requireCallerPane(runtime: OrcaRuntimeService, handle: string): string {
|
||||
const paneKey = runtime.getTerminalPaneKey(handle)
|
||||
if (!paneKey) {
|
||||
throw new OrchestrationError(
|
||||
'stable_pane_required',
|
||||
'The coordinator terminal has no stable pane identity. Run this command inside a live Orca terminal.'
|
||||
)
|
||||
}
|
||||
return paneKey
|
||||
}
|
||||
|
||||
export const ORCHESTRATION_RUN_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.runCreate',
|
||||
params: RunCreateParams,
|
||||
handler: (params, { runtime }) => {
|
||||
const paneKey = requireCallerPane(runtime, params.from)
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const priorRun = db.getCurrentRunForPane(paneKey)
|
||||
const run = db.createRun({
|
||||
objective: params.objective,
|
||||
coordinatorHandle: params.from,
|
||||
coordinatorPaneKey: paneKey
|
||||
})
|
||||
if (priorRun) {
|
||||
runtime.cancelMessageWaiters(`run:${priorRun.id}`)
|
||||
}
|
||||
return { run, binding: { consumerGeneration: run.consumer_generation } }
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'orchestration.runUse',
|
||||
params: RunUseParams,
|
||||
handler: (params, { runtime }) => {
|
||||
const paneKey = requireCallerPane(runtime, params.from)
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const priorRun = db.getCurrentRunForPane(paneKey)
|
||||
const run = db.bindRun({
|
||||
runId: params.id,
|
||||
coordinatorHandle: params.from,
|
||||
coordinatorPaneKey: paneKey
|
||||
})
|
||||
if (!run) {
|
||||
throw new OrchestrationError(
|
||||
'run_not_found',
|
||||
`Run ${params.id} was not found or is inspect-only.`
|
||||
)
|
||||
}
|
||||
runtime.cancelMessageWaiters(`run:${params.id}`)
|
||||
if (priorRun && priorRun.id !== params.id) {
|
||||
runtime.cancelMessageWaiters(`run:${priorRun.id}`)
|
||||
}
|
||||
return { run, binding: { consumerGeneration: run.consumer_generation } }
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'orchestration.runCurrent',
|
||||
params: RunCurrentParams,
|
||||
handler: (params, { runtime }) => {
|
||||
const paneKey = requireCallerPane(runtime, params.from)
|
||||
return { run: runtime.getOrchestrationDb().getCurrentRunForPane(paneKey) ?? null }
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'orchestration.runList',
|
||||
params: RunListParams,
|
||||
handler: (_params, { runtime }) => ({ runs: runtime.getOrchestrationDb().listRuns() })
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'orchestration.runShow',
|
||||
params: RunShowParams,
|
||||
handler: (params, { runtime }) => {
|
||||
const run = runtime.getOrchestrationDb().getRun(params.id)
|
||||
if (!run) {
|
||||
throw new OrchestrationError('run_not_found', `Run ${params.id} was not found.`)
|
||||
}
|
||||
return { run }
|
||||
}
|
||||
})
|
||||
]
|
||||
@@ -0,0 +1,294 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
ORCHESTRATION_WORKER_READ_SOURCES,
|
||||
type OrchestrationWorkerReadResult
|
||||
} from '../../../../shared/orchestration-worker-output'
|
||||
import type { RuntimeTerminalRead } from '../../../../shared/runtime-types'
|
||||
import { OrchestrationError } from '../../orchestration/orchestration-error'
|
||||
import { syncFederatedDispatch } from '../../orchestration/federation-sync'
|
||||
import {
|
||||
createWorkerOutputSourceIdentity,
|
||||
decodeWorkerOutputCursor,
|
||||
encodeWorkerOutputCursor
|
||||
} from '../../orchestration/worker-output-cursor'
|
||||
import { defineMethod, type RpcMethod } from '../core'
|
||||
import { OptionalFiniteNumber, requiredString } from '../schemas'
|
||||
import {
|
||||
callFederatedWorkerShow,
|
||||
exposeWorker,
|
||||
inspectWorkerTerminal,
|
||||
resolvePinnedFederatedServer
|
||||
} from './orchestration-worker-observation'
|
||||
import { readExactWorkerOutput } from './orchestration-worker-output'
|
||||
|
||||
const WorkerDispatchParams = z.object({ dispatch: requiredString('Missing --dispatch') })
|
||||
const WorkerReadParams = WorkerDispatchParams.extend({
|
||||
cursor: z.union([z.number().int().nonnegative(), z.string().min(1).max(2_048)]).optional(),
|
||||
limit: OptionalFiniteNumber,
|
||||
source: z.enum(ORCHESTRATION_WORKER_READ_SOURCES).optional()
|
||||
})
|
||||
|
||||
export const ORCHESTRATION_WORKER_CONTROL_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.workerShow',
|
||||
params: WorkerDispatchParams,
|
||||
handler: async (params, { runtime }) => {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const dispatch = db.getDispatchContextById(params.dispatch)
|
||||
let worker = db.getWorkerDispatch(params.dispatch)
|
||||
if (!dispatch || !worker) {
|
||||
throw new OrchestrationError(
|
||||
'dispatch_not_found',
|
||||
`Worker Dispatch ${params.dispatch} was not found.`
|
||||
)
|
||||
}
|
||||
const federated = db.getFederatedDispatch(params.dispatch)
|
||||
if (federated) {
|
||||
const server = resolvePinnedFederatedServer(runtime, federated)
|
||||
runtime.ensureOrchestrationFederationRelay(dispatch.run_id)
|
||||
const remote = await callFederatedWorkerShow(runtime, federated)
|
||||
const attachment = remote.attachment
|
||||
worker = db.updateWorkerSetupEvidence({
|
||||
dispatchId: params.dispatch,
|
||||
setupState: attachment.setup_state,
|
||||
effects: attachment.effects
|
||||
}).worker
|
||||
if (
|
||||
attachment.state === 'succeeded' ||
|
||||
(attachment.state === 'failed' && attachment.stage === 'worker_report_queued')
|
||||
) {
|
||||
await syncFederatedDispatch(runtime, params.dispatch).catch(() => undefined)
|
||||
} else if (
|
||||
attachment.state === 'stopped' &&
|
||||
['stopping', 'stop_unknown'].includes(worker.state)
|
||||
) {
|
||||
worker = db.reconcileFederatedWorkerStop(params.dispatch)
|
||||
} else if (['ready', 'failed', 'stopped', 'start_unknown'].includes(attachment.state)) {
|
||||
worker = db.reconcileFederatedWorkerStart({
|
||||
dispatchId: params.dispatch,
|
||||
state: attachment.state as 'ready' | 'failed' | 'stopped' | 'start_unknown',
|
||||
stage: attachment.stage,
|
||||
lastError: attachment.last_error,
|
||||
worktreeId: attachment.worktree_id,
|
||||
terminalHandle: attachment.terminal_handle,
|
||||
setupState: attachment.setup_state,
|
||||
effects: attachment.effects,
|
||||
residualResources: attachment.residualResources
|
||||
})
|
||||
if (
|
||||
attachment.state === 'ready' &&
|
||||
attachment.worktree_id &&
|
||||
attachment.terminal_handle
|
||||
) {
|
||||
db.updateFederatedDispatchResources({
|
||||
dispatchId: params.dispatch,
|
||||
remoteRuntimeEpoch: remote.runtimeEpoch,
|
||||
worktreeId: attachment.worktree_id,
|
||||
terminalHandle: attachment.terminal_handle
|
||||
})
|
||||
}
|
||||
}
|
||||
worker = db.getWorkerDispatch(params.dispatch)
|
||||
if (!worker) {
|
||||
throw new OrchestrationError(
|
||||
'dispatch_not_found',
|
||||
`Worker Dispatch ${params.dispatch} was not found after remote reconciliation.`
|
||||
)
|
||||
}
|
||||
return {
|
||||
dispatch: db.getDispatchContextById(params.dispatch),
|
||||
worker: exposeWorker(worker),
|
||||
server: { environmentId: server.environmentId, name: server.name },
|
||||
remoteRuntimeEpoch: remote.runtimeEpoch,
|
||||
terminal: remote.terminal,
|
||||
observation: remote.observation
|
||||
}
|
||||
}
|
||||
if (worker.runtime_epoch && worker.runtime_epoch !== runtime.getRuntimeId()) {
|
||||
if (worker.state === 'starting') {
|
||||
worker = db.markWorkerStartUnknown(
|
||||
params.dispatch,
|
||||
worker.stage,
|
||||
'The runtime restarted before worker-start reached a terminal receipt.'
|
||||
)
|
||||
} else if (worker.state === 'stopping') {
|
||||
worker = db.markWorkerStopUnknown(
|
||||
params.dispatch,
|
||||
'The runtime restarted before worker-stop reached a terminal receipt.'
|
||||
)
|
||||
}
|
||||
}
|
||||
const observation = await inspectWorkerTerminal(runtime, db, params.dispatch)
|
||||
return {
|
||||
dispatch,
|
||||
worker: exposeWorker(worker),
|
||||
terminal: observation.exact ? observation.terminal : null,
|
||||
observation: { status: observation.status, exactWorker: observation.exact }
|
||||
}
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'orchestration.workerRead',
|
||||
params: WorkerReadParams,
|
||||
handler: async (params, { runtime }) => {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const federated = db.getFederatedDispatch(params.dispatch)
|
||||
if (federated) {
|
||||
const server = resolvePinnedFederatedServer(runtime, federated)
|
||||
try {
|
||||
const remote = (await runtime.callOrchestrationWorkerServer(
|
||||
server.environmentId,
|
||||
'orchestration.federationReadOutput',
|
||||
{
|
||||
dispatchId: params.dispatch,
|
||||
cursor: params.cursor,
|
||||
limit: params.limit,
|
||||
source: params.source
|
||||
},
|
||||
15_000
|
||||
)) as { runtimeEpoch: string; output: OrchestrationWorkerReadResult }
|
||||
return {
|
||||
...remote.output,
|
||||
server: { environmentId: server.environmentId, name: server.name },
|
||||
remoteRuntimeEpoch: remote.runtimeEpoch
|
||||
}
|
||||
} catch (error) {
|
||||
if (!(error instanceof OrchestrationError) || error.code !== 'method_not_found') {
|
||||
throw error
|
||||
}
|
||||
return readLegacyFederatedTerminal({
|
||||
runtime,
|
||||
server,
|
||||
federated,
|
||||
workerState: db.getWorkerDispatch(params.dispatch)?.state ?? 'unknown',
|
||||
dispatchId: params.dispatch,
|
||||
source: params.source,
|
||||
cursor: params.cursor,
|
||||
limit: params.limit
|
||||
})
|
||||
}
|
||||
}
|
||||
const worker = db.getWorkerDispatch(params.dispatch)
|
||||
if (!worker?.agent_terminal_handle) {
|
||||
throw new OrchestrationError(
|
||||
'dispatch_not_found',
|
||||
`Worker Dispatch ${params.dispatch} has no agent terminal.`
|
||||
)
|
||||
}
|
||||
const observation = await inspectWorkerTerminal(runtime, db, params.dispatch)
|
||||
if (!observation.exact) {
|
||||
throw new OrchestrationError(
|
||||
'worker_identity_changed',
|
||||
`Worker Dispatch ${params.dispatch} no longer resolves to its exact process.`
|
||||
)
|
||||
}
|
||||
const output = await readExactWorkerOutput({
|
||||
runtime,
|
||||
dispatchId: params.dispatch,
|
||||
terminalHandle: worker.agent_terminal_handle,
|
||||
workerState: worker.state,
|
||||
terminalStatus: observation.status === 'exited' ? 'exited' : 'running',
|
||||
attachedAt: worker.created_at,
|
||||
source: params.source,
|
||||
cursor: params.cursor,
|
||||
limit: params.limit
|
||||
})
|
||||
const afterRead = await inspectWorkerTerminal(runtime, db, params.dispatch)
|
||||
if (!afterRead.exact) {
|
||||
throw new OrchestrationError(
|
||||
'worker_identity_changed',
|
||||
`Worker Dispatch ${params.dispatch} changed process while output was read.`
|
||||
)
|
||||
}
|
||||
return output
|
||||
}
|
||||
}),
|
||||
defineMethod({
|
||||
name: 'orchestration.workerAbandon',
|
||||
params: WorkerDispatchParams,
|
||||
handler: (params, { runtime }) => {
|
||||
const abandoned = runtime.getOrchestrationDb().abandonWorkerDispatch(params.dispatch)
|
||||
const worker = abandoned.worker
|
||||
if (abandoned.disposition === 'abandoned') {
|
||||
runtime.notifyMessageArrived(`dispatch:${params.dispatch}`, 'status')
|
||||
}
|
||||
return {
|
||||
dispatchId: params.dispatch,
|
||||
state: worker.state,
|
||||
alreadySettled: abandoned.disposition !== 'abandoned',
|
||||
stale: abandoned.disposition === 'stale',
|
||||
processAction: 'none',
|
||||
warning:
|
||||
abandoned.disposition === 'stale'
|
||||
? 'The Dispatch is no longer current; no state or process changed.'
|
||||
: 'Possibly-live resources were retained; no process was stopped or deleted.',
|
||||
residualResources: JSON.parse(worker.residual_resources) as unknown[]
|
||||
}
|
||||
}
|
||||
})
|
||||
]
|
||||
|
||||
async function readLegacyFederatedTerminal(args: {
|
||||
runtime: Parameters<typeof resolvePinnedFederatedServer>[0]
|
||||
server: ReturnType<typeof resolvePinnedFederatedServer>
|
||||
federated: Parameters<typeof resolvePinnedFederatedServer>[1]
|
||||
workerState: string
|
||||
dispatchId: string
|
||||
source: (typeof ORCHESTRATION_WORKER_READ_SOURCES)[number] | undefined
|
||||
cursor: string | number | undefined
|
||||
limit: number | undefined
|
||||
}) {
|
||||
const cursor = decodeWorkerOutputCursor(args.cursor, args.dispatchId)
|
||||
if (args.source === 'transcript' || cursor?.source === 'transcript') {
|
||||
throw new OrchestrationError(
|
||||
'transcript_required',
|
||||
`Connected server ${args.server.name} does not support structured worker output.`,
|
||||
{ reason: 'remote_capability_unavailable' }
|
||||
)
|
||||
}
|
||||
const remote = (await args.runtime.callOrchestrationWorkerServer(
|
||||
args.server.environmentId,
|
||||
'orchestration.federationRead',
|
||||
{
|
||||
dispatchId: args.dispatchId,
|
||||
cursor: cursor?.source === 'terminal' ? cursor.position : undefined,
|
||||
limit: args.limit
|
||||
},
|
||||
15_000
|
||||
)) as { runtimeEpoch: string; terminal: RuntimeTerminalRead }
|
||||
const sourceIdentity = createWorkerOutputSourceIdentity([
|
||||
'legacy-remote-terminal',
|
||||
args.federated.peer_fingerprint,
|
||||
args.dispatchId,
|
||||
remote.runtimeEpoch
|
||||
])
|
||||
if (
|
||||
cursor?.source === 'terminal' &&
|
||||
cursor.sourceIdentity !== null &&
|
||||
cursor.sourceIdentity !== sourceIdentity
|
||||
) {
|
||||
throw new OrchestrationError(
|
||||
'source_changed',
|
||||
'The worker output source changed. Start a fresh worker-read without the old cursor.'
|
||||
)
|
||||
}
|
||||
const nextPosition =
|
||||
remote.terminal.nextCursor !== null && /^\d+$/.test(remote.terminal.nextCursor)
|
||||
? Number.parseInt(remote.terminal.nextCursor, 10)
|
||||
: null
|
||||
return {
|
||||
dispatchId: args.dispatchId,
|
||||
source: 'terminal' as const,
|
||||
sourceIdentity,
|
||||
terminal: remote.terminal,
|
||||
cursor:
|
||||
nextPosition === null
|
||||
? null
|
||||
: encodeWorkerOutputCursor(args.dispatchId, 'terminal', sourceIdentity, nextPosition),
|
||||
status: { worker: args.workerState, terminal: remote.terminal.status },
|
||||
fallbackReason: 'remote_capability_unavailable' as const,
|
||||
warnings: [],
|
||||
server: { environmentId: args.server.environmentId, name: args.server.name },
|
||||
remoteRuntimeEpoch: remote.runtimeEpoch
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { RpcMethod } from '../core'
|
||||
import { ORCHESTRATION_WORKER_CONTROL_METHODS } from './orchestration-worker-control'
|
||||
import { ORCHESTRATION_WORKER_STOP_METHODS } from './orchestration-worker-stop'
|
||||
import { ORCHESTRATION_WORKER_START_METHODS } from './orchestration-workers'
|
||||
|
||||
export const ORCHESTRATION_WORKER_METHODS: RpcMethod[] = [
|
||||
...ORCHESTRATION_WORKER_START_METHODS,
|
||||
...ORCHESTRATION_WORKER_CONTROL_METHODS,
|
||||
...ORCHESTRATION_WORKER_STOP_METHODS
|
||||
]
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import type { OrchestrationDb } from '../../orchestration/db'
|
||||
import { OrchestrationError } from '../../orchestration/orchestration-error'
|
||||
import type { FederatedDispatchRow, WorkerDispatchRow } from '../../orchestration/types'
|
||||
|
||||
export async function inspectWorkerTerminal(
|
||||
runtime: OrcaRuntimeService,
|
||||
db: OrchestrationDb,
|
||||
dispatchId: string
|
||||
): Promise<{
|
||||
terminal: Awaited<ReturnType<OrcaRuntimeService['showTerminal']>> | null
|
||||
exact: boolean
|
||||
status: 'unattached' | 'missing' | 'identity_changed' | 'running' | 'exited'
|
||||
}> {
|
||||
const worker = db.getWorkerDispatch(dispatchId)
|
||||
if (!worker?.agent_terminal_handle) {
|
||||
return { terminal: null, exact: false, status: 'unattached' }
|
||||
}
|
||||
const terminal = await runtime.showTerminal(worker.agent_terminal_handle).catch(() => null)
|
||||
if (!terminal) {
|
||||
return { terminal: null, exact: false, status: 'missing' }
|
||||
}
|
||||
const exact = db.isDispatchProcessCurrent({
|
||||
dispatchId,
|
||||
paneKey: runtime.getTerminalPaneKey(worker.agent_terminal_handle),
|
||||
processIncarnation: runtime.getTerminalProcessIncarnation(worker.agent_terminal_handle)
|
||||
})
|
||||
return {
|
||||
terminal,
|
||||
exact,
|
||||
status: exact ? (terminal.connected === false ? 'exited' : 'running') : 'identity_changed'
|
||||
}
|
||||
}
|
||||
|
||||
export function exposeWorker(worker: WorkerDispatchRow) {
|
||||
return {
|
||||
...worker,
|
||||
effects: JSON.parse(worker.effects) as unknown[],
|
||||
residualResources: JSON.parse(worker.residual_resources) as unknown[],
|
||||
startOptions: JSON.parse(worker.start_options) as unknown
|
||||
}
|
||||
}
|
||||
|
||||
export function resolvePinnedFederatedServer(
|
||||
runtime: OrcaRuntimeService,
|
||||
federated: FederatedDispatchRow
|
||||
) {
|
||||
const server = runtime.resolveOrchestrationWorkerServer(federated.environment_id)
|
||||
if (server.peerFingerprint !== federated.peer_fingerprint) {
|
||||
throw new OrchestrationError(
|
||||
'peer_changed',
|
||||
`Saved environment ${federated.environment_name} now identifies a different Orca server.`
|
||||
)
|
||||
}
|
||||
return server
|
||||
}
|
||||
|
||||
export async function callFederatedWorkerShow(
|
||||
runtime: OrcaRuntimeService,
|
||||
federated: FederatedDispatchRow
|
||||
): Promise<{
|
||||
runtimeEpoch: string
|
||||
attachment: {
|
||||
state: string
|
||||
stage: string
|
||||
last_error: string | null
|
||||
worktree_id: string | null
|
||||
terminal_handle: string | null
|
||||
setup_state: string
|
||||
effects: unknown[]
|
||||
residualResources: unknown[]
|
||||
}
|
||||
terminal: unknown
|
||||
observation: { status: string; exactWorker: boolean }
|
||||
}> {
|
||||
return (await runtime.callOrchestrationWorkerServer(
|
||||
federated.environment_id,
|
||||
'orchestration.federationShow',
|
||||
{ dispatchId: federated.dispatch_id },
|
||||
15_000
|
||||
)) as Awaited<ReturnType<typeof callFederatedWorkerShow>>
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { readExactWorkerOutput } from './orchestration-worker-output'
|
||||
|
||||
function codexMessage(id: string, text: string): string {
|
||||
return JSON.stringify({
|
||||
type: 'event_msg',
|
||||
payload: { id, type: 'agent_message', message: text }
|
||||
})
|
||||
}
|
||||
|
||||
describe('exact orchestration worker output', () => {
|
||||
let directory: string
|
||||
let transcriptA: string
|
||||
let transcriptB: string
|
||||
let providerSession: ReturnType<OrcaRuntimeService['getExactWorkerProviderSession']>
|
||||
let runtime: OrcaRuntimeService
|
||||
const readTerminal = vi.fn()
|
||||
|
||||
beforeEach(async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), 'orca-worker-output-'))
|
||||
transcriptA = join(directory, 'session-a.jsonl')
|
||||
transcriptB = join(directory, 'session-b.jsonl')
|
||||
await writeFile(transcriptA, `${codexMessage('a', 'worker A only')}\n`)
|
||||
await writeFile(transcriptB, `${codexMessage('b', 'worker B only')}\n`)
|
||||
providerSession = {
|
||||
paneKey: 'tab:worker',
|
||||
processIncarnation: 'pty:incarnation-1',
|
||||
agent: 'codex',
|
||||
providerSession: {
|
||||
key: 'session_id',
|
||||
id: 'session-a',
|
||||
transcriptPath: transcriptA
|
||||
},
|
||||
observedAt: Date.now()
|
||||
}
|
||||
readTerminal.mockReset()
|
||||
readTerminal.mockResolvedValue({
|
||||
handle: 'term_worker',
|
||||
status: 'running',
|
||||
tail: ['terminal output'],
|
||||
truncated: false,
|
||||
nextCursor: '9'
|
||||
})
|
||||
runtime = {
|
||||
getExactWorkerProviderSession: vi.fn(() => providerSession),
|
||||
getTerminalProcessIncarnation: vi.fn(() => 'pty:incarnation-1'),
|
||||
getTerminalPaneKey: vi.fn(() => 'tab:worker'),
|
||||
readTerminal
|
||||
} as unknown as OrcaRuntimeService
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const read = (overrides: Partial<Parameters<typeof readExactWorkerOutput>[0]> = {}) =>
|
||||
readExactWorkerOutput({
|
||||
runtime,
|
||||
dispatchId: 'dispatch_1',
|
||||
terminalHandle: 'term_worker',
|
||||
workerState: 'ready',
|
||||
terminalStatus: 'running',
|
||||
attachedAt: '2026-07-24 00:00:00',
|
||||
...overrides
|
||||
})
|
||||
|
||||
it('reads only the exact pane session and keeps its local path private', async () => {
|
||||
const result = await read()
|
||||
|
||||
expect(result).toMatchObject({
|
||||
source: 'transcript',
|
||||
provider: 'codex',
|
||||
transcript: {
|
||||
messages: [{ id: 'a', blocks: [{ type: 'text', text: 'worker A only' }] }]
|
||||
}
|
||||
})
|
||||
expect(JSON.stringify(result)).not.toContain(transcriptA)
|
||||
expect(JSON.stringify(result)).not.toContain('worker B only')
|
||||
expect(readTerminal).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reads Grok through the shared Native Chat transcript decoder', async () => {
|
||||
await writeFile(
|
||||
transcriptA,
|
||||
`${JSON.stringify({
|
||||
id: 'grok-a',
|
||||
type: 'assistant',
|
||||
content: 'Grok worker only'
|
||||
})}\n`
|
||||
)
|
||||
providerSession = {
|
||||
...providerSession!,
|
||||
agent: 'grok',
|
||||
providerSession: {
|
||||
key: 'session_id',
|
||||
id: 'session-grok',
|
||||
transcriptPath: transcriptA
|
||||
}
|
||||
}
|
||||
|
||||
const result = await read()
|
||||
|
||||
expect(result).toMatchObject({
|
||||
source: 'transcript',
|
||||
provider: 'grok',
|
||||
transcript: {
|
||||
messages: [{ role: 'assistant', blocks: [{ type: 'text', text: 'Grok worker only' }] }]
|
||||
}
|
||||
})
|
||||
expect(readTerminal).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('labels OpenCode as a terminal fallback when no transcript decoder exists', async () => {
|
||||
const capability = `dcap_${'A'.repeat(43)}`
|
||||
readTerminal.mockResolvedValue({
|
||||
handle: 'term_worker',
|
||||
status: 'running',
|
||||
tail: [`opencode --dispatch-capability ${capability}`],
|
||||
truncated: false,
|
||||
nextCursor: '9'
|
||||
})
|
||||
providerSession = {
|
||||
...providerSession!,
|
||||
agent: 'opencode',
|
||||
providerSession: {
|
||||
key: 'session_id',
|
||||
id: 'session-opencode',
|
||||
transcriptPath: transcriptA
|
||||
}
|
||||
}
|
||||
|
||||
const result = await read()
|
||||
|
||||
expect(result).toMatchObject({
|
||||
source: 'terminal',
|
||||
fallbackReason: 'provider_unsupported',
|
||||
terminal: { tail: ['opencode --dispatch-capability [dispatch capability redacted]'] },
|
||||
warnings: ['Dispatch capability tokens were redacted from terminal output.']
|
||||
})
|
||||
expect(JSON.stringify(result)).not.toContain(capability)
|
||||
})
|
||||
|
||||
it('rejects an old cursor after the exact provider session changes', async () => {
|
||||
const initial = await read()
|
||||
if (initial.source !== 'transcript') {
|
||||
throw new Error('Expected transcript output')
|
||||
}
|
||||
providerSession = {
|
||||
...providerSession!,
|
||||
providerSession: {
|
||||
key: 'session_id',
|
||||
id: 'session-b',
|
||||
transcriptPath: transcriptB
|
||||
}
|
||||
}
|
||||
|
||||
await expect(read({ cursor: initial.cursor })).rejects.toMatchObject({
|
||||
code: 'source_changed'
|
||||
})
|
||||
})
|
||||
|
||||
it('uses a labeled terminal fallback and keeps its cursor pinned', async () => {
|
||||
providerSession = null
|
||||
const fallback = await read()
|
||||
|
||||
expect(fallback).toMatchObject({
|
||||
source: 'terminal',
|
||||
fallbackReason: 'session_not_reported',
|
||||
terminal: { tail: ['terminal output'] }
|
||||
})
|
||||
expect(fallback.cursor).toMatch(/^owr1_/)
|
||||
|
||||
providerSession = {
|
||||
paneKey: 'tab:worker',
|
||||
processIncarnation: 'pty:incarnation-1',
|
||||
agent: 'codex',
|
||||
providerSession: {
|
||||
key: 'session_id',
|
||||
id: 'session-a',
|
||||
transcriptPath: transcriptA
|
||||
},
|
||||
observedAt: Date.now()
|
||||
}
|
||||
await read({ cursor: fallback.cursor ?? undefined })
|
||||
|
||||
expect(readTerminal).toHaveBeenLastCalledWith('term_worker', {
|
||||
cursor: 9,
|
||||
limit: undefined
|
||||
})
|
||||
})
|
||||
|
||||
it('fails instead of falling back when transcript output is required', async () => {
|
||||
providerSession = null
|
||||
|
||||
await expect(read({ source: 'transcript' })).rejects.toMatchObject({
|
||||
code: 'transcript_required',
|
||||
data: { reason: 'session_not_reported' }
|
||||
})
|
||||
expect(readTerminal).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,208 @@
|
||||
import type {
|
||||
OrchestrationWorkerReadFallbackReason,
|
||||
OrchestrationWorkerReadResult,
|
||||
OrchestrationWorkerReadSource
|
||||
} from '../../../../shared/orchestration-worker-output'
|
||||
import type { RuntimeTerminalState } from '../../../../shared/runtime-types'
|
||||
import type { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationError } from '../../orchestration/orchestration-error'
|
||||
import {
|
||||
createWorkerOutputSourceIdentity,
|
||||
decodeWorkerOutputCursor,
|
||||
encodeWorkerOutputCursor
|
||||
} from '../../orchestration/worker-output-cursor'
|
||||
import { redactWorkerTerminalLines } from '../../orchestration/worker-transcript-payload'
|
||||
import { readWorkerTranscript } from '../../orchestration/worker-transcript-read'
|
||||
|
||||
export async function readExactWorkerOutput(args: {
|
||||
runtime: OrcaRuntimeService
|
||||
dispatchId: string
|
||||
terminalHandle: string
|
||||
workerState: string
|
||||
terminalStatus: RuntimeTerminalState
|
||||
attachedAt: string
|
||||
source?: OrchestrationWorkerReadSource
|
||||
cursor?: string | number
|
||||
limit?: number
|
||||
}): Promise<OrchestrationWorkerReadResult> {
|
||||
const source = args.source ?? 'auto'
|
||||
const cursor = decodeWorkerOutputCursor(args.cursor, args.dispatchId)
|
||||
assertCursorSourceMatchesRequest(cursor?.source, source)
|
||||
|
||||
if (cursor?.source === 'terminal' || source === 'terminal') {
|
||||
return readTerminalOutput(args, cursor)
|
||||
}
|
||||
|
||||
const observedAfter = orchestrationTimestampToMs(args.attachedAt)
|
||||
const session = args.runtime.getExactWorkerProviderSession(args.terminalHandle, observedAfter)
|
||||
if (!session) {
|
||||
if (cursor?.source === 'transcript') {
|
||||
throw sourceChanged()
|
||||
}
|
||||
return fallbackOrThrow(args, 'session_not_reported')
|
||||
}
|
||||
const transcript = await readWorkerTranscript({
|
||||
agent: session.agent,
|
||||
sessionId: session.providerSession.id,
|
||||
transcriptPath: session.providerSession.transcriptPath,
|
||||
offset: cursor?.source === 'transcript' ? cursor.position : undefined,
|
||||
limit: args.limit
|
||||
})
|
||||
if (!transcript.ok) {
|
||||
if (transcript.reason === 'source_changed') {
|
||||
throw sourceChanged()
|
||||
}
|
||||
if (cursor?.source === 'transcript') {
|
||||
throw transcriptRequired(args.dispatchId, transcript.reason)
|
||||
}
|
||||
return fallbackOrThrow(args, transcript.reason, transcript.warnings)
|
||||
}
|
||||
const sourceIdentity = createWorkerOutputSourceIdentity([
|
||||
'transcript',
|
||||
session.processIncarnation,
|
||||
session.agent,
|
||||
session.providerSession.key,
|
||||
session.providerSession.id,
|
||||
transcript.filePath
|
||||
])
|
||||
if (cursor?.source === 'transcript' && cursor.sourceIdentity !== sourceIdentity) {
|
||||
throw sourceChanged()
|
||||
}
|
||||
const sessionAfterRead = args.runtime.getExactWorkerProviderSession(
|
||||
args.terminalHandle,
|
||||
observedAfter
|
||||
)
|
||||
if (
|
||||
!sessionAfterRead ||
|
||||
sessionAfterRead.processIncarnation !== session.processIncarnation ||
|
||||
sessionAfterRead.agent !== session.agent ||
|
||||
sessionAfterRead.providerSession.key !== session.providerSession.key ||
|
||||
sessionAfterRead.providerSession.id !== session.providerSession.id ||
|
||||
sessionAfterRead.providerSession.transcriptPath !== session.providerSession.transcriptPath
|
||||
) {
|
||||
throw sourceChanged()
|
||||
}
|
||||
const nextCursor = encodeWorkerOutputCursor(
|
||||
args.dispatchId,
|
||||
'transcript',
|
||||
sourceIdentity,
|
||||
transcript.nextOffset
|
||||
)
|
||||
return {
|
||||
dispatchId: args.dispatchId,
|
||||
source: 'transcript',
|
||||
sourceIdentity,
|
||||
provider: session.agent,
|
||||
transcript: {
|
||||
messages: transcript.messages,
|
||||
nextCursor,
|
||||
limited: transcript.limited,
|
||||
returnedMessageCount: transcript.messages.length
|
||||
},
|
||||
cursor: nextCursor,
|
||||
status: { worker: args.workerState, terminal: args.terminalStatus },
|
||||
fallbackReason: null,
|
||||
warnings: transcript.warnings
|
||||
}
|
||||
}
|
||||
|
||||
async function readTerminalOutput(
|
||||
args: Parameters<typeof readExactWorkerOutput>[0],
|
||||
cursor: ReturnType<typeof decodeWorkerOutputCursor>
|
||||
): Promise<OrchestrationWorkerReadResult> {
|
||||
const processIncarnation = args.runtime.getTerminalProcessIncarnation(args.terminalHandle)
|
||||
const paneKey = args.runtime.getTerminalPaneKey(args.terminalHandle)
|
||||
if (!processIncarnation || !paneKey) {
|
||||
throw new OrchestrationError(
|
||||
'worker_identity_changed',
|
||||
`Worker Dispatch ${args.dispatchId} no longer resolves to its exact process.`
|
||||
)
|
||||
}
|
||||
const sourceIdentity = createWorkerOutputSourceIdentity(['terminal', processIncarnation, paneKey])
|
||||
if (
|
||||
cursor?.source === 'terminal' &&
|
||||
cursor.sourceIdentity !== null &&
|
||||
cursor.sourceIdentity !== sourceIdentity
|
||||
) {
|
||||
throw sourceChanged()
|
||||
}
|
||||
const terminal = await args.runtime.readTerminal(args.terminalHandle, {
|
||||
cursor: cursor?.source === 'terminal' ? cursor.position : undefined,
|
||||
limit: args.limit
|
||||
})
|
||||
const redactedTerminal = redactWorkerTerminalLines(terminal.tail)
|
||||
const position =
|
||||
terminal.nextCursor !== null && /^\d+$/.test(terminal.nextCursor)
|
||||
? Number.parseInt(terminal.nextCursor, 10)
|
||||
: null
|
||||
const nextCursor =
|
||||
position === null
|
||||
? null
|
||||
: encodeWorkerOutputCursor(args.dispatchId, 'terminal', sourceIdentity, position)
|
||||
return {
|
||||
dispatchId: args.dispatchId,
|
||||
source: 'terminal',
|
||||
sourceIdentity,
|
||||
terminal: { ...terminal, tail: redactedTerminal.lines },
|
||||
cursor: nextCursor,
|
||||
status: { worker: args.workerState, terminal: terminal.status },
|
||||
fallbackReason: null,
|
||||
warnings: redactedTerminal.warnings
|
||||
}
|
||||
}
|
||||
|
||||
async function fallbackOrThrow(
|
||||
args: Parameters<typeof readExactWorkerOutput>[0],
|
||||
reason: OrchestrationWorkerReadFallbackReason,
|
||||
warnings: string[] = []
|
||||
): Promise<OrchestrationWorkerReadResult> {
|
||||
if (args.source === 'transcript') {
|
||||
throw transcriptRequired(args.dispatchId, reason)
|
||||
}
|
||||
const fallback = await readTerminalOutput(args, null)
|
||||
return fallback.source === 'terminal'
|
||||
? {
|
||||
...fallback,
|
||||
fallbackReason: reason,
|
||||
warnings: [...new Set([...fallback.warnings, ...warnings])]
|
||||
}
|
||||
: fallback
|
||||
}
|
||||
|
||||
function assertCursorSourceMatchesRequest(
|
||||
cursorSource: 'terminal' | 'transcript' | undefined,
|
||||
requestedSource: OrchestrationWorkerReadSource
|
||||
): void {
|
||||
if (cursorSource && requestedSource !== 'auto' && cursorSource !== requestedSource) {
|
||||
throw new OrchestrationError(
|
||||
'cursor_invalid',
|
||||
`The worker-read cursor is pinned to ${cursorSource} output.`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function orchestrationTimestampToMs(value: string): number {
|
||||
const normalized = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(value)
|
||||
? `${value.replace(' ', 'T')}Z`
|
||||
: value
|
||||
const parsed = Date.parse(normalized)
|
||||
return Number.isFinite(parsed) ? parsed : 0
|
||||
}
|
||||
|
||||
function sourceChanged(): OrchestrationError {
|
||||
return new OrchestrationError(
|
||||
'source_changed',
|
||||
'The worker output source changed. Start a fresh worker-read without the old cursor.'
|
||||
)
|
||||
}
|
||||
|
||||
function transcriptRequired(
|
||||
dispatchId: string,
|
||||
reason: OrchestrationWorkerReadFallbackReason
|
||||
): OrchestrationError {
|
||||
return new OrchestrationError(
|
||||
'transcript_required',
|
||||
`Structured output is unavailable for Dispatch ${dispatchId}: ${reason}.`,
|
||||
{ reason }
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { OrchestrationDb } from '../../orchestration/db'
|
||||
import {
|
||||
applyWaitForSetupOutcome,
|
||||
type WorkerEffect,
|
||||
type WorkerSetupReceipt
|
||||
} from './orchestration-worker-topology'
|
||||
|
||||
function residualWorkerEffects(effects: WorkerEffect[]): WorkerEffect[] {
|
||||
return effects.filter(
|
||||
(effect) => effect.action?.startsWith('created') || effect.action === 'reused_agent_terminal'
|
||||
)
|
||||
}
|
||||
|
||||
type WorkerSetupStageArgs = {
|
||||
db: OrchestrationDb
|
||||
dispatchId: string
|
||||
worktreeId: string
|
||||
terminalHandle: string
|
||||
setup: WorkerSetupReceipt
|
||||
effects: WorkerEffect[]
|
||||
}
|
||||
|
||||
export function persistWorkerReadinessStage(args: WorkerSetupStageArgs): void {
|
||||
args.db.recordWorkerStage({
|
||||
dispatchId: args.dispatchId,
|
||||
stage: 'terminal_readying',
|
||||
worktreeId: args.worktreeId,
|
||||
terminalHandle: args.terminalHandle,
|
||||
setupState: args.setup.state,
|
||||
effects: args.effects,
|
||||
residualResources: residualWorkerEffects(args.effects)
|
||||
})
|
||||
}
|
||||
|
||||
export function persistGatedSetupSpawnFailure(args: WorkerSetupStageArgs): boolean {
|
||||
if (args.setup.startupPolicy !== 'wait-for-setup' || args.setup.state !== 'spawn_failed') {
|
||||
return false
|
||||
}
|
||||
args.db.recordWorkerStage({
|
||||
dispatchId: args.dispatchId,
|
||||
stage: 'setup_start',
|
||||
worktreeId: args.worktreeId,
|
||||
terminalHandle: args.terminalHandle,
|
||||
setupState: args.setup.state,
|
||||
effects: args.effects,
|
||||
residualResources: residualWorkerEffects(args.effects)
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
export function persistWorkerSetupWaitOutcome(
|
||||
args: WorkerSetupStageArgs & { wait: { satisfied: boolean; status: string } }
|
||||
): void {
|
||||
applyWaitForSetupOutcome(args.setup, args.effects, args.wait)
|
||||
if (args.setup.startupPolicy !== 'wait-for-setup') {
|
||||
return
|
||||
}
|
||||
args.db.recordWorkerStage({
|
||||
dispatchId: args.dispatchId,
|
||||
stage: args.setup.state === 'failed' ? 'setup_failed' : 'setup_settled',
|
||||
worktreeId: args.worktreeId,
|
||||
terminalHandle: args.terminalHandle,
|
||||
setupState: args.setup.state,
|
||||
effects: args.effects,
|
||||
residualResources: residualWorkerEffects(args.effects)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { OrchestrationDb } from '../../orchestration/db'
|
||||
import {
|
||||
isUnknownWorkerStartOutcome,
|
||||
type WorkerSetupReceipt
|
||||
} from './orchestration-worker-topology'
|
||||
|
||||
export function failWorkerStartWithReceipt(args: {
|
||||
db: OrchestrationDb
|
||||
runId: string
|
||||
taskId: string
|
||||
dispatchId: string
|
||||
failedStage: string
|
||||
error: unknown
|
||||
setup: WorkerSetupReceipt
|
||||
}): unknown {
|
||||
const reason = args.error instanceof Error ? args.error.message : String(args.error)
|
||||
const unknown = isUnknownWorkerStartOutcome(args.error, args.failedStage)
|
||||
const worker = unknown
|
||||
? args.db.markWorkerStartUnknown(args.dispatchId, args.failedStage, reason)
|
||||
: args.db.failWorkerStart(args.dispatchId, args.failedStage, reason)
|
||||
return {
|
||||
runId: args.runId,
|
||||
taskId: args.taskId,
|
||||
dispatchId: args.dispatchId,
|
||||
state: worker.state === 'start_unknown' ? 'outcome_unknown' : worker.state,
|
||||
stage: worker.stage,
|
||||
failedStage: args.failedStage,
|
||||
lastError: reason,
|
||||
setup: args.setup,
|
||||
effects: JSON.parse(worker.effects) as unknown[],
|
||||
residualResources: JSON.parse(worker.residual_resources) as unknown[],
|
||||
...(unknown
|
||||
? {
|
||||
nextCommands: [
|
||||
`orca orchestration worker-show --dispatch ${args.dispatchId} --json`,
|
||||
`orca orchestration worker-abandon --dispatch ${args.dispatchId} --json`
|
||||
]
|
||||
}
|
||||
: {})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { z } from 'zod'
|
||||
import { OptionalFiniteNumber, OptionalString, requiredString } from '../schemas'
|
||||
|
||||
export const WorkerStartParams = z.object({
|
||||
task: requiredString('Missing --task'),
|
||||
on: OptionalString,
|
||||
run: OptionalString,
|
||||
from: requiredString('Missing --from'),
|
||||
worktree: OptionalString,
|
||||
name: OptionalString,
|
||||
repo: OptionalString,
|
||||
baseBranch: OptionalString,
|
||||
displayName: OptionalString,
|
||||
comment: OptionalString,
|
||||
setup: z.enum(['run', 'skip', 'inherit']).optional(),
|
||||
terminal: OptionalString,
|
||||
agent: OptionalString,
|
||||
retryOf: OptionalString,
|
||||
timeoutMs: OptionalFiniteNumber,
|
||||
devMode: z.boolean().optional()
|
||||
})
|
||||
|
||||
export type WorkerStartInput = z.infer<typeof WorkerStartParams>
|
||||
@@ -0,0 +1,148 @@
|
||||
import { z } from 'zod'
|
||||
import { OrchestrationError } from '../../orchestration/orchestration-error'
|
||||
import { syncFederatedDispatch } from '../../orchestration/federation-sync'
|
||||
import { defineMethod, type RpcMethod } from '../core'
|
||||
import { requiredString } from '../schemas'
|
||||
import {
|
||||
inspectWorkerTerminal,
|
||||
resolvePinnedFederatedServer
|
||||
} from './orchestration-worker-observation'
|
||||
|
||||
const WorkerDispatchParams = z.object({ dispatch: requiredString('Missing --dispatch') })
|
||||
|
||||
export const ORCHESTRATION_WORKER_STOP_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.workerStop',
|
||||
params: WorkerDispatchParams,
|
||||
handler: async (params, { runtime, orchestrationMutation }) => {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const federated = db.getFederatedDispatch(params.dispatch)
|
||||
if (federated) {
|
||||
if (!orchestrationMutation) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'Remote worker-stop requires a durable retry request.'
|
||||
)
|
||||
}
|
||||
const server = resolvePinnedFederatedServer(runtime, federated)
|
||||
const begun = db.beginWorkerStop(params.dispatch)
|
||||
if (begun.disposition === 'already_settled') {
|
||||
return settledReceipt(params.dispatch, begun.worker.state)
|
||||
}
|
||||
try {
|
||||
const remote = (await runtime.callOrchestrationWorkerServer(
|
||||
server.environmentId,
|
||||
'orchestration.federationStop',
|
||||
{ dispatchId: params.dispatch },
|
||||
30_000,
|
||||
{ orchestrationRequestId: orchestrationMutation.requestId }
|
||||
)) as RemoteStopReceipt
|
||||
if (remote.state === 'stopped') {
|
||||
const worker = db.reconcileFederatedWorkerStop(params.dispatch)
|
||||
return {
|
||||
dispatchId: params.dispatch,
|
||||
state: worker.state,
|
||||
alreadySettled: remote.alreadySettled,
|
||||
processAction: remote.processAction,
|
||||
close: remote.close
|
||||
}
|
||||
}
|
||||
if (remote.state === 'succeeded' || remote.state === 'failed') {
|
||||
db.resumeFederatedWorkerForTerminalRelay(params.dispatch)
|
||||
await syncFederatedDispatch(runtime, params.dispatch).catch(() => undefined)
|
||||
return {
|
||||
dispatchId: params.dispatch,
|
||||
state: db.getWorkerDispatch(params.dispatch)?.state ?? remote.state,
|
||||
alreadySettled: true,
|
||||
processAction: 'none'
|
||||
}
|
||||
}
|
||||
return unknownReceipt(
|
||||
params.dispatch,
|
||||
db.markWorkerStopUnknown(
|
||||
params.dispatch,
|
||||
remote.lastError ?? `The worker server returned ${remote.state}.`
|
||||
),
|
||||
remote.processAction
|
||||
)
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
return unknownReceipt(
|
||||
params.dispatch,
|
||||
db.markWorkerStopUnknown(params.dispatch, reason),
|
||||
'unknown'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const begun = db.beginWorkerStop(params.dispatch)
|
||||
if (begun.disposition === 'already_settled') {
|
||||
return settledReceipt(params.dispatch, begun.worker.state)
|
||||
}
|
||||
const handle = begun.worker.agent_terminal_handle
|
||||
if (!handle) {
|
||||
return unknownReceipt(
|
||||
params.dispatch,
|
||||
db.markWorkerStopUnknown(params.dispatch, 'The Dispatch has no recorded agent terminal.'),
|
||||
'unknown'
|
||||
)
|
||||
}
|
||||
const observation = await inspectWorkerTerminal(runtime, db, params.dispatch)
|
||||
if (!observation.exact || observation.status !== 'running') {
|
||||
return unknownReceipt(
|
||||
params.dispatch,
|
||||
db.markWorkerStopUnknown(
|
||||
params.dispatch,
|
||||
`The recorded worker process is ${observation.status}; no terminal was closed.`
|
||||
),
|
||||
'none'
|
||||
)
|
||||
}
|
||||
try {
|
||||
const close = await runtime.closeTerminal(handle)
|
||||
const worker = db.settleWorkerStop(params.dispatch)
|
||||
runtime.notifyMessageArrived(`dispatch:${params.dispatch}`, 'status')
|
||||
return {
|
||||
dispatchId: params.dispatch,
|
||||
state: worker.state,
|
||||
alreadySettled: false,
|
||||
processAction: 'closed_agent_terminal',
|
||||
close
|
||||
}
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
return unknownReceipt(
|
||||
params.dispatch,
|
||||
db.markWorkerStopUnknown(params.dispatch, reason),
|
||||
'unknown'
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
]
|
||||
|
||||
type RemoteStopReceipt = {
|
||||
state: string
|
||||
alreadySettled: boolean
|
||||
processAction: string
|
||||
close?: unknown
|
||||
lastError?: string | null
|
||||
}
|
||||
|
||||
function settledReceipt(dispatchId: string, state: string) {
|
||||
return { dispatchId, state, alreadySettled: true, processAction: 'none' }
|
||||
}
|
||||
|
||||
function unknownReceipt(
|
||||
dispatchId: string,
|
||||
worker: { state: string; last_error: string | null },
|
||||
processAction: string
|
||||
) {
|
||||
return {
|
||||
dispatchId,
|
||||
state: worker.state,
|
||||
alreadySettled: false,
|
||||
processAction,
|
||||
lastError: worker.last_error
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import type { TuiAgent } from '../../../../shared/types'
|
||||
import type { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import type { OrchestrationDb } from '../../orchestration/db'
|
||||
|
||||
export type WorkerEffect = {
|
||||
kind: 'worktree' | 'terminal' | 'setup' | 'dispatch_input'
|
||||
action?: string
|
||||
role?: string
|
||||
id?: string
|
||||
state?: string
|
||||
tabId?: string
|
||||
leafId?: string
|
||||
requested?: string
|
||||
effective?: string
|
||||
source?: string
|
||||
hookFound?: boolean
|
||||
startupPolicy?: string
|
||||
terminalId?: string
|
||||
}
|
||||
|
||||
export type WorkerSetupReceipt = {
|
||||
requested: 'run' | 'skip' | 'inherit' | 'not_applicable'
|
||||
effective: 'run' | 'skip' | 'inherit' | 'not_applicable'
|
||||
source: string
|
||||
hookFound: boolean
|
||||
startupPolicy: 'start-immediately' | 'wait-for-setup'
|
||||
state:
|
||||
| 'running'
|
||||
| 'succeeded'
|
||||
| 'failed'
|
||||
| 'skipped'
|
||||
| 'not_configured'
|
||||
| 'spawn_failed'
|
||||
| 'not_applicable'
|
||||
}
|
||||
|
||||
export function applyWaitForSetupOutcome(
|
||||
receipt: WorkerSetupReceipt,
|
||||
effects: WorkerEffect[],
|
||||
wait: { satisfied: boolean; status: string }
|
||||
): void {
|
||||
if (receipt.startupPolicy !== 'wait-for-setup' || receipt.state !== 'running') {
|
||||
return
|
||||
}
|
||||
if (wait.satisfied) {
|
||||
receipt.state = 'succeeded'
|
||||
} else if (wait.status === 'exited') {
|
||||
receipt.state = 'failed'
|
||||
} else {
|
||||
return
|
||||
}
|
||||
const setupEffect = effects.find((effect) => effect.kind === 'setup')
|
||||
if (setupEffect) {
|
||||
setupEffect.state = receipt.state
|
||||
}
|
||||
}
|
||||
|
||||
export async function createWorkerWorktree(args: {
|
||||
runtime: OrcaRuntimeService
|
||||
db: OrchestrationDb
|
||||
dispatchId: string
|
||||
requestedWorktree: string
|
||||
coordinatorWorktree: Awaited<ReturnType<OrcaRuntimeService['showManagedWorktree']>>
|
||||
params: {
|
||||
repo?: string
|
||||
name?: string
|
||||
baseBranch?: string
|
||||
displayName?: string
|
||||
comment?: string
|
||||
setup?: 'run' | 'skip' | 'inherit'
|
||||
from: string
|
||||
}
|
||||
agent: TuiAgent
|
||||
effects: WorkerEffect[]
|
||||
}): Promise<{
|
||||
worktree: Awaited<ReturnType<OrcaRuntimeService['showManagedWorktree']>>
|
||||
terminalHandle: string
|
||||
setupReceipt: WorkerSetupReceipt
|
||||
}> {
|
||||
const { runtime, db, dispatchId, requestedWorktree, coordinatorWorktree, params, effects } = args
|
||||
const setupDecision = params.setup ?? 'run'
|
||||
db.recordWorkerStage({ dispatchId, stage: 'worktree_creating', effects })
|
||||
const created = await runtime.createManagedWorktree({
|
||||
repoSelector: params.repo ?? coordinatorWorktree.repoId,
|
||||
name: params.name as string,
|
||||
baseBranch: params.baseBranch,
|
||||
displayName: params.displayName,
|
||||
comment: params.comment,
|
||||
runHooks: setupDecision === 'run',
|
||||
setupDecision,
|
||||
awaitTerminalProvisioning: true,
|
||||
observeSetupCompletion: true,
|
||||
createdWithAgent: args.agent,
|
||||
startupAgent: args.agent,
|
||||
activate: false,
|
||||
lineage: {
|
||||
parentWorktree: requestedWorktree === 'new-child' ? coordinatorWorktree.id : undefined,
|
||||
noParent: requestedWorktree === 'new-top-level',
|
||||
callerTerminalHandle: params.from
|
||||
}
|
||||
})
|
||||
const terminalHandle = created.startupTerminal?.handle
|
||||
effects.push({
|
||||
kind: 'worktree',
|
||||
action: requestedWorktree === 'new-child' ? 'created_child' : 'created_top_level',
|
||||
id: created.worktree.id
|
||||
})
|
||||
db.recordWorkerStage({
|
||||
dispatchId,
|
||||
stage: 'worktree_created',
|
||||
worktreeId: created.worktree.id,
|
||||
effects,
|
||||
residualResources: effects
|
||||
})
|
||||
const setupReceipt = {
|
||||
requested: setupDecision,
|
||||
effective: setupDecision,
|
||||
source: params.setup ? 'explicit_request' : 'orchestration_default',
|
||||
hookFound: created.setupReceipt?.hookFound ?? false,
|
||||
startupPolicy: created.setupReceipt?.startupPolicy ?? 'start-immediately',
|
||||
state: created.setupReceipt?.state ?? 'not_configured'
|
||||
}
|
||||
if (!terminalHandle) {
|
||||
throw new Error(created.warning ?? 'Agent-first worktree creation returned no terminal.')
|
||||
}
|
||||
const listed = await runtime.listTerminals(`id:${created.worktree.id}`)
|
||||
const setupTerminalHandle = created.setupReceipt?.terminalHandle
|
||||
for (const terminal of listed.terminals) {
|
||||
effects.push({
|
||||
kind: 'terminal',
|
||||
role:
|
||||
terminal.handle === terminalHandle
|
||||
? 'agent'
|
||||
: terminal.handle === setupTerminalHandle
|
||||
? 'setup'
|
||||
: 'configured_tab',
|
||||
action: terminal.handle === terminalHandle ? 'reused_agent_terminal' : 'created',
|
||||
id: terminal.handle,
|
||||
tabId: terminal.tabId,
|
||||
leafId: terminal.leafId
|
||||
})
|
||||
}
|
||||
const setupTerminal = effects.find(
|
||||
(effect) => effect.kind === 'terminal' && effect.role === 'setup'
|
||||
)
|
||||
effects.push({
|
||||
kind: 'setup',
|
||||
action: setupDecision,
|
||||
requested: setupReceipt.requested,
|
||||
effective: setupReceipt.effective,
|
||||
source: setupReceipt.source,
|
||||
hookFound: setupReceipt.hookFound,
|
||||
startupPolicy: setupReceipt.startupPolicy,
|
||||
state: setupReceipt.state,
|
||||
terminalId: setupTerminalHandle ?? setupTerminal?.id
|
||||
})
|
||||
return {
|
||||
worktree: created.worktree as Awaited<ReturnType<OrcaRuntimeService['showManagedWorktree']>>,
|
||||
terminalHandle,
|
||||
setupReceipt
|
||||
}
|
||||
}
|
||||
|
||||
export function monitorWorkerSetup(args: {
|
||||
runtime: OrcaRuntimeService
|
||||
db: OrchestrationDb
|
||||
runId: string
|
||||
dispatchId: string
|
||||
setupReceipt: WorkerSetupReceipt
|
||||
effects: WorkerEffect[]
|
||||
}): void {
|
||||
const setupTerminal = args.effects.find(
|
||||
(effect) => effect.kind === 'terminal' && effect.role === 'setup' && effect.id
|
||||
)
|
||||
if (
|
||||
!setupTerminal?.id ||
|
||||
args.setupReceipt.startupPolicy !== 'start-immediately' ||
|
||||
args.setupReceipt.state !== 'running'
|
||||
) {
|
||||
return
|
||||
}
|
||||
// Why: setup is intentionally non-gating, but command completion remains durable evidence.
|
||||
void args.runtime
|
||||
.waitForSetupTerminalCompletion(setupTerminal.id)
|
||||
.then((completion) => {
|
||||
const setupState = completion.exitCode === 0 ? 'succeeded' : 'failed'
|
||||
const evidence = args.db.updateWorkerSetupEvidence({
|
||||
dispatchId: args.dispatchId,
|
||||
setupState,
|
||||
effects: args.effects.map((effect) =>
|
||||
effect.kind === 'setup' ? { ...effect, state: setupState } : effect
|
||||
)
|
||||
})
|
||||
if (!evidence.changed) {
|
||||
return
|
||||
}
|
||||
const message = args.db.insertMessage({
|
||||
runId: args.runId,
|
||||
from: `dispatch:${args.dispatchId}`,
|
||||
to: `run:${args.runId}`,
|
||||
subject: `Setup ${setupState} for worker ${args.dispatchId}`,
|
||||
type: 'status',
|
||||
priority: setupState === 'failed' ? 'high' : 'normal',
|
||||
payload: JSON.stringify({
|
||||
dispatchId: args.dispatchId,
|
||||
setupState,
|
||||
terminalHandle: setupTerminal.id
|
||||
})
|
||||
})
|
||||
args.runtime.notifyMessageArrived(message.to_handle, message.type)
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}
|
||||
|
||||
export function isUnknownWorkerStartOutcome(error: unknown, stage: string): boolean {
|
||||
const code =
|
||||
error && typeof error === 'object' && typeof (error as { code?: unknown }).code === 'string'
|
||||
? (error as { code: string }).code
|
||||
: ''
|
||||
if (code === 'operation_unknown') {
|
||||
return true
|
||||
}
|
||||
if (stage !== 'worktree_create') {
|
||||
return false
|
||||
}
|
||||
const message = error instanceof Error ? error.message : String(error)
|
||||
return /connection|disconnect|timed?\s*out|runtime changed|outcome unknown/i.test(message)
|
||||
}
|
||||
@@ -0,0 +1,614 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../shared/protocol-version'
|
||||
import { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationDb } from '../../orchestration/db'
|
||||
import { RpcDispatcher } from '../dispatcher'
|
||||
import type { RpcRequest } from '../core'
|
||||
import { ORCHESTRATION_METHODS } from './orchestration'
|
||||
|
||||
describe('orchestration new-worktree workers', () => {
|
||||
type CreateWorktreeResult = Awaited<ReturnType<OrcaRuntimeService['createManagedWorktree']>>
|
||||
const coordinatorPaneKey = 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
let db: OrchestrationDb
|
||||
let runtime: OrcaRuntimeService
|
||||
let runId: string
|
||||
|
||||
beforeEach(() => {
|
||||
db = new OrchestrationDb(':memory:')
|
||||
runtime = new OrcaRuntimeService()
|
||||
runtime.setOrchestrationDb(db)
|
||||
runId = db.createRun({
|
||||
objective: 'Test new-worktree workers',
|
||||
coordinatorHandle: 'term_coord',
|
||||
coordinatorPaneKey
|
||||
}).id
|
||||
vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((handle) =>
|
||||
handle === 'term_coord'
|
||||
? coordinatorPaneKey
|
||||
: handle === 'term_worker'
|
||||
? 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
|
||||
: null
|
||||
)
|
||||
vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockImplementation((handle) =>
|
||||
handle === 'term_worker' ? 'runtime_test:term_worker:1' : null
|
||||
)
|
||||
vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {})
|
||||
vi.spyOn(runtime, 'showTerminal').mockResolvedValue({
|
||||
handle: 'term_coord',
|
||||
worktreeId: 'repo::parent',
|
||||
status: 'running'
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'showManagedWorktree').mockResolvedValue({
|
||||
id: 'repo::parent',
|
||||
repoId: 'repo'
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'showRepo').mockResolvedValue({
|
||||
id: 'repo',
|
||||
kind: 'git'
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'createTerminal')
|
||||
vi.spyOn(runtime, 'listTerminals').mockResolvedValue({
|
||||
terminals: [{ handle: 'term_worker', title: 'Codex' }],
|
||||
totalCount: 1,
|
||||
truncated: false
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'waitForTerminal').mockResolvedValue({
|
||||
handle: 'term_worker',
|
||||
condition: 'tui-idle',
|
||||
satisfied: true,
|
||||
status: 'running',
|
||||
exitCode: null
|
||||
})
|
||||
vi.spyOn(runtime, 'waitForSetupTerminalCompletion').mockReturnValue(
|
||||
new Promise(() => undefined)
|
||||
)
|
||||
vi.spyOn(runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca')
|
||||
vi.spyOn(runtime, 'sendTerminalAgentPrompt').mockResolvedValue({
|
||||
handle: 'term_worker',
|
||||
accepted: true,
|
||||
bytesWritten: 1
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => db.close())
|
||||
|
||||
async function startWorker(overrides: Record<string, unknown> = {}) {
|
||||
const task = db.createTask({ spec: 'new-worktree task', runId })
|
||||
const method = ORCHESTRATION_METHODS.find(
|
||||
(candidate) => candidate.name === 'orchestration.workerStart'
|
||||
)
|
||||
if (!method) {
|
||||
throw new Error('workerStart method is not registered')
|
||||
}
|
||||
const params = method.params!.parse({
|
||||
task: task.id,
|
||||
from: 'term_coord',
|
||||
worktree: 'new-child',
|
||||
name: 'new-worker',
|
||||
agent: 'codex',
|
||||
...overrides
|
||||
})
|
||||
const result = await method.handler(params, { runtime })
|
||||
return { result, task }
|
||||
}
|
||||
|
||||
function mockCreatedWorktree(options?: {
|
||||
hookFound?: boolean
|
||||
startupPolicy?: 'start-immediately' | 'wait-for-setup'
|
||||
state?: 'running' | 'skipped' | 'not_configured' | 'spawn_failed'
|
||||
terminals?: { handle: string; title: string }[]
|
||||
setupTerminalHandle?: string
|
||||
}) {
|
||||
const hookFound = options?.hookFound ?? true
|
||||
const state = options?.state ?? (hookFound ? 'running' : 'not_configured')
|
||||
vi.spyOn(runtime, 'createManagedWorktree').mockResolvedValue({
|
||||
worktree: { id: 'repo::created', repoId: 'repo' },
|
||||
startupTerminal: { spawned: true, handle: 'term_worker' },
|
||||
setupReceipt: {
|
||||
requested: state === 'skipped' ? 'skip' : 'run',
|
||||
hookFound,
|
||||
startupPolicy: options?.startupPolicy ?? 'start-immediately',
|
||||
state,
|
||||
terminalHandle:
|
||||
options?.setupTerminalHandle ??
|
||||
options?.terminals?.find((terminal) => terminal.title === 'Setup')?.handle
|
||||
}
|
||||
} as never)
|
||||
if (options?.terminals) {
|
||||
vi.mocked(runtime.listTerminals).mockResolvedValue({
|
||||
terminals: options.terminals,
|
||||
totalCount: options.terminals.length,
|
||||
truncated: false
|
||||
} as never)
|
||||
}
|
||||
}
|
||||
|
||||
it('creates an independent top-level worktree and reuses its agent terminal', async () => {
|
||||
mockCreatedWorktree()
|
||||
|
||||
const { result } = await startWorker({ worktree: 'new-top-level' })
|
||||
|
||||
expect(runtime.createManagedWorktree).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
startupAgent: 'codex',
|
||||
awaitTerminalProvisioning: true,
|
||||
observeSetupCompletion: true,
|
||||
lineage: expect.objectContaining({ noParent: true, parentWorktree: undefined })
|
||||
})
|
||||
)
|
||||
expect(result).toMatchObject({ state: 'ready' })
|
||||
expect(result).toHaveProperty(
|
||||
'effects',
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: 'worktree',
|
||||
action: 'created_top_level',
|
||||
id: 'repo::created'
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: 'terminal',
|
||||
role: 'agent',
|
||||
action: 'reused_agent_terminal',
|
||||
id: 'term_worker'
|
||||
})
|
||||
])
|
||||
)
|
||||
expect(runtime.createTerminal).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects a new worktree for a folder project before creating effects', async () => {
|
||||
vi.mocked(runtime.showRepo).mockResolvedValue({
|
||||
id: 'repo',
|
||||
kind: 'folder'
|
||||
} as never)
|
||||
const createWorktree = vi.spyOn(runtime, 'createManagedWorktree')
|
||||
const task = db.createTask({ spec: 'folder task', runId })
|
||||
const method = ORCHESTRATION_METHODS.find(
|
||||
(candidate) => candidate.name === 'orchestration.workerStart'
|
||||
)
|
||||
if (!method) {
|
||||
throw new Error('workerStart method is not registered')
|
||||
}
|
||||
|
||||
await expect(
|
||||
method.handler(
|
||||
method.params!.parse({
|
||||
task: task.id,
|
||||
from: 'term_coord',
|
||||
worktree: 'new-child',
|
||||
name: 'folder-worker',
|
||||
agent: 'codex'
|
||||
}),
|
||||
{ runtime }
|
||||
)
|
||||
).rejects.toMatchObject({
|
||||
code: 'invalid_argument',
|
||||
message:
|
||||
'Folder projects cannot create orchestration worktrees; use current or an exact existing folder workspace.'
|
||||
})
|
||||
expect(createWorktree).not.toHaveBeenCalled()
|
||||
expect(db.getTask(task.id)?.status).toBe('ready')
|
||||
expect(db.getDispatchContext(task.id)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('injects the execution host CLI command and Dispatch capability together', async () => {
|
||||
mockCreatedWorktree()
|
||||
vi.mocked(runtime.getTerminalOrchestrationCliCommand).mockReturnValue('orca-ide')
|
||||
|
||||
await startWorker({ worktree: 'new-top-level' })
|
||||
|
||||
const prompt = vi.mocked(runtime.sendTerminalAgentPrompt).mock.calls[0]?.[1] ?? ''
|
||||
expect(prompt).toContain('orca-ide orchestration send')
|
||||
expect(prompt).toMatch(/--dispatch-capability dcap_[A-Za-z0-9_-]+/)
|
||||
expect(prompt).not.toMatch(/(^|\s)orca orchestration send/)
|
||||
})
|
||||
|
||||
it('passes exact repo, base, metadata, lineage, and setup choices to worktree creation', async () => {
|
||||
mockCreatedWorktree({ state: 'skipped' })
|
||||
|
||||
await startWorker({
|
||||
worktree: 'new-top-level',
|
||||
repo: 'id:repo-explicit',
|
||||
baseBranch: 'origin/release',
|
||||
displayName: 'Windows release audit',
|
||||
comment: 'Created for a supervised audit',
|
||||
setup: 'skip'
|
||||
})
|
||||
|
||||
expect(runtime.createManagedWorktree).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
repoSelector: 'id:repo-explicit',
|
||||
baseBranch: 'origin/release',
|
||||
displayName: 'Windows release audit',
|
||||
comment: 'Created for a supervised audit',
|
||||
setupDecision: 'skip',
|
||||
runHooks: false,
|
||||
lineage: expect.objectContaining({ noParent: true, parentWorktree: undefined })
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('reports an absent setup hook as not configured without failing the start', async () => {
|
||||
mockCreatedWorktree({ hookFound: false })
|
||||
|
||||
const { result } = await startWorker()
|
||||
|
||||
expect(result).toMatchObject({
|
||||
state: 'ready',
|
||||
setup: {
|
||||
requested: 'run',
|
||||
effective: 'run',
|
||||
source: 'orchestration_default',
|
||||
hookFound: false,
|
||||
state: 'not_configured'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
['skip', 'skipped'],
|
||||
['inherit', 'not_configured'],
|
||||
['run', 'running']
|
||||
] as const)('passes explicit setup=%s through with a truthful receipt', async (setup, state) => {
|
||||
mockCreatedWorktree({ hookFound: setup === 'run', state })
|
||||
|
||||
const { result } = await startWorker({ setup })
|
||||
|
||||
expect(runtime.createManagedWorktree).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ setupDecision: setup, runHooks: setup === 'run' })
|
||||
)
|
||||
expect(result).toMatchObject({
|
||||
state: 'ready',
|
||||
setup: { requested: setup, effective: setup, source: 'explicit_request', state }
|
||||
})
|
||||
})
|
||||
|
||||
it('records a later setup failure without gating a start-immediately worker', async () => {
|
||||
mockCreatedWorktree({
|
||||
terminals: [
|
||||
{ handle: 'term_worker', title: 'Codex' },
|
||||
{ handle: 'term_setup', title: 'Setup' }
|
||||
]
|
||||
})
|
||||
let finishSetup: ((result: { exitCode: number | null }) => void) | undefined
|
||||
vi.mocked(runtime.waitForSetupTerminalCompletion).mockImplementation(
|
||||
async () =>
|
||||
await new Promise((resolve) => {
|
||||
finishSetup = resolve
|
||||
})
|
||||
)
|
||||
|
||||
const { result, task } = await startWorker()
|
||||
const dispatchId = (result as { dispatchId: string }).dispatchId
|
||||
|
||||
expect(result).toMatchObject({ state: 'ready', setup: { state: 'running' } })
|
||||
expect(
|
||||
db.settleWorkerReport({
|
||||
taskId: task.id,
|
||||
dispatchId,
|
||||
outcome: 'succeeded',
|
||||
result: '{}'
|
||||
})
|
||||
).toMatchObject({ action: 'settled' })
|
||||
finishSetup?.({ exitCode: 1 })
|
||||
await vi.waitFor(() => expect(db.getWorkerDispatch(dispatchId)?.setup_state).toBe('failed'))
|
||||
expect(db.getWorkerDispatch(dispatchId)).toMatchObject({
|
||||
state: 'succeeded',
|
||||
stage: 'settled',
|
||||
setup_state: 'failed'
|
||||
})
|
||||
expect(JSON.parse(db.getWorkerDispatch(dispatchId)?.effects ?? '[]')).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'dispatch_input', state: 'accepted' })
|
||||
])
|
||||
)
|
||||
expect(runtime.sendTerminalAgentPrompt).toHaveBeenCalledOnce()
|
||||
expect(db.getInbox(10).filter((message) => message.run_id === runId)).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ type: 'status', priority: 'high' })])
|
||||
)
|
||||
})
|
||||
|
||||
it('uses the exact setup handle instead of a configured tab title', async () => {
|
||||
mockCreatedWorktree({
|
||||
setupTerminalHandle: 'term_actual_setup',
|
||||
terminals: [
|
||||
{ handle: 'term_worker', title: 'Codex' },
|
||||
{ handle: 'term_configured_setup', title: 'Setup' },
|
||||
{ handle: 'term_actual_setup', title: 'PowerShell' }
|
||||
]
|
||||
})
|
||||
|
||||
const { result } = await startWorker()
|
||||
|
||||
expect(result).toMatchObject({
|
||||
effects: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: 'terminal',
|
||||
id: 'term_configured_setup',
|
||||
role: 'configured_tab'
|
||||
}),
|
||||
expect.objectContaining({ kind: 'terminal', id: 'term_actual_setup', role: 'setup' }),
|
||||
expect.objectContaining({ kind: 'setup', terminalId: 'term_actual_setup' })
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
it('records wait-for-setup success before task input is accepted', async () => {
|
||||
mockCreatedWorktree({ startupPolicy: 'wait-for-setup', state: 'running' })
|
||||
|
||||
const { result } = await startWorker()
|
||||
const dispatchId = (result as { dispatchId: string }).dispatchId
|
||||
|
||||
expect(result).toMatchObject({
|
||||
state: 'ready',
|
||||
setup: { startupPolicy: 'wait-for-setup', state: 'succeeded' },
|
||||
effects: expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'setup', state: 'succeeded' }),
|
||||
expect.objectContaining({ kind: 'dispatch_input', state: 'accepted' })
|
||||
])
|
||||
})
|
||||
expect(vi.mocked(runtime.waitForTerminal).mock.invocationCallOrder[0]).toBeLessThan(
|
||||
vi.mocked(runtime.sendTerminalAgentPrompt).mock.invocationCallOrder[0]!
|
||||
)
|
||||
expect(JSON.parse(db.getWorkerDispatch(dispatchId)?.effects ?? '[]')).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'dispatch_input', state: 'accepted' })
|
||||
])
|
||||
)
|
||||
})
|
||||
|
||||
it('does not inject task input when the gated setup terminal fails to start', async () => {
|
||||
mockCreatedWorktree({ startupPolicy: 'wait-for-setup', state: 'spawn_failed' })
|
||||
vi.mocked(runtime.waitForTerminal).mockResolvedValue({
|
||||
handle: 'term_worker',
|
||||
condition: 'tui-idle',
|
||||
satisfied: false,
|
||||
status: 'exited',
|
||||
exitCode: 1
|
||||
})
|
||||
|
||||
const { result, task } = await startWorker()
|
||||
|
||||
expect(result).toMatchObject({
|
||||
state: 'failed',
|
||||
failedStage: 'setup_start',
|
||||
setup: { startupPolicy: 'wait-for-setup', state: 'spawn_failed' },
|
||||
effects: expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'setup', state: 'spawn_failed' })
|
||||
])
|
||||
})
|
||||
expect(db.getTask(task.id)?.status).toBe('failed')
|
||||
expect(runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not inject task input when the gated setup script fails', async () => {
|
||||
mockCreatedWorktree({ startupPolicy: 'wait-for-setup', state: 'running' })
|
||||
vi.mocked(runtime.waitForTerminal).mockResolvedValue({
|
||||
handle: 'term_worker',
|
||||
condition: 'tui-idle',
|
||||
satisfied: false,
|
||||
status: 'exited',
|
||||
exitCode: 1
|
||||
})
|
||||
|
||||
const { result } = await startWorker()
|
||||
|
||||
expect(result).toMatchObject({
|
||||
state: 'failed',
|
||||
failedStage: 'setup_wait',
|
||||
setup: { state: 'failed' },
|
||||
effects: expect.arrayContaining([expect.objectContaining({ kind: 'setup', state: 'failed' })])
|
||||
})
|
||||
expect(runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not mislabel a wait-for-setup timeout as setup failure', async () => {
|
||||
mockCreatedWorktree({ startupPolicy: 'wait-for-setup', state: 'running' })
|
||||
vi.mocked(runtime.waitForTerminal).mockResolvedValue({
|
||||
handle: 'term_worker',
|
||||
condition: 'tui-idle',
|
||||
satisfied: false,
|
||||
status: 'running',
|
||||
exitCode: null
|
||||
})
|
||||
|
||||
const { result } = await startWorker()
|
||||
|
||||
expect(result).toMatchObject({
|
||||
state: 'failed',
|
||||
failedStage: 'agent_readiness',
|
||||
setup: { state: 'running' }
|
||||
})
|
||||
expect(runtime.sendTerminalAgentPrompt).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('distinguishes no-effect failure, unknown acceptance, and durable residual effects', async () => {
|
||||
vi.spyOn(runtime, 'createManagedWorktree').mockRejectedValueOnce(
|
||||
new Error('repository validation failed before creation')
|
||||
)
|
||||
const noEffect = await startWorker({ name: 'no-effect' })
|
||||
expect(noEffect.result).toMatchObject({
|
||||
state: 'failed',
|
||||
failedStage: 'worktree_create',
|
||||
effects: [],
|
||||
residualResources: []
|
||||
})
|
||||
|
||||
vi.mocked(runtime.createManagedWorktree).mockRejectedValueOnce(
|
||||
Object.assign(new Error('connection lost after possible acceptance'), {
|
||||
code: 'operation_unknown'
|
||||
})
|
||||
)
|
||||
const unknown = await startWorker({ name: 'unknown-effect' })
|
||||
expect(unknown.result).toMatchObject({
|
||||
state: 'outcome_unknown',
|
||||
failedStage: 'worktree_create',
|
||||
effects: [],
|
||||
residualResources: []
|
||||
})
|
||||
|
||||
mockCreatedWorktree()
|
||||
vi.mocked(runtime.waitForTerminal).mockResolvedValueOnce({
|
||||
handle: 'term_worker',
|
||||
condition: 'tui-idle',
|
||||
satisfied: false,
|
||||
status: 'exited',
|
||||
exitCode: 1
|
||||
})
|
||||
const durableEffect = await startWorker({ name: 'durable-effect' })
|
||||
expect(durableEffect.result).toMatchObject({
|
||||
state: 'failed',
|
||||
failedStage: 'agent_readiness',
|
||||
effects: expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'worktree', id: 'repo::created' }),
|
||||
expect.objectContaining({ kind: 'terminal', id: 'term_worker' })
|
||||
]),
|
||||
residualResources: expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'worktree', id: 'repo::created' }),
|
||||
expect.objectContaining({ kind: 'terminal', id: 'term_worker' })
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
it('returns outcome unknown when worktree creation may have been accepted remotely', async () => {
|
||||
vi.spyOn(runtime, 'createManagedWorktree').mockRejectedValue(
|
||||
Object.assign(new Error('connection closed after request acceptance'), {
|
||||
code: 'operation_unknown'
|
||||
})
|
||||
)
|
||||
|
||||
const { result, task } = await startWorker()
|
||||
|
||||
expect(result).toMatchObject({
|
||||
state: 'outcome_unknown',
|
||||
failedStage: 'worktree_create',
|
||||
nextCommands: expect.arrayContaining([
|
||||
expect.stringContaining('worker-show --dispatch'),
|
||||
expect.stringContaining('worker-abandon --dispatch')
|
||||
])
|
||||
})
|
||||
expect(db.getTask(task.id)?.status).toBe('blocked')
|
||||
})
|
||||
|
||||
it('persists the retry request with the starting Dispatch before worktree effects', async () => {
|
||||
const task = db.createTask({ spec: 'atomic worker acceptance', runId })
|
||||
let finishCreate: ((value: CreateWorktreeResult) => void) | undefined
|
||||
vi.spyOn(runtime, 'createManagedWorktree').mockImplementation(
|
||||
async () =>
|
||||
await new Promise((resolve) => {
|
||||
finishCreate = resolve
|
||||
})
|
||||
)
|
||||
const dispatcher = new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS })
|
||||
const request: RpcRequest = {
|
||||
id: 'rpc_worker_start',
|
||||
authToken: 'caller-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: 'worker_start_request',
|
||||
method: 'orchestration.workerStart',
|
||||
params: {
|
||||
task: task.id,
|
||||
from: 'term_coord',
|
||||
worktree: 'new-child',
|
||||
name: 'atomic-worker',
|
||||
agent: 'codex'
|
||||
}
|
||||
}
|
||||
|
||||
const pending = dispatcher.dispatch(request)
|
||||
await vi.waitFor(() => expect(db.getDispatchContext(task.id)).toBeDefined())
|
||||
const acceptedDispatch = db.getDispatchContext(task.id)!
|
||||
const callerFingerprint = createHash('sha256').update('caller-token').digest('hex')
|
||||
const receipt = db.getMutationReceipt(callerFingerprint, 'worker_start_request')
|
||||
|
||||
expect(receipt).toMatchObject({
|
||||
request_id: 'worker_start_request',
|
||||
method: 'orchestration.workerStart',
|
||||
state: 'pending'
|
||||
})
|
||||
expect(db.getWorkerDispatch(acceptedDispatch.id)).toMatchObject({
|
||||
state: 'starting',
|
||||
stage: 'worktree_creating'
|
||||
})
|
||||
|
||||
finishCreate?.({
|
||||
worktree: { id: 'repo::created', repoId: 'repo' },
|
||||
startupTerminal: { spawned: true, handle: 'term_worker' },
|
||||
setupReceipt: {
|
||||
requested: 'run',
|
||||
hookFound: false,
|
||||
startupPolicy: 'start-immediately',
|
||||
state: 'not_configured'
|
||||
}
|
||||
} as CreateWorktreeResult)
|
||||
await expect(pending).resolves.toMatchObject({
|
||||
ok: true,
|
||||
result: { state: 'ready', mutation: { requestId: 'worker_start_request' } }
|
||||
})
|
||||
expect(db.getMutationReceipt(callerFingerprint, 'worker_start_request')).toMatchObject({
|
||||
state: 'completed'
|
||||
})
|
||||
})
|
||||
|
||||
it('persists pre-effect, post-effect, and post-input stages in order', async () => {
|
||||
mockCreatedWorktree({ hookFound: false })
|
||||
let finishWait:
|
||||
| ((value: Awaited<ReturnType<OrcaRuntimeService['waitForTerminal']>>) => void)
|
||||
| undefined
|
||||
let finishPrompt:
|
||||
| ((value: Awaited<ReturnType<OrcaRuntimeService['sendTerminalAgentPrompt']>>) => void)
|
||||
| undefined
|
||||
vi.mocked(runtime.waitForTerminal).mockImplementationOnce(
|
||||
async () =>
|
||||
await new Promise((resolve) => {
|
||||
finishWait = resolve
|
||||
})
|
||||
)
|
||||
vi.mocked(runtime.sendTerminalAgentPrompt).mockImplementationOnce(
|
||||
async () =>
|
||||
await new Promise((resolve) => {
|
||||
finishPrompt = resolve
|
||||
})
|
||||
)
|
||||
|
||||
const pending = startWorker({ name: 'staged-worker' })
|
||||
await vi.waitFor(() => {
|
||||
const task = db.listTasks()[0]
|
||||
const dispatch = task ? db.getDispatchContext(task.id) : undefined
|
||||
expect(dispatch && db.getWorkerDispatch(dispatch.id)).toMatchObject({
|
||||
state: 'starting',
|
||||
stage: 'terminal_readying',
|
||||
worktree_id: 'repo::created',
|
||||
agent_terminal_handle: 'term_worker'
|
||||
})
|
||||
})
|
||||
const dispatch = db.getDispatchContext(db.listTasks()[0]!.id)!
|
||||
expect(JSON.parse(db.getWorkerDispatch(dispatch.id)!.residual_resources)).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ kind: 'worktree', id: 'repo::created' })])
|
||||
)
|
||||
|
||||
finishWait?.({
|
||||
handle: 'term_worker',
|
||||
condition: 'tui-idle',
|
||||
satisfied: true,
|
||||
status: 'running',
|
||||
exitCode: null
|
||||
})
|
||||
await vi.waitFor(() =>
|
||||
expect(db.getWorkerDispatch(dispatch.id)).toMatchObject({
|
||||
state: 'starting',
|
||||
stage: 'authority_attached'
|
||||
})
|
||||
)
|
||||
|
||||
finishPrompt?.({ handle: 'term_worker', accepted: true, bytesWritten: 1 })
|
||||
await expect(pending).resolves.toMatchObject({
|
||||
result: { state: 'ready', stage: 'input_accepted' }
|
||||
})
|
||||
expect(db.getWorkerDispatch(dispatch.id)).toMatchObject({
|
||||
state: 'ready',
|
||||
stage: 'input_accepted'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,246 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationDb } from '../../orchestration/db'
|
||||
import { ORCHESTRATION_METHODS } from './orchestration'
|
||||
|
||||
describe('orchestration worker recovery', () => {
|
||||
let db: OrchestrationDb
|
||||
let runtime: OrcaRuntimeService
|
||||
|
||||
beforeEach(() => {
|
||||
db = new OrchestrationDb(':memory:')
|
||||
runtime = new OrcaRuntimeService()
|
||||
runtime.setOrchestrationDb(db)
|
||||
vi.spyOn(runtime, 'getTerminalPaneKey').mockReturnValue(
|
||||
'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
|
||||
)
|
||||
vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockReturnValue('runtime:pty:1')
|
||||
vi.spyOn(runtime, 'showTerminal').mockResolvedValue({
|
||||
handle: 'term_worker',
|
||||
worktreeId: 'repo::worktree',
|
||||
connected: true,
|
||||
status: 'running'
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'readTerminal').mockResolvedValue({
|
||||
handle: 'term_worker',
|
||||
status: 'running',
|
||||
tail: ['working'],
|
||||
truncated: false,
|
||||
nextCursor: null
|
||||
})
|
||||
vi.spyOn(runtime, 'closeTerminal').mockResolvedValue({
|
||||
handle: 'term_worker',
|
||||
closed: true
|
||||
} as never)
|
||||
})
|
||||
|
||||
afterEach(() => db.close())
|
||||
|
||||
async function call(name: string, params: Record<string, unknown>) {
|
||||
const method = ORCHESTRATION_METHODS.find((candidate) => candidate.name === name)
|
||||
if (!method) {
|
||||
throw new Error(`Method not found: ${name}`)
|
||||
}
|
||||
return method.handler(method.params!.parse(params), { runtime })
|
||||
}
|
||||
|
||||
function createWorker(runtimeEpoch = runtime.getRuntimeId(), ready = true) {
|
||||
const run = db.createRun({
|
||||
objective: 'Recovery',
|
||||
coordinatorHandle: 'term_coord',
|
||||
coordinatorPaneKey: 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
})
|
||||
const task = db.createTask({ spec: 'recover worker', runId: run.id })
|
||||
const started = db.createStartingWorkerDispatch({
|
||||
taskId: task.id,
|
||||
startOptions: {},
|
||||
runtimeEpoch
|
||||
})
|
||||
db.prepareStartingWorkerAuthority({
|
||||
dispatchId: started.dispatch.id,
|
||||
handle: 'term_worker',
|
||||
paneKey: 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',
|
||||
processIncarnation: 'runtime:pty:1',
|
||||
worktreeId: 'repo::worktree',
|
||||
setupState: 'not_applicable',
|
||||
effects: [{ kind: 'terminal', action: 'created', id: 'term_worker' }]
|
||||
})
|
||||
if (ready) {
|
||||
db.markWorkerDispatchReady(started.dispatch.id)
|
||||
} else {
|
||||
db.markWorkerStartUnknown(started.dispatch.id, 'dispatch_input', 'connection lost')
|
||||
}
|
||||
return { run, task, dispatch: started.dispatch }
|
||||
}
|
||||
|
||||
it('shows and reads only the exact attached worker process', async () => {
|
||||
const { dispatch } = createWorker()
|
||||
|
||||
await expect(
|
||||
call('orchestration.workerShow', { dispatch: dispatch.id })
|
||||
).resolves.toMatchObject({
|
||||
worker: { state: 'ready' },
|
||||
observation: { status: 'running', exactWorker: true },
|
||||
terminal: { handle: 'term_worker' }
|
||||
})
|
||||
await expect(
|
||||
call('orchestration.workerRead', { dispatch: dispatch.id })
|
||||
).resolves.toMatchObject({
|
||||
dispatchId: dispatch.id,
|
||||
terminal: { tail: ['working'] }
|
||||
})
|
||||
})
|
||||
|
||||
it('stops an exact worker whose start receipt is unknown', async () => {
|
||||
const { task, dispatch } = createWorker(runtime.getRuntimeId(), false)
|
||||
|
||||
await expect(
|
||||
call('orchestration.workerStop', { dispatch: dispatch.id })
|
||||
).resolves.toMatchObject({
|
||||
state: 'stopped',
|
||||
processAction: 'closed_agent_terminal'
|
||||
})
|
||||
expect(runtime.closeTerminal).toHaveBeenCalledWith('term_worker')
|
||||
expect(db.getTask(task.id)?.status).toBe('blocked')
|
||||
})
|
||||
|
||||
it('does not adopt or stop a same-looking pane with a new process incarnation', async () => {
|
||||
const { task, dispatch } = createWorker()
|
||||
vi.mocked(runtime.getTerminalProcessIncarnation).mockReturnValue('runtime:pty:2')
|
||||
|
||||
await expect(
|
||||
call('orchestration.workerShow', { dispatch: dispatch.id })
|
||||
).resolves.toMatchObject({
|
||||
worker: { state: 'ready' },
|
||||
observation: { status: 'identity_changed', exactWorker: false },
|
||||
terminal: null
|
||||
})
|
||||
await expect(call('orchestration.workerRead', { dispatch: dispatch.id })).rejects.toMatchObject(
|
||||
{
|
||||
code: 'worker_identity_changed'
|
||||
}
|
||||
)
|
||||
await expect(
|
||||
call('orchestration.workerStop', { dispatch: dispatch.id })
|
||||
).resolves.toMatchObject({
|
||||
state: 'stop_unknown',
|
||||
processAction: 'none'
|
||||
})
|
||||
expect(runtime.closeTerminal).not.toHaveBeenCalled()
|
||||
expect(db.getTask(task.id)?.status).toBe('blocked')
|
||||
})
|
||||
|
||||
it('labels an exact but disconnected worker as exited and does not close it again', async () => {
|
||||
const { task, dispatch } = createWorker()
|
||||
vi.mocked(runtime.showTerminal).mockResolvedValue({
|
||||
handle: 'term_worker',
|
||||
worktreeId: 'repo::worktree',
|
||||
connected: false,
|
||||
writable: false
|
||||
} as never)
|
||||
|
||||
await expect(
|
||||
call('orchestration.workerShow', { dispatch: dispatch.id })
|
||||
).resolves.toMatchObject({
|
||||
observation: { status: 'exited', exactWorker: true },
|
||||
terminal: { handle: 'term_worker', connected: false }
|
||||
})
|
||||
await expect(
|
||||
call('orchestration.workerStop', { dispatch: dispatch.id })
|
||||
).resolves.toMatchObject({
|
||||
state: 'stop_unknown',
|
||||
processAction: 'none'
|
||||
})
|
||||
expect(runtime.closeTerminal).not.toHaveBeenCalled()
|
||||
expect(db.getTask(task.id)?.status).toBe('blocked')
|
||||
})
|
||||
|
||||
it('turns an interrupted start into inspectable unknown after runtime restart', async () => {
|
||||
const run = db.createRun({
|
||||
objective: 'Interrupted start',
|
||||
coordinatorHandle: 'term_coord',
|
||||
coordinatorPaneKey: 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
})
|
||||
const task = db.createTask({ spec: 'interrupted', runId: run.id })
|
||||
const started = db.createStartingWorkerDispatch({
|
||||
taskId: task.id,
|
||||
startOptions: {},
|
||||
runtimeEpoch: 'previous_runtime'
|
||||
})
|
||||
db.recordWorkerStage({
|
||||
dispatchId: started.dispatch.id,
|
||||
stage: 'worktree_creating'
|
||||
})
|
||||
|
||||
await expect(
|
||||
call('orchestration.workerShow', { dispatch: started.dispatch.id })
|
||||
).resolves.toMatchObject({
|
||||
worker: { state: 'start_unknown', stage: 'worktree_creating' },
|
||||
observation: { status: 'unattached', exactWorker: false }
|
||||
})
|
||||
expect(db.getTask(task.id)?.status).toBe('blocked')
|
||||
})
|
||||
|
||||
it('turns an interrupted stop into unknown after runtime restart', async () => {
|
||||
const { task, dispatch } = createWorker('previous_runtime')
|
||||
db.beginWorkerStop(dispatch.id)
|
||||
|
||||
await expect(
|
||||
call('orchestration.workerShow', { dispatch: dispatch.id })
|
||||
).resolves.toMatchObject({
|
||||
worker: { state: 'stop_unknown' }
|
||||
})
|
||||
expect(db.getTask(task.id)?.status).toBe('blocked')
|
||||
})
|
||||
|
||||
it('reconciles a stop_unknown Dispatch from an authoritative remote stopped receipt', async () => {
|
||||
const run = db.createRun({
|
||||
objective: 'Lost remote stop response',
|
||||
coordinatorHandle: 'term_coord',
|
||||
coordinatorPaneKey: 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
})
|
||||
const task = db.createTask({ spec: 'stop remote worker', runId: run.id })
|
||||
const started = db.createStartingWorkerDispatch({
|
||||
taskId: task.id,
|
||||
startOptions: {},
|
||||
runtimeEpoch: runtime.getRuntimeId(),
|
||||
federation: {
|
||||
environmentId: 'environment_windows',
|
||||
environmentName: 'windows',
|
||||
peerFingerprint: 'windows_peer',
|
||||
protocolVersion: 1
|
||||
}
|
||||
})
|
||||
db.markWorkerStartUnknown(started.dispatch.id, 'remote_attach', 'response lost')
|
||||
db.beginWorkerStop(started.dispatch.id)
|
||||
db.markWorkerStopUnknown(started.dispatch.id, 'stop response lost')
|
||||
vi.spyOn(runtime, 'resolveOrchestrationWorkerServer').mockReturnValue({
|
||||
environmentId: 'environment_windows',
|
||||
name: 'windows',
|
||||
peerFingerprint: 'windows_peer'
|
||||
})
|
||||
vi.spyOn(runtime, 'callOrchestrationWorkerServer').mockResolvedValue({
|
||||
runtimeEpoch: 'windows_epoch',
|
||||
attachment: {
|
||||
state: 'stopped',
|
||||
stage: 'process_stopped',
|
||||
last_error: null,
|
||||
worktree_id: 'repo::windows-worktree',
|
||||
terminal_handle: 'term_windows_worker',
|
||||
setup_state: 'running',
|
||||
effects: [],
|
||||
residualResources: []
|
||||
},
|
||||
terminal: { handle: 'term_windows_worker', connected: false },
|
||||
observation: { status: 'exited', exactWorker: true }
|
||||
})
|
||||
|
||||
await expect(
|
||||
call('orchestration.workerShow', { dispatch: started.dispatch.id })
|
||||
).resolves.toMatchObject({
|
||||
worker: { state: 'stopped', stage: 'process_stopped', last_error: null },
|
||||
observation: { status: 'exited', exactWorker: true }
|
||||
})
|
||||
expect(db.getTask(task.id)?.status).toBe('blocked')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,305 @@
|
||||
import { isTuiAgent } from '../../../../shared/tui-agent-config'
|
||||
import type { TuiAgent } from '../../../../shared/types'
|
||||
import { buildDispatchPreamble } from '../../orchestration/preamble'
|
||||
import { OrchestrationError } from '../../orchestration/orchestration-error'
|
||||
import { defineMethod, type RpcMethod } from '../core'
|
||||
import { startFederatedWorker } from './orchestration-federated-worker-start'
|
||||
import { assertOrchestrationWorktreeCreationSupported } from './orchestration-folder-worktree-placement'
|
||||
import { WorkerStartParams } from './orchestration-worker-start-schema'
|
||||
import {
|
||||
createWorkerWorktree,
|
||||
monitorWorkerSetup,
|
||||
type WorkerEffect,
|
||||
type WorkerSetupReceipt
|
||||
} from './orchestration-worker-topology'
|
||||
import {
|
||||
persistGatedSetupSpawnFailure,
|
||||
persistWorkerReadinessStage,
|
||||
persistWorkerSetupWaitOutcome
|
||||
} from './orchestration-worker-setup-gate'
|
||||
import { failWorkerStartWithReceipt } from './orchestration-worker-start-receipt'
|
||||
|
||||
export const ORCHESTRATION_WORKER_START_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.workerStart',
|
||||
params: WorkerStartParams,
|
||||
handler: async (params, { runtime, orchestrationMutation }) => {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const coordinatorPane = runtime.getTerminalPaneKey(params.from)
|
||||
const run = coordinatorPane ? db.getCurrentRunForPane(coordinatorPane) : undefined
|
||||
if (!run || (params.run && params.run !== run.id)) {
|
||||
throw new OrchestrationError(
|
||||
'consumer_fenced',
|
||||
'worker-start requires the coordinator terminal currently bound to the Task Run.'
|
||||
)
|
||||
}
|
||||
const task = db.getTask(params.task)
|
||||
if (!task || task.run_id !== run.id) {
|
||||
throw new OrchestrationError(
|
||||
'task_not_found',
|
||||
`Task ${params.task} was not found in Run ${run.id}.`
|
||||
)
|
||||
}
|
||||
|
||||
if (params.on) {
|
||||
return startFederatedWorker({
|
||||
params,
|
||||
runtime,
|
||||
db,
|
||||
runId: run.id,
|
||||
task,
|
||||
orchestrationMutation
|
||||
})
|
||||
}
|
||||
|
||||
const requestedWorktree = params.worktree ?? 'current'
|
||||
const createsWorktree =
|
||||
requestedWorktree === 'new-child' || requestedWorktree === 'new-top-level'
|
||||
if (params.terminal && params.agent) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'--terminal reuses an existing agent and cannot combine with --agent.'
|
||||
)
|
||||
}
|
||||
if (createsWorktree && params.terminal) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'--terminal cannot combine with new-worktree creation.'
|
||||
)
|
||||
}
|
||||
if (createsWorktree && !params.name) {
|
||||
throw new OrchestrationError('invalid_argument', 'New worktrees require --name.')
|
||||
}
|
||||
if (!createsWorktree && (params.name || params.repo || params.baseBranch || params.setup)) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'Creation and setup options apply only to new-child or new-top-level worktrees.'
|
||||
)
|
||||
}
|
||||
const agent = params.agent
|
||||
if (!params.terminal && (!agent || !isTuiAgent(agent))) {
|
||||
throw new OrchestrationError(
|
||||
'agent_unconfigured',
|
||||
'A configured --agent is required when worker-start creates a terminal.'
|
||||
)
|
||||
}
|
||||
if (agent) {
|
||||
runtime.validateOrchestrationAgentLauncher(agent as TuiAgent)
|
||||
}
|
||||
|
||||
const coordinatorTerminal = await runtime.showTerminal(params.from)
|
||||
const coordinatorWorktree = await runtime.showManagedWorktree(
|
||||
`id:${coordinatorTerminal.worktreeId}`
|
||||
)
|
||||
if (createsWorktree) {
|
||||
await assertOrchestrationWorktreeCreationSupported({
|
||||
runtime,
|
||||
repoSelector: params.repo ?? coordinatorWorktree.repoId,
|
||||
existingPlacement: 'current or an exact existing folder workspace'
|
||||
})
|
||||
}
|
||||
let resolvedWorktree = createsWorktree
|
||||
? undefined
|
||||
: requestedWorktree === 'current'
|
||||
? coordinatorWorktree
|
||||
: await runtime.showManagedWorktree(requestedWorktree)
|
||||
let explicitTerminal
|
||||
if (params.terminal) {
|
||||
explicitTerminal = await runtime.showTerminal(params.terminal)
|
||||
if (explicitTerminal.worktreeId !== resolvedWorktree?.id) {
|
||||
throw new OrchestrationError(
|
||||
'terminal_worktree_mismatch',
|
||||
`Terminal ${params.terminal} does not belong to worktree ${resolvedWorktree?.id}.`
|
||||
)
|
||||
}
|
||||
if (!(await runtime.isTerminalRunningAgent(params.terminal))) {
|
||||
throw new OrchestrationError(
|
||||
'agent_unconfigured',
|
||||
`Terminal ${params.terminal} is not running a recognized agent.`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const startOptions = {
|
||||
worktree: requestedWorktree,
|
||||
resolvedWorktreeId: resolvedWorktree?.id ?? null,
|
||||
name: params.name ?? null,
|
||||
repo: params.repo ?? (createsWorktree ? coordinatorWorktree.repoId : null),
|
||||
baseBranch: params.baseBranch ?? null,
|
||||
terminal: params.terminal ?? null,
|
||||
agent: agent ?? null,
|
||||
timeoutMs: params.timeoutMs ?? 60_000,
|
||||
setup: createsWorktree ? (params.setup ?? 'run') : 'not_applicable',
|
||||
setupSource: createsWorktree
|
||||
? params.setup
|
||||
? 'explicit_request'
|
||||
: 'orchestration_default'
|
||||
: 'existing_worktree'
|
||||
}
|
||||
const started = db.createStartingWorkerDispatch({
|
||||
taskId: task.id,
|
||||
retryOf: params.retryOf,
|
||||
startOptions,
|
||||
runtimeEpoch: runtime.getRuntimeId(),
|
||||
mutationReceipt: orchestrationMutation
|
||||
})
|
||||
const effects: WorkerEffect[] = []
|
||||
if (resolvedWorktree) {
|
||||
effects.push(
|
||||
{ kind: 'worktree', action: 'reused', id: resolvedWorktree.id },
|
||||
{ kind: 'setup', action: 'not_applicable', state: 'not_applicable' }
|
||||
)
|
||||
}
|
||||
let terminalHandle = params.terminal
|
||||
let failedStage = 'terminal_create'
|
||||
let setupReceipt: WorkerSetupReceipt = {
|
||||
requested: 'not_applicable',
|
||||
effective: 'not_applicable',
|
||||
source: 'existing_worktree',
|
||||
hookFound: false,
|
||||
startupPolicy: 'start-immediately',
|
||||
state: 'not_applicable'
|
||||
}
|
||||
try {
|
||||
if (createsWorktree) {
|
||||
failedStage = 'worktree_create'
|
||||
const created = await createWorkerWorktree({
|
||||
runtime,
|
||||
db,
|
||||
dispatchId: started.dispatch.id,
|
||||
requestedWorktree,
|
||||
coordinatorWorktree,
|
||||
params,
|
||||
agent: agent as TuiAgent,
|
||||
effects
|
||||
})
|
||||
resolvedWorktree = created.worktree
|
||||
terminalHandle = created.terminalHandle
|
||||
setupReceipt = created.setupReceipt
|
||||
} else if (!terminalHandle) {
|
||||
db.recordWorkerStage({
|
||||
dispatchId: started.dispatch.id,
|
||||
stage: 'terminal_creating',
|
||||
worktreeId: resolvedWorktree!.id,
|
||||
effects
|
||||
})
|
||||
const terminal = await runtime.createTerminal(`id:${resolvedWorktree!.id}`, {
|
||||
command: agent,
|
||||
title: `worker-${task.id}`,
|
||||
presentation: 'background'
|
||||
})
|
||||
terminalHandle = terminal.handle
|
||||
effects.push({
|
||||
kind: 'terminal',
|
||||
role: 'agent',
|
||||
action: 'created',
|
||||
id: terminal.handle
|
||||
})
|
||||
} else {
|
||||
effects.push({
|
||||
kind: 'terminal',
|
||||
role: 'agent',
|
||||
action: 'reused',
|
||||
id: terminalHandle
|
||||
})
|
||||
}
|
||||
if (!resolvedWorktree || !terminalHandle) {
|
||||
throw new Error('Worker topology did not resolve an agent terminal and worktree.')
|
||||
}
|
||||
const setupStage = {
|
||||
db,
|
||||
dispatchId: started.dispatch.id,
|
||||
worktreeId: resolvedWorktree.id,
|
||||
terminalHandle,
|
||||
setup: setupReceipt,
|
||||
effects
|
||||
}
|
||||
if (persistGatedSetupSpawnFailure(setupStage)) {
|
||||
failedStage = 'setup_start'
|
||||
throw new Error('Setup terminal failed to start before the gated agent launch.')
|
||||
}
|
||||
persistWorkerReadinessStage(setupStage)
|
||||
|
||||
failedStage = 'agent_readiness'
|
||||
const wait = await runtime.waitForTerminal(terminalHandle, {
|
||||
condition: 'tui-idle',
|
||||
timeoutMs: params.timeoutMs ?? 60_000
|
||||
})
|
||||
persistWorkerSetupWaitOutcome({ ...setupStage, wait })
|
||||
if (!wait.satisfied) {
|
||||
if (setupReceipt.state === 'failed') {
|
||||
failedStage = 'setup_wait'
|
||||
}
|
||||
throw new Error(
|
||||
wait.blockedReason
|
||||
? `Agent startup blocked: ${wait.blockedReason}`
|
||||
: `Agent did not become ready (${wait.status}).`
|
||||
)
|
||||
}
|
||||
const paneKey = runtime.getTerminalPaneKey(terminalHandle)
|
||||
const processIncarnation = runtime.getTerminalProcessIncarnation(terminalHandle)
|
||||
if (!paneKey || !processIncarnation) {
|
||||
throw new Error('stable_pane_required')
|
||||
}
|
||||
const capability = db.prepareStartingWorkerAuthority({
|
||||
dispatchId: started.dispatch.id,
|
||||
handle: terminalHandle,
|
||||
paneKey,
|
||||
processIncarnation,
|
||||
worktreeId: resolvedWorktree.id,
|
||||
effects,
|
||||
setupState: setupReceipt.state
|
||||
})
|
||||
|
||||
failedStage = 'dispatch_input'
|
||||
const preamble = buildDispatchPreamble({
|
||||
taskId: task.id,
|
||||
dispatchId: started.dispatch.id,
|
||||
taskSpec: task.spec,
|
||||
coordinatorHandle: params.from,
|
||||
workerHandle: terminalHandle,
|
||||
dispatchCapability: capability,
|
||||
devMode: params.devMode,
|
||||
cliCommand: runtime.getTerminalOrchestrationCliCommand(terminalHandle)
|
||||
})
|
||||
await runtime.sendTerminalAgentPrompt(terminalHandle, preamble)
|
||||
effects.push({
|
||||
kind: 'dispatch_input',
|
||||
role: 'agent',
|
||||
id: terminalHandle,
|
||||
state: 'accepted'
|
||||
})
|
||||
const worker = db.markWorkerDispatchReady(started.dispatch.id, effects)
|
||||
monitorWorkerSetup({
|
||||
runtime,
|
||||
db,
|
||||
runId: run.id,
|
||||
dispatchId: started.dispatch.id,
|
||||
setupReceipt,
|
||||
effects
|
||||
})
|
||||
return {
|
||||
runId: run.id,
|
||||
taskId: task.id,
|
||||
dispatchId: started.dispatch.id,
|
||||
state: worker.state,
|
||||
stage: worker.stage,
|
||||
setup: setupReceipt,
|
||||
timeoutMs: params.timeoutMs ?? 60_000,
|
||||
effects,
|
||||
residualResources: []
|
||||
}
|
||||
} catch (error) {
|
||||
return failWorkerStartWithReceipt({
|
||||
db,
|
||||
runId: run.id,
|
||||
taskId: task.id,
|
||||
dispatchId: started.dispatch.id,
|
||||
failedStage,
|
||||
error,
|
||||
setup: setupReceipt
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user