Files
orca/src/preload/runtime-environment-subscriptions.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

255 lines
8.5 KiB
TypeScript

import { isCrewSetupFact } from '../shared/runtime-environment-subscription-setup'
import type {
CrewSubscriptionAttemptArgs,
CrewSubscriptionAttemptCallbacks,
CrewSubscriptionSetupResult
} from '../shared/runtime-environment-subscription-setup'
import type { RuntimeRpcResponse } from '../shared/runtime-rpc-envelope'
type RuntimeEnvironmentSubscribeArgs = {
subscriptionId?: string
selector: string
method: string
params?: unknown
timeoutMs?: number
expectedEnvironmentPairingRevision?: number
expectedEnvironmentRuntimeId?: string
}
type RuntimeEnvironmentSubscriptionCallbacks = {
onResponse: (response: RuntimeRpcResponse<unknown>) => void
onBinary?: (bytes: Uint8Array<ArrayBufferLike>) => void
onError?: (error: { code: string; message: string }) => void
onClose?: () => void
crewAttempt?: true
}
export type RuntimeEnvironmentSubscriptionHandle = {
unsubscribe: () => void
sendBinary: (bytes: Uint8Array<ArrayBufferLike>) => void
}
type RuntimeEnvironmentSubscriptionEvent =
| { subscriptionId: string; type: 'response'; response: RuntimeRpcResponse<unknown> }
| { subscriptionId: string; type: 'binary'; bytes: Uint8Array<ArrayBufferLike> }
| { subscriptionId: string; type: 'error'; code: string; message: string }
| { subscriptionId: string; type: 'close' }
type RuntimeEnvironmentSubscriptionIpc = {
invoke: (channel: string, args: unknown) => Promise<unknown>
send: (channel: string, args: unknown) => void
on: (
channel: string,
listener: (event: unknown, payload: RuntimeEnvironmentSubscriptionEvent) => void
) => void
removeListener: (
channel: string,
listener: (event: unknown, payload: RuntimeEnvironmentSubscriptionEvent) => void
) => void
}
const SUBSCRIPTION_EVENT_CHANNEL = 'runtimeEnvironments:subscriptionEvent'
// Share one IPC listener so reconnects cannot accumulate listeners retaining renderer state.
type RuntimeEnvironmentSubscriptionDispatcher = {
callbacks: Map<string, RuntimeEnvironmentSubscriptionCallbacks>
listener: (event: unknown, payload: RuntimeEnvironmentSubscriptionEvent) => void
}
const subscriptionDispatchers = new WeakMap<
RuntimeEnvironmentSubscriptionIpc,
RuntimeEnvironmentSubscriptionDispatcher
>()
function releaseIdleDispatcher(
ipc: RuntimeEnvironmentSubscriptionIpc,
callbacks: Map<string, RuntimeEnvironmentSubscriptionCallbacks>,
listener: RuntimeEnvironmentSubscriptionDispatcher['listener']
): void {
if (callbacks.size > 0) {
return
}
ipc.removeListener(SUBSCRIPTION_EVENT_CHANNEL, listener)
subscriptionDispatchers.delete(ipc)
}
function releaseSubscription(
ipc: RuntimeEnvironmentSubscriptionIpc,
dispatcher: RuntimeEnvironmentSubscriptionDispatcher,
subscriptionId: string
): void {
if (!dispatcher.callbacks.delete(subscriptionId)) {
return
}
releaseIdleDispatcher(ipc, dispatcher.callbacks, dispatcher.listener)
}
function getOrCreateDispatcher(
ipc: RuntimeEnvironmentSubscriptionIpc
): RuntimeEnvironmentSubscriptionDispatcher {
const existing = subscriptionDispatchers.get(ipc)
if (existing) {
return existing
}
const callbacks = new Map<string, RuntimeEnvironmentSubscriptionCallbacks>()
const listener = (_event: unknown, event: RuntimeEnvironmentSubscriptionEvent): void => {
const subscriptionCallbacks = callbacks.get(event.subscriptionId)
if (!subscriptionCallbacks) {
return
}
if (event.type === 'response') {
subscriptionCallbacks.onResponse(event.response)
} else if (event.type === 'binary') {
subscriptionCallbacks.onBinary?.(event.bytes)
} else if (event.type === 'error') {
// Shared-control subscriptions survive errors and reconnects.
subscriptionCallbacks.onError?.({ code: event.code, message: event.message })
} else {
// Release first so a throwing or reentrant callback cannot retain renderer state.
callbacks.delete(event.subscriptionId)
releaseIdleDispatcher(ipc, callbacks, listener)
subscriptionCallbacks.onClose?.()
}
}
const dispatcher: RuntimeEnvironmentSubscriptionDispatcher = { callbacks, listener }
subscriptionDispatchers.set(ipc, dispatcher)
ipc.on(SUBSCRIPTION_EVENT_CHANNEL, listener)
return dispatcher
}
function createRuntimeEnvironmentSubscriptionId(): string {
const randomUuid = globalThis.crypto?.randomUUID
if (typeof randomUuid === 'function') {
return randomUuid.call(globalThis.crypto)
}
return `sub-${Date.now()}-${Math.random().toString(36).slice(2)}`
}
export async function subscribeRuntimeEnvironmentFromPreload(
ipc: RuntimeEnvironmentSubscriptionIpc,
args: RuntimeEnvironmentSubscribeArgs,
callbacks: RuntimeEnvironmentSubscriptionCallbacks,
createSubscriptionId = createRuntimeEnvironmentSubscriptionId
): Promise<RuntimeEnvironmentSubscriptionHandle> {
const subscriptionId = args.subscriptionId ?? createSubscriptionId()
// Route before invoking: streaming RPCs can emit frames before the subscribe reply.
const dispatcher = getOrCreateDispatcher(ipc)
if (dispatcher.callbacks.has(subscriptionId)) {
throw new Error('Runtime environment subscription id already exists')
}
dispatcher.callbacks.set(subscriptionId, callbacks)
const releaseCurrentSubscription = (): void => {
if (dispatcher.callbacks.get(subscriptionId) === callbacks) {
releaseSubscription(ipc, dispatcher, subscriptionId)
}
}
try {
const result = (await ipc.invoke('runtimeEnvironments:subscribe', {
...args,
subscriptionId
})) as { subscriptionId: string; requestId: string }
if (result.subscriptionId !== subscriptionId) {
releaseCurrentSubscription()
throw new Error('Runtime environment subscription id mismatch')
}
} catch (error) {
releaseCurrentSubscription()
throw error
}
return {
unsubscribe: () => {
releaseCurrentSubscription()
void ipc.invoke('runtimeEnvironments:unsubscribe', { subscriptionId })
},
sendBinary: (bytes) => {
ipc.send('runtimeEnvironments:subscriptionBinary', { subscriptionId, bytes })
}
}
}
/** Cancel only the opt-in local registration; ordinary finite subscribers keep their contract. */
export function cancelRuntimeEnvironmentSubscriptionFromPreload(
ipc: RuntimeEnvironmentSubscriptionIpc,
subscriptionId: string
): Promise<void> {
const dispatcher = subscriptionDispatchers.get(ipc)
if (dispatcher?.callbacks.get(subscriptionId)?.crewAttempt) {
releaseSubscription(ipc, dispatcher, subscriptionId)
}
return ipc.invoke('runtimeEnvironments:unsubscribe', { subscriptionId }).then(() => undefined)
}
export async function subscribeCrewAttemptFromPreload(
ipc: RuntimeEnvironmentSubscriptionIpc,
args: CrewSubscriptionAttemptArgs,
callbacks: CrewSubscriptionAttemptCallbacks
): Promise<CrewSubscriptionSetupResult> {
const { subscriptionId } = args
const dispatcher = getOrCreateDispatcher(ipc)
if (dispatcher.callbacks.has(subscriptionId)) {
return {
subscriptionId,
ok: false,
failure: {
message: 'Runtime environment subscription id already exists',
fact: { kind: 'input' }
}
}
}
const registration: RuntimeEnvironmentSubscriptionCallbacks = { ...callbacks, crewAttempt: true }
dispatcher.callbacks.set(subscriptionId, registration)
const release = (): void => {
if (dispatcher.callbacks.get(subscriptionId) === registration) {
releaseSubscription(ipc, dispatcher, subscriptionId)
}
}
try {
const result: unknown = await ipc.invoke('runtimeEnvironments:subscribe', {
...args,
setupResult: 'crew'
})
if (!isCrewSubscriptionSetupResult(result) || result.subscriptionId !== subscriptionId) {
throw new Error('Invalid crew subscription setup result')
}
if (!result.ok) {
release()
}
return result
} catch (error) {
release()
throw error
}
}
function isCrewSubscriptionSetupResult(value: unknown): value is CrewSubscriptionSetupResult {
if (
typeof value !== 'object' ||
value === null ||
!('subscriptionId' in value) ||
typeof value.subscriptionId !== 'string' ||
!('ok' in value)
) {
return false
}
if (value.ok === true) {
return true
}
if (
value.ok !== false ||
!('failure' in value) ||
typeof value.failure !== 'object' ||
value.failure === null
) {
return false
}
const failure = value.failure
return (
'message' in failure &&
typeof failure.message === 'string' &&
(!('code' in failure) || typeof failure.code === 'string') &&
'fact' in failure &&
isCrewSetupFact(failure.fact)
)
}