Files
archived-orca/tests/e2e/crew-parent-rpc.unit.test.ts
T
Brennan Benson 0fa5dae2f9 Read who each agent works with: its manager, workers and peers (#34890)
* Nest chat-UI orchestration workers under the agent that started them

Main's lineage projection only walked terminal panes, so workers running
in the chat UI never got a parent link and listed flat in the sidebar.
It now also projects chat workers, keyed by their visible chat row, and
resolves a chat creator or coordinator to that chat's visible row
instead of its handle or private mailbox pane key.

* Fix public worker lineage across assignment and row identities

* Complete terminal lineage provenance and bound active session selection

* Repair lineage test runtime boundaries and SQLite counters

* Provide read-only crew snapshots for each agent

* Batch public lineage verification after exact recency selection

* Derive crew relations once per meaningful host change

* Remove package manager lockfile churn from hook

* Use checked runtime values in lineage integration tests

* Document the trusted Dispatch SQL row boundary

* Keep lineage integration imports within their test programs

* Load native lineage fixtures before test execution

* test: complete lineage inputs in runtime and sidebar fixtures

* test: seed benchmark facts from active dispatches

* test: replace partial orchestration DB casts with typed fixtures

* test: complete stale-leaf mailbox fixture session input

* Derive durable crew parents from retained assignment proof

* fix(test): render worker lineage fixture with production list

* Add scoped terminal identity acquisition and preserve crew source wakes

* Share raw crew identity inputs through scoped production readers

* Exercise crew generation retirement through actual source owners

* Retire crew inputs on consumed ownership and visibility writes

* Use typed crew mutation and fixture access

* Repair crew fixture and RPC type contracts

* Align crew integration fixtures and RPC parameter contracts

* Encapsulate terminal identity mutations and captured reader contracts

* Seed terminal identity fixtures through canonical mutations

* Fix terminal identity fixture return type

* Cover terminal identity lifecycle schedules

* Align terminal fixtures with canonical identity sources

* Repair runtime fixture source contracts

* Use checked database fixtures for federation contracts

* Update crew source inventories and exit fixtures

* Preserve crew setup outcomes at existing subscription owners

* Match managed restore fixture to its nullable async return type

* Keep absent setup observations distinct from undefined failures

* Drive pending Crew questions from existing metadata

* Preserve nested pairing repair outcomes for shared callers

* Route attached workers to explicit local recipients

* Type Crew pending-question measurement receipts

* Match SSH repair fixture target absence to store contract

* Bound cold terminal layout construction and finite pane acquisition

* test: use public runtime identity in pane acquisition fixture

* Avoid repeated searches in cold workspace layout loading

* Verify cold loader fault identity and hook claimant effects

* Revert "Route attached workers to explicit local recipients"

This reverts commit f1335d1c06.

Keep attached workers on the existing Run-home routing path for this change.

* Omit crew peer addresses outside the active home route

* Keep crew retries on the verified runtime session

* Bound cold layout retirement and recorded-key construction

* Verify original cold layout failure identity

* fix: preserve surviving layout split references

* test: use typed retirement instrumentation properties

* test: preserve pane and retirement fixture contracts with checked types

* Prepare Crew record admission and wake identity changes

* Derive Crew recipient actions from current target owners

* Keep nested Crew process facts within selected acquisition

* Defer Crew legacy facts to consumers and complete raw coverage on success

* Use deterministic time in Crew command fixtures

* Document schema-owned Dispatch row assertions

* test: align Crew authority fixtures with typed project boundaries

* test: place Crew CLI integration in cross-surface project

* Type retained identity test meters with canonical source maps

* Document suffix Dispatch row boundary and preserve fixture unbinding

* test: migrate Crew authority arguments and mailbox observations

* Derive Crew attention and actions from complete recipient authority

* Fix Crew public-command fixture type contracts

* Align Crew fixtures with runtime reader and routing contracts

* Narrow receiving fixture calls to unary RPC methods

* Age pending question fixtures from every actual answer timestamp

* Complete Crew public-command workspace fixture result

* Test delegated helper follow-up through Crew advertised address

* Qualify Crew follow-up addresses through shared command admission

* Complete finite follow-up authority and lifetime evidence

* Assert exact remote authority acquisition error identity

* Consolidate Crew SQL test fixture imports

* Trim Crew read-model tests to the high-impact set

Keep the real CLI/RPC/database command paths, one regression per review-found bug, the cross-version contracts and one N vs 10N operation contract per scaling piece. Drop permutation matrices, equivalence oracles, near-duplicate scenarios and diagnostic output, and return the SSH, managed-server and WSL test files to main, since their production changes were reverted earlier in this PR.

* Drop diagnostic output and a duplicate error case from Crew tests

Remove two leftover console.log diagnostics, an unused 2x2 sample matrix and unused return fields in the follow-up cost contract, and the subscription AbortError serialization case that the subscription identity and preload tests already cover.

* Pass the recorded-leaf reader in main's check-details loader test
2026-11-01 13:28:53 -08:00

204 lines
8.2 KiB
TypeScript

import '../../src/main/runtime/rpc/unused-default-rpc-methods.test-fixture'
import { afterEach, expect, it, vi } from 'vitest'
import { z } from 'zod'
import { dispatch } from '../../src/cli/dispatch'
import { RuntimeClient, RuntimeClientError } from '../../src/cli/runtime-client'
import { ORCHESTRATION_CONTRACT_VERSION } from '../../src/shared/protocol-version'
import {
createSessionCallerHarness,
orchestrationRequest
} from '../../src/main/runtime/rpc/orchestration-session-caller-test-fixture'
import { configureFederationWorkerRuntime } from '../../src/main/runtime/rpc/methods/orchestration/federation/federation-runtime.test-support'
import { buildCrewSnapshot } from '../../src/main/runtime/orchestration/crew/crew-read-model'
const hostRef = vi.hoisted((): { current: unknown } => ({ current: null }))
vi.mock('../../src/main/native-chat/agent-session-wire/structured-agent-session-registry', () => ({
getStructuredAgentSessionHost: () => hostRef.current
}))
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllEnvs()
})
it('composes actual local and paired RPC claims in either order and preserves detached CLI refusal', async () => {
for (const order of ['local-first', 'remote-first']) {
const h = createSessionCallerHarness(hostRef)
try {
vi.stubEnv('ORCA_AGENT_SESSION_ID', '')
vi.stubEnv('ORCA_PANE_KEY', '')
configureFederationWorkerRuntime(h.runtime)
vi.spyOn(h.runtime, 'ensureOrchestrationFederationRelay').mockImplementation(() => {})
const pane = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
const handle = 'term_windows_worker'
const coordinatorPane = 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
vi.mocked(h.runtime.getTerminalPaneKey).mockImplementation((value) =>
value === 'term_coord' ? coordinatorPane : value === handle ? pane : null
)
const run = h.db.createRun({
objective: 'Local manager',
coordinatorHandle: 'term_coord',
coordinatorPaneKey: coordinatorPane
})
const task = h.db.createTask({ runId: run.id, spec: 'Existing terminal' })
h.db.updateTaskStatus(task.id, 'ready')
const local = () =>
h.dispatch(
orchestrationRequest('orchestration.dispatch', {
from: 'term_coord',
run: run.id,
task: task.id,
to: handle,
inject: false
})
)
const remote = () =>
h.dispatch(
orchestrationRequest('orchestration.federationAttachStart', {
dispatchId: 'ctx_remote_parent',
runId: 'run_remote_home',
taskId: 'task_remote_parent',
taskSpec: 'Paired worker',
protocolVersion: ORCHESTRATION_CONTRACT_VERSION,
worktree: 'new-top-level',
repo: 'id:windows-repo',
name: 'worker',
agent: 'codex'
})
)
const results =
order === 'local-first' ? [await local(), await remote()] : [await remote(), await local()]
for (const result of results) {
expect(result, JSON.stringify(result)).toMatchObject({ ok: true })
}
const deps = {
db: h.db,
hostKey: 'local',
retainedDbExists: true,
records: null,
statuses: [],
liveHandle: (value: string) => value === handle || value === 'term_coord',
handleForPane: (value: string) => (value === pane ? handle : null),
paneForHandle: (value: string) => (value === handle ? pane : null),
processForHandle: (value: string) => h.runtime.getTerminalProcessIncarnation(value),
name: () => 'Manager'
}
const parents = buildCrewSnapshot(handle, deps).sections.managedBy
const attachment = h.db.getRemoteDispatchAttachment('ctx_remote_parent')
if (!attachment) {
throw new Error('Expected the actual paired worker attachment')
}
const localKey = JSON.stringify(['local', 'term_coord'])
const homeKey = JSON.stringify([attachment.home_peer_fingerprint, 'run:run_remote_home'])
expect(parents.map((row) => row.partyKey).sort()).toEqual([localKey, homeKey].sort())
const localParent = parents.find((row) => row.partyKey === localKey)
const homeParent = parents.find((row) => row.partyKey === homeKey)
expect(localParent).toMatchObject({
role: 'manager',
openTarget: { kind: 'terminal', handle: 'term_coord' }
})
expect(localParent).not.toHaveProperty('sendAddress')
expect(homeParent).toMatchObject({ role: 'manager', sendAddress: 'run:run_remote_home' })
expect(homeParent?.openTarget).toBeUndefined()
if (!homeParent?.sendAddress) {
throw new Error('Expected the published attached Run-home address')
}
const delivery = vi.spyOn(h.runtime, 'deliverPendingMessagesForHandle')
const notification = vi.spyOn(h.runtime, 'notifyMessageArrived')
const effects = () => ({
messages: h.db.getInbox(),
relays: h.db.listFederationRelay({
dispatchId: 'ctx_remote_parent',
direction: 'to_home',
afterSequence: 0
}),
deliveries: delivery.mock.calls.length,
notifications: notification.mock.calls.length
})
const receipts: unknown[] = []
const client = new RuntimeClient('/tmp/crew-parent-routing', 1000, null, null)
vi.spyOn(client, 'call').mockImplementation(async (method: string, params: unknown) => {
const response = await h.dispatch(
orchestrationRequest(method, z.record(z.string(), z.unknown()).parse(params))
)
if (!response.ok) {
throw new RuntimeClientError(response.error.code, response.error.message)
}
receipts.push(response.result)
return {
...response,
result: response.result,
_meta: { runtimeId: 'crew-parent-test' }
}
})
const beforeWrongLocal = effects()
await expect(
dispatch(['orchestration', 'send'], {
client,
flags: new Map([
['from', handle],
['to', 'term_coord'],
['subject', 'Attached local parent'],
['body', 'Local must refuse']
]),
cwd: '/tmp',
json: true
})
).rejects.toMatchObject({
code: 'invalid_argument',
message: 'Federated Dispatch messages route to their Run home; omit --to and --run.'
})
expect(effects()).toEqual(beforeWrongLocal)
const beforeHome = effects()
await dispatch(['orchestration', 'send'], {
client,
flags: new Map([
['from', handle],
['to', homeParent.sendAddress],
['subject', 'Attached home parent'],
['body', 'Hello home'],
['type', 'status']
]),
cwd: '/tmp',
json: true
})
expect(receipts.at(-1)).toMatchObject({
relay: { dispatchId: 'ctx_remote_parent', destination: 'run_home', accepted: true }
})
const afterHome = effects()
expect(afterHome.messages).toEqual(beforeHome.messages)
expect(afterHome.deliveries).toBe(beforeHome.deliveries)
expect(afterHome.notifications).toBe(beforeHome.notifications)
expect(afterHome.relays.slice(0, beforeHome.relays.length)).toEqual(beforeHome.relays)
expect(afterHome.relays).toHaveLength(beforeHome.relays.length + 1)
const homeRelay = afterHome.relays.at(-1)
expect(homeRelay).toMatchObject({ dispatch_id: 'ctx_remote_parent', direction: 'to_home' })
expect(JSON.parse(homeRelay!.payload)).toMatchObject({
from: handle,
subject: 'Attached home parent',
body: 'Hello home',
type: 'status'
})
const beforeDetached = effects()
await expect(
dispatch(['orchestration', 'send'], {
client,
flags: new Map([
['from', 'term_detached'],
['to', 'run:run_remote_home'],
['subject', 'Detached parent'],
['body', 'Hello']
]),
cwd: '/tmp',
json: true
})
).rejects.toMatchObject({ code: 'run_home_unreachable' })
expect(
h.db.db.prepare("SELECT sequence FROM messages WHERE subject = 'Detached parent'").all()
).toEqual([])
expect(effects()).toEqual(beforeDetached)
} finally {
h.close()
}
}
})