From 3b81b86233d926eb59946cfbe5aca3d1fe8f743e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:50:42 -0700 Subject: [PATCH 001/164] 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. --- .../construction/runtime-service-state.ts | 10 ++- .../db/hot-path-statement-compilation.test.ts | 4 +- .../structured-session-lineage.ts | 14 +++ ...ime-agent-orchestration-projection.test.ts | 87 +++++++++++++++++++ .../runtime-agent-orchestration-projection.ts | 68 ++++++++++++--- 5 files changed, 168 insertions(+), 15 deletions(-) create mode 100644 src/main/runtime/runtime-agent-orchestration-projection.test.ts diff --git a/src/main/runtime/construction/runtime-service-state.ts b/src/main/runtime/construction/runtime-service-state.ts index 8d057b5aad3c..797a6c72dd90 100644 --- a/src/main/runtime/construction/runtime-service-state.ts +++ b/src/main/runtime/construction/runtime-service-state.ts @@ -44,6 +44,11 @@ import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' import { mainListsEveryPane } from '../terminal/surface/main-terminal-surfaces' import { TUI_IDLE_QUIESCENCE_MS } from '../orca-runtime-postlude' import { screenClearsBlockedTail } from '../blocked-tail-screen-clear' +import { structuredWorkerIdentities } from '../structured-worker-identity' +import { + lineageDisplayPaneKey, + readAgentSessionRecordStore +} from '../orchestration/structured-session-lineage' export abstract class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWithRuntimeId { protected readonly stopRequestedPtyIds = new Set() @@ -124,7 +129,10 @@ export abstract class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWith getHandleForPaneKey: (paneKey) => this.getTerminalHandleForPaneKey(paneKey), getPaneKey: (handle) => this.getPaneKeyForTerminalHandle(handle), getDispatchAuthority: (handle) => this.getOrchestrationDispatchAuthority(handle), - getAgentStatusSnapshot: () => this.getOrchestrationFleetAgentStatusSnapshot() + getAgentStatusSnapshot: () => this.getOrchestrationFleetAgentStatusSnapshot(), + getStructuredWorkers: () => structuredWorkerIdentities.list(), + getSessionDisplayPaneKey: (orcaSessionId) => + lineageDisplayPaneKey(readAgentSessionRecordStore(), orcaSessionId) }) protected readonly terminalList = new RuntimeTerminalList({ diff --git a/src/main/runtime/orchestration/db/hot-path-statement-compilation.test.ts b/src/main/runtime/orchestration/db/hot-path-statement-compilation.test.ts index 6730976196d0..d8d75f57e72b 100644 --- a/src/main/runtime/orchestration/db/hot-path-statement-compilation.test.ts +++ b/src/main/runtime/orchestration/db/hot-path-statement-compilation.test.ts @@ -103,7 +103,9 @@ function buildProjection(db: OrchestrationDb): RuntimeAgentOrchestrationProjecti processIncarnation: 'inc_1' } as OrchestrationCompatibilityTerminalAuthority) : null, - getAgentStatusSnapshot: () => [] + getAgentStatusSnapshot: () => [], + getStructuredWorkers: () => [], + getSessionDisplayPaneKey: () => null }) } diff --git a/src/main/runtime/orchestration/structured-session-lineage.ts b/src/main/runtime/orchestration/structured-session-lineage.ts index d1b5a6e46954..b65428c84761 100644 --- a/src/main/runtime/orchestration/structured-session-lineage.ts +++ b/src/main/runtime/orchestration/structured-session-lineage.ts @@ -2,6 +2,10 @@ import type { AgentSessionConversationView } from '../../../shared/agent-session-conversation-view' import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/structured-agent-session-registry' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../../shared/structured-agent-session-projection' import { structuredWorkerHostScope } from '../structured-worker-identity' export type AgentSessionRecordReader = { @@ -106,3 +110,13 @@ export function lineageLiveSession( const running = resolveLineageRunningSession(store, sessionId) return running.kind === 'unverifiable' ? null : running.record } + +/** The chat row a session's conversation shows under now; an unverifiable lineage keeps its own row. */ +export function lineageDisplayPaneKey( + store: AgentSessionRecordReader | null, + sessionId: string +): string { + const running = resolveLineageRunningSession(store, sessionId) + const current = running.kind === 'unverifiable' ? sessionId : running.sessionId + return structuredAgentSessionPaneKey(structuredAgentSessionTabId(current), current) +} diff --git a/src/main/runtime/runtime-agent-orchestration-projection.test.ts b/src/main/runtime/runtime-agent-orchestration-projection.test.ts new file mode 100644 index 000000000000..a84fdc44d040 --- /dev/null +++ b/src/main/runtime/runtime-agent-orchestration-projection.test.ts @@ -0,0 +1,87 @@ +import { afterEach, describe, expect, it } from 'vitest' +import { testOrcaSessionId } from '../../shared/orca-session-address-test-fixture' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../shared/structured-agent-session-projection' +import { RuntimeAgentOrchestrationProjection } from './runtime-agent-orchestration-projection' +import type { RuntimeLeafRecord } from './runtime-terminal-state-records' +import { OrchestrationDb } from './orchestration/db' +import { + mintStructuredWorkerHandle, + mintStructuredWorkerPaneKey, + structuredWorkerProcessIncarnation +} from './structured-worker-identity' + +const COORDINATOR_CHAT = testOrcaSessionId('1b6f0c3a-7d2e-4a91-8c55-2e9d4b7a0f13') +const WORKER_CHAT = testOrcaSessionId('9c3e5a17-4b2d-4f60-8e91-0d7a6c2b5e48') +const TERMINAL_WORKER_HANDLE = 'term_worker' +const TERMINAL_WORKER_PANE = 'tab_w:11111111-1111-4111-8111-111111111111' + +function chatRow(sessionId: string): string { + return structuredAgentSessionPaneKey(structuredAgentSessionTabId(sessionId), sessionId) +} + +describe('RuntimeAgentOrchestrationProjection chat lineage', () => { + let db: OrchestrationDb + + afterEach(() => { + db?.close() + }) + + it('nests chat and terminal workers under the chat that dispatched them', () => { + db = new OrchestrationDb(':memory:') + const run = db.createRun({ + objective: 'chat run', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: COORDINATOR_CHAT + }) + const chatWorker = { + handle: mintStructuredWorkerHandle(), + sessionId: WORKER_CHAT, + paneKey: mintStructuredWorkerPaneKey(WORKER_CHAT) + } + const creator = { kind: 'session', orcaSessionId: COORDINATOR_CHAT } as const + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'chat worker' }).id, + assigneeHandle: chatWorker.handle, + assigneePaneKey: chatWorker.paneKey, + processIncarnation: structuredWorkerProcessIncarnation(WORKER_CHAT), + creator, + maxDepth: Number.MAX_SAFE_INTEGER + }) + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'terminal worker' }).id, + assigneeHandle: TERMINAL_WORKER_HANDLE, + assigneePaneKey: TERMINAL_WORKER_PANE, + creator, + maxDepth: Number.MAX_SAFE_INTEGER + }) + const leaf = { ptyId: 'pty_w' } as unknown as RuntimeLeafRecord + const projection = new RuntimeAgentOrchestrationProjection({ + getDb: () => db, + getLeaves: () => [leaf], + getPtys: () => [], + paneOf: () => ({ tabId: null, paneKey: null, recordedAtGraphSequence: 0 }), + issueLeafHandle: () => TERMINAL_WORKER_HANDLE, + issuePtyHandle: () => '', + makePaneKey: () => TERMINAL_WORKER_PANE, + getWorktreeId: () => null, + getHandleForPaneKey: () => null, + getPaneKey: () => null, + getDispatchAuthority: () => null, + getAgentStatusSnapshot: () => [], + getStructuredWorkers: () => [chatWorker], + getSessionDisplayPaneKey: chatRow + }) + + const contexts = projection.buildByPaneKey() + + expect(contexts?.[chatRow(WORKER_CHAT)]?.parentPaneKey).toBe(chatRow(COORDINATOR_CHAT)) + expect(contexts?.[TERMINAL_WORKER_PANE]?.parentPaneKey).toBe(chatRow(COORDINATOR_CHAT)) + // The minted pane key authorizes the worker's mailbox; it must never reach a renderer. + expect(JSON.stringify(contexts)).not.toContain(chatWorker.paneKey) + expect(JSON.stringify(contexts)).not.toContain(chatWorker.handle) + }) +}) diff --git a/src/main/runtime/runtime-agent-orchestration-projection.ts b/src/main/runtime/runtime-agent-orchestration-projection.ts index e76def78154d..f74d0285260e 100644 --- a/src/main/runtime/runtime-agent-orchestration-projection.ts +++ b/src/main/runtime/runtime-agent-orchestration-projection.ts @@ -28,6 +28,10 @@ type RuntimeAgentOrchestrationDependencies = { getPaneKey(handle: string): string | null getDispatchAuthority(handle: string): OrchestrationCompatibilityTerminalAuthority | null getAgentStatusSnapshot(): readonly FleetAgentStatusEvidence[] + /** Chat workers have no leaf or PTY; their minted pane key is a mailbox credential, not a row. */ + getStructuredWorkers(): Iterable<{ handle: string; sessionId: string; paneKey: string }> + /** The chat row showing this session's conversation now, after any /clear. */ + getSessionDisplayPaneKey(orcaSessionId: string): string | null } export class RuntimeAgentOrchestrationProjection { @@ -80,6 +84,21 @@ export class RuntimeAgentOrchestrationProjection { contexts[paneKey] = context } } + for (const worker of this.deps.getStructuredWorkers()) { + const paneKey = this.deps.getSessionDisplayPaneKey(worker.sessionId) + if (!paneKey || contexts[paneKey] || queriedHandles.has(worker.handle)) { + continue + } + queriedHandles.add(worker.handle) + const context = this.getForHandle(worker.handle, db, { + paneKey: worker.paneKey, + evidence: evidenceByPaneKey.get(paneKey), + deferAttention: batchAttention + }) + if (context) { + contexts[paneKey] = context + } + } const entries = Object.entries(contexts) if (entries.length === 0) { return undefined @@ -194,25 +213,43 @@ export class RuntimeAgentOrchestrationProjection { sameCreatorPane ? (creatorPaneHandle ?? undefined) : undefined - const coordinator = this.resolveLivePane( - coordinatorHandle, - owningRun?.legacy === 0 ? owningRun.coordinator_pane_key : null - ) - const creator = currentCreatorHandle - ? { - handle: currentCreatorHandle, - paneKey: this.deps.getPaneKey(currentCreatorHandle) ?? undefined - } - : creatorLineageInRun - ? this.resolveLivePane(creatorPaneHandle, creatorPaneKey ?? null) - : undefined + const selfSession = dispatch.assignee_orca_session_id + const coordinatorSession = + owningRun?.legacy === 0 ? owningRun.coordinator_orca_session_id : null + // Why: a chat party nests by its visible row; its handle and minted pane key match no row. + const coordinator = coordinatorSession + ? this.resolveSessionPane(coordinatorSession) + : this.resolveLivePane( + coordinatorHandle, + owningRun?.legacy === 0 ? owningRun.coordinator_pane_key : null + ) + const creatorSession = + dispatch.creator_orca_session_id && dispatch.creator_orca_session_id !== selfSession + ? dispatch.creator_orca_session_id + : null + const creator = creatorSession + ? this.resolveSessionPane(creatorSession) + : currentCreatorHandle + ? { + handle: currentCreatorHandle, + paneKey: this.deps.getPaneKey(currentCreatorHandle) ?? undefined + } + : creatorLineageInRun + ? this.resolveLivePane(creatorPaneHandle, creatorPaneKey ?? null) + : undefined const coordinatorIsSelf = coordinator.handle === handle || + (coordinatorSession !== null && coordinatorSession === selfSession) || (paneKey !== undefined && coordinator.paneKey !== undefined && coordinator.paneKey === paneKey) // Why: a creator whose pane is gone still has a coordinator to nest under. - const parent = creator?.handle ? creator : coordinatorIsSelf ? {} : coordinator + const parent = + creator?.handle || (creatorSession && creator?.paneKey) + ? creator + : coordinatorIsSelf + ? {} + : coordinator const attention = !deferAttention && db && typeof db.getWorkerAttentionFacts === 'function' ? buildWorkerAttentionContext({ db, dispatch, task, evidence }) @@ -231,6 +268,11 @@ export class RuntimeAgentOrchestrationProjection { } } + private resolveSessionPane(orcaSessionId: string): { handle?: string; paneKey?: string } { + const paneKey = this.deps.getSessionDisplayPaneKey(orcaSessionId) + return paneKey ? { paneKey } : {} + } + /** Never publish stale process-local handles; re-resolve the durable pane key, retaining it while offline so restored rows can nest again. */ private resolveLivePane( storedHandle: string | null | undefined, From d399b89b8236b07ef2142f9248df6295e083e574 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:51:13 -0700 Subject: [PATCH 002/164] Fix public worker lineage across assignment and row identities --- .../src/components/WorktreeAgentList.test.tsx | 62 ++ ...index-omitted-host-scope-selectors.test.ts | 77 ++- .../construction/runtime-service-state.ts | 16 +- .../db/dispatch-context/dispatch-lookup.ts | 76 ++- .../db/hot-path-statement-compilation.test.ts | 3 +- ...ing-dispatch-statement-compilation.test.ts | 13 + .../db/schema/schema-column-probes.ts | 8 + .../structured-session-lineage.ts | 52 +- .../runtime-agent-lineage.test-fixture.ts | 120 ++++ ...ime-agent-orchestration-projection.test.ts | 607 +++++++++++++++++- .../runtime-agent-orchestration-projection.ts | 174 +++-- .../runtime-agent-orchestration-scope.ts | 97 +++ .../activity-event-builder-sources.ts | 11 +- .../activity/activity-event-builder.ts | 10 +- .../activity/use-agent-pane-threads.ts | 3 +- .../dashboard/build-dashboard-snapshot.ts | 9 +- .../useAgentBucketCounts.gate.test.ts | 4 +- .../dashboard/useAgentBucketCounts.ts | 42 +- .../dashboard/useLiveDashboardSnapshot.ts | 2 + .../dashboard/worktree-agent-rows-cache.ts | 4 + .../structured-agent-session-tabs.ts | 19 + .../sidebar/WorkerLineage.fixture.tsx | 68 ++ ...worktree-agent-rows-subscriptions.test.tsx | 498 ++++++++++++++ .../sidebar/useWorktreeAgentRows.ts | 4 + .../worktree-agent-activity-summary.ts | 30 +- .../worktree-agent-live-index-patch.ts | 13 +- .../worktree-agent-orchestration-index.ts | 43 +- .../worktree-agent-row-fallback-tab.ts | 8 +- .../worktree-agent-row-orchestration.ts | 16 +- .../sidebar/worktree-agent-row-selectors.ts | 9 +- .../components/sidebar/worktree-agent-rows.ts | 14 +- .../runtime/structured-agent-session-owner.ts | 17 +- .../runtime/visible-agent-orchestration.ts | 197 ++++++ .../agent-status-live-entry-builder.ts | 3 +- .../agent-status-orchestration-actions.ts | 44 +- .../agent-status-retention-actions.ts | 3 +- .../agent-status-slice-contract.ts | 3 +- .../workspace-cleanup-agent-evidence.ts | 4 + .../src/store/workspace-record-selectors.ts | 19 +- .../agent-status-worktree-attribution.ts | 11 +- 40 files changed, 2207 insertions(+), 206 deletions(-) create mode 100644 src/main/runtime/runtime-agent-lineage.test-fixture.ts create mode 100644 src/main/runtime/runtime-agent-orchestration-scope.ts create mode 100644 src/renderer/src/components/sidebar/WorkerLineage.fixture.tsx create mode 100644 src/renderer/src/runtime/visible-agent-orchestration.ts diff --git a/mobile/src/components/WorktreeAgentList.test.tsx b/mobile/src/components/WorktreeAgentList.test.tsx index 3cb14c4eb672..4cdb7a5007c4 100644 --- a/mobile/src/components/WorktreeAgentList.test.tsx +++ b/mobile/src/components/WorktreeAgentList.test.tsx @@ -2,6 +2,8 @@ import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import { WorktreeAgentRow } from './WorktreeAgentRow' +import { WorktreeAgentSummary } from './WorktreeAgentSummary' import { WorktreeAgentList } from './WorktreeAgentList' import { findAllByHostType, findByHostType } from '../test-support/react-test-renderer-host-nodes' @@ -168,3 +170,63 @@ describe('WorktreeAgentList', () => { ) }) }) + +it('renders production-built canonical assignments as nested rows and groups only roots', async () => { + const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = + await import('../../../src/main/runtime/runtime-agent-lineage.test-fixture') + const { flattenAgentRowLineage } = await import('../worktree/agent-row-lineage') + const f = publicLineageFixture() + let tree: ReactTestRenderer | undefined + try { + const agents = f.build().agents + expect(flattenAgentRowLineage(agents).map((node) => [node.row.paneKey, node.depth])).toEqual([ + [canonicalChatRow(LINEAGE_PARENT), 0], + [canonicalChatRow(LINEAGE_CHILD), 1] + ]) + await act(async () => { + tree = create( + createElement(WorktreeAgentList, { + agents, + now: Date.now(), + unvisited: false, + statusLive: true + }) + ) + }) + expect( + tree?.root + .findAllByType(WorktreeAgentRow) + .map((node) => [node.props.agent.paneKey, node.props.depth]) + ).toEqual([ + [canonicalChatRow(LINEAGE_PARENT), 0], + [canonicalChatRow(LINEAGE_CHILD), 1] + ]) + expect(tree?.root.findAllByType(WorktreeAgentSummary)).toHaveLength(0) + expect(JSON.stringify(tree?.toJSON())).toContain('Build the worker result') + expect(JSON.stringify(tree?.toJSON())).not.toContain('2 agents') + expect(JSON.stringify(tree?.toJSON())).not.toContain(f.privateHandle) + expect(JSON.stringify(tree?.toJSON())).not.toContain(f.privatePane) + const orphan = { + ...agents[1], + paneKey: 'missing-parent-worker', + parentPaneKey: 'missing-parent' + } + await act(async () => + tree?.update( + createElement(WorktreeAgentList, { + agents: [...agents, orphan], + now: Date.now(), + unvisited: false + }) + ) + ) + expect( + tree?.root + .findByType(WorktreeAgentSummary) + .props.agents.map((row: RuntimeWorktreeAgentRow) => row.paneKey) + ).toEqual([canonicalChatRow(LINEAGE_PARENT), orphan.paneKey]) + } finally { + await act(async () => tree?.unmount()) + f.db.close() + } +}) diff --git a/src/cli/index-omitted-host-scope-selectors.test.ts b/src/cli/index-omitted-host-scope-selectors.test.ts index 4a7842df97a6..0c16ea6a4eeb 100644 --- a/src/cli/index-omitted-host-scope-selectors.test.ts +++ b/src/cli/index-omitted-host-scope-selectors.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from 'vitest' +import type * as ChildProcess from 'node:child_process' const { callMock, @@ -35,12 +36,22 @@ vi.mock('./runtime/environments', () => ({ resolveEnvironment: vi.fn() })) -vi.mock('child_process', async () => { +vi.mock('child_process', async (importOriginal) => { + const actual = await importOriginal() const { createChildProcessModuleMock } = await import('./index-test-harness.js') - return createChildProcessModuleMock(spawnMock) + return { ...actual, ...createChildProcessModuleMock(spawnMock) } }) import { main } from './index' +import { + publicLineageFixture, + canonicalChatRow, + LINEAGE_PARENT, + LINEAGE_CHILD +} from '../main/runtime/runtime-agent-lineage.test-fixture' +import type { OrcaRuntimeService } from '../main/runtime/orca-runtime' +import { RpcDispatcher } from '../main/runtime/rpc/dispatcher' +import { WORKTREE_CATALOG_METHODS } from '../main/runtime/rpc/methods/worktree-catalog-methods' import { COMMAND_SPECS } from './specs' import { okFixture, queueFixtures } from './test-fixtures' import { pairRuntimeEnvironment, useWorktreeAwarenessEnvironment } from './index-test-harness' @@ -71,6 +82,68 @@ describe('omittedHostIds selector annotation', () => { spawnMock }) + it.each(['repo::/workspace', 'folder:lineage'])( + 'prints canonical production-built lineage through actual CLI and worktree RPC for %s', + async (worktreeId) => { + const f = publicLineageFixture(worktreeId) + try { + // SAFETY: these catalog methods use only this read-only runtime seam; rows come from production projection/attachment. + const runtime = { + getRuntimeId: () => 'lineage-test', + getWorktreePs: async () => ({ worktrees: [f.build()], totalCount: 1, truncated: false }) + } as unknown as OrcaRuntimeService + const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_CATALOG_METHODS }) + const resultOf = (response: unknown) => JSON.parse(JSON.stringify(response)).result + const request = (params = {}) => + dispatcher.dispatch({ + id: 'req_worktree_ps', + authToken: 'test', + method: 'worktree.ps', + params + }) + const legacy = await request() + expect(legacy).toMatchObject({ + ok: true, + result: { + worktrees: [ + { + agents: [ + { parentPaneKey: null }, + { + parentPaneKey: canonicalChatRow(LINEAGE_PARENT), + taskTitle: 'Build the worker result' + } + ] + } + ] + } + }) + callMock.mockResolvedValueOnce(legacy) + const log = vi.spyOn(console, 'log').mockImplementation(() => {}) + await main(['worktree', 'ps', '--json'], '/workspace') + const printed = JSON.parse(String(log.mock.calls[0]?.[0])) + expect(printed.result.worktrees[0].agents[1].paneKey).toBe(canonicalChatRow(LINEAGE_CHILD)) + expect(JSON.stringify(printed)).not.toContain(f.privateHandle) + expect(JSON.stringify(printed)).not.toContain(f.privatePane) + const first = resultOf(await request({ afterSnapshotId: null })) + expect(resultOf(await request({ afterSnapshotId: first.snapshotId }))).toMatchObject({ + unchanged: true + }) + f.db.db + .prepare( + 'UPDATE runs SET coordinator_orca_session_id = NULL, coordinator_orca_session_id_generation = NULL WHERE id = ?' + ) + .run(f.run.id) + expect(resultOf(await request({ afterSnapshotId: first.snapshotId })).snapshotId).not.toBe( + first.snapshotId + ) + log.mockRestore() + } finally { + f.db.close() + } + } + ) + it('marks a stale runtime host that no caller can select', async () => { pairRuntimeEnvironment(listEnvironmentsMock, 'env-paired', 'm4air') queueFixtures( diff --git a/src/main/runtime/construction/runtime-service-state.ts b/src/main/runtime/construction/runtime-service-state.ts index 797a6c72dd90..88f06aa8ccff 100644 --- a/src/main/runtime/construction/runtime-service-state.ts +++ b/src/main/runtime/construction/runtime-service-state.ts @@ -44,11 +44,9 @@ import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' import { mainListsEveryPane } from '../terminal/surface/main-terminal-surfaces' import { TUI_IDLE_QUIESCENCE_MS } from '../orca-runtime-postlude' import { screenClearsBlockedTail } from '../blocked-tail-screen-clear' -import { structuredWorkerIdentities } from '../structured-worker-identity' -import { - lineageDisplayPaneKey, - readAgentSessionRecordStore -} from '../orchestration/structured-session-lineage' +import { conversationRecordReader } from '../orchestration/structured-session-lineage' +import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/structured-agent-session-registry' +import { peekOpenedAgentSessionRecordStore } from '../agent-session-record-store-slot' export abstract class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWithRuntimeId { protected readonly stopRequestedPtyIds = new Set() @@ -130,9 +128,11 @@ export abstract class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWith getPaneKey: (handle) => this.getPaneKeyForTerminalHandle(handle), getDispatchAuthority: (handle) => this.getOrchestrationDispatchAuthority(handle), getAgentStatusSnapshot: () => this.getOrchestrationFleetAgentStatusSnapshot(), - getStructuredWorkers: () => structuredWorkerIdentities.list(), - getSessionDisplayPaneKey: (orcaSessionId) => - lineageDisplayPaneKey(readAgentSessionRecordStore(), orcaSessionId) + getSessionRecords: () => { + const store = + getStructuredAgentSessionHost()?.deps.store ?? peekOpenedAgentSessionRecordStore() + return store ? conversationRecordReader(store) : null + } }) protected readonly terminalList = new RuntimeTerminalList({ diff --git a/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts b/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts index 4f4fdd79b0d5..ac5c552371a8 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts @@ -1,3 +1,4 @@ +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../../shared/agent-status-types' import { parsePaneKey } from '../../../../../shared/stable-pane-id' import type { DispatchContextRow } from '../../types' import { @@ -24,6 +25,77 @@ const ACTIVE_DISPATCH_BY_PANE_SUFFIX_SQL = `SELECT ${DISPATCH_CONTEXT_COLUMN_LIS ORDER BY rowid DESC LIMIT 1` const LATEST_DISPATCH_BY_HANDLE_SQL = `SELECT ${DISPATCH_CONTEXT_COLUMN_LIST} FROM dispatch_contexts WHERE assignee_handle = ? ORDER BY rowid DESC LIMIT 1` +/** Preserve the terminal projection's exact ISO/SQLite recency contract, including future dates. */ +export function isRecentPresentationDispatch(dispatch: DispatchContextRow, now: number): boolean { + if (!dispatch.completed_at || dispatch.status === 'pending' || dispatch.status === 'dispatched') { + return false + } + const completedAt = Date.parse( + dispatch.completed_at.includes('T') + ? dispatch.completed_at + : `${dispatch.completed_at.replace(' ', 'T')}Z` + ) + return Number.isFinite(completedAt) && now - completedAt <= AGENT_STATUS_STALE_AFTER_MS +} + +/** Active first, otherwise latest per address; an older eligible completion never resurfaces. */ +export function listSessionDispatchesForPresentation( + this: OrchestrationDb, + now: number +): { dispatch: DispatchContextRow; order: number }[] { + const lowerBound = new Date(now - AGENT_STATUS_STALE_AFTER_MS - 86_400_000).toISOString() + // SAFETY: explicit Dispatch columns plus SQLite's internal ordering identity. + const candidates = this.db + .prepare(` + SELECT rowid AS presentation_order, ${DISPATCH_CONTEXT_COLUMN_LIST} FROM dispatch_contexts + INDEXED BY idx_dispatch_session_presentation + WHERE assignee_orca_session_id IS NOT NULL AND status IN ('pending', 'dispatched') + UNION ALL + SELECT rowid AS presentation_order, ${DISPATCH_CONTEXT_COLUMN_LIST} FROM dispatch_contexts + INDEXED BY idx_dispatch_session_presentation + WHERE assignee_orca_session_id IS NOT NULL + AND status IN ('completed', 'failed', 'circuit_broken') AND completed_at >= ? + `) + .all(lowerBound) as (DispatchContextRow & { presentation_order: number })[] + const selected = new Map() + for (const candidate of candidates) { + const address = candidate.assignee_handle + ? `handle:${candidate.assignee_handle}` + : `session:${candidate.assignee_orca_session_id}` + const previous = selected.get(address) + const active = candidate.status === 'pending' || candidate.status === 'dispatched' + const previousActive = previous?.status === 'pending' || previous?.status === 'dispatched' + if ( + !previous || + (active && !previousActive) || + (active === previousActive && candidate.presentation_order > previous.presentation_order) + ) { + selected.set(address, candidate) + } + } + const result: { dispatch: DispatchContextRow; order: number }[] = [] + for (const candidate of selected.values()) { + const { presentation_order, ...dispatch } = candidate + const active = dispatch.status === 'pending' || dispatch.status === 'dispatched' + // SAFETY: equality-index probes return just the internal row order, or no row. + const latest = this.db + .prepare(`SELECT rowid AS n FROM dispatch_contexts + WHERE ${candidate.assignee_handle ? 'assignee_handle' : 'assignee_orca_session_id'} = ? + ${active ? "AND status IN ('pending', 'dispatched')" : ''} ORDER BY rowid DESC LIMIT 1`) + .get(candidate.assignee_handle || candidate.assignee_orca_session_id) as + | { n: number } + | undefined + if ( + latest?.n !== presentation_order || + (!active && !isRecentPresentationDispatch(dispatch, now)) + ) { + continue + } + result.push({ dispatch, order: presentation_order }) + } + return result +} + export function getActiveDispatchForTerminal( this: OrchestrationDb, handle: string, @@ -168,6 +240,7 @@ export type DispatchLookupMethods = { getActiveDispatchMailboxOwners: typeof getActiveDispatchMailboxOwners isDispatchMessageSender: typeof isDispatchMessageSender findActiveDispatchForAssignee: typeof findActiveDispatchForAssignee + listSessionDispatchesForPresentation: typeof listSessionDispatchesForPresentation getLatestDispatchForTerminal: typeof getLatestDispatchForTerminal } @@ -179,6 +252,7 @@ export function attachDispatchLookup(ctor: { prototype: object }): void { getActiveDispatchMailboxOwners, isDispatchMessageSender, findActiveDispatchForAssignee, - getLatestDispatchForTerminal + getLatestDispatchForTerminal, + listSessionDispatchesForPresentation }) } diff --git a/src/main/runtime/orchestration/db/hot-path-statement-compilation.test.ts b/src/main/runtime/orchestration/db/hot-path-statement-compilation.test.ts index d8d75f57e72b..5c44b3cd746d 100644 --- a/src/main/runtime/orchestration/db/hot-path-statement-compilation.test.ts +++ b/src/main/runtime/orchestration/db/hot-path-statement-compilation.test.ts @@ -104,8 +104,7 @@ function buildProjection(db: OrchestrationDb): RuntimeAgentOrchestrationProjecti } as OrchestrationCompatibilityTerminalAuthority) : null, getAgentStatusSnapshot: () => [], - getStructuredWorkers: () => [], - getSessionDisplayPaneKey: () => null + getSessionRecords: () => null }) } diff --git a/src/main/runtime/orchestration/db/remaining-dispatch-statement-compilation.test.ts b/src/main/runtime/orchestration/db/remaining-dispatch-statement-compilation.test.ts index bbf0785d6eeb..897ca307e5ed 100644 --- a/src/main/runtime/orchestration/db/remaining-dispatch-statement-compilation.test.ts +++ b/src/main/runtime/orchestration/db/remaining-dispatch-statement-compilation.test.ts @@ -62,6 +62,7 @@ function fixture(count = 1, version: 'fresh' | 'v41' = 'fresh') { ${DROP_REMOVED_WORK_TRIGGERS_SQL} DROP INDEX idx_runs_coordinator_orca_session_id; DROP INDEX idx_dispatch_assignee_orca_session_id; + DROP INDEX idx_dispatch_session_presentation; DROP TRIGGER trg_runs_remember_coordinator_insert; DROP TRIGGER trg_runs_remember_coordinator_update; DROP TRIGGER trg_messages_route_coordinator_mail; @@ -92,7 +93,19 @@ function fixture(count = 1, version: 'fresh' | 'v41' = 'fresh') { .map((row) => row.name) .toSorted() ).toEqual(DISPATCH_CONTEXT_COLUMNS.toSorted()) + const priorVersion = writer.db.pragma('user_version', { simple: true }) + expect( + writer.db + .prepare("SELECT name FROM sqlite_master WHERE name = 'idx_dispatch_session_presentation'") + .get() + ).toBeDefined() const reader = new OrchestrationDb(path) + expect(reader.db.pragma('user_version', { simple: true })).toBe(priorVersion) + expect( + reader.db + .prepare("SELECT name FROM sqlite_master WHERE name = 'idx_dispatch_session_presentation'") + .get() + ).toBeDefined() databases.push(reader) return { writer, reader, run, entries } } diff --git a/src/main/runtime/orchestration/db/schema/schema-column-probes.ts b/src/main/runtime/orchestration/db/schema/schema-column-probes.ts index c408135b4f21..7b87b5f6edd8 100644 --- a/src/main/runtime/orchestration/db/schema/schema-column-probes.ts +++ b/src/main/runtime/orchestration/db/schema/schema-column-probes.ts @@ -7,6 +7,14 @@ export function hasColumn(this: OrchestrationDb, table: string, column: string): } export function createMailboxDeliveryIndexesIfPossible(this: OrchestrationDb): void { + if ( + ['assignee_orca_session_id', 'status', 'completed_at'].every((column) => + this.hasColumn('dispatch_contexts', column) + ) + ) { + this.db.exec(`CREATE INDEX IF NOT EXISTS idx_dispatch_session_presentation + ON dispatch_contexts(status, completed_at) WHERE assignee_orca_session_id IS NOT NULL`) + } if (this.hasColumn('deliveries', 'mailbox_handle')) { this.db.exec(OUTSTANDING_MAILBOX_INDEX_SQL) } diff --git a/src/main/runtime/orchestration/structured-session-lineage.ts b/src/main/runtime/orchestration/structured-session-lineage.ts index b65428c84761..5c87456247bd 100644 --- a/src/main/runtime/orchestration/structured-session-lineage.ts +++ b/src/main/runtime/orchestration/structured-session-lineage.ts @@ -60,6 +60,7 @@ export function resolveLineageRunningSession( sessionId: string ): LineageRunningSession { const lineage = [sessionId] + const visited = new Set(lineage) if (!store) { return { kind: 'unverifiable', @@ -90,13 +91,14 @@ export function resolveLineageRunningSession( ? { kind: 'here', ...running } : { kind: 'other-host', ...running } } - if (lineage.includes(next)) { + if (visited.has(next)) { return { kind: 'unverifiable', reason: `The /clear lineage of structured session ${sessionId} loops back on itself.`, lineage } } + visited.add(next) lineage.push(next) current = next } @@ -111,12 +113,44 @@ export function lineageLiveSession( return running.kind === 'unverifiable' ? null : running.record } -/** The chat row a session's conversation shows under now; an unverifiable lineage keeps its own row. */ -export function lineageDisplayPaneKey( - store: AgentSessionRecordReader | null, - sessionId: string -): string { - const running = resolveLineageRunningSession(store, sessionId) - const current = running.kind === 'unverifiable' ? sessionId : running.sessionId - return structuredAgentSessionPaneKey(structuredAgentSessionTabId(current), current) +/** Canonical host status keys; this build-local resolver shares successful suffixes and failed verdicts. */ +export function createCanonicalSessionPaneResolver( + store: AgentSessionRecordReader | null +): (sessionId: string) => string { + const resolved = new Map() + return (sessionId) => { + let current = sessionId + const path = new Set() + let destination: string | null = null + for (;;) { + if (resolved.has(current)) { + destination = resolved.get(current) ?? null + break + } + if (path.has(current)) { + break + } + path.add(current) + let record: AgentSessionConversationView | null + try { + record = store?.getRecord(current) ?? null + } catch { + record = null + } + if (!record) { + break + } + const next = clearedInto(record) + if (!next) { + destination = current + break + } + current = next + } + for (const member of path) { + resolved.set(member, destination) + } + const id = destination ?? sessionId + return structuredAgentSessionPaneKey(structuredAgentSessionTabId(id), id) + } } diff --git a/src/main/runtime/runtime-agent-lineage.test-fixture.ts b/src/main/runtime/runtime-agent-lineage.test-fixture.ts new file mode 100644 index 000000000000..755e6d59cc50 --- /dev/null +++ b/src/main/runtime/runtime-agent-lineage.test-fixture.ts @@ -0,0 +1,120 @@ +import { OrchestrationDb } from './orchestration/db' +import { RuntimeAgentOrchestrationProjection } from './runtime-agent-orchestration-projection' +import { attachRuntimeWorktreeAgentRows } from './runtime-worktree-agent-rows' +import type { RuntimeWorktreePsSummary } from '../../shared/runtime-types' +import type { RuntimeWorktreeAgentSource } from './runtime-worktree-agent-source' +import { testOrcaSessionId } from '../../shared/orca-session-address-test-fixture' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../shared/structured-agent-session-projection' +import { + mintStructuredWorkerHandle, + mintStructuredWorkerPaneKey, + structuredWorkerProcessIncarnation +} from './structured-worker-identity' + +export const LINEAGE_PARENT = testOrcaSessionId('ca1f6c2e-8b3d-4e7a-9c15-0d2b6e8f1a37') +export const LINEAGE_CHILD = testOrcaSessionId('ce3b9d15-2c4a-4f86-a0b1-5c9e2d7f3b64') +export const canonicalChatRow = (id: string): string => + structuredAgentSessionPaneKey(structuredAgentSessionTabId(id), id) + +/** Production assignment projection and host row attachment; no preassembled agent output. */ +export function publicLineageFixture(worktreeId = 'repo::/workspace') { + const db = new OrchestrationDb(':memory:') + const privateHandle = mintStructuredWorkerHandle() + const privatePane = mintStructuredWorkerPaneKey(LINEAGE_CHILD) + const run = db.createRun({ + objective: 'lineage', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: LINEAGE_PARENT + }) + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'Build the worker result' }).id, + assigneeHandle: privateHandle, + assigneePaneKey: privatePane, + processIncarnation: structuredWorkerProcessIncarnation(LINEAGE_CHILD), + creator: { kind: 'system' }, + maxDepth: 99 + }) + const projection = new RuntimeAgentOrchestrationProjection({ + getDb: () => db, + getLeaves: () => [], + getPtys: () => [], + getSessionRecords: () => null, + paneOf: () => ({ tabId: null, paneKey: null, recordedAtGraphSequence: 0 }), + issueLeafHandle: () => '', + issuePtyHandle: () => '', + makePaneKey: () => '', + getWorktreeId: () => null, + getHandleForPaneKey: () => null, + getPaneKey: () => null, + getDispatchAuthority: () => null, + getAgentStatusSnapshot: () => [] + }) + const updatedAt = Date.now() + const build = (): RuntimeWorktreePsSummary => { + const row: RuntimeWorktreePsSummary = { + worktreeId, + workspaceKind: worktreeId.startsWith('folder:') ? 'folder-workspace' : 'git', + repoId: 'repo', + repo: 'repo', + path: '/workspace', + branch: 'main', + isArchived: false, + isMainWorktree: true, + hasHostSidebarActivity: false, + parentWorktreeId: null, + childWorktreeIds: [], + displayName: 'Workspace', + workspaceStatus: '', + sortOrder: 0, + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + linkedGitLabMR: null, + linkedGitLabIssue: null, + comment: '', + isPinned: false, + isActive: false, + unread: false, + liveTerminalCount: 0, + hasAttachedPty: false, + lastOutputAt: null, + preview: '', + status: 'inactive', + agents: [] + } + const sources = new Map( + [LINEAGE_PARENT, LINEAGE_CHILD].map((id) => [ + canonicalChatRow(id), + { + paneKey: canonicalChatRow(id), + connectionId: null, + worktreeId, + state: 'working', + agentType: 'codex', + prompt: id === LINEAGE_PARENT ? 'Coordinate work' : 'Implement work', + lastAssistantMessage: null, + toolName: null, + toolInput: null, + interrupted: false, + stateStartedAt: 1, + updatedAt, + structuredHost: 'owned' + } + ]) + ) + const summaries = new Map([[worktreeId, row]]) + attachRuntimeWorktreeAgentRows({ + summaries, + rowSources: sources, + terminalTitleEvidenceByWorktreeId: new Map(), + orchestrationByPaneKey: projection.buildByPaneKey(), + getSummary: (id) => summaries.get(id) ?? null + }) + return row + } + return { db, projection, build, privateHandle, privatePane, run } +} diff --git a/src/main/runtime/runtime-agent-orchestration-projection.test.ts b/src/main/runtime/runtime-agent-orchestration-projection.test.ts index a84fdc44d040..2cf2b82667d9 100644 --- a/src/main/runtime/runtime-agent-orchestration-projection.test.ts +++ b/src/main/runtime/runtime-agent-orchestration-projection.test.ts @@ -1,4 +1,33 @@ -import { afterEach, describe, expect, it } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { seedTestAgentSessionRecordStore } from './agent-session-record-store-test-harness' +import { closeTestJournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database-test-support' +import { + openAgentSessionRecordStoreOnce, + releaseAgentSessionRecordStore +} from './agent-session-record-store-slot' +import { recordingStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/structured-agent-session-logger-test-support' +import { OrcaRuntimeService } from './orca-runtime' +import './rpc/unused-default-rpc-methods.test-fixture' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { agentSessionConversationView } from '../../shared/agent-session-conversation-view' +import { + createSessionCallerHarness, + orchestrationRequest, + resultOf, + idOf, + SESSION_X, + SESSION_Y, + sessionRecord +} from './rpc/orchestration-session-caller-test-fixture' +import { formatOrcaSessionAddress } from '../../shared/orca-session-address' +import type { AgentSessionRecordReader } from './orchestration/structured-session-lineage' + +const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) +vi.mock('../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ + getStructuredAgentSessionHost: () => hostRef.current +})) import { testOrcaSessionId } from '../../shared/orca-session-address-test-fixture' import { structuredAgentSessionPaneKey, @@ -27,6 +56,8 @@ describe('RuntimeAgentOrchestrationProjection chat lineage', () => { afterEach(() => { db?.close() + hostRef.current = null + vi.restoreAllMocks() }) it('nests chat and terminal workers under the chat that dispatched them', () => { @@ -72,8 +103,7 @@ describe('RuntimeAgentOrchestrationProjection chat lineage', () => { getPaneKey: () => null, getDispatchAuthority: () => null, getAgentStatusSnapshot: () => [], - getStructuredWorkers: () => [chatWorker], - getSessionDisplayPaneKey: chatRow + getSessionRecords: () => null }) const contexts = projection.buildByPaneKey() @@ -85,3 +115,574 @@ describe('RuntimeAgentOrchestrationProjection chat lineage', () => { expect(JSON.stringify(contexts)).not.toContain(chatWorker.handle) }) }) + +function projectionFor(db: OrchestrationDb, records: AgentSessionRecordReader | null = null) { + return new RuntimeAgentOrchestrationProjection({ + getDb: () => db, + getLeaves: () => [], + getPtys: () => [], + paneOf: () => ({ tabId: null, paneKey: null, recordedAtGraphSequence: 0 }), + issueLeafHandle: () => '', + issuePtyHandle: () => '', + makePaneKey: () => '', + getWorktreeId: () => null, + getHandleForPaneKey: () => null, + getPaneKey: () => null, + getDispatchAuthority: () => null, + getAgentStatusSnapshot: () => [], + getSessionRecords: () => records + }) +} + +it('publishes ordinary RPC assignments without registering display authority and honors current Run generations', async () => { + const h = createSessionCallerHarness(hostRef) + try { + const runId = idOf( + resultOf( + await h.dispatch( + orchestrationRequest( + 'orchestration.runCreate', + { objective: 'public lineage' }, + { sessionId: SESSION_X } + ) + ) + ).run + ) + const task = h.db.createTask({ runId, spec: 'existing chat task' }) + const response = await h.dispatch( + orchestrationRequest( + 'orchestration.dispatch', + { task: task.id, to: formatOrcaSessionAddress(SESSION_Y) }, + { sessionId: SESSION_X } + ) + ) + const dispatchId = idOf(resultOf(response).dispatch) + const projection = h.runtime['agentOrchestrationProjection'] + expect(projection.buildByPaneKey()?.[chatRow(SESSION_Y)]).toMatchObject({ + dispatchId, + parentPaneKey: chatRow(SESSION_X), + taskTitle: 'existing chat task' + }) + h.db.db + .prepare('UPDATE runs SET coordinator_orca_session_id = ? WHERE id = ?') + .run(COORDINATOR_CHAT, runId) + expect(projection.buildByPaneKey()?.[chatRow(SESSION_Y)]?.parentPaneKey).toBe( + chatRow(SESSION_X) + ) + h.db.db + .prepare('UPDATE runs SET coordinator_orca_session_id = ? WHERE id = ?') + .run(SESSION_X, runId) + // A callback does not have to populate mailbox authority before the public relationship exists. + h.runtime.onStructuredSessionStatusForMail({ sessionId: SESSION_Y, status: 'attention' }) + expect(projection.buildByPaneKey()?.[chatRow(SESSION_Y)]?.parentPaneKey).toBe( + chatRow(SESSION_X) + ) + h.db.db + .prepare('UPDATE dispatch_contexts SET creator_orca_session_id = NULL WHERE id = ?') + .run(dispatchId) + const terminal = 'offline:11111111-1111-4111-8111-111111111111' + h.db.db + .prepare( + 'UPDATE runs SET coordinator_handle = ?, coordinator_pane_key = ?, consumer_generation = consumer_generation + 1 WHERE id = ?' + ) + .run('term_old_writer', terminal, runId) + expect(projection.buildByPaneKey()?.[chatRow(SESSION_Y)]?.parentPaneKey).toBe(terminal) + h.db.db + .prepare( + 'UPDATE runs SET coordinator_orca_session_id_generation = consumer_generation WHERE id = ?' + ) + .run(runId) + expect(projection.buildByPaneKey()?.[chatRow(SESSION_Y)]?.parentPaneKey).toBe( + chatRow(SESSION_X) + ) + h.db.db + .prepare( + 'UPDATE runs SET coordinator_orca_session_id_generation = NULL, coordinator_handle = ?, coordinator_pane_key = ? WHERE id = ?' + ) + .run(mintStructuredWorkerHandle(), mintStructuredWorkerPaneKey(SESSION_X), runId) + expect(projection.buildByPaneKey()?.[chatRow(SESSION_Y)]?.parentPaneKey).toBeUndefined() + expect(JSON.stringify(projection.buildByPaneKey())).not.toContain('structworker_') + } finally { + h.close() + } +}) + +it.each([20, 200])( + 'shares forward lineage and DB/attention work across %i workers; each build rederives facts', + (n) => { + const db = new OrchestrationDb(':memory:') + try { + const run = db.createRun({ + objective: 'shared ancestry', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: SESSION_X + }) + for (let i = 0; i < n; i++) { + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'shared task' }).id, + assigneeHandle: `ordinary-${i}`, + creator: { kind: 'session', orcaSessionId: SESSION_X }, + maxDepth: 9999 + }) + db.db + .prepare( + 'UPDATE dispatch_contexts SET assignee_orca_session_id = ? WHERE assignee_handle = ?' + ) + .run(`worker-${i}`, `ordinary-${i}`) + } + let endpoint = n + const read = vi.fn((id: string) => { + const record = sessionRecord(id) + const index = id === SESSION_X ? 0 : id.startsWith('edge-') ? Number(id.slice(5)) : endpoint + return agentSessionConversationView( + index < endpoint + ? { + ...record, + conversationCommand: { + command: 'clear', + runtimeFence: record.lease.runtimeFence, + operationId: 'clear', + callerKey: 'test', + phase: 'committed', + state: 'completed', + replacementSessionId: `edge-${index + 1}` + } + } + : record + ) + }) + const projection = projectionFor(db, { getRecord: read, listRecords: () => [] }) + const tasks = vi.spyOn(db, 'getTask') + const runs = vi.spyOn(db, 'getRun') + const batch = vi.spyOn(db, 'getWorkerAttentionFactsForDispatches') + const individual = vi.spyOn(db, 'getWorkerAttentionFacts') + const roster = vi.spyOn(db, 'listSessionDispatchesForPresentation') + let candidateVisits = 0 + let latestVisits = 0 + db.db.function('lineage_candidate_visit', {}, (_rowid: unknown) => { + candidateVisits++ + return 1 + }) + db.db.function('lineage_latest_visit', {}, (_rowid: unknown) => { + latestVisits++ + return 1 + }) + const prepare = db.db.prepare.bind(db.db) + const sql = vi + .spyOn(db.db, 'prepare') + .mockImplementation((query) => + prepare( + query + .replaceAll( + 'WHERE assignee_orca_session_id IS NOT NULL', + 'WHERE assignee_orca_session_id IS NOT NULL AND lineage_candidate_visit(rowid)' + ) + .replace( + 'ORDER BY rowid DESC LIMIT 1', + query.includes('rowid AS n') + ? 'AND lineage_latest_visit(rowid) ORDER BY rowid DESC LIMIT 1' + : 'ORDER BY rowid DESC LIMIT 1' + ) + ) + ) + const output = projection.buildByPaneKey() + expect(Object.keys(output ?? {})).toHaveLength(n) + expect( + Object.values(output ?? {}).every( + (context) => context.parentPaneKey === chatRow(`edge-${n}`) + ) + ).toBe(true) + expect(read).toHaveBeenCalledTimes(n + n + 1) + expect(tasks).toHaveBeenCalledTimes(n) + expect(runs).toHaveBeenCalledTimes(1) + expect(roster).toHaveBeenCalledTimes(1) + expect(candidateVisits).toBe(n) + expect(latestVisits).toBe(n) + expect( + sql.mock.calls.filter(([query]) => query.includes('d.id AS dispatch_id')) + ).toHaveLength(1) + expect( + sql.mock.calls.filter(([query]) => query.includes('FROM attempt_observation_facts')) + ).toHaveLength(1) + expect(batch).toHaveBeenCalledTimes(1) + expect(individual).not.toHaveBeenCalled() + endpoint++ + read.mockClear() + expect( + Object.values(projection.buildByPaneKey() ?? {}).every( + (context) => context.parentPaneKey === chatRow(`edge-${endpoint}`) + ) + ).toBe(true) + expect(read.mock.calls.length).toBeLessThanOrEqual(n + endpoint + 1) + for (const failure of ['missing', 'error', 'cycle', 'prepared']) { + read.mockImplementation((id) => { + if (failure === 'error') { + throw new Error('unreadable') + } + if (failure === 'missing') { + return null + } + const record = sessionRecord(id) + return agentSessionConversationView({ + ...record, + conversationCommand: { + command: 'clear', + runtimeFence: record.lease.runtimeFence, + operationId: 'cycle', + callerKey: 'test', + phase: failure === 'prepared' ? 'prepared' : 'committed', + state: 'completed', + replacementSessionId: SESSION_X + } + }) + }) + expect( + Object.values(projection.buildByPaneKey() ?? {}).every( + (context) => context.parentPaneKey === chatRow(SESSION_X) + ) + ).toBe(true) + } + } finally { + db.close() + } + } +) + +it('selects indexed active/latest per address with exact ISO/SQLite recency and deterministic public collisions', () => { + const db = new OrchestrationDb(':memory:') + const now = Date.parse('2026-10-27T00:00:10.000Z') + try { + const emptyRoster = vi.spyOn(db, 'listSessionDispatchesForPresentation') + const emptyRead = vi.fn(() => null) + expect( + projectionFor(db, { getRecord: emptyRead, listRecords: () => [] }).buildByPaneKey() + ).toBeUndefined() + expect(emptyRoster).not.toHaveBeenCalled() + expect(emptyRead).not.toHaveBeenCalled() + const version = db.db.pragma('user_version', { simple: true }) + const run = db.createRun({ + objective: 'selection', + coordinatorHandle: 'term_c', + coordinatorPaneKey: 'c:11111111-1111-4111-8111-111111111111' + }) + let counter = 0 + const add = ( + handle: string, + session: string | null, + status: string, + completed: string | null + ) => { + const row = db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'selection' }).id, + assigneeHandle: `${handle}-${counter++}`, + creator: { kind: 'system' }, + maxDepth: 99 + }) + db.db + .prepare( + 'UPDATE dispatch_contexts SET assignee_handle = ?, assignee_orca_session_id = ?, status = ?, completed_at = ? WHERE id = ?' + ) + .run(handle, session, status, completed, row.id) + return row.id + } + add('suppressed', SESSION_X, 'completed', '2026-10-27T00:00:00Z') + add('suppressed', null, 'failed', null) + const sqlite = add('sqlite', SESSION_Y, 'completed', '2026-10-26 23:59:59') + add('expired', 'expired', 'completed', '2020-01-01T00:00:00Z') + add('invalid', 'invalid', 'completed', 'zzzz') + add('missing', 'missing', 'failed', null) + const future = add('future', 'future', 'failed', '2099-01-01T00:00:00Z') + const active = add('active', SESSION_Y, 'dispatched', null) + add('same-address', 'active-old', 'pending', null) + const newest = add('same-address', 'active-new', 'pending', null) + expect( + db + .listSessionDispatchesForPresentation(now) + .map((row) => row.dispatch.id) + .sort() + ).toEqual([newest, active, future, sqlite].sort()) + const noHandle = add('null-handle', 'null-address', 'dispatched', null) + db.db.prepare('UPDATE dispatch_contexts SET assignee_handle = NULL WHERE id = ?').run(noHandle) + expect( + db.listSessionDispatchesForPresentation(now).some((row) => row.dispatch.id === noHandle) + ).toBe(true) + const columns = db.db.prepare('PRAGMA index_info(idx_dispatch_session_presentation)').all() + expect(columns).toMatchObject([{ name: 'status' }, { name: 'completed_at' }]) + db.createMailboxDeliveryIndexesIfPossible() + expect(db.db.pragma('user_version', { simple: true })).toBe(version) + const plan = JSON.stringify( + db.db + .prepare( + "EXPLAIN QUERY PLAN SELECT rowid FROM dispatch_contexts INDEXED BY idx_dispatch_session_presentation WHERE assignee_orca_session_id IS NOT NULL AND status = 'completed' AND completed_at >= ?" + ) + .all('2026-10-26') + ) + expect(plan).toContain('idx_dispatch_session_presentation (status=? AND completed_at>?)') + expect(projectionFor(db).buildByPaneKey()?.[chatRow(SESSION_Y)]?.dispatchId).toBe(active) + const latestActive = add('cleared-address', SESSION_X, 'pending', null) + add('newer-recent-address', SESSION_Y, 'completed', '2099-01-01T00:00:00Z') + const read = (id: string) => { + const record = sessionRecord(id) + return agentSessionConversationView( + id === SESSION_X + ? { + ...record, + conversationCommand: { + command: 'clear', + runtimeFence: record.lease.runtimeFence, + operationId: 'destination', + callerKey: 'test', + phase: 'committed', + state: 'completed', + replacementSessionId: SESSION_Y + } + } + : record + ) + } + const sharedDestination = projectionFor(db, { + getRecord: read, + listRecords: () => [] + }).buildByPaneKey() + expect(sharedDestination?.[chatRow(SESSION_Y)]?.dispatchId).toBe(latestActive) + expect(sharedDestination?.[chatRow(SESSION_X)]).toBeUndefined() + } finally { + db.close() + } +}) + +it.skipIf(process.env.ORCA_LINEAGE_BENCH !== '1')( + 'benchmarks retained-history ranges and first derived-index creation (admitted machines only)', + () => { + for (const history of [10_000, 100_000]) { + for (const terminalHistory of [0, 100_000]) { + for (const attentionFacts of [0, 2_000]) { + const directory = mkdtempSync(join(tmpdir(), 'orca-lineage-benchmark-')) + const path = join(directory, 'orchestration.sqlite') + let db = new OrchestrationDb(path) + try { + const run = db.createRun({ + objective: 'benchmark', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: SESSION_X + }) + for (let i = 0; i < 20; i++) { + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'active' }).id, + assigneeHandle: formatOrcaSessionAddress( + testOrcaSessionId(`00000000-0000-4000-8000-${String(i).padStart(12, '0')}`) + ), + creator: { kind: 'system' }, + maxDepth: 99 + }) + } + const taskId = db.createTask({ runId: run.id, spec: 'history' }).id + const insert = db.db + .prepare(`INSERT INTO dispatch_contexts(id, run_id, task_id, assignee_handle, assignee_orca_session_id, status, completed_at) + WITH RECURSIVE seq(n) AS (VALUES(1) UNION ALL SELECT n+1 FROM seq WHERE n < ?) + SELECT ? || n, ?, ?, ? || n, CASE WHEN ? THEN 'session-' || n ELSE NULL END, 'completed', '2020-01-01T00:00:00Z' FROM seq`) + insert.run(history, 'session-history-', run.id, taskId, 'session-address-', 1) + if (terminalHistory) { + insert.run( + terminalHistory, + 'terminal-history-', + run.id, + taskId, + 'terminal-address-', + 0 + ) + } + const active = db.db + .prepare( + "SELECT id, task_id FROM dispatch_contexts WHERE status = 'pending' ORDER BY rowid" + ) + .all() + const insertFact = db.db.prepare( + `INSERT INTO attempt_observation_facts(id, dispatch_id, task_id, sequence, authority_id, authority_clock, facet, payload, home_received_at) VALUES (?, ?, ?, ?, 'home', 'home', 'process_turn', '{"process":"running","turn":"working"}', ?)` + ) + for (let i = 0; i < attentionFacts; i++) { + const row = active[i % active.length] + if (typeof row?.id !== 'string' || typeof row.task_id !== 'string') { + throw new Error('Missing benchmark Dispatch') + } + insertFact.run( + `observation-${i}`, + row.id, + row.task_id, + Math.floor(i / active.length), + Date.now() + ) + } + db.db.exec('DROP INDEX idx_dispatch_session_presentation') + const first = performance.now() + db.createMailboxDeliveryIndexesIfPossible() + const indexMs = performance.now() - first + db.db.exec('DROP INDEX idx_dispatch_session_presentation') + db.close() + const openStarted = performance.now() + db = new OrchestrationDb(path) + const firstOpenIndexMs = performance.now() - openStarted + let observationVisits = 0 + db.db.function('lineage_observation_visit', {}, (_rowid: unknown) => { + observationVisits++ + return 1 + }) + let visits = 0 + db.db.function('lineage_bench_visit', {}, (_rowid: unknown) => { + visits++ + return 1 + }) + const prepare = db.db.prepare.bind(db.db) + const trace = vi + .spyOn(db.db, 'prepare') + .mockImplementation((query) => + prepare( + query + .replaceAll( + 'WHERE assignee_orca_session_id IS NOT NULL', + 'WHERE assignee_orca_session_id IS NOT NULL AND lineage_bench_visit(rowid)' + ) + .replace( + 'WHERE dispatch_id IN', + 'WHERE lineage_observation_visit(rowid) AND dispatch_id IN' + ) + ) + ) + const start = performance.now() + const output = projectionFor(db).buildByPaneKey() + const buildMs = performance.now() - start + const plans = trace.mock.calls + .filter( + ([query]) => + query.includes('idx_dispatch_session_presentation') || + query.includes('rowid AS n') + ) + .map(([query]) => + db.db + .prepare(`EXPLAIN QUERY PLAN ${query}`) + .all( + ...(query.includes('completed_at >= ?') + ? ['2026-10-26T00:00:00Z'] + : ['orca_session_id:bench-0']) + ) + ) + expect(Object.keys(output ?? {})).toHaveLength(20) + expect(visits).toBe(20) + expect(observationVisits).toBe(attentionFacts) + expect(JSON.stringify(plans)).not.toMatch(/SCAN dispatch_contexts/) + console.log( + 'LINEAGE_BENCH_ENVIRONMENT_EVIDENCE', + JSON.stringify({ + history, + terminalHistory, + attentionFacts, + observationVisits, + indexMs, + firstOpenIndexMs, + buildMs, + candidateVisits: visits, + sqlExecutions: trace.mock.calls.length, + plans + }) + ) + trace.mockRestore() + } finally { + db.close() + rmSync(directory, { recursive: true, force: true }) + } + } + } + } + } +) + +it('reads reopened/backfilled assignments and committed clear facts from the already opened store before host installation', async () => { + const directory = mkdtempSync(join(tmpdir(), 'orca-lineage-contract-')) + const root = sessionRecord(SESSION_X) + const successor = COORDINATOR_CHAT + await seedTestAgentSessionRecordStore(directory, { + records: [ + { + ...root, + conversationCommand: { + command: 'clear', + runtimeFence: root.lease.runtimeFence, + operationId: 'clear', + callerKey: 'test', + phase: 'committed', + state: 'completed', + replacementSessionId: successor + } + }, + sessionRecord(successor), + sessionRecord(SESSION_Y) + ], + sessionTabs: [ + { tabId: 'reserved-successor', sessionId: successor }, + { tabId: 'reserved-worker', sessionId: SESSION_Y } + ] + }) + closeTestJournalHostDatabase(directory) + const path = join(directory, 'orchestration.sqlite') + let db = new OrchestrationDb(path) + let opened = false + try { + const run = db.createRun({ + objective: 'cold public display', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: SESSION_X + }) + const privateHandles: string[] = [] + const privatePanes: string[] = [] + for (const id of [SESSION_Y, successor]) { + const handle = mintStructuredWorkerHandle() + const pane = mintStructuredWorkerPaneKey(id) + privateHandles.push(handle) + privatePanes.push(pane) + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'persisted worker' }).id, + assigneeHandle: handle, + assigneePaneKey: pane, + processIncarnation: structuredWorkerProcessIncarnation(id), + creator: { kind: 'session', orcaSessionId: SESSION_X }, + maxDepth: 99 + }) + } + db.db.exec('UPDATE dispatch_contexts SET assignee_orca_session_id = NULL') + db.close() + db = new OrchestrationDb(path) + const runtime = new OrcaRuntimeService() + runtime.setOrchestrationDb(db) + hostRef.current = null + const before = runtime['agentOrchestrationProjection'].buildByPaneKey() + expect(before?.[chatRow(SESSION_Y)]?.parentPaneKey).toBe(chatRow(SESSION_X)) + await openAgentSessionRecordStoreOnce({ + stateDirectory: directory, + hostId: 'local', + logger: recordingStructuredAgentSessionLogger().logger + }) + opened = true + const result = runtime['agentOrchestrationProjection'].buildByPaneKey() + expect(result?.[chatRow(SESSION_Y)]?.parentPaneKey).toBe(chatRow(successor)) + expect(result?.[chatRow(successor)]?.parentPaneKey).toBeUndefined() + for (const privateValue of [...privateHandles, ...privatePanes]) { + expect(JSON.stringify(result)).not.toContain(privateValue) + } + for (const status of ['idle', 'working', 'attention'] as const) { + runtime.onStructuredSessionStatusForMail({ sessionId: SESSION_Y, status }) + expect( + runtime['agentOrchestrationProjection'].buildByPaneKey()?.[chatRow(SESSION_Y)] + ?.parentPaneKey + ).toBe(chatRow(successor)) + } + } finally { + if (opened) { + ;(await releaseAgentSessionRecordStore())?.journalDatabase.close() + } + db.close() + rmSync(directory, { recursive: true, force: true }) + } +}) diff --git a/src/main/runtime/runtime-agent-orchestration-projection.ts b/src/main/runtime/runtime-agent-orchestration-projection.ts index f74d0285260e..c474055c27f6 100644 --- a/src/main/runtime/runtime-agent-orchestration-projection.ts +++ b/src/main/runtime/runtime-agent-orchestration-projection.ts @@ -1,7 +1,4 @@ -import { - AGENT_STATUS_STALE_AFTER_MS, - type AgentStatusOrchestrationContext -} from '../../shared/agent-status-types' +import type { AgentStatusOrchestrationContext } from '../../shared/agent-status-types' import type { FleetAgentStatusEvidence } from '../../shared/orchestration-fleet-agent-status-evidence' import { buildOrchestrationTaskDisplayMetadata } from '../../shared/orchestration-task-display' import { parsePaneKey } from '../../shared/stable-pane-id' @@ -13,9 +10,14 @@ import { projectWorkerAttentionContext } from './orchestration/worker-attention-context' import { worktreeIdsEqual } from '../../shared/worktree/id' +import type { AgentSessionRecordReader } from './orchestration/structured-session-lineage' +import { createOrchestrationProjectionScope } from './runtime-agent-orchestration-scope' +import { isRecentPresentationDispatch } from './orchestration/db/dispatch-context/dispatch-lookup' +import { currentRunCoordinatorOrcaSessionId } from './orchestration/db/runs/run-coordinator-orca-session' +import type { DispatchContextRow } from './orchestration/types' import type { PtyPaneOf } from './terminal/surface/pty-pane-query' -type RuntimeAgentOrchestrationDependencies = { +export type RuntimeAgentOrchestrationDependencies = { getDb(): OrchestrationDb | null getLeaves(): Iterable getPtys(): Iterable @@ -28,10 +30,7 @@ type RuntimeAgentOrchestrationDependencies = { getPaneKey(handle: string): string | null getDispatchAuthority(handle: string): OrchestrationCompatibilityTerminalAuthority | null getAgentStatusSnapshot(): readonly FleetAgentStatusEvidence[] - /** Chat workers have no leaf or PTY; their minted pane key is a mailbox credential, not a row. */ - getStructuredWorkers(): Iterable<{ handle: string; sessionId: string; paneKey: string }> - /** The chat row showing this session's conversation now, after any /clear. */ - getSessionDisplayPaneKey(orcaSessionId: string): string | null + getSessionRecords(): AgentSessionRecordReader | null } export class RuntimeAgentOrchestrationProjection { @@ -42,6 +41,7 @@ export class RuntimeAgentOrchestrationProjection { if (!db || db.hasAnyDispatchContexts?.() === false) { return undefined } + const scope = createOrchestrationProjectionScope(db, this.deps) const contexts: Record = {} const evidenceByPaneKey = new Map( this.deps.getAgentStatusSnapshot().map((evidence) => [evidence.activity.paneKey, evidence]) @@ -56,11 +56,16 @@ export class RuntimeAgentOrchestrationProjection { const handle = this.deps.issueLeafHandle(leaf) queriedHandles.add(handle) const paneKey = this.deps.makePaneKey(leaf) - const context = this.getForHandle(handle, db, { - paneKey, - evidence: evidenceByPaneKey.get(paneKey), - deferAttention: batchAttention - }) + const context = this.getForHandle( + handle, + db, + { + paneKey, + evidence: evidenceByPaneKey.get(paneKey), + deferAttention: batchAttention + }, + scope + ) if (context) { contexts[paneKey] = context } @@ -75,28 +80,33 @@ export class RuntimeAgentOrchestrationProjection { continue } queriedHandles.add(handle) - const context = this.getForHandle(handle, db, { - paneKey, - evidence: evidenceByPaneKey.get(paneKey), - deferAttention: batchAttention - }) + const context = this.getForHandle( + handle, + db, + { + paneKey, + evidence: evidenceByPaneKey.get(paneKey), + deferAttention: batchAttention + }, + scope + ) if (context) { contexts[paneKey] = context } } - for (const worker of this.deps.getStructuredWorkers()) { - const paneKey = this.deps.getSessionDisplayPaneKey(worker.sessionId) - if (!paneKey || contexts[paneKey] || queriedHandles.has(worker.handle)) { - continue - } - queriedHandles.add(worker.handle) - const context = this.getForHandle(worker.handle, db, { - paneKey: worker.paneKey, - evidence: evidenceByPaneKey.get(paneKey), - deferAttention: batchAttention - }) - if (context) { - contexts[paneKey] = context + for (const [paneKey, { dispatch }] of scope.sessionDispatches()) { + if (!contexts[paneKey]) { + contexts[paneKey] = this.projectDispatch( + dispatch, + dispatch.assignee_handle ?? '', + db, + { + paneKey, + evidence: evidenceByPaneKey.get(paneKey), + deferAttention: batchAttention + }, + scope + ) } } const entries = Object.entries(contexts) @@ -104,7 +114,7 @@ export class RuntimeAgentOrchestrationProjection { return undefined } if (batchAttention) { - const now = Date.now() + const now = scope.now const factsByDispatch = db.getWorkerAttentionFactsForDispatches( entries.map(([, context]) => context.dispatchId), now @@ -135,15 +145,27 @@ export class RuntimeAgentOrchestrationProjection { paneKey?: string evidence?: FleetAgentStatusEvidence deferAttention?: boolean - } = {} + } = {}, + scope = createOrchestrationProjectionScope(db, this.deps) ): AgentStatusOrchestrationContext | undefined { - const { paneKey, evidence, deferAttention = false } = options + const { paneKey } = options const dispatch = - db?.getActiveDispatchForTerminal?.(handle, paneKey) ?? this.getRecent(handle, db) + db?.getActiveDispatchForTerminal?.(handle, paneKey) ?? this.getRecent(handle, db, scope.now) if (!dispatch) { return undefined } - const task = db?.getTask?.(dispatch.task_id, dispatch.run_id) + return this.projectDispatch(dispatch, handle, db, options, scope) + } + + private projectDispatch( + dispatch: DispatchContextRow, + handle: string, + db: OrchestrationDb | null, + options: { paneKey?: string; evidence?: FleetAgentStatusEvidence; deferAttention?: boolean }, + scope: ReturnType + ): AgentStatusOrchestrationContext { + const { paneKey, evidence, deferAttention = false } = options + const task = scope.task(dispatch.task_id, dispatch.run_id) const display = typeof task?.spec === 'string' ? buildOrchestrationTaskDisplayMetadata({ @@ -153,7 +175,7 @@ export class RuntimeAgentOrchestrationProjection { }) : { taskTitle: '', displayName: '' } const owningRun = - task?.run_id && task.run_id === dispatch.run_id ? db?.getRun?.(dispatch.run_id) : undefined + task?.run_id && task.run_id === dispatch.run_id ? scope.run(dispatch.run_id) : undefined const runCoordinatorHandle = owningRun?.coordinator_handle ?? undefined const legacyActiveRun = owningRun?.legacy === 1 && (dispatch.status === 'pending' || dispatch.status === 'dispatched') @@ -189,7 +211,7 @@ export class RuntimeAgentOrchestrationProjection { currentCreatorPane && storedCreatorPane.leafId === currentCreatorPane.leafId)) ) - const paneRun = creatorPaneKey ? db?.getCurrentRunForPane?.(creatorPaneKey) : undefined + const paneRun = creatorPaneKey ? scope.pane(creatorPaneKey) : undefined const sameRunCreatorDispatch = Boolean( task?.creator_dispatch_id && task.creator_dispatch_run_id === owningRun?.id && @@ -214,12 +236,13 @@ export class RuntimeAgentOrchestrationProjection { ? (creatorPaneHandle ?? undefined) : undefined const selfSession = dispatch.assignee_orca_session_id + const selfPane = selfSession ? scope.resolve(selfSession) : paneKey const coordinatorSession = - owningRun?.legacy === 0 ? owningRun.coordinator_orca_session_id : null + owningRun?.legacy === 0 ? currentRunCoordinatorOrcaSessionId(owningRun) : null // Why: a chat party nests by its visible row; its handle and minted pane key match no row. - const coordinator = coordinatorSession - ? this.resolveSessionPane(coordinatorSession) - : this.resolveLivePane( + const coordinator: { handle?: string; paneKey?: string } = coordinatorSession + ? { paneKey: scope.resolve(coordinatorSession) } + : scope.resolveTerminal( coordinatorHandle, owningRun?.legacy === 0 ? owningRun.coordinator_pane_key : null ) @@ -227,15 +250,12 @@ export class RuntimeAgentOrchestrationProjection { dispatch.creator_orca_session_id && dispatch.creator_orca_session_id !== selfSession ? dispatch.creator_orca_session_id : null - const creator = creatorSession - ? this.resolveSessionPane(creatorSession) + const creator: { handle?: string; paneKey?: string } | undefined = creatorSession + ? { paneKey: scope.resolve(creatorSession) } : currentCreatorHandle - ? { - handle: currentCreatorHandle, - paneKey: this.deps.getPaneKey(currentCreatorHandle) ?? undefined - } + ? scope.resolveTerminal(currentCreatorHandle, creatorAuthority?.paneKey ?? null) : creatorLineageInRun - ? this.resolveLivePane(creatorPaneHandle, creatorPaneKey ?? null) + ? scope.resolveTerminal(creatorPaneHandle, creatorPaneKey ?? null) : undefined const coordinatorIsSelf = coordinator.handle === handle || @@ -245,14 +265,18 @@ export class RuntimeAgentOrchestrationProjection { coordinator.paneKey === paneKey) // Why: a creator whose pane is gone still has a coordinator to nest under. const parent = - creator?.handle || (creatorSession && creator?.paneKey) + (creator?.handle || (creatorSession && creator?.paneKey)) && + (!selfPane || creator?.paneKey !== selfPane) && + creator?.handle !== handle ? creator : coordinatorIsSelf ? {} - : coordinator + : coordinator.paneKey === selfPane + ? {} + : coordinator const attention = !deferAttention && db && typeof db.getWorkerAttentionFacts === 'function' - ? buildWorkerAttentionContext({ db, dispatch, task, evidence }) + ? buildWorkerAttentionContext({ db, dispatch, task, evidence, now: scope.now }) : undefined return { taskId: dispatch.task_id, @@ -268,48 +292,8 @@ export class RuntimeAgentOrchestrationProjection { } } - private resolveSessionPane(orcaSessionId: string): { handle?: string; paneKey?: string } { - const paneKey = this.deps.getSessionDisplayPaneKey(orcaSessionId) - return paneKey ? { paneKey } : {} - } - - /** Never publish stale process-local handles; re-resolve the durable pane key, retaining it while offline so restored rows can nest again. */ - private resolveLivePane( - storedHandle: string | null | undefined, - storedPaneKey: string | null - ): { handle?: string; paneKey?: string } { - if (storedHandle && this.deps.getWorktreeId(storedHandle) !== null) { - return { - handle: storedHandle, - paneKey: this.deps.getPaneKey(storedHandle) ?? storedPaneKey ?? undefined - } - } - if (!storedPaneKey) { - return {} - } - const liveHandle = this.deps.getHandleForPaneKey(storedPaneKey) - if (!liveHandle) { - return { paneKey: storedPaneKey } - } - return { handle: liveHandle, paneKey: this.deps.getPaneKey(liveHandle) ?? storedPaneKey } - } - - private getRecent(handle: string, db: OrchestrationDb | null) { + private getRecent(handle: string, db: OrchestrationDb | null, now: number) { const dispatch = db?.getLatestDispatchForTerminal?.(handle) - if ( - !dispatch?.completed_at || - dispatch.status === 'pending' || - dispatch.status === 'dispatched' - ) { - return undefined - } - const completedAt = Date.parse( - dispatch.completed_at.includes('T') - ? dispatch.completed_at - : `${dispatch.completed_at.replace(' ', 'T')}Z` - ) - return Number.isFinite(completedAt) && Date.now() - completedAt <= AGENT_STATUS_STALE_AFTER_MS - ? dispatch - : undefined + return dispatch && isRecentPresentationDispatch(dispatch, now) ? dispatch : undefined } } diff --git a/src/main/runtime/runtime-agent-orchestration-scope.ts b/src/main/runtime/runtime-agent-orchestration-scope.ts new file mode 100644 index 000000000000..31be7d7b40a5 --- /dev/null +++ b/src/main/runtime/runtime-agent-orchestration-scope.ts @@ -0,0 +1,97 @@ +import type { OrchestrationDb } from './orchestration/db' +import type { RuntimeAgentOrchestrationDependencies } from './runtime-agent-orchestration-projection' +import { createCanonicalSessionPaneResolver } from './orchestration/structured-session-lineage' +import { isStructuredWorkerHandle } from '../../shared/structured-worker-handle' + +export function createOrchestrationProjectionScope( + db: OrchestrationDb | null, + deps: RuntimeAgentOrchestrationDependencies +) { + const tasks = new Map>() + const runs = new Map>() + const panes = new Map>() + const now = Date.now() + const resolve = createCanonicalSessionPaneResolver(deps.getSessionRecords()) + return { + now, + resolve, + sessionDispatches: () => { + const destinations = new Map< + string, + ReturnType[number] + >() + for (const candidate of db?.listSessionDispatchesForPresentation(now) ?? []) { + if (!candidate.dispatch.assignee_orca_session_id) { + continue + } + const paneKey = resolve(candidate.dispatch.assignee_orca_session_id) + const previous = destinations.get(paneKey) + const active = + candidate.dispatch.status === 'pending' || candidate.dispatch.status === 'dispatched' + const previousActive = + previous?.dispatch.status === 'pending' || previous?.dispatch.status === 'dispatched' + if ( + !previous || + (active && !previousActive) || + (active === previousActive && candidate.order > previous.order) + ) { + destinations.set(paneKey, candidate) + } + } + return destinations + }, + resolveTerminal: (storedHandle: string | null | undefined, storedPaneKey: string | null) => + resolveLivePane(deps, storedHandle, storedPaneKey), + task: (id: string, run: string) => { + const key = `${run}:${id}` + if (!tasks.has(key)) { + tasks.set(key, db?.getTask?.(id, run)) + } + return tasks.get(key) + }, + run: (id: string) => { + if (!runs.has(id)) { + runs.set(id, db?.getRun?.(id)) + } + return runs.get(id) + }, + pane: (id: string) => { + if (!panes.has(id)) { + panes.set(id, db?.getCurrentRunForPane?.(id)) + } + return panes.get(id) + } + } +} + +/** Never publish stale process-local handles; re-resolve the durable pane key, retaining it while offline so restored rows can nest again. */ +function resolveLivePane( + deps: RuntimeAgentOrchestrationDependencies, + storedHandle: string | null | undefined, + storedPaneKey: string | null +): { handle?: string; paneKey?: string } { + // Structured mailbox panes are credentials, including stale rows with no current public proof. + if (isStructuredWorkerHandle(storedHandle)) { + return {} + } + if (storedHandle && deps.getWorktreeId(storedHandle) !== null) { + return { + handle: storedHandle, + paneKey: deps.getPaneKey(storedHandle) ?? storedPaneKey ?? undefined + } + } + if (storedPaneKey?.startsWith('structured-agent-session-')) { + return {} + } + if (!storedPaneKey) { + return {} + } + const liveHandle = deps.getHandleForPaneKey(storedPaneKey) + if (isStructuredWorkerHandle(liveHandle)) { + return {} + } + if (!liveHandle) { + return { paneKey: storedPaneKey } + } + return { handle: liveHandle, paneKey: deps.getPaneKey(liveHandle) ?? storedPaneKey } +} diff --git a/src/renderer/src/components/activity/activity-event-builder-sources.ts b/src/renderer/src/components/activity/activity-event-builder-sources.ts index 19394166226b..8ec07a07a55f 100644 --- a/src/renderer/src/components/activity/activity-event-builder-sources.ts +++ b/src/renderer/src/components/activity/activity-event-builder-sources.ts @@ -1,3 +1,5 @@ +import { getStructuredAgentSessionTabsByPaneKey } from '@/components/native-chat/structured-agent-session-tabs' +import { parseAgentStatusPaneIdentity } from '../../../../shared/agent-status-worktree-attribution' import { migrationUnsupportedToAgentStatusEntry } from '../../../../shared/migration-unsupported-agent-entry' import { parsePaneKey } from '../../../../shared/stable-pane-id' import type { TerminalTab } from '../../../../shared/terminal-tab-types' @@ -75,7 +77,14 @@ export function appendUnsupportedAndRetainedEvents(context: { } for (const [paneKey, retained] of Object.entries(args.retainedAgentsByPaneKey)) { - if (!parsePaneKey(paneKey)) { + if ( + !parseAgentStatusPaneIdentity( + paneKey, + args.unifiedTabsByWorktree + ? getStructuredAgentSessionTabsByPaneKey(args.unifiedTabsByWorktree).get(paneKey) + : undefined + ) + ) { continue } const owner = resolveOwner( diff --git a/src/renderer/src/components/activity/activity-event-builder.ts b/src/renderer/src/components/activity/activity-event-builder.ts index fb1b5e649fbb..ba60b09dd39f 100644 --- a/src/renderer/src/components/activity/activity-event-builder.ts +++ b/src/renderer/src/components/activity/activity-event-builder.ts @@ -1,3 +1,5 @@ +import { getStructuredAgentSessionTabsByPaneKey } from '@/components/native-chat/structured-agent-session-tabs' +import { parseAgentStatusPaneIdentity } from '../../../../shared/agent-status-worktree-attribution' import { freshActivityLiveAgentState } from './activity-event-state' import type { RetainedAgentEntry } from '@/store/slices/agent-status/agent-status-contract' import type { @@ -8,7 +10,6 @@ import type { import type { ExecutionHostId } from '../../../../shared/execution-host' import type { StructuredChatTabNames } from '@/runtime/structured-chat-tab-name' import type { Repo } from '../../../../shared/repo-types' -import { parsePaneKey } from '../../../../shared/stable-pane-id' import type { Tab } from '../../../../shared/tab-types' import type { TerminalTab } from '../../../../shared/terminal-tab-types' import type { Worktree } from '../../../../shared/worktree/types' @@ -83,7 +84,12 @@ export function buildActivityEvents( } for (const [paneKey, entry] of Object.entries(args.agentStatusByPaneKey)) { - const parsed = parsePaneKey(paneKey) + const parsed = parseAgentStatusPaneIdentity( + paneKey, + args.unifiedTabsByWorktree + ? getStructuredAgentSessionTabsByPaneKey(args.unifiedTabsByWorktree).get(paneKey) + : undefined + ) if (!parsed) { continue } diff --git a/src/renderer/src/components/activity/use-agent-pane-threads.ts b/src/renderer/src/components/activity/use-agent-pane-threads.ts index 43a32d6ad13d..130437fd530e 100644 --- a/src/renderer/src/components/activity/use-agent-pane-threads.ts +++ b/src/renderer/src/components/activity/use-agent-pane-threads.ts @@ -1,3 +1,4 @@ +import { selectVisibleAgentOrchestration } from '@/runtime/visible-agent-orchestration' import { useDeferredValue, useMemo, useRef } from 'react' import { useShallow } from 'zustand/react/shallow' import { useAppStore } from '@/store' @@ -111,7 +112,7 @@ export function useAgentPaneThreads(args: { const storeData = useAppStore( useShallow((s) => ({ agentStatusByPaneKey: s.agentStatusByPaneKey, - runtimeAgentOrchestrationByPaneKey: s.runtimeAgentOrchestrationByPaneKey, + runtimeAgentOrchestrationByPaneKey: selectVisibleAgentOrchestration(s), migrationUnsupportedByPtyId: s.migrationUnsupportedByPtyId, retainedAgentsByPaneKey: s.retainedAgentsByPaneKey, tabsByWorktree: s.tabsByWorktree, diff --git a/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts b/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts index ce4aaeb1d45a..99af818ba26e 100644 --- a/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts +++ b/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts @@ -69,7 +69,14 @@ export type DashboardSnapshotState = Pick< Partial< DashboardCardTerminalInputState & DashboardLaunchDetectionState & - Pick + Pick< + AppState, + | 'runtimeEnvironments' + | 'sshTargetLabels' + | 'unifiedTabsByWorktree' + | 'activeWorktreeId' + | 'activeWorkspaceExecutionHostId' + > > export type DashboardSnapshotInput = DashboardSnapshotState & { chatNames: StructuredChatTabNames } diff --git a/src/renderer/src/components/dashboard/useAgentBucketCounts.gate.test.ts b/src/renderer/src/components/dashboard/useAgentBucketCounts.gate.test.ts index c318a5de42b4..87b5f98529b7 100644 --- a/src/renderer/src/components/dashboard/useAgentBucketCounts.gate.test.ts +++ b/src/renderer/src/components/dashboard/useAgentBucketCounts.gate.test.ts @@ -133,10 +133,10 @@ describe('agent bucket count input gate', () => { expect(second.agentStatusEpoch).toBe(1) }) - it('carries every slice the counts read, and settings pinned to null', () => { + it('carries canonical contexts and every row-owner input the counts read', () => { const state = storeState() const inputs = selectAgentBucketCountState(state) - expect(inputs.settings).toBeNull() + expect(inputs.settings).toBe(state.settings) for (const key of [ 'repos', 'worktreesByRepo', diff --git a/src/renderer/src/components/dashboard/useAgentBucketCounts.ts b/src/renderer/src/components/dashboard/useAgentBucketCounts.ts index f0802621109c..c92e9850cc5b 100644 --- a/src/renderer/src/components/dashboard/useAgentBucketCounts.ts +++ b/src/renderer/src/components/dashboard/useAgentBucketCounts.ts @@ -6,7 +6,11 @@ import { buildDashboardBucketCounts, createDashboardBucketCountsCache } from './build-dashboard-bucket-counts' -import { selectFolderWorkspaces, selectWorktreesByRepo } from '@/store/workspace-record-selectors' +import { + selectDetectedWorktreesByRepo, + selectFolderWorkspaces, + selectWorktreesByRepo +} from '@/store/workspace-record-selectors' export type AgentBucketCounts = Record @@ -28,10 +32,16 @@ export type AgentBucketCountState = Pick< | 'folderWorkspaces' | 'acknowledgedAgentsByPaneKey' | 'agentStatusEpoch' -> & { - // Counts never render generated conversation names; keep this path off settings subscriptions. - settings: null -} + | 'settings' + | 'detectedWorktreesByRepo' + | 'projectGroups' + | 'restoredRuntimeHostIdByWorkspaceSessionKey' + | 'activeWorktreeId' + | 'activeWorkspaceExecutionHostId' + | 'runtimeEnvironments' + | 'runtimeEnvironmentCatalogHydrated' + | 'removedRuntimeEnvironmentIds' +> // Compare slice identities directly: useShallow allocates entries/Maps per store write. This pure state projection shares one allocation-free unchanged path across consumers. let previousState: AgentBucketCountState | null = null @@ -59,7 +69,17 @@ export function selectAgentBucketCountState(s: AppState): AgentBucketCountState previous.paneForegroundAgentByPaneKey === s.paneForegroundAgentByPaneKey && selectFolderWorkspaces(previous) === selectFolderWorkspaces(s) && previous.acknowledgedAgentsByPaneKey === s.acknowledgedAgentsByPaneKey && - previous.agentStatusEpoch === s.agentStatusEpoch + previous.agentStatusEpoch === s.agentStatusEpoch && + previous.settings === s.settings && + selectDetectedWorktreesByRepo(previous) === selectDetectedWorktreesByRepo(s) && + previous.projectGroups === s.projectGroups && + previous.restoredRuntimeHostIdByWorkspaceSessionKey === + s.restoredRuntimeHostIdByWorkspaceSessionKey && + previous.activeWorktreeId === s.activeWorktreeId && + previous.activeWorkspaceExecutionHostId === s.activeWorkspaceExecutionHostId && + previous.runtimeEnvironments === s.runtimeEnvironments && + previous.runtimeEnvironmentCatalogHydrated === s.runtimeEnvironmentCatalogHydrated && + previous.removedRuntimeEnvironmentIds === s.removedRuntimeEnvironmentIds ) { return previous } @@ -79,7 +99,15 @@ export function selectAgentBucketCountState(s: AppState): AgentBucketCountState folderWorkspaces: selectFolderWorkspaces(s), acknowledgedAgentsByPaneKey: s.acknowledgedAgentsByPaneKey, agentStatusEpoch: s.agentStatusEpoch, - settings: null + settings: s.settings, + detectedWorktreesByRepo: selectDetectedWorktreesByRepo(s), + projectGroups: s.projectGroups, + restoredRuntimeHostIdByWorkspaceSessionKey: s.restoredRuntimeHostIdByWorkspaceSessionKey, + activeWorktreeId: s.activeWorktreeId, + activeWorkspaceExecutionHostId: s.activeWorkspaceExecutionHostId, + runtimeEnvironments: s.runtimeEnvironments, + runtimeEnvironmentCatalogHydrated: s.runtimeEnvironmentCatalogHydrated, + removedRuntimeEnvironmentIds: s.removedRuntimeEnvironmentIds } return previousState } diff --git a/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts b/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts index 347adab3b8de..be48c17d1218 100644 --- a/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts +++ b/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts @@ -79,6 +79,8 @@ export function useLiveDashboardSnapshot(): DashboardSnapshot { buildDashboardSnapshot( { chatNames, + activeWorktreeId: launchRouteStore.activeWorktreeId, + activeWorkspaceExecutionHostId: launchRouteStore.activeWorkspaceExecutionHostId, repos, worktreesByRepo, tabsByWorktree, diff --git a/src/renderer/src/components/dashboard/worktree-agent-rows-cache.ts b/src/renderer/src/components/dashboard/worktree-agent-rows-cache.ts index 00e07d8e728f..6bd0aee71ce5 100644 --- a/src/renderer/src/components/dashboard/worktree-agent-rows-cache.ts +++ b/src/renderer/src/components/dashboard/worktree-agent-rows-cache.ts @@ -1,3 +1,4 @@ +import { getStructuredAgentSessionTabsByPaneKey } from '@/components/native-chat/structured-agent-session-tabs' import type { AgentStatusEntry, AgentStatusOrchestrationContext, @@ -146,6 +147,9 @@ export function selectWorktreeAgentRowsCached(args: { const rows = applyAgentRowLineage( buildWorktreeAgentRows({ tabs: tabs ?? [], + representedTabs: state.unifiedTabsByWorktree + ? getStructuredAgentSessionTabsByPaneKey(state.unifiedTabsByWorktree) + : undefined, entries, retained, runtimePaneTitlesByTabId: paneTitlesByTabId, diff --git a/src/renderer/src/components/native-chat/structured-agent-session-tabs.ts b/src/renderer/src/components/native-chat/structured-agent-session-tabs.ts index 188babc270fa..15ebacd1cf4d 100644 --- a/src/renderer/src/components/native-chat/structured-agent-session-tabs.ts +++ b/src/renderer/src/components/native-chat/structured-agent-session-tabs.ts @@ -1,3 +1,4 @@ +import { structuredAgentSessionPaneKey } from '../../../../shared/structured-agent-session-projection' import { isStructuredTab } from '../../../../shared/structured-agent-session-tab' import type { Tab } from '../../../../shared/tab-types' @@ -28,3 +29,21 @@ export function getStructuredAgentSessionTabs( structuredTabsByUnifiedTabsSnapshot.set(unifiedTabsByWorktree, tabs) return tabs } + +const paneTabs = new WeakMap, ReadonlyMap>() +export function getStructuredAgentSessionTabsByPaneKey( + tabs: Record +): ReadonlyMap { + const cached = paneTabs.get(tabs) + if (cached) { + return cached + } + const result = new Map( + getStructuredAgentSessionTabs(tabs).map((tab) => [ + structuredAgentSessionPaneKey(tab.id, tab.entityId), + tab + ]) + ) + paneTabs.set(tabs, result) + return result +} diff --git a/src/renderer/src/components/sidebar/WorkerLineage.fixture.tsx b/src/renderer/src/components/sidebar/WorkerLineage.fixture.tsx new file mode 100644 index 000000000000..23ad40070193 --- /dev/null +++ b/src/renderer/src/components/sidebar/WorkerLineage.fixture.tsx @@ -0,0 +1,68 @@ +import { defineFixture } from '../../component-fixtures/component-fixture' +import { CompactAgentRow } from './worktree-card-compact-agent-row' +import { applyAgentRowLineage } from '../dashboard/agent-row-lineage' +import { buildWorktreeAgentRows } from './worktree-agent-rows' +import { structuredAgentSessionPaneKey } from '../../../../shared/structured-agent-session-projection' +import type { Tab } from '../../../../shared/tab-types' +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' + +const now = 1_792_983_600_000 +const tabs: Tab[] = [ + '11111111-1111-4111-8111-111111111111', + '22222222-2222-4222-8222-222222222222' +].map((entityId, index) => ({ + id: index === 0 ? 'reserved-chat-tab' : 'worker-chat-tab:history-1', + entityId, + contentType: 'agent-session', + agentSessionAgent: 'codex', + worktreeId: 'fixture-workspace', + groupId: 'fixture-group', + executionHostId: 'local', + label: 'Chat', + customLabel: null, + color: null, + sortOrder: index, + createdAt: now +})) +const [parent, child] = tabs.map((tab) => structuredAgentSessionPaneKey(tab.id, tab.entityId)) +const entries: AgentStatusEntry[] = [parent, child].map((paneKey, index) => ({ + paneKey, + worktreeId: 'fixture-workspace', + agentType: 'codex', + state: 'working', + prompt: index === 0 ? 'Coordinate the release checks' : 'Verify the worker result', + updatedAt: now, + stateStartedAt: now, + stateHistory: [], + ...(index === 1 + ? { orchestration: { taskId: 'task', dispatchId: 'dispatch', parentPaneKey: parent } } + : {}) +})) +const rows = applyAgentRowLineage( + buildWorktreeAgentRows({ + tabs: [], + representedTabs: new Map( + tabs.map((tab) => [structuredAgentSessionPaneKey(tab.id, tab.entityId), tab]) + ), + entries, + retained: [], + now + }) +) + +export const nestedChatWorker = defineFixture({ + width: 380, + render: () => ( +
+ {rows.map((agent) => ( + {}} + cacheTimerActive={false} + /> + ))} +
+ ) +}) diff --git a/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx b/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx index 3b502328587c..9ef016a11e1d 100644 --- a/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx +++ b/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx @@ -220,3 +220,501 @@ describe('mounted worktree agent row subscriptions', () => { } }) }) + +it.each([20, 200])( + 'shares canonical receiving/alias work and preserves unaffected mounted rows at %i worktrees', + async (n) => { + const { structuredAgentSessionPaneKey: pane, structuredAgentSessionTabId: tabId } = + await import('../../../../shared/structured-agent-session-projection') + const { makeUnifiedTab } = await import('@/store/slices/store-test-helpers') + const { visibleOrchestrationWorkForTest } = + await import('@/runtime/visible-agent-orchestration') + const { _getWorktreeAgentOrchestrationIndexBuildCountForTest: indexBuilds } = + await import('./worktree-agent-orchestration-index') + const live: AppState['agentStatusByPaneKey'] = {} + const tabs: AppState['unifiedTabsByWorktree'] = {} + const raw: AppState['runtimeAgentOrchestrationByPaneKey'] = {} + const observed = new Map() + const counts = new Map() + for (let i = 0; i < n; i++) { + const worktreeId = `lineage-${i}` + tabs[worktreeId] = ['parent', 'child'].map((role) => + makeUnifiedTab({ + id: `${role}-actual-${i}`, + entityId: `${role}-${i}`, + groupId: 'group', + worktreeId, + contentType: 'agent-session', + agentSessionAgent: 'codex', + executionHostId: i === n - 1 ? 'runtime:other' : 'local' + }) + ) + for (const tab of tabs[worktreeId]) { + live[pane(tab.id, tab.entityId)] = { + ...entry(pane(tab.id, tab.entityId), worktreeId), + tabId: tab.id + } + } + raw[pane(tabId(`child-${i}`), `child-${i}`)] = { + taskId: `task-${i}`, + dispatchId: `dispatch-${i}`, + dispatchStatus: 'dispatched', + parentPaneKey: pane(tabId(`parent-${i}`), `parent-${i}`) + } + } + patch({ + tabsByWorktree: {}, + unifiedTabsByWorktree: tabs, + agentStatusByPaneKey: live, + runtimeAgentOrchestrationByPaneKey: {}, + retainedAgentsByPaneKey: {} + }) + act(() => useAppStore.getState().setRuntimeAgentOrchestrationByPaneKey(raw)) + function ManyProbe({ index }: { index: number }) { + observed.set(index, useWorktreeAgentRows(`lineage-${index}`)) + counts.set(index, (counts.get(index) ?? 0) + 1) + return null + } + act(() => + root.render(Array.from({ length: n }, (_, index) => )) + ) + const initial = new Map(observed) + counts.clear() + const beforeEqual = visibleOrchestrationWorkForTest() + const canonicalBefore = useAppStore.getState().runtimeAgentOrchestrationByPaneKey + act(() => useAppStore.getState().setRuntimeAgentOrchestrationByPaneKey(structuredClone(raw))) + expect(useAppStore.getState().runtimeAgentOrchestrationByPaneKey).toBe(canonicalBefore) + expect(counts.size).toBe(0) + expect(visibleOrchestrationWorkForTest()).toEqual(beforeEqual) + const changedKey = pane(tabId('child-0'), 'child-0') + for (const change of [ + { taskTitle: 'A real new title' }, + { dispatchStatus: 'completed' as const }, + { attention: { categories: ['input' as const], requiresAction: true } }, + { parentPaneKey: 'missing-parent' } + ]) { + const before = visibleOrchestrationWorkForTest() + const beforeIndex = indexBuilds() + counts.clear() + act(() => + useAppStore.getState().setRuntimeAgentOrchestrationByPaneKey({ + ...useAppStore.getState().runtimeAgentOrchestrationByPaneKey, + [changedKey]: { ...raw[changedKey], ...change } + }) + ) + expect(counts.get(0)).toBe(1) + expect( + observed.get(0)?.find((row) => row.paneKey === pane('child-actual-0', 'child-0'))?.entry + .orchestration + ).toMatchObject(change) + for (let i = 1; i < n; i++) { + expect(counts.has(i)).toBe(false) + expect(observed.get(i)).toBe(initial.get(i)) + } + const after = visibleOrchestrationWorkForTest() + expect(after.builds - before.builds).toBeLessThanOrEqual(1) + expect(after.aliasBuilds).toBe(before.aliasBuilds) + expect(indexBuilds() - beforeIndex).toBeLessThanOrEqual(1) + expect(after.visits - before.visits).toBeLessThanOrEqual(n * 14) + } + act(() => useAppStore.getState().setRuntimeAgentOrchestrationByPaneKey(raw)) + // Releasing one relationship preserves unrelated arrays even while its embedded completion remains. + counts.clear() + const remaining = { ...useAppStore.getState().runtimeAgentOrchestrationByPaneKey } + delete remaining[changedKey] + act(() => useAppStore.getState().setRuntimeAgentOrchestrationByPaneKey(remaining)) + for (let i = 1; i < n; i++) { + expect(observed.get(i)).toBe(initial.get(i)) + } + const epoch = useAppStore.getState().agentStatusEpoch + const beforeAlias = visibleOrchestrationWorkForTest() + patch({ + unifiedTabsByWorktree: { + ...tabs, + 'lineage-0': tabs['lineage-0'].map((tab) => + tab.entityId === 'parent-0' ? { ...tab, id: 'remapped-parent' } : tab + ) + } + }) + expect( + observed.get(0)?.find((row) => row.paneKey === pane('child-actual-0', 'child-0'))?.entry + .orchestration?.parentPaneKey + ).toBe(pane('remapped-parent', 'parent-0')) + expect(useAppStore.getState().agentStatusEpoch).toBe(epoch) + for (let i = 1; i < n; i++) { + expect(observed.get(i)).toBe(initial.get(i)) + } + expect(visibleOrchestrationWorkForTest().builds - beforeAlias.builds).toBe(1) + // A host change cannot attach a local worker to an identically named foreign parent. + patch({ + unifiedTabsByWorktree: { + ...tabs, + 'lineage-0': tabs['lineage-0'].map((tab) => + tab.entityId === 'parent-0' ? { ...tab, executionHostId: 'runtime:other' } : tab + ) + } + }) + expect( + observed.get(0)?.find((row) => row.paneKey === pane('child-actual-0', 'child-0')) + ?.parentPaneKey + ).not.toBe(pane('parent-actual-0', 'parent-0')) + for (let i = 1; i < n; i++) { + expect(observed.get(i)).toBe(initial.get(i)) + } + counts.clear() + const foreignRow = pane(`child-actual-${n - 1}`, `child-${n - 1}`) + act(() => + useAppStore + .getState() + .setAgentStatus( + foreignRow, + { state: 'working', agentType: 'codex', prompt: 'Another host update' }, + undefined, + { updatedAt: Date.now() + 1 }, + { tabId: `child-actual-${n - 1}`, worktreeId: `lineage-${n - 1}` } + ) + ) + for (let i = 0; i < n - 1; i++) { + expect(counts.has(i)).toBe(false) + } + } +) + +it('joins production mirrored custom/collision rows locally and keeps canonical initial, graph, retained and consumer contexts', async () => { + const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = + await import('../../../../main/runtime/runtime-agent-lineage.test-fixture') + const { makeUnifiedTab, makeWorktree, TEST_REPO } = + await import('@/store/slices/store-test-helpers') + const { buildMirroredAgentTabs } = + await import('@/runtime/web-session-tabs-sync/terminal-surfaces') + const { projectStatus } = + await import('@/components/native-chat/structured-agent-session-status-projection') + const { getStructuredAgentSessionTabs } = + await import('@/components/native-chat/structured-agent-session-tabs') + const { selectVisibleAgentOrchestration } = await import('@/runtime/visible-agent-orchestration') + const { structuredAgentSessionPaneKey: pane, structuredAgentSessionTabId: tabId } = + await import('../../../../shared/structured-agent-session-projection') + const { selectWorktreeAgentActivitySummary } = await import('./worktree-agent-activity-summary') + const { selectDashboardOrchestration } = + await import('@/components/dashboard/dashboard-orchestration-selection') + const { selectWorktreeAgentRowsCached } = + await import('@/components/dashboard/worktree-agent-rows-cache') + const { buildActivityEvents } = await import('@/components/activity/activity-event-builder') + const f = publicLineageFixture('folder-a') + try { + const predecessor = makeUnifiedTab({ + id: 'reserved-parent', + entityId: 'old-parent', + groupId: 'g', + worktreeId: 'folder-a', + contentType: 'agent-session', + agentSessionAgent: 'codex', + executionHostId: 'local' + }) + const occupied = makeUnifiedTab({ + id: tabId(LINEAGE_CHILD), + entityId: 'unrelated', + groupId: 'g', + worktreeId: 'folder-a' + }) + const mirrored = buildMirroredAgentTabs( + { + worktree: 'folder-a', + publicationEpoch: 'test', + snapshotVersion: 1, + activeGroupId: 'g', + activeTabId: null, + activeTabType: 'agent-session', + tabs: [ + { + type: 'agent-session', + id: 'host-parent', + title: 'Parent', + sessionId: LINEAGE_PARENT, + replacesSessionId: 'old-parent', + agent: 'codex', + isActive: false + }, + { + type: 'agent-session', + id: 'host-child', + title: 'Child', + sessionId: LINEAGE_CHILD, + agent: 'codex', + isActive: false + } + ] + }, + 'local', + new Map(), + 'g', + 0, + [predecessor, occupied], + Date.now() + ).map((item) => item.unifiedTab) + expect(mirrored[0].id).toBe('reserved-parent') + expect(mirrored[1].id).toContain(':history-1') + const raw = f.projection.buildByPaneKey() ?? {} + patch({ + tabsByWorktree: {}, + unifiedTabsByWorktree: {}, + agentStatusByPaneKey: {}, + retainedAgentsByPaneKey: {}, + runtimeAgentOrchestrationByPaneKey: {} + }) + act(() => useAppStore.getState().setRuntimeAgentOrchestrationByPaneKey(raw)) + const canonical = useAppStore.getState().runtimeAgentOrchestrationByPaneKey + patch({ unifiedTabsByWorktree: { 'folder-a': mirrored } }) + const actualParent = pane(mirrored[0].id, LINEAGE_PARENT) + const actualChild = pane(mirrored[1].id, LINEAGE_CHILD) + expect(selectVisibleAgentOrchestration(useAppStore.getState())[actualChild].parentPaneKey).toBe( + actualParent + ) + const emitStatuses = () => + act(() => + useAppStore.getState().transactAgentStatuses((transaction) => { + for (const tab of getStructuredAgentSessionTabs( + useAppStore.getState().unifiedTabsByWorktree + )) { + projectStatus( + transaction, + tab, + { + sessionId: tab.entityId, + workspaceId: tab.worktreeId, + agent: 'codex', + status: 'working', + latestPrompt: tab.label, + updatedAt: Date.now(), + hostExecutionOwned: true + }, + 'live', + null + ) + } + }) + ) + emitStatuses() + expect( + useAppStore.getState().agentStatusByPaneKey[actualChild].orchestration?.parentPaneKey + ).toBe(canonicalChatRow(LINEAGE_PARENT)) + expect(useAppStore.getState().runtimeAgentOrchestrationByPaneKey).toBe(canonical) + act(() => root.render()) + expect(rows.map((row) => row.paneKey)).toEqual([actualParent, actualChild]) + expect(rows[1].entry.orchestration?.parentPaneKey).toBe(actualParent) + const worktree = makeWorktree({ id: 'folder-a', repoId: TEST_REPO.id }) + patch({ repos: [TEST_REPO], worktreesByRepo: { [TEST_REPO.id]: [worktree] } }) + const state = useAppStore.getState() + const singleton = selectDashboardOrchestration(state, [{ worktree }]).singletonOrchestration + const batch = selectDashboardOrchestration(state, [ + { worktree }, + { worktree: { ...worktree, id: 'other' } } + ]).orchestrationByWorktree?.get('folder-a') + expect(batch).toBe(singleton) + const dashboard = selectWorktreeAgentRowsCached({ + state, + worktreeId: 'folder-a', + orchestration: singleton ?? {}, + now: Date.now(), + generation: 1 + }) + expect(dashboard.map((row) => row.lineage.depth)).toEqual([0, 1]) + expect(selectWorktreeAgentActivitySummary(state, 'folder-a').hasLiveWorking).toBe(true) + const activity = buildActivityEvents({ + ...state, + chatNames: new Map(), + tabsByWorktree: state.tabsByWorktree, + unifiedTabsByWorktree: state.unifiedTabsByWorktree, + worktreeMap: new Map([[worktree.id, worktree]]), + repoMap: new Map([[TEST_REPO.id, TEST_REPO]]), + runtimeAgentOrchestrationByPaneKey: selectVisibleAgentOrchestration(state), + now: Date.now() + }) + expect(activity.paneEntryByPaneKey[actualChild]?.orchestration?.parentPaneKey).toBe( + actualParent + ) + expect(activity.paneEntryByPaneKey[actualParent]).toBeDefined() + const { getWorkspaceCleanupAgentEvidence } = + await import('@/store/slices/workspace-cleanup-agent-evidence') + const { makeCandidate } = await import('@/store/slices/workspace-cleanup-slice-test-harness') + expect([ + ...getWorkspaceCleanupAgentEvidence(state, [ + makeCandidate({ worktreeId: 'folder-a', executionHostId: 'local' }) + ]).values() + ]).toEqual(['live']) + const { buildDashboardSnapshot } = + await import('@/components/dashboard/build-dashboard-snapshot') + const snapshot = buildDashboardSnapshot({ ...state, chatNames: new Map() }, Date.now()) + expect(JSON.stringify(snapshot)).toContain(actualChild) + expect(JSON.stringify(snapshot)).toContain(actualParent) + + // Payload-before-graph and a retained terminal child's embedded parent use that same read-side join. + act(() => useAppStore.getState().setRuntimeAgentOrchestrationByPaneKey({})) + expect(selectVisibleAgentOrchestration(useAppStore.getState())[actualChild].parentPaneKey).toBe( + actualParent + ) + const terminal = { + ...entry(KEY_B, 'folder-a'), + state: 'done' as const, + orchestration: raw[canonicalChatRow(LINEAGE_CHILD)] + } + act(() => + useAppStore.getState().retainAgents([ + { + entry: terminal, + worktreeId: 'folder-a', + tab: makeTab({ id: 'tab-b', worktreeId: 'folder-a' }), + agentType: 'codex', + startedAt: Date.now() + } + ]) + ) + expect(selectVisibleAgentOrchestration(useAppStore.getState())[KEY_B].parentPaneKey).toBe( + actualParent + ) + // Alias rederivation is immediate and writes neither canonical storage nor an epoch. + const epoch = useAppStore.getState().agentStatusEpoch + patch({ + unifiedTabsByWorktree: { + 'folder-a': mirrored.map((tab, index) => (index === 0 ? { ...tab, id: 'new-parent' } : tab)) + } + }) + expect(selectVisibleAgentOrchestration(useAppStore.getState())[actualChild].parentPaneKey).toBe( + pane('new-parent', LINEAGE_PARENT) + ) + expect(useAppStore.getState().agentStatusEpoch).toBe(epoch) + patch({ + unifiedTabsByWorktree: { + 'folder-a': mirrored.map((tab, index) => + index === 0 ? { ...tab, executionHostId: 'runtime:foreign' } : tab + ) + } + }) + expect( + selectVisibleAgentOrchestration(useAppStore.getState())[actualChild]?.parentPaneKey + ).not.toBe(actualParent) + } finally { + f.db.close() + } +}) + +it('settles the production graph subscription/scheduler/publication/receiver loop with at most one feedback flight', async () => { + const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = + await import('../../../../main/runtime/runtime-agent-lineage.test-fixture') + const { useRuntimeGraphSync } = await import('@/app-shell/use-runtime-graph-sync') + const { setRuntimeGraphSyncEnabled, setRuntimeGraphStoreStateGetter } = + await import('@/runtime/sync-runtime-graph') + const { graphState } = await import('@/runtime/sync-runtime-graph/graph-state') + const { makeUnifiedTab } = await import('@/store/slices/store-test-helpers') + const { selectVisibleAgentOrchestration } = await import('@/runtime/visible-agent-orchestration') + const { structuredAgentSessionPaneKey: pane } = + await import('../../../../shared/structured-agent-session-projection') + const f = publicLineageFixture('folder-a') + const response = { + runtimeId: 'lineage', + rendererGraphEpoch: 1, + graphStatus: 'ready' as const, + authoritativeWindowId: null, + liveTabCount: 0, + liveLeafCount: 0, + agentOrchestrationByPaneKey: f.projection.buildByPaneKey() + } + let release: (() => void) | undefined + let fail = false + let hold = true + const previousApi = window.api + const sync = vi.fn(async () => { + if (hold) { + await new Promise((resolve) => { + release = resolve + }) + } + if (fail) { + throw new Error('expected transport failure') + } + return structuredClone(response) + }) + Reflect.set(window, 'api', { + ...previousApi, + runtime: { ...previousApi?.runtime, syncWindowGraph: sync } + }) + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + function SyncProbe() { + useRuntimeGraphSync() + return null + } + const flush = () => + act(async () => { + await vi.advanceTimersByTimeAsync(20) + }) + try { + patch({ + workspaceSessionReady: true, + tabsByWorktree: {}, + unifiedTabsByWorktree: {}, + retainedAgentsByPaneKey: {}, + runtimeAgentOrchestrationByPaneKey: {}, + agentStatusByPaneKey: { + [canonicalChatRow(LINEAGE_CHILD)]: entry(canonicalChatRow(LINEAGE_CHILD), 'folder-a') + } + }) + act(() => root.render()) + await flush() + expect(sync).toHaveBeenCalledTimes(1) + const parent = makeUnifiedTab({ + id: 'late-parent', + entityId: LINEAGE_PARENT, + groupId: 'g', + worktreeId: 'folder-a', + contentType: 'agent-session', + agentSessionAgent: 'codex', + executionHostId: 'local' + }) + patch({ unifiedTabsByWorktree: { 'folder-a': [parent] } }) + hold = false + await act(async () => { + release?.() + await Promise.resolve() + }) + await flush() + expect(sync).toHaveBeenCalledTimes(2) + const stable = useAppStore.getState() + expect( + selectVisibleAgentOrchestration(stable)[canonicalChatRow(LINEAGE_CHILD)].parentPaneKey + ).toBe(pane(parent.id, LINEAGE_PARENT)) + await flush() + expect(sync).toHaveBeenCalledTimes(2) + expect(useAppStore.getState().runtimeAgentOrchestrationByPaneKey).toBe( + stable.runtimeAgentOrchestrationByPaneKey + ) + expect(useAppStore.getState().agentStatusByPaneKey).toBe(stable.agentStatusByPaneKey) + expect(useAppStore.getState().agentStatusEpoch).toBe(stable.agentStatusEpoch) + fail = true + patch({ unifiedTabsByWorktree: { 'folder-a': [{ ...parent, label: 'legitimate wake' }] } }) + await flush() + expect(sync).toHaveBeenCalledTimes(3) + expect(graphState.syncInFlight).toBe(false) + await flush() + expect(sync).toHaveBeenCalledTimes(3) + setRuntimeGraphSyncEnabled(false) + patch({ unifiedTabsByWorktree: { 'folder-a': [{ ...parent, id: 'disabled-local-alias' }] } }) + expect( + selectVisibleAgentOrchestration(useAppStore.getState())[canonicalChatRow(LINEAGE_CHILD)] + .parentPaneKey + ).toBe(pane('disabled-local-alias', LINEAGE_PARENT)) + await flush() + expect(sync).toHaveBeenCalledTimes(3) + fail = false + setRuntimeGraphSyncEnabled(true) + await flush() + expect(sync).toHaveBeenCalledTimes(4) + await flush() + expect(sync).toHaveBeenCalledTimes(4) + } finally { + setRuntimeGraphSyncEnabled(false) + setRuntimeGraphStoreStateGetter(null) + Reflect.set(window, 'api', previousApi) + error.mockRestore() + f.db.close() + } +}) diff --git a/src/renderer/src/components/sidebar/useWorktreeAgentRows.ts b/src/renderer/src/components/sidebar/useWorktreeAgentRows.ts index e54c1a78c204..030eeb3ca7b5 100644 --- a/src/renderer/src/components/sidebar/useWorktreeAgentRows.ts +++ b/src/renderer/src/components/sidebar/useWorktreeAgentRows.ts @@ -1,3 +1,4 @@ +import { getStructuredAgentSessionTabsByPaneKey } from '@/components/native-chat/structured-agent-session-tabs' import { useCallback, useMemo, useSyncExternalStore } from 'react' import type { DashboardAgentRow } from '@/components/dashboard/useDashboardData' import { applyAgentRowLineage } from '@/components/dashboard/agent-row-lineage' @@ -117,6 +118,9 @@ export function useWorktreeAgentRows(worktreeId: string, active = true): Dashboa return applyAgentRowLineage( buildWorktreeAgentRows({ tabs: tabs ?? EMPTY_TABS, + representedTabs: getStructuredAgentSessionTabsByPaneKey( + useAppStore.getState().unifiedTabsByWorktree + ), entries, retained, runtimePaneTitlesByTabId, diff --git a/src/renderer/src/components/sidebar/worktree-agent-activity-summary.ts b/src/renderer/src/components/sidebar/worktree-agent-activity-summary.ts index d07ed32bc39e..344639edb05e 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-activity-summary.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-activity-summary.ts @@ -1,3 +1,8 @@ +import { getStructuredAgentSessionTabsByPaneKey } from '@/components/native-chat/structured-agent-session-tabs' +import { + selectVisibleAgentOrchestration, + type VisibleOrchestrationState +} from '@/runtime/visible-agent-orchestration' import type { AppState } from '@/store' import { isExplicitAgentStatusFresh } from '@/lib/agent-status' import { migrationUnsupportedToAgentStatusEntry } from '../../../../shared/migration-unsupported-agent-entry' @@ -56,10 +61,11 @@ export type AgentActivityInput = Pick< | 'agentStatusByPaneKey' | 'migrationUnsupportedByPtyId' | 'retainedAgentsByPaneKey' -> & { - tabsByWorktree: AgentActivityTabsByWorktree - runtimeAgentOrchestrationByPaneKey?: AppState['runtimeAgentOrchestrationByPaneKey'] -} +> & + VisibleOrchestrationState & { + tabsByWorktree: AgentActivityTabsByWorktree + runtimeAgentOrchestrationByPaneKey?: AppState['runtimeAgentOrchestrationByPaneKey'] + } type AgentActivityCache = { tabsByWorktree: AgentActivityTabsByWorktree @@ -82,7 +88,7 @@ export function selectWorktreeAgentActivitySummary( function getWorktreeAgentActivitySummaries( state: AgentActivityInput ): Map { - const runtimeAgentOrchestrationByPaneKey = state.runtimeAgentOrchestrationByPaneKey + const runtimeAgentOrchestrationByPaneKey = selectVisibleAgentOrchestration(state) if ( agentActivityCache && agentActivityCache.tabsByWorktree === state.tabsByWorktree && @@ -114,7 +120,12 @@ function getWorktreeAgentActivitySummaries( const now = Date.now() for (const [paneKey, entry] of Object.entries(state.agentStatusByPaneKey)) { - const paneIdentity = parseAgentStatusPaneIdentity(paneKey) + const paneIdentity = parseAgentStatusPaneIdentity( + paneKey, + state.unifiedTabsByWorktree + ? getStructuredAgentSessionTabsByPaneKey(state.unifiedTabsByWorktree).get(paneKey) + : undefined + ) if (!paneIdentity) { continue } @@ -276,7 +287,12 @@ function worktreeIdForPaneKey( paneKey: string | undefined, tabIdToWorktreeId: Map ): string | null { - const paneIdentity = parseAgentStatusPaneIdentity(paneKey) + const paneIdentity = parseAgentStatusPaneIdentity( + paneKey, + state.unifiedTabsByWorktree + ? getStructuredAgentSessionTabsByPaneKey(state.unifiedTabsByWorktree).get(paneKey) + : undefined + ) return paneIdentity ? (tabIdToWorktreeId.get(paneIdentity.tabId) ?? null) : null } diff --git a/src/renderer/src/components/sidebar/worktree-agent-live-index-patch.ts b/src/renderer/src/components/sidebar/worktree-agent-live-index-patch.ts index df4f21cfd12b..9eafdf401a21 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-live-index-patch.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-live-index-patch.ts @@ -1,7 +1,8 @@ +import type { Tab } from '../../../../shared/tab-types' +import { parseAgentStatusPaneIdentity } from '../../../../shared/agent-status-worktree-attribution' import { resolveAgentStatusWorktreeId } from '../../../../shared/agent-status-worktree-attribution' import type { AppState } from '@/store/types' import type { AgentStatusEntry } from '../../../../shared/agent-status-types' -import { parsePaneKey } from '../../../../shared/stable-pane-id' import { isWebTerminalSurfaceTabId } from '../../../../shared/terminal-surface-id' export type LiveEntriesByWorktreeCache = { @@ -24,9 +25,10 @@ export function recordLiveEntriesFullRebuild(): void { export function liveEntryWorktreeId( paneKey: string, entry: AgentStatusEntry, - tabIdToWorktreeId: Map + tabIdToWorktreeId: Map, + representedTabs?: ReadonlyMap ): string | undefined { - const parsed = parsePaneKey(paneKey) + const parsed = parseAgentStatusPaneIdentity(paneKey, representedTabs?.get(paneKey)) if (!parsed) { return undefined } @@ -42,7 +44,8 @@ export function liveEntryWorktreeId( export function patchLiveEntriesByWorktree( cache: LiveEntriesByWorktreeCache, agentStatusByPaneKey: AppState['agentStatusByPaneKey'], - tabIdToWorktreeId: Map + tabIdToWorktreeId: Map, + representedTabs?: ReadonlyMap ): Map | null { const previousMap = cache.agentStatusByPaneKey const changed: { paneKey: string; entry: AgentStatusEntry }[] = [] @@ -76,7 +79,7 @@ export function patchLiveEntriesByWorktree( const entriesByWorktree = new Map(cache.entriesByWorktree) const clonedBuckets = new Set() for (const { paneKey, entry } of changed) { - const worktreeId = liveEntryWorktreeId(paneKey, entry, tabIdToWorktreeId) + const worktreeId = liveEntryWorktreeId(paneKey, entry, tabIdToWorktreeId, representedTabs) if (!worktreeId) { continue } diff --git a/src/renderer/src/components/sidebar/worktree-agent-orchestration-index.ts b/src/renderer/src/components/sidebar/worktree-agent-orchestration-index.ts index 41bfb22e804c..6dbdbf3e9329 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-orchestration-index.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-orchestration-index.ts @@ -1,3 +1,8 @@ +import { + selectVisibleAgentOrchestration, + representedOrchestrationWorktrees, + type VisibleOrchestrationState +} from '@/runtime/visible-agent-orchestration' import type { AppState } from '@/store/types' import type { AgentStatusOrchestrationContext } from '../../../../shared/agent-status-types' import { parsePaneKey } from '../../../../shared/stable-pane-id' @@ -8,7 +13,8 @@ type OrchestrationIndexState = Pick< | 'retainedAgentsByPaneKey' | 'runtimeAgentOrchestrationByPaneKey' | 'tabsByWorktree' -> +> & + VisibleOrchestrationState type RuntimeOrchestrationRecord = Record @@ -26,6 +32,7 @@ type PaneWorktreeProjectionCache = { runtimeSource: OrchestrationIndexState['runtimeAgentOrchestrationByPaneKey'] liveSource: OrchestrationIndexState['agentStatusByPaneKey'] retainedSource: OrchestrationIndexState['retainedAgentsByPaneKey'] + representedSource: OrchestrationIndexState['unifiedTabsByWorktree'] paneWorktreeIds: readonly (string | undefined)[] } @@ -76,27 +83,37 @@ function projectPaneWorktreeIds( runtimeSource: OrchestrationIndexState['runtimeAgentOrchestrationByPaneKey'], runtimeEntries: readonly [string, AgentStatusOrchestrationContext][], agentStatusByPaneKey: OrchestrationIndexState['agentStatusByPaneKey'], - retainedAgentsByPaneKey: OrchestrationIndexState['retainedAgentsByPaneKey'] + retainedAgentsByPaneKey: OrchestrationIndexState['retainedAgentsByPaneKey'], + state: OrchestrationIndexState ): readonly (string | undefined)[] { // Cache by map identity so all cards share one attribution scan per publication. if ( paneWorktreeProjectionCache?.runtimeSource === runtimeSource && paneWorktreeProjectionCache.liveSource === agentStatusByPaneKey && - paneWorktreeProjectionCache.retainedSource === retainedAgentsByPaneKey + paneWorktreeProjectionCache.retainedSource === retainedAgentsByPaneKey && + paneWorktreeProjectionCache.representedSource === state.unifiedTabsByWorktree ) { return paneWorktreeProjectionCache.paneWorktreeIds } const paneWorktreeIds: (string | undefined)[] = [] - for (const [paneKey] of runtimeEntries) { + const represented = state.unifiedTabsByWorktree + ? representedOrchestrationWorktrees(state) + : new Map() + for (const [paneKey, context] of runtimeEntries) { paneWorktreeIds.push( agentStatusByPaneKey[paneKey]?.worktreeId, - retainedAgentsByPaneKey[paneKey]?.worktreeId + retainedAgentsByPaneKey[paneKey]?.worktreeId, + represented.get(paneKey), + represented.size > 0 && context.parentPaneKey + ? represented.get(context.parentPaneKey) + : undefined ) } paneWorktreeProjectionCache = { runtimeSource, liveSource: agentStatusByPaneKey, retainedSource: retainedAgentsByPaneKey, + representedSource: state.unifiedTabsByWorktree, paneWorktreeIds } return paneWorktreeIds @@ -195,7 +212,15 @@ function buildIndex( } const liveWorktreeId = paneWorktreeIds[projectionCursor] const retainedWorktreeId = paneWorktreeIds[projectionCursor + 1] - projectionCursor += 2 + const representedWorktreeId = paneWorktreeIds[projectionCursor + 2] + const parentWorktreeId = paneWorktreeIds[projectionCursor + 3] + if (representedWorktreeId) { + targets.add(representedWorktreeId) + } + if (parentWorktreeId) { + targets.add(parentWorktreeId) + } + projectionCursor += 4 if (typeof liveWorktreeId === 'string') { targets.add(liveWorktreeId) } @@ -227,8 +252,7 @@ function buildIndex( export function selectWorktreeAgentOrchestrationIndex( state: OrchestrationIndexState ): ReadonlyMap { - const runtimeAgentOrchestrationByPaneKey = - state.runtimeAgentOrchestrationByPaneKey ?? EMPTY_SOURCE + const runtimeAgentOrchestrationByPaneKey = selectVisibleAgentOrchestration(state) // Cache context entries separately so unrelated live/retained churn cannot force enumeration. if (runtimeEntriesCache?.source !== runtimeAgentOrchestrationByPaneKey) { runtimeEntriesCache = { @@ -251,7 +275,8 @@ export function selectWorktreeAgentOrchestrationIndex( runtimeAgentOrchestrationByPaneKey, runtimeEntries, state.agentStatusByPaneKey ?? EMPTY_SOURCE, - state.retainedAgentsByPaneKey ?? EMPTY_SOURCE + state.retainedAgentsByPaneKey ?? EMPTY_SOURCE, + state ) if ( orchestrationIndexCache?.runtimeSource === runtimeAgentOrchestrationByPaneKey && diff --git a/src/renderer/src/components/sidebar/worktree-agent-row-fallback-tab.ts b/src/renderer/src/components/sidebar/worktree-agent-row-fallback-tab.ts index 18ec88e62086..72237e08cba1 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-row-fallback-tab.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-row-fallback-tab.ts @@ -1,5 +1,6 @@ import type { AgentStatusEntry } from '../../../../shared/agent-status-types' -import { parsePaneKey } from '../../../../shared/stable-pane-id' +import { parseAgentStatusPaneIdentity } from '../../../../shared/agent-status-worktree-attribution' +import type { Tab } from '../../../../shared/tab-types' import type { TerminalTab } from '../../../../shared/terminal-tab-types' export function effectiveWorktreeAgentRowStartedAt(entry: AgentStatusEntry): number { @@ -8,9 +9,10 @@ export function effectiveWorktreeAgentRowStartedAt(entry: AgentStatusEntry): num export function tabFromWorktreeAttributedStatusEntry( entry: AgentStatusEntry, - effectiveStartedAt: number + effectiveStartedAt: number, + representedTab?: Tab ): TerminalTab | null { - const parsed = parsePaneKey(entry.paneKey) + const parsed = parseAgentStatusPaneIdentity(entry.paneKey, representedTab) if (!parsed || !entry.worktreeId) { return null } diff --git a/src/renderer/src/components/sidebar/worktree-agent-row-orchestration.ts b/src/renderer/src/components/sidebar/worktree-agent-row-orchestration.ts index abf5df6c5dc4..f959da82fb16 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-row-orchestration.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-row-orchestration.ts @@ -3,21 +3,7 @@ import type { AgentStatusOrchestrationContext } from '../../../../shared/agent-status-types' -function orchestrationContextsEqual( - a: AgentStatusOrchestrationContext, - b: AgentStatusOrchestrationContext -): boolean { - return ( - a.taskId === b.taskId && - a.dispatchId === b.dispatchId && - a.taskTitle === b.taskTitle && - a.displayName === b.displayName && - a.parentTerminalHandle === b.parentTerminalHandle && - a.parentPaneKey === b.parentPaneKey && - a.coordinatorHandle === b.coordinatorHandle && - a.orchestrationRunId === b.orchestrationRunId - ) -} +import { orchestrationContextsEqual } from '@/store/slices/agent-status/agent-status-orchestration-context' export function entryWithRuntimeOrchestration( entry: AgentStatusEntry, diff --git a/src/renderer/src/components/sidebar/worktree-agent-row-selectors.ts b/src/renderer/src/components/sidebar/worktree-agent-row-selectors.ts index 7828bc624646..94938dfaf84b 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-row-selectors.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-row-selectors.ts @@ -1,3 +1,4 @@ +import { getStructuredAgentSessionTabsByPaneKey } from '@/components/native-chat/structured-agent-session-tabs' import type { RetainedAgentEntry } from '@/store/slices/agent-status/agent-status-contract' import type { AppState } from '@/store/types' import type { @@ -129,6 +130,9 @@ function getLiveEntriesByWorktree(state: WorktreeAgentRowsState): Map() for (const [paneKey, entry] of Object.entries(agentStatusByPaneKey)) { - const worktreeId = liveEntryWorktreeId(paneKey, entry, tabIdToWorktreeId) + const worktreeId = liveEntryWorktreeId(paneKey, entry, tabIdToWorktreeId, represented) if (!worktreeId) { continue } diff --git a/src/renderer/src/components/sidebar/worktree-agent-rows.ts b/src/renderer/src/components/sidebar/worktree-agent-rows.ts index 6f46eb6e06f7..31977d6b14a9 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-rows.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-rows.ts @@ -1,3 +1,5 @@ +import type { Tab } from '../../../../shared/tab-types' +import { parseAgentStatusPaneIdentity } from '../../../../shared/agent-status-worktree-attribution' import type { DashboardAgentRow } from '@/components/dashboard/useDashboardData' import { isExplicitAgentStatusFresh } from '@/lib/agent-status' import type { RetainedAgentEntry } from '@/store/slices/agent-status/agent-status-contract' @@ -138,6 +140,7 @@ function markCompletedWorkerParentPaneKeysSeen(args: { export function buildWorktreeAgentRows(args: { tabs: TerminalTab[] + representedTabs?: ReadonlyMap entries: AgentStatusEntry[] retained: RetainedAgentEntry[] runtimePaneTitlesByTabId?: Record> @@ -153,7 +156,10 @@ export function buildWorktreeAgentRows(args: { const entriesByTabId = new Map() for (const entry of args.entries) { - const parsed = parsePaneKey(entry.paneKey) + const parsed = parseAgentStatusPaneIdentity( + entry.paneKey, + args.representedTabs?.get(entry.paneKey) + ) if (!parsed) { continue } @@ -211,7 +217,11 @@ export function buildWorktreeAgentRows(args: { } const rowEntry = entryWithRuntimeOrchestration(entry, args.runtimeAgentOrchestrationByPaneKey) const startedAt = effectiveWorktreeAgentRowStartedAt(rowEntry) - const tab = tabFromWorktreeAttributedStatusEntry(rowEntry, startedAt) + const tab = tabFromWorktreeAttributedStatusEntry( + rowEntry, + startedAt, + args.representedTabs?.get(rowEntry.paneKey) + ) if (!tab) { continue } diff --git a/src/renderer/src/runtime/structured-agent-session-owner.ts b/src/renderer/src/runtime/structured-agent-session-owner.ts index 4fac831d58c3..353bcbfbb5d9 100644 --- a/src/renderer/src/runtime/structured-agent-session-owner.ts +++ b/src/renderer/src/runtime/structured-agent-session-owner.ts @@ -1,3 +1,8 @@ +import { + selectDetectedWorktreesByRepo, + selectFolderWorkspaces, + selectWorktreesByRepo +} from '@/store/workspace-record-selectors' import { LOCAL_EXECUTION_HOST_ID, parseExecutionHostId, @@ -7,12 +12,6 @@ import { import type { Tab } from '../../../shared/tab-types' import { getExecutionHostIdForWorktree } from '@/lib/worktree-runtime-owner' import type { WorktreeRuntimeOwnerState } from '@/lib/worktree-runtime-owner-state' -import type { AppState } from '@/store/types' -import { - selectDetectedWorktreesByRepo, - selectFolderWorkspaces, - selectWorktreesByRepo -} from '@/store/workspace-record-selectors' import { isTwinWorkspace, namedHostForOwnerRef, resolveOwner } from '@/lib/resolve-owner' import { authorityKey } from '../../../shared/host-authority' import { LOCAL_STRUCTURED_SESSION_OWNER } from './local-structured-session-owner' @@ -92,7 +91,9 @@ export function legacyStructuredChatRenameOwner( } /** Catalog inputs independent of the user's current workspace selection. */ -export function structuredAgentSessionCatalogOwnerInputs(state: AppState): unknown[] { +export function structuredAgentSessionCatalogOwnerInputs( + state: WorktreeRuntimeOwnerState +): unknown[] { return [ state.repos, selectWorktreesByRepo(state), @@ -105,7 +106,7 @@ export function structuredAgentSessionCatalogOwnerInputs(state: AppState): unkno } /** Inputs to the legacy workspace-owner resolver, compared before scanning chat tabs. */ -export function structuredAgentSessionOwnerInputs(state: AppState): unknown[] { +export function structuredAgentSessionOwnerInputs(state: WorktreeRuntimeOwnerState): unknown[] { return [ ...structuredAgentSessionCatalogOwnerInputs(state), state.settings, diff --git a/src/renderer/src/runtime/visible-agent-orchestration.ts b/src/renderer/src/runtime/visible-agent-orchestration.ts new file mode 100644 index 000000000000..57fb40bacfb2 --- /dev/null +++ b/src/renderer/src/runtime/visible-agent-orchestration.ts @@ -0,0 +1,197 @@ +import type { AppState } from '@/store/types' +import type { WorktreeRuntimeOwnerState } from '@/lib/worktree-runtime-owner-state' +import { getStructuredAgentSessionTabs } from '@/components/native-chat/structured-agent-session-tabs' +import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../../shared/structured-agent-session-projection' +import type { AgentStatusOrchestrationContext } from '../../../shared/agent-status-types' +import { orchestrationContextsEqual } from '@/store/slices/agent-status/agent-status-orchestration-context' +import { + resolveStructuredAgentSessionOwner, + structuredAgentSessionOwnerForTab, + structuredAgentSessionOwnerInputs +} from './structured-agent-session-owner' + +type Contexts = Record +export type VisibleOrchestrationState = WorktreeRuntimeOwnerState & + Partial< + Pick< + AppState, + | 'unifiedTabsByWorktree' + | 'agentStatusByPaneKey' + | 'retainedAgentsByPaneKey' + | 'runtimeAgentOrchestrationByPaneKey' + > + > +const EMPTY = {} +const producerByContext = new WeakMap() +export function orchestrationProducer(context: AgentStatusOrchestrationContext): string { + return producerByContext.get(context) ?? LOCAL_EXECUTION_HOST_ID +} +export function recordOrchestrationProducer( + context: AgentStatusOrchestrationContext, + host: string +): void { + producerByContext.set(context, host) +} +type RowIdentities = { + inputs: unknown[] + aliases: Map + canonical: Map + worktrees: Map +} +let rowCache: RowIdentities | undefined +let cache: { inputs: unknown[]; contexts: Contexts } | undefined +let builds = 0 +let aliasBuilds = 0 +let visits = 0 +export function visibleOrchestrationWorkForTest(): { + builds: number + aliasBuilds: number + visits: number +} { + return { builds, aliasBuilds, visits } +} +const aliasKey = (host: string, key: string) => `${host}\0${key}` + +function rowIdentities(state: VisibleOrchestrationState): RowIdentities { + const inputs = [state.unifiedTabsByWorktree, ...structuredAgentSessionOwnerInputs(state)] + if (rowCache && inputs.every((value, index) => value === rowCache?.inputs[index])) { + return rowCache + } + aliasBuilds++ + const aliases = new Map() + const worktrees = new Map() + const canonical = new Map() + for (const tab of getStructuredAgentSessionTabs(state.unifiedTabsByWorktree ?? EMPTY)) { + visits++ + if (!tab.entityId) { + continue + } + const key = structuredAgentSessionPaneKey( + structuredAgentSessionTabId(tab.entityId), + tab.entityId + ) + const actual = structuredAgentSessionPaneKey(tab.id, tab.entityId) + const host = structuredAgentSessionOwnerForTab(state, tab) + canonical.set(actual, { key, host }) + worktrees.set(actual, tab.worktreeId) + if (host && !aliases.has(aliasKey(host, key))) { + aliases.set(aliasKey(host, key), actual) + } + } + rowCache = { inputs, aliases, canonical, worktrees } + return rowCache +} + +function projection(state: VisibleOrchestrationState): NonNullable { + const rows = rowIdentities(state) + const inputs = [ + state.runtimeAgentOrchestrationByPaneKey, + state.agentStatusByPaneKey, + state.retainedAgentsByPaneKey, + rows + ] + if (cache && inputs.every((value, index) => value === cache?.inputs[index])) { + return cache + } + builds++ + const { aliases, canonical } = rows + const contexts: Contexts = Object.fromEntries([]) + const visibleKey = (key: string, host: string | null) => { + if (!host) { + return canonical.has(key) ? aliasKey('unknown', key) : key + } + const alias = aliases.get(aliasKey(host, key)) + // An identically spelled row from another runtime cannot satisfy this relationship. + return ( + alias ?? (canonical.has(key) && canonical.get(key)?.host !== host ? aliasKey(host, key) : key) + ) + } + const adapt = (key: string, context: AgentStatusOrchestrationContext, host: string | null) => { + visits++ + const actual = visibleKey(key, host) + const parent = context.parentPaneKey ? visibleKey(context.parentPaneKey, host) : undefined + const next = parent === context.parentPaneKey ? context : { ...context, parentPaneKey: parent } + const previous = cache?.contexts[actual] + contexts[actual] = + next !== context && previous && orchestrationContextsEqual(previous, next) ? previous : next + } + for (const [key, context] of Object.entries(state.runtimeAgentOrchestrationByPaneKey ?? EMPTY)) { + adapt(key, context, producerByContext.get(context) ?? LOCAL_EXECUTION_HOST_ID) + } + const embedded = ( + entry: AppState['agentStatusByPaneKey'][string], + worktreeId = entry.worktreeId + ) => { + visits++ + if (!entry?.orchestration) { + return + } + const row = canonical.get(entry.paneKey) + const runtime = state.runtimeAgentOrchestrationByPaneKey?.[row?.key ?? entry.paneKey] + const host = row + ? row.host + : entry.connectionId + ? null + : worktreeId + ? resolveStructuredAgentSessionOwner(state, worktreeId) + : null + if ( + runtime && + host === (producerByContext.get(runtime) ?? LOCAL_EXECUTION_HOST_ID) && + runtime.taskId === entry.orchestration.taskId && + runtime.dispatchId === entry.orchestration.dispatchId + ) { + return + } + if ( + entry.orchestration.parentPaneKey && + visibleKey(entry.orchestration.parentPaneKey, host) !== entry.orchestration.parentPaneKey + ) { + adapt(entry.paneKey, entry.orchestration, host) + } + } + for (const entry of Object.values(state.agentStatusByPaneKey ?? EMPTY)) { + embedded(entry) + } + for (const retained of Object.values(state.retainedAgentsByPaneKey ?? EMPTY)) { + embedded(retained.entry, retained.worktreeId) + } + const previous = cache?.contexts + const equal = + previous && + Object.keys(previous).length === Object.keys(contexts).length && + Object.keys(contexts).every((key) => previous[key] === contexts[key]) + cache = { inputs, contexts: equal ? previous : contexts } + return cache +} + +/** Canonical contexts stay in storage; actual rows and parent aliases are a shared read-only view. */ +export function selectVisibleAgentOrchestration(state: VisibleOrchestrationState): Contexts { + if (!state.unifiedTabsByWorktree) { + return state.runtimeAgentOrchestrationByPaneKey ?? EMPTY + } + return projection(state).contexts +} + +/** The same row identity joins graph enrichment and first status paint, without translating stored parents. */ +export function canonicalOrchestrationForRow( + state: VisibleOrchestrationState, + paneKey: string +): AgentStatusOrchestrationContext | undefined { + const row = rowIdentities(state).canonical.get(paneKey) + const context = state.runtimeAgentOrchestrationByPaneKey?.[row?.key ?? paneKey] + return context && + (!row || row.host === (producerByContext.get(context) ?? LOCAL_EXECUTION_HOST_ID)) + ? context + : undefined +} + +export function representedOrchestrationWorktrees( + state: VisibleOrchestrationState +): ReadonlyMap { + return rowIdentities(state).worktrees +} diff --git a/src/renderer/src/store/slices/agent-status/agent-status-live-entry-builder.ts b/src/renderer/src/store/slices/agent-status/agent-status-live-entry-builder.ts index dd4ee18d24ab..a14709b6ba58 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-live-entry-builder.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-live-entry-builder.ts @@ -1,3 +1,4 @@ +import { canonicalOrchestrationForRow } from '@/runtime/visible-agent-orchestration' import { sameAgentStatusTerminalOwner } from '../../../../../shared/agent-status-terminal-owner' import type { AppState } from '../../types' import { resolveAgentStatusLiveEntryMainAgent } from './agent-status-live-entry-main-agent' @@ -141,7 +142,7 @@ export function buildAgentStatusLiveEntry( ) { return { entry: null, reason: 'suppressed-inherited-terminal' } } - const runtimeOrchestration = state.runtimeAgentOrchestrationByPaneKey[paneKey] + const runtimeOrchestration = canonicalOrchestrationForRow(state, paneKey) const runtimeMergedOrchestration = runtimeOrchestration ? mergeCurrentOrchestrationContext(existing?.orchestration, runtimeOrchestration) : undefined diff --git a/src/renderer/src/store/slices/agent-status/agent-status-orchestration-actions.ts b/src/renderer/src/store/slices/agent-status/agent-status-orchestration-actions.ts index cf9fad39aef3..bc2f9cd4939c 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-orchestration-actions.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-orchestration-actions.ts @@ -1,3 +1,9 @@ +import { + canonicalOrchestrationForRow, + recordOrchestrationProducer, + orchestrationProducer +} from '@/runtime/visible-agent-orchestration' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host' import type { AgentStatusEntry, AgentStatusOrchestrationContext @@ -10,7 +16,7 @@ import { } from '../../../../../shared/agent-row-primary-text' import { mergeCurrentOrchestrationContext, - orchestrationMapsEqual + orchestrationContextsEqual } from './agent-status-orchestration-context' export function createAgentStatusOrchestrationActions( @@ -19,20 +25,42 @@ export function createAgentStatusOrchestrationActions( const { get, set } = runtime return { setRuntimeAgentOrchestrationByPaneKey: ( - entries: Record + entries: Record, + producerHost = LOCAL_EXECUTION_HOST_ID ) => { const generatedTitleUpdates: AgentStatusEntry[] = [] set((s) => { - const runtimeMapChanged = !orchestrationMapsEqual( - s.runtimeAgentOrchestrationByPaneKey, - entries - ) + const previous = s.runtimeAgentOrchestrationByPaneKey + const reconciled: Record = Object.fromEntries([]) + let runtimeMapChanged = Object.keys(previous).length !== Object.keys(entries).length + for (const [key, context] of Object.entries(entries)) { + const old = previous[key] + const value = + old && + orchestrationProducer(old) === producerHost && + orchestrationContextsEqual(old, context) + ? old + : context + reconciled[key] = value + recordOrchestrationProducer(value, producerHost) + if (value !== old) { + runtimeMapChanged = true + } + } + const canonicalState = { + ...s, + runtimeAgentOrchestrationByPaneKey: runtimeMapChanged ? reconciled : previous + } let nextLive = s.agentStatusByPaneKey let liveChanged = false let nextRetained = s.retainedAgentsByPaneKey let retainedChanged = false - for (const [paneKey, runtimeOrchestration] of Object.entries(entries)) { + for (const paneKey of new Set([...Object.keys(nextLive), ...Object.keys(nextRetained)])) { + const runtimeOrchestration = canonicalOrchestrationForRow(canonicalState, paneKey) + if (!runtimeOrchestration) { + continue + } const liveEntry = nextLive[paneKey] if (liveEntry) { const merged = mergeCurrentOrchestrationContext( @@ -83,7 +111,7 @@ export function createAgentStatusOrchestrationActions( } return { - ...(runtimeMapChanged ? { runtimeAgentOrchestrationByPaneKey: entries } : {}), + ...(runtimeMapChanged ? { runtimeAgentOrchestrationByPaneKey: reconciled } : {}), ...(liveChanged ? { agentStatusByPaneKey: nextLive } : {}), ...(retainedChanged ? { retainedAgentsByPaneKey: nextRetained } : {}), ...(liveChanged ? { agentStatusEpoch: s.agentStatusEpoch + 1 } : {}) diff --git a/src/renderer/src/store/slices/agent-status/agent-status-retention-actions.ts b/src/renderer/src/store/slices/agent-status/agent-status-retention-actions.ts index 737a72315517..d726f48bba46 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-retention-actions.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-retention-actions.ts @@ -1,3 +1,4 @@ +import { canonicalOrchestrationForRow } from '@/runtime/visible-agent-orchestration' import type { RetainedAgentEntry } from './agent-status-contract' import type { AgentStatusSlice } from './agent-status-slice-contract' import type { AgentStatusRuntime } from './agent-status-runtime' @@ -34,7 +35,7 @@ export function createAgentStatusRetentionActions( } const next = { ...s.retainedAgentsByPaneKey } for (const retained of entries) { - const runtimeOrchestration = s.runtimeAgentOrchestrationByPaneKey[retained.entry.paneKey] + const runtimeOrchestration = canonicalOrchestrationForRow(s, retained.entry.paneKey) const mergedOrchestration = runtimeOrchestration ? mergeCurrentOrchestrationContext(retained.entry.orchestration, runtimeOrchestration) : retained.entry.orchestration diff --git a/src/renderer/src/store/slices/agent-status/agent-status-slice-contract.ts b/src/renderer/src/store/slices/agent-status/agent-status-slice-contract.ts index c1d9503a08d2..12a1f4adc501 100644 --- a/src/renderer/src/store/slices/agent-status/agent-status-slice-contract.ts +++ b/src/renderer/src/store/slices/agent-status/agent-status-slice-contract.ts @@ -115,7 +115,8 @@ export type AgentStatusSlice = { clearAgentLaunchConfig: (paneKey: string) => void setRuntimeAgentOrchestrationByPaneKey: ( - entries: Record + entries: Record, + producerHost?: string ) => void setMigrationUnsupportedPty: (entry: MigrationUnsupportedPtyEntry) => void diff --git a/src/renderer/src/store/slices/workspace-cleanup-agent-evidence.ts b/src/renderer/src/store/slices/workspace-cleanup-agent-evidence.ts index 0895cc26aa84..7bd68312de58 100644 --- a/src/renderer/src/store/slices/workspace-cleanup-agent-evidence.ts +++ b/src/renderer/src/store/slices/workspace-cleanup-agent-evidence.ts @@ -1,3 +1,4 @@ +import { getStructuredAgentSessionTabsByPaneKey } from '@/components/native-chat/structured-agent-session-tabs' import type { AppState } from '../types' import type { WorkspaceCleanupCandidate } from '../../../../shared/workspace-cleanup' import { parsePaneKey } from '../../../../shared/stable-pane-id' @@ -68,6 +69,9 @@ export function getWorkspaceCleanupAgentEvidence( for (const [worktreeId, worktreeCandidates] of candidatesByWorktreeId) { const rows = buildWorktreeAgentRows({ tabs: state.tabsByWorktree[worktreeId] ?? [], + representedTabs: state.unifiedTabsByWorktree + ? getStructuredAgentSessionTabsByPaneKey(state.unifiedTabsByWorktree) + : undefined, entries: selectLiveAgentStatusEntriesForWorktree(state, worktreeId), retained: selectRetainedAgentEntriesForWorktree(state, worktreeId), runtimePaneTitlesByTabId: state.runtimePaneTitlesByTabId, diff --git a/src/renderer/src/store/workspace-record-selectors.ts b/src/renderer/src/store/workspace-record-selectors.ts index 3e98eca9fec6..b0247da9b418 100644 --- a/src/renderer/src/store/workspace-record-selectors.ts +++ b/src/renderer/src/store/workspace-record-selectors.ts @@ -1,3 +1,4 @@ +import type { WorktreeRuntimeOwnerState } from '@/lib/worktree-runtime-owner-state' import type { FolderWorkspace } from '../../../shared/folder-workspace-types' import type { ExecutionHostId } from '../../../shared/execution-host' import type { Worktree } from '../../../shared/worktree/types' @@ -15,22 +16,22 @@ import { export type WorkspaceRecordState = Pick /** Git worktrees per repo id, in listing order. */ -export function selectWorktreesByRepo( - state: Pick -): AppState['worktreesByRepo'] { +export function selectWorktreesByRepo< + State extends Pick +>(state: State): State['worktreesByRepo'] { return state.worktreesByRepo } -export function selectFolderWorkspaces( - state: Pick -): AppState['folderWorkspaces'] { +export function selectFolderWorkspaces< + State extends Pick +>(state: State): State['folderWorkspaces'] { return state.folderWorkspaces } /** Checkouts git reports that Orca does not track, per repo id. */ -export function selectDetectedWorktreesByRepo( - state: Pick -): AppState['detectedWorktreesByRepo'] { +export function selectDetectedWorktreesByRepo< + State extends Pick +>(state: State): State['detectedWorktreesByRepo'] { return state.detectedWorktreesByRepo } diff --git a/src/shared/agent-status-worktree-attribution.ts b/src/shared/agent-status-worktree-attribution.ts index 06369550faae..8bb573118736 100644 --- a/src/shared/agent-status-worktree-attribution.ts +++ b/src/shared/agent-status-worktree-attribution.ts @@ -1,3 +1,5 @@ +import type { Tab } from './tab-types' +import { structuredAgentSessionPaneKey } from './structured-agent-session-projection' import type { AgentStatusEntry, AgentStatusOrchestrationContext } from './agent-status-types' import { isWebTerminalSurfaceTabId } from './terminal-surface-id' import { parseLegacyNumericPaneKey, parsePaneKey } from './stable-pane-id' @@ -5,11 +7,18 @@ import { parseLegacyNumericPaneKey, parsePaneKey } from './stable-pane-id' export type AgentStatusPaneIdentity = { tabId: string; paneId: string } export function parseAgentStatusPaneIdentity( - paneKey: string | undefined + paneKey: string | undefined, + representedTab?: Pick ): AgentStatusPaneIdentity | null { if (!paneKey) { return null } + if ( + representedTab?.contentType === 'agent-session' && + structuredAgentSessionPaneKey(representedTab.id, representedTab.entityId) === paneKey + ) { + return { tabId: representedTab.id, paneId: paneKey.slice(representedTab.id.length + 1) } + } const parsed = parsePaneKey(paneKey) if (parsed) { return { tabId: parsed.tabId, paneId: parsed.leafId } From df5f9f00a98b9fb3a7cec402e0444f5a79ebcfd7 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:10:32 -0700 Subject: [PATCH 003/164] Complete terminal lineage provenance and bound active session selection --- .../db/dispatch-context/dispatch-lookup.ts | 24 +- ...tion-orca-session-column-migration.test.ts | 1 + ...ime-agent-orchestration-projection.test.ts | 379 ++++++++++++------ ...mirrored-terminal-lineage.test-fixture.tsx | 346 ++++++++++++++++ ...worktree-agent-rows-subscriptions.test.tsx | 55 ++- .../worktree-agent-activity-summary.test.ts | 27 ++ .../worktree-agent-activity-summary.ts | 7 +- .../runtime/visible-agent-orchestration.ts | 107 ++++- 8 files changed, 790 insertions(+), 156 deletions(-) create mode 100644 src/renderer/src/components/sidebar/mirrored-terminal-lineage.test-fixture.tsx diff --git a/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts b/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts index ac5c552371a8..d72f8f5a9626 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts @@ -57,8 +57,19 @@ export function listSessionDispatchesForPresentation( AND status IN ('completed', 'failed', 'circuit_broken') AND completed_at >= ? `) .all(lowerBound) as (DispatchContextRow & { presentation_order: number })[] + const newestActiveOrderBySession = new Map() const selected = new Map() for (const candidate of candidates) { + // Include handled rows even when a newer non-public row later suppresses their address. + if (candidate.status === 'pending' || candidate.status === 'dispatched') { + const session = candidate.assignee_orca_session_id + if (session) { + newestActiveOrderBySession.set( + session, + Math.max(newestActiveOrderBySession.get(session) ?? 0, candidate.presentation_order) + ) + } + } const address = candidate.assignee_handle ? `handle:${candidate.assignee_handle}` : `session:${candidate.assignee_orca_session_id}` @@ -78,13 +89,16 @@ export function listSessionDispatchesForPresentation( const { presentation_order, ...dispatch } = candidate const active = dispatch.status === 'pending' || dispatch.status === 'dispatched' // SAFETY: equality-index probes return just the internal row order, or no row. - const latest = this.db - .prepare(`SELECT rowid AS n FROM dispatch_contexts + const latest = + active && !candidate.assignee_handle + ? { n: newestActiveOrderBySession.get(candidate.assignee_orca_session_id ?? '') } + : (this.db + .prepare(`SELECT rowid AS n FROM dispatch_contexts WHERE ${candidate.assignee_handle ? 'assignee_handle' : 'assignee_orca_session_id'} = ? ${active ? "AND status IN ('pending', 'dispatched')" : ''} ORDER BY rowid DESC LIMIT 1`) - .get(candidate.assignee_handle || candidate.assignee_orca_session_id) as - | { n: number } - | undefined + .get(candidate.assignee_handle || candidate.assignee_orca_session_id) as + | { n: number } + | undefined) if ( latest?.n !== presentation_order || (!active && !isRecentPresentationDispatch(dispatch, now)) diff --git a/src/main/runtime/orchestration/orchestration-orca-session-column-migration.test.ts b/src/main/runtime/orchestration/orchestration-orca-session-column-migration.test.ts index e312bd3e2eb6..d25744e63e66 100644 --- a/src/main/runtime/orchestration/orchestration-orca-session-column-migration.test.ts +++ b/src/main/runtime/orchestration/orchestration-orca-session-column-migration.test.ts @@ -136,6 +136,7 @@ function stripOrcaSessionSchema(path: string, version: number): void { raw.exec(` ${DROP_REMOVED_WORK_TRIGGERS_SQL} DROP INDEX idx_runs_coordinator_orca_session_id; + DROP INDEX IF EXISTS idx_dispatch_session_presentation; DROP INDEX idx_dispatch_assignee_orca_session_id; DROP TRIGGER trg_runs_remember_coordinator_insert; DROP TRIGGER trg_runs_remember_coordinator_update; diff --git a/src/main/runtime/runtime-agent-orchestration-projection.test.ts b/src/main/runtime/runtime-agent-orchestration-projection.test.ts index 2cf2b82667d9..46573954ae85 100644 --- a/src/main/runtime/runtime-agent-orchestration-projection.test.ts +++ b/src/main/runtime/runtime-agent-orchestration-projection.test.ts @@ -1,5 +1,5 @@ import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' +import { hostname, tmpdir } from 'node:os' import { join } from 'node:path' import { seedTestAgentSessionRecordStore } from './agent-session-record-store-test-harness' import { closeTestJournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database-test-support' @@ -349,6 +349,101 @@ it.each([20, 200])( } ) +it.each([20, 200])( + 'derives newest active null-address sessions from one complete batch at %i identities', + (n) => { + const db = new OrchestrationDb(':memory:') + try { + const run = db.createRun({ + objective: 'null-address history', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: SESSION_X + }) + const task = db.createTask({ runId: run.id, spec: 'null-address selection' }) + const insert = db.db.prepare(`INSERT INTO dispatch_contexts + (id, run_id, task_id, assignee_orca_session_id, status, completed_at) + WITH RECURSIVE seq(n) AS (VALUES(1) UNION ALL SELECT n+1 FROM seq WHERE n < ?) + SELECT ? || n, ?, ?, ?, 'completed', '2020-01-01T00:00:00Z' FROM seq`) + for (let i = 0; i < n; i++) { + const dispatch = db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'active selection' }).id, + assigneeHandle: `old-${i}`, + creator: { kind: 'system' }, + maxDepth: 99 + }) + db.db + .prepare( + 'UPDATE dispatch_contexts SET assignee_handle = NULL, assignee_pane_key = NULL, assignee_orca_session_id = ? WHERE id = ?' + ) + .run(`null-session-${i}`, dispatch.id) + insert.run(n, `expired-${i}-`, run.id, task.id, `null-session-${i}`) + } + let candidates = 0 + db.db.function('null_candidate_visit', {}, (_rowid: unknown) => { + candidates++ + return 1 + }) + const prepare = db.db.prepare.bind(db.db) + const trace = vi + .spyOn(db.db, 'prepare') + .mockImplementation((query) => + prepare( + query.replaceAll( + 'WHERE assignee_orca_session_id IS NOT NULL', + 'WHERE assignee_orca_session_id IS NOT NULL AND null_candidate_visit(rowid)' + ) + ) + ) + const roster = vi.spyOn(db, 'listSessionDispatchesForPresentation') + const projection = projectionFor(db) + const output = projection.buildByPaneKey() ?? {} + expect(Object.keys(output)).toHaveLength(n) + for (let i = 0; i < n; i++) { + expect(output[chatRow(`null-session-${i}`)]?.parentPaneKey).toBe(chatRow(SESSION_X)) + } + expect(roster).toHaveBeenCalledTimes(1) + expect(candidates).toBe(n) + expect( + trace.mock.calls.filter( + ([q]) => + q.includes('rowid AS n') && + q.includes('assignee_orca_session_id') && + q.includes("AND status IN ('pending', 'dispatched')") + ) + ).toHaveLength(0) + expect( + trace.mock.calls.filter(([q]) => q.includes('idx_dispatch_session_presentation')) + ).toHaveLength(1) + trace.mockRestore() + // The newer handled active row contributes to the session maximum even if its address is suppressed. + const handled = db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'active selection' }).id, + assigneeHandle: 'new-handled', + creator: { kind: 'system' }, + maxDepth: 99 + }) + db.db + .prepare('UPDATE dispatch_contexts SET assignee_orca_session_id = ? WHERE id = ?') + .run('null-session-0', handled.id) + const newer = db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'active selection' }).id, + assigneeHandle: 'newer-suppression', + creator: { kind: 'system' }, + maxDepth: 99 + }) + db.db + .prepare('UPDATE dispatch_contexts SET assignee_handle = ? WHERE id = ?') + .run('new-handled', newer.id) + const suppressed = projection.buildByPaneKey() ?? {} + expect(suppressed[chatRow('null-session-0')]).toBeUndefined() + expect(Object.keys(suppressed)).toHaveLength(n - 1) + } finally { + db.close() + } + } +) + it('selects indexed active/latest per address with exact ISO/SQLite recency and deterministic public collisions', () => { const db = new OrchestrationDb(':memory:') const now = Date.parse('2026-10-27T00:00:10.000Z') @@ -455,142 +550,174 @@ it('selects indexed active/latest per address with exact ISO/SQLite recency and it.skipIf(process.env.ORCA_LINEAGE_BENCH !== '1')( 'benchmarks retained-history ranges and first derived-index creation (admitted machines only)', () => { - for (const history of [10_000, 100_000]) { - for (const terminalHistory of [0, 100_000]) { - for (const attentionFacts of [0, 2_000]) { - const directory = mkdtempSync(join(tmpdir(), 'orca-lineage-benchmark-')) - const path = join(directory, 'orchestration.sqlite') - let db = new OrchestrationDb(path) - try { - const run = db.createRun({ - objective: 'benchmark', - coordinatorHandle: null, - coordinatorPaneKey: null, - coordinatorOrcaSessionId: SESSION_X - }) - for (let i = 0; i < 20; i++) { - db.createDispatchContext({ - taskId: db.createTask({ runId: run.id, spec: 'active' }).id, - assigneeHandle: formatOrcaSessionAddress( - testOrcaSessionId(`00000000-0000-4000-8000-${String(i).padStart(12, '0')}`) - ), - creator: { kind: 'system' }, - maxDepth: 99 + for (const nullAddress of [false, true]) { + for (const history of [10_000, 100_000]) { + for (const terminalHistory of [0, 100_000]) { + for (const attentionFacts of [0, 2_000]) { + const directory = mkdtempSync(join(tmpdir(), 'orca-lineage-benchmark-')) + const path = join(directory, 'orchestration.sqlite') + let db = new OrchestrationDb(path) + try { + const run = db.createRun({ + objective: 'benchmark', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: SESSION_X }) - } - const taskId = db.createTask({ runId: run.id, spec: 'history' }).id - const insert = db.db - .prepare(`INSERT INTO dispatch_contexts(id, run_id, task_id, assignee_handle, assignee_orca_session_id, status, completed_at) + for (let i = 0; i < 20; i++) { + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'active' }).id, + assigneeHandle: formatOrcaSessionAddress( + testOrcaSessionId(`00000000-0000-4000-8000-${String(i).padStart(12, '0')}`) + ), + creator: { kind: 'system' }, + maxDepth: 99 + }) + } + if (nullAddress) { + db.db.exec( + "UPDATE dispatch_contexts SET assignee_handle = NULL, assignee_pane_key = NULL WHERE status = 'pending'" + ) + } + const taskId = db.createTask({ runId: run.id, spec: 'history' }).id + const insert = db.db + .prepare(`INSERT INTO dispatch_contexts(id, run_id, task_id, assignee_handle, assignee_orca_session_id, status, completed_at) WITH RECURSIVE seq(n) AS (VALUES(1) UNION ALL SELECT n+1 FROM seq WHERE n < ?) - SELECT ? || n, ?, ?, ? || n, CASE WHEN ? THEN 'session-' || n ELSE NULL END, 'completed', '2020-01-01T00:00:00Z' FROM seq`) - insert.run(history, 'session-history-', run.id, taskId, 'session-address-', 1) - if (terminalHistory) { + SELECT ? || n, ?, ?, ? || n, CASE WHEN ? THEN CASE WHEN ? THEN printf('00000000-0000-4000-8000-%012d', (n-1) % 20) ELSE 'session-' || n END ELSE NULL END, 'completed', '2020-01-01T00:00:00Z' FROM seq`) insert.run( - terminalHistory, - 'terminal-history-', + history, + 'session-history-', run.id, taskId, - 'terminal-address-', - 0 - ) - } - const active = db.db - .prepare( - "SELECT id, task_id FROM dispatch_contexts WHERE status = 'pending' ORDER BY rowid" + 'session-address-', + 1, + nullAddress ? 1 : 0 ) - .all() - const insertFact = db.db.prepare( - `INSERT INTO attempt_observation_facts(id, dispatch_id, task_id, sequence, authority_id, authority_clock, facet, payload, home_received_at) VALUES (?, ?, ?, ?, 'home', 'home', 'process_turn', '{"process":"running","turn":"working"}', ?)` - ) - for (let i = 0; i < attentionFacts; i++) { - const row = active[i % active.length] - if (typeof row?.id !== 'string' || typeof row.task_id !== 'string') { - throw new Error('Missing benchmark Dispatch') + if (terminalHistory) { + insert.run( + terminalHistory, + 'terminal-history-', + run.id, + taskId, + 'terminal-address-', + 0, + 0 + ) } - insertFact.run( - `observation-${i}`, - row.id, - row.task_id, - Math.floor(i / active.length), - Date.now() - ) - } - db.db.exec('DROP INDEX idx_dispatch_session_presentation') - const first = performance.now() - db.createMailboxDeliveryIndexesIfPossible() - const indexMs = performance.now() - first - db.db.exec('DROP INDEX idx_dispatch_session_presentation') - db.close() - const openStarted = performance.now() - db = new OrchestrationDb(path) - const firstOpenIndexMs = performance.now() - openStarted - let observationVisits = 0 - db.db.function('lineage_observation_visit', {}, (_rowid: unknown) => { - observationVisits++ - return 1 - }) - let visits = 0 - db.db.function('lineage_bench_visit', {}, (_rowid: unknown) => { - visits++ - return 1 - }) - const prepare = db.db.prepare.bind(db.db) - const trace = vi - .spyOn(db.db, 'prepare') - .mockImplementation((query) => - prepare( - query - .replaceAll( - 'WHERE assignee_orca_session_id IS NOT NULL', - 'WHERE assignee_orca_session_id IS NOT NULL AND lineage_bench_visit(rowid)' - ) - .replace( - 'WHERE dispatch_id IN', - 'WHERE lineage_observation_visit(rowid) AND dispatch_id IN' - ) + const active = db.db + .prepare( + "SELECT id, task_id FROM dispatch_contexts WHERE status = 'pending' ORDER BY rowid" ) + .all() + const insertFact = db.db.prepare( + `INSERT INTO attempt_observation_facts(id, dispatch_id, task_id, sequence, authority_id, authority_clock, facet, payload, home_received_at) VALUES (?, ?, ?, ?, 'home', 'home', 'process_turn', '{"process":"running","turn":"working"}', ?)` ) - const start = performance.now() - const output = projectionFor(db).buildByPaneKey() - const buildMs = performance.now() - start - const plans = trace.mock.calls - .filter( - ([query]) => - query.includes('idx_dispatch_session_presentation') || - query.includes('rowid AS n') - ) - .map(([query]) => - db.db - .prepare(`EXPLAIN QUERY PLAN ${query}`) - .all( - ...(query.includes('completed_at >= ?') - ? ['2026-10-26T00:00:00Z'] - : ['orca_session_id:bench-0']) + for (let i = 0; i < attentionFacts; i++) { + const row = active[i % active.length] + if (typeof row?.id !== 'string' || typeof row.task_id !== 'string') { + throw new Error('Missing benchmark Dispatch') + } + insertFact.run( + `observation-${i}`, + row.id, + row.task_id, + Math.floor(i / active.length), + Date.now() + ) + } + db.db.exec('DROP INDEX idx_dispatch_session_presentation') + const first = performance.now() + db.createMailboxDeliveryIndexesIfPossible() + const indexHelperMs = performance.now() - first + db.db.exec('DROP INDEX idx_dispatch_session_presentation') + db.close() + const openStarted = performance.now() + db = new OrchestrationDb(path) + const reopenWithIndexCreationMs = performance.now() - openStarted + let observationVisits = 0 + db.db.function('lineage_observation_visit', {}, (_rowid: unknown) => { + observationVisits++ + return 1 + }) + let visits = 0 + db.db.function('lineage_bench_visit', {}, (_rowid: unknown) => { + visits++ + return 1 + }) + const prepare = db.db.prepare.bind(db.db) + const trace = vi + .spyOn(db.db, 'prepare') + .mockImplementation((query) => + prepare( + query + .replaceAll( + 'WHERE assignee_orca_session_id IS NOT NULL', + 'WHERE assignee_orca_session_id IS NOT NULL AND lineage_bench_visit(rowid)' + ) + .replace( + 'WHERE dispatch_id IN', + 'WHERE lineage_observation_visit(rowid) AND dispatch_id IN' + ) ) + ) + const start = performance.now() + const output = projectionFor(db).buildByPaneKey() + const buildMs = performance.now() - start + const productionPrepareCalls = trace.mock.calls.length + const activeSessionVerificationProbes = trace.mock.calls.filter( + ([query]) => + query.includes('rowid AS n') && + query.includes('assignee_orca_session_id') && + query.includes("AND status IN ('pending', 'dispatched')") + ).length + expect(activeSessionVerificationProbes).toBe(0) + const plans = trace.mock.calls + .filter( + ([query]) => + query.includes('idx_dispatch_session_presentation') || + query.includes('rowid AS n') + ) + .map(([query]) => + db.db + .prepare(`EXPLAIN QUERY PLAN ${query}`) + .all( + ...(query.includes('completed_at >= ?') + ? ['2026-10-26T00:00:00Z'] + : ['orca_session_id:bench-0']) + ) + ) + expect(Object.keys(output ?? {})).toHaveLength(20) + expect(visits).toBe(20) + expect(observationVisits).toBe(attentionFacts) + expect(JSON.stringify(plans)).not.toMatch(/SCAN dispatch_contexts/) + console.log( + 'LINEAGE_BENCH_ENVIRONMENT_EVIDENCE', + JSON.stringify({ + host: hostname(), + node: process.version, + platform: process.platform, + arch: process.arch, + checkout: process.cwd(), + history, + nullAddress, + terminalHistory, + attentionFacts, + observationVisits, + indexHelperMs, + reopenWithIndexCreationMs, + buildMs, + candidateVisits: visits, + productionPrepareCalls, + diagnosticPrepareCalls: trace.mock.calls.length - productionPrepareCalls, + activeSessionVerificationProbes, + plans + }) ) - expect(Object.keys(output ?? {})).toHaveLength(20) - expect(visits).toBe(20) - expect(observationVisits).toBe(attentionFacts) - expect(JSON.stringify(plans)).not.toMatch(/SCAN dispatch_contexts/) - console.log( - 'LINEAGE_BENCH_ENVIRONMENT_EVIDENCE', - JSON.stringify({ - history, - terminalHistory, - attentionFacts, - observationVisits, - indexMs, - firstOpenIndexMs, - buildMs, - candidateVisits: visits, - sqlExecutions: trace.mock.calls.length, - plans - }) - ) - trace.mockRestore() - } finally { - db.close() - rmSync(directory, { recursive: true, force: true }) + trace.mockRestore() + } finally { + db.close() + rmSync(directory, { recursive: true, force: true }) + } } } } diff --git a/src/renderer/src/components/sidebar/mirrored-terminal-lineage.test-fixture.tsx b/src/renderer/src/components/sidebar/mirrored-terminal-lineage.test-fixture.tsx new file mode 100644 index 000000000000..d0460a179241 --- /dev/null +++ b/src/renderer/src/components/sidebar/mirrored-terminal-lineage.test-fixture.tsx @@ -0,0 +1,346 @@ +import { act } from 'react' +import { expect } from 'vitest' +import { useAppStore } from '@/store' +import type { AppState } from '@/store/types' +import type { DashboardAgentRow } from '@/components/dashboard/useDashboardData' +import { makePaneKey } from '../../../../shared/stable-pane-id' +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import { makeTab } from '@/store/slices/store-test-helpers' + +const LEAF = '11111111-1111-4111-8111-111111111111' + +export async function verifyMirroredTerminalLineage( + kind: 'default' | 'reserved' | 'collision', + { + patch, + entry, + mount, + getRows + }: { + patch: (update: Partial) => void + entry: (key: string, worktree: string) => AgentStatusEntry + mount: () => void + getRows: () => DashboardAgentRow[] + } +): Promise { + const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = + await import('../../../../main/runtime/runtime-agent-lineage.test-fixture') + const { makeUnifiedTab, makeWorktree, TEST_REPO } = + await import('@/store/slices/store-test-helpers') + const { selectDashboardOrchestration } = + await import('@/components/dashboard/dashboard-orchestration-selection') + const { selectWorktreeAgentRowsCached } = + await import('@/components/dashboard/worktree-agent-rows-cache') + const { buildActivityEvents } = await import('@/components/activity/activity-event-builder') + const { buildMirroredAgentTabs } = + await import('@/runtime/web-session-tabs-sync/terminal-surfaces') + const { buildMirroredAgentStatusPatch } = + await import('@/runtime/web-session-tabs-sync/agent-status-patch') + const { buildTerminalUnifiedTab } = await import('@/runtime/web-session-tabs-sync/tab-builders') + const { toRemoteRuntimePtyId } = + await import('../../../../shared/remote-runtime/remote-runtime-pty-id') + const { toWebTerminalSurfaceTabId } = await import('../../../../shared/terminal-surface-id') + const { projectStatus } = + await import('@/components/native-chat/structured-agent-session-status-projection') + const { structuredAgentSessionPaneKey: pane, structuredAgentSessionTabId: tabId } = + await import('../../../../shared/structured-agent-session-projection') + const { selectVisibleAgentOrchestration } = await import('@/runtime/visible-agent-orchestration') + const worktree = makeWorktree({ id: 'folder-a', repoId: TEST_REPO.id }) + patch({ repos: [TEST_REPO], worktreesByRepo: { [TEST_REPO.id]: [worktree] } }) + const f = publicLineageFixture('folder-a') + try { + const context = f.projection.buildByPaneKey()?.[canonicalChatRow(LINEAGE_CHILD)] + if (!context) { + throw new Error('Missing production context') + } + const native = buildMirroredAgentTabs( + { + worktree: 'folder-a', + publicationEpoch: 'test', + snapshotVersion: 1, + activeGroupId: 'g', + activeTabId: null, + activeTabType: 'agent-session', + tabs: [ + { + type: 'agent-session', + id: 'host-parent', + title: 'Parent', + sessionId: LINEAGE_PARENT, + replacesSessionId: 'previous', + agent: 'codex', + isActive: false + } + ] + }, + 'runtime:paired', + new Map(), + 'g', + 0, + kind === 'default' + ? [] + : [ + makeUnifiedTab({ + id: kind === 'reserved' ? 'reserved-parent' : tabId(LINEAGE_PARENT), + entityId: kind === 'reserved' ? 'previous' : 'occupied', + worktreeId: 'folder-a', + groupId: 'g', + contentType: 'agent-session' + }) + ], + Date.now() + )[0].unifiedTab + const actualParent = pane(native.id, LINEAGE_PARENT) + const tab = makeTab({ + id: toWebTerminalSurfaceTabId('host-terminal'), + worktreeId: 'folder-a', + ptyId: toRemoteRuntimePtyId('terminal', 'paired') + }) + const worker = makePaneKey(tab.id, LEAF) + const terminal = buildTerminalUnifiedTab(tab, 'g', 'paired') + patch({ + tabsByWorktree: { 'folder-a': [tab] }, + unifiedTabsByWorktree: {}, + ptyIdsByTabId: {}, + agentStatusByPaneKey: {}, + retainedAgentsByPaneKey: {}, + runtimeAgentOrchestrationByPaneKey: {} + }) + const produced = buildMirroredAgentStatusPatch( + useAppStore.getState(), + [], + [ + { + type: 'terminal', + id: 'surface', + title: 'Worker', + parentTabId: 'host-terminal', + leafId: LEAF, + terminal: 'terminal', + status: 'ready', + isActive: false, + agentStatus: { + ...entry(makePaneKey('host-terminal', LEAF), 'folder-a'), + orchestration: context + } + } + ], + [], + 'paired', + 'folder-a', + new Set(), + Date.now() + ) + if (!produced) { + throw new Error('Missing mirrored terminal status') + } + patch(produced) + expect(useAppStore.getState().agentStatusByPaneKey[worker].connectionId).toBe('paired') + // Status before graph: the missing parent stays rooted, then tab hydration alone joins it. + expect(selectVisibleAgentOrchestration(useAppStore.getState())[worker]?.parentPaneKey).not.toBe( + actualParent + ) + patch({ unifiedTabsByWorktree: { 'folder-a': [native, terminal] } }) + act(() => + useAppStore.getState().transactAgentStatuses((transaction) => + projectStatus( + transaction, + native, + { + sessionId: LINEAGE_PARENT, + workspaceId: 'folder-a', + agent: 'codex', + status: 'working', + latestPrompt: 'Parent', + updatedAt: Date.now(), + hostExecutionOwned: true + }, + 'live', + null + ) + ) + ) + mount() + const assertNested = (parent = actualParent) => { + expect(getRows().map((row) => row.paneKey)).toEqual([parent, worker]) + expect(getRows().map((row) => row.lineage?.depth)).toEqual([0, 1]) + expect(getRows()[1].entry.orchestration?.parentPaneKey).toBe(parent) + expect( + useAppStore.getState().agentStatusByPaneKey[worker]?.orchestration?.parentPaneKey ?? + context.parentPaneKey + ).toBe(canonicalChatRow(LINEAGE_PARENT)) + const state = useAppStore.getState() + const orchestration = + selectDashboardOrchestration(state, [{ worktree }]).singletonOrchestration ?? {} + const dashboard = selectWorktreeAgentRowsCached({ + state, + worktreeId: 'folder-a', + orchestration, + now: Date.now(), + generation: 1 + }) + expect(dashboard.map((row) => [row.paneKey, row.lineage.depth])).toEqual([ + [parent, 0], + [worker, 1] + ]) + const activity = buildActivityEvents({ + ...state, + chatNames: new Map(), + worktreeMap: new Map([[worktree.id, worktree]]), + repoMap: new Map([[TEST_REPO.id, TEST_REPO]]), + runtimeAgentOrchestrationByPaneKey: selectVisibleAgentOrchestration(state), + now: Date.now() + }) + expect(activity.paneEntryByPaneKey[worker]?.orchestration?.parentPaneKey).toBe(parent) + expect(activity.paneEntryByPaneKey[parent]).toBeDefined() + } + assertNested() + // A host-supplied legacy connection spelling does not override actual producer proof. + patch({ + agentStatusByPaneKey: { + ...useAppStore.getState().agentStatusByPaneKey, + [worker]: { + ...useAppStore.getState().agentStatusByPaneKey[worker], + connectionId: 'ssh-legacy' + } + } + }) + assertNested() + const canonical = useAppStore.getState().agentStatusByPaneKey[worker] + const epoch = useAppStore.getState().agentStatusEpoch + // Graph before parent hydration; matching task/Dispatch producer remains valid with nonempty connectionId. + const parentEntry = useAppStore.getState().agentStatusByPaneKey[actualParent] + patch({ + unifiedTabsByWorktree: { 'folder-a': [terminal] }, + agentStatusByPaneKey: { [worker]: canonical } + }) + act(() => + useAppStore + .getState() + .setRuntimeAgentOrchestrationByPaneKey( + { [worker]: structuredClone(context) }, + 'runtime:paired' + ) + ) + expect(getRows().find((row) => row.paneKey === worker)?.lineage?.depth).toBe(0) + patch({ + unifiedTabsByWorktree: { 'folder-a': [native, terminal] }, + agentStatusByPaneKey: { [worker]: canonical, [actualParent]: parentEntry } + }) + assertNested() + act(() => useAppStore.getState().setRuntimeAgentOrchestrationByPaneKey({})) + // PTY-only hydration is an independent cache input; disagreeing tab/PTY facts must not join. + patch({ + unifiedTabsByWorktree: { 'folder-a': [native] }, + tabsByWorktree: { 'folder-a': [{ ...tab, ptyId: null }] } + }) + expect(getRows().find((row) => row.paneKey === worker)?.lineage?.depth).toBe(0) + patch({ ptyIdsByTabId: { [tab.id]: [tab.ptyId ?? ''] } }) + assertNested() + patch({ + unifiedTabsByWorktree: { + 'folder-a': [native, { ...terminal, executionHostId: 'runtime:other' }] + } + }) + expect(getRows().find((row) => row.paneKey === worker)?.lineage?.depth).toBe(0) + patch({ + unifiedTabsByWorktree: { + 'folder-a': [{ ...native, executionHostId: 'runtime:other' }, terminal] + }, + ptyIdsByTabId: {} + }) + expect(getRows().find((row) => row.paneKey === worker)?.lineage?.depth).toBe(0) + patch({ unifiedTabsByWorktree: { 'folder-a': [native, terminal] } }) + assertNested() + // Retained snapshot proves the runtime after the current terminal tab/PTY/unified row disappears. + act(() => + useAppStore.getState().retainAgents([ + { + entry: { ...canonical, state: 'done' }, + worktreeId: 'folder-a', + tab, + agentType: 'claude', + startedAt: Date.now() + } + ]) + ) + patch({ + agentStatusByPaneKey: { + [actualParent]: useAppStore.getState().agentStatusByPaneKey[actualParent] + }, + tabsByWorktree: {}, + unifiedTabsByWorktree: { 'folder-a': [native] }, + ptyIdsByTabId: {} + }) + assertNested() + patch({ unifiedTabsByWorktree: { 'folder-a': [{ ...native, id: 'remapped-parent' }] } }) + // The parent status arrives independently; canonical retained context did not change or need an RPC. + patch({ + agentStatusByPaneKey: { + [pane('remapped-parent', LINEAGE_PARENT)]: { + ...useAppStore.getState().agentStatusByPaneKey[actualParent], + paneKey: pane('remapped-parent', LINEAGE_PARENT), + tabId: 'remapped-parent' + } + } + }) + assertNested(pane('remapped-parent', LINEAGE_PARENT)) + expect( + useAppStore.getState().retainedAgentsByPaneKey[worker].entry.orchestration?.parentPaneKey + ).toBe(canonicalChatRow(LINEAGE_PARENT)) + expect(useAppStore.getState().agentStatusEpoch).toBeGreaterThanOrEqual(epoch) + // Removing the only retained PTY proof cannot infer a runtime from its connection spelling. + patch({ + retainedAgentsByPaneKey: { + [worker]: { + ...useAppStore.getState().retainedAgentsByPaneKey[worker], + tab: { ...tab, ptyId: null } + } + } + }) + expect(getRows().find((row) => row.paneKey === worker)?.lineage?.depth).toBe(0) + expect(new Set(getRows().map((row) => row.paneKey)).size).toBe(getRows().length) + // Matching graph context identifies its producer even when terminal routing names another host. + const renamedParent = pane('remapped-parent', LINEAGE_PARENT) + patch({ + retainedAgentsByPaneKey: {}, + tabsByWorktree: { 'folder-a': [tab] }, + unifiedTabsByWorktree: { + 'folder-a': [{ ...native, id: 'remapped-parent', executionHostId: 'local' }, terminal] + }, + agentStatusByPaneKey: { + [renamedParent]: useAppStore.getState().agentStatusByPaneKey[renamedParent], + [worker]: canonical + } + }) + act(() => + useAppStore + .getState() + .setRuntimeAgentOrchestrationByPaneKey({ [worker]: structuredClone(context) }) + ) + assertNested(renamedParent) + act(() => + useAppStore + .getState() + .setRuntimeAgentOrchestrationByPaneKey( + { [worker]: structuredClone(context) }, + 'runtime:other' + ) + ) + expect(getRows().find((row) => row.paneKey === worker)?.lineage?.depth).toBe(0) + act(() => useAppStore.getState().setRuntimeAgentOrchestrationByPaneKey({})) + patch({ + tabsByWorktree: { 'folder-a': [{ ...tab, ptyId: 'remote:%zz@@terminal' }] }, + unifiedTabsByWorktree: { + 'folder-a': [{ ...native, id: 'remapped-parent', executionHostId: 'local' }] + }, + agentStatusByPaneKey: { + ...useAppStore.getState().agentStatusByPaneKey, + [worker]: { ...canonical, connectionId: undefined } + } + }) + expect(getRows().find((row) => row.paneKey === worker)?.lineage?.depth).toBe(0) + } finally { + f.db.close() + } +} diff --git a/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx b/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx index 9ef016a11e1d..a81928ac118f 100644 --- a/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx +++ b/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx @@ -252,6 +252,7 @@ it.each([20, 200])( for (const tab of tabs[worktreeId]) { live[pane(tab.id, tab.entityId)] = { ...entry(pane(tab.id, tab.entityId), worktreeId), + agentType: 'codex', tabId: tab.id } } @@ -363,20 +364,42 @@ it.each([20, 200])( } counts.clear() const foreignRow = pane(`child-actual-${n - 1}`, `child-${n - 1}`) + const beforeForeign = visibleOrchestrationWorkForTest() + const beforeForeignIndex = indexBuilds() + const { projectStatus } = + await import('@/components/native-chat/structured-agent-session-status-projection') + const foreignTab = tabs[`lineage-${n - 1}`][1] act(() => - useAppStore - .getState() - .setAgentStatus( - foreignRow, - { state: 'working', agentType: 'codex', prompt: 'Another host update' }, - undefined, - { updatedAt: Date.now() + 1 }, - { tabId: `child-actual-${n - 1}`, worktreeId: `lineage-${n - 1}` } + useAppStore.getState().transactAgentStatuses((transaction) => + projectStatus( + transaction, + foreignTab, + { + sessionId: foreignTab.entityId, + workspaceId: foreignTab.worktreeId, + agent: 'codex', + status: 'working', + latestPrompt: 'Another host update', + updatedAt: Date.now() + 1, + hostExecutionOwned: true + }, + 'live', + null ) + ) + ) + expect(counts.get(n - 1)).toBe(1) + expect(observed.get(n - 1)?.find((row) => row.paneKey === foreignRow)?.entry.prompt).toBe( + 'Another host update' ) for (let i = 0; i < n - 1; i++) { expect(counts.has(i)).toBe(false) } + const afterForeign = visibleOrchestrationWorkForTest() + expect(afterForeign.builds - beforeForeign.builds).toBeLessThanOrEqual(1) + expect(afterForeign.aliasBuilds).toBe(beforeForeign.aliasBuilds) + expect(indexBuilds() - beforeForeignIndex).toBeLessThanOrEqual(1) + expect(afterForeign.visits - beforeForeign.visits).toBeLessThanOrEqual(n * 14) } ) @@ -518,7 +541,7 @@ it('joins production mirrored custom/collision rows locally and keeps canonical now: Date.now(), generation: 1 }) - expect(dashboard.map((row) => row.lineage.depth)).toEqual([0, 1]) + expect(dashboard.map((row) => row.lineage?.depth)).toEqual([0, 1]) expect(selectWorktreeAgentActivitySummary(state, 'folder-a').hasLiveWorking).toBe(true) const activity = buildActivityEvents({ ...state, @@ -598,6 +621,20 @@ it('joins production mirrored custom/collision rows locally and keeps canonical } }) +it.each(['default', 'reserved', 'collision'] as const)( + 'joins mirrored live/retained terminal contexts with positive provenance and a %s parent', + async (kind) => { + const { verifyMirroredTerminalLineage } = + await import('./mirrored-terminal-lineage.test-fixture') + await verifyMirroredTerminalLineage(kind, { + patch, + entry, + mount: () => act(() => root.render()), + getRows: () => rows + }) + } +) + it('settles the production graph subscription/scheduler/publication/receiver loop with at most one feedback flight', async () => { const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = await import('../../../../main/runtime/runtime-agent-lineage.test-fixture') diff --git a/src/renderer/src/components/sidebar/worktree-agent-activity-summary.test.ts b/src/renderer/src/components/sidebar/worktree-agent-activity-summary.test.ts index 44f022357e9f..37c65e599815 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-activity-summary.test.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-activity-summary.test.ts @@ -64,6 +64,33 @@ describe('selectWorktreeAgentActivitySummary', () => { vi.restoreAllMocks() }) + it('attributes migration-blocked UUID and legacy terminal panes without affecting other worktrees', () => { + for (const paneKey of [makePaneKey('tab-1', LEAF_ID), 'tab-1:0', undefined, 'malformed']) { + const state: AgentActivityInput = { + tabsByWorktree: { 'repo::/wt-1': [makeTab('tab-1', 'repo::/wt-1')] }, + agentStatusEpoch: 0, + agentStatusByPaneKey: {}, + retainedAgentsByPaneKey: {}, + runtimeAgentOrchestrationByPaneKey: {}, + migrationUnsupportedByPtyId: { + legacy: { + ptyId: 'legacy', + paneKey, + worktreeId: 'repo::/wt-1', + tabId: 'tab-1', + reason: 'legacy-numeric-pane-key', + source: 'local', + updatedAt: 1_000 + } + } + } + expect(selectWorktreeAgentActivitySummary(state, 'repo::/wt-1').hasPermission).toBe( + paneKey !== undefined && paneKey !== 'malformed' + ) + expect(selectWorktreeAgentActivitySummary(state, 'other').hasPermission).toBe(false) + } + }) + it('builds one cached agent summary index for multiple worktree lookups', () => { const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(2_000) const firstPaneKey = makePaneKey('tab-1', LEAF_ID) diff --git a/src/renderer/src/components/sidebar/worktree-agent-activity-summary.ts b/src/renderer/src/components/sidebar/worktree-agent-activity-summary.ts index 344639edb05e..c09caeb7fab8 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-activity-summary.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-activity-summary.ts @@ -287,12 +287,7 @@ function worktreeIdForPaneKey( paneKey: string | undefined, tabIdToWorktreeId: Map ): string | null { - const paneIdentity = parseAgentStatusPaneIdentity( - paneKey, - state.unifiedTabsByWorktree - ? getStructuredAgentSessionTabsByPaneKey(state.unifiedTabsByWorktree).get(paneKey) - : undefined - ) + const paneIdentity = parseAgentStatusPaneIdentity(paneKey) return paneIdentity ? (tabIdToWorktreeId.get(paneIdentity.tabId) ?? null) : null } diff --git a/src/renderer/src/runtime/visible-agent-orchestration.ts b/src/renderer/src/runtime/visible-agent-orchestration.ts index 57fb40bacfb2..8e593b828f61 100644 --- a/src/renderer/src/runtime/visible-agent-orchestration.ts +++ b/src/renderer/src/runtime/visible-agent-orchestration.ts @@ -1,7 +1,12 @@ import type { AppState } from '@/store/types' import type { WorktreeRuntimeOwnerState } from '@/lib/worktree-runtime-owner-state' import { getStructuredAgentSessionTabs } from '@/components/native-chat/structured-agent-session-tabs' -import { LOCAL_EXECUTION_HOST_ID } from '../../../shared/execution-host' +import { LOCAL_EXECUTION_HOST_ID, toRuntimeExecutionHostId } from '../../../shared/execution-host' +import { + isRemoteRuntimePtyId, + parseRemoteRuntimePtyId +} from '../../../shared/remote-runtime/remote-runtime-pty-id' +import { parseAgentStatusPaneIdentity } from '../../../shared/agent-status-worktree-attribution' import { structuredAgentSessionPaneKey, structuredAgentSessionTabId @@ -23,8 +28,11 @@ export type VisibleOrchestrationState = WorktreeRuntimeOwnerState & | 'agentStatusByPaneKey' | 'retainedAgentsByPaneKey' | 'runtimeAgentOrchestrationByPaneKey' + | 'ptyIdsByTabId' > - > + > & { + tabsByWorktree?: Record + } const EMPTY = {} const producerByContext = new WeakMap() export function orchestrationProducer(context: AgentStatusOrchestrationContext): string { @@ -86,12 +94,80 @@ function rowIdentities(state: VisibleOrchestrationState): RowIdentities { return rowCache } +let terminalCache: + | { inputs: unknown[]; hosts: Map; ptys: Map } + | undefined +function terminalProvenance(state: VisibleOrchestrationState) { + const inputs = [ + state.unifiedTabsByWorktree, + state.tabsByWorktree, + state.ptyIdsByTabId, + state.retainedAgentsByPaneKey + ] + if (terminalCache && inputs.every((value, index) => value === terminalCache?.inputs[index])) { + return terminalCache + } + const hosts = new Map() + const ptys = new Map() + const merge = (map: Map, key: string, host: string | null) => { + map.set(key, map.has(key) && map.get(key) !== host ? null : host) + } + const ptyHost = (id?: string | null): string | null | undefined => { + if (!id) { + return undefined + } + const remote = parseRemoteRuntimePtyId(id) + return remote?.environmentId + ? toRuntimeExecutionHostId(remote.environmentId) + : isRemoteRuntimePtyId(id) + ? null + : undefined + } + for (const [tab, ids] of Object.entries(state.ptyIdsByTabId ?? EMPTY)) { + for (const id of ids) { + visits++ + const host = ptyHost(id) + if (host !== undefined) { + merge(ptys, tab, host) + } + } + } + for (const tabs of Object.values(state.unifiedTabsByWorktree ?? EMPTY)) { + for (const tab of tabs) { + visits++ + if (tab.contentType === 'terminal' && tab.executionHostId) { + merge(hosts, aliasKey(tab.worktreeId, tab.entityId), tab.executionHostId) + } + } + } + for (const [worktree, tabs] of Object.entries(state.tabsByWorktree ?? EMPTY)) { + for (const tab of tabs) { + visits++ + const host = ptyHost(tab.ptyId) + if (host !== undefined) { + merge(hosts, aliasKey(worktree, tab.id), host) + } + } + } + for (const retained of Object.values(state.retainedAgentsByPaneKey ?? EMPTY)) { + visits++ + const host = ptyHost(retained.tab.ptyId) + if (host !== undefined) { + merge(hosts, aliasKey(retained.worktreeId, retained.tab.id), host) + } + } + terminalCache = { inputs, hosts, ptys } + return terminalCache +} + function projection(state: VisibleOrchestrationState): NonNullable { const rows = rowIdentities(state) + const terminals = terminalProvenance(state) const inputs = [ state.runtimeAgentOrchestrationByPaneKey, state.agentStatusByPaneKey, state.retainedAgentsByPaneKey, + terminals, rows ] if (cache && inputs.every((value, index) => value === cache?.inputs[index])) { @@ -132,21 +208,32 @@ function projection(state: VisibleOrchestrationState): NonNullable } const row = canonical.get(entry.paneKey) const runtime = state.runtimeAgentOrchestrationByPaneKey?.[row?.key ?? entry.paneKey] - const host = row - ? row.host - : entry.connectionId - ? null - : worktreeId - ? resolveStructuredAgentSessionOwner(state, worktreeId) - : null if ( runtime && - host === (producerByContext.get(runtime) ?? LOCAL_EXECUTION_HOST_ID) && + (!row || row.host === orchestrationProducer(runtime)) && runtime.taskId === entry.orchestration.taskId && runtime.dispatchId === entry.orchestration.dispatchId ) { + // Matching graph facts already carry the context's producer, independently of execution routing. return } + const tabId = parseAgentStatusPaneIdentity(entry.paneKey)?.tabId + const terminalKey = worktreeId && tabId ? aliasKey(worktreeId, tabId) : null + const tabHost = terminalKey ? terminals.hosts.get(terminalKey) : undefined + const ptyHost = tabId ? terminals.ptys.get(tabId) : undefined + const terminalHost = + tabHost === undefined + ? ptyHost + : ptyHost === undefined || tabHost === ptyHost + ? tabHost + : null + const host = row + ? row.host + : terminalHost !== undefined + ? terminalHost + : !entry.connectionId && worktreeId + ? resolveStructuredAgentSessionOwner(state, worktreeId) + : null if ( entry.orchestration.parentPaneKey && visibleKey(entry.orchestration.parentPaneKey, host) !== entry.orchestration.parentPaneKey From 784ad778a35e929f561ca5daca0fa095734c3fe8 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 00:57:33 -0700 Subject: [PATCH 004/164] Repair lineage test runtime boundaries and SQLite counters --- config/mobile-ci.vitest.config.mjs | 1 + .../scripts/check-tests-typecheck-ratchet.mjs | 4 + ...WorktreeAgentList.runtime-lineage.test.tsx | 83 ++++++++++++++ .../src/components/WorktreeAgentList.test.tsx | 62 ----------- mobile/tsconfig.test.json | 1 + .../dispatch-predicate-visits.test-fixture.ts | 47 ++++++++ ...ime-agent-orchestration-projection.test.ts | 102 +++++++----------- 7 files changed, 176 insertions(+), 124 deletions(-) create mode 100644 mobile/src/components/WorktreeAgentList.runtime-lineage.test.tsx create mode 100644 src/main/runtime/dispatch-predicate-visits.test-fixture.ts diff --git a/config/mobile-ci.vitest.config.mjs b/config/mobile-ci.vitest.config.mjs index a5c7684ae42b..cff0edf75878 100644 --- a/config/mobile-ci.vitest.config.mjs +++ b/config/mobile-ci.vitest.config.mjs @@ -3,6 +3,7 @@ import original from '../mobile/vitest.config.ts' // Keep real process, native, and runtime-specific contracts on Node. const nodeFiles = [ + 'src/components/WorktreeAgentList.runtime-lineage.test.tsx', 'scripts/check-tests-typecheck-incremental-cache.test.ts', 'src/tasks/mobile-agent-launch-architecture.test.ts', 'src/tasks/agent-launch-mobile-replay.test.ts', diff --git a/mobile/scripts/check-tests-typecheck-ratchet.mjs b/mobile/scripts/check-tests-typecheck-ratchet.mjs index 93972c1a0dec..15813105b3fb 100644 --- a/mobile/scripts/check-tests-typecheck-ratchet.mjs +++ b/mobile/scripts/check-tests-typecheck-ratchet.mjs @@ -13,6 +13,10 @@ const ERROR_LINE = /^(\S.*?)\(\d+,\d+\): error TS\d+:/ // Require every on-disk test in program except these explicit exclusions: error-only diff cannot see excluded/shadowed tests. export const TESTS_OUTSIDE_PROGRAM = new Map([ + [ + 'src/components/WorktreeAgentList.runtime-lineage.test.tsx', + 'Node-side: renders the mobile consumer of real desktop SQLite assignment projection, against Node rather than RN libs' + ], [ 'src/session/mobile-native-command-discovery.test.tsx', 'Node-side: imports the desktop ACP command discovery source, checked against @types/node rather than RN libs' diff --git a/mobile/src/components/WorktreeAgentList.runtime-lineage.test.tsx b/mobile/src/components/WorktreeAgentList.runtime-lineage.test.tsx new file mode 100644 index 000000000000..ec3f367296e2 --- /dev/null +++ b/mobile/src/components/WorktreeAgentList.runtime-lineage.test.tsx @@ -0,0 +1,83 @@ +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { expect, it, vi } from 'vitest' +import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' +import { WorktreeAgentSummary } from './WorktreeAgentSummary' +import { WorktreeAgentList } from './WorktreeAgentList' + +vi.mock('react-native', () => ({ + Pressable: 'Pressable', + StyleSheet: { create: (styles: T) => styles }, + Text: 'Text', + View: 'View' +})) +vi.mock('lucide-react-native', () => ({ + ChevronDown: 'ChevronDown', + ChevronRight: 'ChevronRight' +})) +vi.mock('./AgentStateDot', () => ({ AgentStateDot: () => null })) +vi.mock('./MobileAgentIcon', () => ({ MobileAgentIcon: () => null })) + +it('renders production-built canonical assignments as nested rows and groups only roots', async () => { + const clock = vi.spyOn(Date, 'now').mockReturnValue(1_800_000_000_000) + const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = + await import('../../../src/main/runtime/runtime-agent-lineage.test-fixture') + const { flattenAgentRowLineage } = await import('../worktree/agent-row-lineage') + const f = publicLineageFixture() + let tree: ReactTestRenderer | undefined + try { + const agents = f.build().agents + expect(flattenAgentRowLineage(agents).map((node) => [node.row.paneKey, node.depth])).toEqual([ + [canonicalChatRow(LINEAGE_PARENT), 0], + [canonicalChatRow(LINEAGE_CHILD), 1] + ]) + await act(async () => { + tree = create( + createElement(WorktreeAgentList, { + agents, + now: 1_800_000_000_000, + unvisited: false, + statusLive: true + }) + ) + }) + expect( + tree?.root + .findAll((node) => node.props.agent !== undefined) + .map((node) => [node.props.agent.paneKey, node.props.depth]) + ).toEqual([ + [canonicalChatRow(LINEAGE_PARENT), 0], + [canonicalChatRow(LINEAGE_CHILD), 1] + ]) + expect(tree?.root.findAllByType(WorktreeAgentSummary)).toHaveLength(0) + expect(agents[1].taskTitle).toBe('Build the worker result') + expect(JSON.stringify(tree?.toJSON())).toContain('Coordinate work') + expect(JSON.stringify(tree?.toJSON())).toContain('Implement work') + expect(JSON.stringify(tree?.toJSON())).not.toContain('2 agents') + expect(JSON.stringify(tree?.toJSON())).not.toContain(f.privateHandle) + expect(JSON.stringify(tree?.toJSON())).not.toContain(f.privatePane) + const orphan = { + ...agents[1], + paneKey: 'missing-parent-worker', + parentPaneKey: 'missing-parent' + } + await act(async () => + tree?.update( + createElement(WorktreeAgentList, { + agents: [...agents, orphan], + now: 1_800_000_000_000, + unvisited: false + }) + ) + ) + expect( + tree?.root + .findByType(WorktreeAgentSummary) + .props.agents.map((row: RuntimeWorktreeAgentRow) => row.paneKey) + ).toEqual([canonicalChatRow(LINEAGE_PARENT), orphan.paneKey]) + } finally { + await act(async () => tree?.unmount()) + f.db.close() + clock.mockRestore() + } +}) diff --git a/mobile/src/components/WorktreeAgentList.test.tsx b/mobile/src/components/WorktreeAgentList.test.tsx index 4cdb7a5007c4..3cb14c4eb672 100644 --- a/mobile/src/components/WorktreeAgentList.test.tsx +++ b/mobile/src/components/WorktreeAgentList.test.tsx @@ -2,8 +2,6 @@ import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types' -import { WorktreeAgentRow } from './WorktreeAgentRow' -import { WorktreeAgentSummary } from './WorktreeAgentSummary' import { WorktreeAgentList } from './WorktreeAgentList' import { findAllByHostType, findByHostType } from '../test-support/react-test-renderer-host-nodes' @@ -170,63 +168,3 @@ describe('WorktreeAgentList', () => { ) }) }) - -it('renders production-built canonical assignments as nested rows and groups only roots', async () => { - const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = - await import('../../../src/main/runtime/runtime-agent-lineage.test-fixture') - const { flattenAgentRowLineage } = await import('../worktree/agent-row-lineage') - const f = publicLineageFixture() - let tree: ReactTestRenderer | undefined - try { - const agents = f.build().agents - expect(flattenAgentRowLineage(agents).map((node) => [node.row.paneKey, node.depth])).toEqual([ - [canonicalChatRow(LINEAGE_PARENT), 0], - [canonicalChatRow(LINEAGE_CHILD), 1] - ]) - await act(async () => { - tree = create( - createElement(WorktreeAgentList, { - agents, - now: Date.now(), - unvisited: false, - statusLive: true - }) - ) - }) - expect( - tree?.root - .findAllByType(WorktreeAgentRow) - .map((node) => [node.props.agent.paneKey, node.props.depth]) - ).toEqual([ - [canonicalChatRow(LINEAGE_PARENT), 0], - [canonicalChatRow(LINEAGE_CHILD), 1] - ]) - expect(tree?.root.findAllByType(WorktreeAgentSummary)).toHaveLength(0) - expect(JSON.stringify(tree?.toJSON())).toContain('Build the worker result') - expect(JSON.stringify(tree?.toJSON())).not.toContain('2 agents') - expect(JSON.stringify(tree?.toJSON())).not.toContain(f.privateHandle) - expect(JSON.stringify(tree?.toJSON())).not.toContain(f.privatePane) - const orphan = { - ...agents[1], - paneKey: 'missing-parent-worker', - parentPaneKey: 'missing-parent' - } - await act(async () => - tree?.update( - createElement(WorktreeAgentList, { - agents: [...agents, orphan], - now: Date.now(), - unvisited: false - }) - ) - ) - expect( - tree?.root - .findByType(WorktreeAgentSummary) - .props.agents.map((row: RuntimeWorktreeAgentRow) => row.paneKey) - ).toEqual([canonicalChatRow(LINEAGE_PARENT), orphan.paneKey]) - } finally { - await act(async () => tree?.unmount()) - f.db.close() - } -}) diff --git a/mobile/tsconfig.test.json b/mobile/tsconfig.test.json index b2eb7cb44eb0..f8e44802b172 100644 --- a/mobile/tsconfig.test.json +++ b/mobile/tsconfig.test.json @@ -10,6 +10,7 @@ // are React Native's, where `setTimeout` answers a number rather than a NodeJS.Timeout, so // pulling that graph in reports ~280 errors about the desktop rather than about mobile. Their // own runtime coverage is vitest, which runs them under Node. + "src/components/WorktreeAgentList.runtime-lineage.test.tsx", "src/session/mobile-native-command-discovery.test.tsx", "src/tasks/agent-launch-mobile-replay.test.ts", "src/test-support/rpc-recording/recorded-request-params.test.ts", diff --git a/src/main/runtime/dispatch-predicate-visits.test-fixture.ts b/src/main/runtime/dispatch-predicate-visits.test-fixture.ts new file mode 100644 index 000000000000..33e9a53366c4 --- /dev/null +++ b/src/main/runtime/dispatch-predicate-visits.test-fixture.ts @@ -0,0 +1,47 @@ +import { DatabaseSync } from 'node:sqlite' +import { vi } from 'vitest' +import type SyncDatabase from '../sqlite/sync-database' + +// SQL predicate visits complement range plans/probe counts; they are not total SQLite VM steps. +export function installSqlVisitCounters(counters: Record number>) { + const initialized = new WeakSet() + const prepare = DatabaseSync.prototype.prepare + return vi.spyOn(DatabaseSync.prototype, 'prepare').mockImplementation(function ( + this: DatabaseSync, + sql + ) { + if (!initialized.has(this)) { + for (const [name, visit] of Object.entries(counters)) { + this.function(name, {}, (_rowid: unknown) => visit()) + } + initialized.add(this) + } + return prepare.call(this, sql) + }) +} + +export function traceDispatchPredicateVisits( + db: SyncDatabase, + functions: { candidate: string; latest?: string; observation?: string } +) { + const prepare = db.prepare.bind(db) + return vi.spyOn(db, 'prepare').mockImplementation((query) => { + let instrumented = query.replaceAll( + 'WHERE assignee_orca_session_id IS NOT NULL', + `WHERE assignee_orca_session_id IS NOT NULL AND ${functions.candidate}(rowid)` + ) + if (functions.latest && query.includes('rowid AS n')) { + instrumented = instrumented.replace( + 'ORDER BY rowid DESC LIMIT 1', + `AND ${functions.latest}(rowid) ORDER BY rowid DESC LIMIT 1` + ) + } + if (functions.observation) { + instrumented = instrumented.replace( + 'WHERE dispatch_id IN', + `WHERE ${functions.observation}(rowid) AND dispatch_id IN` + ) + } + return prepare(instrumented) + }) +} diff --git a/src/main/runtime/runtime-agent-orchestration-projection.test.ts b/src/main/runtime/runtime-agent-orchestration-projection.test.ts index 46573954ae85..6394f7061e99 100644 --- a/src/main/runtime/runtime-agent-orchestration-projection.test.ts +++ b/src/main/runtime/runtime-agent-orchestration-projection.test.ts @@ -34,6 +34,10 @@ import { structuredAgentSessionTabId } from '../../shared/structured-agent-session-projection' import { RuntimeAgentOrchestrationProjection } from './runtime-agent-orchestration-projection' +import { + installSqlVisitCounters, + traceDispatchPredicateVisits +} from './dispatch-predicate-visits.test-fixture' import type { RuntimeLeafRecord } from './runtime-terminal-state-records' import { OrchestrationDb } from './orchestration/db' import { @@ -47,6 +51,8 @@ const WORKER_CHAT = testOrcaSessionId('9c3e5a17-4b2d-4f60-8e91-0d7a6c2b5e48') const TERMINAL_WORKER_HANDLE = 'term_worker' const TERMINAL_WORKER_PANE = 'tab_w:11111111-1111-4111-8111-111111111111' +afterEach(() => vi.restoreAllMocks()) + function chatRow(sessionId: string): string { return structuredAgentSessionPaneKey(structuredAgentSessionTabId(sessionId), sessionId) } @@ -260,32 +266,20 @@ it.each([20, 200])( const roster = vi.spyOn(db, 'listSessionDispatchesForPresentation') let candidateVisits = 0 let latestVisits = 0 - db.db.function('lineage_candidate_visit', {}, (_rowid: unknown) => { - candidateVisits++ - return 1 + installSqlVisitCounters({ + lineage_candidate_visit: () => { + candidateVisits++ + return 1 + }, + lineage_latest_visit: () => { + latestVisits++ + return 1 + } }) - db.db.function('lineage_latest_visit', {}, (_rowid: unknown) => { - latestVisits++ - return 1 + const sql = traceDispatchPredicateVisits(db.db, { + candidate: 'lineage_candidate_visit', + latest: 'lineage_latest_visit' }) - const prepare = db.db.prepare.bind(db.db) - const sql = vi - .spyOn(db.db, 'prepare') - .mockImplementation((query) => - prepare( - query - .replaceAll( - 'WHERE assignee_orca_session_id IS NOT NULL', - 'WHERE assignee_orca_session_id IS NOT NULL AND lineage_candidate_visit(rowid)' - ) - .replace( - 'ORDER BY rowid DESC LIMIT 1', - query.includes('rowid AS n') - ? 'AND lineage_latest_visit(rowid) ORDER BY rowid DESC LIMIT 1' - : 'ORDER BY rowid DESC LIMIT 1' - ) - ) - ) const output = projection.buildByPaneKey() expect(Object.keys(output ?? {})).toHaveLength(n) expect( @@ -380,21 +374,13 @@ it.each([20, 200])( insert.run(n, `expired-${i}-`, run.id, task.id, `null-session-${i}`) } let candidates = 0 - db.db.function('null_candidate_visit', {}, (_rowid: unknown) => { - candidates++ - return 1 + installSqlVisitCounters({ + null_candidate_visit: () => { + candidates++ + return 1 + } }) - const prepare = db.db.prepare.bind(db.db) - const trace = vi - .spyOn(db.db, 'prepare') - .mockImplementation((query) => - prepare( - query.replaceAll( - 'WHERE assignee_orca_session_id IS NOT NULL', - 'WHERE assignee_orca_session_id IS NOT NULL AND null_candidate_visit(rowid)' - ) - ) - ) + const trace = traceDispatchPredicateVisits(db.db, { candidate: 'null_candidate_visit' }) const roster = vi.spyOn(db, 'listSessionDispatchesForPresentation') const projection = projectionFor(db) const output = projection.buildByPaneKey() ?? {} @@ -557,6 +543,7 @@ it.skipIf(process.env.ORCA_LINEAGE_BENCH !== '1')( const directory = mkdtempSync(join(tmpdir(), 'orca-lineage-benchmark-')) const path = join(directory, 'orchestration.sqlite') let db = new OrchestrationDb(path) + let nativePrepare: ReturnType | undefined try { const run = db.createRun({ objective: 'benchmark', @@ -622,7 +609,7 @@ it.skipIf(process.env.ORCA_LINEAGE_BENCH !== '1')( row.id, row.task_id, Math.floor(i / active.length), - Date.now() + 1_800_000_000_000 + i ) } db.db.exec('DROP INDEX idx_dispatch_session_presentation') @@ -635,31 +622,21 @@ it.skipIf(process.env.ORCA_LINEAGE_BENCH !== '1')( db = new OrchestrationDb(path) const reopenWithIndexCreationMs = performance.now() - openStarted let observationVisits = 0 - db.db.function('lineage_observation_visit', {}, (_rowid: unknown) => { - observationVisits++ - return 1 - }) let visits = 0 - db.db.function('lineage_bench_visit', {}, (_rowid: unknown) => { - visits++ - return 1 + nativePrepare = installSqlVisitCounters({ + lineage_observation_visit: () => { + observationVisits++ + return 1 + }, + lineage_bench_visit: () => { + visits++ + return 1 + } + }) + const trace = traceDispatchPredicateVisits(db.db, { + candidate: 'lineage_bench_visit', + observation: 'lineage_observation_visit' }) - const prepare = db.db.prepare.bind(db.db) - const trace = vi - .spyOn(db.db, 'prepare') - .mockImplementation((query) => - prepare( - query - .replaceAll( - 'WHERE assignee_orca_session_id IS NOT NULL', - 'WHERE assignee_orca_session_id IS NOT NULL AND lineage_bench_visit(rowid)' - ) - .replace( - 'WHERE dispatch_id IN', - 'WHERE lineage_observation_visit(rowid) AND dispatch_id IN' - ) - ) - ) const start = performance.now() const output = projectionFor(db).buildByPaneKey() const buildMs = performance.now() - start @@ -715,6 +692,7 @@ it.skipIf(process.env.ORCA_LINEAGE_BENCH !== '1')( ) trace.mockRestore() } finally { + nativePrepare?.mockRestore() db.close() rmSync(directory, { recursive: true, force: true }) } From 1523a1c1c3617666e2a3e2bf63216ccd7e1d7050 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 01:11:21 -0700 Subject: [PATCH 005/164] Provide read-only crew snapshots for each agent --- .../agent-session-record-publication.ts | 2 + .../construction/runtime-service-state.ts | 2 + .../canonical-orca-session-id.ts | 30 +- .../orchestration/crew/crew-changes.ts | 27 ++ .../crew/crew-cli-addresses.test.ts | 183 +++++++++++ .../crew/crew-mutation-notifications.ts | 58 ++++ .../orchestration/crew/crew-parties.ts | 68 ++++ .../runtime/orchestration/crew/crew-query.ts | 164 ++++++++++ .../crew/crew-read-model.test.ts | 299 ++++++++++++++++++ .../orchestration/crew/crew-read-model.ts | 283 +++++++++++++++++ .../runtime/orchestration/crew/crew-rules.ts | 26 ++ .../runtime/orchestration/crew/crew-stream.ts | 54 ++++ .../db/attach-orchestration-db-methods.ts | 2 + .../orchestration/db/orchestration-db.ts | 2 + .../db/schema/schema-column-probes.ts | 12 + .../orchestration-sender-name.ts | 18 +- src/main/runtime/rpc/methods/orchestration.ts | 2 + .../rpc/methods/orchestration/crew-methods.ts | 51 +++ .../runtime-agent-orchestration-projection.ts | 29 +- .../runtime-orchestration-sender-names.ts | 9 +- .../visible-graph-changed-worktrees.ts | 39 +++ .../session-tabs/session-tabs-inventory.ts | 36 +-- .../automation-operations.ts | 30 ++ .../workspaces/workspace-process-listing.ts | 1 + src/shared/orchestration-agent-reference.ts | 8 + src/shared/orchestration-crew.ts | 55 ++++ 26 files changed, 1425 insertions(+), 65 deletions(-) create mode 100644 src/main/runtime/orchestration/crew/crew-changes.ts create mode 100644 src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts create mode 100644 src/main/runtime/orchestration/crew/crew-mutation-notifications.ts create mode 100644 src/main/runtime/orchestration/crew/crew-parties.ts create mode 100644 src/main/runtime/orchestration/crew/crew-query.ts create mode 100644 src/main/runtime/orchestration/crew/crew-read-model.test.ts create mode 100644 src/main/runtime/orchestration/crew/crew-read-model.ts create mode 100644 src/main/runtime/orchestration/crew/crew-rules.ts create mode 100644 src/main/runtime/orchestration/crew/crew-stream.ts create mode 100644 src/main/runtime/rpc/methods/orchestration/crew-methods.ts create mode 100644 src/main/runtime/session-graph/visible-graph-changed-worktrees.ts create mode 100644 src/shared/orchestration-agent-reference.ts create mode 100644 src/shared/orchestration-crew.ts diff --git a/src/main/runtime/agent-session-record-publication.ts b/src/main/runtime/agent-session-record-publication.ts index bb532bfbde4f..513587adc1d8 100644 --- a/src/main/runtime/agent-session-record-publication.ts +++ b/src/main/runtime/agent-session-record-publication.ts @@ -1,3 +1,4 @@ +import { sessionCrewChanges } from './orchestration/crew/crew-changes' import type { AgentSessionStoreState } from './agent-session-store-state' import type { AgentSessionStoreTransactions } from './agent-session-store-transactions' @@ -41,6 +42,7 @@ export abstract class AgentSessionRecordPublication { .map(([id]) => id) return applied }, options) + sessionCrewChanges.notify() for (const sessionId of proven) { this.deathEvidenceListeners.forEach((listener) => listener(sessionId)) } diff --git a/src/main/runtime/construction/runtime-service-state.ts b/src/main/runtime/construction/runtime-service-state.ts index 88f06aa8ccff..60894f2edc44 100644 --- a/src/main/runtime/construction/runtime-service-state.ts +++ b/src/main/runtime/construction/runtime-service-state.ts @@ -1,3 +1,4 @@ +import { CrewChanges } from '../orchestration/crew/crew-changes' import { OrchestrationStructuredMailboxPointerDelivery } from '../orchestration/structured-mailbox-pointer-delivery' import { createStructuredMailboxPointerHost } from '../orchestration/structured-mailbox-pointer-host' @@ -237,6 +238,7 @@ export abstract class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWith } }) + readonly crewChanges = new CrewChanges() protected _orchestrationDb: OrchestrationDb | null = null protected readonly orchestrationMailboxOwner = new OrchestrationMailboxOwner({ diff --git a/src/main/runtime/orchestration/canonical-orca-session-id.ts b/src/main/runtime/orchestration/canonical-orca-session-id.ts index ff2808eb45ad..06767a607148 100644 --- a/src/main/runtime/orchestration/canonical-orca-session-id.ts +++ b/src/main/runtime/orchestration/canonical-orca-session-id.ts @@ -10,8 +10,14 @@ export function canonicalOrcaSessionId( orcaSessionId: OrcaSessionId, store: Pick | null = readAgentSessionRecordStore() ): OrcaSessionId { + return createCanonicalOrcaSessionResolver(store)(orcaSessionId) +} + +export function createCanonicalOrcaSessionResolver( + store: Pick | null +): (id: OrcaSessionId) => OrcaSessionId { if (!store) { - return orcaSessionId + return (id) => id } const clearedFrom = new Map() for (const record of store.listRecords()) { @@ -20,15 +26,17 @@ export function canonicalOrcaSessionId( clearedFrom.set(next, record.sessionId) } } - // The visited set bounds corrupt chains; valid clear lineage is acyclic. - let root: string = orcaSessionId - const earlier = new Set([root]) - let prior = clearedFrom.get(root) - while (prior && !earlier.has(prior)) { - earlier.add(prior) - root = prior - prior = clearedFrom.get(root) + return (orcaSessionId) => { + // The visited set bounds corrupt chains; valid clear lineage is acyclic. + let root: string = orcaSessionId + const earlier = new Set([root]) + let prior = clearedFrom.get(root) + while (prior && !earlier.has(prior)) { + earlier.add(prior) + root = prior + prior = clearedFrom.get(root) + } + // Record ids are minted as Orca session ids; one that is not cannot name the conversation. + return isOrcaSessionId(root) ? root : orcaSessionId } - // Record ids are minted as Orca session ids; one that is not cannot name the conversation. - return isOrcaSessionId(root) ? root : orcaSessionId } diff --git a/src/main/runtime/orchestration/crew/crew-changes.ts b/src/main/runtime/orchestration/crew/crew-changes.ts new file mode 100644 index 000000000000..584306f9a2ba --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-changes.ts @@ -0,0 +1,27 @@ +export class CrewChanges { + private readonly listeners = new Set<() => void>() + private queued = false + + subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener) + return () => { + this.listeners.delete(listener) + } + } + + notify = (): void => { + if (this.queued || this.listeners.size === 0) { + return + } + this.queued = true + // Database mutations are synchronous; readers run after their outer transaction finishes. + queueMicrotask(() => { + this.queued = false + for (const listener of this.listeners) { + listener() + } + }) + } +} + +export const sessionCrewChanges = new CrewChanges() diff --git a/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts b/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts new file mode 100644 index 000000000000..da6130ad4b1c --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts @@ -0,0 +1,183 @@ +import '../../rpc/unused-default-rpc-methods.test-fixture' +import { afterEach, expect, it, vi } from 'vitest' +import { z } from 'zod' +import { ORCHESTRATION_FEDERATION_CONTROL_MAIL_PROTOCOL_VERSION } from '../../../../shared/protocol-version' +import { dispatch } from '../../../../cli/dispatch' +import { RuntimeClient, RuntimeClientError } from '../../../../cli/runtime-client' +import { buildCrewSnapshot } from './crew-read-model' +import { agentSessionConversationView } from '../../../../shared/agent-session-conversation-view' +import { + createSessionCallerHarness, + orchestrationRequest, + sessionRecord, + SESSION_X, + SESSION_Y, + WORKER_HANDLE, + WORKER_PANE +} from '../../rpc/orchestration-session-caller-test-fixture' + +const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) +vi.mock('../../../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ + getStructuredAgentSessionHost: () => hostRef.current +})) +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllEnvs() +}) + +it('executes snapshot addresses through CLI send and the dispatcher into the proven mailbox', async () => { + const h = createSessionCallerHarness(hostRef) + try { + vi.stubEnv('ORCA_AGENT_SESSION_ID', '') + vi.stubEnv('ORCA_PANE_KEY', '') + vi.spyOn(console, 'log').mockImplementation(() => {}) + vi.spyOn(h.runtime, 'deliverPendingMessagesForHandle').mockImplementation(() => {}) + vi.spyOn(h.runtime, 'ensureOrchestrationFederationRelay').mockImplementation(() => {}) + vi.spyOn(h.runtime, 'getTerminalPaneKey').mockImplementation((handle) => + handle === 'term_peer' + ? 'tab_peer:cccccccc-cccc-4ccc-8ccc-cccccccccccc' + : handle === 'term_coord' + ? 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + : handle === WORKER_HANDLE + ? WORKER_PANE + : null + ) + vi.spyOn(h.runtime, 'getLiveTerminalPaneKey').mockImplementation((handle) => + h.runtime.getTerminalPaneKey(handle) + ) + const run = h.db.createRun({ + objective: 'Crew', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + }) + const worker = h.db.createDispatchContext({ + taskId: h.db.createTask({ runId: run.id, spec: 'Worker' }).id, + assigneeHandle: WORKER_HANDLE, + assigneePaneKey: WORKER_PANE, + creator: { kind: 'system' }, + maxDepth: 10 + }) + const federated = h.db.createStartingWorkerDispatch({ + taskSpec: 'Federated worker', + taskRunId: run.id, + creator: { kind: 'system' }, + maxDepth: 10, + startOptions: { agent: 'codex' }, + federation: { + environmentId: 'other-host', + environmentName: 'Windows', + peerFingerprint: 'test-peer', + protocolVersion: ORCHESTRATION_FEDERATION_CONTROL_MAIL_PROTOCOL_VERSION + } + }) + h.db.prepareStartingWorkerAuthority({ + dispatchId: federated.dispatch.id, + handle: 'term_remote', + paneKey: 'tab_remote:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', + processIncarnation: 'runtime:remote:1', + worktreeId: 'folder-remote', + effects: [], + setupState: 'not_applicable' + }) + h.db.markWorkerDispatchReady(federated.dispatch.id) + h.db.insertMessage({ from: 'term_peer', to: 'term_coord', subject: 'Hello', body: 'hello' }) + const x = sessionRecord(SESSION_X) + h.records.set(SESSION_X, { + ...x, + conversationCommand: { + command: 'clear', + phase: 'committed', + state: 'completed', + callerKey: 'clear-key', + operationId: 'clear-test', + replacementSessionId: SESSION_Y + } + }) + h.records.set(SESSION_Y, sessionRecord(SESSION_Y)) + h.db.insertMessage({ + from: `orca_session_id:${SESSION_X}`, + to: 'term_coord', + subject: 'Chat', + body: 'clear lineage' + }) + const deps = { + db: h.db, + retainedDbExists: true, + hostKey: 'local', + statuses: [], + records: { + getRecord: (id: string) => { + const record = h.records.get(id) + return record ? agentSessionConversationView(record) : null + }, + listRecords: () => [...h.records.values()].map(agentSessionConversationView) + }, + liveHandle: (handle: string) => handle.startsWith('term_'), + paneForHandle: (handle: string) => (handle === WORKER_HANDLE ? WORKER_PANE : null), + handleForPane: () => null, + name: () => 'Duplicate name' + } + const crew = buildCrewSnapshot('term_coord', deps) + const managed = buildCrewSnapshot(WORKER_HANDLE, deps) + const addresses = [ + ...crew.sections.managing, + ...crew.sections.talkingWith, + ...managed.sections.managedBy + ].flatMap((row) => (row.sendAddress ? [row.sendAddress] : [])) + expect(addresses).toEqual( + expect.arrayContaining([ + `dispatch:${worker.id}`, + `dispatch:${federated.dispatch.id}`, + `run:${run.id}`, + 'term_peer', + `orca_session_id:${SESSION_X}` + ]) + ) + const client = new RuntimeClient('/tmp/crew-address-client', 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) + } + // SAFETY: the real dispatcher validates each method's result; this is only the in-memory transport boundary. + return { ...response, result: response.result as T, _meta: { runtimeId: 'crew-test' } } + }) + for (const to of addresses) { + await dispatch(['orchestration', 'send'], { + client, + flags: new Map([ + ['from', WORKER_HANDLE], + ['to', to], + ['subject', 'Crew send'], + ['body', to] + ]), + cwd: '/tmp', + json: true + }) + } + const messages = h.db.db + .prepare("SELECT to_handle, body FROM messages WHERE subject = 'Crew send' ORDER BY sequence") + .all() + expect(messages).toEqual( + addresses + .filter((address) => address !== `dispatch:${federated.dispatch.id}`) + .map((address) => ({ to_handle: address, body: address })) + ) + const relays = h.db.db + .prepare( + "SELECT dispatch_id, direction, payload FROM federation_relay_items WHERE kind = 'control_message'" + ) + .all() + expect(relays).toEqual([ + expect.objectContaining({ + dispatch_id: federated.dispatch.id, + direction: 'to_worker', + payload: expect.stringContaining(`dispatch:${federated.dispatch.id}`) + }) + ]) + } finally { + h.close() + } +}) diff --git a/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts b/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts new file mode 100644 index 000000000000..ebad9003de75 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts @@ -0,0 +1,58 @@ +import type { OrchestrationDb } from '../db' + +const mutations = [ + 'insertMessage', + 'insertMessages', + 'createDispatchContext', + 'createStartingWorkerDispatch', + 'prepareStartingWorkerAuthority', + 'markWorkerDispatchReady', + 'recordWorkerStage', + 'completeDispatch', + 'completeActiveDispatchesForTask', + 'failActiveDispatchForTask', + 'failDispatch', + 'settleWorkerReport', + 'bindRun', + 'createRun', + 'createQuestion', + 'answerQuestion', + 'closeQuestionsForDispatch', + 'createGate', + 'resolveGate', + 'timeoutGate', + 'updateTaskStatus', + 'updateFederatedDispatchResources', + 'updateFederatedDispatchRuntimeEpoch', + 'transitionLifecycle', + 'abandonWorkerDispatch', + 'failWorkerStart', + 'markWorkerStartUnknown', + 'beginWorkerStop', + 'settleWorkerStop', + 'markWorkerStopUnknown', + 'unbindOtherRunsForCoordinator', + 'recordAttemptObservation', + 'resetAll', + 'resetTasks', + 'resetMessages' +] as const satisfies readonly (keyof OrchestrationDb)[] + +/** Wake after the synchronous outer mutation; nested writes coalesce and rolled-back reads compare equal. */ +export function attachCrewMutationNotifications(ctor: { prototype: object }): void { + for (const name of mutations) { + const original: unknown = Reflect.get(ctor.prototype, name) + if (typeof original !== 'function') { + continue + } + Object.defineProperty(ctor.prototype, name, { + configurable: true, + writable: true, + value(this: OrchestrationDb, ...args: unknown[]) { + const result: unknown = original.apply(this, args) + this.crewChanges.notify() + return result + } + }) + } +} diff --git a/src/main/runtime/orchestration/crew/crew-parties.ts b/src/main/runtime/orchestration/crew/crew-parties.ts new file mode 100644 index 000000000000..7cfa6a3eb738 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-parties.ts @@ -0,0 +1,68 @@ +import type { AgentMessageSender } from '../../../../shared/agent-session/agent-session-message-source' +import { + formatOrcaSessionAddress, + isOrcaSessionId, + parseOrcaSessionAddress +} from '../../../../shared/orca-session-address' +import { isPublicOrchestrationAddress } from '../../../../shared/orchestration-agent-reference' +import { createCanonicalSessionPaneResolver } from '../structured-session-lineage' +import { createCanonicalOrcaSessionResolver } from '../canonical-orca-session-id' +import type { CrewReadDependencies } from './crew-read-model' + +export type Party = AgentMessageSender['party'] & { paneKey: string | null } + +export function createCrewPartyRegistry(deps: CrewReadDependencies) { + const recordList = deps.records?.listRecords() ?? [] + const resolveRoot = createCanonicalOrcaSessionResolver({ listRecords: () => recordList }) + const rootCache = new Map() + const root = (id: string): string => { + let value = rootCache.get(id) + if (!value) { + value = isOrcaSessionId(id) ? resolveRoot(id) : id + rootCache.set(id, value) + } + return value + } + const canonicalPane = createCanonicalSessionPaneResolver(deps.records) + const parties = new Map() + const aliases = new Map() + const party = ( + session: string | null, + storedHandle: string | null, + pane: string | null, + fallback?: string + ): Party | undefined => { + const sessionId = session ? root(session) : null + const liveHandle = pane ? deps.handleForPane(pane) : null + const handle = + liveHandle ?? (storedHandle && deps.liveHandle(storedHandle) ? storedHandle : null) + const publicHandle = handle?.startsWith('term_') ? handle : null + const publicAddress = + sessionId && isOrcaSessionId(sessionId) + ? formatOrcaSessionAddress(sessionId) + : ((publicHandle && aliases.get(publicHandle)) ?? publicHandle ?? fallback) + if (!publicAddress || !isPublicOrchestrationAddress(publicAddress)) { + return undefined + } + const existing = parties.get(publicAddress) + const value = existing ?? { + address: publicAddress, + terminalHandle: publicHandle, + orcaSessionId: parseOrcaSessionAddress(publicAddress), + paneKey: sessionId ? canonicalPane(sessionId) : pane + } + parties.set(publicAddress, value) + for (const alias of [ + publicAddress, + storedHandle, + handle, + session && isOrcaSessionId(session) ? formatOrcaSessionAddress(session) : null + ]) { + if (alias) { + aliases.set(alias, publicAddress) + } + } + return value + } + return { parties, aliases, party } +} diff --git a/src/main/runtime/orchestration/crew/crew-query.ts b/src/main/runtime/orchestration/crew/crew-query.ts new file mode 100644 index 000000000000..ab87d635d6ed --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-query.ts @@ -0,0 +1,164 @@ +import { z } from 'zod' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-freshness' +import type { OrchestrationDb } from '../db' +import { currentRunCoordinatorOrcaSessionIdSql } from '../db/runs/run-coordinator-orca-session' + +const nullable = z.string().nullable() +export const CrewAssignment = z.object({ + ordinal: z.number(), + id: z.string(), + run_id: z.string(), + task_id: z.string(), + assignee_handle: nullable, + assignee_pane_key: nullable, + assignee_orca_session_id: nullable, + creator_handle: nullable, + creator_pane_key: nullable, + creator_orca_session_id: nullable, + creator_dispatch_id: nullable, + status: z.string(), + completed_at: nullable, + spec: z.string(), + task_title: nullable, + display_name: nullable, + task_status: z.string(), + coordinator_handle: nullable, + coordinator_pane_key: nullable, + coordinator_session: nullable, + stage: nullable, + agent: nullable, + host_label: nullable +}) +export type CrewAssignmentRow = z.infer + +const assignmentColumns = `d.rowid AS ordinal, d.id, d.run_id, d.task_id, + d.assignee_handle, d.assignee_pane_key, d.assignee_orca_session_id, + d.creator_handle, d.creator_pane_key, d.creator_orca_session_id, d.creator_dispatch_id, + d.status, d.completed_at, t.spec, t.task_title, t.display_name, t.status AS task_status, + r.coordinator_handle, r.coordinator_pane_key, + ${currentRunCoordinatorOrcaSessionIdSql('r')} AS coordinator_session, + w.stage, json_extract(w.start_options, '$.agent') AS agent, f.environment_name AS host_label` +const assignmentJoins = `JOIN tasks t ON t.id = d.task_id JOIN runs r ON r.id = d.run_id + LEFT JOIN worker_dispatches w ON w.dispatch_id = d.id + LEFT JOIN federated_dispatches f ON f.dispatch_id = d.id` + +export function readCrewAssignments(db: OrchestrationDb, now: number): CrewAssignmentRow[] { + const cutoff = new Date(now - AGENT_STATUS_STALE_AFTER_MS).toISOString() + const sessionIds = db.listSessionDispatchesForPresentation(now).map(({ dispatch }) => dispatch.id) + return CrewAssignment.array().parse( + db.db + .prepare(` + SELECT ${assignmentColumns} FROM dispatch_contexts d ${assignmentJoins} + WHERE d.assignee_orca_session_id IS NULL AND d.status IN ('pending', 'dispatched') + UNION ALL + SELECT ${assignmentColumns} FROM dispatch_contexts d ${assignmentJoins} + WHERE d.assignee_orca_session_id IS NULL AND d.status NOT IN ('pending', 'dispatched') AND julianday(d.completed_at) >= julianday(?) + AND NOT EXISTS (SELECT 1 FROM dispatch_contexts newer WHERE newer.rowid > d.rowid + AND ((d.assignee_orca_session_id IS NOT NULL AND newer.assignee_orca_session_id = d.assignee_orca_session_id) + OR (d.assignee_handle IS NOT NULL AND newer.assignee_handle = d.assignee_handle))) + UNION ALL + SELECT ${assignmentColumns} FROM dispatch_contexts d ${assignmentJoins} + WHERE d.id IN (SELECT value FROM json_each(?)) + ORDER BY ordinal DESC + `) + .all(cutoff, JSON.stringify(sessionIds)) + ) +} + +export function readCrewMailboxAssignments( + db: OrchestrationDb, + addresses: string[] +): CrewAssignmentRow[] { + const ids = addresses + .filter((address) => address.startsWith('dispatch:')) + .map((address) => address.slice(9)) + return ids.length === 0 + ? [] + : CrewAssignment.array().parse( + db.db + .prepare(` + SELECT ${assignmentColumns} FROM dispatch_contexts d ${assignmentJoins} + WHERE d.id IN (SELECT value FROM json_each(?)) + `) + .all(JSON.stringify(ids)) + ) +} + +const Traffic = z.object({ + peer: z.string(), + direction: z.enum(['to', 'from']), + sequence: z.number(), + body: z.string(), + created_at: z.string() +}) +export type CrewTraffic = z.infer + +/** Pair maxima follow enumeration, so a busy mailbox cannot crowd out its quieter peers. */ +export function readCrewTraffic( + db: OrchestrationDb, + aliases: string[], + cutoff: string +): CrewTraffic[] { + return Traffic.array().parse( + db.db + .prepare(` + WITH traffic AS ( + SELECT to_handle AS peer, 'to' AS direction, sequence, body, created_at + FROM messages WHERE from_handle IN (SELECT value FROM json_each(?)) + AND julianday(created_at) >= julianday(?) AND type <> 'heartbeat' + UNION ALL + SELECT from_handle AS peer, 'from' AS direction, sequence, body, created_at + FROM messages WHERE to_handle IN (SELECT value FROM json_each(?)) + AND julianday(created_at) >= julianday(?) AND type <> 'heartbeat' + ), peers AS (SELECT peer, MAX(sequence) AS sequence FROM traffic GROUP BY peer) + SELECT traffic.peer, traffic.direction, traffic.sequence, traffic.body, traffic.created_at + FROM peers JOIN traffic ON traffic.peer = peers.peer AND traffic.sequence = peers.sequence + ORDER BY traffic.sequence DESC + `) + .all(JSON.stringify(aliases), cutoff, JSON.stringify(aliases), cutoff) + ) +} + +export function readCrewQuestions(db: OrchestrationDb, aliases: string[]) { + return z + .object({ dispatch_id: z.string(), body: z.string(), created_at: z.string() }) + .array() + .parse( + db.db + .prepare(`SELECT q.dispatch_id, m.body, m.created_at FROM messages m + JOIN question_threads q ON q.message_id = m.id AND q.status = 'pending' + WHERE m.to_handle IN (SELECT value FROM json_each(?)) ORDER BY m.sequence DESC + `) + .all(JSON.stringify(aliases)) + ) +} + +export function readCrewRuns(db: OrchestrationDb, addresses: string[]) { + const ids = addresses + .filter((address) => address.startsWith('run:')) + .map((address) => address.slice(4)) + return z + .object({ id: z.string(), handle: nullable, pane: nullable, session: nullable }) + .array() + .parse( + db.db + .prepare(`SELECT id, coordinator_handle AS handle, coordinator_pane_key AS pane, + ${currentRunCoordinatorOrcaSessionIdSql('runs')} AS session FROM runs + WHERE id IN (SELECT value FROM json_each(?))`) + .all(JSON.stringify(ids)) + ) +} + +export function readCrewSelfAssignments( + db: OrchestrationDb, + party: { terminalHandle: string | null; paneKey: string | null; orcaSessionId: string | null } +) { + return CrewAssignment.array().parse( + db.db + .prepare(`SELECT ${assignmentColumns} + FROM dispatch_contexts d ${assignmentJoins} WHERE d.assignee_handle = ? + OR d.assignee_pane_key = ? OR d.assignee_orca_session_id = ? + `) + .all(party.terminalHandle, party.paneKey, party.orcaSessionId) + ) +} diff --git a/src/main/runtime/orchestration/crew/crew-read-model.test.ts b/src/main/runtime/orchestration/crew/crew-read-model.test.ts new file mode 100644 index 000000000000..2167000bcd77 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-read-model.test.ts @@ -0,0 +1,299 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { OrchestrationDb } from '../db' +import { buildCrewSnapshot, type CrewReadDependencies } from './crew-read-model' +import { CrewChanges } from './crew-changes' +import { subscribeCrew } from './crew-stream' +import type { OrchestrationCrewFrame } from '../../../../shared/orchestration-crew' +import { agentSessionRecordFixture } from '../../../native-chat/agent-session-record-test-fixture' +import { agentSessionConversationView } from '../../../../shared/agent-session-conversation-view' + +const opened: OrchestrationDb[] = [] +afterEach(() => opened.splice(0).forEach((db) => db.close())) +function fixture() { + const db = new OrchestrationDb(':memory:') + opened.push(db) + const handles = new Map( + ['coord', 'worker', 'helper', 'grandchild', 'peer', 'outbound'].map((name) => [ + `term_${name}`, + `tab_${name}:aaaaaaaa-aaaa-4aaa-8aaa-${name.padEnd(12, 'a')}` + ]) + ) + const deps: CrewReadDependencies = { + db, + retainedDbExists: true, + hostKey: 'test-host', + records: null, + statuses: [], + liveHandle: (handle) => handles.has(handle), + handleForPane: (pane) => [...handles].find(([, value]) => value === pane)?.[0] ?? null, + paneForHandle: (handle) => handles.get(handle) ?? null, + name: (_identity, task) => task ?? 'Duplicate name' + } + const run = db.createRun({ + objective: 'Crew', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: handles.get('term_coord')! + }) + const assign = (handle: string, creator = 'term_coord', title = 'Implement crew') => { + const task = db.createTask({ runId: run.id, spec: title, taskTitle: title }) + db.updateTaskStatus(task.id, 'ready') + return db.createDispatchContext({ + taskId: task.id, + assigneeHandle: handle, + assigneePaneKey: handles.get(handle), + creator: { kind: 'terminal', handle: creator, paneKey: handles.get(creator) }, + maxDepth: 10 + }) + } + return { db, deps, run, assign } +} + +describe('public crew read and stream', () => { + it('derives direct roles and two-sided latest mail without consuming questions or leaking authority', async () => { + const { db, deps, run, assign } = fixture() + const worker = assign('term_worker') + assign('orca_session_id:chat-root', 'term_coord', 'Chat task') + const helper = assign('term_helper', 'term_worker', 'Help worker') + assign('term_grandchild', 'term_helper', 'Help helper') + const mail = db.insertMessage({ + runId: run.id, + from: 'term_worker', + to: 'term_coord', + subject: 'Update', + body: 'earlier' + }) + const newest = db.insertMessage({ + runId: run.id, + from: `run:${run.id}`, + to: `dispatch:${worker.id}`, + subject: 'Reply', + body: 'latest' + }) + db.insertMessage({ from: 'term_peer', to: 'term_coord', subject: 'Peer', body: 'inbound' }) + db.insertMessage({ from: 'term_coord', to: 'term_outbound', subject: 'Peer', body: 'outbound' }) + db.insertMessage({ + from: 'term_noise', + to: 'term_coord', + subject: 'heartbeat', + type: 'heartbeat' + }) + const asked = db.createQuestion({ + runId: run.id, + dispatchId: worker.id, + askerHandle: 'term_worker', + question: 'Which option?' + }) + const before = db.db.prepare('SELECT read FROM messages WHERE id = ?').get(mail.id) + let snapshot = buildCrewSnapshot('term_coord', deps) + expect(snapshot.sections.managing.map((row) => row.task?.title).sort()).toEqual([ + 'Chat task', + 'Implement crew' + ]) + expect(snapshot.sections.talkingWith.map((row) => row.latest?.direction).sort()).toEqual([ + 'from', + 'to' + ]) + expect( + snapshot.sections.managing.find((row) => row.sendAddress === `dispatch:${worker.id}`) + ?.pendingQuestion?.preview + ).toBe('Which option?') + expect( + snapshot.sections.managing.find((row) => row.sendAddress === `dispatch:${worker.id}`)?.latest + ?.sequence + ).toBe(asked.message.sequence) + expect( + buildCrewSnapshot('term_worker', deps).sections.managing.map((row) => row.sendAddress) + ).toEqual([`dispatch:${helper.id}`]) + expect(db.db.prepare('SELECT read FROM messages WHERE id = ?').get(mail.id)).toEqual(before) + expect(JSON.stringify(snapshot)).not.toMatch( + /structworker_|capability|paneKey|process_incarnation|launch_token/ + ) + db.answerQuestion({ + messageId: asked.message.id, + runId: run.id, + body: 'Use B', + consumerGeneration: run.consumer_generation + }) + snapshot = buildCrewSnapshot('term_coord', deps) + expect(snapshot.sections.managing.some((row) => row.pendingQuestion)).toBe(false) + expect( + snapshot.sections.managing.find((row) => row.sendAddress === `dispatch:${worker.id}`)?.latest + ?.direction + ).toBe('to') + expect(newest.sequence).toBeGreaterThan(mail.sequence) + const gate = db.createGate({ taskId: worker.task_id, question: 'Ship?' }) + db.resolveGate(gate.id, 'Yes') + expect( + buildCrewSnapshot('term_coord', deps).sections.managing.find( + (row) => row.sendAddress === `dispatch:${worker.id}` + )?.task?.state + ).toBe('ready') + }) + + it('keeps an empty subscription awake for first creation, coalesces changes and resolves cleared chat roots', async () => { + const { db, deps, assign } = fixture() + const wake = new CrewChanges() + deps.db = null + deps.retainedDbExists = false + const frames: OrchestrationCrewFrame[] = [] + const stop = subscribeCrew( + () => buildCrewSnapshot('term_coord', deps), + wake.subscribe, + (frame) => frames.push(frame) + ) + expect(frames).toEqual([{ type: 'begin', status: 'ok' }, { type: 'complete' }]) + deps.retainedDbExists = true + expect(buildCrewSnapshot('term_coord', deps).status).toBe('unknown') + deps.db = db + const unwatchDb = db.crewChanges.subscribe(wake.notify) + assign('term_worker') + await new Promise((resolve) => queueMicrotask(resolve)) + await new Promise((resolve) => queueMicrotask(resolve)) + expect(frames.filter((frame) => frame.type === 'complete')).toHaveLength(2) + expect(frames.find((frame) => frame.type === 'rows')).toMatchObject({ section: 'managing' }) + wake.notify() + await new Promise((resolve) => queueMicrotask(resolve)) + await new Promise((resolve) => queueMicrotask(resolve)) + expect(frames.filter((frame) => frame.type === 'complete')).toHaveLength(2) + stop() + unwatchDb() + const count = frames.length + wake.notify() + await Promise.resolve() + expect(frames).toHaveLength(count) + const root = agentSessionConversationView( + agentSessionRecordFixture({ + sessionId: 'chat-root', + conversationCommand: { + command: 'clear', + phase: 'committed', + replacementSessionId: 'chat-next', + operationId: 'clear-one' + } + }) + ) + const next = agentSessionConversationView( + agentSessionRecordFixture({ + sessionId: 'chat-next', + conversationName: 'Renamed', + location: { workspaceId: 'folder-custom' } + }) + ) + deps.records = { + listRecords: () => [root, next], + getRecord: (id) => (id === root.sessionId ? root : id === next.sessionId ? next : null) + } + assign('orca_session_id:chat-root') + const chat = buildCrewSnapshot('orca_session_id:chat-next', deps) + expect(chat.status).toBe('ok') + expect(chat.sections.managedBy).toHaveLength(1) + const child = buildCrewSnapshot('term_coord', deps).sections.managing.find( + (row) => row.openTarget?.kind === 'chat' + ) + expect(child?.openTarget).toEqual({ + kind: 'chat', + sessionId: 'chat-next', + worktreeId: 'folder-custom' + }) + }) +}) + +it('batches crew work as relationships scale and keeps skewed peers despite unrelated retained history', async () => { + const { db, deps, run, assign } = fixture() + for (let i = 0; i < 3; i++) { + assign(`term_extra_${i}`) + } + let dependency = false + const selection = db.listSessionDispatchesForPresentation.bind(db) + const selectionSpy = vi + .spyOn(db, 'listSessionDispatchesForPresentation') + .mockImplementation((now) => { + dependency = true + try { + return selection(now) + } finally { + dependency = false + } + }) + let queries = 0, + materialized = 0 + const prepare = db.db.prepare.bind(db.db) + const querySpy = vi.spyOn(db.db, 'prepare').mockImplementation((sql) => { + if (!dependency) { + queries++ + } + const statement = prepare(sql) + const ownRead = !dependency + return new Proxy(statement, { + get(target, key) { + const value = Reflect.get(target, key) + if (key === 'all') { + return (...args: unknown[]) => { + const rows = statement.all(...args) + if (ownRead) { + materialized += rows.length + } + return rows + } + } + return typeof value === 'function' ? value.bind(target) : value + } + }) + }) + buildCrewSnapshot('term_coord', deps) + const small = { queries, materialized } + const readCount = selectionSpy.mock.calls.length + expect(readCount).toBe(1) + const frames: OrchestrationCrewFrame[] = [] + const stop = subscribeCrew( + () => buildCrewSnapshot('term_coord', deps), + db.crewChanges.subscribe, + (frame) => frames.push(frame) + ) + for (let i = 0; i < 100; i++) { + const old = assign(`term_retained_${i}`) + db.completeDispatch(old.id) + db.db + .prepare("UPDATE dispatch_contexts SET completed_at = '2000-01-01T00:00:00Z' WHERE id = ?") + .run(old.id) + } + await new Promise((resolve) => queueMicrotask(resolve)) + await new Promise((resolve) => queueMicrotask(resolve)) + expect(frames.filter((frame) => frame.type === 'complete')).toHaveLength(1) + queries = 0 + materialized = 0 + buildCrewSnapshot('term_coord', deps) + expect({ queries, materialized }).toEqual(small) + for (let i = 3; i < 30; i++) { + assign(`term_extra_${i}`) + } + queries = 0 + materialized = 0 + const large = buildCrewSnapshot('term_coord', deps) + expect(large.sections.managing).toHaveLength(30) + expect(queries).toBe(small.queries) + expect(materialized).toBeLessThanOrEqual(small.materialized * 10) + querySpy.mockRestore() + selectionSpy.mockRestore() + for (let i = 0; i < 100; i++) { + db.insertMessage({ + from: `run:${run.id}`, + to: `term_mail_peer_${i}`, + subject: 'Outbound only', + body: String(i) + }) + } + const latest = db.insertMessage({ + from: 'term_mail_peer_0', + to: 'term_coord', + subject: 'Inbound', + body: 'highest sequence across aliases' + }) + const skewed = buildCrewSnapshot('term_coord', deps) + expect(skewed.sections.talkingWith).toHaveLength(100) + expect( + skewed.sections.talkingWith.find((row) => row.latest?.preview === latest.body)?.latest + ).toMatchObject({ sequence: latest.sequence, direction: 'from' }) + stop() + vi.restoreAllMocks() +}) diff --git a/src/main/runtime/orchestration/crew/crew-read-model.ts b/src/main/runtime/orchestration/crew/crew-read-model.ts new file mode 100644 index 000000000000..ebc5dc071ef4 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-read-model.ts @@ -0,0 +1,283 @@ +import type { AgentMessageSender } from '../../../../shared/agent-session/agent-session-message-source' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-freshness' +import { + emptyCrew, + type OrchestrationCrewSnapshot, + type OrchestrationCrewRow +} from '../../../../shared/orchestration-crew' +import { parseOrcaSessionAddress } from '../../../../shared/orca-session-address' +import type { FleetAgentStatusEvidence } from '../../../../shared/orchestration-fleet-agent-status-evidence' +import { isPublicOrchestrationAddress } from '../../../../shared/orchestration-agent-reference' +import type { OrchestrationDb } from '../db' +import { + resolveLineageRunningSession, + type AgentSessionRecordReader +} from '../structured-session-lineage' +import { crewDisplayName, creatorFirstParent, crewTaskDisplay } from './crew-rules' +import { + readCrewAssignments, + readCrewMailboxAssignments, + readCrewQuestions, + readCrewRuns, + readCrewTraffic, + readCrewSelfAssignments, + type CrewAssignmentRow +} from './crew-query' + +import { createCrewPartyRegistry, type Party } from './crew-parties' +export type CrewReadDependencies = { + db: OrchestrationDb | null + retainedDbExists: boolean + hostKey: string + records: AgentSessionRecordReader | null + liveHandle: (handle: string) => boolean + handleForPane: (pane: string) => string | null + paneForHandle: (handle: string) => string | null + name: (party: AgentMessageSender['party'], taskName: string | null) => string | null + statuses: readonly FleetAgentStatusEvidence[] + now?: number +} + +function preview(body: string): string { + const bytes = Buffer.from(body) + return bytes.length <= 1024 + ? body + : `${bytes + .subarray(0, 1021) + .toString('utf8') + .replace(/\uFFFD$/, '')}…` +} + +export function buildCrewSnapshot( + address: string, + deps: CrewReadDependencies +): OrchestrationCrewSnapshot { + const db = deps.db + if (!db) { + return emptyCrew(deps.retainedDbExists ? 'unknown' : 'ok') + } + const now = deps.now ?? Date.now() + const cutoff = new Date(now - AGENT_STATUS_STALE_AFTER_MS).toISOString() + const records = deps.records + const { party, aliases, parties } = createCrewPartyRegistry(deps) + const rawSession = parseOrcaSessionAddress(address) + let self = party( + rawSession, + rawSession ? null : address, + rawSession ? null : deps.paneForHandle(address) + ) + if (!self) { + return emptyCrew('unknown') + } + const assignments = readCrewAssignments(db, now).sort( + (a, b) => + Number(['pending', 'dispatched'].includes(b.status)) - + Number(['pending', 'dispatched'].includes(a.status)) || b.ordinal - a.ordinal + ) + const assignmentsById = new Map(assignments.map((row) => [row.id, row])) + const assignmentParty = new Map() + const addAssignment = (row: CrewAssignmentRow): Party => { + const worker = party( + row.assignee_orca_session_id, + row.assignee_handle, + row.assignee_pane_key, + `dispatch:${row.id}` + )! + assignmentParty.set(row.id, worker) + aliases.set(`dispatch:${row.id}`, worker.address) + return worker + } + for (const row of readCrewSelfAssignments(db, self)) { + addAssignment(row) + } + for (const row of assignments) { + addAssignment(row) + const coordinator = party( + row.coordinator_session, + row.coordinator_handle, + row.coordinator_pane_key + ) + if (coordinator) { + aliases.set(`run:${row.run_id}`, coordinator.address) + } + party(row.creator_orca_session_id, row.creator_handle, row.creator_pane_key) + } + self = parties.get(aliases.get(self.address) ?? self.address) ?? self + // A peer-only coordinator can have no eligible assignments in its Run. + const ownedRuns = db.db + .prepare( + `SELECT id FROM runs WHERE coordinator_handle = ? OR coordinator_pane_key = ? OR coordinator_orca_session_id = ?` + ) + .all(self.terminalHandle, self.paneKey, self.orcaSessionId) + const ownedRunAddresses = ownedRuns.flatMap((run) => + typeof run.id === 'string' ? [`run:${run.id}`] : [] + ) + for (const current of readCrewRuns(db, ownedRunAddresses)) { + const coordinator = party(current.session, current.handle, current.pane) + if (coordinator) { + aliases.set(`run:${current.id}`, coordinator.address) + } + } + const selfAliases = () => + [...aliases].filter(([, identity]) => identity === self.address).map(([alias]) => alias) + const traffic = readCrewTraffic(db, selfAliases(), cutoff) + const mailboxRows = readCrewMailboxAssignments( + db, + traffic.map((message) => message.peer) + ) + for (const row of mailboxRows) { + addAssignment(row) + } + for (const run of readCrewRuns( + db, + traffic.map((message) => message.peer) + )) { + const coordinator = party(run.session, run.handle, run.pane) + if (coordinator) { + aliases.set(`run:${run.id}`, coordinator.address) + } + } + const statuses = new Map(deps.statuses.map((status) => [status.activity.paneKey, status])) + const rows = new Map() + const decorate = ( + target: Party, + role: OrchestrationCrewRow['role'], + assignment?: CrewAssignmentRow, + sendAddress?: string + ): OrchestrationCrewRow => { + const display = crewTaskDisplay(assignment) + const evidence = target.paneKey ? statuses.get(target.paneKey) : undefined + const fresh = + evidence && now - evidence.clock.at <= AGENT_STATUS_STALE_AFTER_MS ? evidence : undefined + const title = display.taskTitle || display.displayName + const live = target.orcaSessionId + ? resolveLineageRunningSession(records, target.orcaSessionId) + : null + const row: OrchestrationCrewRow = { + partyKey: JSON.stringify([deps.hostKey, target.address]), + role, + label: crewDisplayName( + deps.name(target, display.displayName || display.taskTitle || null), + title, + 'Agent' + )!, + agentKind: + live?.kind === 'here' + ? live.record.provider + : (fresh?.activity.agentType ?? assignment?.agent ?? 'Agent'), + status: + fresh?.activity.state ?? + (assignment + ? ['pending', 'dispatched'].includes(assignment.status) + ? 'working' + : 'done' + : 'unknown'), + ...(title && assignment ? { task: { title, state: assignment.task_status } } : {}), + ...(assignment?.stage && !['accepted', 'ready'].includes(assignment.stage) + ? { progress: assignment.stage.replaceAll('_', ' ') } + : {}), + ...(assignment?.host_label ? { hostLabel: assignment.host_label } : {}), + ...(sendAddress && isPublicOrchestrationAddress(sendAddress) ? { sendAddress } : {}) + } + if (live?.kind === 'here') { + row.openTarget = { + kind: 'chat', + sessionId: live.sessionId, + worktreeId: live.record.location.workspaceId + } + } else if (target.terminalHandle) { + row.openTarget = { kind: 'terminal', handle: target.terminalHandle } + } else if (assignment && !assignment.host_label) { + row.openTarget = { kind: 'dispatch', address: `dispatch:${assignment.id}` } + } + rows.set(target.address, row) + return row + } + const snapshot = emptyCrew('ok') + const selected = new Set() + for (const assignment of assignments) { + const worker = assignmentParty.get(assignment.id)! + if (selected.has(worker.address)) { + continue + } + selected.add(worker.address) + const creator = + (assignment.creator_dispatch_id + ? assignmentParty.get(assignment.creator_dispatch_id) + : undefined) ?? + party( + assignment.creator_orca_session_id, + assignment.creator_handle, + assignment.creator_pane_key + ) + const coordinator = party( + assignment.coordinator_session, + assignment.coordinator_handle, + assignment.coordinator_pane_key + ) + const parent = creatorFirstParent( + creator?.address === worker.address ? undefined : creator, + coordinator, + coordinator?.address === worker.address + ) + if (parent?.address === self.address && worker.address !== self.address) { + snapshot.sections.managing.push( + decorate(worker, 'worker', assignment, `dispatch:${assignment.id}`) + ) + } else if (worker.address === self.address && parent && parent.address !== self.address) { + const parentAssignment = assignment.creator_dispatch_id + ? assignmentsById.get(assignment.creator_dispatch_id) + : undefined + const sendAddress = + creator?.address === parent.address + ? parentAssignment + ? `dispatch:${parentAssignment.id}` + : parent.address + : `run:${assignment.run_id}` + if (!rows.has(parent.address)) { + snapshot.sections.managedBy.push(decorate(parent, 'manager', parentAssignment, sendAddress)) + } + } + } + const questions = readCrewQuestions(db, selfAliases()) + for (const question of questions) { + const target = assignmentParty.get(question.dispatch_id) + const row = target ? rows.get(target.address) : undefined + if (row && !row.pendingQuestion) { + row.pendingQuestion = { preview: preview(question.body), at: question.created_at } + } + } + for (const message of traffic) { + let targetAddress = aliases.get(message.peer) + if (!targetAddress) { + const parsed = parseOrcaSessionAddress(message.peer) + targetAddress = party(parsed, parsed ? null : message.peer, null, message.peer)?.address + } + if (!targetAddress || targetAddress === self.address) { + continue + } + const target = parties.get(targetAddress)! + let row = rows.get(targetAddress) + if (!row) { + row = decorate( + target, + 'peer', + undefined, + target.orcaSessionId + ? target.address + : (target.terminalHandle ?? + (target.address.startsWith('dispatch:') ? target.address : undefined)) + ) + snapshot.sections.talkingWith.push(row) + } + if (!row.latest || message.sequence > row.latest.sequence) { + row.latest = { + direction: message.direction, + preview: preview(message.body), + at: message.created_at, + sequence: message.sequence + } + } + } + return snapshot +} diff --git a/src/main/runtime/orchestration/crew/crew-rules.ts b/src/main/runtime/orchestration/crew/crew-rules.ts new file mode 100644 index 000000000000..5a83ab7ee1db --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-rules.ts @@ -0,0 +1,26 @@ +import { buildOrchestrationTaskDisplayMetadata } from '../../../../shared/orchestration-task-display' +import type { TaskRow } from '../types' + +export function crewTaskDisplay( + task: Pick | undefined +) { + return typeof task?.spec === 'string' + ? buildOrchestrationTaskDisplayMetadata({ + spec: task.spec, + taskTitle: task.task_title, + displayName: task.display_name + }) + : { taskTitle: '', displayName: '' } +} + +export function creatorFirstParent( + creator: T | undefined, + coordinator: T | undefined, + coordinatorIsSelf: boolean +): T | undefined { + return creator ?? (coordinatorIsSelf ? undefined : coordinator) +} + +export function crewDisplayName(...names: (string | null | undefined)[]): string | null { + return names.find((name) => Boolean(name)) || null +} diff --git a/src/main/runtime/orchestration/crew/crew-stream.ts b/src/main/runtime/orchestration/crew/crew-stream.ts new file mode 100644 index 000000000000..0f240cadfd81 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-stream.ts @@ -0,0 +1,54 @@ +import { + emptyCrew, + type OrchestrationCrewFrame, + type OrchestrationCrewSnapshot +} from '../../../../shared/orchestration-crew' + +export function subscribeCrew( + read: () => OrchestrationCrewSnapshot, + watch: (wake: () => void) => () => void, + emit: (frame: OrchestrationCrewFrame) => void +): () => void { + let alive = true + let queued = false + let previous: string | undefined + const publish = () => { + if (!alive) { + return + } + let snapshot: OrchestrationCrewSnapshot + try { + snapshot = read() + } catch { + snapshot = emptyCrew('unknown') + } + const serialized = JSON.stringify(snapshot) + if (serialized === previous) { + return + } + previous = serialized + emit({ type: 'begin', status: snapshot.status }) + for (const section of ['managedBy', 'managing', 'talkingWith'] as const) { + for (const row of snapshot.sections[section]) { + // Previews are byte-bounded; one allow-listed row fits comfortably in one frame. + emit({ type: 'rows', section, rows: [row] }) + } + } + emit({ type: 'complete' }) + } + const unwatch = watch(() => { + if (queued) { + return + } + queued = true + queueMicrotask(() => { + queued = false + publish() + }) + }) + publish() + return () => { + alive = false + unwatch() + } +} diff --git a/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts b/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts index 2c90cab8e00e..ce36e5d55fb7 100644 --- a/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts +++ b/src/main/runtime/orchestration/db/attach-orchestration-db-methods.ts @@ -1,3 +1,4 @@ +import { attachCrewMutationNotifications } from '../crew/crew-mutation-notifications' import { attachAttemptObservationStore } from './attempt-observation-store' import { attachCoordinatorRunStore } from './coordinator-runs/coordinator-run-store' import { attachDecisionGateStore } from './decision-gates/decision-gate-store' @@ -134,4 +135,5 @@ export function attachOrchestrationDbMethods(ctor: { prototype: object }): void attachDecisionGateStore(ctor) attachCoordinatorRunStore(ctor) attachOrchestrationReset(ctor) + attachCrewMutationNotifications(ctor) } diff --git a/src/main/runtime/orchestration/db/orchestration-db.ts b/src/main/runtime/orchestration/db/orchestration-db.ts index 7d4a247c704c..7deb3a29d503 100644 --- a/src/main/runtime/orchestration/db/orchestration-db.ts +++ b/src/main/runtime/orchestration/db/orchestration-db.ts @@ -1,3 +1,4 @@ +import { CrewChanges } from '../crew/crew-changes' import Database from '../../../sqlite/sync-database' import { attachOrchestrationDbMethods } from './attach-orchestration-db-methods' import type { MailHandBack } from './messages/helper-mailbox-hand-back' @@ -19,6 +20,7 @@ import { backfillStructuredWorkerOrcaSessionIds } from './schema/structured-work import { reconcileSettledWorkerDispatches } from './worker-dispatch/worker-dispatch-settlement' class OrchestrationDbCore { + readonly crewChanges = new CrewChanges() db: Database.Database // Cache Dispatch emptiness to skip per-terminal queries on 16ms graph ticks for users without orchestration. diff --git a/src/main/runtime/orchestration/db/schema/schema-column-probes.ts b/src/main/runtime/orchestration/db/schema/schema-column-probes.ts index 7b87b5f6edd8..203bbfdb7d5c 100644 --- a/src/main/runtime/orchestration/db/schema/schema-column-probes.ts +++ b/src/main/runtime/orchestration/db/schema/schema-column-probes.ts @@ -18,6 +18,18 @@ export function createMailboxDeliveryIndexesIfPossible(this: OrchestrationDb): v if (this.hasColumn('deliveries', 'mailbox_handle')) { this.db.exec(OUTSTANDING_MAILBOX_INDEX_SQL) } + if (this.hasColumn('messages', 'created_at')) { + this.db.exec(` + CREATE INDEX IF NOT EXISTS idx_messages_crew_from + ON messages(from_handle, julianday(created_at), to_handle, sequence) WHERE type <> 'heartbeat'; + CREATE INDEX IF NOT EXISTS idx_messages_crew_to + ON messages(to_handle, julianday(created_at), from_handle, sequence) WHERE type <> 'heartbeat'; + `) + } + if (this.hasColumn('dispatch_contexts', 'completed_at')) { + this.db.exec(`CREATE INDEX IF NOT EXISTS idx_dispatch_crew_recent + ON dispatch_contexts(julianday(completed_at)) WHERE status NOT IN ('pending', 'dispatched');`) + } const hasDeliveredAt = this.hasColumn('messages', 'delivered_at') if (hasDeliveredAt) { this.db.exec(` diff --git a/src/main/runtime/orchestration/orchestration-sender-name.ts b/src/main/runtime/orchestration/orchestration-sender-name.ts index f903865c81f2..850d762fdb89 100644 --- a/src/main/runtime/orchestration/orchestration-sender-name.ts +++ b/src/main/runtime/orchestration/orchestration-sender-name.ts @@ -1,3 +1,4 @@ +import { crewDisplayName } from './crew/crew-rules' import type { AgentMessageSender } from '../../../shared/agent-session/agent-session-message-source' import { defaultAgentChatLabel } from '../../../shared/agent-session/agent-session-chat-label' import { @@ -38,7 +39,8 @@ type Party = AgentMessageSender['party'] export function orchestrationSenderName( party: Party, sources: SenderNamingSources, - reportedDispatchId?: string + reportedDispatchId?: string, + taskName?: string | null ): string | null { const federated = party.address.startsWith('dispatch:') const terminal = @@ -53,12 +55,14 @@ export function orchestrationSenderName( terminal.providerSessionId ) : null - return ( - chat?.ownName || - terminalName || - dispatchTaskName(party, federated, terminal, sources.db, reportedDispatchId) || - chat?.fallback || - (terminal?.agent ? formatAgentTypeLabel(terminal.agent) : null) + return crewDisplayName( + chat?.ownName, + terminalName, + taskName !== undefined + ? taskName + : dispatchTaskName(party, federated, terminal, sources.db, reportedDispatchId), + chat?.fallback, + terminal?.agent ? formatAgentTypeLabel(terminal.agent) : null ) } diff --git a/src/main/runtime/rpc/methods/orchestration.ts b/src/main/runtime/rpc/methods/orchestration.ts index ce98a0553266..9675a9f8490a 100644 --- a/src/main/runtime/rpc/methods/orchestration.ts +++ b/src/main/runtime/rpc/methods/orchestration.ts @@ -1,3 +1,4 @@ +import { ORCHESTRATION_CREW_METHODS } from './orchestration/crew-methods' import { ORCHESTRATION_RUN_METHODS } from './orchestration/runs/runs' import { ORCHESTRATION_WORKER_METHODS } from './orchestration/worker/worker-methods' import { ORCHESTRATION_FEDERATION_METHODS } from './orchestration/federation/federation-methods' @@ -12,6 +13,7 @@ import { ORCHESTRATION_RESET_METHODS } from './orchestration/runs/reset-methods' import { ORCHESTRATION_CALLER_METHODS } from './orchestration/caller-show' export const ORCHESTRATION_METHODS = [ + ...ORCHESTRATION_CREW_METHODS, ...ORCHESTRATION_RUN_METHODS, ...ORCHESTRATION_WORKER_METHODS, ...ORCHESTRATION_FEDERATION_METHODS, diff --git a/src/main/runtime/rpc/methods/orchestration/crew-methods.ts b/src/main/runtime/rpc/methods/orchestration/crew-methods.ts new file mode 100644 index 000000000000..d09be28a78d7 --- /dev/null +++ b/src/main/runtime/rpc/methods/orchestration/crew-methods.ts @@ -0,0 +1,51 @@ +import { z } from 'zod' +import { CrewParty } from '../../../../../shared/orchestration-crew' +import { sessionCrewChanges } from '../../../orchestration/crew/crew-changes' +import { subscribeCrew } from '../../../orchestration/crew/crew-stream' +import { defineStreamingMethod } from '../../core' + +let sequence = 0 +export const ORCHESTRATION_CREW_METHODS = [ + defineStreamingMethod({ + name: 'orchestration.crewSubscribe', + permission: 'workspace', + params: z.object({ party: CrewParty }), + handler: async ({ party }, { runtime, signal, connectionId }, emit) => { + await new Promise((resolve) => { + const key = `crew:${connectionId ?? 'local'}:${++sequence}` + const release = () => runtime.cleanupSubscription(key) + const stop = subscribeCrew( + () => runtime.getOrchestrationCrewSnapshot(party), + (wake) => { + const disposers = [ + runtime.crewChanges.subscribe(wake), + sessionCrewChanges.subscribe(wake), + runtime.agentTransitions.subscribe(wake), + runtime.onClientEvent((event) => { + if (event.type === 'terminalSideEffects' || event.type === 'workspaceViewChanged') { + wake() + } + }) + ] + return () => disposers.forEach((dispose) => dispose()) + }, + emit + ) + runtime.registerSubscriptionCleanup( + key, + () => { + stop() + signal?.removeEventListener('abort', release) + emit({ type: 'end' }) + resolve() + }, + connectionId + ) + signal?.addEventListener('abort', release, { once: true }) + if (signal?.aborted) { + release() + } + }) + } + }) +] diff --git a/src/main/runtime/runtime-agent-orchestration-projection.ts b/src/main/runtime/runtime-agent-orchestration-projection.ts index c474055c27f6..db3731fb4e51 100644 --- a/src/main/runtime/runtime-agent-orchestration-projection.ts +++ b/src/main/runtime/runtime-agent-orchestration-projection.ts @@ -1,6 +1,6 @@ import type { AgentStatusOrchestrationContext } from '../../shared/agent-status-types' import type { FleetAgentStatusEvidence } from '../../shared/orchestration-fleet-agent-status-evidence' -import { buildOrchestrationTaskDisplayMetadata } from '../../shared/orchestration-task-display' +import { creatorFirstParent, crewTaskDisplay } from './orchestration/crew/crew-rules' import { parsePaneKey } from '../../shared/stable-pane-id' import type { OrchestrationCompatibilityTerminalAuthority } from './runtime-terminal-contracts' import type { RuntimeLeafRecord, RuntimePtyWorktreeRecord } from './runtime-terminal-state-records' @@ -166,14 +166,7 @@ export class RuntimeAgentOrchestrationProjection { ): AgentStatusOrchestrationContext { const { paneKey, evidence, deferAttention = false } = options const task = scope.task(dispatch.task_id, dispatch.run_id) - const display = - typeof task?.spec === 'string' - ? buildOrchestrationTaskDisplayMetadata({ - spec: task.spec, - taskTitle: task.task_title, - displayName: task.display_name - }) - : { taskTitle: '', displayName: '' } + const display = crewTaskDisplay(task) const owningRun = task?.run_id && task.run_id === dispatch.run_id ? scope.run(dispatch.run_id) : undefined const runCoordinatorHandle = owningRun?.coordinator_handle ?? undefined @@ -265,15 +258,15 @@ export class RuntimeAgentOrchestrationProjection { coordinator.paneKey === paneKey) // Why: a creator whose pane is gone still has a coordinator to nest under. const parent = - (creator?.handle || (creatorSession && creator?.paneKey)) && - (!selfPane || creator?.paneKey !== selfPane) && - creator?.handle !== handle - ? creator - : coordinatorIsSelf - ? {} - : coordinator.paneKey === selfPane - ? {} - : coordinator + creatorFirstParent( + (creator?.handle || (creatorSession && creator?.paneKey)) && + (!selfPane || creator?.paneKey !== selfPane) && + creator?.handle !== handle + ? creator + : undefined, + coordinator, + coordinatorIsSelf || coordinator.paneKey === selfPane + ) ?? {} const attention = !deferAttention && db && typeof db.getWorkerAttentionFacts === 'function' ? buildWorkerAttentionContext({ db, dispatch, task, evidence, now: scope.now }) diff --git a/src/main/runtime/runtime-orchestration-sender-names.ts b/src/main/runtime/runtime-orchestration-sender-names.ts index 79f84a3f6c92..c410edef2c0e 100644 --- a/src/main/runtime/runtime-orchestration-sender-names.ts +++ b/src/main/runtime/runtime-orchestration-sender-names.ts @@ -75,7 +75,11 @@ export class RuntimeOrchestrationSenderNames { ) } - nameOf(party: AgentMessageSender['party'], reportedDispatchId?: string): string | null { + nameOf( + party: AgentMessageSender['party'], + reportedDispatchId?: string, + taskName?: string | null + ): string | null { return orchestrationSenderName( party, { @@ -90,7 +94,8 @@ export class RuntimeOrchestrationSenderNames { terminal: (handle) => this.terminalNaming(handle), generatedTitlesEnabled: this.deps.getGeneratedTitlesEnabled() }, - reportedDispatchId + reportedDispatchId, + taskName ) } diff --git a/src/main/runtime/session-graph/visible-graph-changed-worktrees.ts b/src/main/runtime/session-graph/visible-graph-changed-worktrees.ts new file mode 100644 index 000000000000..5488ae4f4853 --- /dev/null +++ b/src/main/runtime/session-graph/visible-graph-changed-worktrees.ts @@ -0,0 +1,39 @@ +import type { RuntimeSyncedTab } from '../../../shared/runtime-types' +import type { RuntimeLeafRecord } from '../runtime-terminal-state-records' + +export function visibleGraphChangedWorktrees( + previousTabs: Map, + previousLeaves: Map, + tabs: Map, + leaves: Map +): Set { + const changed = new Set() + for (const [tabId, tab] of tabs) { + const prev = previousTabs.get(tabId) + if (!prev || prev.title !== tab.title) { + changed.add(tab.worktreeId) + } + } + for (const [tabId, tab] of previousTabs) { + if (!tabs.has(tabId)) { + changed.add(tab.worktreeId) + } + } + for (const [leafKey, leaf] of leaves) { + const prev = previousLeaves.get(leafKey) + if ( + !prev || + prev.ptyId !== leaf.ptyId || + prev.connected !== leaf.connected || + prev.paneTitle !== leaf.paneTitle + ) { + changed.add(leaf.worktreeId) + } + } + for (const [leafKey, leaf] of previousLeaves) { + if (!leaves.has(leafKey)) { + changed.add(leaf.worktreeId) + } + } + return changed +} diff --git a/src/main/runtime/session-tabs/session-tabs-inventory.ts b/src/main/runtime/session-tabs/session-tabs-inventory.ts index 545f0188aa42..24a48b9ec932 100644 --- a/src/main/runtime/session-tabs/session-tabs-inventory.ts +++ b/src/main/runtime/session-tabs/session-tabs-inventory.ts @@ -1,3 +1,4 @@ +import { visibleGraphChangedWorktrees } from '../session-graph/visible-graph-changed-worktrees' import type { RuntimeSessionTabsInventoryPublication as SessionTabsInventoryPublicationMethods } from './session-tabs-inventory-publication' import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as ScheduleMobileSessionTabsChangedMethods } from './session-tabs-change-publication' import type { OrcaRuntimeWithResolveBrowserNetworkExecutionHostForWorktree as ResolveBrowserNetworkExecutionHostForWorktreeMethods } from '../terminal/launch/terminal-workspace-scope' @@ -145,33 +146,14 @@ export abstract class OrcaRuntimeWithCollectMobileVisibleGraphChangedWorktrees e previousTabs: Map, previousLeaves: Map ): Set { - const changed = new Set() - for (const [tabId, tab] of this.tabs) { - const prev = previousTabs.get(tabId) - if (!prev || prev.title !== tab.title) { - changed.add(tab.worktreeId) - } - } - for (const [tabId, tab] of previousTabs) { - if (!this.tabs.has(tabId)) { - changed.add(tab.worktreeId) - } - } - for (const [leafKey, leaf] of this.leaves) { - const prev = previousLeaves.get(leafKey) - if ( - !prev || - prev.ptyId !== leaf.ptyId || - prev.connected !== leaf.connected || - prev.paneTitle !== leaf.paneTitle - ) { - changed.add(leaf.worktreeId) - } - } - for (const [leafKey, leaf] of previousLeaves) { - if (!this.leaves.has(leafKey)) { - changed.add(leaf.worktreeId) - } + const changed = visibleGraphChangedWorktrees( + previousTabs, + previousLeaves, + this.tabs, + this.leaves + ) + if (changed.size > 0) { + this.crewChanges.notify() } return changed } diff --git a/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts b/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts index 3be1a12b1838..a02bc52d2dc6 100644 --- a/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts +++ b/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts @@ -1,3 +1,7 @@ +import { buildCrewSnapshot } from '../../orchestration/crew/crew-read-model' +import { getPublishedHostDescriptor } from '../../host-descriptor' +import { conversationRecordReader } from '../../orchestration/structured-session-lineage' +import { peekOpenedAgentSessionRecordStore } from '../../agent-session-record-store-slot' import type { AutomationsChangedPayload } from '../../../../shared/runtime-client-events' import type { ResolvedWorktree } from '../../runtime-worktree-path-identity' import { OrcaRuntimeWithPtyForegroundProcessReads } from '../../client/runtime-client-state' @@ -153,6 +157,7 @@ export abstract class OrcaRuntimeWithAutomationOperations extends OrcaRuntimeWit if (!this._orchestrationDb) { this._orchestrationDb = new OrchestrationDb(this.orchestrationDbPath()) this.bindMailHandBack(this._orchestrationDb) + this.bindCrewChanges(this._orchestrationDb) this.ensureOrchestrationFederationRelay() this.scheduleRestoredMessageRepoints() } @@ -175,10 +180,35 @@ export abstract class OrcaRuntimeWithAutomationOperations extends OrcaRuntimeWit this.mailPointerRepointScheduler.clear() this._orchestrationDb = db this.bindMailHandBack(db) + this.bindCrewChanges(db) this.ensureOrchestrationFederationRelay() this.scheduleRestoredMessageRepoints() } + private unwatchCrewDb: (() => void) | undefined + + private bindCrewChanges(db: OrchestrationDb): void { + this.unwatchCrewDb?.() + this.unwatchCrewDb = db.crewChanges.subscribe(this.crewChanges.notify) + this.crewChanges.notify() + } + + getOrchestrationCrewSnapshot(party: string) { + const store = peekOpenedAgentSessionRecordStore() + return buildCrewSnapshot(party, { + db: this._orchestrationDb, + retainedDbExists: existsSync(this.orchestrationDbPath()), + hostKey: getPublishedHostDescriptor(this.runtimeId)?.installationId ?? this.runtimeId, + records: store ? conversationRecordReader(store) : null, + liveHandle: (handle) => this.getTerminalWorktreeIdForHandle(handle) !== null, + handleForPane: (pane) => this.getTerminalHandleForPaneKey(pane), + paneForHandle: (handle) => this.getPaneKeyForTerminalHandle(handle), + name: (identity, taskName) => + this.orchestrationSenderNames.nameOf(identity, undefined, taskName), + statuses: this.getOrchestrationFleetAgentStatusSnapshot() + }) + } + private bindMailHandBack(db: OrchestrationDb): void { db.mailHandBackListener = (handBack) => this.offerHandedBackMail(db, handBack) } diff --git a/src/main/runtime/workspaces/workspace-process-listing.ts b/src/main/runtime/workspaces/workspace-process-listing.ts index 18158bf29ffa..87f8a60c7687 100644 --- a/src/main/runtime/workspaces/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/workspace-process-listing.ts @@ -283,6 +283,7 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends OrcaRuntimeWithWorktr onRequestFailure: (failure) => this.onStructuredRequestFailureForErrorMail(failure), // Structured chat has no CLI hooks; this projection drives first-work renaming. onSessionStatusChanged: (summary, options) => { + this.crewChanges.notify() this.onStructuredSessionStatusForMail(summary) nameChat(summary, options) void maybeAutoRenameWorkspaceOnFirstStructuredTurn( diff --git a/src/shared/orchestration-agent-reference.ts b/src/shared/orchestration-agent-reference.ts new file mode 100644 index 000000000000..de75c73bfcd7 --- /dev/null +++ b/src/shared/orchestration-agent-reference.ts @@ -0,0 +1,8 @@ +import { parseOrcaSessionAddress } from './orca-session-address' + +export function isPublicOrchestrationAddress(address: string): boolean { + return ( + /^(?:term_[a-zA-Z0-9_-]+|(?:dispatch|run):[a-zA-Z0-9_-]+)$/.test(address) || + parseOrcaSessionAddress(address) !== null + ) +} diff --git a/src/shared/orchestration-crew.ts b/src/shared/orchestration-crew.ts new file mode 100644 index 000000000000..c7390de49f86 --- /dev/null +++ b/src/shared/orchestration-crew.ts @@ -0,0 +1,55 @@ +import { z } from 'zod' +import { isPublicOrchestrationAddress } from './orchestration-agent-reference' + +export const CrewParty = z.string().refine(isPublicOrchestrationAddress) +export const CrewRow = z.object({ + partyKey: z.string(), + role: z.enum(['manager', 'worker', 'peer']), + label: z.string(), + agentKind: z.string(), + hostLabel: z.string().optional(), + status: z.string(), + task: z.object({ title: z.string(), state: z.string() }).optional(), + progress: z.string().optional(), + latest: z + .object({ + direction: z.enum(['to', 'from']), + preview: z.string(), + at: z.string(), + sequence: z.number() + }) + .optional(), + pendingQuestion: z.object({ preview: z.string(), at: z.string() }).optional(), + sendAddress: CrewParty.optional(), + openTarget: z + .discriminatedUnion('kind', [ + z.object({ kind: z.literal('chat'), sessionId: z.string(), worktreeId: z.string() }), + z.object({ kind: z.literal('terminal'), handle: z.string() }), + z.object({ kind: z.literal('dispatch'), address: z.string() }) + ]) + .optional() +}) +export type OrchestrationCrewRow = z.infer +export const CrewSnapshot = z.object({ + status: z.enum(['ok', 'unknown']), + sections: z.object({ + managedBy: z.array(CrewRow), + managing: z.array(CrewRow), + talkingWith: z.array(CrewRow) + }) +}) +export type OrchestrationCrewSnapshot = z.infer +export const CrewFrame = z.discriminatedUnion('type', [ + z.object({ type: z.literal('begin'), status: z.enum(['ok', 'unknown']) }), + z.object({ + type: z.literal('rows'), + section: z.enum(['managedBy', 'managing', 'talkingWith']), + rows: z.array(CrewRow) + }), + z.object({ type: z.literal('complete') }), + z.object({ type: z.literal('end') }) +]) +export type OrchestrationCrewFrame = z.infer +export function emptyCrew(status: 'ok' | 'unknown'): OrchestrationCrewSnapshot { + return { status, sections: { managedBy: [], managing: [], talkingWith: [] } } +} From 9cca5cfc33f918dcbb7af3607eb8f5fe25befb29 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 04:30:58 -0700 Subject: [PATCH 006/164] Batch public lineage verification after exact recency selection --- .../dispatch-predicate-visits.test-fixture.ts | 95 +++++- .../db/dispatch-context/dispatch-lookup.ts | 64 +++- ...nt-orchestration-benchmark.test-fixture.ts | 237 +++++++++++++ ...ime-agent-orchestration-projection.test.ts | 310 +++++++++--------- .../worktree-agent-live-index-patch.ts | 6 +- 5 files changed, 528 insertions(+), 184 deletions(-) create mode 100644 src/main/runtime/runtime-agent-orchestration-benchmark.test-fixture.ts diff --git a/src/main/runtime/dispatch-predicate-visits.test-fixture.ts b/src/main/runtime/dispatch-predicate-visits.test-fixture.ts index 33e9a53366c4..f7dc47f5024e 100644 --- a/src/main/runtime/dispatch-predicate-visits.test-fixture.ts +++ b/src/main/runtime/dispatch-predicate-visits.test-fixture.ts @@ -1,6 +1,8 @@ import { DatabaseSync } from 'node:sqlite' import { vi } from 'vitest' import type SyncDatabase from '../sqlite/sync-database' +import type { SqliteBindings } from '../sqlite/sqlite-statement' +import type { OrchestrationDb } from './orchestration/db' // SQL predicate visits complement range plans/probe counts; they are not total SQLite VM steps. export function installSqlVisitCounters(counters: Record number>) { @@ -25,7 +27,9 @@ export function traceDispatchPredicateVisits( functions: { candidate: string; latest?: string; observation?: string } ) { const prepare = db.prepare.bind(db) - return vi.spyOn(db, 'prepare').mockImplementation((query) => { + const executions: { query: string; parameters: SqliteBindings; rows: number }[] = [] + const observed = new WeakSet() + const trace = vi.spyOn(db, 'prepare').mockImplementation((query) => { let instrumented = query.replaceAll( 'WHERE assignee_orca_session_id IS NOT NULL', `WHERE assignee_orca_session_id IS NOT NULL AND ${functions.candidate}(rowid)` @@ -42,6 +46,93 @@ export function traceDispatchPredicateVisits( `WHERE ${functions.observation}(rowid) AND dispatch_id IN` ) } - return prepare(instrumented) + const statement = prepare(instrumented) + if (!observed.has(statement)) { + observed.add(statement) + const all = statement.all.bind(statement) + const get = statement.get.bind(statement) + vi.spyOn(statement, 'all').mockImplementation((...args) => { + const rows = all(...args) + executions.push({ query, parameters: args, rows: rows.length }) + return rows + }) + vi.spyOn(statement, 'get').mockImplementation((...args) => { + const row = get(...args) + executions.push({ query, parameters: args, rows: row ? 1 : 0 }) + return row + }) + } + return statement }) + return Object.assign(trace, { executions }) +} + +export function latestStatementMetrics( + trace: ReturnType, + native: ReturnType +) { + const latest = (query: string) => query.includes('rowid AS n FROM dispatch_contexts') + const executions = trace.executions.filter(({ query }) => latest(query)) + return { + cachedPrepareCalls: trace.mock.calls.filter(([query]) => latest(query)).length, + executedStatements: executions.length, + nativeCompilations: native.mock.calls.filter(([query]) => latest(query)).length, + addressEntries: executions.reduce((sum, { parameters }) => { + const addresses: unknown = + typeof parameters[0] === 'string' ? JSON.parse(parameters[0]) : null + if (!Array.isArray(addresses) || !addresses.every((value) => typeof value === 'string')) { + throw new Error('Expected actual JSON address batch') + } + return sum + addresses.length + }, 0), + returnedVerificationRows: executions.reduce((sum, { rows }) => sum + rows, 0) + } +} + +export function dispatchQueryPlans( + db: SyncDatabase, + trace: ReturnType +) { + const queries = new Map( + trace.executions + .filter( + ({ query }) => + query.includes('idx_dispatch_session_presentation') || + query.includes('rowid AS n FROM dispatch_contexts') + ) + .map(({ query, parameters }) => [query, parameters]) + ) + return [...queries].map(([query, parameters]) => ({ + query, + parameters, + plan: db.prepare(`EXPLAIN QUERY PLAN ${query}`).all(...parameters) + })) +} + +export function seedCoarsePresentationDispatches( + db: OrchestrationDb, + runId: string, + count: number, + now: number, + prefix = 'coarse' +) { + if (!count) { + return + } + const task = db.createTask({ runId, spec: 'coarse-only history' }) + db.db + .prepare(`INSERT INTO dispatch_contexts + (id, run_id, task_id, assignee_handle, assignee_orca_session_id, status, completed_at) + WITH RECURSIVE seq(n) AS (VALUES(1) UNION ALL SELECT n+1 FROM seq WHERE n < ?) + SELECT ? || n, ?, ?, CASE WHEN n % 2 = 1 THEN ? || n WHEN n % 4 = 0 THEN '' ELSE NULL END, + ? || n, 'completed', ? FROM seq`) + .run( + count, + `${prefix}-id-`, + runId, + task.id, + `${prefix}-handle-`, + `${prefix}-session-`, + new Date(now - 7_200_000).toISOString() + ) } diff --git a/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts b/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts index d72f8f5a9626..15bea2c788ef 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts @@ -25,6 +25,10 @@ const ACTIVE_DISPATCH_BY_PANE_SUFFIX_SQL = `SELECT ${DISPATCH_CONTEXT_COLUMN_LIS ORDER BY rowid DESC LIMIT 1` const LATEST_DISPATCH_BY_HANDLE_SQL = `SELECT ${DISPATCH_CONTEXT_COLUMN_LIST} FROM dispatch_contexts WHERE assignee_handle = ? ORDER BY rowid DESC LIMIT 1` +function presentationAddressKey(column: string, address: string | null): string { + return `${column}:${address}` +} + /** Preserve the terminal projection's exact ISO/SQLite recency contract, including future dates. */ export function isRecentPresentationDispatch(dispatch: DispatchContextRow, now: number): boolean { if (!dispatch.completed_at || dispatch.status === 'pending' || dispatch.status === 'dispatched') { @@ -70,9 +74,10 @@ export function listSessionDispatchesForPresentation( ) } } - const address = candidate.assignee_handle - ? `handle:${candidate.assignee_handle}` - : `session:${candidate.assignee_orca_session_id}` + const address = presentationAddressKey( + candidate.assignee_handle ? 'assignee_handle' : 'assignee_orca_session_id', + candidate.assignee_handle || candidate.assignee_orca_session_id + ) const previous = selected.get(address) const active = candidate.status === 'pending' || candidate.status === 'dispatched' const previousActive = previous?.status === 'pending' || previous?.status === 'dispatched' @@ -84,25 +89,50 @@ export function listSessionDispatchesForPresentation( selected.set(address, candidate) } } + const eligible = [...selected].filter( + ([, candidate]) => + candidate.status === 'pending' || + candidate.status === 'dispatched' || + isRecentPresentationDispatch(candidate, now) + ) + const latestOrderByAddress = new Map() + for (const [column, active] of [ + ['assignee_handle', true], + ['assignee_handle', false], + ['assignee_orca_session_id', false] + ] as const) { + const addresses = eligible + .filter( + ([, candidate]) => + Boolean(candidate.assignee_handle) === (column === 'assignee_handle') && + (candidate.status === 'pending' || candidate.status === 'dispatched') === active + ) + .map(([, candidate]) => candidate[column]) + if (addresses.length === 0) { + continue + } + // Batch native calls, retaining one equality-index seek per selected address. + const latest = this.db + .prepare(`SELECT requested.value AS address, (SELECT rowid AS n FROM dispatch_contexts + WHERE ${column} = requested.value + ${active ? "AND status IN ('pending', 'dispatched')" : ''} + ORDER BY rowid DESC LIMIT 1) AS n FROM json_each(?) requested`) + .all(JSON.stringify(addresses)) + for (const row of latest) { + if (typeof row.address === 'string' && typeof row.n === 'number') { + latestOrderByAddress.set(presentationAddressKey(column, row.address), row.n) + } + } + } const result: { dispatch: DispatchContextRow; order: number }[] = [] - for (const candidate of selected.values()) { + for (const [address, candidate] of eligible) { const { presentation_order, ...dispatch } = candidate const active = dispatch.status === 'pending' || dispatch.status === 'dispatched' - // SAFETY: equality-index probes return just the internal row order, or no row. const latest = active && !candidate.assignee_handle - ? { n: newestActiveOrderBySession.get(candidate.assignee_orca_session_id ?? '') } - : (this.db - .prepare(`SELECT rowid AS n FROM dispatch_contexts - WHERE ${candidate.assignee_handle ? 'assignee_handle' : 'assignee_orca_session_id'} = ? - ${active ? "AND status IN ('pending', 'dispatched')" : ''} ORDER BY rowid DESC LIMIT 1`) - .get(candidate.assignee_handle || candidate.assignee_orca_session_id) as - | { n: number } - | undefined) - if ( - latest?.n !== presentation_order || - (!active && !isRecentPresentationDispatch(dispatch, now)) - ) { + ? newestActiveOrderBySession.get(candidate.assignee_orca_session_id ?? '') + : latestOrderByAddress.get(address) + if (latest !== presentation_order) { continue } result.push({ dispatch, order: presentation_order }) diff --git a/src/main/runtime/runtime-agent-orchestration-benchmark.test-fixture.ts b/src/main/runtime/runtime-agent-orchestration-benchmark.test-fixture.ts new file mode 100644 index 000000000000..91628db3c425 --- /dev/null +++ b/src/main/runtime/runtime-agent-orchestration-benchmark.test-fixture.ts @@ -0,0 +1,237 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { execFileSync } from 'node:child_process' +import { hostname, tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, vi } from 'vitest' +import { OrchestrationDb } from './orchestration/db' +import { formatOrcaSessionAddress, type OrcaSessionId } from '../../shared/orca-session-address' +import { testOrcaSessionId } from '../../shared/orca-session-address-test-fixture' +import { + structuredAgentSessionPaneKey, + structuredAgentSessionTabId +} from '../../shared/structured-agent-session-projection' +import { + installSqlVisitCounters, + traceDispatchPredicateVisits, + latestStatementMetrics, + dispatchQueryPlans, + seedCoarsePresentationDispatches +} from './dispatch-predicate-visits.test-fixture' + +export function benchmarkPresentationCorpus( + corpus: { + nullAddress: boolean + history: number + terminalHistory: number + attentionFacts: number + parentSessionId: OrcaSessionId + }, + build: ( + db: OrchestrationDb + ) => Record | undefined +) { + const { nullAddress, history, terminalHistory, attentionFacts, parentSessionId } = corpus + const revision = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim() + const now = Date.parse('2026-10-27T12:00:00Z') + const clock = vi.spyOn(Date, 'now').mockReturnValue(now) + const directory = mkdtempSync(join(tmpdir(), 'orca-lineage-benchmark-')) + const path = join(directory, 'orchestration.sqlite') + let db = new OrchestrationDb(path) + let native: ReturnType | undefined + let trace: ReturnType | undefined + try { + const run = db.createRun({ + objective: 'benchmark', + coordinatorHandle: null, + coordinatorPaneKey: null, + coordinatorOrcaSessionId: parentSessionId + }) + const expected = new Map() + for (let i = 0; i < 20; i++) { + const session = testOrcaSessionId(`00000000-0000-4000-8000-${String(i).padStart(12, '0')}`) + const dispatch = db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'active' }).id, + assigneeHandle: formatOrcaSessionAddress(session), + creator: { kind: 'system' }, + maxDepth: 99 + }) + expected.set( + structuredAgentSessionPaneKey(structuredAgentSessionTabId(session), session), + dispatch.id + ) + } + if (nullAddress) { + db.db.exec( + "UPDATE dispatch_contexts SET assignee_handle = NULL, assignee_pane_key = NULL WHERE status = 'pending'" + ) + } + const task = db.createTask({ runId: run.id, spec: 'history' }) + const insert = db.db.prepare(`INSERT INTO dispatch_contexts + (id, run_id, task_id, assignee_handle, assignee_orca_session_id, status, completed_at) + WITH RECURSIVE seq(n) AS (VALUES(1) UNION ALL SELECT n+1 FROM seq WHERE n < ?) + SELECT ? || n, ?, ?, CASE WHEN ? THEN printf('orca_session_id:00000000-0000-4000-8000-%012d', (n-1) % 20) ELSE 'terminal-address-' || n END, + CASE WHEN ? THEN CASE WHEN ? THEN printf('00000000-0000-4000-8000-%012d', (n-1) % 20) ELSE 'session-' || n END ELSE NULL END, + 'completed', '2020-01-01T00:00:00Z' FROM seq`) + insert.run(history, 'session-history-', run.id, task.id, 1, 1, nullAddress ? 1 : 0) + if (terminalHistory) { + insert.run(terminalHistory, 'terminal-history-', run.id, task.id, 0, 0, 0) + } + const active = db.db + .prepare("SELECT id, task_id FROM dispatch_contexts WHERE status = 'pending' ORDER BY rowid") + .all() + const insertFact = db.db.prepare( + `INSERT INTO attempt_observation_facts(id, dispatch_id, task_id, sequence, authority_id, authority_clock, facet, payload, home_received_at) VALUES (?, ?, ?, ?, 'home', 'home', 'process_turn', '{"process":"running","turn":"working"}', ?)` + ) + for (let i = 0; i < attentionFacts; i++) { + const row = active[i % active.length] + if (typeof row?.id !== 'string' || typeof row.task_id !== 'string') { + throw new Error('Missing benchmark Dispatch') + } + insertFact.run( + `observation-${i}`, + row.id, + row.task_id, + Math.floor(i / active.length), + 1_800_000_000_000 + i + ) + } + const sqlite = db.db.prepare('SELECT sqlite_version() AS version').get()?.version + db.db.exec('DROP INDEX idx_dispatch_session_presentation') + const first = performance.now() + db.createMailboxDeliveryIndexesIfPossible() + const indexHelperMs = performance.now() - first + db.db.exec('DROP INDEX idx_dispatch_session_presentation') + db.close() + const openStarted = performance.now() + db = new OrchestrationDb(path) + const reopenWithIndexCreationMs = performance.now() - openStarted + let candidateVisits = 0, + latestVisits = 0, + observationVisits = 0 + native = installSqlVisitCounters({ + lineage_bench_visit: () => { + candidateVisits++ + return 1 + }, + lineage_latest_visit: () => { + latestVisits++ + return 1 + }, + lineage_observation_visit: () => { + observationVisits++ + return 1 + } + }) + trace = traceDispatchPredicateVisits(db.db, { + candidate: 'lineage_bench_visit', + latest: 'lineage_latest_visit', + observation: 'lineage_observation_visit' + }) + let plans: ReturnType | undefined + let previousCoarse = 0 + const sweep = + !nullAddress && history === 10_000 && terminalHistory === 0 && attentionFacts === 0 + for (const coarseOnly of sweep ? [0, 1_000, 10_000] : [0]) { + seedCoarsePresentationDispatches( + db, + run.id, + coarseOnly - previousCoarse, + now, + `coarse-${coarseOnly}` + ) + previousCoarse = coarseOnly + trace.mockClear() + trace.executions.length = 0 + native.mockClear() + candidateVisits = 0 + latestVisits = 0 + observationVisits = 0 + const start = performance.now() + const output = build(db) + const buildMs = performance.now() - start + const production = { + cachedPrepareCalls: trace.mock.calls.length, + executedStatements: trace.executions.length, + nativeCompilations: native.mock.calls.length, + latest: latestStatementMetrics(trace, native), + candidateVisits, + latestVisits, + observationVisits + } + expect(production.latest).toEqual({ + cachedPrepareCalls: nullAddress ? 0 : 1, + executedStatements: nullAddress ? 0 : 1, + nativeCompilations: nullAddress || coarseOnly ? 0 : 1, + addressEntries: nullAddress ? 0 : 20, + returnedVerificationRows: nullAddress ? 0 : 20 + }) + expect( + trace.executions.filter( + ({ query }) => + query.includes('rowid AS n') && + query.includes('assignee_orca_session_id') && + query.includes("AND status IN ('pending', 'dispatched')") + ) + ).toHaveLength(0) + expect(Object.keys(output ?? {}).sort()).toEqual([...expected.keys()].sort()) + for (const [key, dispatchId] of expected) { + expect(output?.[key]).toMatchObject({ + dispatchId, + parentPaneKey: structuredAgentSessionPaneKey( + structuredAgentSessionTabId(parentSessionId), + parentSessionId + ) + }) + } + expect(candidateVisits).toBe(20 + coarseOnly) + expect(latestVisits).toBe(nullAddress ? 0 : 20) + expect(observationVisits).toBe(attentionFacts) + if (!plans) { + plans = dispatchQueryPlans(db.db, trace) + } + const planText = JSON.stringify(plans) + expect(planText).not.toMatch(/SCAN dispatch_contexts|USE TEMP B-TREE/) + expect(planText).toContain('idx_dispatch_session_presentation (status=? AND completed_at>?)') + if (!nullAddress) { + expect(planText).toContain('idx_dispatch_active_assignee_handle (assignee_handle=?)') + } + console.log( + 'LINEAGE_BENCH_ENVIRONMENT_EVIDENCE', + JSON.stringify({ + host: hostname(), + node: process.version, + sqlite, + platform: process.platform, + arch: process.arch, + checkout: process.cwd(), + revision, + timingScope: 'instrumented production build; includes predicate/tracing overhead', + corpus, + coarseOnly, + Q: 20 + coarseOnly, + E: nullAddress ? 0 : 20, + B: nullAddress ? 0 : 1, + cachePhase: coarseOnly + ? 'warm statements after coarse-only inserts' + : 'first instrumented build after constructor reopen', + indexHelperMs, + reopenWithIndexCreationMs, + buildMs, + production, + diagnostic: { + cachedPrepareCalls: trace.mock.calls.length - production.cachedPrepareCalls, + executedStatements: trace.executions.length - production.executedStatements, + nativeCompilations: native.mock.calls.length - production.nativeCompilations + }, + plans + }) + ) + } + } finally { + trace?.mockRestore() + native?.mockRestore() + clock.mockRestore() + db.close() + rmSync(directory, { recursive: true, force: true }) + } +} diff --git a/src/main/runtime/runtime-agent-orchestration-projection.test.ts b/src/main/runtime/runtime-agent-orchestration-projection.test.ts index 6394f7061e99..819ce349aa04 100644 --- a/src/main/runtime/runtime-agent-orchestration-projection.test.ts +++ b/src/main/runtime/runtime-agent-orchestration-projection.test.ts @@ -1,5 +1,5 @@ import { mkdtempSync, rmSync } from 'node:fs' -import { hostname, tmpdir } from 'node:os' +import { tmpdir } from 'node:os' import { join } from 'node:path' import { seedTestAgentSessionRecordStore } from './agent-session-record-store-test-harness' import { closeTestJournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database-test-support' @@ -36,8 +36,12 @@ import { import { RuntimeAgentOrchestrationProjection } from './runtime-agent-orchestration-projection' import { installSqlVisitCounters, + latestStatementMetrics, + dispatchQueryPlans, + seedCoarsePresentationDispatches, traceDispatchPredicateVisits } from './dispatch-predicate-visits.test-fixture' +import { benchmarkPresentationCorpus } from './runtime-agent-orchestration-benchmark.test-fixture' import type { RuntimeLeafRecord } from './runtime-terminal-state-records' import { OrchestrationDb } from './orchestration/db' import { @@ -216,6 +220,8 @@ it('publishes ordinary RPC assignments without registering display authority and it.each([20, 200])( 'shares forward lineage and DB/attention work across %i workers; each build rederives facts', (n) => { + const now = Date.parse('2026-10-27T12:00:00Z') + vi.spyOn(Date, 'now').mockReturnValue(now) const db = new OrchestrationDb(':memory:') try { const run = db.createRun({ @@ -237,6 +243,15 @@ it.each([20, 200])( ) .run(`worker-${i}`, `ordinary-${i}`) } + seedCoarsePresentationDispatches(db, run.id, 2 * n, now) + const historyTask = db.createTask({ runId: run.id, spec: 'newer inactive handle history' }) + const insertHistory = db.db.prepare(`INSERT INTO dispatch_contexts + (id, run_id, task_id, assignee_handle, status, completed_at) + WITH RECURSIVE seq(n) AS (VALUES(1) UNION ALL SELECT n+1 FROM seq WHERE n < ?) + SELECT ? || n, ?, ?, ?, 'completed', '2020-01-01T00:00:00Z' FROM seq`) + for (let i = 0; i < n; i++) { + insertHistory.run(n, `expired-handled-${i}-`, run.id, historyTask.id, `ordinary-${i}`) + } let endpoint = n const read = vi.fn((id: string) => { const record = sessionRecord(id) @@ -266,7 +281,7 @@ it.each([20, 200])( const roster = vi.spyOn(db, 'listSessionDispatchesForPresentation') let candidateVisits = 0 let latestVisits = 0 - installSqlVisitCounters({ + const native = installSqlVisitCounters({ lineage_candidate_visit: () => { candidateVisits++ return 1 @@ -291,8 +306,15 @@ it.each([20, 200])( expect(tasks).toHaveBeenCalledTimes(n) expect(runs).toHaveBeenCalledTimes(1) expect(roster).toHaveBeenCalledTimes(1) - expect(candidateVisits).toBe(n) + expect(candidateVisits).toBe(3 * n) expect(latestVisits).toBe(n) + expect(latestStatementMetrics(sql, native)).toEqual({ + cachedPrepareCalls: 1, + executedStatements: 1, + nativeCompilations: 1, + addressEntries: n, + returnedVerificationRows: n + }) expect( sql.mock.calls.filter(([query]) => query.includes('d.id AS dispatch_id')) ).toHaveLength(1) @@ -309,6 +331,20 @@ it.each([20, 200])( ) ).toBe(true) expect(read.mock.calls.length).toBeLessThanOrEqual(n + endpoint + 1) + expect(latestStatementMetrics(sql, native)).toEqual({ + cachedPrepareCalls: 2, + executedStatements: 2, + nativeCompilations: 1, + addressEntries: 2 * n, + returnedVerificationRows: 2 * n + }) + expect(candidateVisits).toBe(6 * n) + expect(latestVisits).toBe(2 * n) + const plans = dispatchQueryPlans(db.db, sql) + expect(JSON.stringify(plans)).toContain( + 'idx_dispatch_active_assignee_handle (assignee_handle=?)' + ) + expect(JSON.stringify(plans)).not.toMatch(/SCAN dispatch_contexts|USE TEMP B-TREE/) for (const failure of ['missing', 'error', 'cycle', 'prepared']) { read.mockImplementation((id) => { if (failure === 'error') { @@ -337,6 +373,28 @@ it.each([20, 200])( ) ).toBe(true) } + db.db + .prepare( + "UPDATE dispatch_contexts SET status = 'completed', completed_at = ? WHERE status IN ('pending', 'dispatched')" + ) + .run(new Date(now - 7_200_000).toISOString()) + sql.mockClear() + sql.executions.length = 0 + native.mockClear() + candidateVisits = 0 + latestVisits = 0 + read.mockClear() + expect(projection.buildByPaneKey()).toBeUndefined() + expect(candidateVisits).toBe(3 * n) + expect(latestVisits).toBe(0) + expect(read).not.toHaveBeenCalled() + expect(latestStatementMetrics(sql, native)).toEqual({ + cachedPrepareCalls: 0, + executedStatements: 0, + nativeCompilations: 0, + addressEntries: 0, + returnedVerificationRows: 0 + }) } finally { db.close() } @@ -449,7 +507,7 @@ it('selects indexed active/latest per address with exact ISO/SQLite recency and }) let counter = 0 const add = ( - handle: string, + handle: string | null, session: string | null, status: string, completed: string | null @@ -469,6 +527,31 @@ it('selects indexed active/latest per address with exact ISO/SQLite recency and } add('suppressed', SESSION_X, 'completed', '2026-10-27T00:00:00Z') add('suppressed', null, 'failed', null) + add('active-hidden', 'hidden', 'pending', null) + add('active-hidden', null, 'pending', null) + add('newer-expired', 'expired-hidden', 'completed', '2026-10-27T00:00:00Z') + add('newer-expired', 'expired-hidden', 'completed', '2020-01-01T00:00:00Z') + add('newer-invalid', 'invalid-hidden', 'completed', '2026-10-27T00:00:00Z') + add('newer-invalid', 'invalid-hidden', 'completed', 'zzzz') + const unhandledRecent = add('', 'session-recent', 'completed', '2026-10-27T00:00:00Z') + const collisionHandle = add( + 'shared-address', + 'handle-namespace-session', + 'completed', + '2026-10-27T00:00:00Z' + ) + const collisionSession = add(null, 'shared-address', 'completed', '2026-10-27T00:00:00Z') + const nullRecent = add(null, 'null-recent', 'completed', '2026-10-27T00:00:00Z') + const boundary = add( + 'exact-boundary', + 'boundary', + 'completed', + new Date(now - 1_800_000).toISOString() + ) + add('stale-boundary', 'stale-boundary', 'completed', new Date(now - 1_800_001).toISOString()) + add(null, 'suppressed-session', 'completed', '2026-10-27T00:00:00Z') + add('suppressed-session-handle', 'suppressed-session', 'completed', '2026-10-27T00:00:00Z') + add('suppressed-session-handle', null, 'completed', '2026-10-27T00:00:00Z') const sqlite = add('sqlite', SESSION_Y, 'completed', '2026-10-26 23:59:59') add('expired', 'expired', 'completed', '2020-01-01T00:00:00Z') add('invalid', 'invalid', 'completed', 'zzzz') @@ -477,12 +560,65 @@ it('selects indexed active/latest per address with exact ISO/SQLite recency and const active = add('active', SESSION_Y, 'dispatched', null) add('same-address', 'active-old', 'pending', null) const newest = add('same-address', 'active-new', 'pending', null) + const native = installSqlVisitCounters({ + selection_candidate: () => 1, + selection_latest: () => 1 + }) + const trace = traceDispatchPredicateVisits(db.db, { + candidate: 'selection_candidate', + latest: 'selection_latest' + }) + expect(db.listSessionDispatchesForPresentation(now).map((row) => row.dispatch.id)).toEqual([ + active, + newest, + sqlite, + boundary, + unhandledRecent, + collisionHandle, + collisionSession, + nullRecent, + future + ]) + const metrics = latestStatementMetrics(trace, native) + expect(metrics.cachedPrepareCalls).toBe(3) + expect(metrics.executedStatements).toBe(3) + expect(metrics.nativeCompilations).toBe(3) + expect(metrics.addressEntries).toBe(metrics.returnedVerificationRows) + const latestExecutions = trace.executions.filter(({ query }) => + query.includes('rowid AS n FROM dispatch_contexts') + ) + expect(new Set(latestExecutions.map(({ query }) => query)).size).toBe(3) + expect(latestExecutions.map(({ parameters }) => JSON.parse(String(parameters[0])))).toEqual([ + ['active', 'active-hidden', 'same-address'], + [ + 'sqlite', + 'exact-boundary', + 'suppressed', + 'newer-expired', + 'shared-address', + 'suppressed-session-handle', + 'future' + ], + ['session-recent', 'shared-address', 'null-recent', 'suppressed-session'] + ]) + const plans = dispatchQueryPlans(db.db, trace) + const planText = JSON.stringify(plans) + for (const index of [ + 'idx_dispatch_active_assignee_handle (assignee_handle=?)', + 'idx_dispatch_assignee_handle (assignee_handle=?)', + 'idx_dispatch_assignee_orca_session_id (assignee_orca_session_id=?)', + 'idx_dispatch_session_presentation (status=? AND completed_at>?)' + ]) { + expect(planText).toContain(index) + } + expect(planText).not.toMatch(/SCAN dispatch_contexts|USE TEMP B-TREE/) + trace.mockRestore() + add('', 'session-recent', 'completed', 'zzzz') expect( db .listSessionDispatchesForPresentation(now) - .map((row) => row.dispatch.id) - .sort() - ).toEqual([newest, active, future, sqlite].sort()) + .some((row) => row.dispatch.id === unhandledRecent) + ).toBe(false) const noHandle = add('null-handle', 'null-address', 'dispatched', null) db.db.prepare('UPDATE dispatch_contexts SET assignee_handle = NULL WHERE id = ?').run(noHandle) expect( @@ -540,162 +676,10 @@ it.skipIf(process.env.ORCA_LINEAGE_BENCH !== '1')( for (const history of [10_000, 100_000]) { for (const terminalHistory of [0, 100_000]) { for (const attentionFacts of [0, 2_000]) { - const directory = mkdtempSync(join(tmpdir(), 'orca-lineage-benchmark-')) - const path = join(directory, 'orchestration.sqlite') - let db = new OrchestrationDb(path) - let nativePrepare: ReturnType | undefined - try { - const run = db.createRun({ - objective: 'benchmark', - coordinatorHandle: null, - coordinatorPaneKey: null, - coordinatorOrcaSessionId: SESSION_X - }) - for (let i = 0; i < 20; i++) { - db.createDispatchContext({ - taskId: db.createTask({ runId: run.id, spec: 'active' }).id, - assigneeHandle: formatOrcaSessionAddress( - testOrcaSessionId(`00000000-0000-4000-8000-${String(i).padStart(12, '0')}`) - ), - creator: { kind: 'system' }, - maxDepth: 99 - }) - } - if (nullAddress) { - db.db.exec( - "UPDATE dispatch_contexts SET assignee_handle = NULL, assignee_pane_key = NULL WHERE status = 'pending'" - ) - } - const taskId = db.createTask({ runId: run.id, spec: 'history' }).id - const insert = db.db - .prepare(`INSERT INTO dispatch_contexts(id, run_id, task_id, assignee_handle, assignee_orca_session_id, status, completed_at) - WITH RECURSIVE seq(n) AS (VALUES(1) UNION ALL SELECT n+1 FROM seq WHERE n < ?) - SELECT ? || n, ?, ?, ? || n, CASE WHEN ? THEN CASE WHEN ? THEN printf('00000000-0000-4000-8000-%012d', (n-1) % 20) ELSE 'session-' || n END ELSE NULL END, 'completed', '2020-01-01T00:00:00Z' FROM seq`) - insert.run( - history, - 'session-history-', - run.id, - taskId, - 'session-address-', - 1, - nullAddress ? 1 : 0 - ) - if (terminalHistory) { - insert.run( - terminalHistory, - 'terminal-history-', - run.id, - taskId, - 'terminal-address-', - 0, - 0 - ) - } - const active = db.db - .prepare( - "SELECT id, task_id FROM dispatch_contexts WHERE status = 'pending' ORDER BY rowid" - ) - .all() - const insertFact = db.db.prepare( - `INSERT INTO attempt_observation_facts(id, dispatch_id, task_id, sequence, authority_id, authority_clock, facet, payload, home_received_at) VALUES (?, ?, ?, ?, 'home', 'home', 'process_turn', '{"process":"running","turn":"working"}', ?)` - ) - for (let i = 0; i < attentionFacts; i++) { - const row = active[i % active.length] - if (typeof row?.id !== 'string' || typeof row.task_id !== 'string') { - throw new Error('Missing benchmark Dispatch') - } - insertFact.run( - `observation-${i}`, - row.id, - row.task_id, - Math.floor(i / active.length), - 1_800_000_000_000 + i - ) - } - db.db.exec('DROP INDEX idx_dispatch_session_presentation') - const first = performance.now() - db.createMailboxDeliveryIndexesIfPossible() - const indexHelperMs = performance.now() - first - db.db.exec('DROP INDEX idx_dispatch_session_presentation') - db.close() - const openStarted = performance.now() - db = new OrchestrationDb(path) - const reopenWithIndexCreationMs = performance.now() - openStarted - let observationVisits = 0 - let visits = 0 - nativePrepare = installSqlVisitCounters({ - lineage_observation_visit: () => { - observationVisits++ - return 1 - }, - lineage_bench_visit: () => { - visits++ - return 1 - } - }) - const trace = traceDispatchPredicateVisits(db.db, { - candidate: 'lineage_bench_visit', - observation: 'lineage_observation_visit' - }) - const start = performance.now() - const output = projectionFor(db).buildByPaneKey() - const buildMs = performance.now() - start - const productionPrepareCalls = trace.mock.calls.length - const activeSessionVerificationProbes = trace.mock.calls.filter( - ([query]) => - query.includes('rowid AS n') && - query.includes('assignee_orca_session_id') && - query.includes("AND status IN ('pending', 'dispatched')") - ).length - expect(activeSessionVerificationProbes).toBe(0) - const plans = trace.mock.calls - .filter( - ([query]) => - query.includes('idx_dispatch_session_presentation') || - query.includes('rowid AS n') - ) - .map(([query]) => - db.db - .prepare(`EXPLAIN QUERY PLAN ${query}`) - .all( - ...(query.includes('completed_at >= ?') - ? ['2026-10-26T00:00:00Z'] - : ['orca_session_id:bench-0']) - ) - ) - expect(Object.keys(output ?? {})).toHaveLength(20) - expect(visits).toBe(20) - expect(observationVisits).toBe(attentionFacts) - expect(JSON.stringify(plans)).not.toMatch(/SCAN dispatch_contexts/) - console.log( - 'LINEAGE_BENCH_ENVIRONMENT_EVIDENCE', - JSON.stringify({ - host: hostname(), - node: process.version, - platform: process.platform, - arch: process.arch, - checkout: process.cwd(), - history, - nullAddress, - terminalHistory, - attentionFacts, - observationVisits, - indexHelperMs, - reopenWithIndexCreationMs, - buildMs, - candidateVisits: visits, - productionPrepareCalls, - diagnosticPrepareCalls: trace.mock.calls.length - productionPrepareCalls, - activeSessionVerificationProbes, - plans - }) - ) - trace.mockRestore() - } finally { - nativePrepare?.mockRestore() - db.close() - rmSync(directory, { recursive: true, force: true }) - } + benchmarkPresentationCorpus( + { nullAddress, history, terminalHistory, attentionFacts, parentSessionId: SESSION_X }, + (db) => projectionFor(db).buildByPaneKey() + ) } } } diff --git a/src/renderer/src/components/sidebar/worktree-agent-live-index-patch.ts b/src/renderer/src/components/sidebar/worktree-agent-live-index-patch.ts index 9eafdf401a21..6bc041ea4774 100644 --- a/src/renderer/src/components/sidebar/worktree-agent-live-index-patch.ts +++ b/src/renderer/src/components/sidebar/worktree-agent-live-index-patch.ts @@ -1,6 +1,8 @@ import type { Tab } from '../../../../shared/tab-types' -import { parseAgentStatusPaneIdentity } from '../../../../shared/agent-status-worktree-attribution' -import { resolveAgentStatusWorktreeId } from '../../../../shared/agent-status-worktree-attribution' +import { + parseAgentStatusPaneIdentity, + resolveAgentStatusWorktreeId +} from '../../../../shared/agent-status-worktree-attribution' import type { AppState } from '@/store/types' import type { AgentStatusEntry } from '../../../../shared/agent-status-types' import { isWebTerminalSurfaceTabId } from '../../../../shared/terminal-surface-id' From 05fa4e905217c7bb1a41334c6d509f6b6fa268dd Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 04:56:44 -0700 Subject: [PATCH 007/164] Derive crew relations once per meaningful host change --- pnpm-lock.yaml | 25 + .../structured-agent-session-registry.ts | 5 + .../agent-session-record-publication.ts | 2 - .../agent-session-record-store-slot.test.ts | 25 +- .../agent-session-record-store-slot.ts | 7 + .../agent-session-store-transactions.test.ts | 90 +++- .../agent-session-store-transactions.ts | 28 + .../runtime/orca-runtime-agent-transitions.ts | 6 + .../orchestration/crew/crew-changes.ts | 27 +- .../crew/crew-cli-addresses.test.ts | 170 ++++++ .../crew/crew-host-derivation.ts | 171 ++++++ .../crew/crew-mutation-notifications.ts | 70 ++- .../orchestration/crew/crew-parties.ts | 177 +++++-- .../orchestration/crew/crew-party-snapshot.ts | 239 +++++++++ .../runtime/orchestration/crew/crew-query.ts | 101 ++-- .../crew/crew-read-model-performance.test.ts | 352 ++++++++++++ .../crew/crew-read-model.test-fixture.ts | 43 ++ .../crew/crew-read-model.test.ts | 500 +++++++++++++++--- .../orchestration/crew/crew-read-model.ts | 347 +++--------- .../orchestration/crew/crew-runtime-watch.ts | 88 +++ .../crew/crew-workspace-names.ts | 22 + .../db/schema/schema-column-probes.ts | 14 + .../rpc/methods/orchestration/crew-methods.ts | 15 +- .../runtime-orchestration-sender-names.ts | 10 +- .../automation-operations.ts | 44 +- .../session-hosts/get-runtime-id.ts | 6 + .../workspaces/workspace-process-listing.ts | 2 +- 27 files changed, 2091 insertions(+), 495 deletions(-) create mode 100644 src/main/runtime/orchestration/crew/crew-host-derivation.ts create mode 100644 src/main/runtime/orchestration/crew/crew-party-snapshot.ts create mode 100644 src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts create mode 100644 src/main/runtime/orchestration/crew/crew-read-model.test-fixture.ts create mode 100644 src/main/runtime/orchestration/crew/crew-runtime-watch.ts create mode 100644 src/main/runtime/orchestration/crew/crew-workspace-names.ts diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b5bfd4cee68d..9df280f23651 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6,6 +6,9 @@ importers: .: configDependencies: {} packageManagerDependencies: + '@pnpm/exe': + specifier: 12.14.0 + version: 12.14.0 pnpm: specifier: 12.14.0 version: 12.14.0 @@ -89,6 +92,11 @@ packages: cpu: [x64] os: [win32] + '@pnpm/exe@12.14.0': + resolution: {integrity: sha512-iZCbiKegYUapNVkZY4O8vjXt9EF/j34LbDvew6qUM5g/HrxMY38cFJaoE8+5ZWQfbt2YCsLfufI5TTh+GxUbWw==} + engines: {node: '>=18.*'} + hasBin: true + pnpm@12.14.0: resolution: {integrity: sha512-wYum2HmT09Fky16JSPMrLAbuhUSH4GzY2GeBNC+z5btGNDZwNHEehoArqpw3vqkGzhkprQjXCITJfYAd8TOJpg==} engines: {node: '>=18.*'} @@ -138,6 +146,23 @@ snapshots: '@pnpm/exe.win32-x64@12.14.0': optional: true + '@pnpm/exe@12.14.0': + optionalDependencies: + '@pnpm/exe.android-arm64': 12.14.0 + '@pnpm/exe.android-x64': 12.14.0 + '@pnpm/exe.darwin-arm64': 12.14.0 + '@pnpm/exe.darwin-x64': 12.14.0 + '@pnpm/exe.freebsd-x64': 12.14.0 + '@pnpm/exe.linux-arm64': 12.14.0 + '@pnpm/exe.linux-arm64-musl': 12.14.0 + '@pnpm/exe.linux-ppc64': 12.14.0 + '@pnpm/exe.linux-riscv64': 12.14.0 + '@pnpm/exe.linux-s390x': 12.14.0 + '@pnpm/exe.linux-x64': 12.14.0 + '@pnpm/exe.linux-x64-musl': 12.14.0 + '@pnpm/exe.win32-arm64': 12.14.0 + '@pnpm/exe.win32-x64': 12.14.0 + pnpm@12.14.0: optionalDependencies: '@pnpm/exe.android-arm64': 12.14.0 diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-registry.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-registry.ts index 62f0e336120b..f0d1ab5fc2ed 100644 --- a/src/main/native-chat/agent-session-wire/structured-agent-session-registry.ts +++ b/src/main/native-chat/agent-session-wire/structured-agent-session-registry.ts @@ -1,3 +1,4 @@ +import { sessionCrewChanges } from '../../runtime/orchestration/crew/crew-changes' import type { StructuredAgentSessionHost } from './structured-agent-session-host' let host: StructuredAgentSessionHost | null = null @@ -33,7 +34,11 @@ function publishHeld(): void { export function setStructuredAgentSessionHost(next: StructuredAgentSessionHost | null): void { stopWatchingHost?.() stopWatchingHost = null + const changed = host !== next host = next + if (changed) { + sessionCrewChanges.notify() + } try { stopWatchingHost = typeof next?.onSessionsHeld === 'function' ? next.onSessionsHeld(publishHeld) : null diff --git a/src/main/runtime/agent-session-record-publication.ts b/src/main/runtime/agent-session-record-publication.ts index 513587adc1d8..bb532bfbde4f 100644 --- a/src/main/runtime/agent-session-record-publication.ts +++ b/src/main/runtime/agent-session-record-publication.ts @@ -1,4 +1,3 @@ -import { sessionCrewChanges } from './orchestration/crew/crew-changes' import type { AgentSessionStoreState } from './agent-session-store-state' import type { AgentSessionStoreTransactions } from './agent-session-store-transactions' @@ -42,7 +41,6 @@ export abstract class AgentSessionRecordPublication { .map(([id]) => id) return applied }, options) - sessionCrewChanges.notify() for (const sessionId of proven) { this.deathEvidenceListeners.forEach((listener) => listener(sessionId)) } diff --git a/src/main/runtime/agent-session-record-store-slot.test.ts b/src/main/runtime/agent-session-record-store-slot.test.ts index 344f885f3c93..f70dcdea5cfc 100644 --- a/src/main/runtime/agent-session-record-store-slot.test.ts +++ b/src/main/runtime/agent-session-record-store-slot.test.ts @@ -1,3 +1,4 @@ +import { sessionCrewChanges } from './orchestration/crew/crew-changes' /** Early launch admission and the later chat host must share one record-store writer. */ import { mkdtemp, rm, writeFile } from 'node:fs/promises' @@ -6,7 +7,11 @@ import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { JournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database' import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/structured-agent-session-logger' -import { openAgentSessionRecordStoreOnce } from './agent-session-record-store-slot' +import { + openAgentSessionRecordStoreOnce, + peekOpenedAgentSessionRecordStore, + releaseAgentSessionRecordStore +} from './agent-session-record-store-slot' import { ensureStructuredAgentSessionHost, stopStructuredAgentSessionRuntime @@ -94,3 +99,21 @@ describe('the record store slot', () => { }) }) }) + +it('publishes source installation and release even when opening an empty record store', async () => { + const observed: unknown[] = [] + const stop = sessionCrewChanges.subscribe(() => + observed.push(peekOpenedAgentSessionRecordStore()) + ) + try { + const first = await openAgentSessionRecordStoreOnce(location()) + expect(observed).toEqual([first.store]) + await openAgentSessionRecordStoreOnce(location()) + expect(observed).toEqual([first.store]) + const released = await releaseAgentSessionRecordStore() + expect(observed).toEqual([first.store, null]) + released?.journalDatabase.close() + } finally { + stop() + } +}) diff --git a/src/main/runtime/agent-session-record-store-slot.ts b/src/main/runtime/agent-session-record-store-slot.ts index f72d4c589f2a..977904e066a1 100644 --- a/src/main/runtime/agent-session-record-store-slot.ts +++ b/src/main/runtime/agent-session-record-store-slot.ts @@ -1,3 +1,4 @@ +import { sessionCrewChanges } from './orchestration/crew/crew-changes' // Launch admission opens the single-writer store before chat-host installation; both must reuse this instance. // Quit-only edge: failed host teardown can leave its connection open after releasing the slot; a post-stop open lasts until exit. @@ -44,6 +45,9 @@ export function openAgentSessionRecordStoreOnce( opened: openRecordStore(location).then( (opened) => { slot.store = opened.store + if (opening === slot) { + sessionCrewChanges.notify() + } return opened }, (error: unknown) => { @@ -82,6 +86,9 @@ async function openRecordStore( export async function releaseAgentSessionRecordStore(): Promise { const released = opening opening = null + if (released) { + sessionCrewChanges.notify() + } return released ? released.opened.catch(() => null) : null } diff --git a/src/main/runtime/agent-session-store-transactions.test.ts b/src/main/runtime/agent-session-store-transactions.test.ts index 772e938bb468..1368c2f8a122 100644 --- a/src/main/runtime/agent-session-store-transactions.test.ts +++ b/src/main/runtime/agent-session-store-transactions.test.ts @@ -1,7 +1,13 @@ +import { sessionCrewChanges } from './orchestration/crew/crew-changes' +import { CrewReadModel, type CrewReadDependencies } from './orchestration/crew/crew-read-model' +import { subscribeCrew } from './orchestration/crew/crew-stream' +import { OrchestrationDb } from './orchestration/db' +import { conversationRecordReader } from './orchestration/structured-session-lineage' +import type { OrchestrationCrewFrame } from '../../shared/orchestration-crew' import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { AgentSessionRecord } from '../../shared/agent-session-record' import { closeTestJournalHostDatabases, @@ -243,3 +249,85 @@ describe('after the database closes', () => { expect(store.getRecord('chat-a-0001')).toBe(before) }) }) + +it.each([3, 30])( + 'keeps %i crew subscribers idle on lease-only commits and refreshes a committed name', + async (population) => { + const store = await openTestAgentSessionRecordStore(root) + const records: AgentSessionRecord[] = [] + for (let i = 0; i < population; i++) { + records.push(await liveChat(store, `chat-crew-${i}`)) + } + const db = new OrchestrationDb(':memory:') + const run = db.createRun({ + objective: 'Crew', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + }) + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'Worker' }).id, + assigneeHandle: `orca_session_id:${records[0].sessionId}`, + creator: { kind: 'system' }, + maxDepth: 10 + }) + const list = vi.spyOn(store, 'listConversations') + const dependencies = vi.fn((): CrewReadDependencies => ({ + db, + retainedDbExists: true, + hostKey: 'test', + records: conversationRecordReader(store), + statuses: [], + liveHandle: (handle) => handle === 'term_coord', + handleForPane: () => null, + paneForHandle: () => 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + name: (party, _task, captured) => + party.orcaSessionId + ? (captured?.getRecord(party.orcaSessionId)?.conversationName ?? 'Chat') + : 'Coordinator' + })) + const model = new CrewReadModel(dependencies, (wake) => { + const stops = [db.crewChanges.subscribe(wake), sessionCrewChanges.subscribe(wake)] + return () => stops.forEach((stop) => stop()) + }) + const publications = Array.from({ length: population }, () => [] as OrchestrationCrewFrame[]) + const stops = publications.map((frames, i) => + subscribeCrew( + () => model.read(i === 0 ? 'term_coord' : `orca_session_id:chat-empty-${i}`), + model.subscribe, + (frame) => frames.push(frame) + ) + ) + try { + expect(dependencies).toHaveBeenCalledTimes(1) + expect(list).toHaveBeenCalledTimes(1) + for (const record of records) { + await store.renewLease({ + sessionId: record.sessionId, + fence: record.lease.runtimeFence, + childProbe: { outcome: 'identity-matched', matchedOn: ['spawn-token'] }, + now: NOW + 10_000 + }) + } + await Promise.resolve() + await Promise.resolve() + expect(dependencies).toHaveBeenCalledTimes(1) + expect(list).toHaveBeenCalledTimes(1) + await store.setConversationName(records[0].sessionId, 'Renamed worker') + await Promise.resolve() + await Promise.resolve() + expect(dependencies).toHaveBeenCalledTimes(2) + expect(list).toHaveBeenCalledTimes(1) + expect(publications[0].filter((frame) => frame.type === 'complete')).toHaveLength(2) + expect(publications[0].findLast((frame) => frame.type === 'rows')).toMatchObject({ + rows: [{ label: 'Renamed worker' }] + }) + for (const frames of publications.slice(1)) { + expect(frames.filter((frame) => frame.type === 'complete')).toHaveLength(1) + } + } finally { + stops.forEach((stop) => stop()) + list.mockRestore() + db.close() + } + } +) diff --git a/src/main/runtime/agent-session-store-transactions.ts b/src/main/runtime/agent-session-store-transactions.ts index d9a3a0d54f8f..e3c5122835b5 100644 --- a/src/main/runtime/agent-session-store-transactions.ts +++ b/src/main/runtime/agent-session-store-transactions.ts @@ -1,3 +1,4 @@ +import { sessionCrewChanges } from './orchestration/crew/crew-changes' import type { JournalHostDatabase } from '../native-chat/agent-session-journal/journal-host-database' import type { JournalOperationReceipt } from '../native-chat/agent-session-journal/journal-row-writer' import { journalOpenRefusalError } from '../native-chat/agent-session-journal/journal-open-failure' @@ -227,6 +228,33 @@ export class AgentSessionStoreTransactions { if (writes) { freezeRows(draft, writes) this.published = draft + const topologyChanged = + writes.records.remove.length > 0 || + writes.records.upsert.some(([id]) => { + const before = published.records.get(id) + const after = draft.records.get(id) + return ( + !before || + !after || + before.provider !== after.provider || + before.location !== after.location || + before.conversationCommand !== after.conversationCommand + ) + }) + const renamed = writes.records.upsert + .filter( + ([id]) => + published.records.get(id)?.conversationName !== + draft.records.get(id)?.conversationName + ) + .map(([id]) => id) + if (topologyChanged) { + sessionCrewChanges.notify(new Set(['records'])) + } else if (renamed.length) { + sessionCrewChanges.notify( + Object.assign(new Set(['names'] as const), { recordIds: renamed }) + ) + } } } } diff --git a/src/main/runtime/orca-runtime-agent-transitions.ts b/src/main/runtime/orca-runtime-agent-transitions.ts index c94f962da5cb..b767827f07d6 100644 --- a/src/main/runtime/orca-runtime-agent-transitions.ts +++ b/src/main/runtime/orca-runtime-agent-transitions.ts @@ -72,11 +72,17 @@ export abstract class OrcaRuntimeWithAgentTransitions extends OrcaRuntimeWithMig // Attach connector watches at hook-store startup, before any connector call. this.externalConversations.current() const detachTransitions = this.agentTransitions.attach(store) + const detachCrew = store.subscribeStatusRowMutations(() => + this.crewChanges.notify(new Set(['status', 'names'])) + ) + this.crewChanges.notify(new Set(['status', 'names'])) const subscribe = store.subscribeEnrichedStatus?.bind(store) const detachTitles = subscribe ? subscribeHookStatusTitles({ subscribeEnrichedStatus: subscribe }, this) : () => {} return () => { + detachCrew() + this.crewChanges.notify(new Set(['status', 'names'])) detachTitles() detachTransitions() } diff --git a/src/main/runtime/orchestration/crew/crew-changes.ts b/src/main/runtime/orchestration/crew/crew-changes.ts index 584306f9a2ba..e799e2a89883 100644 --- a/src/main/runtime/orchestration/crew/crew-changes.ts +++ b/src/main/runtime/orchestration/crew/crew-changes.ts @@ -1,26 +1,19 @@ +export type CrewFacet = 'topology' | 'records' | 'status' | 'names' | 'traffic' +export type CrewInvalidation = ReadonlySet & { readonly recordIds?: readonly string[] } + +/** Invalidation is synchronous; the existing stream scheduler reads only after the commit. */ export class CrewChanges { - private readonly listeners = new Set<() => void>() - private queued = false + private readonly listeners = new Set<(facets: CrewInvalidation) => void>() - subscribe = (listener: () => void): (() => void) => { + subscribe = (listener: (facets: CrewInvalidation) => void): (() => void) => { this.listeners.add(listener) - return () => { - this.listeners.delete(listener) - } + return () => this.listeners.delete(listener) } - notify = (): void => { - if (this.queued || this.listeners.size === 0) { - return + notify = (facets: CrewInvalidation = new Set(['topology'])): void => { + for (const listener of this.listeners) { + listener(facets) } - this.queued = true - // Database mutations are synchronous; readers run after their outer transaction finishes. - queueMicrotask(() => { - this.queued = false - for (const listener of this.listeners) { - listener() - } - }) } } diff --git a/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts b/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts index da6130ad4b1c..b085b9e3ca5a 100644 --- a/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts +++ b/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts @@ -1,3 +1,5 @@ +import type { RuntimeStore } from '../../runtime-store-contract' +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' import '../../rpc/unused-default-rpc-methods.test-fixture' import { afterEach, expect, it, vi } from 'vitest' import { z } from 'zod' @@ -181,3 +183,171 @@ it('executes snapshot addresses through CLI send and the dispatcher into the pro h.close() } }) + +it('keeps crew as the only observer for title, settings and mirrored-name source changes', async () => { + const { OrcaRuntimeService } = await import('../../orca-runtime') + const { partialRuntimeStore } = await import('../../runtime-store-partial-fixture') + const { getDefaultWorkspaceSession } = await import('../../../../shared/constants') + const { makeTerminalTab } = await import('../../../persistence/persistence-session-fixtures') + const settingsListeners = new Set>[0]>() + const sessionListeners = new Set< + Parameters>[0] + >() + const worktreeId = 'repo-1::/workspace' + let session = { + ...getDefaultWorkspaceSession(), + tabsByWorktree: { + [worktreeId]: [ + makeTerminalTab({ + id: 'tab_worker', + worktreeId, + title: 'Initial worker', + customTitle: 'Initial worker' + }) + ] + } + } + let generated = true + const store = partialRuntimeStore({ + getSettings: () => ({ tabAutoGenerateTitle: generated }), + getWorkspaceSession: () => session, + getWorkspaceSessionHostIds: () => ['local'], + onSettingsChanged: (listener) => { + settingsListeners.add(listener) + return () => settingsListeners.delete(listener) + }, + onWorkspaceSessionWritten: (listener) => { + sessionListeners.add(listener) + return () => sessionListeners.delete(listener) + } + }) + const runtime = new OrcaRuntimeService(store) + const { OrchestrationDb } = await import('../db') + const { subscribeCrew } = await import('./crew-stream') + const db = new OrchestrationDb(':memory:') + runtime.setOrchestrationDb(db) + const workerPane = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + const coordinatorPane = 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + runtime.registerPty('pty_worker', worktreeId, null, { + tabId: 'tab_worker', + leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + }) + runtime.registerPty('pty_coord', worktreeId, null, { + tabId: 'tab_coord', + leafId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + }) + runtime.attachWindow(1) + runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab_worker', + worktreeId, + title: 'Initial worker', + activeLeafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', + layout: null + }, + { + tabId: 'tab_coord', + worktreeId, + title: 'Coordinator', + activeLeafId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + layout: null + } + ], + leaves: [ + { + tabId: 'tab_worker', + worktreeId, + leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', + paneRuntimeId: 1, + ptyId: 'pty_worker' + }, + { + tabId: 'tab_coord', + worktreeId, + leafId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + paneRuntimeId: 1, + ptyId: 'pty_coord' + } + ] + }) + const workerHandle = runtime.getTerminalHandleForPaneKey(workerPane)! + const coordinatorHandle = runtime.getTerminalHandleForPaneKey(coordinatorPane)! + const run = db.createRun({ + objective: 'Observed names', + coordinatorHandle, + coordinatorPaneKey: coordinatorPane + }) + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'Worker' }).id, + assigneeHandle: workerHandle, + assigneePaneKey: workerPane, + creator: { kind: 'system' }, + maxDepth: 10 + }) + const names = vi.spyOn(runtime.orchestrationSenderNames, 'nameOf') + const selection = vi.spyOn(db, 'listSessionDispatchesForPresentation') + const frames: unknown[] = [] + const stop = subscribeCrew( + () => runtime.getOrchestrationCrewSnapshot(coordinatorHandle), + runtime.watchOrchestrationCrew, + (frame) => frames.push(frame) + ) + try { + expect(runtime.getOrchestrationCrewSnapshot(coordinatorHandle).sections.managing[0].label).toBe( + 'Initial worker' + ) + selection.mockClear() + names.mockClear() + // RuntimeClientEventBus is the real production filter. Crew is its only enrolled consumer. + // SAFETY: the protected method is this class's client-event publication boundary, exercised without OS input. + const events = runtime as unknown as { + emitClientEvent(event: RuntimeClientEvent): void + } + events.emitClientEvent({ + type: 'terminalSideEffects', + batch: { ptyId: 'pty', seq: 1, facts: [{ kind: 'bell' }] } + }) + await Promise.resolve() + expect(selection).not.toHaveBeenCalled() + expect(names).not.toHaveBeenCalled() + events.emitClientEvent({ + type: 'terminalSideEffects', + batch: { + ptyId: 'pty', + seq: 2, + facts: [{ kind: 'title', rawTitle: 'Working', normalizedTitle: 'Working' }] + } + }) + generated = false + for (const listener of settingsListeners) { + listener({ tabAutoGenerateTitle: false }, store.getSettings()) + } + session = { + ...session, + tabsByWorktree: { + [worktreeId]: [ + makeTerminalTab({ + id: 'tab_worker', + worktreeId, + title: 'Renamed tab', + customTitle: 'Renamed tab' + }) + ] + } + } + for (const listener of sessionListeners) { + listener('local') + } + await Promise.resolve() + expect(selection).not.toHaveBeenCalled() + expect(names).toHaveBeenCalledTimes(1) + expect(runtime.getOrchestrationCrewSnapshot(coordinatorHandle).sections.managing[0].label).toBe( + 'Renamed tab' + ) + expect(frames).toHaveLength(6) + } finally { + stop() + db.close() + } +}) diff --git a/src/main/runtime/orchestration/crew/crew-host-derivation.ts b/src/main/runtime/orchestration/crew/crew-host-derivation.ts new file mode 100644 index 000000000000..1145fc4e8001 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-host-derivation.ts @@ -0,0 +1,171 @@ +import type { FleetDurableWorker } from '../../../../shared/orchestration-fleet-projection' +import { createFleetStatusIndex } from '../../../../shared/orchestration-fleet-status-index' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-freshness' +import { creatorFirstParent } from './crew-rules' +import { createCrewPartyRegistry, type Party } from './crew-parties' +import { readCrewAssignments, type CrewAssignmentRow } from './crew-query' +import type { CrewReadDependencies } from './crew-read-model' + +export function createCrewHostDerivation(deps: CrewReadDependencies, now: number) { + const { statuses, ...sources } = deps + const registry = createCrewPartyRegistry({ ...sources, statuses }) + const { party, alias } = registry + const selected = (rows: CrewAssignmentRow[]) => + rows.sort( + (a, b) => + Number(['pending', 'dispatched'].includes(b.status)) - + Number(['pending', 'dispatched'].includes(a.status)) || b.ordinal - a.ordinal + ) + const assignments = deps.db ? [...selected(readCrewAssignments(deps.db, now))] : [] + const assignmentsById = new Map(assignments.map((row) => [row.id, row])) + const assignmentParty = new Map() + const addAssignment = (row: CrewAssignmentRow): Party => { + const worker = party( + row.assignee_orca_session_id, + row.assignee_handle, + row.assignee_pane_key, + `dispatch:${row.id}` + )! + assignmentParty.set(row.id, worker) + alias(`dispatch:${row.id}`, worker.address) + return worker + } + const coordinator = (row: CrewAssignmentRow) => + party( + row.coordinator_session, + row.coordinator_handle, + row.coordinator_pane_key, + `run:${row.run_id}` + ) + for (const row of assignments) { + addAssignment(row) + const manager = coordinator(row) + if (manager) { + alias(`run:${row.run_id}`, manager.address) + } + party(row.creator_orca_session_id, row.creator_handle, row.creator_pane_key) + } + const relations = new Map< + string, + { + assignment: CrewAssignmentRow + worker: Party + parent: Party + parentAssignment: CrewAssignmentRow | undefined + parentAddress: string + }[] + >() + const selectedWorkers = new Set() + for (const assignment of assignments) { + const worker = assignmentParty.get(assignment.id)! + if (selectedWorkers.has(worker.address)) { + continue + } + selectedWorkers.add(worker.address) + const creator = + (assignment.creator_dispatch_id + ? assignmentParty.get(assignment.creator_dispatch_id) + : undefined) ?? + party( + assignment.creator_orca_session_id, + assignment.creator_handle, + assignment.creator_pane_key + ) + const manager = coordinator(assignment) + const parent = creatorFirstParent( + creator?.address === worker.address ? undefined : creator, + manager, + manager?.address === worker.address + ) + if (!parent || parent.address === worker.address) { + continue + } + const parentAssignment = assignment.creator_dispatch_id + ? assignmentsById.get(assignment.creator_dispatch_id) + : undefined + const relation = { + assignment, + worker, + parent, + parentAssignment, + parentAddress: + creator?.address === parent.address + ? parentAssignment + ? `dispatch:${parentAssignment.id}` + : parent.address + : `run:${assignment.run_id}` + } + for (const address of [worker.address, parent.address]) { + const edges = relations.get(address) ?? [] + edges.push(relation) + relations.set(address, edges) + } + } + const workers: FleetDurableWorker[] = assignments.map((row) => ({ + dispatchId: row.id, + taskId: row.task_id, + runId: row.run_id, + parentTaskId: null, + workerState: 'unsupervised', + dispatchStatus: row.status, + workerStage: row.stage, + agentTerminalHandle: row.assignee_handle, + paneKey: row.assignee_pane_key, + worktreeId: null, + terminalState: null, + resource: row.resource_incarnation + ? { + id: row.id, + ownerDispatchId: row.id, + worktreeId: null, + paneKey: row.assignee_pane_key, + processIncarnation: row.resource_incarnation, + hostScope: row.resource_host_scope, + ownershipState: 'owned', + releaseState: 'live', + updatedAt: '' + } + : null + })) + let expiresAt = Infinity + for (const row of assignments) { + if (row.completed_at) { + const completed = Date.parse( + row.completed_at.includes('T') ? row.completed_at : `${row.completed_at.replace(' ', 'T')}Z` + ) + if (Number.isFinite(completed)) { + expiresAt = Math.min(expiresAt, completed + AGENT_STATUS_STALE_AFTER_MS + 1) + } + } + } + return refreshCrewStatuses( + { + registry, + deps: { ...sources, statuses, records: registry.records }, + now, + expiresAt, + relations, + workersById: new Map(workers.map((worker) => [worker.dispatchId, worker])) + }, + statuses + ) +} + +export function refreshCrewStatuses< + T extends { + deps: CrewReadDependencies + workersById: Map + } +>(host: T, statuses: CrewReadDependencies['statuses']) { + const statusIndex = createFleetStatusIndex(statuses, [...host.workersById.values()]) + const statusesByPane = new Map() + for (const status of statuses) { + const prior = statusesByPane.get(status.activity.paneKey) + if (!prior || status.deliveredAt > prior.deliveredAt) { + statusesByPane.set(status.activity.paneKey, status) + } + } + return { ...host, deps: { ...host.deps, statuses }, statusIndex, statusesByPane } +} + +export type CrewHostDerivation = ReturnType diff --git a/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts b/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts index ebad9003de75..8df3744bd3b7 100644 --- a/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts +++ b/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts @@ -1,8 +1,26 @@ import type { OrchestrationDb } from '../db' const mutations = [ - 'insertMessage', - 'insertMessages', + 'createRemoteDispatchAttachment', + 'prepareRemoteAttachmentAuthority', + 'markRemoteAttachmentReady', + 'recordRemoteAttachmentStage', + 'settleRemoteAttachmentInRelayTransaction', + 'updateRemoteAttachmentSetupEvidence', + 'failRemoteAttachment', + 'beginRemoteAttachmentStop', + 'settleRemoteAttachmentStop', + 'markRemoteAttachmentStopUnknown', + 'requestRemoteAttachmentTerminalRelease', + 'routeDirectMessagePage', + 'routeUnreadDispatchMailboxToRunMailbox', + 'routeForeignDirectMessagesToOwnedMailboxes', + 'registerFederatedQuestion', + 'answerRemoteQuestion', + 'convertLifecycleMessageToRejection', + 'createWorkerTerminalResourceStatement', + 'transferWorkerTerminalResourceStatement', + 'rekeyWorkerTerminalResourcePaneKey', 'createDispatchContext', 'createStartingWorkerDispatch', 'prepareStartingWorkerAuthority', @@ -13,6 +31,11 @@ const mutations = [ 'failActiveDispatchForTask', 'failDispatch', 'settleWorkerReport', + 'settleWorkerReportInTransaction', + 'importFederatedRelayItem', + 'reconcileFederatedWorkerStart', + 'reconcileMissingWorkerTerminal', + 'promoteReadyTasks', 'bindRun', 'createRun', 'createQuestion', @@ -38,10 +61,36 @@ const mutations = [ 'resetMessages' ] as const satisfies readonly (keyof OrchestrationDb)[] +const trafficMutations: ReadonlySet = new Set([ + 'routeDirectMessagePage', + 'routeUnreadDispatchMailboxToRunMailbox', + 'routeForeignDirectMessagesToOwnedMailboxes', + 'registerFederatedQuestion', + 'answerRemoteQuestion', + 'convertLifecycleMessageToRejection', + 'createQuestion', + 'answerQuestion', + 'closeQuestionsForDispatch', + 'createGate', + 'resolveGate', + 'timeoutGate', + 'resetMessages' +]) + /** Wake after the synchronous outer mutation; nested writes coalesce and rolled-back reads compare equal. */ export function attachCrewMutationNotifications(ctor: { prototype: object }): void { + // SAFETY: the database installer invokes this after installing the domain methods. + const prototype = ctor.prototype as OrchestrationDb + const insert = prototype.insertMessage + prototype.insertMessage = function (message) { + const result = insert.call(this, message) + if (result.type !== 'heartbeat') { + this.crewChanges.notify(new Set(['traffic'])) + } + return result + } for (const name of mutations) { - const original: unknown = Reflect.get(ctor.prototype, name) + const original = prototype[name] if (typeof original !== 'function') { continue } @@ -49,8 +98,19 @@ export function attachCrewMutationNotifications(ctor: { prototype: object }): vo configurable: true, writable: true, value(this: OrchestrationDb, ...args: unknown[]) { - const result: unknown = original.apply(this, args) - this.crewChanges.notify() + const invoke: (...values: never[]) => unknown = original + // SAFETY: the wrapper forwards the unmodified arguments to the selected domain method. + const result = invoke.apply(this, args as never[]) + if ( + typeof result === 'object' && + result !== null && + 'types' in result && + Array.isArray(result.types) && + result.types.every((type) => type === 'heartbeat') + ) { + return result + } + this.crewChanges.notify(new Set([trafficMutations.has(name) ? 'traffic' : 'topology'])) return result } }) diff --git a/src/main/runtime/orchestration/crew/crew-parties.ts b/src/main/runtime/orchestration/crew/crew-parties.ts index 7cfa6a3eb738..86203f187c86 100644 --- a/src/main/runtime/orchestration/crew/crew-parties.ts +++ b/src/main/runtime/orchestration/crew/crew-parties.ts @@ -6,63 +6,146 @@ import { } from '../../../../shared/orca-session-address' import { isPublicOrchestrationAddress } from '../../../../shared/orchestration-agent-reference' import { createCanonicalSessionPaneResolver } from '../structured-session-lineage' -import { createCanonicalOrcaSessionResolver } from '../canonical-orca-session-id' +import { clearedInto } from '../structured-session-lineage' import type { CrewReadDependencies } from './crew-read-model' export type Party = AgentMessageSender['party'] & { paneKey: string | null } export function createCrewPartyRegistry(deps: CrewReadDependencies) { - const recordList = deps.records?.listRecords() ?? [] - const resolveRoot = createCanonicalOrcaSessionResolver({ listRecords: () => recordList }) - const rootCache = new Map() - const root = (id: string): string => { - let value = rootCache.get(id) - if (!value) { - value = isOrcaSessionId(id) ? resolveRoot(id) : id - rootCache.set(id, value) + const recordList = structuredClone(deps.records?.listRecords() ?? []) + const recordMap = new Map(recordList.map((record) => [record.sessionId, record])) + const adjacent = new Map>() + const incoming = new Map() + for (const record of recordList) { + const next = clearedInto(record) + if (!next) { + continue + } + incoming.set(next, (incoming.get(next) ?? 0) + 1) + for (const [from, to] of [ + [record.sessionId, next], + [next, record.sessionId] + ]) { + const neighbors = adjacent.get(from) ?? new Set() + neighbors.add(to) + adjacent.set(from, neighbors) } - return value } - const canonicalPane = createCanonicalSessionPaneResolver(deps.records) - const parties = new Map() - const aliases = new Map() - const party = ( - session: string | null, - storedHandle: string | null, - pane: string | null, - fallback?: string - ): Party | undefined => { - const sessionId = session ? root(session) : null - const liveHandle = pane ? deps.handleForPane(pane) : null - const handle = - liveHandle ?? (storedHandle && deps.liveHandle(storedHandle) ? storedHandle : null) - const publicHandle = handle?.startsWith('term_') ? handle : null - const publicAddress = - sessionId && isOrcaSessionId(sessionId) - ? formatOrcaSessionAddress(sessionId) - : ((publicHandle && aliases.get(publicHandle)) ?? publicHandle ?? fallback) - if (!publicAddress || !isPublicOrchestrationAddress(publicAddress)) { - return undefined + const roots = new Map() + const lineageAliases = new Map() + for (const record of recordList) { + if (roots.has(record.sessionId)) { + continue } - const existing = parties.get(publicAddress) - const value = existing ?? { - address: publicAddress, - terminalHandle: publicHandle, - orcaSessionId: parseOrcaSessionAddress(publicAddress), - paneKey: sessionId ? canonicalPane(sessionId) : pane + const component = new Set([record.sessionId]) + for (const id of component) { + for (const peer of adjacent.get(id) ?? []) { + component.add(peer) + } } - parties.set(publicAddress, value) - for (const alias of [ - publicAddress, - storedHandle, - handle, - session && isOrcaSessionId(session) ? formatOrcaSessionAddress(session) : null - ]) { - if (alias) { - aliases.set(alias, publicAddress) + const heads = [...component].filter((id) => !incoming.has(id)) + const valid = + heads.length === 1 && + [...component].every((id) => recordMap.has(id) && (incoming.get(id) ?? 0) <= 1) + // Corrupt or incomplete chains retain their own identity; traversal order cannot merge them. + for (const id of component) { + roots.set(id, valid ? heads[0] : id) + } + if (valid) { + lineageAliases.set(heads[0], [...component].sort().map(formatOrcaSessionAddress)) + } + } + const root = (id: string) => roots.get(id) ?? id + const records = deps.records + ? { + ...deps.records, + listRecords: () => recordList, + getRecord: (id: string) => recordMap.get(id) ?? null + } + : null + const canonicalPane = createCanonicalSessionPaneResolver(records) + const build = (base?: CrewPartyLookup) => { + const parties = new Map() + const aliases = new Map() + const aliasesByParty = new Map>() + const alias = (address: string, identity: string) => { + const previous = aliases.get(address) ?? base?.addressOf(address) + if (previous === identity || base?.addressOf(address) || (previous && previous !== address)) { + return + } + if (previous) { + aliasesByParty.get(previous)?.delete(address) } + aliases.set(address, identity) + const members = aliasesByParty.get(identity) ?? new Set() + members.add(address) + aliasesByParty.set(identity, members) + } + const party = ( + session: string | null, + storedHandle: string | null, + pane: string | null, + fallback?: string + ): Party | undefined => { + const sessionId = session ? root(session) : null + const liveHandle = pane ? deps.handleForPane(pane) : null + const handle = + liveHandle ?? (storedHandle && deps.liveHandle(storedHandle) ? storedHandle : null) + const publicHandle = handle?.startsWith('term_') ? handle : null + const publicAddress = + sessionId && isOrcaSessionId(sessionId) + ? formatOrcaSessionAddress(sessionId) + : ((publicHandle && (aliases.get(publicHandle) ?? base?.addressOf(publicHandle))) ?? + publicHandle ?? + fallback) + if (!publicAddress || !isPublicOrchestrationAddress(publicAddress)) { + return undefined + } + const existing = parties.get(publicAddress) ?? base?.getParty(publicAddress) + const value = existing ?? { + address: publicAddress, + terminalHandle: publicHandle, + orcaSessionId: parseOrcaSessionAddress(publicAddress), + paneKey: sessionId ? canonicalPane(sessionId) : pane + } + parties.set(publicAddress, value) + const registerAlias = alias + for (const alias of [ + publicAddress, + ...(sessionId ? (lineageAliases.get(sessionId) ?? []) : []), + storedHandle, + handle, + session && isOrcaSessionId(session) ? formatOrcaSessionAddress(session) : null + ]) { + if (alias) { + registerAlias(alias, publicAddress) + } + } + return value + } + const lookup: CrewPartyLookup = { + addressOf: (address) => aliases.get(address) ?? base?.addressOf(address), + getParty: (address) => parties.get(address) ?? base?.getParty(address), + aliasesFor: (address) => [ + ...new Set([...(base?.aliasesFor(address) ?? []), ...(aliasesByParty.get(address) ?? [])]) + ] + } + return { + ...lookup, + parties, + aliases, + aliasesByParty, + alias, + party, + records, + fork: () => build(lookup) } - return value } - return { parties, aliases, party } + return build() +} + +export type CrewPartyLookup = { + addressOf: (address: string) => string | undefined + getParty: (address: string) => Party | undefined + aliasesFor: (address: string) => string[] } diff --git a/src/main/runtime/orchestration/crew/crew-party-snapshot.ts b/src/main/runtime/orchestration/crew/crew-party-snapshot.ts new file mode 100644 index 000000000000..afc2bb8b8364 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-party-snapshot.ts @@ -0,0 +1,239 @@ +import type { AgentMessageSender } from '../../../../shared/agent-session/agent-session-message-source' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-freshness' +import { + emptyCrew, + type OrchestrationCrewSnapshot, + type OrchestrationCrewRow +} from '../../../../shared/orchestration-crew' +import { parseOrcaSessionAddress } from '../../../../shared/orca-session-address' +import type { FleetAgentStatusEvidence } from '../../../../shared/orchestration-fleet-agent-status-evidence' +import { isPublicOrchestrationAddress } from '../../../../shared/orchestration-agent-reference' +import type { OrchestrationDb } from '../db' +import { + resolveLineageRunningSession, + type AgentSessionRecordReader +} from '../structured-session-lineage' +import { crewDisplayName, crewTaskDisplay } from './crew-rules' +import { + readCrewProvenance, + readCrewOwnedRunAddresses, + readCrewQuestions, + readCrewRuns, + readCrewTraffic, + type CrewAssignmentRow +} from './crew-query' + +import type { Party } from './crew-parties' +import { createCrewHostDerivation } from './crew-host-derivation' +import { statusForFleetWorker } from '../../../../shared/orchestration-fleet-status-index' +import { projectLiveness } from '../../../../shared/orchestration-fleet-worker-projection' +export type CrewReadDependencies = { + db: OrchestrationDb | null + retainedDbExists: boolean + hostKey: string + records: AgentSessionRecordReader | null + liveHandle: (handle: string) => boolean + handleForPane: (pane: string) => string | null + paneForHandle: (handle: string) => string | null + name: ( + party: AgentMessageSender['party'], + taskName: string | null, + records: AgentSessionRecordReader | null + ) => string | null + statuses: readonly FleetAgentStatusEvidence[] + now?: number +} + +function preview(body: string): string { + const bytes = Buffer.from(body) + return bytes.length <= 1024 + ? body + : `${bytes + .subarray(0, 1021) + .toString('utf8') + .replace(/\uFFFD$/, '')}…` +} + +export function buildCrewSnapshot( + address: string, + deps: CrewReadDependencies, + host = createCrewHostDerivation(deps, deps.now ?? Date.now()) +): OrchestrationCrewSnapshot { + const db = deps.db + if (!db) { + return emptyCrew(deps.retainedDbExists ? 'unknown' : 'ok') + } + const now = deps.now ?? Date.now() + const cutoff = new Date(now - AGENT_STATUS_STALE_AFTER_MS).toISOString() + const registry = host.registry.fork() + const { party, alias, addressOf, getParty, aliasesFor } = registry + const records = host.deps.records + const hydrate = (addresses: string[], panes: string[] = []) => { + const provenance = readCrewProvenance(db, addresses, panes) + for (const family of [provenance.local, provenance.remote]) { + for (const row of family) { + const worker = party(row.session, row.handle, row.pane, `dispatch:${row.id}`) + if (worker) { + alias(`dispatch:${row.id}`, worker.address) + } + } + } + } + const rawSession = parseOrcaSessionAddress(address) + let self = party( + rawSession, + rawSession ? null : address, + rawSession ? null : deps.paneForHandle(address), + address + ) + if (!self) { + return emptyCrew('unknown') + } + hydrate(aliasesFor(self.address), self.paneKey ? [self.paneKey] : []) + self = getParty(addressOf(self.address) ?? self.address) ?? self + const ownedRunAddresses = readCrewOwnedRunAddresses(db, self) + for (const current of readCrewRuns(db, ownedRunAddresses)) { + const coordinator = party(current.session, current.handle, current.pane, `run:${current.id}`) + if (coordinator) { + alias(`run:${current.id}`, coordinator.address) + } + } + const selfAliases = () => aliasesFor(self.address) + const traffic = readCrewTraffic(db, selfAliases(), cutoff) + hydrate(traffic.map((message) => message.peer)) + for (const run of readCrewRuns( + db, + traffic.map((message) => message.peer) + )) { + const coordinator = party(run.session, run.handle, run.pane, `run:${run.id}`) + if (coordinator) { + alias(`run:${run.id}`, coordinator.address) + } + } + const rows = new Map() + const decorate = ( + target: Party, + role: OrchestrationCrewRow['role'], + assignment?: CrewAssignmentRow, + sendAddress?: string + ): OrchestrationCrewRow => { + const display = crewTaskDisplay(assignment) + const title = display.taskTitle || display.displayName + const live = target.orcaSessionId + ? resolveLineageRunningSession(records, target.orcaSessionId) + : null + const worker = assignment ? host.workersById.get(assignment.id) : undefined + const evidence = + worker && !target.orcaSessionId + ? statusForFleetWorker(worker, host.statusIndex) + : target.paneKey + ? host.statusesByPane.get(target.paneKey) + : undefined + const bound = + evidence && + (live?.kind === 'here' || + Boolean(worker) || + (evidence.binding.kind !== 'unresolved' && + evidence.binding.terminalHandle === target.terminalHandle && + evidence.binding.paneKey === target.paneKey && + (evidence.binding.kind !== 'worker' || evidence.binding.dispatchId === assignment?.id))) + const fresh = + bound && projectLiveness({ resource: null }, evidence, now).verdict === 'live' + ? evidence + : undefined + const row: OrchestrationCrewRow = { + partyKey: JSON.stringify([deps.hostKey, target.address]), + role, + label: crewDisplayName( + deps.name(target, display.displayName || display.taskTitle || null, records), + title, + 'Agent' + )!, + agentKind: + live?.kind === 'here' + ? live.record.provider + : (fresh?.activity.agentType ?? assignment?.agent ?? 'Agent'), + status: + fresh?.activity.state ?? + (assignment + ? ['pending', 'dispatched'].includes(assignment.status) + ? 'working' + : 'done' + : 'unknown'), + ...(title && assignment ? { task: { title, state: assignment.task_status } } : {}), + ...(assignment?.stage && !['accepted', 'ready'].includes(assignment.stage) + ? { progress: assignment.stage.replaceAll('_', ' ') } + : {}), + ...(assignment?.host_label ? { hostLabel: assignment.host_label } : {}), + ...(sendAddress && isPublicOrchestrationAddress(sendAddress) ? { sendAddress } : {}) + } + if (live?.kind === 'here') { + row.openTarget = { + kind: 'chat', + sessionId: live.sessionId, + worktreeId: live.record.location.workspaceId + } + } else if (target.terminalHandle) { + row.openTarget = { kind: 'terminal', handle: target.terminalHandle } + } else if (assignment && !assignment.host_label) { + row.openTarget = { kind: 'dispatch', address: `dispatch:${assignment.id}` } + } + rows.set(target.address, row) + return row + } + const snapshot = emptyCrew('ok') + for (const { assignment, worker, parent, parentAssignment, parentAddress } of host.relations.get( + self.address + ) ?? []) { + if (parent.address === self.address) { + snapshot.sections.managing.push( + decorate(worker, 'worker', assignment, `dispatch:${assignment.id}`) + ) + } else if (!rows.has(parent.address)) { + snapshot.sections.managedBy.push(decorate(parent, 'manager', parentAssignment, parentAddress)) + } + } + for (const message of traffic) { + let targetAddress = addressOf(message.peer) + if (!targetAddress) { + const parsed = parseOrcaSessionAddress(message.peer) + targetAddress = party(parsed, parsed ? null : message.peer, null, message.peer)?.address + } + if (!targetAddress || targetAddress === self.address) { + continue + } + const target = getParty(targetAddress)! + let row = rows.get(targetAddress) + if (!row) { + row = decorate( + target, + 'peer', + undefined, + target.orcaSessionId + ? target.address + : (target.terminalHandle ?? + (target.address.startsWith('dispatch:') || target.address.startsWith('run:') + ? target.address + : undefined)) + ) + snapshot.sections.talkingWith.push(row) + } + if (!row.latest || message.sequence > row.latest.sequence) { + row.latest = { + direction: message.direction, + preview: preview(message.body), + at: message.created_at, + sequence: message.sequence + } + } + } + const questions = readCrewQuestions(db, selfAliases()) + for (const question of questions) { + const target = addressOf(`dispatch:${question.dispatch_id}`) + const row = target ? rows.get(target) : undefined + if (row && !row.pendingQuestion) { + row.pendingQuestion = { preview: preview(question.body), at: question.created_at } + } + } + return snapshot +} diff --git a/src/main/runtime/orchestration/crew/crew-query.ts b/src/main/runtime/orchestration/crew/crew-query.ts index ab87d635d6ed..79bdcb420f3d 100644 --- a/src/main/runtime/orchestration/crew/crew-query.ts +++ b/src/main/runtime/orchestration/crew/crew-query.ts @@ -27,7 +27,9 @@ export const CrewAssignment = z.object({ coordinator_session: nullable, stage: nullable, agent: nullable, - host_label: nullable + host_label: nullable, + resource_incarnation: nullable, + resource_host_scope: nullable }) export type CrewAssignmentRow = z.infer @@ -37,10 +39,12 @@ const assignmentColumns = `d.rowid AS ordinal, d.id, d.run_id, d.task_id, d.status, d.completed_at, t.spec, t.task_title, t.display_name, t.status AS task_status, r.coordinator_handle, r.coordinator_pane_key, ${currentRunCoordinatorOrcaSessionIdSql('r')} AS coordinator_session, - w.stage, json_extract(w.start_options, '$.agent') AS agent, f.environment_name AS host_label` + w.stage, json_extract(w.start_options, '$.agent') AS agent, f.environment_name AS host_label, resource.process_incarnation AS resource_incarnation, + resource.host_scope AS resource_host_scope` const assignmentJoins = `JOIN tasks t ON t.id = d.task_id JOIN runs r ON r.id = d.run_id LEFT JOIN worker_dispatches w ON w.dispatch_id = d.id - LEFT JOIN federated_dispatches f ON f.dispatch_id = d.id` + LEFT JOIN federated_dispatches f ON f.dispatch_id = d.id + LEFT JOIN worker_terminal_resources resource ON resource.owner_dispatch_id = d.id` export function readCrewAssignments(db: OrchestrationDb, now: number): CrewAssignmentRow[] { const cutoff = new Date(now - AGENT_STATUS_STALE_AFTER_MS).toISOString() @@ -65,23 +69,50 @@ export function readCrewAssignments(db: OrchestrationDb, now: number): CrewAssig ) } -export function readCrewMailboxAssignments( - db: OrchestrationDb, - addresses: string[] -): CrewAssignmentRow[] { - const ids = addresses - .filter((address) => address.startsWith('dispatch:')) - .map((address) => address.slice(9)) - return ids.length === 0 - ? [] - : CrewAssignment.array().parse( - db.db - .prepare(` - SELECT ${assignmentColumns} FROM dispatch_contexts d ${assignmentJoins} - WHERE d.id IN (SELECT value FROM json_each(?)) - `) - .all(JSON.stringify(ids)) - ) +const Provenance = z.object({ + id: z.string(), + handle: nullable, + pane: nullable, + session: nullable +}) + +/** Retained aliases are narrow provenance, never eligible relationship membership. */ +export function readCrewProvenance(db: OrchestrationDb, addresses: string[], panes: string[] = []) { + const handles = JSON.stringify(addresses.filter((address) => address.startsWith('term_'))) + const sessions = JSON.stringify( + addresses + .filter((address) => address.startsWith('orca_session_id:')) + .map((address) => address.slice('orca_session_id:'.length)) + ) + const ids = JSON.stringify( + addresses + .filter((address) => address.startsWith('dispatch:')) + .map((address) => address.slice(9)) + ) + const local = Provenance.array().parse( + db.db + .prepare(`SELECT d.id, d.assignee_handle AS handle, + d.assignee_pane_key AS pane, d.assignee_orca_session_id AS session + FROM dispatch_contexts d WHERE d.rowid IN ( + SELECT rowid FROM dispatch_contexts WHERE assignee_handle IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM dispatch_contexts WHERE assignee_orca_session_id IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM dispatch_contexts WHERE assignee_pane_key IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM dispatch_contexts WHERE id IN (SELECT value FROM json_each(?))) + ORDER BY d.rowid DESC`) + .all(handles, sessions, JSON.stringify(panes), ids) + ) + const remote = Provenance.array().parse( + db.db + .prepare(`SELECT dispatch_id AS id, + terminal_handle AS handle, pane_key AS pane, NULL AS session + FROM remote_dispatch_attachments WHERE rowid IN ( + SELECT rowid FROM remote_dispatch_attachments WHERE terminal_handle IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM remote_dispatch_attachments WHERE pane_key IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM remote_dispatch_attachments WHERE dispatch_id IN (SELECT value FROM json_each(?))) + ORDER BY rowid DESC`) + .all(handles, JSON.stringify(panes), ids) + ) + return { local, remote } } const Traffic = z.object({ @@ -103,16 +134,17 @@ export function readCrewTraffic( db.db .prepare(` WITH traffic AS ( - SELECT to_handle AS peer, 'to' AS direction, sequence, body, created_at + SELECT to_handle AS peer, 'to' AS direction, sequence FROM messages WHERE from_handle IN (SELECT value FROM json_each(?)) AND julianday(created_at) >= julianday(?) AND type <> 'heartbeat' UNION ALL - SELECT from_handle AS peer, 'from' AS direction, sequence, body, created_at + SELECT from_handle AS peer, 'from' AS direction, sequence FROM messages WHERE to_handle IN (SELECT value FROM json_each(?)) AND julianday(created_at) >= julianday(?) AND type <> 'heartbeat' ), peers AS (SELECT peer, MAX(sequence) AS sequence FROM traffic GROUP BY peer) - SELECT traffic.peer, traffic.direction, traffic.sequence, traffic.body, traffic.created_at + SELECT traffic.peer, traffic.direction, traffic.sequence, winner.body, winner.created_at FROM peers JOIN traffic ON traffic.peer = peers.peer AND traffic.sequence = peers.sequence + JOIN messages winner ON winner.sequence = traffic.sequence ORDER BY traffic.sequence DESC `) .all(JSON.stringify(aliases), cutoff, JSON.stringify(aliases), cutoff) @@ -125,9 +157,9 @@ export function readCrewQuestions(db: OrchestrationDb, aliases: string[]) { .array() .parse( db.db - .prepare(`SELECT q.dispatch_id, m.body, m.created_at FROM messages m - JOIN question_threads q ON q.message_id = m.id AND q.status = 'pending' - WHERE m.to_handle IN (SELECT value FROM json_each(?)) ORDER BY m.sequence DESC + .prepare(`SELECT q.dispatch_id, m.body, m.created_at FROM question_threads q INDEXED BY idx_crew_pending_questions + JOIN messages m ON m.id = q.message_id + WHERE q.status = 'pending' AND m.to_handle IN (SELECT value FROM json_each(?)) ORDER BY m.sequence DESC `) .all(JSON.stringify(aliases)) ) @@ -149,16 +181,15 @@ export function readCrewRuns(db: OrchestrationDb, addresses: string[]) { ) } -export function readCrewSelfAssignments( +export function readCrewOwnedRunAddresses( db: OrchestrationDb, party: { terminalHandle: string | null; paneKey: string | null; orcaSessionId: string | null } -) { - return CrewAssignment.array().parse( - db.db - .prepare(`SELECT ${assignmentColumns} - FROM dispatch_contexts d ${assignmentJoins} WHERE d.assignee_handle = ? - OR d.assignee_pane_key = ? OR d.assignee_orca_session_id = ? - `) - .all(party.terminalHandle, party.paneKey, party.orcaSessionId) +): string[] { + const ids = new Set( + party.terminalHandle ? db.getRunMailboxOwnerIdsForHandle(party.terminalHandle) : [] ) + for (const run of db.runsBoundToCoordinator(party)) { + ids.add(run.id) + } + return [...ids].map((id) => `run:${id}`) } diff --git a/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts b/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts new file mode 100644 index 000000000000..4a6808dbba85 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts @@ -0,0 +1,352 @@ +import { readCrewTraffic, readCrewProvenance } from './crew-query' + +import type { AgentStatusIpcPayload } from '../../../../shared/agent-status-ipc-payload' +import { RuntimeAgentOrchestrationProjection } from '../../runtime-agent-orchestration-projection' +import { readOrchestrationFleetAgentStatusSnapshot } from '../../orchestration-fleet-agent-status-snapshot' +import { RuntimeOrchestrationSenderNames } from '../../runtime-orchestration-sender-names' + +import { expect, it, vi } from 'vitest' + +import { CrewReadModel } from './crew-read-model' +import { CrewChanges } from './crew-changes' +import { subscribeCrew } from './crew-stream' +import type { OrchestrationCrewFrame } from '../../../../shared/orchestration-crew' +import { agentSessionRecordFixture } from '../../../native-chat/agent-session-record-test-fixture' +import { agentSessionConversationView } from '../../../../shared/agent-session-conversation-view' + +import { fixture } from './crew-read-model.test-fixture' +it('shares complete host derivation across N/10N handled assignments and subscribers on real wakes', async () => { + const flush = async () => { + await Promise.resolve() + await Promise.resolve() + } + const measure = async (population: number, subscribers: number) => { + const { db, deps, assign, handles } = fixture() + assign('term_worker') + const unrelatedRun = db.createRun({ + objective: 'Other crews', + coordinatorHandle: 'term_peer', + coordinatorPaneKey: handles.get('term_peer')! + }) + const records = Array.from({ length: population }, (_, i) => + agentSessionConversationView(agentSessionRecordFixture({ sessionId: `chat-scale-${i}` })) + ) + for (const record of records) { + db.createDispatchContext({ + taskId: db.createTask({ runId: unrelatedRun.id, spec: 'Unrelated' }).id, + assigneeHandle: `term_handled_${record.sessionId}`, + processIncarnation: `structured:${record.sessionId}`, + creator: { kind: 'system' }, + maxDepth: 10 + }) + } + const listRecords = vi.fn(() => records) + deps.records = { + listRecords, + getRecord: (id) => records.find((record) => record.sessionId === id) ?? null + } + const resolvePane = vi.spyOn(deps, 'handleForPane') + const operations = { all: 0, get: 0, iterate: 0, rows: 0, bytes: 0 } + const prepare = db.db.prepare.bind(db.db) + const querySpy = vi.spyOn(db.db, 'prepare').mockImplementation((sql) => { + const statement = prepare(sql) + return { + all: (...args) => { + operations.all++ + const rows = statement.all(...args) + operations.rows += rows.length + operations.bytes += Buffer.byteLength(JSON.stringify(rows)) + return rows + }, + get: (...args) => { + operations.get++ + const row = statement.get(...args) + operations.rows += row ? 1 : 0 + operations.bytes += Buffer.byteLength(JSON.stringify(row ?? null)) + return row + }, + run: (...args) => statement.run(...args), + iterate: function* (...args) { + operations.iterate++ + for (const row of statement.iterate(...args)) { + operations.rows++ + operations.bytes += Buffer.byteLength(JSON.stringify(row)) + yield row + } + }, + setReadBigInts: (value) => statement.setReadBigInts(value) + } + }) + const dependencies = vi.fn(() => deps) + const watch = vi.fn(db.crewChanges.subscribe) + const model = new CrewReadModel(dependencies, watch) + const publications = Array.from({ length: subscribers }, () => [] as OrchestrationCrewFrame[]) + const stops = publications.map((frames, i) => + subscribeCrew( + () => model.read(i === 0 ? 'term_coord' : `orca_session_id:chat-empty-${i}`), + model.subscribe, + (frame) => frames.push(frame) + ) + ) + await flush() + expect(watch).toHaveBeenCalledTimes(1) + expect(dependencies).toHaveBeenCalledTimes(1) + expect(listRecords).toHaveBeenCalledTimes(1) + expect(publications[0].filter((frame) => frame.type === 'rows')).toHaveLength(1) + for (const frames of publications.slice(1)) { + expect(frames).toEqual([{ type: 'begin', status: 'ok' }, { type: 'complete' }]) + } + const initial = { ...operations } + operations.all = operations.get = operations.iterate = operations.rows = operations.bytes = 0 + listRecords.mockClear() + resolvePane.mockClear() + db.insertMessage({ + from: 'term_peer', + to: 'term_outbound', + subject: 'Unrelated update', + body: 'Other crew traffic' + }) + await flush() + expect(dependencies).toHaveBeenCalledTimes(1) + expect(listRecords).not.toHaveBeenCalled() + // Traffic retains the immutable topology and never invokes the dependency helper. + expect(operations.get).toBeLessThan(population + 10) + expect(resolvePane.mock.calls.length).toBeLessThan(5 * population + 2 * subscribers + 10) + for (const frames of publications) { + expect(frames.filter((frame) => frame.type === 'complete')).toHaveLength(1) + } + const update = { ...operations } + console.log( + 'crew host operation contract', + JSON.stringify({ population, subscribers, initial, update }) + ) + for (const stop of stops) { + stop() + } + const reads = dependencies.mock.calls.length + db.insertMessage({ from: 'term_peer', to: 'term_outbound', subject: 'After teardown' }) + await flush() + expect(dependencies).toHaveBeenCalledTimes(reads) + querySpy.mockRestore() + resolvePane.mockRestore() + return { initial, update } + } + const n = await measure(3, 3) + const manyPanes = await measure(3, 30) + const manyAssignments = await measure(30, 3) + const tenN = await measure(30, 30) + expect(manyPanes.update.get).toBe(n.update.get) + expect(tenN.update.get).toBe(manyAssignments.update.get) + for (const phase of ['initial', 'update'] as const) { + for (const operation of ['all', 'get', 'iterate', 'rows', 'bytes'] as const) { + expect(tenN[phase][operation]).toBeLessThanOrEqual(n[phase][operation] * 10) + } + } +}) +it('counts the real status qualification/projection SQL on a decoration wake without global reacquisition', async () => { + const measurements = [] + for (const population of [3, 30]) { + const { db, deps, assign, handles } = fixture() + assign('term_worker') + const unrelated = db.createRun({ + objective: 'Unrelated', + coordinatorHandle: 'term_peer', + coordinatorPaneKey: handles.get('term_peer')! + }) + for (let i = 0; i < population; i++) { + const handle = `term_status_${i}` + handles.set(handle, `tab_status_${i}:aaaaaaaa-aaaa-4aaa-8aaa-${String(i).padStart(12, '0')}`) + db.createDispatchContext({ + taskId: db.createTask({ runId: unrelated.id, spec: 'Other' }).id, + assigneeHandle: handle, + assigneePaneKey: handles.get(handle), + creator: { kind: 'system' }, + maxDepth: 10 + }) + } + const listRecords = vi.fn(() => []) + deps.records = { listRecords, getRecord: () => null } + const projection = new RuntimeAgentOrchestrationProjection({ + getDb: () => db, + getLeaves: () => [], + getPtys: () => [], + paneOf: () => ({ tabId: null, paneKey: null, recordedAtGraphSequence: 0 }), + issueLeafHandle: () => '', + issuePtyHandle: () => '', + makePaneKey: () => '', + getWorktreeId: () => null, + getHandleForPaneKey: deps.handleForPane, + getPaneKey: deps.paneForHandle, + getDispatchAuthority: () => null, + getAgentStatusSnapshot: () => [], + getSessionRecords: () => deps.records + }) + const raw: AgentStatusIpcPayload[] = [...handles] + .filter(([handle]) => handle === 'term_worker' || handle.startsWith('term_status_')) + .map(([, paneKey]) => ({ + paneKey, + state: 'working', + agentType: 'codex', + prompt: '', + connectionId: null, + receivedAt: Date.now(), + stateStartedAt: Date.now() + })) + const acquireStatus = vi.fn(() => + readOrchestrationFleetAgentStatusSnapshot({ + getAgentStatusSnapshotFn: () => raw, + readObservedAgentStatusPaneIdentityFn: () => ({ kind: 'unobserved' }), + getAgentStatusTerminalHandleForPaneKey: (pane) => deps.handleForPane(pane) ?? undefined, + getTerminalProcessIncarnation: () => 'test-process', + getAgentStatusOrchestrationContextForPaneKey: (paneKey) => + projection.getForHandle(deps.handleForPane(paneKey)!, undefined, { paneKey }) + }) + ) + let title = 'First title' + const names = new RuntimeOrchestrationSenderNames({ + getDb: () => db, + getHandleRecord: (handle) => + handle === 'term_worker' + ? { worktreeId: 'folder', tabId: 'tab_worker', ptyId: 'pty' } + : undefined, + getPtyAgents: () => ({ launchAgent: 'codex' }), + getTerminalPaneKey: deps.paneForHandle, + getWorkspaceSession: () => ({ + tabsByWorktree: { folder: [{ id: 'tab_worker', title, customTitle: null }] } + }), + getGeneratedTitlesEnabled: () => true, + getAgentStatusSnapshotForPane: (pane) => raw.filter((row) => row.paneKey === pane), + getTrackedTitle: () => null + }) + deps.name = (party, task, records) => names.nameOf(party, undefined, task, records) + const wake = new CrewChanges() + const model = new CrewReadModel( + () => ({ + ...deps, + get statuses() { + return acquireStatus() + } + }), + wake.subscribe + ) + const streams = Array.from({ length: population }, (_, i) => + subscribeCrew( + () => model.read(i === 0 ? 'term_coord' : `orca_session_id:chat-empty-${i}`), + model.subscribe, + () => {} + ) + ) + const globalSelection = vi.spyOn(db, 'listSessionDispatchesForPresentation') + acquireStatus.mockClear() + listRecords.mockClear() + const executed = { get: 0, all: 0, iterate: 0, rows: 0 } + const prepare = db.db.prepare.bind(db.db) + const sql: string[] = [] + const spy = vi.spyOn(db.db, 'prepare').mockImplementation((text) => { + const statement = prepare(text) + return { + get: (...args) => { + sql.push(text) + executed.get++ + const row = statement.get(...args) + executed.rows += row ? 1 : 0 + return row + }, + all: (...args) => { + sql.push(text) + executed.all++ + const rows = statement.all(...args) + executed.rows += rows.length + return rows + }, + iterate: function* (...args) { + sql.push(text) + executed.iterate++ + for (const row of statement.iterate(...args)) { + executed.rows++ + yield row + } + }, + run: (...args) => statement.run(...args), + setReadBigInts: (value) => statement.setReadBigInts(value) + } + }) + raw[0] = { ...raw[0], state: 'waiting' } + wake.notify(new Set(['status'])) + await Promise.resolve() + expect(acquireStatus).toHaveBeenCalledTimes(1) + expect(globalSelection).not.toHaveBeenCalled() + expect(listRecords).not.toHaveBeenCalled() + expect(executed.get).toBeGreaterThan(population * 2) + expect(sql.some((text) => text.includes('attempt_observation_facts'))).toBe(true) + expect(model.read('term_coord').sections.managing[0].status).toBe('waiting') + measurements.push({ population, ...executed }) + acquireStatus.mockClear() + title = 'Changed title' + wake.notify(new Set(['names'])) + await Promise.resolve() + expect(acquireStatus).not.toHaveBeenCalled() + expect(globalSelection).not.toHaveBeenCalled() + expect(model.read('term_coord').sections.managing[0].label).toBe(title) + for (const stop of streams) { + stop() + } + spy.mockRestore() + globalSelection.mockRestore() + } + for (const key of ['get', 'all', 'iterate', 'rows'] as const) { + expect(measurements[1][key]).toBeLessThanOrEqual(measurements[0][key] * 10) + } + console.log('crew actual status operation contract', JSON.stringify(measurements)) +}) +it('selects peer maxima without losing bodies and uses indexed historical provenance', () => { + const { db, run, assign } = fixture() + assign('term_worker') + db.insertMessage({ + runId: run.id, + from: 'term_worker', + to: 'term_coord', + subject: 'Large losing body', + body: 'x'.repeat(64 * 1024) + }) + const winner = db.insertMessage({ + runId: run.id, + from: 'term_worker', + to: 'term_coord', + subject: 'Winner', + body: 'latest' + }) + const plans: unknown[] = [] + const prepare = db.db.prepare.bind(db.db) + const spy = vi.spyOn(db.db, 'prepare').mockImplementation((sql) => { + const statement = prepare(sql) + return { + all: (...args) => { + const rows = statement.all(...args) + plans.push(...prepare(`EXPLAIN QUERY PLAN ${sql}`).all(...args)) + return rows + }, + get: (...args) => statement.get(...args), + run: (...args) => statement.run(...args), + iterate: (...args) => statement.iterate(...args), + setReadBigInts: (value) => statement.setReadBigInts(value) + } + }) + const traffic = readCrewTraffic(db, ['term_coord', `run:${run.id}`], '2000-01-01T00:00:00Z') + expect(traffic).toMatchObject([ + { peer: 'term_worker', direction: 'from', sequence: winner.sequence, body: 'latest' } + ]) + const provenance = readCrewProvenance( + db, + ['term_worker'], + ['tab_worker:aaaaaaaa-aaaa-4aaa-8aaa-workeraaaaaa'] + ) + expect(provenance.local).toHaveLength(1) + const plan = JSON.stringify(plans) + expect(plan).toContain('idx_messages_crew_from') + expect(plan).toContain('idx_messages_crew_to') + expect(plan).toContain('idx_crew_dispatch_pane') + expect(plan).not.toContain('SCAN dispatch_contexts') + console.log('crew scoped query plans', plan) + spy.mockRestore() +}) diff --git a/src/main/runtime/orchestration/crew/crew-read-model.test-fixture.ts b/src/main/runtime/orchestration/crew/crew-read-model.test-fixture.ts new file mode 100644 index 000000000000..0f892a5cd23d --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-read-model.test-fixture.ts @@ -0,0 +1,43 @@ +import { afterEach } from 'vitest' +import { OrchestrationDb } from '../db' +import type { CrewReadDependencies } from './crew-read-model' +const opened: OrchestrationDb[] = [] +afterEach(() => opened.splice(0).forEach((db) => db.close())) +export function fixture() { + const db = new OrchestrationDb(':memory:') + opened.push(db) + const handles = new Map( + ['coord', 'worker', 'helper', 'grandchild', 'peer', 'outbound'].map((name) => [ + `term_${name}`, + `tab_${name}:aaaaaaaa-aaaa-4aaa-8aaa-${name.padEnd(12, 'a')}` + ]) + ) + const deps: CrewReadDependencies = { + db, + retainedDbExists: true, + hostKey: 'test-host', + records: null, + statuses: [], + liveHandle: (handle) => handles.has(handle), + handleForPane: (pane) => [...handles].find(([, value]) => value === pane)?.[0] ?? null, + paneForHandle: (handle) => handles.get(handle) ?? null, + name: (_identity, task) => task ?? 'Duplicate name' + } + const run = db.createRun({ + objective: 'Crew', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: handles.get('term_coord')! + }) + const assign = (handle: string, creator = 'term_coord', title = 'Implement crew') => { + const task = db.createTask({ runId: run.id, spec: title, taskTitle: title }) + db.updateTaskStatus(task.id, 'ready') + return db.createDispatchContext({ + taskId: task.id, + assigneeHandle: handle, + assigneePaneKey: handles.get(handle), + creator: { kind: 'terminal', handle: creator, paneKey: handles.get(creator) }, + maxDepth: 10 + }) + } + return { db, deps, run, assign, handles } +} diff --git a/src/main/runtime/orchestration/crew/crew-read-model.test.ts b/src/main/runtime/orchestration/crew/crew-read-model.test.ts index 2167000bcd77..f52e06e88c37 100644 --- a/src/main/runtime/orchestration/crew/crew-read-model.test.ts +++ b/src/main/runtime/orchestration/crew/crew-read-model.test.ts @@ -1,52 +1,17 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { OrchestrationDb } from '../db' -import { buildCrewSnapshot, type CrewReadDependencies } from './crew-read-model' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-freshness' + +import { createCrewPartyRegistry } from './crew-parties' +import type { FleetAgentStatusEvidence } from '../../../../shared/orchestration-fleet-agent-status-evidence' +import { describe, expect, it, vi } from 'vitest' + +import { buildCrewSnapshot, CrewReadModel } from './crew-read-model' import { CrewChanges } from './crew-changes' import { subscribeCrew } from './crew-stream' import type { OrchestrationCrewFrame } from '../../../../shared/orchestration-crew' import { agentSessionRecordFixture } from '../../../native-chat/agent-session-record-test-fixture' import { agentSessionConversationView } from '../../../../shared/agent-session-conversation-view' -const opened: OrchestrationDb[] = [] -afterEach(() => opened.splice(0).forEach((db) => db.close())) -function fixture() { - const db = new OrchestrationDb(':memory:') - opened.push(db) - const handles = new Map( - ['coord', 'worker', 'helper', 'grandchild', 'peer', 'outbound'].map((name) => [ - `term_${name}`, - `tab_${name}:aaaaaaaa-aaaa-4aaa-8aaa-${name.padEnd(12, 'a')}` - ]) - ) - const deps: CrewReadDependencies = { - db, - retainedDbExists: true, - hostKey: 'test-host', - records: null, - statuses: [], - liveHandle: (handle) => handles.has(handle), - handleForPane: (pane) => [...handles].find(([, value]) => value === pane)?.[0] ?? null, - paneForHandle: (handle) => handles.get(handle) ?? null, - name: (_identity, task) => task ?? 'Duplicate name' - } - const run = db.createRun({ - objective: 'Crew', - coordinatorHandle: 'term_coord', - coordinatorPaneKey: handles.get('term_coord')! - }) - const assign = (handle: string, creator = 'term_coord', title = 'Implement crew') => { - const task = db.createTask({ runId: run.id, spec: title, taskTitle: title }) - db.updateTaskStatus(task.id, 'ready') - return db.createDispatchContext({ - taskId: task.id, - assigneeHandle: handle, - assigneePaneKey: handles.get(handle), - creator: { kind: 'terminal', handle: creator, paneKey: handles.get(creator) }, - maxDepth: 10 - }) - } - return { db, deps, run, assign } -} +import { fixture } from './crew-read-model.test-fixture' describe('public crew read and stream', () => { it('derives direct roles and two-sided latest mail without consuming questions or leaking authority', async () => { @@ -203,47 +168,39 @@ it('batches crew work as relationships scale and keeps skewed peers despite unre for (let i = 0; i < 3; i++) { assign(`term_extra_${i}`) } - let dependency = false - const selection = db.listSessionDispatchesForPresentation.bind(db) - const selectionSpy = vi - .spyOn(db, 'listSessionDispatchesForPresentation') - .mockImplementation((now) => { - dependency = true - try { - return selection(now) - } finally { - dependency = false - } - }) - let queries = 0, - materialized = 0 + const operations = { all: 0, get: 0, iterate: 0, rows: 0, bytes: 0 } const prepare = db.db.prepare.bind(db.db) const querySpy = vi.spyOn(db.db, 'prepare').mockImplementation((sql) => { - if (!dependency) { - queries++ - } const statement = prepare(sql) - const ownRead = !dependency - return new Proxy(statement, { - get(target, key) { - const value = Reflect.get(target, key) - if (key === 'all') { - return (...args: unknown[]) => { - const rows = statement.all(...args) - if (ownRead) { - materialized += rows.length - } - return rows - } + return { + all: (...args) => { + operations.all++ + const rows = statement.all(...args) + operations.rows += rows.length + operations.bytes += Buffer.byteLength(JSON.stringify(rows)) + return rows + }, + get: (...args) => { + operations.get++ + const row = statement.get(...args) + operations.rows += row ? 1 : 0 + operations.bytes += Buffer.byteLength(JSON.stringify(row ?? null)) + return row + }, + run: (...args) => statement.run(...args), + iterate: function* (...args) { + operations.iterate++ + for (const row of statement.iterate(...args)) { + operations.rows++ + operations.bytes += Buffer.byteLength(JSON.stringify(row)) + yield row } - return typeof value === 'function' ? value.bind(target) : value - } - }) + }, + setReadBigInts: (value) => statement.setReadBigInts(value) + } }) buildCrewSnapshot('term_coord', deps) - const small = { queries, materialized } - const readCount = selectionSpy.mock.calls.length - expect(readCount).toBe(1) + const small = { ...operations } const frames: OrchestrationCrewFrame[] = [] const stop = subscribeCrew( () => buildCrewSnapshot('term_coord', deps), @@ -260,21 +217,19 @@ it('batches crew work as relationships scale and keeps skewed peers despite unre await new Promise((resolve) => queueMicrotask(resolve)) await new Promise((resolve) => queueMicrotask(resolve)) expect(frames.filter((frame) => frame.type === 'complete')).toHaveLength(1) - queries = 0 - materialized = 0 + operations.all = operations.get = operations.iterate = operations.rows = operations.bytes = 0 buildCrewSnapshot('term_coord', deps) - expect({ queries, materialized }).toEqual(small) + expect(operations).toEqual(small) for (let i = 3; i < 30; i++) { assign(`term_extra_${i}`) } - queries = 0 - materialized = 0 + operations.all = operations.get = operations.iterate = operations.rows = operations.bytes = 0 const large = buildCrewSnapshot('term_coord', deps) expect(large.sections.managing).toHaveLength(30) - expect(queries).toBe(small.queries) - expect(materialized).toBeLessThanOrEqual(small.materialized * 10) + expect(operations.all).toBe(small.all) + expect(operations.get).toBe(small.get) + expect(operations.rows).toBeLessThanOrEqual(small.rows * 10) querySpy.mockRestore() - selectionSpy.mockRestore() for (let i = 0; i < 100; i++) { db.insertMessage({ from: `run:${run.id}`, @@ -297,3 +252,376 @@ it('batches crew work as relationships scale and keeps skewed peers despite unre stop() vi.restoreAllMocks() }) + +it('preserves a bound offline manager and the complete committed clear conversation', () => { + const { db, deps, run, handles } = fixture() + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'System worker' }).id, + assigneeHandle: 'term_worker', + assigneePaneKey: handles.get('term_worker'), + creator: { kind: 'system' }, + maxDepth: 10 + }) + handles.delete('term_coord') + const manager = buildCrewSnapshot('term_worker', deps).sections.managedBy + expect(manager).toHaveLength(1) + expect(manager[0].sendAddress).toBe(`run:${run.id}`) + expect(manager[0].openTarget).toBeUndefined() + const record = (sessionId: string, next?: string) => + agentSessionConversationView( + agentSessionRecordFixture({ + sessionId, + ...(next + ? { + conversationCommand: { + command: 'clear', + phase: 'committed', + replacementSessionId: next, + operationId: `clear-${sessionId}` + } + } + : {}) + }) + ) + const records = [ + record('chat-aaa', 'chat-bbb'), + record('chat-bbb', 'chat-ccc'), + record('chat-ccc') + ] + deps.records = { + listRecords: () => records, + getRecord: (id) => records.find((entry) => entry.sessionId === id) ?? null + } + db.insertMessage({ + from: 'orca_session_id:chat-aaa', + to: 'term_peer', + subject: 'Root', + body: 'root' + }) + const latest = db.insertMessage({ + from: 'term_peer', + to: 'orca_session_id:chat-bbb', + subject: 'Intermediate', + body: 'intermediate' + }) + const peers = buildCrewSnapshot('orca_session_id:chat-ccc', deps).sections.talkingWith + expect(peers).toHaveLength(1) + expect(peers[0].latest).toMatchObject({ + preview: 'intermediate', + sequence: latest.sequence, + direction: 'from' + }) +}) + +it('decorates handed-back peer questions after row creation without flattening direct children', () => { + const { db, deps, run, assign } = fixture() + const parent = assign('term_worker') + const helper = assign('term_helper', 'term_worker') + const question = db.createQuestion({ + runId: run.id, + dispatchId: helper.id, + askerHandle: 'term_helper', + to: `dispatch:${parent.id}`, + question: 'Choose the helper option?' + }) + db.completeDispatch(parent.id) + expect(db.getMessageById(question.message.id)?.to_handle).toBe(`run:${run.id}`) + const snapshot = buildCrewSnapshot('term_coord', deps) + expect(snapshot.sections.managing.map((row) => row.sendAddress)).toEqual([ + `dispatch:${parent.id}` + ]) + expect(snapshot.sections.talkingWith).toHaveLength(1) + expect(snapshot.sections.talkingWith[0].pendingQuestion?.preview).toBe( + 'Choose the helper option?' + ) + expect(db.getQuestion(question.message.id)?.status).toBe('pending') +}) + +it('uses qualified terminal status and keeps canonical native status without requiring a terminal binding', () => { + const { deps, assign, handles } = fixture() + const worker = assign('term_worker') + const now = Date.now() + deps.now = now + const status: FleetAgentStatusEvidence = { + binding: { + kind: 'worker', + dispatchId: worker.id, + paneKey: handles.get('term_worker')!, + terminalHandle: 'term_worker', + processIncarnation: 'incarnation' + }, + clock: { kind: 'observed', at: now }, + deliveredAt: now, + activity: { + paneKey: handles.get('term_worker')!, + connectionId: null, + state: 'done', + agentType: 'codex', + model: null, + worktreeId: null, + restoredUnconfirmed: false, + providerSessionOnly: false + } + } + const read = () => + buildCrewSnapshot('term_coord', deps).sections.managing.find( + (row) => row.sendAddress === `dispatch:${worker.id}` + ) + for (const invalid of [ + { ...status, binding: { kind: 'unresolved', reason: 'stale_incarnation' } }, + { ...status, binding: { ...status.binding, kind: 'worker', dispatchId: 'ctx_other' } }, + { ...status, activity: { ...status.activity, restoredUnconfirmed: true } }, + { ...status, activity: { ...status.activity, providerSessionOnly: true } }, + { ...status, clock: { kind: 'observed', at: now + 60_000 } }, + { ...status, clock: { kind: 'observed', at: now - 31 * 60_000 } } + ] satisfies FleetAgentStatusEvidence[]) { + deps.statuses = [invalid] + expect(read()?.status).toBe('working') + expect(read()?.agentKind).toBe('Agent') + } + deps.statuses = [status] + expect(read()?.status).toBe('done') + const native = agentSessionConversationView( + agentSessionRecordFixture({ sessionId: 'chat-native' }) + ) + deps.records = { + listRecords: () => [native], + getRecord: (id) => (id === native.sessionId ? native : null) + } + assign('orca_session_id:chat-native') + const nativeRow = buildCrewSnapshot('term_coord', deps).sections.managing.find( + (row) => row.openTarget?.kind === 'chat' + )! + const registry = createCrewPartyRegistry(deps) + const paneKey = registry.party('chat-native', null, null)!.paneKey! + deps.statuses = [ + { + ...status, + binding: { kind: 'unresolved', reason: 'pane_not_bound' }, + activity: { ...status.activity, paneKey, state: 'waiting' } + } + ] + expect( + buildCrewSnapshot('term_coord', deps).sections.managing.find( + (row) => row.partyKey === nativeRow.partyKey + )?.status + ).toBe('waiting') +}) + +it('hydrates expired peer provenance identically in reversed read orders without mutating shared inputs', () => { + const { db, deps, run, handles } = fixture() + handles.set('term_old', 'tab_old:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa') + const record = agentSessionConversationView( + agentSessionRecordFixture({ sessionId: 'chat-history' }) + ) + deps.records = { + listRecords: () => [record], + getRecord: (id) => (id === record.sessionId ? record : null) + } + const dispatch = db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'Old' }).id, + assigneeHandle: 'term_old', + processIncarnation: 'structured:chat-history', + creator: { kind: 'system' }, + maxDepth: 10 + }) + db.completeDispatch(dispatch.id) + db.db + .prepare("UPDATE dispatch_contexts SET completed_at = '2000-01-01' WHERE id = ?") + .run(dispatch.id) + db.insertMessage({ from: 'term_old', to: 'term_peer', subject: 'Recent', body: 'retained alias' }) + const model = new CrewReadModel(() => deps, db.crewChanges.subscribe) + const stop = model.subscribe(() => {}) + const fresh = buildCrewSnapshot('term_peer', deps) + const before = model.read('term_peer') + expect(before).toEqual(fresh) + expect(before.sections.talkingWith[0].sendAddress).toBe('orca_session_id:chat-history') + model.read('orca_session_id:chat-history') + expect(model.read('term_peer')).toEqual(before) + stop() + const stopAgain = model.subscribe(() => {}) + model.read('orca_session_id:chat-history') + expect(model.read('term_peer')).toEqual(before) + stopAgain() +}) + +it('keeps corrupt clear branches, missing successors and cycles independent of record order', () => { + const { deps } = fixture() + const record = (sessionId: string, next: string) => + agentSessionConversationView( + agentSessionRecordFixture({ + sessionId, + conversationCommand: { + command: 'clear', + phase: 'committed', + replacementSessionId: next, + operationId: sessionId + } + }) + ) + const rows = [ + record('chat-aaa', 'chat-ccc'), + record('chat-bbb', 'chat-ccc'), + record('chat-ccc', 'chat-ddd'), + record('chat-xxx', 'chat-yyy'), + record('chat-yyy', 'chat-xxx') + ] + const identities = (records: typeof rows) => { + const registry = createCrewPartyRegistry({ + ...deps, + records: { listRecords: () => records, getRecord: () => null } + }) + return rows.map((row) => registry.party(row.sessionId, null, null)?.address) + } + expect(identities(rows)).toEqual(rows.map((row) => `orca_session_id:${row.sessionId}`)) + expect(identities(rows.toReversed())).toEqual(identities(rows)) +}) + +it('wakes for later routing pages and existing-message question registration, including rollback', async () => { + const { db, deps, run, assign } = fixture() + const worker = assign('term_worker') + const model = new CrewReadModel(() => deps, db.crewChanges.subscribe) + const frames: OrchestrationCrewFrame[] = [] + const stop = subscribeCrew( + () => model.read('term_coord'), + model.subscribe, + (frame) => frames.push(frame) + ) + const messages = db.insertMessages( + Array.from({ length: 51 }, (_, i) => ({ + runId: run.id, + from: `dispatch:${worker.id}`, + to: 'term_unowned', + subject: 'Routed', + body: `page-${i}` + })) + ) + await Promise.resolve() + expect(db.routeDirectMessagePage(`run:${run.id}`, run.id, 'term_unowned').hasMore).toBe(true) + await Promise.resolve() + expect(model.read('term_coord').sections.managing[0].latest?.preview).toBe('page-49') + db.routeDirectMessagePage(`run:${run.id}`, run.id, 'term_unowned') + await Promise.resolve() + expect(model.read('term_coord').sections.managing[0].latest?.preview).toBe('page-50') + const existing = db.insertMessage({ + runId: run.id, + from: `dispatch:${worker.id}`, + to: `run:${run.id}`, + subject: 'Question already imported', + type: 'question', + body: 'Existing metadata' + }) + await Promise.resolve() + expect(model.read('term_coord').sections.managing[0].pendingQuestion).toBeUndefined() + db.registerFederatedQuestion({ messageId: existing.id, runId: run.id, dispatchId: worker.id }) + await Promise.resolve() + expect(model.read('term_coord').sections.managing[0].pendingQuestion?.preview).toBe( + 'Existing metadata' + ) + const count = frames.filter((frame) => frame.type === 'complete').length + db.db.exec('BEGIN') + db.insertMessage({ + from: 'term_peer', + to: 'term_coord', + subject: 'Rolled back', + body: 'never visible' + }) + db.db.exec('ROLLBACK') + await Promise.resolve() + expect(frames.filter((frame) => frame.type === 'complete')).toHaveLength(count) + expect(db.getMessageById(messages[50].id)?.to_handle).toBe(`run:${run.id}`) + stop() +}) + +it('rederives exact and backwards clocks and drops unwatched one-shot truth', () => { + const { db, deps, assign } = fixture() + const worker = assign('term_worker') + db.completeDispatch(worker.id) + const completed = Date.parse('2026-10-28T00:00:00Z') + db.db + .prepare('UPDATE dispatch_contexts SET completed_at = ? WHERE id = ?') + .run(new Date(completed).toISOString(), worker.id) + const clock = vi.spyOn(Date, 'now').mockReturnValue(completed) + try { + const model = new CrewReadModel(() => deps, db.crewChanges.subscribe) + const stop = model.subscribe(() => {}) + expect(model.read('term_coord').sections.managing).toHaveLength(1) + clock.mockReturnValue(completed + AGENT_STATUS_STALE_AFTER_MS) + expect(model.read('term_coord').sections.managing).toHaveLength(1) + clock.mockReturnValue(completed + AGENT_STATUS_STALE_AFTER_MS + 1) + expect(model.read('term_coord').sections.managing).toHaveLength(0) + clock.mockReturnValue(completed) + expect(model.read('term_coord').sections.managing).toHaveLength(1) + stop() + expect(model.read('term_coord').sections.managing).toHaveLength(1) + db.db + .prepare("UPDATE dispatch_contexts SET completed_at = '2000-01-01' WHERE id = ?") + .run(worker.id) + expect(model.read('term_coord').sections.managing).toHaveLength(0) + } finally { + clock.mockRestore() + } +}) + +it('retains reentrant invalidations and discards a generation whose acquisition fails', async () => { + const { deps, assign } = fixture() + assign('term_worker') + const wake = new CrewChanges() + let fail = false + let reenter = false + let reads = 0 + const model = new CrewReadModel(() => { + reads++ + if (fail) { + throw new Error('source unavailable') + } + if (reenter) { + reenter = false + wake.notify(new Set(['records'])) + } + return deps + }, wake.subscribe) + const stop = model.subscribe(() => {}) + expect(model.read('term_coord').sections.managing).toHaveLength(1) + reenter = true + wake.notify() + model.read('term_coord') + model.read('term_coord') + expect(reads).toBe(3) + fail = true + wake.notify(new Set(['status'])) + expect(() => model.read('term_coord')).toThrow('source unavailable') + fail = false + // The next legitimate event must reacquire, even when it only changes traffic. + wake.notify(new Set(['traffic'])) + expect(model.read('term_coord').sections.managing).toHaveLength(1) + expect(reads).toBe(5) + stop() +}) + +it('invalidates host membership when report import uses the transaction settlement entry point', async () => { + const { db, deps, assign } = fixture() + const worker = assign('term_worker') + const model = new CrewReadModel(() => deps, db.crewChanges.subscribe) + const frames: OrchestrationCrewFrame[] = [] + const stop = subscribeCrew( + () => model.read('term_coord'), + model.subscribe, + (frame) => frames.push(frame) + ) + expect(model.read('term_coord').sections.managing[0].task?.state).toBe('dispatched') + db.db.exec('BEGIN') + const result = db.settleWorkerReportInTransaction({ + taskId: worker.task_id, + dispatchId: worker.id, + outcome: 'succeeded', + result: 'Completed remotely' + }) + db.db.exec('COMMIT') + await Promise.resolve() + expect(result.action).toBe('settled') + expect(db.getDispatchContextById(worker.id)?.completed_at).toBeTruthy() + expect(model.read('term_coord').sections.managing[0].task?.state).toBe('completed') + expect(frames.filter((frame) => frame.type === 'complete')).toHaveLength(2) + stop() +}) diff --git a/src/main/runtime/orchestration/crew/crew-read-model.ts b/src/main/runtime/orchestration/crew/crew-read-model.ts index ebc5dc071ef4..3d31956522ae 100644 --- a/src/main/runtime/orchestration/crew/crew-read-model.ts +++ b/src/main/runtime/orchestration/crew/crew-read-model.ts @@ -1,283 +1,96 @@ -import type { AgentMessageSender } from '../../../../shared/agent-session/agent-session-message-source' -import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-freshness' +import type { CrewFacet, CrewInvalidation } from './crew-changes' +import { buildCrewSnapshot, type CrewReadDependencies } from './crew-party-snapshot' +import type { OrchestrationCrewSnapshot } from '../../../../shared/orchestration-crew' import { - emptyCrew, - type OrchestrationCrewSnapshot, - type OrchestrationCrewRow -} from '../../../../shared/orchestration-crew' -import { parseOrcaSessionAddress } from '../../../../shared/orca-session-address' -import type { FleetAgentStatusEvidence } from '../../../../shared/orchestration-fleet-agent-status-evidence' -import { isPublicOrchestrationAddress } from '../../../../shared/orchestration-agent-reference' -import type { OrchestrationDb } from '../db' -import { - resolveLineageRunningSession, - type AgentSessionRecordReader -} from '../structured-session-lineage' -import { crewDisplayName, creatorFirstParent, crewTaskDisplay } from './crew-rules' -import { - readCrewAssignments, - readCrewMailboxAssignments, - readCrewQuestions, - readCrewRuns, - readCrewTraffic, - readCrewSelfAssignments, - type CrewAssignmentRow -} from './crew-query' + createCrewHostDerivation, + refreshCrewStatuses, + type CrewHostDerivation +} from './crew-host-derivation' +export { buildCrewSnapshot, type CrewReadDependencies } from './crew-party-snapshot' -import { createCrewPartyRegistry, type Party } from './crew-parties' -export type CrewReadDependencies = { - db: OrchestrationDb | null - retainedDbExists: boolean - hostKey: string - records: AgentSessionRecordReader | null - liveHandle: (handle: string) => boolean - handleForPane: (pane: string) => string | null - paneForHandle: (handle: string) => string | null - name: (party: AgentMessageSender['party'], taskName: string | null) => string | null - statuses: readonly FleetAgentStatusEvidence[] - now?: number -} +/** One host derivation is shared by all mounted parties; the last subscriber releases its inputs. */ +export class CrewReadModel { + private host: CrewHostDerivation | undefined + private readonly listeners = new Set<() => void>() + private readonly renamed = new Set() + private readonly dirty = new Set() + private unwatch: (() => void) | undefined -function preview(body: string): string { - const bytes = Buffer.from(body) - return bytes.length <= 1024 - ? body - : `${bytes - .subarray(0, 1021) - .toString('utf8') - .replace(/\uFFFD$/, '')}…` -} + constructor( + private readonly readDependencies: () => CrewReadDependencies, + private readonly watch: (wake: (facets: CrewInvalidation) => void) => () => void + ) {} -export function buildCrewSnapshot( - address: string, - deps: CrewReadDependencies -): OrchestrationCrewSnapshot { - const db = deps.db - if (!db) { - return emptyCrew(deps.retainedDbExists ? 'unknown' : 'ok') - } - const now = deps.now ?? Date.now() - const cutoff = new Date(now - AGENT_STATUS_STALE_AFTER_MS).toISOString() - const records = deps.records - const { party, aliases, parties } = createCrewPartyRegistry(deps) - const rawSession = parseOrcaSessionAddress(address) - let self = party( - rawSession, - rawSession ? null : address, - rawSession ? null : deps.paneForHandle(address) - ) - if (!self) { - return emptyCrew('unknown') - } - const assignments = readCrewAssignments(db, now).sort( - (a, b) => - Number(['pending', 'dispatched'].includes(b.status)) - - Number(['pending', 'dispatched'].includes(a.status)) || b.ordinal - a.ordinal - ) - const assignmentsById = new Map(assignments.map((row) => [row.id, row])) - const assignmentParty = new Map() - const addAssignment = (row: CrewAssignmentRow): Party => { - const worker = party( - row.assignee_orca_session_id, - row.assignee_handle, - row.assignee_pane_key, - `dispatch:${row.id}` - )! - assignmentParty.set(row.id, worker) - aliases.set(`dispatch:${row.id}`, worker.address) - return worker - } - for (const row of readCrewSelfAssignments(db, self)) { - addAssignment(row) - } - for (const row of assignments) { - addAssignment(row) - const coordinator = party( - row.coordinator_session, - row.coordinator_handle, - row.coordinator_pane_key - ) - if (coordinator) { - aliases.set(`run:${row.run_id}`, coordinator.address) + private invalidate = (facets: CrewInvalidation) => { + for (const id of facets.recordIds ?? []) { + this.renamed.add(id) } - party(row.creator_orca_session_id, row.creator_handle, row.creator_pane_key) - } - self = parties.get(aliases.get(self.address) ?? self.address) ?? self - // A peer-only coordinator can have no eligible assignments in its Run. - const ownedRuns = db.db - .prepare( - `SELECT id FROM runs WHERE coordinator_handle = ? OR coordinator_pane_key = ? OR coordinator_orca_session_id = ?` - ) - .all(self.terminalHandle, self.paneKey, self.orcaSessionId) - const ownedRunAddresses = ownedRuns.flatMap((run) => - typeof run.id === 'string' ? [`run:${run.id}`] : [] - ) - for (const current of readCrewRuns(db, ownedRunAddresses)) { - const coordinator = party(current.session, current.handle, current.pane) - if (coordinator) { - aliases.set(`run:${current.id}`, coordinator.address) + for (const facet of facets) { + this.dirty.add(facet) } - } - const selfAliases = () => - [...aliases].filter(([, identity]) => identity === self.address).map(([alias]) => alias) - const traffic = readCrewTraffic(db, selfAliases(), cutoff) - const mailboxRows = readCrewMailboxAssignments( - db, - traffic.map((message) => message.peer) - ) - for (const row of mailboxRows) { - addAssignment(row) - } - for (const run of readCrewRuns( - db, - traffic.map((message) => message.peer) - )) { - const coordinator = party(run.session, run.handle, run.pane) - if (coordinator) { - aliases.set(`run:${run.id}`, coordinator.address) + for (const listener of this.listeners) { + listener() } } - const statuses = new Map(deps.statuses.map((status) => [status.activity.paneKey, status])) - const rows = new Map() - const decorate = ( - target: Party, - role: OrchestrationCrewRow['role'], - assignment?: CrewAssignmentRow, - sendAddress?: string - ): OrchestrationCrewRow => { - const display = crewTaskDisplay(assignment) - const evidence = target.paneKey ? statuses.get(target.paneKey) : undefined - const fresh = - evidence && now - evidence.clock.at <= AGENT_STATUS_STALE_AFTER_MS ? evidence : undefined - const title = display.taskTitle || display.displayName - const live = target.orcaSessionId - ? resolveLineageRunningSession(records, target.orcaSessionId) - : null - const row: OrchestrationCrewRow = { - partyKey: JSON.stringify([deps.hostKey, target.address]), - role, - label: crewDisplayName( - deps.name(target, display.displayName || display.taskTitle || null), - title, - 'Agent' - )!, - agentKind: - live?.kind === 'here' - ? live.record.provider - : (fresh?.activity.agentType ?? assignment?.agent ?? 'Agent'), - status: - fresh?.activity.state ?? - (assignment - ? ['pending', 'dispatched'].includes(assignment.status) - ? 'working' - : 'done' - : 'unknown'), - ...(title && assignment ? { task: { title, state: assignment.task_status } } : {}), - ...(assignment?.stage && !['accepted', 'ready'].includes(assignment.stage) - ? { progress: assignment.stage.replaceAll('_', ' ') } - : {}), - ...(assignment?.host_label ? { hostLabel: assignment.host_label } : {}), - ...(sendAddress && isPublicOrchestrationAddress(sendAddress) ? { sendAddress } : {}) - } - if (live?.kind === 'here') { - row.openTarget = { - kind: 'chat', - sessionId: live.sessionId, - worktreeId: live.record.location.workspaceId + + subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener) + this.unwatch ??= this.watch(this.invalidate) + return () => { + this.listeners.delete(listener) + if (this.listeners.size === 0) { + this.unwatch?.() + this.unwatch = undefined + this.host = undefined + this.dirty.clear() + this.renamed.clear() } - } else if (target.terminalHandle) { - row.openTarget = { kind: 'terminal', handle: target.terminalHandle } - } else if (assignment && !assignment.host_label) { - row.openTarget = { kind: 'dispatch', address: `dispatch:${assignment.id}` } } - rows.set(target.address, row) - return row } - const snapshot = emptyCrew('ok') - const selected = new Set() - for (const assignment of assignments) { - const worker = assignmentParty.get(assignment.id)! - if (selected.has(worker.address)) { - continue - } - selected.add(worker.address) - const creator = - (assignment.creator_dispatch_id - ? assignmentParty.get(assignment.creator_dispatch_id) - : undefined) ?? - party( - assignment.creator_orca_session_id, - assignment.creator_handle, - assignment.creator_pane_key - ) - const coordinator = party( - assignment.coordinator_session, - assignment.coordinator_handle, - assignment.coordinator_pane_key - ) - const parent = creatorFirstParent( - creator?.address === worker.address ? undefined : creator, - coordinator, - coordinator?.address === worker.address - ) - if (parent?.address === self.address && worker.address !== self.address) { - snapshot.sections.managing.push( - decorate(worker, 'worker', assignment, `dispatch:${assignment.id}`) - ) - } else if (worker.address === self.address && parent && parent.address !== self.address) { - const parentAssignment = assignment.creator_dispatch_id - ? assignmentsById.get(assignment.creator_dispatch_id) - : undefined - const sendAddress = - creator?.address === parent.address - ? parentAssignment - ? `dispatch:${parentAssignment.id}` - : parent.address - : `run:${assignment.run_id}` - if (!rows.has(parent.address)) { - snapshot.sections.managedBy.push(decorate(parent, 'manager', parentAssignment, sendAddress)) + + read = (address: string): OrchestrationCrewSnapshot => { + const now = Date.now() + const dirty = new Set(this.dirty) + const renamed = new Set(this.renamed) + this.dirty.clear() + this.renamed.clear() + if ( + !this.host || + dirty.has('topology') || + dirty.has('records') || + now < this.host.now || + now >= this.host.expiresAt + ) { + this.host = undefined + const deps = this.readDependencies() + // A one-shot read has no watch to keep captured truth current. + const host = createCrewHostDerivation(deps, deps.now ?? now) + if (this.listeners.size === 0) { + return buildCrewSnapshot(address, { ...host.deps, now }, host) } - } - } - const questions = readCrewQuestions(db, selfAliases()) - for (const question of questions) { - const target = assignmentParty.get(question.dispatch_id) - const row = target ? rows.get(target.address) : undefined - if (row && !row.pendingQuestion) { - row.pendingQuestion = { preview: preview(question.body), at: question.created_at } - } - } - for (const message of traffic) { - let targetAddress = aliases.get(message.peer) - if (!targetAddress) { - const parsed = parseOrcaSessionAddress(message.peer) - targetAddress = party(parsed, parsed ? null : message.peer, null, message.peer)?.address - } - if (!targetAddress || targetAddress === self.address) { - continue - } - const target = parties.get(targetAddress)! - let row = rows.get(targetAddress) - if (!row) { - row = decorate( - target, - 'peer', - undefined, - target.orcaSessionId - ? target.address - : (target.terminalHandle ?? - (target.address.startsWith('dispatch:') ? target.address : undefined)) - ) - snapshot.sections.talkingWith.push(row) - } - if (!row.latest || message.sequence > row.latest.sequence) { - row.latest = { - direction: message.direction, - preview: preview(message.body), - at: message.created_at, - sequence: message.sequence + this.host = host + } else if (dirty.has('status') || dirty.has('names')) { + const previous = this.host + this.host = undefined + const deps = this.readDependencies() + this.host = dirty.has('status') ? refreshCrewStatuses(previous, deps.statuses) : previous + let records = this.host.deps.records + if (renamed.size && records) { + const captured = new Map(records.listRecords().map((record) => [record.sessionId, record])) + for (const id of renamed) { + const record = deps.records?.getRecord(id) + if (record) { + captured.set(id, record) + } + } + records = { + ...records, + getRecord: (id) => captured.get(id) ?? null, + listRecords: () => [...captured.values()] + } } + this.host = { ...this.host, deps: { ...this.host.deps, records, name: deps.name } } } + return buildCrewSnapshot(address, { ...this.host.deps, now }, this.host) } - return snapshot } diff --git a/src/main/runtime/orchestration/crew/crew-runtime-watch.ts b/src/main/runtime/orchestration/crew/crew-runtime-watch.ts new file mode 100644 index 000000000000..3804431414b2 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-runtime-watch.ts @@ -0,0 +1,88 @@ +import type { OrcaRuntimeService } from '../../orca-runtime' +import type { OrchestrationDb } from '../db' +import type { CrewReadDependencies } from './crew-read-model' +import { conversationRecordReader } from '../structured-session-lineage' +import { peekOpenedAgentSessionRecordStore } from '../../agent-session-record-store-slot' +import { isDeepStrictEqual } from 'node:util' +import type { RuntimeStore } from '../../runtime-store-contract' +import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events' +import { crewWorkspaceNames } from './crew-workspace-names' +import { sessionCrewChanges, type CrewInvalidation } from './crew-changes' + +type CrewRuntimeWatchDependencies = { + store: RuntimeStore | null + watchChanges: (wake: (facets: CrewInvalidation) => void) => () => void + watchTransitions: (wake: () => void) => () => void + watchClient: (wake: (event: RuntimeClientEvent) => void) => () => void +} + +export function watchCrewRuntimeSources( + deps: CrewRuntimeWatchDependencies, + wake: (facets: CrewInvalidation) => void +) { + const hostIds = () => deps.store?.getWorkspaceSessionHostIds?.() ?? (['local'] as const) + const namesByHost = new Map( + hostIds().map((hostId) => [ + hostId, + crewWorkspaceNames(deps.store?.getWorkspaceSession?.(hostId)) + ]) + ) + const disposers = [ + deps.watchChanges(wake), + sessionCrewChanges.subscribe(wake), + deps.watchTransitions(() => wake(new Set(['status', 'names']))), + deps.store?.onWorkspaceSessionWritten?.((hostId) => { + for (const id of hostId === null ? hostIds() : [hostId]) { + const next = crewWorkspaceNames(deps.store?.getWorkspaceSession?.(id)) + if (!isDeepStrictEqual(namesByHost.get(id), next)) { + namesByHost.set(id, next) + wake(new Set(['names'])) + } + } + }) ?? (() => {}), + deps.store?.onSettingsChanged?.((updates) => { + if ('tabAutoGenerateTitle' in updates) { + wake(new Set(['names'])) + } + }) ?? (() => {}), + deps.watchClient((event) => { + if ( + event.type === 'terminalSideEffects' && + event.batch.facts.some((fact) => fact.kind === 'title') + ) { + wake(new Set(['names'])) + } + }) + ] + return () => disposers.forEach((dispose) => dispose()) +} + +export function readCrewRuntimeInputs( + runtime: Pick< + OrcaRuntimeService, + | 'getTerminalWorktreeIdForHandle' + | 'getTerminalHandleForPaneKey' + | 'getPaneKeyForTerminalHandle' + | 'getOrchestrationFleetAgentStatusSnapshot' + | 'orchestrationSenderNames' + >, + db: OrchestrationDb | null, + retainedDbExists: boolean, + hostKey: string +): CrewReadDependencies { + const store = peekOpenedAgentSessionRecordStore() + return { + db, + retainedDbExists, + hostKey, + records: store ? conversationRecordReader(store) : null, + liveHandle: (handle) => runtime.getTerminalWorktreeIdForHandle(handle) !== null, + handleForPane: (pane) => runtime.getTerminalHandleForPaneKey(pane), + paneForHandle: (handle) => runtime.getPaneKeyForTerminalHandle(handle), + name: (identity, taskName, records) => + runtime.orchestrationSenderNames.nameOf(identity, undefined, taskName, records), + get statuses() { + return runtime.getOrchestrationFleetAgentStatusSnapshot() + } + } +} diff --git a/src/main/runtime/orchestration/crew/crew-workspace-names.ts b/src/main/runtime/orchestration/crew/crew-workspace-names.ts new file mode 100644 index 000000000000..b3eab5e07405 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-workspace-names.ts @@ -0,0 +1,22 @@ +import type { WorkspaceSessionState } from '../../../../shared/workspace-session-state-types' + +/** Excludes scrollback, focus, bells and other session bookkeeping from name invalidation. */ +export function crewWorkspaceNames(session: WorkspaceSessionState | null | undefined) { + return session + ? { + tabs: Object.entries(session.tabsByWorktree ?? {}).map(([id, tabs]) => [ + id, + tabs.map((tab) => [tab.id, tab.title, tab.customTitle]) + ]), + chats: Object.entries(session.unifiedTabs ?? {}).map(([id, tabs]) => [ + id, + tabs.map((tab) => [tab.contentType, tab.entityId, tab.customLabel, tab.label]) + ]), + layouts: Object.entries(session.terminalLayoutsByTabId ?? {}).map(([id, layout]) => [ + id, + layout.root, + layout.titlesByLeafId + ]) + } + : null +} diff --git a/src/main/runtime/orchestration/db/schema/schema-column-probes.ts b/src/main/runtime/orchestration/db/schema/schema-column-probes.ts index 203bbfdb7d5c..dee28e5a33b0 100644 --- a/src/main/runtime/orchestration/db/schema/schema-column-probes.ts +++ b/src/main/runtime/orchestration/db/schema/schema-column-probes.ts @@ -30,6 +30,20 @@ export function createMailboxDeliveryIndexesIfPossible(this: OrchestrationDb): v this.db.exec(`CREATE INDEX IF NOT EXISTS idx_dispatch_crew_recent ON dispatch_contexts(julianday(completed_at)) WHERE status NOT IN ('pending', 'dispatched');`) } + if (this.hasColumn('dispatch_contexts', 'assignee_pane_key')) { + this.db.exec(`CREATE INDEX IF NOT EXISTS idx_crew_dispatch_pane + ON dispatch_contexts(assignee_pane_key) WHERE assignee_pane_key IS NOT NULL`) + } + if (this.hasColumn('remote_dispatch_attachments', 'terminal_handle')) { + this.db.exec(` + CREATE INDEX IF NOT EXISTS idx_crew_remote_handle ON remote_dispatch_attachments(terminal_handle); + CREATE INDEX IF NOT EXISTS idx_crew_remote_pane ON remote_dispatch_attachments(pane_key); + `) + } + if (this.hasColumn('question_threads', 'status')) { + this.db.exec(`CREATE INDEX IF NOT EXISTS idx_crew_pending_questions + ON question_threads(message_id) WHERE status = 'pending'`) + } const hasDeliveredAt = this.hasColumn('messages', 'delivered_at') if (hasDeliveredAt) { this.db.exec(` diff --git a/src/main/runtime/rpc/methods/orchestration/crew-methods.ts b/src/main/runtime/rpc/methods/orchestration/crew-methods.ts index d09be28a78d7..64f6f5486a54 100644 --- a/src/main/runtime/rpc/methods/orchestration/crew-methods.ts +++ b/src/main/runtime/rpc/methods/orchestration/crew-methods.ts @@ -1,6 +1,5 @@ import { z } from 'zod' import { CrewParty } from '../../../../../shared/orchestration-crew' -import { sessionCrewChanges } from '../../../orchestration/crew/crew-changes' import { subscribeCrew } from '../../../orchestration/crew/crew-stream' import { defineStreamingMethod } from '../../core' @@ -16,19 +15,7 @@ export const ORCHESTRATION_CREW_METHODS = [ const release = () => runtime.cleanupSubscription(key) const stop = subscribeCrew( () => runtime.getOrchestrationCrewSnapshot(party), - (wake) => { - const disposers = [ - runtime.crewChanges.subscribe(wake), - sessionCrewChanges.subscribe(wake), - runtime.agentTransitions.subscribe(wake), - runtime.onClientEvent((event) => { - if (event.type === 'terminalSideEffects' || event.type === 'workspaceViewChanged') { - wake() - } - }) - ] - return () => disposers.forEach((dispose) => dispose()) - }, + runtime.watchOrchestrationCrew, emit ) runtime.registerSubscriptionCleanup( diff --git a/src/main/runtime/runtime-orchestration-sender-names.ts b/src/main/runtime/runtime-orchestration-sender-names.ts index c410edef2c0e..cca95f63bfcf 100644 --- a/src/main/runtime/runtime-orchestration-sender-names.ts +++ b/src/main/runtime/runtime-orchestration-sender-names.ts @@ -12,7 +12,10 @@ import { type TerminalSenderNaming } from './orchestration/orchestration-sender-name' import { agentMessageSender } from './orchestration/agent-message-sender' -import { readAgentSessionRecordStore } from './orchestration/structured-session-lineage' +import { + type AgentSessionRecordReader, + readAgentSessionRecordStore +} from './orchestration/structured-session-lineage' import { terminalHostConnectionMatches } from './orchestration/worker-provider-session' type RuntimeSenderNameDeps = { @@ -78,13 +81,14 @@ export class RuntimeOrchestrationSenderNames { nameOf( party: AgentMessageSender['party'], reportedDispatchId?: string, - taskName?: string | null + taskName?: string | null, + records: AgentSessionRecordReader | null = readAgentSessionRecordStore() ): string | null { return orchestrationSenderName( party, { db: this.deps.getDb(), - records: readAgentSessionRecordStore(), + records, chatTab: (worktreeId, sessionId) => this.deps .getWorkspaceSession(worktreeId) diff --git a/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts b/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts index a02bc52d2dc6..45bc1be3352e 100644 --- a/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts +++ b/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts @@ -1,7 +1,9 @@ -import { buildCrewSnapshot } from '../../orchestration/crew/crew-read-model' +import { + readCrewRuntimeInputs, + watchCrewRuntimeSources +} from '../../orchestration/crew/crew-runtime-watch' +import { CrewReadModel } from '../../orchestration/crew/crew-read-model' import { getPublishedHostDescriptor } from '../../host-descriptor' -import { conversationRecordReader } from '../../orchestration/structured-session-lineage' -import { peekOpenedAgentSessionRecordStore } from '../../agent-session-record-store-slot' import type { AutomationsChangedPayload } from '../../../../shared/runtime-client-events' import type { ResolvedWorktree } from '../../runtime-worktree-path-identity' import { OrcaRuntimeWithPtyForegroundProcessReads } from '../../client/runtime-client-state' @@ -193,22 +195,32 @@ export abstract class OrcaRuntimeWithAutomationOperations extends OrcaRuntimeWit this.crewChanges.notify() } + private readonly crewReadModel = new CrewReadModel( + () => + readCrewRuntimeInputs( + this, + this._orchestrationDb, + existsSync(this.orchestrationDbPath()), + getPublishedHostDescriptor(this.runtimeId)?.installationId ?? this.runtimeId + ), + (wake) => + watchCrewRuntimeSources( + { + store: this.store, + watchChanges: this.crewChanges.subscribe, + watchTransitions: (listener) => this.agentTransitions.subscribe(listener), + watchClient: (listener) => this.onClientEvent(listener) + }, + wake + ) + ) + getOrchestrationCrewSnapshot(party: string) { - const store = peekOpenedAgentSessionRecordStore() - return buildCrewSnapshot(party, { - db: this._orchestrationDb, - retainedDbExists: existsSync(this.orchestrationDbPath()), - hostKey: getPublishedHostDescriptor(this.runtimeId)?.installationId ?? this.runtimeId, - records: store ? conversationRecordReader(store) : null, - liveHandle: (handle) => this.getTerminalWorktreeIdForHandle(handle) !== null, - handleForPane: (pane) => this.getTerminalHandleForPaneKey(pane), - paneForHandle: (handle) => this.getPaneKeyForTerminalHandle(handle), - name: (identity, taskName) => - this.orchestrationSenderNames.nameOf(identity, undefined, taskName), - statuses: this.getOrchestrationFleetAgentStatusSnapshot() - }) + return this.crewReadModel.read(party) } + watchOrchestrationCrew = (wake: () => void) => this.crewReadModel.subscribe(wake) + private bindMailHandBack(db: OrchestrationDb): void { db.mailHandBackListener = (handBack) => this.offerHandedBackMail(db, handBack) } diff --git a/src/main/runtime/workspaces/session-hosts/get-runtime-id.ts b/src/main/runtime/workspaces/session-hosts/get-runtime-id.ts index 8122ce6c904c..860dc740b197 100644 --- a/src/main/runtime/workspaces/session-hosts/get-runtime-id.ts +++ b/src/main/runtime/workspaces/session-hosts/get-runtime-id.ts @@ -1,3 +1,5 @@ +import { crewWorkspaceNames } from '../../orchestration/crew/crew-workspace-names' +import { isDeepStrictEqual } from 'node:util' import { OrcaRuntimeWithHasExactPersistedTerminalSurfaceIdentity } from '../persisted-surfaces/has-exact-persisted-terminal-surface-identity' import type { OrchestrationEnvironmentCallOptions, @@ -196,7 +198,11 @@ export abstract class OrcaRuntimeWithGetRuntimeId extends OrcaRuntimeWithHasExac } setWorkspaceSessionForWorktree(worktreeId: string, session: WorkspaceSessionState): void { + const before = crewWorkspaceNames(this.workspaceSessions.get(worktreeId)) this.workspaceSessions.setForWorktree(worktreeId, session) + if (!isDeepStrictEqual(before, crewWorkspaceNames(this.workspaceSessions.get(worktreeId)))) { + this.crewChanges.notify(new Set(['names'])) + } } protected getKnownWorkspaceSessionWorktreeIds(): Set { diff --git a/src/main/runtime/workspaces/workspace-process-listing.ts b/src/main/runtime/workspaces/workspace-process-listing.ts index 87f8a60c7687..91d414099703 100644 --- a/src/main/runtime/workspaces/workspace-process-listing.ts +++ b/src/main/runtime/workspaces/workspace-process-listing.ts @@ -283,7 +283,7 @@ export abstract class OrcaRuntimeWithGetWorktreePs extends OrcaRuntimeWithWorktr onRequestFailure: (failure) => this.onStructuredRequestFailureForErrorMail(failure), // Structured chat has no CLI hooks; this projection drives first-work renaming. onSessionStatusChanged: (summary, options) => { - this.crewChanges.notify() + this.crewChanges.notify(new Set(['status', 'names'])) this.onStructuredSessionStatusForMail(summary) nameChat(summary, options) void maybeAutoRenameWorkspaceOnFirstStructuredTurn( From dd9c204769766479be615233f6315b38baa3a6b4 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 04:59:15 -0700 Subject: [PATCH 008/164] Remove package manager lockfile churn from hook --- pnpm-lock.yaml | 25 ------------------------- 1 file changed, 25 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9df280f23651..b5bfd4cee68d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6,9 +6,6 @@ importers: .: configDependencies: {} packageManagerDependencies: - '@pnpm/exe': - specifier: 12.14.0 - version: 12.14.0 pnpm: specifier: 12.14.0 version: 12.14.0 @@ -92,11 +89,6 @@ packages: cpu: [x64] os: [win32] - '@pnpm/exe@12.14.0': - resolution: {integrity: sha512-iZCbiKegYUapNVkZY4O8vjXt9EF/j34LbDvew6qUM5g/HrxMY38cFJaoE8+5ZWQfbt2YCsLfufI5TTh+GxUbWw==} - engines: {node: '>=18.*'} - hasBin: true - pnpm@12.14.0: resolution: {integrity: sha512-wYum2HmT09Fky16JSPMrLAbuhUSH4GzY2GeBNC+z5btGNDZwNHEehoArqpw3vqkGzhkprQjXCITJfYAd8TOJpg==} engines: {node: '>=18.*'} @@ -146,23 +138,6 @@ snapshots: '@pnpm/exe.win32-x64@12.14.0': optional: true - '@pnpm/exe@12.14.0': - optionalDependencies: - '@pnpm/exe.android-arm64': 12.14.0 - '@pnpm/exe.android-x64': 12.14.0 - '@pnpm/exe.darwin-arm64': 12.14.0 - '@pnpm/exe.darwin-x64': 12.14.0 - '@pnpm/exe.freebsd-x64': 12.14.0 - '@pnpm/exe.linux-arm64': 12.14.0 - '@pnpm/exe.linux-arm64-musl': 12.14.0 - '@pnpm/exe.linux-ppc64': 12.14.0 - '@pnpm/exe.linux-riscv64': 12.14.0 - '@pnpm/exe.linux-s390x': 12.14.0 - '@pnpm/exe.linux-x64': 12.14.0 - '@pnpm/exe.linux-x64-musl': 12.14.0 - '@pnpm/exe.win32-arm64': 12.14.0 - '@pnpm/exe.win32-x64': 12.14.0 - pnpm@12.14.0: optionalDependencies: '@pnpm/exe.android-arm64': 12.14.0 From 7d1cabf90e4f188ba2aadd52ce8a67a223e38639 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 01:17:36 -0700 Subject: [PATCH 009/164] =?UTF-8?q?Show=20each=20pane=E2=80=99s=20agent=20?= =?UTF-8?q?crew=20with=20open=20and=20copy=20actions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../native-chat/NativeChatResolvedView.tsx | 23 +- .../NativeChatStructuredActivity.tsx | 45 +++ .../NativeChatStructuredSession.tsx | 226 ++++++------ .../native-chat/native-chat-split-shortcut.ts | 23 ++ .../use-orchestration-crew.test.tsx | 168 +++++++++ .../native-chat/use-orchestration-crew.ts | 189 ++++++++++ .../NativeChatCrewPanel.tsx | 21 ++ .../OrchestrationCrewPanel.tsx | 336 ++++++++++++++++++ .../TerminalCrewPortals.tsx | 46 +++ .../use-terminal-crew-identity.ts | 65 ++++ .../terminal-pane/TerminalPaneSurface.tsx | 2 + .../terminal-pane/terminal-handle-copy.ts | 15 +- .../activate-ai-vault-structured-session.ts | 9 +- .../src/lib/open-agent-message-sender.ts | 57 +++ 14 files changed, 1086 insertions(+), 139 deletions(-) create mode 100644 src/renderer/src/components/native-chat/NativeChatStructuredActivity.tsx create mode 100644 src/renderer/src/components/native-chat/use-orchestration-crew.test.tsx create mode 100644 src/renderer/src/components/native-chat/use-orchestration-crew.ts create mode 100644 src/renderer/src/components/orchestration-crew/NativeChatCrewPanel.tsx create mode 100644 src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx create mode 100644 src/renderer/src/components/orchestration-crew/TerminalCrewPortals.tsx create mode 100644 src/renderer/src/components/orchestration-crew/use-terminal-crew-identity.ts diff --git a/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx b/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx index eec1b20b54ec..ffca66a62631 100644 --- a/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx +++ b/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx @@ -1,3 +1,6 @@ +import { NativeChatCrewPanel } from '../orchestration-crew/NativeChatCrewPanel' +import { useTerminalCrewIdentity } from '../orchestration-crew/use-terminal-crew-identity' +import { useNativeChatTabOwnerWorktreeId } from './use-native-chat-tab-owner' import { cn } from '@/lib/utils' import { NATIVE_CHAT_APPEARANCE_ROOT_CLASS } from './native-chat-appearance-style' import { useNativeChatStoreAppearanceStyle } from './use-native-chat-store-appearance-style' @@ -56,8 +59,7 @@ import { useNativeChatFileLinkContext } from './use-native-chat-file-link-contex import { useRecheckNativeChatFileLinksWhenTurnEnds } from './use-native-chat-file-link-existence' import { useNativeChatLocalCommandAnswer } from './use-native-chat-local-command-answer' import { useNativeChatImageRuntimeContext } from './native-chat-image-runtime-context' -import { matchNativeChatSplitShortcut } from './native-chat-split-shortcut' -import { getShortcutPlatform } from '@/lib/shortcut-platform' +import { handleNativeChatSplitShortcut } from './native-chat-split-shortcut' import { formatShortcutLabel } from '@/hooks/useShortcutLabel' export function NativeChatResolvedView({ @@ -77,6 +79,8 @@ export function NativeChatResolvedView({ // Route reads/subscriptions through the pane’s runtime owner; null retains local routing. const selectOwner = useMemo(() => createNativeChatRuntimeSelector(terminalTabId), [terminalTabId]) const runtimeEnvironmentId = useAppStore(selectOwner) + const ownerWorktreeId = useNativeChatTabOwnerWorktreeId(terminalTabId) + const crew = useTerminalCrewIdentity(paneKey, targetPtyId, ownerWorktreeId) const keybindings = useAppStore((s) => s.keybindings) const imageRuntimeContext = useNativeChatImageRuntimeContext(terminalTabId) const session = useNativeChatRetainedSession({ @@ -327,17 +331,7 @@ export function NativeChatResolvedView({ }} onKeyDownCapture={(event) => { find.onKeyDownCapture(event) - const splitDirection = event.repeat - ? null - : matchNativeChatSplitShortcut(event, getShortcutPlatform(), keybindings) - if (splitDirection && contextMenuActions) { - event.preventDefault() - event.stopPropagation() - if (splitDirection === 'right') { - contextMenuActions.onSplitRight() - } else { - contextMenuActions.onSplitDown() - } + if (handleNativeChatSplitShortcut(event, keybindings, contextMenuActions)) { return } rootInput.onKeyDownCapture(event) @@ -345,11 +339,12 @@ export function NativeChatResolvedView({ onContextMenuCapture={contextMenu.onContextMenuCapture} className={cn( NATIVE_CHAT_APPEARANCE_ROOT_CLASS, - 'flex h-full min-h-0 w-full flex-col focus:outline-none' + 'relative flex h-full min-h-0 w-full flex-col focus:outline-none' )} style={appearanceStyle} data-native-chat-scheme={appearanceStyle.colorScheme} > +
{find.isOpen ? : null} {viewState.kind === 'loading' ? ( diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredActivity.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredActivity.tsx new file mode 100644 index 000000000000..1a402672b7cc --- /dev/null +++ b/src/renderer/src/components/native-chat/NativeChatStructuredActivity.tsx @@ -0,0 +1,45 @@ +import type { useStructuredAgentSession } from './use-structured-agent-session' +import type { NativeChatStructuredComposerTransport } from './native-chat-composer-types' +import { NativeChatStructuredSessionStatus } from './NativeChatStructuredSessionStatus' +import { NativeChatStructuredGoalStrip } from './NativeChatStructuredGoalStrip' + +export function NativeChatStructuredActivity(props: { + controller: Pick< + ReturnType, + | 'backgroundTasks' + | 'stopBackgroundTask' + | 'threadGoal' + | 'isWorking' + | 'turnId' + | 'workingStartedAt' + > + sessionId: string + paneKey: string + isVisible: boolean + transport: NativeChatStructuredComposerTransport + showGoal: boolean +}): React.JSX.Element { + const { controller } = props + return ( + <> + + {props.showGoal ? ( + + ) : null} + + ) +} diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx index 90e898b5cdc0..cc258d9cda7f 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx @@ -1,3 +1,4 @@ +import { NativeChatCrewPanel } from '../orchestration-crew/NativeChatCrewPanel' import { useNativeChatHandOff } from './use-native-chat-hand-off' import { cn } from '@/lib/utils' import { NATIVE_CHAT_APPEARANCE_ROOT_CLASS } from './native-chat-appearance-style' @@ -33,7 +34,7 @@ import { useStructuredAgentSession } from './use-structured-agent-session' import { useNativeChatImageRuntimeContext } from './native-chat-image-runtime-context' import { useStructuredNativeChatPaneCommands } from './use-structured-native-chat-pane-commands' import type { NativeChatStructuredViewProps } from './native-chat-view-types' -import { NativeChatStructuredSessionStatus } from './NativeChatStructuredSessionStatus' +import { NativeChatStructuredActivity } from './NativeChatStructuredActivity' import { useNativeChatLaunchDraftSignal } from './use-native-chat-launch-draft-adoption' import { useNativeChatInterruptedContinuation } from './NativeChatInterruptedContinue' import { NativeChatOrcaStopContext } from './native-chat-orca-stop-context' @@ -51,7 +52,6 @@ import { chatApprovalFromJournal } from '../../../../shared/native-chat-interact import { useAppStore } from '../../store' import { structuredAgentLabel } from '@/lib/structured-agent-session-launch-label' import { useNativeChatStructuredComposerTransport } from './use-native-chat-structured-composer-transport' -import { NativeChatStructuredGoalStrip } from './NativeChatStructuredGoalStrip' import { nativeChatPaneHeader } from './NativeChatPaneHeader' import { structuredAgentSessionReadFailureNotice } from './structured-agent-session-read-failure-notice' import { useStructuredAgentSessionDeliveryNotices } from './use-structured-agent-session-delivery-notices' @@ -287,126 +287,118 @@ export function NativeChatStructuredSession( data-native-chat-scheme={appearanceStyle.colorScheme} > {nativeChatPaneHeader(props, ownerWorktreeId, appearanceStyle.colorScheme, handOff)} - - {find.isOpen ? : null} - {viewState.kind === 'loading' || (viewState.kind === 'error' && !readFailure) ? ( - historyPhase !== 'unread' && - ) : viewState.kind === 'error' ? ( - - ) : viewState.kind === 'empty' ? ( - - ) : ( - - - - - - - - )} - - {readFailure?.final ? null : ( - <> - {/* Keep queued drafts outside the transcript and above the background-task dock. */} - - - {prompt ? null : ( - + + + {find.isOpen ? : null} + {viewState.kind === 'loading' || (viewState.kind === 'error' && !readFailure) ? ( + historyPhase !== 'unread' && + ) : viewState.kind === 'error' ? ( + + ) : viewState.kind === 'empty' ? ( + + ) : ( + + + + + + + )} - {composerShown ? null : } - {prompt && approval ? ( - - void promptResponse.respond(prompt, { kind: 'option', optionId }) - } - isSubmitting={promptResponse.holds(prompt)} - onCancel={cancelPrompt} - shouldFocus={!promptsUnanswerable && props.isVisible && props.isFocusedGroup} - {...fileLinkProps} - /> - ) : null} - {prompt && questionBody ? ( - void promptResponse.respond(prompt, response)} - isSubmitting={promptResponse.holds(prompt)} - onCancel={cancelPrompt} - shouldFocus={!promptsUnanswerable && props.isVisible && props.isFocusedGroup} - answerInputRef={questionAnswerInputRef} + + {readFailure?.final ? null : ( + <> + {/* Keep queued drafts outside the transcript and above the background-task dock. */} + - ) : null} - {prompt ? null : } - {composerShown && } - {composerShown ? ( - - ) : null} - - )} + {composerShown ? null : } + {prompt && approval ? ( + + void promptResponse.respond(prompt, { kind: 'option', optionId }) + } + isSubmitting={promptResponse.holds(prompt)} + onCancel={cancelPrompt} + shouldFocus={!promptsUnanswerable && props.isVisible && props.isFocusedGroup} + {...fileLinkProps} + /> + ) : null} + {prompt && questionBody ? ( + void promptResponse.respond(prompt, response)} + isSubmitting={promptResponse.holds(prompt)} + onCancel={cancelPrompt} + shouldFocus={!promptsUnanswerable && props.isVisible && props.isFocusedGroup} + answerInputRef={questionAnswerInputRef} + /> + ) : null} + {prompt ? null : } + {composerShown && } + {composerShown ? ( + + ) : null} + + )} +
{paneCommands.menu} {handOff.dialog} diff --git a/src/renderer/src/components/native-chat/native-chat-split-shortcut.ts b/src/renderer/src/components/native-chat/native-chat-split-shortcut.ts index 5ded10fa6bb8..97f5443c4253 100644 --- a/src/renderer/src/components/native-chat/native-chat-split-shortcut.ts +++ b/src/renderer/src/components/native-chat/native-chat-split-shortcut.ts @@ -1,3 +1,5 @@ +import type { KeyboardEvent } from 'react' +import { getShortcutPlatform } from '@/lib/shortcut-platform' import { keybindingMatchesAction, type KeybindingInput, @@ -19,3 +21,24 @@ export function matchNativeChatSplitShortcut( } return null } + +export function handleNativeChatSplitShortcut( + event: KeyboardEvent, + keybindings: KeybindingOverrides, + actions?: { onSplitRight: () => void; onSplitDown: () => void } +): boolean { + const direction = event.repeat + ? null + : matchNativeChatSplitShortcut(event, getShortcutPlatform(), keybindings) + if (!direction || !actions) { + return false + } + event.preventDefault() + event.stopPropagation() + if (direction === 'right') { + actions.onSplitRight() + } else { + actions.onSplitDown() + } + return true +} diff --git a/src/renderer/src/components/native-chat/use-orchestration-crew.test.tsx b/src/renderer/src/components/native-chat/use-orchestration-crew.test.tsx new file mode 100644 index 000000000000..250e8e88d908 --- /dev/null +++ b/src/renderer/src/components/native-chat/use-orchestration-crew.test.tsx @@ -0,0 +1,168 @@ +// @vitest-environment happy-dom +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' +import type { RuntimeRpcSubscriptionHandlers } from '@/runtime/runtime-rpc-subscribe' +import { replaceRuntimeEnvironmentRevisions } from '@/runtime/runtime-environment-revision' +import { useOrchestrationCrew } from './use-orchestration-crew' + +const rig = vi.hoisted(() => ({ + streams: [] as { + target: RuntimeClientTarget + party: string + handlers: RuntimeRpcSubscriptionHandlers + unsubscribe: ReturnType + }[], + listeners: new Set<() => void>(), + state: { + runtimeStatusByEnvironmentId: new Map([ + [ + 'crew-host', + { status: { runtimeId: 'runtime-one' }, connectionGeneration: 1, hostContactEpoch: 1 } + ] + ]) + } +})) +vi.mock('@/runtime/runtime-rpc-subscribe', () => ({ + subscribeRuntimeRpc: vi.fn( + async ( + target: RuntimeClientTarget, + _method: string, + params: { party: string }, + handlers: RuntimeRpcSubscriptionHandlers + ) => { + const stream = { target, party: params.party, handlers, unsubscribe: vi.fn() } + rig.streams.push(stream) + return { unsubscribe: stream.unsubscribe } + } + ) +})) +vi.mock('@/store', async () => { + const { useSyncExternalStore } = await import('react') + return { + useAppStore: (select: (state: typeof rig.state) => unknown) => + useSyncExternalStore( + (wake) => { + rig.listeners.add(wake) + return () => rig.listeners.delete(wake) + }, + () => select(rig.state) + ) + } +}) +afterEach(() => { + cleanup() + rig.streams.length = 0 +}) +const local = { kind: 'local' } as const +const remote = { kind: 'environment', environmentId: 'crew-host' } as const +function Pane({ + party, + target = local, + renderCount +}: { + party: string + target?: RuntimeClientTarget + renderCount: () => void +}) { + const crew = useOrchestrationCrew(target, party) + renderCount() + return ( + + {crew.status === 'ok' ? crew.sections.managing.length : 'unknown'} + + ) +} +function publish(index: number, pending = false) { + const handlers = rig.streams[index].handlers + handlers.onEvent({ type: 'begin', status: 'ok' }) + handlers.onEvent({ + type: 'rows', + section: 'managing', + rows: [ + { + partyKey: 'host-worker', + role: 'worker', + label: 'Worker', + agentKind: 'codex', + status: 'working', + sendAddress: 'term_worker', + ...(pending + ? { pendingQuestion: { preview: 'Which option?', at: new Date(0).toISOString() } } + : {}) + } + ] + }) + return () => handlers.onEvent({ type: 'complete' }) +} + +it('retains the collapsed/no-crew wake, publishes only complete replacements and isolates parties', async () => { + const first = vi.fn(), + other = vi.fn() + const view = render( + <> + + + + ) + await act(async () => {}) + expect(rig.streams).toHaveLength(2) + act(() => { + rig.streams[0].handlers.onEvent({ type: 'begin', status: 'ok' }) + rig.streams[0].handlers.onEvent({ type: 'complete' }) + }) + expect(view.getByTestId('term_first').textContent).toBe('0') + const beforeOther = other.mock.calls.length + let complete = () => {} + act(() => { + complete = publish(0, true) + }) + expect(view.getByTestId('term_first').textContent).toBe('0') + act(complete) + expect(view.getByTestId('term_first').textContent).toBe('1') + expect(other).toHaveBeenCalledTimes(beforeOther) + const before = first.mock.calls.length + act(() => publish(0, true)()) + expect(first).toHaveBeenCalledTimes(before) + act(() => publish(0, false)()) + expect(first).toHaveBeenCalledTimes(before + 1) + view.unmount() + expect(rig.streams.every((stream) => stream.unsubscribe.mock.calls.length === 1)).toBe(true) + expect(rig.listeners.size).toBe(0) +}) + +it('caches old-host refusal per generation and resubscribes after reconnect or pairing changes', async () => { + replaceRuntimeEnvironmentRevisions([{ id: 'crew-host', createdAt: 1 }]) + const view = render() + await act(async () => {}) + act(() => rig.streams[0].handlers.onError({ code: 'method_not_found' })) + expect(view.getByTestId('term_old').textContent).toBe('unknown') + view.rerender() + await act(async () => {}) + expect(rig.streams).toHaveLength(1) + act(() => { + rig.state = { + runtimeStatusByEnvironmentId: new Map([ + [ + 'crew-host', + { status: { runtimeId: 'runtime-two' }, connectionGeneration: 2, hostContactEpoch: 2 } + ] + ]) + } + rig.listeners.forEach((wake) => wake()) + }) + await act(async () => {}) + expect(rig.streams).toHaveLength(2) + act(() => publish(1)()) + expect(view.getByTestId('term_plain').textContent).toBe('1') + act(() => rig.streams[1].handlers.onClose()) + expect(view.getByTestId('term_plain').textContent).toBe('unknown') + act(() => + replaceRuntimeEnvironmentRevisions([{ id: 'crew-host', createdAt: 1, pairingRevision: 2 }]) + ) + await act(async () => {}) + expect(rig.streams).toHaveLength(3) + expect(rig.streams[1].unsubscribe).toHaveBeenCalledOnce() + view.unmount() + expect(rig.streams[2].unsubscribe).toHaveBeenCalledOnce() +}) diff --git a/src/renderer/src/components/native-chat/use-orchestration-crew.ts b/src/renderer/src/components/native-chat/use-orchestration-crew.ts new file mode 100644 index 000000000000..59547293b783 --- /dev/null +++ b/src/renderer/src/components/native-chat/use-orchestration-crew.ts @@ -0,0 +1,189 @@ +import { useCallback, useMemo, useSyncExternalStore } from 'react' +import { useAppStore } from '@/store' +import { subscribeRuntimeRpc } from '@/runtime/runtime-rpc-subscribe' +import { + getRuntimeEnvironmentRevision, + onRuntimeEnvironmentRevisionsChanged, + onRuntimeEnvironmentsRetired +} from '@/runtime/runtime-environment-revision' +import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' +import { + CrewFrame, + emptyCrew, + type OrchestrationCrewSnapshot +} from '../../../../shared/orchestration-crew' + +const UNKNOWN = emptyCrew('unknown') +const unsupported = new Set() +const entries = new Map() + +export class CrewSubscription { + snapshot = UNKNOWN + private pending: OrchestrationCrewSnapshot | undefined + private readonly listeners = new Set<() => void>() + private stop: (() => void) | undefined + private active = false + constructor( + private readonly target: RuntimeClientTarget, + private readonly party: string, + private readonly generation: string, + private readonly onIdle?: () => void + ) {} + private publish(snapshot: OrchestrationCrewSnapshot) { + if (JSON.stringify(this.snapshot) === JSON.stringify(snapshot)) { + return + } + this.snapshot = snapshot + this.listeners.forEach((listener) => listener()) + } + subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener) + if (!this.active && !unsupported.has(this.generation)) { + this.active = true + let alive = true + this.stop = () => { + alive = false + } + void subscribeRuntimeRpc( + this.target, + 'orchestration.crewSubscribe', + { party: this.party }, + { + onEvent: (value) => { + if (!alive) { + return + } + const parsed = CrewFrame.safeParse(value) + if (!parsed.success) { + this.publish(UNKNOWN) + return + } + const frame = parsed.data + if (frame.type === 'begin') { + this.pending = emptyCrew(frame.status) + } else if (frame.type === 'rows') { + this.pending?.sections[frame.section].push(...frame.rows) + } else if (frame.type === 'complete' && this.pending) { + this.publish(this.pending) + this.pending = undefined + } else if (frame.type === 'end') { + this.publish(UNKNOWN) + } + }, + onError: (error) => { + if (!alive) { + return + } + if ( + typeof error === 'object' && + error !== null && + 'code' in error && + error.code === 'method_not_found' + ) { + unsupported.add(this.generation) + } + this.pending = undefined + this.publish(UNKNOWN) + }, + onClose: () => { + if (alive) { + this.pending = undefined + this.publish(UNKNOWN) + } + } + } + ) + .then((subscription) => { + if (!alive) { + subscription.unsubscribe() + } else { + this.stop = () => { + alive = false + subscription.unsubscribe() + } + } + }) + .catch(() => { + if (alive) { + this.publish(UNKNOWN) + } + }) + } + return () => { + this.listeners.delete(listener) + if (this.listeners.size === 0) { + this.stop?.() + this.stop = undefined + this.active = false + this.pending = undefined + this.snapshot = UNKNOWN + this.onIdle?.() + } + } + } + read = (): OrchestrationCrewSnapshot => this.snapshot +} + +export function useOrchestrationCrew( + target: RuntimeClientTarget | null, + party: string | null +): OrchestrationCrewSnapshot { + const environmentId = target?.kind === 'environment' ? target.environmentId : null + const pairingRevision = useSyncExternalStore( + useCallback( + (wake) => { + const changed = (ids: readonly string[]) => { + if (environmentId && ids.includes(environmentId)) { + wake() + } + } + const dispose = onRuntimeEnvironmentRevisionsChanged(changed) + const retire = onRuntimeEnvironmentsRetired(changed) + return () => { + dispose() + retire() + } + }, + [environmentId] + ), + () => (environmentId ? getRuntimeEnvironmentRevision(environmentId) : undefined) + ) + const generation = useAppStore((state) => { + if (!environmentId) { + return 'local' + } + const entry = state.runtimeStatusByEnvironmentId?.get(environmentId) + if (!entry?.status) { + return `offline:${environmentId}` + } + return JSON.stringify([ + environmentId, + pairingRevision, + entry.status.runtimeId, + entry.connectionGeneration, + entry.hostContactEpoch + ]) + }) + const key = target && party ? JSON.stringify([target, party, generation]) : null + const entry = useMemo(() => { + if (!key || !target || !party || generation.startsWith('offline:')) { + return null + } + let entry = entries.get(key) + if (!entry) { + const created = new CrewSubscription(target, party, generation, () => { + if (entries.get(key) === created) { + entries.delete(key) + } + }) + entry = created + entries.set(key, entry) + } + return entry + }, [key, generation, target, party]) + const subscribe = useCallback( + (listener: () => void) => entry?.subscribe(listener) ?? (() => {}), + [entry] + ) + return useSyncExternalStore(subscribe, entry?.read ?? (() => UNKNOWN)) +} diff --git a/src/renderer/src/components/orchestration-crew/NativeChatCrewPanel.tsx b/src/renderer/src/components/orchestration-crew/NativeChatCrewPanel.tsx new file mode 100644 index 000000000000..5eab3d5780af --- /dev/null +++ b/src/renderer/src/components/orchestration-crew/NativeChatCrewPanel.tsx @@ -0,0 +1,21 @@ +import { formatOrcaSessionAddress, isOrcaSessionId } from '../../../../shared/orca-session-address' +import { OrchestrationCrewPanel } from './OrchestrationCrewPanel' +import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' + +export function NativeChatCrewPanel({ + target, + party: suppliedParty, + sessionId +}: { + target: RuntimeClientTarget | null + party?: string | null + sessionId?: string +}): React.JSX.Element | null { + const party = + suppliedParty ?? + (sessionId && isOrcaSessionId(sessionId) ? formatOrcaSessionAddress(sessionId) : null) + if (!target || !party) { + return null + } + return +} diff --git a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx new file mode 100644 index 000000000000..169851d3774d --- /dev/null +++ b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx @@ -0,0 +1,336 @@ +import { useLayoutEffect, useRef, useState } from 'react' +import { + ChevronDown, + ChevronRight, + ExternalLink, + MoreHorizontal, + PanelRight, + PanelRightClose +} from 'lucide-react' +import { toast } from 'sonner' +import { Button } from '@/components/ui/button' +import { Badge } from '@/components/ui/badge' +import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger +} from '@/components/ui/dropdown-menu' +import { AgentIcon } from '@/lib/agent-catalog' +import { isTuiAgent } from '../../../../shared/tui-agent-config' +import type { + OrchestrationCrewRow, + OrchestrationCrewSnapshot +} from '../../../../shared/orchestration-crew' +import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' +import { useOrchestrationCrew } from '../native-chat/use-orchestration-crew' +import { openOrchestrationCrewAgent } from '@/lib/open-agent-message-sender' +import { cn } from '@/lib/utils' + +function Avatar({ row }: { row: OrchestrationCrewRow }) { + return ( + + ) +} +function Dot({ row }: { row: OrchestrationCrewRow }) { + return ( + + ) +} +function Time({ at }: { at?: string }) { + if (!at) { + return null + } + const date = new Date(at.includes('T') ? at : `${at.replace(' ', 'T')}Z`) + return Number.isFinite(date.getTime()) ? ( + + ) : null +} +function IconButton({ + label, + children, + ...props +}: React.ComponentProps & { label: string }) { + return ( + + + + + + {label} + + + ) +} + +type PanelProps = { + target: RuntimeClientTarget + party: string +} +export function OrchestrationCrewPanel(props: PanelProps): React.JSX.Element | null { + const snapshot = useOrchestrationCrew(props.target, props.party) + return +} + +function CrewPanelContent({ + target, + snapshot +}: PanelProps & { snapshot: OrchestrationCrewSnapshot }): React.JSX.Element | null { + const [open, setOpen] = useState(false) + const tab = useRef(null) + const collapse = useRef(null) + const restore = useRef(false) + useLayoutEffect(() => { + if (open) { + collapse.current?.focus({ preventScroll: true }) + } else if (restore.current) { + tab.current?.focus({ preventScroll: true }) + } + }, [open]) + const { managedBy, managing, talkingWith } = snapshot.sections + const all = [...managedBy, ...managing, ...talkingWith] + if (snapshot.status !== 'ok' || all.length === 0) { + return null + } + const pending = all.filter((row) => row.pendingQuestion).length + const label = managing.length + ? `${managing.length} workers` + : managedBy.length + ? `Managed by ${managedBy[0].label}` + : `Talking with ${talkingWith[0].label}` + const changeOpen = (value: boolean) => { + restore.current = true + setOpen(value) + } + const sections = [ + ['Managed by', managedBy], + ['Managing', managing], + ['Talking with', talkingWith] + ] as const + return ( +
event.stopPropagation()} + onMouseDown={(event) => event.stopPropagation()} + onKeyDown={(event) => { + event.stopPropagation() + if (event.key === 'Escape' && open) { + event.preventDefault() + changeOpen(false) + } + }} + > + {open ? ( + + ) : ( + + )} +
+ ) +} + +function CrewRowView({ row, target }: { row: OrchestrationCrewRow; target: RuntimeClientTarget }) { + const [disclosure, setDisclosure] = useState<{ question?: string; expanded: boolean }>() + const question = row.pendingQuestion?.at + const expanded = + disclosure?.question === question + ? (disclosure?.expanded ?? Boolean(question)) + : Boolean(question) + const open = () => { + void openOrchestrationCrewAgent(row, target) + } + return ( +
+
+ +
+
+
+ {expanded ? ( +
+
Task
+
+ {row.task ? ( + <> + + {row.task.state} + + {row.task.title} + + ) : ( + 'No shared task' + )} +
+ {row.progress ? ( + <> +
Progress
+
{row.progress}
+ + ) : null} + {row.pendingQuestion ? ( + <> +
Asks you
+
{row.pendingQuestion.preview}
+ + ) : row.latest ? ( + <> +
Latest
+
+ + {row.latest.direction === 'to' ? 'To' : 'From'} {row.label} ·{' '} + +
+ {row.latest.preview} +
+
+ + ) : null} +
+ ) : null} +
+ ) +} diff --git a/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.tsx b/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.tsx new file mode 100644 index 000000000000..0860195add6b --- /dev/null +++ b/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.tsx @@ -0,0 +1,46 @@ +import { createPortal } from 'react-dom' +import { useAppStore } from '@/store' +import type { ManagedPane } from '@/lib/pane-manager/pane-manager' +import type { TerminalPaneController } from '../terminal-pane/use-terminal-pane-controller' +import { makePaneKey } from '../../../../shared/stable-pane-id' +import { useTerminalCrewIdentity } from './use-terminal-crew-identity' +import { OrchestrationCrewPanel } from './OrchestrationCrewPanel' + +function TerminalCrewPortal({ + pane, + controller +}: { + pane: ManagedPane + controller: TerminalPaneController +}) { + const { tabId, worktreeId, paneTransportsRef } = controller + const paneKey = makePaneKey(tabId, pane.leafId) + const boundPtyId = useAppStore( + (state) => state.terminalLayoutsByTabId[tabId]?.ptyIdsByLeafId?.[pane.leafId] ?? null + ) + const transport = paneTransportsRef.current.get(pane.id) + const { target, party } = useTerminalCrewIdentity( + paneKey, + transport?.getPtyId() ?? boundPtyId, + worktreeId + ) + if (!target || !party || !transport) { + return null + } + return createPortal( + , + pane.container, + `crew-${pane.id}` + ) +} +export function TerminalCrewPortals({ controller }: { controller: TerminalPaneController }) { + return ( + <> + {controller.managedPanes.map((pane) => + controller.effectiveChatViewMode && controller.chatPane?.id === pane.id ? null : ( + + ) + )} + + ) +} diff --git a/src/renderer/src/components/orchestration-crew/use-terminal-crew-identity.ts b/src/renderer/src/components/orchestration-crew/use-terminal-crew-identity.ts new file mode 100644 index 000000000000..52dc3be5ce4f --- /dev/null +++ b/src/renderer/src/components/orchestration-crew/use-terminal-crew-identity.ts @@ -0,0 +1,65 @@ +import { useEffect, useMemo, useState } from 'react' +import { useAppStore } from '@/store' +import { getKnownExecutionHostIdForWorktree } from '@/lib/worktree-runtime-owner' +import { parseExecutionHostId } from '../../../../shared/execution-host' +import { parseRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id' +import { parsePaneKey } from '../../../../shared/stable-pane-id' +import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' +import { resolveTerminalHandleForPane } from '../terminal-pane/terminal-handle-copy' + +/** One boundary from the pane's actual host/binding to a public crew party. */ +export function useTerminalCrewIdentity( + paneKey: string, + ptyId: string | null, + worktreeId: string | null +) { + const hostId = useAppStore((state) => + worktreeId ? getKnownExecutionHostIdForWorktree(state, worktreeId) : null + ) + const remote = ptyId ? parseRemoteRuntimePtyId(ptyId) : null + const host = parseExecutionHostId(hostId) + const environmentId = + remote?.environmentId ?? (host?.kind === 'runtime' ? host.environmentId : null) + const locallyOwned = host?.kind === 'local' || host?.kind === 'ssh' + const target = useMemo( + () => + environmentId + ? { kind: 'environment', environmentId } + : locallyOwned + ? { kind: 'local' } + : null, + [environmentId, locallyOwned] + ) + const isRemote = remote !== null + const key = JSON.stringify([paneKey, ptyId, target]) + const [resolved, setResolved] = useState<{ key: string; party: string }>() + useEffect(() => { + if (!target || !ptyId || isRemote) { + return + } + const pane = parsePaneKey(paneKey) + if (!pane) { + return + } + let alive = true + void resolveTerminalHandleForPane({ + tabId: pane.tabId, + leafId: pane.leafId, + ptyId, + callRuntime: window.api.runtime.call + }) + .then((party) => { + if (alive) { + setResolved({ key, party }) + } + }) + .catch(() => {}) + return () => { + alive = false + } + }, [key, paneKey, ptyId, target, isRemote]) + return { + target, + party: target ? (remote?.handle ?? (resolved?.key === key ? resolved.party : null)) : null + } +} diff --git a/src/renderer/src/components/terminal-pane/TerminalPaneSurface.tsx b/src/renderer/src/components/terminal-pane/TerminalPaneSurface.tsx index d0b39b1dce2a..4ad4578037f4 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPaneSurface.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPaneSurface.tsx @@ -1,3 +1,4 @@ +import { TerminalCrewPortals } from '../orchestration-crew/TerminalCrewPortals' import { createPortal } from 'react-dom' import { TerminalPaneFileDropOwner } from './TerminalPaneFileDropOwner' import { makePaneKey } from '../../../../shared/stable-pane-id' @@ -186,6 +187,7 @@ export function TerminalPaneSurface({ paneTransportsRef={paneTransportsRef} /> ))} + Promise } -export async function copyTerminalHandleForPane({ +export async function copyTerminalHandleForPane(args: CopyTerminalHandleDeps): Promise { + const handle = await resolveTerminalHandleForPane(args) + await args.writeClipboardText(handle) + return handle +} + +export async function resolveTerminalHandleForPane({ tabId, leafId, ptyId, - callRuntime, - writeClipboardText -}: CopyTerminalHandleDeps): Promise { + callRuntime +}: Omit): Promise { // Use the paired owner’s bound handle; this desktop’s runtime cannot resolve the server’s pane. if (ptyId && isRemoteRuntimePtyId(ptyId)) { const ownerHandle = parseRemoteRuntimePtyId(ptyId)?.handle if (!ownerHandle) { throw new Error('Terminal ID unavailable') } - await writeClipboardText(ownerHandle) return ownerHandle } const paneKey = makePaneKey(tabId, leafId) @@ -45,7 +49,6 @@ export async function copyTerminalHandleForPane({ if (!handle) { throw new Error('Terminal ID unavailable') } - await writeClipboardText(handle) return handle } diff --git a/src/renderer/src/lib/activate-ai-vault-structured-session.ts b/src/renderer/src/lib/activate-ai-vault-structured-session.ts index 9a76c516fe48..eb65372c2044 100644 --- a/src/renderer/src/lib/activate-ai-vault-structured-session.ts +++ b/src/renderer/src/lib/activate-ai-vault-structured-session.ts @@ -79,7 +79,8 @@ const defaultDeps: StructuredSessionActivationDeps = { export async function activateAiVaultStructuredSession( session: Pick, deps: StructuredSessionActivationDeps = defaultDeps, - target?: RuntimeClientTarget + target?: RuntimeClientTarget, + feedback?: Pick ): Promise { const structured = session.structuredSession if (!structured) { @@ -97,7 +98,11 @@ export async function activateAiVaultStructuredSession( if (inFlight) { return inFlight } - const activation = activateStructuredSession(structured, deps, target) + const activation = activateStructuredSession( + structured, + feedback ? { ...deps, ...feedback } : deps, + target + ) activationsInFlight.set(key, activation) try { return await activation diff --git a/src/renderer/src/lib/open-agent-message-sender.ts b/src/renderer/src/lib/open-agent-message-sender.ts index ec21c8319aab..fceb307398fd 100644 --- a/src/renderer/src/lib/open-agent-message-sender.ts +++ b/src/renderer/src/lib/open-agent-message-sender.ts @@ -1,3 +1,4 @@ +import type { OrchestrationCrewRow } from '../../../shared/orchestration-crew' // Open the sender through chat or terminal-handle routes; choose feedback from the answering host’s evidence, never the sender’s address shape. import { toast } from 'sonner' @@ -198,3 +199,59 @@ function showLookupFailure(failure: LookupFailure): void { ) ) } + +/** Crew opens share the sender's host-aware navigation; mailbox identity is never a terminal handle. */ +export async function openOrchestrationCrewAgent( + row: OrchestrationCrewRow, + host: RuntimeClientTarget +): Promise { + const unavailable = (detail: string) => toast.error(`${row.label}: ${detail}`) + let target = row.openTarget + try { + if (target?.kind === 'dispatch') { + const result = await callRuntimeRpc( + host, + 'orchestration.partyLocation', + { address: target.address } + ) + if (!result.location) { + unavailable( + result.lost + ? 'This agent is no longer available.' + : 'This host cannot locate this agent. Try again.' + ) + return + } + target = result.location + } + if (target?.kind === 'chat') { + await activateAiVaultStructuredSession( + { structuredSession: { workspaceId: target.worktreeId, sessionId: target.sessionId } }, + undefined, + host, + { + unavailable: () => unavailable('This host cannot open the chat. Try again.'), + gone: () => unavailable('This chat is no longer on this host.'), + hostCannotOpen: () => unavailable('Update Orca to open this chat.') + } + ) + } else if (target?.kind === 'terminal') { + const environmentId = host.kind === 'environment' ? host.environmentId : null + if (!focusRendererTerminalHandle(target.handle, environmentId)) { + await focusRuntimeTerminalHandle(target.handle, environmentId) + } + } else { + unavailable( + row.hostLabel + ? `Open this agent on ${row.hostLabel}.` + : 'This host cannot locate this agent. Try again.' + ) + } + } catch (error) { + unavailable( + error instanceof RuntimeRpcCallError && TERMINAL_GONE_CODES.has(error.code) + ? 'This terminal has exited.' + : 'This host cannot open this agent. Try again.' + ) + } +} From a5aa6d1c9128272b3e78eb2153e459bf543377e3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 05:27:50 -0700 Subject: [PATCH 010/164] Use checked runtime values in lineage integration tests --- src/cli/index-omitted-host-scope-selectors.test.ts | 14 ++++++++------ .../runtime-agent-orchestration-projection.test.ts | 3 ++- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/cli/index-omitted-host-scope-selectors.test.ts b/src/cli/index-omitted-host-scope-selectors.test.ts index 0c16ea6a4eeb..09a98489c2d0 100644 --- a/src/cli/index-omitted-host-scope-selectors.test.ts +++ b/src/cli/index-omitted-host-scope-selectors.test.ts @@ -49,7 +49,7 @@ import { LINEAGE_PARENT, LINEAGE_CHILD } from '../main/runtime/runtime-agent-lineage.test-fixture' -import type { OrcaRuntimeService } from '../main/runtime/orca-runtime' +import { OrcaRuntimeService } from '../main/runtime/orca-runtime' import { RpcDispatcher } from '../main/runtime/rpc/dispatcher' import { WORKTREE_CATALOG_METHODS } from '../main/runtime/rpc/methods/worktree-catalog-methods' import { COMMAND_SPECS } from './specs' @@ -87,11 +87,13 @@ describe('omittedHostIds selector annotation', () => { async (worktreeId) => { const f = publicLineageFixture(worktreeId) try { - // SAFETY: these catalog methods use only this read-only runtime seam; rows come from production projection/attachment. - const runtime = { - getRuntimeId: () => 'lineage-test', - getWorktreePs: async () => ({ worktrees: [f.build()], totalCount: 1, truncated: false }) - } as unknown as OrcaRuntimeService + const runtime = new OrcaRuntimeService() + vi.spyOn(runtime, 'getRuntimeId').mockReturnValue('lineage-test') + vi.spyOn(runtime, 'getWorktreePs').mockImplementation(async () => ({ + worktrees: [f.build()], + totalCount: 1, + truncated: false + })) const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_CATALOG_METHODS }) const resultOf = (response: unknown) => JSON.parse(JSON.stringify(response)).result const request = (params = {}) => diff --git a/src/main/runtime/runtime-agent-orchestration-projection.test.ts b/src/main/runtime/runtime-agent-orchestration-projection.test.ts index 819ce349aa04..c1c4b9667c33 100644 --- a/src/main/runtime/runtime-agent-orchestration-projection.test.ts +++ b/src/main/runtime/runtime-agent-orchestration-projection.test.ts @@ -42,6 +42,7 @@ import { traceDispatchPredicateVisits } from './dispatch-predicate-visits.test-fixture' import { benchmarkPresentationCorpus } from './runtime-agent-orchestration-benchmark.test-fixture' +import { MIRROR_LEAVES_STEP_1 } from './runtime-leaf-record-projection.test-fixture' import type { RuntimeLeafRecord } from './runtime-terminal-state-records' import { OrchestrationDb } from './orchestration/db' import { @@ -99,7 +100,7 @@ describe('RuntimeAgentOrchestrationProjection chat lineage', () => { creator, maxDepth: Number.MAX_SAFE_INTEGER }) - const leaf = { ptyId: 'pty_w' } as unknown as RuntimeLeafRecord + const leaf: RuntimeLeafRecord = { ...MIRROR_LEAVES_STEP_1[0], ptyId: 'pty_w' } const projection = new RuntimeAgentOrchestrationProjection({ getDb: () => db, getLeaves: () => [leaf], From 3f2eb0ccd79048892ca67197ce340a0dbe423fa9 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 05:38:31 -0700 Subject: [PATCH 011/164] Preserve host-aware crew navigation remedies --- .../use-orchestration-crew.test.tsx | 103 +++++++++++++++- .../OrchestrationCrewPanel.test.tsx | 110 ++++++++++++++++++ .../src/lib/open-agent-message-sender.test.ts | 107 ++++++++++++++++- .../src/lib/open-agent-message-sender.ts | 61 ++++++---- 4 files changed, 350 insertions(+), 31 deletions(-) create mode 100644 src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.test.tsx diff --git a/src/renderer/src/components/native-chat/use-orchestration-crew.test.tsx b/src/renderer/src/components/native-chat/use-orchestration-crew.test.tsx index 250e8e88d908..9a2f377f5cd1 100644 --- a/src/renderer/src/components/native-chat/use-orchestration-crew.test.tsx +++ b/src/renderer/src/components/native-chat/use-orchestration-crew.test.tsx @@ -15,6 +15,7 @@ const rig = vi.hoisted(() => ({ }[], listeners: new Set<() => void>(), state: { + unusedLocalState: 0, runtimeStatusByEnvironmentId: new Map([ [ 'crew-host', @@ -68,9 +69,14 @@ function Pane({ const crew = useOrchestrationCrew(target, party) renderCount() return ( - - {crew.status === 'ok' ? crew.sections.managing.length : 'unknown'} - + <> + + {crew.status === 'ok' ? crew.sections.managing.length : 'unknown'} + + + {crew.sections.managing[0]?.pendingQuestion?.preview} + + ) } function publish(index: number, pending = false) { @@ -142,6 +148,7 @@ it('caches old-host refusal per generation and resubscribes after reconnect or p expect(rig.streams).toHaveLength(1) act(() => { rig.state = { + ...rig.state, runtimeStatusByEnvironmentId: new Map([ [ 'crew-host', @@ -166,3 +173,93 @@ it('caches old-host refusal per generation and resubscribes after reconnect or p view.unmount() expect(rig.streams[2].unsubscribe).toHaveBeenCalledOnce() }) + +it('renders no unaffected local parties or hosts after unused state and other-host updates', async () => { + const otherHost = { kind: 'environment', environmentId: 'crew-other-host' } as const + const status = { + status: { runtimeId: 'runtime-isolation' }, + connectionGeneration: 1, + hostContactEpoch: 1 + } + rig.state = { + unusedLocalState: 0, + runtimeStatusByEnvironmentId: new Map([ + ['crew-host', status], + ['crew-other-host', status] + ]) + } + replaceRuntimeEnvironmentRevisions([ + { id: 'crew-host', createdAt: 10 }, + { id: 'crew-other-host', createdAt: 20 } + ]) + const localFirst = vi.fn(), + localOther = vi.fn(), + selected = vi.fn(), + other = vi.fn() + const counts = [localFirst, localOther, selected, other] + const view = render( + <> + + + + + + ) + await act(async () => {}) + expect(rig.streams).toHaveLength(4) + for (let index = 0; index < 4; index++) { + act(() => publish(index)()) + } + counts.forEach((count) => count.mockClear()) + const expectNone = () => counts.forEach((count) => expect(count).not.toHaveBeenCalled()) + + act(() => { + rig.state = { ...rig.state, unusedLocalState: 1 } + rig.listeners.forEach((wake) => wake()) + }) + expectNone() + act(() => { + rig.state = { + ...rig.state, + runtimeStatusByEnvironmentId: new Map(rig.state.runtimeStatusByEnvironmentId).set( + 'crew-other-host', + { ...status, connectionGeneration: 2 } + ) + } + rig.listeners.forEach((wake) => wake()) + }) + await act(async () => {}) + expect(localFirst).not.toHaveBeenCalled() + expect(localOther).not.toHaveBeenCalled() + expect(selected).not.toHaveBeenCalled() + expect(other).toHaveBeenCalled() + expect(rig.streams).toHaveLength(5) + counts.forEach((count) => count.mockClear()) + act(() => + replaceRuntimeEnvironmentRevisions([ + { id: 'crew-host', createdAt: 10 }, + { id: 'crew-other-host', createdAt: 20, pairingRevision: 21 } + ]) + ) + await act(async () => {}) + expect(localFirst).not.toHaveBeenCalled() + expect(localOther).not.toHaveBeenCalled() + expect(selected).not.toHaveBeenCalled() + expect(other).toHaveBeenCalled() + expect(rig.streams).toHaveLength(6) + counts.forEach((count) => count.mockClear()) + act(() => publish(5, true)()) + expect(localFirst).not.toHaveBeenCalled() + expect(localOther).not.toHaveBeenCalled() + expect(selected).not.toHaveBeenCalled() + expect(other).toHaveBeenCalledOnce() + counts.forEach((count) => count.mockClear()) + act(() => publish(2, true)()) + expect(selected).toHaveBeenCalledOnce() + expect(localFirst).not.toHaveBeenCalled() + expect(localOther).not.toHaveBeenCalled() + expect(other).not.toHaveBeenCalled() + expect(view.getByTestId('term_selected').textContent).toBe('1') + expect(view.getByTestId('term_selected-question').textContent).toBe('Which option?') + view.unmount() +}) diff --git a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.test.tsx b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.test.tsx new file mode 100644 index 000000000000..426c2d80d017 --- /dev/null +++ b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.test.tsx @@ -0,0 +1,110 @@ +// @vitest-environment happy-dom +import '@testing-library/jest-dom/vitest' +import { cleanup, render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { emptyCrew, type OrchestrationCrewRow } from '../../../../shared/orchestration-crew' +import { OrchestrationCrewPanel } from './OrchestrationCrewPanel' + +const rig = vi.hoisted(() => ({ snapshot: {}, open: vi.fn(), copy: vi.fn(), success: vi.fn() })) +vi.mock('../native-chat/use-orchestration-crew', () => ({ + useOrchestrationCrew: () => rig.snapshot +})) +vi.mock('@/lib/open-agent-message-sender', () => ({ openOrchestrationCrewAgent: rig.open })) +vi.mock('sonner', () => ({ toast: { success: rig.success } })) +const host = { kind: 'environment', environmentId: 'captured-host' } as const +const worker: OrchestrationCrewRow = { + partyKey: 'worker', + role: 'worker', + label: 'Worker', + agentKind: 'codex', + status: 'working', + sendAddress: 'dispatch:d1', + openTarget: { kind: 'terminal', handle: 'term_captured' }, + task: { title: 'Check the result', state: 'active' }, + latest: { + direction: 'from', + preview: 'The result is ready.', + at: '2026-10-28T00:00:00Z', + sequence: 1 + } +} +function mount(row = worker) { + rig.snapshot = { + ...emptyCrew('ok'), + sections: { managedBy: [], managing: [row], talkingWith: [] } + } + rig.copy.mockResolvedValue(undefined) + Object.defineProperty(window, 'api', { + configurable: true, + value: { ui: { writeTerminalClipboardText: rig.copy } } + }) + render( + + + + ) +} +afterEach(() => { + cleanup() + vi.clearAllMocks() +}) + +it('keeps keyboard/body disclosure, chevron, Open, Copy, Escape and collapse independent', async () => { + const user = userEvent.setup() + mount() + const tab = screen.getByRole('button', { name: 'Show crew: 1 workers' }) + tab.focus() + await user.keyboard('{Enter}') + expect(screen.getByRole('button', { name: 'Collapse crew panel' })).toHaveFocus() + const body = screen.getByRole('button', { name: /Worker codex Check the result/ }) + expect(body).toHaveAttribute('aria-expanded', 'false') + body.focus() + await user.keyboard(' ') + expect(body).toHaveAttribute('aria-expanded', 'true') + expect(screen.getByText('The result is ready.')).toBeInTheDocument() + expect(rig.open).not.toHaveBeenCalled() + expect(rig.copy).not.toHaveBeenCalled() + await user.click(screen.getByRole('button', { name: "Show Worker's task and latest message" })) + expect(body).toHaveAttribute('aria-expanded', 'false') + await user.click(body) + expect(body).toHaveAttribute('aria-expanded', 'true') + const open = screen.getByRole('button', { name: 'Open Worker' }) + open.focus() + await user.keyboard('{Enter}') + expect(rig.open).toHaveBeenCalledExactlyOnceWith(worker, host) + expect(body).toHaveAttribute('aria-expanded', 'true') + await user.click(screen.getByRole('button', { name: 'More for Worker' })) + await user.click(screen.getByRole('menuitem', { name: 'Copy address' })) + expect(rig.copy).toHaveBeenCalledExactlyOnceWith('dispatch:d1') + expect(rig.success).toHaveBeenCalledExactlyOnceWith("Copied Worker's address") + expect(rig.open).toHaveBeenCalledOnce() + expect(body).toHaveAttribute('aria-expanded', 'true') + await user.click(screen.getByRole('button', { name: 'More for Worker' })) + const menuOpen = screen.getByRole('menuitem', { name: 'Open its chat' }) + menuOpen.focus() + await user.keyboard('{Enter}') + expect(rig.open).toHaveBeenCalledTimes(2) + expect(rig.open).toHaveBeenLastCalledWith(worker, host) + expect(body).toHaveAttribute('aria-expanded', 'true') + screen.getByRole('button', { name: 'Collapse crew panel' }).focus() + await user.keyboard('{Escape}') + expect(screen.queryByRole('complementary', { name: 'Agent crew' })).not.toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Show crew: 1 workers' })).toHaveFocus() + await user.keyboard('{Enter}') + await user.click(screen.getByRole('button', { name: 'Collapse crew panel' })) + expect(screen.getByRole('button', { name: 'Show crew: 1 workers' })).toHaveFocus() + expect(rig.copy).toHaveBeenCalledOnce() +}) + +it('starts pending questions expanded without navigating or copying', async () => { + const user = userEvent.setup() + mount({ ...worker, pendingQuestion: { preview: 'Which option?', at: '2026-10-28T01:00:00Z' } }) + await user.click(screen.getByRole('button', { name: 'Show crew: 1 workers' })) + expect(screen.getByText('Asks you')).toBeInTheDocument() + expect(screen.getByText('Which option?')).toBeInTheDocument() + expect(screen.queryByText('The result is ready.')).not.toBeInTheDocument() + expect(rig.open).not.toHaveBeenCalled() + expect(rig.copy).not.toHaveBeenCalled() +}) diff --git a/src/renderer/src/lib/open-agent-message-sender.test.ts b/src/renderer/src/lib/open-agent-message-sender.test.ts index 80a912213036..6bcee89f8bea 100644 --- a/src/renderer/src/lib/open-agent-message-sender.test.ts +++ b/src/renderer/src/lib/open-agent-message-sender.test.ts @@ -49,11 +49,12 @@ vi.mock('@/store', () => ({ })) import { RuntimeRpcCallError } from '@/runtime/runtime-rpc-result' -import { RUNTIME_COMPAT_BLOCK_CODE } from '@/runtime/runtime-protocol-compat' +import { assertRuntimeStatusCompatible } from '@/runtime/runtime-protocol-compat' +import type { OrchestrationCrewRow } from '../../../shared/orchestration-crew' import type { AgentMessageSource } from '../../../shared/agent-session/agent-session-message-source' import { AGENT_SESSION_WRITE_NOTICE_COPY } from '../../../shared/agent-session-write-notice-copy' import { testOrcaSessionId } from '../../../shared/orca-session-address-test-fixture' -import { openAgentMessageSender } from './open-agent-message-sender' +import { openAgentMessageSender, openOrchestrationCrewAgent } from './open-agent-message-sender' const HOST = { kind: 'environment', environmentId: 'env-host' } const ROOT = testOrcaSessionId('4a1f6c2e-8b3d-4e7a-9c15-0d2b6e8f1a37') @@ -93,7 +94,24 @@ function failure(code: string): RuntimeRpcCallError { } function versionBlock(): Error { - return Object.assign(new Error('update needed'), { code: RUNTIME_COMPAT_BLOCK_CODE }) + try { + assertRuntimeStatusCompatible({ + runtimeId: 'runtime-old', + rendererGraphEpoch: 0, + graphStatus: 'ready', + authoritativeWindowId: null, + liveTabCount: 0, + liveLeafCount: 0, + runtimeProtocolVersion: 0, + minCompatibleRuntimeClientVersion: Number.MAX_SAFE_INTEGER + }) + } catch (error) { + if (error instanceof Error) { + return error + } + throw error + } + throw new Error('Expected the production compatibility gate to block') } // Existing sentences, each translated whole: the cause and what to do, or which Orca to update. @@ -108,6 +126,89 @@ beforeEach(() => { }) describe("opening a message's sender", () => { + it('preserves sender remedies and the captured host/target across crew terminal and dispatch opens', async () => { + const host = { kind: 'environment', environmentId: 'captured-host' } as const + for (const kind of ['terminal', 'dispatch'] as const) { + for (const outcome of ['compat', 'transient', 'gone', 'older-host'] as const) { + if (kind === 'terminal' && outcome === 'older-host') { + continue + } + const party = kind === 'terminal' ? terminal : dispatch + const row: OrchestrationCrewRow = { + partyKey: 'captured-worker', + role: 'worker', + label: 'Worker', + agentKind: 'codex', + status: 'working', + sendAddress: 'run:mailbox-is-not-a-pane', + openTarget: + kind === 'terminal' + ? { kind, handle: 'term_captured' } + : { kind, address: party.address } + } + const prepare = () => { + vi.clearAllMocks() + mocks.callRuntimeRpc.mockReset() + mocks.focusRuntime.mockReset() + mocks.focusRenderer.mockReturnValue(false) + const error = outcome === 'compat' ? versionBlock() : failure('request_timeout') + if (kind === 'terminal') { + mocks.callRuntimeRpc.mockResolvedValue({ + location: { kind: 'terminal', handle: 'term_captured' } + }) + mocks.focusRuntime.mockRejectedValue( + outcome === 'gone' ? failure('terminal_handle_stale') : error + ) + } else if (outcome === 'gone') { + mocks.callRuntimeRpc.mockResolvedValue({ location: null, lost: 'terminal' }) + } else { + mocks.callRuntimeRpc.mockRejectedValue( + outcome === 'older-host' ? failure('method_not_found') : error + ) + } + } + prepare() + const source = sourceFor(party) + await openAgentMessageSender(source, source.senders[0]!, 'wt-chat', host) + const oldMessages = mocks.toastError.mock.calls.map(([message]) => message) + expect(oldMessages).toEqual( + outcome === 'gone' + ? [] + : [outcome === 'compat' ? UPDATE : outcome === 'older-host' ? OLDER_HOST : UNREACHABLE] + ) + expect(mocks.paneUnavailable).toHaveBeenCalledTimes(outcome === 'gone' ? 1 : 0) + prepare() + await openOrchestrationCrewAgent(row, host) + expect(mocks.toastError.mock.calls.map(([message]) => message)).toEqual([ + outcome === 'gone' + ? `Worker: ${kind === 'terminal' ? 'This terminal has exited.' : 'This agent is no longer available.'}` + : `Worker: ${oldMessages[0]}` + ]) + expect(mocks.paneUnavailable).not.toHaveBeenCalled() + expect(mocks.activateChat).not.toHaveBeenCalled() + if (kind === 'terminal') { + expect(mocks.callRuntimeRpc).not.toHaveBeenCalled() + expect(mocks.focusRenderer).toHaveBeenCalledExactlyOnceWith( + 'term_captured', + 'captured-host' + ) + expect(mocks.focusRuntime).toHaveBeenCalledExactlyOnceWith( + 'term_captured', + 'captured-host' + ) + } else { + expect(mocks.callRuntimeRpc).toHaveBeenCalledExactlyOnceWith( + host, + 'orchestration.partyLocation', + { address: party.address } + ) + expect(mocks.focusRenderer).not.toHaveBeenCalled() + expect(mocks.focusRuntime).not.toHaveBeenCalled() + } + } + } + }) + it("asks the chat's host where a terminal is, with the mail it sent, and focuses what it finds", async () => { mocks.callRuntimeRpc.mockResolvedValue({ location: { kind: 'terminal', handle: 'term_now' } }) mocks.focusRenderer.mockReturnValue(true) diff --git a/src/renderer/src/lib/open-agent-message-sender.ts b/src/renderer/src/lib/open-agent-message-sender.ts index fceb307398fd..d66c39a2861a 100644 --- a/src/renderer/src/lib/open-agent-message-sender.ts +++ b/src/renderer/src/lib/open-agent-message-sender.ts @@ -123,7 +123,14 @@ async function openSender( await focusTerminal(location.handle, environmentId) } -async function focusTerminal(handle: string, environmentId: string | null): Promise { +async function focusTerminal( + handle: string, + environmentId: string | null, + feedback = { + gone: showAgentPaneUnavailable, + lookupFailure: showLookupFailure + } +): Promise { if (focusRendererTerminalHandle(handle, environmentId)) { return } @@ -131,9 +138,9 @@ async function focusTerminal(handle: string, environmentId: string | null): Prom await focusRuntimeTerminalHandle(handle, environmentId) } catch (error) { if (error instanceof RuntimeRpcCallError && TERMINAL_GONE_CODES.has(error.code)) { - showAgentPaneUnavailable() + feedback.gone() } else { - showLookupFailure(isRuntimeCompatBlockError(error) ? 'update' : 'unreachable') + feedback.lookupFailure(lookupFailure(error)) } } } @@ -153,10 +160,14 @@ async function lookUpSender( if (error instanceof RuntimeRpcCallError && error.code === 'method_not_found') { return lookUpOnOlderHost(party, host) } - return isRuntimeCompatBlockError(error) ? 'update' : 'unreachable' + return lookupFailure(error) } } +function lookupFailure(error: unknown): LookupFailure { + return isRuntimeCompatBlockError(error) ? 'update' : 'unreachable' +} + /** Older hosts allow root-ID chats and terminal-handle opens; other identities require updating that host. */ function lookUpOnOlderHost(party: Sender['party'], host: RuntimeClientTarget): Lookup { const sessionId = party.orcaSessionId @@ -188,16 +199,15 @@ function located(location: OrchestrationPartyLocation): OrchestrationPartyLocati return { location } } -function showLookupFailure(failure: LookupFailure): void { - toast.error( - agentSessionWriteNoticeText( - failure === 'older-host' - ? ['unsupported'] - : failure === 'update' - ? ['updateOrcaToOpenChat'] - : ['unreachable', 'tryAgain'] - ) +function showLookupFailure(failure: LookupFailure, label?: string): void { + const message = agentSessionWriteNoticeText( + failure === 'older-host' + ? ['unsupported'] + : failure === 'update' + ? ['updateOrcaToOpenChat'] + : ['unreachable', 'tryAgain'] ) + toast.error(label ? `${label}: ${message}` : message) } /** Crew opens share the sender's host-aware navigation; mailbox identity is never a terminal handle. */ @@ -209,11 +219,15 @@ export async function openOrchestrationCrewAgent( let target = row.openTarget try { if (target?.kind === 'dispatch') { - const result = await callRuntimeRpc( - host, - 'orchestration.partyLocation', - { address: target.address } + const result = await lookUpSender( + { address: target.address, terminalHandle: null, orcaSessionId: null }, + [], + host ) + if (typeof result === 'string') { + showLookupFailure(result, row.label) + return + } if (!result.location) { unavailable( result.lost @@ -237,9 +251,10 @@ export async function openOrchestrationCrewAgent( ) } else if (target?.kind === 'terminal') { const environmentId = host.kind === 'environment' ? host.environmentId : null - if (!focusRendererTerminalHandle(target.handle, environmentId)) { - await focusRuntimeTerminalHandle(target.handle, environmentId) - } + await focusTerminal(target.handle, environmentId, { + gone: () => unavailable('This terminal has exited.'), + lookupFailure: (failure) => showLookupFailure(failure, row.label) + }) } else { unavailable( row.hostLabel @@ -248,10 +263,6 @@ export async function openOrchestrationCrewAgent( ) } } catch (error) { - unavailable( - error instanceof RuntimeRpcCallError && TERMINAL_GONE_CODES.has(error.code) - ? 'This terminal has exited.' - : 'This host cannot open this agent. Try again.' - ) + showLookupFailure(lookupFailure(error), row.label) } } From 3e34030a594305713821574011f3840c59e1e5a8 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 01:18:42 -0700 Subject: [PATCH 012/164] Insert crew references into chat drafts and terminal prompts --- .../native-chat/NativeChatPromptEditor.tsx | 15 + .../NativeChatQueuedMessageEditor.test.tsx | 1 + ...ResolvedView.prompt-card-composer.test.tsx | 1 + .../native-chat/NativeChatResolvedView.tsx | 6 +- .../NativeChatSelectionQuote.test.tsx | 1 + .../NativeChatStructuredSession.tsx | 10 +- .../native-chat-agent-reference-send.ts | 55 +++ .../native-chat-agent-reference.test.tsx | 335 ++++++++++++++++++ .../native-chat-agent-reference.tsx | 42 +++ .../native-chat/native-chat-composer-input.ts | 2 + .../native-chat/native-chat-composer-types.ts | 2 + .../native-chat-paste-routing.test.tsx | 1 + .../native-chat-prompt-document.ts | 8 + .../use-native-chat-composer-handle.ts | 11 + .../use-native-chat-composer-submit.ts | 9 +- ...use-native-chat-context-menu.find.test.tsx | 1 + ...-native-chat-context-menu.targets.test.tsx | 1 + .../native-chat/use-native-chat-find.test.tsx | 1 + .../use-native-chat-pty-composer-send.ts | 10 +- ...se-native-chat-root-input-routing.test.tsx | 1 + ...se-native-chat-structured-composer-send.ts | 10 +- .../NativeChatCrewPanel.tsx | 24 +- .../OrchestrationCrewPanel.tsx | 54 ++- .../TerminalCrewPortals.tsx | 31 +- .../terminal-pane/terminal-crew-mention.ts | 25 ++ src/shared/orchestration-agent-reference.ts | 21 ++ 26 files changed, 664 insertions(+), 14 deletions(-) create mode 100644 src/renderer/src/components/native-chat/native-chat-agent-reference-send.ts create mode 100644 src/renderer/src/components/native-chat/native-chat-agent-reference.test.tsx create mode 100644 src/renderer/src/components/native-chat/native-chat-agent-reference.tsx create mode 100644 src/renderer/src/components/terminal-pane/terminal-crew-mention.ts diff --git a/src/renderer/src/components/native-chat/NativeChatPromptEditor.tsx b/src/renderer/src/components/native-chat/NativeChatPromptEditor.tsx index b6f0ad00dcbe..4998765b45c0 100644 --- a/src/renderer/src/components/native-chat/NativeChatPromptEditor.tsx +++ b/src/renderer/src/components/native-chat/NativeChatPromptEditor.tsx @@ -1,3 +1,4 @@ +import { NativeChatAgentReference } from './native-chat-agent-reference' import { createNativeChatPastedTextHistory } from './native-chat-pasted-text-history' import { resolveNativeChatPastedText } from './native-chat-composer-pasted-text-references' import { NativeChatPastedTextScopeProvider } from './native-chat-pasted-text-state' @@ -86,6 +87,7 @@ export function NativeChatPromptEditor({ underline: false, trailingNode: false }), + NativeChatAgentReference, NativeChatSkill, NativeChatFileReference, NativeChatImageReference, @@ -180,6 +182,19 @@ export function NativeChatPromptEditor({ () => editor ? { + insertAgentReferences: (references) => { + if (!editor.isEditable) { + return + } + editor.view.dispatch(closeHistory(editor.state.tr)) + editor.commands.insertContent( + references.flatMap((attrs) => [ + { type: NativeChatAgentReference.name, attrs }, + { type: 'text', text: ' ' } + ]) + ) + editor.view.dispatch(closeHistory(editor.state.tr)) + }, insertText: (text) => { const content = editor.schema.nodeFromJSON(promptTextContent(text)) editor.view.dispatch( diff --git a/src/renderer/src/components/native-chat/NativeChatQueuedMessageEditor.test.tsx b/src/renderer/src/components/native-chat/NativeChatQueuedMessageEditor.test.tsx index 29ca12c13913..7918d3d156a8 100644 --- a/src/renderer/src/components/native-chat/NativeChatQueuedMessageEditor.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatQueuedMessageEditor.test.tsx @@ -368,6 +368,7 @@ describe('queued card image edit', () => { vi.stubGlobal('navigator', { userAgent: 'Windows', clipboard: undefined }) const composer: NativeChatComposerHandle = { focus: vi.fn(() => true), + insertAgentReferences: () => false, insertTypedText: () => true, acceptsText: () => true, appendText: vi.fn(), diff --git a/src/renderer/src/components/native-chat/NativeChatResolvedView.prompt-card-composer.test.tsx b/src/renderer/src/components/native-chat/NativeChatResolvedView.prompt-card-composer.test.tsx index 3193356389b5..002869213893 100644 --- a/src/renderer/src/components/native-chat/NativeChatResolvedView.prompt-card-composer.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatResolvedView.prompt-card-composer.test.tsx @@ -49,6 +49,7 @@ vi.mock('./NativeChatComposer', async () => { fieldRef.current?.focus() return true }, + insertAgentReferences: () => false, insertTypedText: composer.typed, acceptsText: () => true, appendText: () => {}, diff --git a/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx b/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx index ffca66a62631..9464e06e04fa 100644 --- a/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx +++ b/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx @@ -344,7 +344,11 @@ export function NativeChatResolvedView({ style={appearanceStyle} data-native-chat-scheme={appearanceStyle.colorScheme} > - +
{find.isOpen ? : null} {viewState.kind === 'loading' ? ( diff --git a/src/renderer/src/components/native-chat/NativeChatSelectionQuote.test.tsx b/src/renderer/src/components/native-chat/NativeChatSelectionQuote.test.tsx index 536bc12b215b..d804190aea46 100644 --- a/src/renderer/src/components/native-chat/NativeChatSelectionQuote.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatSelectionQuote.test.tsx @@ -19,6 +19,7 @@ const appendText = vi.fn<(text: string) => void>() const acceptsText = vi.fn(() => true) const composer: NativeChatComposerHandle = { focus: () => true, + insertAgentReferences: () => false, insertTypedText: () => true, appendText, acceptsText, diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx index cc258d9cda7f..b28d17d25267 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx @@ -288,7 +288,15 @@ export function NativeChatStructuredSession( > {nativeChatPaneHeader(props, ownerWorktreeId, appearanceStyle.colorScheme, handOff)}
- + {find.isOpen ? : null} {viewState.kind === 'loading' || (viewState.kind === 'error' && !readFailure) ? ( diff --git a/src/renderer/src/components/native-chat/native-chat-agent-reference-send.ts b/src/renderer/src/components/native-chat/native-chat-agent-reference-send.ts new file mode 100644 index 000000000000..29b556e35dd0 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-agent-reference-send.ts @@ -0,0 +1,55 @@ +import type { JSONContent } from '@tiptap/react' +import { imageReferenceToken } from '../../../../shared/native-chat-image-reference' +import { + agentReferenceToken, + isPublicOrchestrationAddress, + type OrchestrationAgentReference +} from '../../../../shared/orchestration-agent-reference' + +/** Only the document matching this submission can contribute selected targets. */ +export function serializeNativeChatAgentReferences(text: string, document?: JSONContent): string { + const references = new Map() + const render = (node: JSONContent, wire: boolean): string => { + if (node.type === 'nativeChatAgentReference') { + const { label, address, hostKey } = node.attrs ?? {} + if (typeof label !== 'string' || typeof address !== 'string' || typeof hostKey !== 'string') { + return '' + } + const reference = { label, address, hostKey } + if (wire && isPublicOrchestrationAddress(address)) { + references.set(JSON.stringify([hostKey, address]), reference) + return `@${label}` + } + return agentReferenceToken(reference) + } + if (node.type === 'hardBreak') { + return '\n' + } + if (node.type === 'nativeChatImageReference') { + return imageReferenceToken(String(node.attrs?.attachmentId)) + } + if (node.text !== undefined) { + return node.text + } + if (typeof node.attrs?.token === 'string') { + return node.attrs.token + } + return (node.content ?? []) + .map((child) => render(child, wire)) + .join(node.type === 'doc' ? '\n' : '') + } + if (!document || render(document, false) !== text) { + return text + } + const wire = render(document, true) + return `${wire}${ + references.size === 0 + ? '' + : `\n\n${[...references.values()] + .map( + ({ label, address }) => + `[Orca agent "${label}": ${address} — message it with orca orchestration send --to ${address}]` + ) + .join('\n')}` + }` +} diff --git a/src/renderer/src/components/native-chat/native-chat-agent-reference.test.tsx b/src/renderer/src/components/native-chat/native-chat-agent-reference.test.tsx new file mode 100644 index 000000000000..15f2d44815c9 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-agent-reference.test.tsx @@ -0,0 +1,335 @@ +// @vitest-environment happy-dom +import { CrewPanelContent } from '../orchestration-crew/OrchestrationCrewPanel' +import { TooltipProvider } from '../ui/tooltip' +import { emptyCrew, type OrchestrationCrewRow } from '../../../../shared/orchestration-crew' +import { openOrchestrationCrewAgent } from '@/lib/open-agent-message-sender' +import { createRef } from 'react' +import { act, cleanup, render, renderHook, within, fireEvent } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import type { PaneManager } from '@/lib/pane-manager/pane-manager' +import type { PtyTransport } from '../terminal-pane/pty-transport-types' +import type { NativeChatStructuredComposerTransport } from './native-chat-composer-types' +import type { NativeChatComposerInput } from './native-chat-composer-input' +import { NativeChatPromptEditor } from './NativeChatPromptEditor' +import { promptEditor } from './native-chat-prompt-editor.test-support' +import { agentReferenceToken } from '../../../../shared/orchestration-agent-reference' +import { serializeNativeChatAgentReferences } from './native-chat-agent-reference-send' +import { useNativeChatStructuredComposerSend } from './use-native-chat-structured-composer-send' +import { useNativeChatPtyComposerSend } from './use-native-chat-pty-composer-send' +import { useNativeChatComposerSubmit } from './use-native-chat-composer-submit' +import { sendNativeChatMessage } from './native-chat-runtime-send' +import { + clearNativeChatComposerDraftsForTests, + readNativeChatComposerDraft, + updateNativeChatComposerDraft +} from './native-chat-composer-draft-store' +import { captureTerminalDropTarget } from '../terminal-pane/terminal-drop-target' +import { insertTerminalCrewMention } from '../terminal-pane/terminal-crew-mention' +import { takeStructuredAgentSessionSendSlot } from './structured-agent-session-send-slot' +import { clearStructuredAgentSessionPendingSends } from './structured-agent-session-pending-sends' +import { + attemptStructuredAgentSessionSend, + noteStructuredAgentSessionFence +} from './structured-agent-session-send-attempt' + +const queuedRuntime = vi.hoisted(() => ({ call: vi.fn() })) +vi.mock('@/runtime/structured-agent-session-client', () => ({ + callStructuredAgentSession: queuedRuntime.call +})) + +vi.mock('@/lib/open-agent-message-sender', () => ({ openOrchestrationCrewAgent: vi.fn() })) +vi.mock('./native-chat-runtime-send', () => ({ + sendNativeChatMessage: vi.fn(() => ({ cancel() {}, settleAfterMs: 0 })), + sendNativeChatTypedCommand: vi.fn(), + submitNativeChatPrompt: vi.fn() +})) +vi.mock('@/lib/native-chat-telemetry', () => ({ emitNativeChatMessageSent: vi.fn() })) +vi.mock('@/lib/worker-terminal-takeover-report', () => ({ + reportStructuredSessionUserInput: vi.fn() +})) +afterEach(() => { + cleanup() + clearNativeChatComposerDraftsForTests() + clearStructuredAgentSessionPendingSends('test-session') + vi.restoreAllMocks() +}) +const first = { label: 'Same name', address: 'term_first', hostKey: 'local' } +const second = { ...first, address: 'dispatch:ctx_second' } +function editor(scope: string, text = 'Hello ') { + const ref = createRef() + const view = render( + + ) + return { + ...view, + input: ref.current!, + editor: promptEditor(within(view.container).getByRole('textbox')) + } +} +function transport(): NativeChatStructuredComposerTransport { + return { + capturePresentation: () => () => true, + send: vi.fn(() => 'queued'), + dispatchCommand: vi.fn(async () => ({ accepted: true, error: null })), + optionsSurface: { + getSnapshot: () => [], + setOption: vi.fn(), + invokeAction: vi.fn(), + subscribe: () => () => {} + }, + optionSnapshot: [], + onError: vi.fn(), + runtime: 'local', + sessionId: 'test-session', + runtimeEnvironmentId: null + } +} + +it('keeps a split’s caret, duplicate-name identities, literal copy/recall and atomic undo', async () => { + const left = editor('left') + const right = editor('right', 'Other draft') + await act(async () => { + left.input.setSelectionRange(6, 6) + right.input.focus() + left.input.insertAgentReferences!([first, second]) + }) + const stored = `Hello ${agentReferenceToken(first)} ${agentReferenceToken(second)} ` + expect(left.input.value).toBe(stored) + expect(right.input.value).toBe('Other draft') + expect(left.container.querySelectorAll('[data-native-chat-agent-reference]')).toHaveLength(2) + const doc = readNativeChatComposerDraft('left').document + expect(serializeNativeChatAgentReferences(stored, doc)).toBe( + 'Hello @Same name @Same name \n\n[Orca agent "Same name": term_first — message it with orca orchestration send --to term_first]\n[Orca agent "Same name": dispatch:ctx_second — message it with orca orchestration send --to dispatch:ctx_second]' + ) + expect(left.editor.getText()).toBe(stored) + expect(serializeNativeChatAgentReferences('/model', doc)).toBe('/model') + await act(async () => { + left.input.setSelectionRange(6, 6 + agentReferenceToken(first).length) + left.editor.commands.deleteSelection() + }) + expect(left.container.querySelectorAll('[data-native-chat-agent-reference]')).toHaveLength(1) + await act(async () => { + left.editor.commands.undo() + }) + expect(left.input.value).toBe(stored) + await act(async () => { + left.input.value = 'Old plain @Same name draft' + }) + expect(left.container.querySelectorAll('[data-native-chat-agent-reference]')).toHaveLength(0) + expect( + serializeNativeChatAgentReferences( + left.input.value, + readNativeChatComposerDraft('left').document + ) + ).toBe('Old plain @Same name draft') +}) + +it('serializes before structured queue admission, PTY writes and goal submission; picker sends do not inherit atoms', async () => { + const pane = editor('send') + act(() => { + pane.input.setSelectionRange(6, 6) + pane.input.insertAgentReferences!([first, first, second]) + }) + const snapshot = readNativeChatComposerDraft('send') + const wire = serializeNativeChatAgentReferences(snapshot.text, snapshot.document) + const structured = transport() + const structuredHook = renderHook(() => + useNativeChatStructuredComposerSend({ + agent: 'claude', + draftScopeKey: 'send', + imageAttachments: [], + structuredTransport: structured, + isComposing: () => false, + clearSkillOrigin: vi.fn(), + setDraft: vi.fn(), + setCaret: vi.fn() + }) + ) + await act(async () => { + await structuredHook.result.current(snapshot.text) + }) + expect(structured.send).toHaveBeenCalledWith(wire, []) + expect(wire.match(/\[Orca agent/g)).toHaveLength(2) + const queued = vi.mocked(structured.send).mock.calls[0][0] + const entry = takeStructuredAgentSessionSendSlot({ + sessionId: 'test-session', + text: queued, + delivery: 'queue-if-active' + }) + expect(entry).not.toBeNull() + updateNativeChatComposerDraft('send', { text: 'new draft', document: undefined }, 'immediate') + noteStructuredAgentSessionFence('test-session', 1) + queuedRuntime.call.mockResolvedValue({ + ok: true, + replayed: true, + fence: 1, + value: { clientMessageId: entry!.clientMessageId } + }) + for (let attempt = 0; attempt < 2; attempt += 1) { + await attemptStructuredAgentSessionSend({ + entry: entry!, + target: { kind: 'local' }, + beforeIssue: vi.fn(), + abandoned: () => false, + reconcile: vi.fn() + }) + } + expect(queuedRuntime.call).toHaveBeenCalledTimes(2) + for (const [, method, params] of queuedRuntime.call.mock.calls) { + expect(method).toBe('agentSession.send') + expect(params.body.blocks).toEqual([{ type: 'text', text: wire }]) + expect(params.delivery).toBe('queue-if-active') + expect(params.envelope.clientOperationId).toBe(entry!.clientMessageId) + } + await act(async () => { + await structuredHook.result.current('/compact') + }) + expect(structured.dispatchCommand).toHaveBeenCalledWith('/compact') + updateNativeChatComposerDraft('send', snapshot, 'immediate') + const ptyHook = renderHook(() => + useNativeChatPtyComposerSend({ + agent: 'codex', + draftScopeKey: 'send', + draft: snapshot.text, + imageAttachments: [], + disabled: false, + isDispatchingSessionOption: false, + launchDraftResolved: true, + resolveTarget: () => ({ ptyId: 'pty-left', settings: null }), + classifySend: () => 'chat', + sessionOptionsSurface: null, + terminalTabId: 'tab-left', + trackPendingSend: vi.fn(), + setDraft: vi.fn(), + setCaret: vi.fn(), + clearSkillOrigin: vi.fn(), + clearImageAttachments: vi.fn(), + setNotice: vi.fn() + }) + ) + act(() => ptyHook.result.current()) + expect(vi.mocked(sendNativeChatMessage).mock.calls.at(-1)?.slice(0, 2)).toEqual([ + 'pty-left', + wire + ]) + const goalTransport = transport() + goalTransport.threadGoal = { setObjective: vi.fn(async () => true) } + const goalHook = renderHook(() => + useNativeChatComposerSubmit({ + structuredTransport: goalTransport, + draftScopeKey: 'send', + draft: snapshot.text, + caret: 0, + imageAttachments: [], + disabled: false, + sendPty: vi.fn(), + sendStructured: vi.fn(), + setDraft: vi.fn(), + setCaret: vi.fn() + }) + ) + act(() => + goalHook.result.current.goalMode.interceptPick(vi.fn())({ + kind: 'command', + id: 'goal', + name: 'goal', + token: '/goal', + skillCollision: false + }) + ) + updateNativeChatComposerDraft('send', snapshot, 'immediate') + await act(async () => goalHook.result.current.send()) + expect(goalTransport.threadGoal.setObjective).toHaveBeenCalledWith(wire.trim()) +}) + +it('writes only revalidated split bytes, sanitizing controls without Enter and surfacing rejected acceptance', async () => { + let leaf = 'leaf-left' + const sendInput = vi.fn(() => true) + const sendInputAccepted = vi.fn(async () => true) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: mention only reads pane id/leaf, never operates a terminal widget. + const manager = { getPanes: () => [{ id: 1, leafId: leaf }] } as PaneManager + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the existing drop validator and writer only consume these four transport methods. + const pty = { + getPtyId: () => 'pty-left', + isConnected: () => true, + sendInput, + sendInputAccepted + } as unknown as PtyTransport + const target = captureTerminalDropTarget({ id: 1, leafId: leaf }, pty) + const transports = new Map([[1, pty]]) + expect( + await insertTerminalCrewMention(manager, transports, target, [ + { ...first, label: 'Zoë\r\n\u001b[31m\u2028\u0085' } + ]) + ).toBe(true) + expect(sendInputAccepted).toHaveBeenCalledWith('Zoë [31m (Orca agent term_first) ', 'driving') + expect(sendInput).not.toHaveBeenCalled() + leaf = 'leaf-replaced' + expect(await insertTerminalCrewMention(manager, transports, target, [first])).toBe(false) + expect(sendInputAccepted).toHaveBeenCalledTimes(1) + leaf = 'leaf-left' + sendInputAccepted.mockResolvedValueOnce(false) + expect(await insertTerminalCrewMention(manager, transports, target, [first])).toBe(false) + expect(sendInputAccepted).toHaveBeenCalledTimes(2) + expect( + await insertTerminalCrewMention(manager, transports, target, [ + { ...first, address: 'term_bad\r' } + ]) + ).toBe(false) + expect(sendInputAccepted).toHaveBeenCalledTimes(2) +}) + +it('hides unknown hosts, starts collapsed and separates mention, navigation and disclosure hit targets', () => { + const mention = vi.fn() + const row: OrchestrationCrewRow = { + partyKey: 'host+worker', + role: 'worker', + label: 'Worker', + agentKind: 'codex', + status: 'waiting', + task: { title: 'Implement crew', state: 'blocked' }, + pendingQuestion: { preview: 'Choose A or B?', at: new Date(0).toISOString() }, + sendAddress: 'dispatch:ctx_worker' + } + const props = { + target: { kind: 'local' } as const, + party: 'term_coord', + canMention: true, + mention + } + const view = render( + + + + ) + expect(view.container.querySelector('[data-orchestration-crew]')).toBeNull() + const snapshot = emptyCrew('ok') + snapshot.sections.managing.push(row) + view.rerender( + + + + ) + expect(view.queryByRole('complementary')).toBeNull() + fireEvent.click(view.getByRole('button', { name: 'Show crew: 1 workers' })) + expect(view.getByText('Choose A or B?')).toBeTruthy() + fireEvent.click(view.getByRole('button', { name: 'Mention all' })) + expect(mention).toHaveBeenCalledWith([row]) + mention.mockClear() + fireEvent.click(view.getByRole('button', { name: 'Open Worker' })) + expect(openOrchestrationCrewAgent).toHaveBeenCalledWith(row, props.target) + fireEvent.click(view.getByRole('button', { name: "Show Worker's task and latest message" })) + expect(view.queryByText('Choose A or B?')).toBeNull() + expect(mention).not.toHaveBeenCalled() + fireEvent.keyDown(view.getByRole('complementary'), { key: 'Escape' }) + expect(view.queryByRole('complementary')).toBeNull() + expect(document.activeElement).toBe(view.getByRole('button', { name: 'Show crew: 1 workers' })) +}) diff --git a/src/renderer/src/components/native-chat/native-chat-agent-reference.tsx b/src/renderer/src/components/native-chat/native-chat-agent-reference.tsx new file mode 100644 index 000000000000..1e241f01782c --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-agent-reference.tsx @@ -0,0 +1,42 @@ +import { Node, NodeViewWrapper, ReactNodeViewRenderer, type NodeViewProps } from '@tiptap/react' +import { Users } from 'lucide-react' +import { NativeChatPromptPill } from './NativeChatPromptPill' +import { agentReferenceToken } from '../../../../shared/orchestration-agent-reference' + +function AgentReferencePill({ node, selected }: NodeViewProps): React.JSX.Element { + return ( + + + + ) +} + +export const NativeChatAgentReference = Node.create({ + name: 'nativeChatAgentReference', + group: 'inline', + inline: true, + atom: true, + selectable: true, + addAttributes: () => ({ + label: { default: '' }, + address: { default: '' }, + hostKey: { default: '' } + }), + addNodeView: () => ReactNodeViewRenderer(AgentReferencePill), + renderText: ({ node }) => + agentReferenceToken({ + label: String(node.attrs.label), + address: String(node.attrs.address), + hostKey: String(node.attrs.hostKey) + }), + renderHTML: ({ node }) => [ + 'span', + { 'data-native-chat-agent-reference': node.attrs.address }, + `@${node.attrs.label}` + ] +}) diff --git a/src/renderer/src/components/native-chat/native-chat-composer-input.ts b/src/renderer/src/components/native-chat/native-chat-composer-input.ts index 5c7a7507e9f1..a7dffda92b73 100644 --- a/src/renderer/src/components/native-chat/native-chat-composer-input.ts +++ b/src/renderer/src/components/native-chat/native-chat-composer-input.ts @@ -1,3 +1,4 @@ +import type { OrchestrationAgentReference } from '../../../../shared/orchestration-agent-reference' /** Text coordinates keep transport, attachments, and picker logic independent of the editor. */ export type NativeChatComposerInput = Pick< HTMLTextAreaElement, @@ -9,6 +10,7 @@ export type NativeChatComposerInput = Pick< | 'select' | 'setSelectionRange' > & { + insertAgentReferences?: (references: OrchestrationAgentReference[]) => void contains?: (node: Node | null) => boolean insertText?: (text: string) => void insertSkill?: (from: number, to: number, token: string, path?: string) => void diff --git a/src/renderer/src/components/native-chat/native-chat-composer-types.ts b/src/renderer/src/components/native-chat/native-chat-composer-types.ts index b05855ac30bf..b437c35cb644 100644 --- a/src/renderer/src/components/native-chat/native-chat-composer-types.ts +++ b/src/renderer/src/components/native-chat/native-chat-composer-types.ts @@ -1,3 +1,4 @@ +import type { OrchestrationAgentReference } from '../../../../shared/orchestration-agent-reference' import type { CaptureStructuredAgentSessionPresentation } from './use-structured-agent-session-mutate' import type { StructuredAgentSessionSendRequest } from './structured-agent-session-send-slot' import type { NativeChatComposerNotice } from './native-chat-composer-notice' @@ -142,6 +143,7 @@ export type NativeChatLaunchSeed = { } export type NativeChatComposerHandle = { + insertAgentReferences: (references: OrchestrationAgentReference[]) => boolean focus: () => boolean insertTypedText: (text: string) => boolean /** Whether the input is there and enabled, so text given to it lands. */ diff --git a/src/renderer/src/components/native-chat/native-chat-paste-routing.test.tsx b/src/renderer/src/components/native-chat/native-chat-paste-routing.test.tsx index 6bdaa365a9b9..d376bcdde8cb 100644 --- a/src/renderer/src/components/native-chat/native-chat-paste-routing.test.tsx +++ b/src/renderer/src/components/native-chat/native-chat-paste-routing.test.tsx @@ -83,6 +83,7 @@ function composerHandle(): NativeChatComposerHandle & { element: HTMLElement } { element.focus() return true }), + insertAgentReferences: () => false, insertTypedText: vi.fn(() => true), appendText: vi.fn(), acceptsText: () => true, diff --git a/src/renderer/src/components/native-chat/native-chat-prompt-document.ts b/src/renderer/src/components/native-chat/native-chat-prompt-document.ts index d6fa38549fae..2f796d0dc9de 100644 --- a/src/renderer/src/components/native-chat/native-chat-prompt-document.ts +++ b/src/renderer/src/components/native-chat/native-chat-prompt-document.ts @@ -1,3 +1,4 @@ +import { agentReferenceToken } from '../../../../shared/orchestration-agent-reference' import { NativeChatFileReferencePill } from './NativeChatFileReferencePill' import { NativeChatSkillPill, skillLabel } from './NativeChatSkillPill' import { NativeChatImageReferencePill } from './NativeChatImageReferencePill' @@ -86,6 +87,13 @@ export function fileReferenceContent(path: string): JSONContent { /** A pill reads as its token and a hard break as a newline, so the text is what the agent receives. */ export function promptLeafText(node: ProseMirrorNode): string { + if (node.type.name === 'nativeChatAgentReference') { + return agentReferenceToken({ + label: String(node.attrs.label), + address: String(node.attrs.address), + hostKey: String(node.attrs.hostKey) + }) + } if (node.type.name === IMAGE_REFERENCE_NODE) { return imageReferenceToken(String(node.attrs.attachmentId)) } diff --git a/src/renderer/src/components/native-chat/use-native-chat-composer-handle.ts b/src/renderer/src/components/native-chat/use-native-chat-composer-handle.ts index 5d4e85b68ac3..901ea62cfd23 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-composer-handle.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-composer-handle.ts @@ -49,6 +49,15 @@ export function useNativeChatComposerHandle( useImperativeHandle( ref, () => ({ + insertAgentReferences: (references) => { + const input = textareaRef.current + if (!input || input.disabled || !input.insertAgentReferences || isComposing()) { + return false + } + input.insertAgentReferences(references) + input.focus() + return true + }, focus, insertTypedText, acceptsText, @@ -58,6 +67,8 @@ export function useNativeChatComposerHandle( contains }), [ + textareaRef, + isComposing, focus, insertTypedText, acceptsText, diff --git a/src/renderer/src/components/native-chat/use-native-chat-composer-submit.ts b/src/renderer/src/components/native-chat/use-native-chat-composer-submit.ts index 7733e82ec15b..a2bc134eed8e 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-composer-submit.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-composer-submit.ts @@ -1,3 +1,4 @@ +import { serializeNativeChatAgentReferences } from './native-chat-agent-reference-send' import { useCallback, useMemo, useState } from 'react' import { translate } from '@/i18n/i18n' import { applyPickerSuggestion } from '../../../../shared/native-chat/input/native-chat-picker-triggers' @@ -72,7 +73,13 @@ export function useNativeChatComposerSubmit(args: { // Clear only the submitted draft after host acceptance; the goal controller refuses concurrent submissions. const setGoal = useCallback(() => { const objective = structuredAgentSessionGoalObjective( - resolveNativeChatPastedText(draftScopeKey, draft) + resolveNativeChatPastedText( + draftScopeKey, + serializeNativeChatAgentReferences( + draft, + readNativeChatComposerDraft(draftScopeKey).document + ) + ) ) if (!threadGoal || !structuredTransport || objective === '') { return diff --git a/src/renderer/src/components/native-chat/use-native-chat-context-menu.find.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-context-menu.find.test.tsx index d55099e11592..fa4570727ed6 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-context-menu.find.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-context-menu.find.test.tsx @@ -23,6 +23,7 @@ function Chat(): React.JSX.Element { composerElementRef.current?.focus() return true }, + insertAgentReferences: () => false, insertTypedText: () => true, acceptsText: () => true, appendText: () => {}, diff --git a/src/renderer/src/components/native-chat/use-native-chat-context-menu.targets.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-context-menu.targets.test.tsx index 7eea1a525b49..30da79a4559a 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-context-menu.targets.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-context-menu.targets.test.tsx @@ -55,6 +55,7 @@ function Chat({ const rootRef = useRef(null) const composerRef = useRef({ focus: () => true, + insertAgentReferences: () => false, insertTypedText: () => true, acceptsText: () => acceptsText, appendText: mocks.appendText, diff --git a/src/renderer/src/components/native-chat/use-native-chat-find.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-find.test.tsx index 2fb8de24d0d0..04d4b2423e5b 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-find.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-find.test.tsx @@ -37,6 +37,7 @@ function composerHandle(): Composer { handle.element.focus() return true }), + insertAgentReferences: () => false, insertTypedText: vi.fn(() => true), appendText: vi.fn(), acceptsText: () => true, diff --git a/src/renderer/src/components/native-chat/use-native-chat-pty-composer-send.ts b/src/renderer/src/components/native-chat/use-native-chat-pty-composer-send.ts index ef9ccb137e1d..b53e43918ec7 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-pty-composer-send.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-pty-composer-send.ts @@ -1,3 +1,5 @@ +import { readNativeChatComposerDraft } from './native-chat-composer-draft-store' +import { serializeNativeChatAgentReferences } from './native-chat-agent-reference-send' import { admitNativeChatPastedText, resolveNativeChatPastedText @@ -74,7 +76,13 @@ export function useNativeChatPtyComposerSend(args: { if (!admitNativeChatPastedText(args.draftScopeKey, text, args.setNotice)) { return } - text = resolveNativeChatPastedText(args.draftScopeKey, text) + text = resolveNativeChatPastedText( + args.draftScopeKey, + serializeNativeChatAgentReferences( + text, + readNativeChatComposerDraft(args.draftScopeKey).document + ) + ) const { sendOptions: launchSendOptions } = resolveNativeChatLaunchDraftSend({ launchDraft: args.launchDraft, launchDraftResolved: args.launchDraftResolved, diff --git a/src/renderer/src/components/native-chat/use-native-chat-root-input-routing.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-root-input-routing.test.tsx index 6d1ee8a99e40..cd6b9bd7f798 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-root-input-routing.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-root-input-routing.test.tsx @@ -13,6 +13,7 @@ vi.mock('@/lib/visible-overlay', () => ({ hasVisibleOverlay: () => overlay.visib const insertTypedText = vi.fn(() => true) const composer: NativeChatComposerHandle = { focus: () => true, + insertAgentReferences: () => false, insertTypedText, appendText: () => {}, acceptsText: () => true, diff --git a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts index a3b315023df7..a07219cb4c0c 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts @@ -1,3 +1,4 @@ +import { serializeNativeChatAgentReferences } from './native-chat-agent-reference-send' import { getAgentLabel } from '@/lib/agent-catalog' import { formatAgentTypeLabel } from '../../../../shared/agent-type-label' import { isTuiAgent } from '../../../../shared/tui-agent-config' @@ -77,6 +78,8 @@ export function useNativeChatStructuredComposerSend({ if (!admitNativeChatPastedText(draftScopeKey, text, structuredTransport.onError)) { return } + const submitted = readNativeChatComposerDraft(draftScopeKey) + const submittedText = text text = resolveNativeChatPastedText(draftScopeKey, text) const hostCommand = isNativeChatStructuredHostCommand(text, agent, structuredTransport) // Blocked hosts cannot take turns/conversation commands; option commands only configure later turns. @@ -106,7 +109,12 @@ export function useNativeChatStructuredComposerSend({ structuredTransport.onSubmitted?.() } const isCurrent = structuredTransport.capturePresentation() - const submitted = readNativeChatComposerDraft(draftScopeKey) + if (!hostCommand) { + text = resolveNativeChatPastedText( + draftScopeKey, + serializeNativeChatAgentReferences(submittedText, submitted.document) + ) + } await dispatchNativeChatStructuredComposerText( structuredTransport, text, diff --git a/src/renderer/src/components/orchestration-crew/NativeChatCrewPanel.tsx b/src/renderer/src/components/orchestration-crew/NativeChatCrewPanel.tsx index 5eab3d5780af..cd1c474ce523 100644 --- a/src/renderer/src/components/orchestration-crew/NativeChatCrewPanel.tsx +++ b/src/renderer/src/components/orchestration-crew/NativeChatCrewPanel.tsx @@ -1,15 +1,21 @@ import { formatOrcaSessionAddress, isOrcaSessionId } from '../../../../shared/orca-session-address' +import type { RefObject } from 'react' +import type { NativeChatComposerHandle } from '../native-chat/native-chat-composer-types' import { OrchestrationCrewPanel } from './OrchestrationCrewPanel' import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' export function NativeChatCrewPanel({ target, party: suppliedParty, - sessionId + sessionId, + composerRef, + canMention }: { target: RuntimeClientTarget | null party?: string | null sessionId?: string + composerRef: RefObject + canMention: boolean }): React.JSX.Element | null { const party = suppliedParty ?? @@ -17,5 +23,19 @@ export function NativeChatCrewPanel({ if (!target || !party) { return null } - return + const hostKey = target.kind === 'local' ? 'local' : target.environmentId + return ( + { + composerRef.current?.insertAgentReferences( + rows.flatMap((row) => + row.sendAddress ? [{ label: row.label, address: row.sendAddress, hostKey }] : [] + ) + ) + }} + /> + ) } diff --git a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx index 169851d3774d..6a173d716ca6 100644 --- a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx +++ b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx @@ -83,17 +83,30 @@ function IconButton({ ) } +function runningWorker(row: OrchestrationCrewRow): boolean { + return Boolean( + row.sendAddress && + row.task && + !['completed', 'failed'].includes(row.task.state) && + (row.task.state === 'dispatched' || ['working', 'waiting', 'blocked'].includes(row.status)) + ) +} + type PanelProps = { target: RuntimeClientTarget party: string + canMention: boolean + mention: (rows: OrchestrationCrewRow[]) => void } export function OrchestrationCrewPanel(props: PanelProps): React.JSX.Element | null { const snapshot = useOrchestrationCrew(props.target, props.party) return } -function CrewPanelContent({ +export function CrewPanelContent({ target, + canMention, + mention, snapshot }: PanelProps & { snapshot: OrchestrationCrewSnapshot }): React.JSX.Element | null { const [open, setOpen] = useState(false) @@ -164,9 +177,26 @@ function CrewPanelContent({
{title} {rows.length} + {title === 'Managing' ? ( + + ) : null}
{rows.map((row) => ( - + mention([row])} + /> ))} ) : null @@ -211,7 +241,17 @@ function CrewPanelContent({ ) } -function CrewRowView({ row, target }: { row: OrchestrationCrewRow; target: RuntimeClientTarget }) { +function CrewRowView({ + row, + target, + canMention, + mention +}: { + row: OrchestrationCrewRow + target: RuntimeClientTarget + canMention: boolean + mention: () => void +}) { const [disclosure, setDisclosure] = useState<{ question?: string; expanded: boolean }>() const question = row.pendingQuestion?.at const expanded = @@ -227,8 +267,9 @@ function CrewRowView({ row, target }: { row: OrchestrationCrewRow; target: Runti event.preventDefault()}> + + Mention in message + Open its chat state.terminalLayoutsByTabId[tabId]?.ptyIdsByLeafId?.[pane.leafId] ?? null @@ -27,8 +30,32 @@ function TerminalCrewPortal({ if (!target || !party || !transport) { return null } + const captured = captureTerminalDropTarget(pane, transport) + const hostKey = target.kind === 'local' ? 'local' : target.environmentId return createPortal( - , + { + const manager = managerRef.current + const references = rows.flatMap((row) => + row.sendAddress ? [{ label: row.label, address: row.sendAddress, hostKey }] : [] + ) + if (manager) { + void insertTerminalCrewMention( + manager, + paneTransportsRef.current, + captured, + references + ).then((accepted) => { + if (!accepted) { + toast.error('The terminal did not accept the agent reference. Try again.') + } + }) + } + }} + />, pane.container, `crew-${pane.id}` ) diff --git a/src/renderer/src/components/terminal-pane/terminal-crew-mention.ts b/src/renderer/src/components/terminal-pane/terminal-crew-mention.ts new file mode 100644 index 000000000000..a3ec445b12c7 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/terminal-crew-mention.ts @@ -0,0 +1,25 @@ +import type { PaneManager } from '@/lib/pane-manager/pane-manager' +import { + terminalAgentReference, + type OrchestrationAgentReference +} from '../../../../shared/orchestration-agent-reference' +import { + getCurrentTerminalDropTransport, + type CapturedTerminalDropTarget +} from './terminal-drop-target' +import { writeTerminalPastePtyInput } from './terminal-pty-paste-writer' +import type { PtyTransport } from './pty-transport-types' + +export async function insertTerminalCrewMention( + manager: PaneManager, + transports: Map, + target: CapturedTerminalDropTarget, + references: OrchestrationAgentReference[] +): Promise { + const parts = references.map(terminalAgentReference) + if (parts.length === 0 || parts.some((part) => part === null)) { + return false + } + const transport = getCurrentTerminalDropTransport(manager, transports, target) + return transport ? await writeTerminalPastePtyInput(transport, parts.join(''), 'driving') : false +} diff --git a/src/shared/orchestration-agent-reference.ts b/src/shared/orchestration-agent-reference.ts index de75c73bfcd7..a018b628e79d 100644 --- a/src/shared/orchestration-agent-reference.ts +++ b/src/shared/orchestration-agent-reference.ts @@ -1,8 +1,29 @@ import { parseOrcaSessionAddress } from './orca-session-address' +export type OrchestrationAgentReference = { label: string; address: string; hostKey: string } + export function isPublicOrchestrationAddress(address: string): boolean { return ( /^(?:term_[a-zA-Z0-9_-]+|(?:dispatch|run):[a-zA-Z0-9_-]+)$/.test(address) || parseOrcaSessionAddress(address) !== null ) } + +export function printableAgentLabel(label: string): string { + return [...label.replace(/[\r\n\u2028\u2029]/g, ' ')] + .filter( + (char) => + char.charCodeAt(0) >= 32 && !(char.charCodeAt(0) >= 127 && char.charCodeAt(0) <= 159) + ) + .join('') +} + +export function agentReferenceToken(reference: OrchestrationAgentReference): string { + return `@${reference.label} (Orca agent ${reference.address})` +} + +export function terminalAgentReference(reference: OrchestrationAgentReference): string | null { + return isPublicOrchestrationAddress(reference.address) + ? `${printableAgentLabel(reference.label)} (Orca agent ${reference.address}) ` + : null +} From 4ab8442bf59574a6755874fc80f39854ce8dd847 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 05:55:21 -0700 Subject: [PATCH 013/164] Document the trusted Dispatch SQL row boundary --- .../orchestration/db/dispatch-context/dispatch-lookup.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts b/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts index 15bea2c788ef..aeeae762eea9 100644 --- a/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts +++ b/src/main/runtime/orchestration/db/dispatch-context/dispatch-lookup.ts @@ -48,8 +48,7 @@ export function listSessionDispatchesForPresentation( now: number ): { dispatch: DispatchContextRow; order: number }[] { const lowerBound = new Date(now - AGENT_STATUS_STALE_AFTER_MS - 86_400_000).toISOString() - // SAFETY: explicit Dispatch columns plus SQLite's internal ordering identity. - const candidates = this.db + const rawCandidates = this.db .prepare(` SELECT rowid AS presentation_order, ${DISPATCH_CONTEXT_COLUMN_LIST} FROM dispatch_contexts INDEXED BY idx_dispatch_session_presentation @@ -60,7 +59,9 @@ export function listSessionDispatchesForPresentation( WHERE assignee_orca_session_id IS NOT NULL AND status IN ('completed', 'failed', 'circuit_broken') AND completed_at >= ? `) - .all(lowerBound) as (DispatchContextRow & { presentation_order: number })[] + .all(lowerBound) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The complete schema-pinned Dispatch projection restores the persisted-row contract; the default integer wrapper normalizes rowid to a safe number. + const candidates = rawCandidates as (DispatchContextRow & { presentation_order: number })[] const newestActiveOrderBySession = new Map() const selected = new Map() for (const candidate of candidates) { From e3a08bb7a04eb1236a72ce6d335f0bc2e325094f Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 06:26:50 -0700 Subject: [PATCH 014/164] Keep lineage integration imports within their test programs --- ...index-omitted-host-scope-selectors.test.ts | 32 ++++++++--------- ...time-agent-lineage-catalog.test-fixture.ts | 19 ++++++++++ .../runtime-agent-lineage.test-fixture.ts | 8 +++++ ...ime-agent-orchestration-projection.test.ts | 2 +- ...mirrored-terminal-lineage.test-fixture.tsx | 14 ++++++-- ...worktree-agent-rows-subscriptions.test.tsx | 23 ++++++++---- .../runtime/visible-agent-orchestration.ts | 2 +- ...ime-agent-lineage-consumer.test-fixture.ts | 35 +++++++++++++++++++ 8 files changed, 107 insertions(+), 28 deletions(-) create mode 100644 src/main/runtime/runtime-agent-lineage-catalog.test-fixture.ts create mode 100644 src/shared/runtime-agent-lineage-consumer.test-fixture.ts diff --git a/src/cli/index-omitted-host-scope-selectors.test.ts b/src/cli/index-omitted-host-scope-selectors.test.ts index 09a98489c2d0..3844585eef7f 100644 --- a/src/cli/index-omitted-host-scope-selectors.test.ts +++ b/src/cli/index-omitted-host-scope-selectors.test.ts @@ -43,15 +43,10 @@ vi.mock('child_process', async (importOriginal) => { }) import { main } from './index' -import { - publicLineageFixture, - canonicalChatRow, - LINEAGE_PARENT, - LINEAGE_CHILD -} from '../main/runtime/runtime-agent-lineage.test-fixture' -import { OrcaRuntimeService } from '../main/runtime/orca-runtime' -import { RpcDispatcher } from '../main/runtime/rpc/dispatcher' -import { WORKTREE_CATALOG_METHODS } from '../main/runtime/rpc/methods/worktree-catalog-methods' +import type { + RuntimeAgentLineageTestModule, + RuntimeAgentLineageCatalogTestModule +} from '../shared/runtime-agent-lineage-consumer.test-fixture' import { COMMAND_SPECS } from './specs' import { okFixture, queueFixtures } from './test-fixtures' import { pairRuntimeEnvironment, useWorktreeAwarenessEnvironment } from './index-test-harness' @@ -85,16 +80,19 @@ describe('omittedHostIds selector annotation', () => { it.each(['repo::/workspace', 'folder:lineage'])( 'prints canonical production-built lineage through actual CLI and worktree RPC for %s', async (worktreeId) => { + const { + default: { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } + } = await vi.importActual<{ default: RuntimeAgentLineageTestModule }>( + '../main/runtime/runtime-agent-lineage.test-fixture' + ) + const { + default: { createLineageCatalogDispatcher } + } = await vi.importActual<{ default: RuntimeAgentLineageCatalogTestModule }>( + '../main/runtime/runtime-agent-lineage-catalog.test-fixture' + ) const f = publicLineageFixture(worktreeId) try { - const runtime = new OrcaRuntimeService() - vi.spyOn(runtime, 'getRuntimeId').mockReturnValue('lineage-test') - vi.spyOn(runtime, 'getWorktreePs').mockImplementation(async () => ({ - worktrees: [f.build()], - totalCount: 1, - truncated: false - })) - const dispatcher = new RpcDispatcher({ runtime, methods: WORKTREE_CATALOG_METHODS }) + const dispatcher = createLineageCatalogDispatcher(f.build) const resultOf = (response: unknown) => JSON.parse(JSON.stringify(response)).result const request = (params = {}) => dispatcher.dispatch({ diff --git a/src/main/runtime/runtime-agent-lineage-catalog.test-fixture.ts b/src/main/runtime/runtime-agent-lineage-catalog.test-fixture.ts new file mode 100644 index 000000000000..105317b0486f --- /dev/null +++ b/src/main/runtime/runtime-agent-lineage-catalog.test-fixture.ts @@ -0,0 +1,19 @@ +import { vi } from 'vitest' +import { OrcaRuntimeService } from './orca-runtime' +import { RpcDispatcher } from './rpc/dispatcher' +import { WORKTREE_CATALOG_METHODS } from './rpc/methods/worktree-catalog-methods' +import type { RuntimeWorktreePsSummary } from '../../shared/runtime-types' +import type { RuntimeAgentLineageCatalogTestModule } from '../../shared/runtime-agent-lineage-consumer.test-fixture' + +export function createLineageCatalogDispatcher(build: () => RuntimeWorktreePsSummary) { + const runtime = new OrcaRuntimeService() + vi.spyOn(runtime, 'getRuntimeId').mockReturnValue('lineage-test') + vi.spyOn(runtime, 'getWorktreePs').mockImplementation(async () => ({ + worktrees: [build()], + totalCount: 1, + truncated: false + })) + return new RpcDispatcher({ runtime, methods: WORKTREE_CATALOG_METHODS }) +} + +export default { createLineageCatalogDispatcher } satisfies RuntimeAgentLineageCatalogTestModule diff --git a/src/main/runtime/runtime-agent-lineage.test-fixture.ts b/src/main/runtime/runtime-agent-lineage.test-fixture.ts index 755e6d59cc50..19e9ad08a100 100644 --- a/src/main/runtime/runtime-agent-lineage.test-fixture.ts +++ b/src/main/runtime/runtime-agent-lineage.test-fixture.ts @@ -1,4 +1,5 @@ import { OrchestrationDb } from './orchestration/db' +import type { RuntimeAgentLineageTestModule } from '../../shared/runtime-agent-lineage-consumer.test-fixture' import { RuntimeAgentOrchestrationProjection } from './runtime-agent-orchestration-projection' import { attachRuntimeWorktreeAgentRows } from './runtime-worktree-agent-rows' import type { RuntimeWorktreePsSummary } from '../../shared/runtime-types' @@ -118,3 +119,10 @@ export function publicLineageFixture(worktreeId = 'repo::/workspace') { } return { db, projection, build, privateHandle, privatePane, run } } + +export default { + publicLineageFixture, + canonicalChatRow, + LINEAGE_PARENT, + LINEAGE_CHILD +} satisfies RuntimeAgentLineageTestModule diff --git a/src/main/runtime/runtime-agent-orchestration-projection.test.ts b/src/main/runtime/runtime-agent-orchestration-projection.test.ts index c1c4b9667c33..4b12e1825789 100644 --- a/src/main/runtime/runtime-agent-orchestration-projection.test.ts +++ b/src/main/runtime/runtime-agent-orchestration-projection.test.ts @@ -254,7 +254,7 @@ it.each([20, 200])( insertHistory.run(n, `expired-handled-${i}-`, run.id, historyTask.id, `ordinary-${i}`) } let endpoint = n - const read = vi.fn((id: string) => { + const read = vi.fn((id: string): ReturnType | null => { const record = sessionRecord(id) const index = id === SESSION_X ? 0 : id.startsWith('edge-') ? Number(id.slice(5)) : endpoint return agentSessionConversationView( diff --git a/src/renderer/src/components/sidebar/mirrored-terminal-lineage.test-fixture.tsx b/src/renderer/src/components/sidebar/mirrored-terminal-lineage.test-fixture.tsx index d0460a179241..355eb91b192e 100644 --- a/src/renderer/src/components/sidebar/mirrored-terminal-lineage.test-fixture.tsx +++ b/src/renderer/src/components/sidebar/mirrored-terminal-lineage.test-fixture.tsx @@ -1,5 +1,7 @@ import { act } from 'react' -import { expect } from 'vitest' +import { expect, vi } from 'vitest' +import type { RuntimeAgentLineageTestModule } from '../../../../shared/runtime-agent-lineage-consumer.test-fixture' +import { isStructuredTab } from '../../../../shared/structured-agent-session-tab' import { useAppStore } from '@/store' import type { AppState } from '@/store/types' import type { DashboardAgentRow } from '@/components/dashboard/useDashboardData' @@ -23,8 +25,11 @@ export async function verifyMirroredTerminalLineage( getRows: () => DashboardAgentRow[] } ): Promise { - const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = - await import('../../../../main/runtime/runtime-agent-lineage.test-fixture') + const { + default: { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } + } = await vi.importActual<{ default: RuntimeAgentLineageTestModule }>( + '../../../../main/runtime/runtime-agent-lineage.test-fixture' + ) const { makeUnifiedTab, makeWorktree, TEST_REPO } = await import('@/store/slices/store-test-helpers') const { selectDashboardOrchestration } = @@ -90,6 +95,9 @@ export async function verifyMirroredTerminalLineage( ], Date.now() )[0].unifiedTab + if (!isStructuredTab(native)) { + throw new Error('Expected the mirrored native session tab') + } const actualParent = pane(native.id, LINEAGE_PARENT) const tab = makeTab({ id: toWebTerminalSurfaceTabId('host-terminal'), diff --git a/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx b/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx index a81928ac118f..5314c582d5dc 100644 --- a/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx +++ b/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx @@ -13,6 +13,8 @@ import { type AgentStatusEntry } from '../../../../shared/agent-status-types' import { useWorktreeAgentRows } from './useWorktreeAgentRows' +import type { RuntimeAgentLineageTestModule } from '../../../../shared/runtime-agent-lineage-consumer.test-fixture' +import { isStructuredTab } from '../../../../shared/structured-agent-session-tab' Reflect.set(globalThis, 'IS_REACT_ACT_ENVIRONMENT', true) @@ -356,8 +358,8 @@ it.each([20, 200])( } }) expect( - observed.get(0)?.find((row) => row.paneKey === pane('child-actual-0', 'child-0')) - ?.parentPaneKey + observed.get(0)?.find((row) => row.paneKey === pane('child-actual-0', 'child-0'))?.entry + .orchestration?.parentPaneKey ).not.toBe(pane('parent-actual-0', 'parent-0')) for (let i = 1; i < n; i++) { expect(observed.get(i)).toBe(initial.get(i)) @@ -369,6 +371,9 @@ it.each([20, 200])( const { projectStatus } = await import('@/components/native-chat/structured-agent-session-status-projection') const foreignTab = tabs[`lineage-${n - 1}`][1] + if (!isStructuredTab(foreignTab)) { + throw new Error('Expected the native session tab') + } act(() => useAppStore.getState().transactAgentStatuses((transaction) => projectStatus( @@ -404,8 +409,11 @@ it.each([20, 200])( ) it('joins production mirrored custom/collision rows locally and keeps canonical initial, graph, retained and consumer contexts', async () => { - const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = - await import('../../../../main/runtime/runtime-agent-lineage.test-fixture') + const { + default: { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } + } = await vi.importActual<{ default: RuntimeAgentLineageTestModule }>( + '../../../../main/runtime/runtime-agent-lineage.test-fixture' + ) const { makeUnifiedTab, makeWorktree, TEST_REPO } = await import('@/store/slices/store-test-helpers') const { buildMirroredAgentTabs } = @@ -636,8 +644,11 @@ it.each(['default', 'reserved', 'collision'] as const)( ) it('settles the production graph subscription/scheduler/publication/receiver loop with at most one feedback flight', async () => { - const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = - await import('../../../../main/runtime/runtime-agent-lineage.test-fixture') + const { + default: { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } + } = await vi.importActual<{ default: RuntimeAgentLineageTestModule }>( + '../../../../main/runtime/runtime-agent-lineage.test-fixture' + ) const { useRuntimeGraphSync } = await import('@/app-shell/use-runtime-graph-sync') const { setRuntimeGraphSyncEnabled, setRuntimeGraphStoreStateGetter } = await import('@/runtime/sync-runtime-graph') diff --git a/src/renderer/src/runtime/visible-agent-orchestration.ts b/src/renderer/src/runtime/visible-agent-orchestration.ts index 8e593b828f61..f1a0b634a714 100644 --- a/src/renderer/src/runtime/visible-agent-orchestration.ts +++ b/src/renderer/src/runtime/visible-agent-orchestration.ts @@ -33,7 +33,7 @@ export type VisibleOrchestrationState = WorktreeRuntimeOwnerState & > & { tabsByWorktree?: Record } -const EMPTY = {} +const EMPTY: Record = {} const producerByContext = new WeakMap() export function orchestrationProducer(context: AgentStatusOrchestrationContext): string { return producerByContext.get(context) ?? LOCAL_EXECUTION_HOST_ID diff --git a/src/shared/runtime-agent-lineage-consumer.test-fixture.ts b/src/shared/runtime-agent-lineage-consumer.test-fixture.ts new file mode 100644 index 000000000000..ef7febdedde6 --- /dev/null +++ b/src/shared/runtime-agent-lineage-consumer.test-fixture.ts @@ -0,0 +1,35 @@ +import type { AgentStatusOrchestrationContext } from './agent-status-types' +import type { OrcaSessionId } from './orca-session-address' +import type { RuntimeRpcResponse } from './runtime-rpc-envelope' +import type { RuntimeWorktreePsSummary } from './runtime-types' + +// Keep desktop-only imports in the native fixture; its export checks this consumer contract. +export type RuntimeAgentLineageTestModule = { + LINEAGE_PARENT: OrcaSessionId + LINEAGE_CHILD: OrcaSessionId + canonicalChatRow(id: string): string + publicLineageFixture(worktreeId?: string): { + db: { + db: { prepare(sql: string): { run(...values: string[]): unknown } } + close(): void + } + projection: { + buildByPaneKey(): Record | undefined + } + build(): RuntimeWorktreePsSummary + privateHandle: string + privatePane: string + run: { id: string } + } +} + +export type RuntimeAgentLineageCatalogTestModule = { + createLineageCatalogDispatcher(build: () => RuntimeWorktreePsSummary): { + dispatch(request: { + id: string + authToken: string + method: string + params?: Record + }): Promise> + } +} From 4f61440b1c16ed1ca3ce0d846d2921c26db5a93d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 06:30:54 -0700 Subject: [PATCH 015/164] Preserve selected agent assignments in captured submissions --- .../native-chat-agent-reference-send.test.tsx | 116 +++++++ .../native-chat-agent-reference-send.ts | 163 ++++++++-- .../native-chat-agent-reference.test.tsx | 284 +++++++++++++++++- ...ve-chat-composer-pasted-text-references.ts | 18 +- .../use-native-chat-composer-submit.ts | 15 +- .../use-native-chat-pty-composer-send.ts | 14 +- ...se-native-chat-structured-composer-send.ts | 16 +- .../TerminalCrewPortals.test.tsx | 159 ++++++++++ .../TerminalCrewPortals.tsx | 16 +- .../structured-agent-session-composer.ts | 4 + 10 files changed, 737 insertions(+), 68 deletions(-) create mode 100644 src/renderer/src/components/native-chat/native-chat-agent-reference-send.test.tsx create mode 100644 src/renderer/src/components/orchestration-crew/TerminalCrewPortals.test.tsx diff --git a/src/renderer/src/components/native-chat/native-chat-agent-reference-send.test.tsx b/src/renderer/src/components/native-chat/native-chat-agent-reference-send.test.tsx new file mode 100644 index 000000000000..c8ec9f7f4198 --- /dev/null +++ b/src/renderer/src/components/native-chat/native-chat-agent-reference-send.test.tsx @@ -0,0 +1,116 @@ +// @vitest-environment happy-dom +import type { JSONContent } from '@tiptap/react' +import { expect, it } from 'vitest' +import { + agentReferenceToken, + type OrchestrationAgentReference +} from '../../../../shared/orchestration-agent-reference' +import { serializeNativeChatAgentReferences } from './native-chat-agent-reference-send' +import { nativeChatPastedTextToken } from './native-chat-pasted-text-reference' +import { formatNativeChatFileReference } from '../../../../shared/agent-image-paste' + +const alpha = { label: 'Worker', address: 'term_alpha', hostKey: 'local' } +const beta = { ...alpha, address: 'term_beta' } +export function submission(parts: (string | OrchestrationAgentReference)[]) { + const text = parts + .map((part) => (typeof part === 'string' ? part : agentReferenceToken(part))) + .join('') + const document: JSONContent = { + type: 'doc', + content: [ + { + type: 'paragraph', + content: parts.map((part) => + typeof part === 'string' + ? { type: 'text', text: part } + : { type: 'nativeChatAgentReference', attrs: part } + ) + } + ] + } + return { text, document } +} +const line = (label: string, address: string) => + `[Orca agent "${label}": ${address} — message it with orca orchestration send --to ${address}]` +function send(parts: (string | OrchestrationAgentReference)[]) { + const { text, document } = submission(parts) + return serializeNativeChatAgentReferences(text, document) +} + +it('preserves occurrence identity for repeated collisions and stored-label variants without changing ordinary bytes', () => { + const a = send([alpha, ' tests; ', beta, ' docs; ', alpha, ' tests; ', beta, ' docs']) + const b = send([alpha, ' tests; ', beta, ' docs; ', beta, ' tests; ', alpha, ' docs']) + expect(a).not.toBe(b) + expect(a).toBe( + `@Worker (1) tests; @Worker (2) docs; @Worker (1) tests; @Worker (2) docs\n\n${line('Worker (1)', alpha.address)}\n${line('Worker (2)', beta.address)}` + ) + const old = { ...alpha, label: 'Old' }, + other = { ...beta, label: 'Other' } + expect(send([old, ' ', other, ' ', alpha, ' tests ', old, ' ', other])).not.toBe( + send([old, ' ', other, ' ', { ...beta, label: 'Worker' }, ' tests ', old, ' ', other]) + ) + expect(send([old, ' ', alpha, ' ', old])).toBe( + `@Old (1) @Old (1) @Old (1)\n\n${line('Old (1)', alpha.address)}` + ) + expect(send(['Ask ', alpha, ' then ', alpha])).toBe( + `Ask @Worker then @Worker\n\n${line('Worker', alpha.address)}` + ) + const raw = submission(['ordinary @Worker ', alpha]) + const before = structuredClone(raw) + serializeNativeChatAgentReferences(raw.text, raw.document) + expect(raw).toEqual(before) + expect(serializeNativeChatAgentReferences(`${raw.text} changed`, raw.document)).toBe( + `${raw.text} changed` + ) + expect(serializeNativeChatAgentReferences(raw.text)).toBe(raw.text) +}) + +it('reserves globally against real labels, authored suffixes and the completed file projection, preserving host tuple dedupe', () => { + const id = '11111111-1111-4111-8111-111111111111' + const token = nativeChatPastedTextToken(id) + const path = '/tmp/Worker (3).txt' + const raw = submission([ + alpha, + ' ', + beta, + ' ', + { ...alpha, address: 'term_real', label: 'Worker (1)' }, + ' authored (2) ', + token, + ' ', + { ...alpha, hostKey: 'remote' } + ]) + const result = serializeNativeChatAgentReferences(raw.text, raw.document, { [id]: path }) + expect(result).toContain( + `@Worker (4) @Worker (5) @Worker (1) authored (2) ${formatNativeChatFileReference(path)} @Worker (6)` + ) + expect(result).toContain(line('Worker (4)', alpha.address)) + expect(result).toContain(line('Worker (6)', alpha.address)) + expect(result.match(/\[Orca agent/g)).toHaveLength(4) + const huge = '9'.repeat(400) + expect(send([alpha, ` (${huge}) `, beta, ' (1) (01)'])).toContain('@Worker (2)') + expect(send(['authored\0@', alpha, '\0', beta])).toContain('@Worker (1)\0@Worker (2)') + const ordinary = submission(['before', token, alpha, 'after']) + expect( + serializeNativeChatAgentReferences(ordinary.text, ordinary.document, { [id]: '/tmp/plain.txt' }) + ).toBe( + `before ${formatNativeChatFileReference('/tmp/plain.txt')} @Workerafter\n\n${line('Worker', alpha.address)}` + ) +}) + +it('frames only generated label data safely, including normalization collisions and empty control-only labels', () => { + const dangerous = { ...alpha, label: 'Zoë"\\]\r\n\u001b\u0085\u2028[' } + const safe = 'Zoë\\"\\\\\\] \\[' + expect(send(['literal [Orca agent "authored"] ', dangerous])).toBe( + `literal [Orca agent "authored"] @${safe}\n\n${line(safe, alpha.address)}` + ) + expect(send([{ ...alpha, label: '\u0000\u001b\u0085' }])).toBe( + `@Agent\n\n${line('Agent', alpha.address)}` + ) + expect(send([{ ...alpha, label: 'A\nB' }, ' ', { ...beta, label: 'A B' }])).toBe( + `@A B (1) @A B (2)\n\n${line('A B (1)', alpha.address)}\n${line('A B (2)', beta.address)}` + ) + expect(send(['ordinary @Worker ', { ...alpha, address: 'term_bad\n' }])).toBe( + 'ordinary @Worker @Worker (Orca agent term_bad\n)' + ) +}) diff --git a/src/renderer/src/components/native-chat/native-chat-agent-reference-send.ts b/src/renderer/src/components/native-chat/native-chat-agent-reference-send.ts index 29b556e35dd0..d57528be376b 100644 --- a/src/renderer/src/components/native-chat/native-chat-agent-reference-send.ts +++ b/src/renderer/src/components/native-chat/native-chat-agent-reference-send.ts @@ -3,53 +3,156 @@ import { imageReferenceToken } from '../../../../shared/native-chat-image-refere import { agentReferenceToken, isPublicOrchestrationAddress, + printableAgentLabel, type OrchestrationAgentReference } from '../../../../shared/orchestration-agent-reference' +import { projectNativeChatPastedText } from './native-chat-composer-pasted-text-references' -/** Only the document matching this submission can contribute selected targets. */ -export function serializeNativeChatAgentReferences(text: string, document?: JSONContent): string { - const references = new Map() - const render = (node: JSONContent, wire: boolean): string => { +type SelectedReference = { + reference: OrchestrationAgentReference + labels: Set + safeLabels: Set + label: string + affected: boolean +} + +function framedLabel(label: string): string { + return printableAgentLabel(label).replace(/[\\"[\]]/g, '\\$&') || 'Agent' +} + +/** Only a matching submitted document contributes targets; delivery owns the finished plain text. */ +export function serializeNativeChatAgentReferences( + text: string, + document?: JSONContent, + files: Readonly> = {} +): string { + const selected = new Map() + const occurrences: (SelectedReference | string)[] = [] + const render = (node: JSONContent): string => { if (node.type === 'nativeChatAgentReference') { const { label, address, hostKey } = node.attrs ?? {} if (typeof label !== 'string' || typeof address !== 'string' || typeof hostKey !== 'string') { return '' } const reference = { label, address, hostKey } - if (wire && isPublicOrchestrationAddress(address)) { - references.set(JSON.stringify([hostKey, address]), reference) - return `@${label}` + const literal = agentReferenceToken(reference) + if (isPublicOrchestrationAddress(address)) { + const key = JSON.stringify([hostKey, address]) + let target = selected.get(key) + if (!target) { + target = { + reference, + labels: new Set(), + safeLabels: new Set(), + label: framedLabel(label), + affected: false + } + selected.set(key, target) + } + target.labels.add(label) + target.safeLabels.add(framedLabel(label)) + occurrences.push(target) + } else { + occurrences.push(literal) } - return agentReferenceToken(reference) + return literal } if (node.type === 'hardBreak') { + occurrences.push('\n') return '\n' } - if (node.type === 'nativeChatImageReference') { - return imageReferenceToken(String(node.attrs?.attachmentId)) + if (node.type === 'doc' || node.content) { + return (node.content ?? []) + .map((child, index) => { + if (node.type === 'doc' && index > 0) { + occurrences.push('\n') + } + return render(child) + }) + .join(node.type === 'doc' ? '\n' : '') + } + const plain = + node.type === 'nativeChatImageReference' + ? imageReferenceToken(String(node.attrs?.attachmentId)) + : (node.text ?? (typeof node.attrs?.token === 'string' ? node.attrs.token : '')) + occurrences.push(plain) + return plain + } + if (!document || render(document) !== text || selected.size === 0) { + return projectNativeChatPastedText(text, files) + } + const owners = new Map>() + const forbidden = new Set() + const spellings = new Set() + const reserve = (value: string) => { + for (const match of value.matchAll(/\(([1-9][0-9]*)\)/g)) { + forbidden.add(match[1]) + } + } + for (const target of selected.values()) { + for (const label of target.labels) { + reserve(label) } - if (node.text !== undefined) { - return node.text + for (const label of target.safeLabels) { + reserve(label) + spellings.add(label) + const keys = owners.get(label) ?? new Set() + keys.add(target) + owners.set(label, keys) } - if (typeof node.attrs?.token === 'string') { - return node.attrs.token + } + for (const target of selected.values()) { + target.affected = + target.labels.size > 1 || [...target.safeLabels].some((label) => owners.get(label)!.size > 1) + } + // A delimiter longer than every source run cannot occur in authored text or expanded file paths. + let longest = 0 + for (const value of [text, ...Object.values(files)]) { + for (const match of value.matchAll(/\0+/g)) { + longest = Math.max(longest, match[0].length) } - return (node.content ?? []) - .map((child) => render(child, wire)) - .join(node.type === 'doc' ? '\n' : '') } - if (!document || render(document, false) !== text) { - return text + const delimiter = `@${'\0'.repeat(longest + 1)}:` + const slots: { target: SelectedReference; tail: string }[] = [] + const template = occurrences + .map((part) => { + if (typeof part === 'string') { + return part + } + const tail = part.affected ? '' : (part.label.match(/\s+$/)?.[0] ?? '') + const index = slots.push({ target: part, tail }) - 1 + return `${delimiter}${index}${delimiter}${tail}` + }) + .join('') + const projected = projectNativeChatPastedText(template, files) + reserve(projected) + let suffix = 0 + for (const target of selected.values()) { + if (!target.affected) { + continue + } + // At most forbidden.size + selected.size candidates: each skipped number was captured above. + do { + suffix++ + } while (forbidden.has(String(suffix)) || spellings.has(`${target.label} (${suffix})`)) + forbidden.add(String(suffix)) + target.label = `${target.label} (${suffix})` + spellings.add(target.label) } - const wire = render(document, true) - return `${wire}${ - references.size === 0 - ? '' - : `\n\n${[...references.values()] - .map( - ({ label, address }) => - `[Orca agent "${label}": ${address} — message it with orca orchestration send --to ${address}]` - ) - .join('\n')}` - }` + const body = projected + .split(delimiter) + .map((part, index) => { + if (index % 2 === 0) { + return part + } + const { target, tail } = slots[Number(part)] + return `@${tail ? target.label.slice(0, -tail.length) : target.label}` + }) + .join('') + return `${body}\n\n${[...selected.values()] + .map( + ({ reference, label }) => + `[Orca agent "${label}": ${reference.address} — message it with orca orchestration send --to ${reference.address}]` + ) + .join('\n')}` } diff --git a/src/renderer/src/components/native-chat/native-chat-agent-reference.test.tsx b/src/renderer/src/components/native-chat/native-chat-agent-reference.test.tsx index 15f2d44815c9..79aac676f2fd 100644 --- a/src/renderer/src/components/native-chat/native-chat-agent-reference.test.tsx +++ b/src/renderer/src/components/native-chat/native-chat-agent-reference.test.tsx @@ -1,9 +1,22 @@ // @vitest-environment happy-dom +import { claudeDispatchMessageContent } from '../../../../main/claude/claude-structured-dispatch-content' +import { turnInputFor } from '../../../../main/codex/codex-structured-message-options' +import type { CodexTurnHost } from '../../../../main/codex/codex-structured-turn-start' +import { preparePiRpcPrompt } from '../../../../main/pi/rpc-prompt' +import type { NativeChatMessage } from '../../../../shared/native-chat-types' +import { + pendingSendsAsMessages, + prunePendingSends +} from '../../../../shared/native-chat-pending-sends' +import { useNativeChatComposerRecall } from './use-native-chat-composer-recall' +import { useNativeChatComposerKeyDown } from './use-native-chat-composer-keydown' +import { dispatchStructuredAgentSessionComposerCommand } from '../../../../shared/structured-agent-session-composer' +import { nativeChatPastedTextToken } from './native-chat-pasted-text-reference' import { CrewPanelContent } from '../orchestration-crew/OrchestrationCrewPanel' import { TooltipProvider } from '../ui/tooltip' import { emptyCrew, type OrchestrationCrewRow } from '../../../../shared/orchestration-crew' import { openOrchestrationCrewAgent } from '@/lib/open-agent-message-sender' -import { createRef } from 'react' +import { createRef, useRef, useState } from 'react' import { act, cleanup, render, renderHook, within, fireEvent } from '@testing-library/react' import { afterEach, expect, it, vi } from 'vitest' import type { PaneManager } from '@/lib/pane-manager/pane-manager' @@ -12,6 +25,7 @@ import type { NativeChatStructuredComposerTransport } from './native-chat-compos import type { NativeChatComposerInput } from './native-chat-composer-input' import { NativeChatPromptEditor } from './NativeChatPromptEditor' import { promptEditor } from './native-chat-prompt-editor.test-support' +import { promptText } from './native-chat-prompt-document' import { agentReferenceToken } from '../../../../shared/orchestration-agent-reference' import { serializeNativeChatAgentReferences } from './native-chat-agent-reference-send' import { useNativeChatStructuredComposerSend } from './use-native-chat-structured-composer-send' @@ -93,7 +107,7 @@ function transport(): NativeChatStructuredComposerTransport { } } -it('keeps a split’s caret, duplicate-name identities, literal copy/recall and atomic undo', async () => { +it('keeps a split’s caret, duplicate-name identities, literal unsent copy and atomic undo', async () => { const left = editor('left') const right = editor('right', 'Other draft') await act(async () => { @@ -107,7 +121,7 @@ it('keeps a split’s caret, duplicate-name identities, literal copy/recall and expect(left.container.querySelectorAll('[data-native-chat-agent-reference]')).toHaveLength(2) const doc = readNativeChatComposerDraft('left').document expect(serializeNativeChatAgentReferences(stored, doc)).toBe( - 'Hello @Same name @Same name \n\n[Orca agent "Same name": term_first — message it with orca orchestration send --to term_first]\n[Orca agent "Same name": dispatch:ctx_second — message it with orca orchestration send --to dispatch:ctx_second]' + 'Hello @Same name (1) @Same name (2) \n\n[Orca agent "Same name (1)": term_first — message it with orca orchestration send --to term_first]\n[Orca agent "Same name (2)": dispatch:ctx_second — message it with orca orchestration send --to dispatch:ctx_second]' ) expect(left.editor.getText()).toBe(stored) expect(serializeNativeChatAgentReferences('/model', doc)).toBe('/model') @@ -138,9 +152,27 @@ it('serializes before structured queue admission, PTY writes and goal submission pane.input.setSelectionRange(6, 6) pane.input.insertAgentReferences!([first, first, second]) }) + const fileId = '22222222-2222-4222-8222-222222222222' + act(() => pane.editor.commands.insertContent(` ${nativeChatPastedTextToken(fileId)}`)) + updateNativeChatComposerDraft( + 'send', + { pastedTextFiles: { [fileId]: '/tmp/Same name (1).txt' } }, + 'immediate' + ) const snapshot = readNativeChatComposerDraft('send') - const wire = serializeNativeChatAgentReferences(snapshot.text, snapshot.document) + const wire = serializeNativeChatAgentReferences( + snapshot.text, + snapshot.document, + snapshot.pastedTextFiles + ) const structured = transport() + structured.dispatchCommand = vi.fn((text) => + dispatchStructuredAgentSessionComposerCommand(text, { + snapshot: [], + invokeAction: async () => true, + setOption: async () => true + }) + ) const structuredHook = renderHook(() => useNativeChatStructuredComposerSend({ agent: 'claude', @@ -165,7 +197,15 @@ it('serializes before structured queue admission, PTY writes and goal submission delivery: 'queue-if-active' }) expect(entry).not.toBeNull() - updateNativeChatComposerDraft('send', { text: 'new draft', document: undefined }, 'immediate') + updateNativeChatComposerDraft( + 'send', + { + text: 'new draft/label/file', + document: undefined, + pastedTextFiles: { [fileId]: '/tmp/changed.txt' } + }, + 'immediate' + ) noteStructuredAgentSessionFence('test-session', 1) queuedRuntime.call.mockResolvedValue({ ok: true, @@ -194,6 +234,7 @@ it('serializes before structured queue admission, PTY writes and goal submission }) expect(structured.dispatchCommand).toHaveBeenCalledWith('/compact') updateNativeChatComposerDraft('send', snapshot, 'immediate') + const optimistic = vi.fn() const ptyHook = renderHook(() => useNativeChatPtyComposerSend({ agent: 'codex', @@ -208,6 +249,7 @@ it('serializes before structured queue admission, PTY writes and goal submission sessionOptionsSurface: null, terminalTabId: 'tab-left', trackPendingSend: vi.fn(), + onOptimisticSend: optimistic, setDraft: vi.fn(), setCaret: vi.fn(), clearSkillOrigin: vi.fn(), @@ -220,6 +262,14 @@ it('serializes before structured queue admission, PTY writes and goal submission 'pty-left', wire ]) + expect(optimistic).toHaveBeenCalledExactlyOnceWith(wire, []) + if (!entry) { + throw new Error('send slot not admitted') + } + expect(await claudeDispatchMessageContent(entry.body)).toEqual([{ type: 'text', text: wire }]) + // SAFETY: a text-only body with no skills never reads the turn host; the production adapter consumes only its captured blocks. + expect(turnInputFor({} as CodexTurnHost, entry.body)).toEqual([{ type: 'text', text: wire }]) + expect((await preparePiRpcPrompt(entry.body)).message).toBe(wire) const goalTransport = transport() goalTransport.threadGoal = { setObjective: vi.fn(async () => true) } const goalHook = renderHook(() => @@ -333,3 +383,227 @@ it('hides unknown hosts, starts collapsed and separates mention, navigation and expect(view.queryByRole('complementary')).toBeNull() expect(document.activeElement).toBe(view.getByRole('button', { name: 'Show crew: 1 workers' })) }) + +it('captures projected identity once for real typed-goal dispatch and Goal mode while isolating other host commands', async () => { + const id = '11111111-1111-4111-8111-111111111111' + const token = nativeChatPastedTextToken(id) + const pane = editor('goals', '/goal Inspect ') + act(() => { + pane.input.setSelectionRange(pane.input.value.length, pane.input.value.length) + pane.input.insertAgentReferences!([first, second, first]) + pane.editor.commands.insertContent(` ${token}`) + }) + const raw = readNativeChatComposerDraft('goals') + updateNativeChatComposerDraft( + 'goals', + { pastedTextFiles: { [id]: '/tmp/Same name (1).txt' } }, + 'immediate' + ) + const snapshot = readNativeChatComposerDraft('goals') + const expected = serializeNativeChatAgentReferences( + snapshot.text, + snapshot.document, + snapshot.pastedTextFiles + ) + .replace(/^\/goal\s+/, '') + .trim() + expect(expected).toContain('@Same name (2) @Same name (3) @Same name (2)') + const setObjective = vi.fn(async () => true) + const structured = transport() + structured.threadGoal = { setObjective } + structured.dispatchCommand = (text) => + dispatchStructuredAgentSessionComposerCommand(text, { + snapshot: [], + invokeAction: async () => true, + setOption: async () => true, + setThreadGoalObjective: setObjective + }) + structured.capturePresentation = () => { + updateNativeChatComposerDraft( + 'goals', + { text: 'later @label', document: undefined, pastedTextFiles: { [id]: '/tmp/later.txt' } }, + 'immediate' + ) + return () => true + } + const hook = renderHook(() => + useNativeChatStructuredComposerSend({ + agent: 'claude', + draftScopeKey: 'goals', + imageAttachments: [], + structuredTransport: structured, + isComposing: () => false, + clearSkillOrigin: vi.fn(), + setDraft: vi.fn(), + setCaret: vi.fn() + }) + ) + await act(async () => hook.result.current(snapshot.text)) + expect(setObjective).toHaveBeenLastCalledWith(expected) + expect(structured.send).not.toHaveBeenCalled() + updateNativeChatComposerDraft('goals', snapshot, 'immediate') + const mode = renderHook(() => + useNativeChatComposerSubmit({ + structuredTransport: structured, + draftScopeKey: 'goals', + draft: snapshot.text, + caret: 0, + imageAttachments: [], + disabled: false, + sendPty: vi.fn(), + sendStructured: vi.fn(), + setDraft: vi.fn(), + setCaret: vi.fn() + }) + ) + act(() => + mode.result.current.goalMode.interceptPick(vi.fn())({ + kind: 'command', + id: 'goal', + name: 'goal', + token: '/goal', + skillCollision: false + }) + ) + await act(async () => mode.result.current.send()) + expect(setObjective).toHaveBeenCalledTimes(2) + expect(setObjective).toHaveBeenLastCalledWith(expected) + updateNativeChatComposerDraft('goals', snapshot, 'immediate') + structured.dispatchCommand = vi.fn(async () => ({ handled: true, accepted: true, error: null })) + for (const command of ['/compact', '/model sonnet']) { + await act(async () => hook.result.current(command)) + expect(structured.dispatchCommand).toHaveBeenLastCalledWith(command) + } + expect(raw.text).toContain(token) +}) + +function RecallComposer({ + messages, + onSend +}: { + messages: NativeChatMessage[] + onSend: (text: string) => void +}) { + const inputRef = useRef(null) + const [draft, setDraft] = useState('') + const [, setCaret] = useState(0) + const { recall } = useNativeChatComposerRecall({ draft, source: { messages }, inputRef }) + const structured = transport() + structured.send = (text) => { + onSend(text) + return 'queued' + } + const send = useNativeChatStructuredComposerSend({ + agent: 'claude', + draftScopeKey: 'recall', + imageAttachments: [], + structuredTransport: structured, + isComposing: () => false, + clearSkillOrigin: vi.fn(), + setDraft, + setCaret + }) + const keydown = useNativeChatComposerKeyDown({ + autocomplete: { mode: 'none' }, + mentionFiles: { files: [], loading: false, failed: false }, + completeMention: vi.fn(), + activeSuggestion: 0, + draft, + recall, + isComposing: () => false, + completePickerItem: vi.fn(), + dispatchPickerCommand: vi.fn(), + dismissPicker: vi.fn(), + interrupt: vi.fn(), + send: () => void send(draft), + setActiveSuggestion: vi.fn(), + setDraft, + setCaret + }) + return ( + setDraft(input.value)} + onSelect={vi.fn()} + onKeyDown={keydown} + /> + ) +} + +it('replaces optimistic exact and glued echoes with authoritative turns before ArrowUp, plain resend and remount', async () => { + const pane = editor('echo', 'ordinary @Same name ') + act(() => { + pane.input.setSelectionRange(pane.input.value.length, pane.input.value.length) + pane.input.insertAgentReferences!([first, second, first]) + }) + const submitted = readNativeChatComposerDraft('echo') + const wire = serializeNativeChatAgentReferences(submitted.text, submitted.document).trim() + const pending = [{ id: 'optimistic', text: wire, sentAt: 1 }] + expect(pendingSendsAsMessages(pending)[0].id).toBe('pending:optimistic') + const authoritative: NativeChatMessage = { + id: 'provider-user', + role: 'user', + blocks: [{ type: 'text', text: wire }], + timestamp: 2, + source: 'transcript' + } + expect(pendingSendsAsMessages(pending, [authoritative])).toEqual([]) + const assistant: NativeChatMessage = { + id: 'provider-reply', + role: 'assistant', + blocks: [{ type: 'text', text: 'ok' }], + timestamp: 3, + source: 'transcript' + } + expect(prunePendingSends(pending, [authoritative, assistant])).toEqual([]) + const glued: NativeChatMessage = { + ...authoritative, + id: 'provider-glued', + blocks: [{ type: 'text', text: `${wire}follow-up` }] + } + const both = [...pending, { id: 'second', text: 'follow-up', sentAt: 1 }] + expect(pendingSendsAsMessages(both, [glued])).toEqual([]) + expect(prunePendingSends(both, [glued, assistant])).toEqual([]) + pane.unmount() + const sent = vi.fn() + for (let mount = 0; mount < 2; mount++) { + const recalled = render() + const textbox = within(recalled.container).getByRole('textbox') + fireEvent.keyDown(textbox, { key: 'ArrowUp' }) + expect(promptText(promptEditor(textbox).state.doc)).toBe(wire) + expect(recalled.container.querySelector('[data-native-chat-agent-reference]')).toBeNull() + await act(async () => fireEvent.keyDown(textbox, { key: 'Enter' })) + expect(sent).toHaveBeenLastCalledWith(wire) + recalled.unmount() + clearNativeChatComposerDraftsForTests() + } +}) + +it('applies structured UTF-8 admission to the expanded final body before any send slot is taken', async () => { + const pane = editor('size', '') + act(() => pane.input.insertAgentReferences!([{ ...first, label: 'é'.repeat(70000) }])) + const raw = readNativeChatComposerDraft('size') + expect(Buffer.byteLength(raw.text, 'utf8')).toBeLessThan(256 * 1024) + const structured = transport() + structured.dispatchCommand = async () => ({ handled: false, accepted: false, error: null }) + const hook = renderHook(() => + useNativeChatStructuredComposerSend({ + agent: 'claude', + draftScopeKey: 'size', + imageAttachments: [], + structuredTransport: structured, + isComposing: () => false, + clearSkillOrigin: vi.fn(), + setDraft: vi.fn(), + setCaret: vi.fn() + }) + ) + await act(async () => hook.result.current(raw.text)) + expect(structured.send).not.toHaveBeenCalled() + expect(structured.onError).toHaveBeenCalledTimes(1) + expect(readNativeChatComposerDraft('size').text).toBe(raw.text) +}) diff --git a/src/renderer/src/components/native-chat/native-chat-composer-pasted-text-references.ts b/src/renderer/src/components/native-chat/native-chat-composer-pasted-text-references.ts index a875edab09ed..6de2e5b7db89 100644 --- a/src/renderer/src/components/native-chat/native-chat-composer-pasted-text-references.ts +++ b/src/renderer/src/components/native-chat/native-chat-composer-pasted-text-references.ts @@ -26,10 +26,26 @@ export function nativeChatPastedTextState(scope: string, token: string): string /** Only completed paths need boundaries; copied source bytes remain literal. */ export function resolveNativeChatPastedText(scope: string, text: string, copy = false): string { + return projectPastedText(text, (token) => nativeChatPastedTextState(scope, token), copy) +} + +/** Capture completed file facts with the submitted document, before any send body is built. */ +export function projectNativeChatPastedText( + text: string, + files: Readonly> = {} +): string { + return projectPastedText(text, (token) => files[nativeChatPastedTextId(token) ?? ''] ?? null) +} + +function projectPastedText( + text: string, + stateOf: (token: string) => string | null, + copy = false +): string { let resolved = '' let pathBefore = false text.split(NATIVE_CHAT_PASTED_TEXT_TOKEN).forEach((part, index) => { - const state = index % 2 === 1 ? nativeChatPastedTextState(scope, part) : null + const state = index % 2 === 1 ? stateOf(part) : null const path = state !== null && state !== 'saving' && state !== 'unsaved' const piece = path ? formatNativeChatFileReference(state) diff --git a/src/renderer/src/components/native-chat/use-native-chat-composer-submit.ts b/src/renderer/src/components/native-chat/use-native-chat-composer-submit.ts index a2bc134eed8e..77229fd9746c 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-composer-submit.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-composer-submit.ts @@ -15,10 +15,7 @@ import { structuredAgentSessionGoalObjective } from '../../../../shared/structured-agent-session-composer' -import { - admitNativeChatPastedText, - resolveNativeChatPastedText -} from './native-chat-composer-pasted-text-references' +import { admitNativeChatPastedText } from './native-chat-composer-pasted-text-references' const GOAL_COMMAND = 'goal' @@ -72,14 +69,9 @@ export function useNativeChatComposerSubmit(args: { // Clear only the submitted draft after host acceptance; the goal controller refuses concurrent submissions. const setGoal = useCallback(() => { + const submitted = readNativeChatComposerDraft(draftScopeKey) const objective = structuredAgentSessionGoalObjective( - resolveNativeChatPastedText( - draftScopeKey, - serializeNativeChatAgentReferences( - draft, - readNativeChatComposerDraft(draftScopeKey).document - ) - ) + serializeNativeChatAgentReferences(draft, submitted.document, submitted.pastedTextFiles) ) if (!threadGoal || !structuredTransport || objective === '') { return @@ -95,7 +87,6 @@ export function useNativeChatComposerSubmit(args: { } structuredTransport.onSubmitted?.() const isCurrent = structuredTransport.capturePresentation() - const submitted = readNativeChatComposerDraft(draftScopeKey) void threadGoal.setObjective(objective).then((accepted) => { if (!accepted) { return diff --git a/src/renderer/src/components/native-chat/use-native-chat-pty-composer-send.ts b/src/renderer/src/components/native-chat/use-native-chat-pty-composer-send.ts index b53e43918ec7..d302e79d547d 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-pty-composer-send.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-pty-composer-send.ts @@ -1,9 +1,6 @@ import { readNativeChatComposerDraft } from './native-chat-composer-draft-store' import { serializeNativeChatAgentReferences } from './native-chat-agent-reference-send' -import { - admitNativeChatPastedText, - resolveNativeChatPastedText -} from './native-chat-composer-pasted-text-references' +import { admitNativeChatPastedText } from './native-chat-composer-pasted-text-references' import { useCallback, type Dispatch, type SetStateAction } from 'react' import type { AgentType } from '../../../../shared/agent-status-types' import type { NativeChatLaunchDraft } from '@/lib/native-chat-launch-prompt' @@ -76,13 +73,8 @@ export function useNativeChatPtyComposerSend(args: { if (!admitNativeChatPastedText(args.draftScopeKey, text, args.setNotice)) { return } - text = resolveNativeChatPastedText( - args.draftScopeKey, - serializeNativeChatAgentReferences( - text, - readNativeChatComposerDraft(args.draftScopeKey).document - ) - ) + const submitted = readNativeChatComposerDraft(args.draftScopeKey) + text = serializeNativeChatAgentReferences(text, submitted.document, submitted.pastedTextFiles) const { sendOptions: launchSendOptions } = resolveNativeChatLaunchDraftSend({ launchDraft: args.launchDraft, launchDraftResolved: args.launchDraftResolved, diff --git a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts index a07219cb4c0c..ba276bcce226 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-structured-composer-send.ts @@ -27,7 +27,7 @@ import { import { nativeChatComposerDraftLeftAfterSend } from './native-chat-composer-draft-comparison' import { admitNativeChatPastedText, - resolveNativeChatPastedText + projectNativeChatPastedText } from './native-chat-composer-pasted-text-references' export type UseNativeChatStructuredComposerSendArgs = { @@ -80,7 +80,7 @@ export function useNativeChatStructuredComposerSend({ } const submitted = readNativeChatComposerDraft(draftScopeKey) const submittedText = text - text = resolveNativeChatPastedText(draftScopeKey, text) + text = projectNativeChatPastedText(text, submitted.pastedTextFiles) const hostCommand = isNativeChatStructuredHostCommand(text, agent, structuredTransport) // Blocked hosts cannot take turns/conversation commands; option commands only configure later turns. if ( @@ -109,10 +109,14 @@ export function useNativeChatStructuredComposerSend({ structuredTransport.onSubmitted?.() } const isCurrent = structuredTransport.capturePresentation() - if (!hostCommand) { - text = resolveNativeChatPastedText( - draftScopeKey, - serializeNativeChatAgentReferences(submittedText, submitted.document) + if ( + !hostCommand || + (structuredTransport.threadGoal && isStructuredAgentSessionGoalCommand(text)) + ) { + text = serializeNativeChatAgentReferences( + submittedText, + submitted.document, + submitted.pastedTextFiles ) } await dispatchNativeChatStructuredComposerText( diff --git a/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.test.tsx b/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.test.tsx new file mode 100644 index 000000000000..4106eeacc703 --- /dev/null +++ b/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.test.tsx @@ -0,0 +1,159 @@ +// @vitest-environment happy-dom +import { act, cleanup, fireEvent, render, within } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import { toast } from 'sonner' +import type { ManagedPane } from '@/lib/pane-manager/pane-manager' +import type { TerminalPaneController } from '../terminal-pane/use-terminal-pane-controller' +import type { PtyTransport } from '../terminal-pane/pty-transport-types' +import { parsePaneKey } from '../../../../shared/stable-pane-id' +import { emptyCrew } from '../../../../shared/orchestration-crew' +import { TooltipProvider } from '../ui/tooltip' +import { TerminalCrewPortals } from './TerminalCrewPortals' + +vi.mock('@/store', () => ({ + useAppStore: (selector: (state: unknown) => unknown) => selector({ terminalLayoutsByTabId: {} }) +})) +vi.mock('./use-terminal-crew-identity', () => ({ + useTerminalCrewIdentity: () => ({ target: { kind: 'local' }, party: 'term_self' }) +})) +vi.mock('../native-chat/use-orchestration-crew', () => ({ + useOrchestrationCrew: () => { + const snapshot = emptyCrew('ok') + snapshot.sections.managing.push({ + partyKey: 'worker', + role: 'worker', + label: 'Worker', + agentKind: 'codex', + status: 'working', + task: { title: 'Inspect', state: 'dispatched' }, + sendAddress: 'term_worker' + }) + return snapshot + } +})) +vi.mock('@/lib/open-agent-message-sender', () => ({ openOrchestrationCrewAgent: vi.fn() })) +vi.mock('sonner', () => ({ toast: { error: vi.fn() } })) +afterEach(() => { + cleanup() + document.body.replaceChildren() + vi.clearAllMocks() +}) + +function fixture(acceptance: boolean | Promise | undefined) { + let ptyId = 'pty-captured' + const container = document.createElement('div') + const input = document.createElement('textarea') + input.value = 'existing suffix' + input.setSelectionRange(8, 8) + container.append(input) + document.body.append(container) + // SAFETY: the mounted portal consumes only this pane's identity and its portal container. + const pane = { id: 7, leafId: '11111111-1111-4111-8111-111111111111', container } as ManagedPane + const sendInput = vi.fn(() => true) + const accepted = vi.fn(async () => acceptance ?? true) + // SAFETY: the portal/drop validator/paste writer consume only the listed transport surface. + const transport = { + getPtyId: () => ptyId, + isConnected: () => true, + sendInput, + ...(acceptance === undefined ? {} : { sendInputAccepted: accepted }) + } as unknown as PtyTransport + const transports = new Map([[pane.id, transport]]) + const manager = { + getPanes: () => [pane], + setActivePane: vi.fn((id: number) => { + if (id === pane.id) { + input.focus() + } + }) + } + // SAFETY: TerminalCrewPortals reads only the controller's pane/transport identity and view-mode fields below. + const controller = { + tabId: 'tab', + worktreeId: 'workspace', + managerRef: { current: manager }, + paneTransportsRef: { current: transports }, + managedPanes: [pane], + effectiveChatViewMode: false, + chatPane: null + } as unknown as TerminalPaneController + render( + + + + ) + fireEvent.click(within(container).getByRole('button', { name: 'Show crew: 1 workers' })) + const mention = () => + fireEvent.click(within(container).getByRole('button', { name: 'Mention all' })) + return { + pane, + input, + mention, + manager, + transports, + transport, + accepted, + sendInput, + replacePty: () => { + ptyId = 'pty-replaced' + } + } +} + +it('restores the captured pane focus after acceptance, preserves caret/no Enter, and uses the legacy input fallback', async () => { + for (const acceptance of [true, undefined]) { + const test = fixture(acceptance) + expect(document.activeElement).not.toBe(test.input) + await act(async () => test.mention()) + expect(test.manager.setActivePane).toHaveBeenCalledExactlyOnceWith(7) + expect(document.activeElement).toBe(test.input) + expect(test.input.selectionStart).toBe(8) + expect(test.input.value).toBe('existing suffix') + const writer = acceptance === undefined ? test.sendInput : test.accepted + expect(writer).toHaveBeenCalledExactlyOnceWith('Worker (Orca agent term_worker) ', 'driving') + expect(toast.error).not.toHaveBeenCalled() + cleanup() + document.body.replaceChildren() + vi.clearAllMocks() + } +}) + +it('shows one refusal toast and never focuses replaced captured pane, PTY or transport after an asynchronous write', async () => { + for (const rejects of [false, true]) { + const refused = fixture(false) + if (rejects) { + refused.accepted.mockRejectedValueOnce(new Error('transport rejected')) + } + await act(async () => refused.mention()) + expect(toast.error).toHaveBeenCalledTimes(1) + expect(refused.manager.setActivePane).not.toHaveBeenCalled() + cleanup() + document.body.replaceChildren() + vi.clearAllMocks() + } + for (const kind of ['pane', 'pty', 'transport'] as const) { + let finish!: (accepted: boolean) => void + const test = fixture( + new Promise((resolve) => { + finish = resolve + }) + ) + act(() => test.mention()) + if (kind === 'pane') { + test.pane.leafId = parsePaneKey('tab:22222222-2222-4222-8222-222222222222')!.leafId + } + if (kind === 'pty') { + test.replacePty() + } + if (kind === 'transport') { + test.transports.set(test.pane.id, { ...test.transport }) + } + await act(async () => finish(true)) + expect(test.manager.setActivePane).not.toHaveBeenCalled() + expect(toast.error).not.toHaveBeenCalled() + expect(test.accepted).toHaveBeenCalledTimes(1) + cleanup() + document.body.replaceChildren() + vi.clearAllMocks() + } +}) diff --git a/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.tsx b/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.tsx index 4bfa83c8a838..824d04d4bec8 100644 --- a/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.tsx +++ b/src/renderer/src/components/orchestration-crew/TerminalCrewPortals.tsx @@ -4,7 +4,10 @@ import { useAppStore } from '@/store' import type { ManagedPane } from '@/lib/pane-manager/pane-manager' import type { TerminalPaneController } from '../terminal-pane/use-terminal-pane-controller' import { makePaneKey } from '../../../../shared/stable-pane-id' -import { captureTerminalDropTarget } from '../terminal-pane/terminal-drop-target' +import { + captureTerminalDropTarget, + getCurrentTerminalDropTransport +} from '../terminal-pane/terminal-drop-target' import { insertTerminalCrewMention } from '../terminal-pane/terminal-crew-mention' import { useTerminalCrewIdentity } from './use-terminal-crew-identity' import { OrchestrationCrewPanel } from './OrchestrationCrewPanel' @@ -43,6 +46,8 @@ function TerminalCrewPortal({ row.sendAddress ? [{ label: row.label, address: row.sendAddress, hostKey }] : [] ) if (manager) { + const rejected = () => + toast.error('The terminal did not accept the agent reference. Try again.') void insertTerminalCrewMention( manager, paneTransportsRef.current, @@ -50,9 +55,14 @@ function TerminalCrewPortal({ references ).then((accepted) => { if (!accepted) { - toast.error('The terminal did not accept the agent reference. Try again.') + rejected() + } else if ( + managerRef.current === manager && + getCurrentTerminalDropTransport(manager, paneTransportsRef.current, captured) + ) { + manager.setActivePane(captured.paneId) } - }) + }, rejected) } }} />, diff --git a/src/shared/structured-agent-session-composer.ts b/src/shared/structured-agent-session-composer.ts index 75f167723538..69e9960e2ecc 100644 --- a/src/shared/structured-agent-session-composer.ts +++ b/src/shared/structured-agent-session-composer.ts @@ -70,6 +70,10 @@ function commandParts(text: string): { name: string; argument: string } | null { if (!text.startsWith('/')) { return null } + const goal = /^\/goal(?:\s+([\s\S]*))?$/i.exec(text.trimEnd()) + if (goal) { + return { name: 'goal', argument: goal[1]?.trim() ?? '' } + } const match = /^\/([^\s]+)(?:\s+(.*))?$/.exec(text.trimEnd()) return match ? { name: match[1]!.toLowerCase(), argument: match[2]?.trim() ?? '' } : null } From a55e7857e4d0295081516b8c95a445011651c35d Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 06:43:56 -0700 Subject: [PATCH 016/164] Load native lineage fixtures before test execution --- ...index-omitted-host-scope-selectors.test.ts | 32 ++++++++++++------- ...mirrored-terminal-lineage.test-fixture.tsx | 12 ++++--- ...worktree-agent-rows-subscriptions.test.tsx | 20 +++++------- 3 files changed, 35 insertions(+), 29 deletions(-) diff --git a/src/cli/index-omitted-host-scope-selectors.test.ts b/src/cli/index-omitted-host-scope-selectors.test.ts index 3844585eef7f..d1dacb5c6391 100644 --- a/src/cli/index-omitted-host-scope-selectors.test.ts +++ b/src/cli/index-omitted-host-scope-selectors.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest' +import { beforeAll, describe, expect, it, vi } from 'vitest' import type * as ChildProcess from 'node:child_process' const { @@ -51,6 +51,23 @@ import { COMMAND_SPECS } from './specs' import { okFixture, queueFixtures } from './test-fixtures' import { pairRuntimeEnvironment, useWorktreeAwarenessEnvironment } from './index-test-harness' +let lineage: RuntimeAgentLineageTestModule +let catalog: RuntimeAgentLineageCatalogTestModule + +// The CLI's Node16 program needs a hook; each test still creates its own DB and runtime. +beforeAll(async () => { + lineage = ( + await vi.importActual<{ default: RuntimeAgentLineageTestModule }>( + '../main/runtime/runtime-agent-lineage.test-fixture' + ) + ).default + catalog = ( + await vi.importActual<{ default: RuntimeAgentLineageCatalogTestModule }>( + '../main/runtime/runtime-agent-lineage-catalog.test-fixture' + ) + ).default +}) + const TERMINAL_ROW = { handle: 'term_1', ptyId: 'pty-1', @@ -80,19 +97,10 @@ describe('omittedHostIds selector annotation', () => { it.each(['repo::/workspace', 'folder:lineage'])( 'prints canonical production-built lineage through actual CLI and worktree RPC for %s', async (worktreeId) => { - const { - default: { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } - } = await vi.importActual<{ default: RuntimeAgentLineageTestModule }>( - '../main/runtime/runtime-agent-lineage.test-fixture' - ) - const { - default: { createLineageCatalogDispatcher } - } = await vi.importActual<{ default: RuntimeAgentLineageCatalogTestModule }>( - '../main/runtime/runtime-agent-lineage-catalog.test-fixture' - ) + const { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } = lineage const f = publicLineageFixture(worktreeId) try { - const dispatcher = createLineageCatalogDispatcher(f.build) + const dispatcher = catalog.createLineageCatalogDispatcher(f.build) const resultOf = (response: unknown) => JSON.parse(JSON.stringify(response)).result const request = (params = {}) => dispatcher.dispatch({ diff --git a/src/renderer/src/components/sidebar/mirrored-terminal-lineage.test-fixture.tsx b/src/renderer/src/components/sidebar/mirrored-terminal-lineage.test-fixture.tsx index 355eb91b192e..cc10b98f5b28 100644 --- a/src/renderer/src/components/sidebar/mirrored-terminal-lineage.test-fixture.tsx +++ b/src/renderer/src/components/sidebar/mirrored-terminal-lineage.test-fixture.tsx @@ -9,6 +9,13 @@ import { makePaneKey } from '../../../../shared/stable-pane-id' import type { AgentStatusEntry } from '../../../../shared/agent-status-types' import { makeTab } from '@/store/slices/store-test-helpers' +// Load the native graph during collection; fixture state stays per test. +const { + default: { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } +} = await vi.importActual<{ default: RuntimeAgentLineageTestModule }>( + '../../../../main/runtime/runtime-agent-lineage.test-fixture' +) + const LEAF = '11111111-1111-4111-8111-111111111111' export async function verifyMirroredTerminalLineage( @@ -25,11 +32,6 @@ export async function verifyMirroredTerminalLineage( getRows: () => DashboardAgentRow[] } ): Promise { - const { - default: { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } - } = await vi.importActual<{ default: RuntimeAgentLineageTestModule }>( - '../../../../main/runtime/runtime-agent-lineage.test-fixture' - ) const { makeUnifiedTab, makeWorktree, TEST_REPO } = await import('@/store/slices/store-test-helpers') const { selectDashboardOrchestration } = diff --git a/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx b/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx index 5314c582d5dc..995524e67507 100644 --- a/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx +++ b/src/renderer/src/components/sidebar/use-worktree-agent-rows-subscriptions.test.tsx @@ -13,11 +13,19 @@ import { type AgentStatusEntry } from '../../../../shared/agent-status-types' import { useWorktreeAgentRows } from './useWorktreeAgentRows' +import { verifyMirroredTerminalLineage } from './mirrored-terminal-lineage.test-fixture' import type { RuntimeAgentLineageTestModule } from '../../../../shared/runtime-agent-lineage-consumer.test-fixture' import { isStructuredTab } from '../../../../shared/structured-agent-session-tab' Reflect.set(globalThis, 'IS_REACT_ACT_ENVIRONMENT', true) +// Load the native graph during collection; fixture state stays per test. +const { + default: { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } +} = await vi.importActual<{ default: RuntimeAgentLineageTestModule }>( + '../../../../main/runtime/runtime-agent-lineage.test-fixture' +) + const LEAF = '11111111-1111-4111-8111-111111111111' const KEY_A = makePaneKey('tab-a', LEAF) const KEY_B = makePaneKey('tab-b', LEAF) @@ -409,11 +417,6 @@ it.each([20, 200])( ) it('joins production mirrored custom/collision rows locally and keeps canonical initial, graph, retained and consumer contexts', async () => { - const { - default: { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } - } = await vi.importActual<{ default: RuntimeAgentLineageTestModule }>( - '../../../../main/runtime/runtime-agent-lineage.test-fixture' - ) const { makeUnifiedTab, makeWorktree, TEST_REPO } = await import('@/store/slices/store-test-helpers') const { buildMirroredAgentTabs } = @@ -632,8 +635,6 @@ it('joins production mirrored custom/collision rows locally and keeps canonical it.each(['default', 'reserved', 'collision'] as const)( 'joins mirrored live/retained terminal contexts with positive provenance and a %s parent', async (kind) => { - const { verifyMirroredTerminalLineage } = - await import('./mirrored-terminal-lineage.test-fixture') await verifyMirroredTerminalLineage(kind, { patch, entry, @@ -644,11 +645,6 @@ it.each(['default', 'reserved', 'collision'] as const)( ) it('settles the production graph subscription/scheduler/publication/receiver loop with at most one feedback flight', async () => { - const { - default: { publicLineageFixture, canonicalChatRow, LINEAGE_PARENT, LINEAGE_CHILD } - } = await vi.importActual<{ default: RuntimeAgentLineageTestModule }>( - '../../../../main/runtime/runtime-agent-lineage.test-fixture' - ) const { useRuntimeGraphSync } = await import('@/app-shell/use-runtime-graph-sync') const { setRuntimeGraphSyncEnabled, setRuntimeGraphStoreStateGetter } = await import('@/runtime/sync-runtime-graph') From cedb1e181b58033a2cbbcadd03c42773410f0309 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 07:34:38 -0700 Subject: [PATCH 017/164] test: complete lineage inputs in runtime and sidebar fixtures --- .../orca-runtime-test-orchestration-messages.spec.ts | 4 ++++ .../runtime/orca-runtime-test-scenario-builders.spec.ts | 1 + .../lineage-and-scan-cache-part-04.spec.ts | 6 ++++++ .../lineage-and-scan-cache-part-05.spec.ts | 5 +++++ .../lineage-and-scan-cache-part-06.spec.ts | 4 ++++ .../runtime/orca-runtime-tests/mobile-summaries.spec.ts | 1 + .../terminal-creation-and-readiness-part-02.spec.ts | 1 + .../terminal-output-and-worker-recovery-part-02.spec.ts | 1 + .../terminal-output-and-worker-recovery-part-03.spec.ts | 2 ++ .../terminal-output-and-worker-recovery-part-04.spec.ts | 2 ++ .../terminal-output-and-worker-recovery-part-05.spec.ts | 3 +++ .../terminal-output-and-worker-recovery-part-06.spec.ts | 2 ++ .../sidebar/WorktreeCard.affiliate-list-mode.test.tsx | 1 + 13 files changed, 33 insertions(+) diff --git a/src/main/runtime/orca-runtime-test-orchestration-messages.spec.ts b/src/main/runtime/orca-runtime-test-orchestration-messages.spec.ts index 1184f667d8ee..7a2f1407b3bb 100644 --- a/src/main/runtime/orca-runtime-test-orchestration-messages.spec.ts +++ b/src/main/runtime/orca-runtime-test-orchestration-messages.spec.ts @@ -227,6 +227,10 @@ export class InMemoryOrchestrationMessages { return [...this.runs.values()].find((run) => run.coordinator_pane_key === paneKey) } + listSessionDispatchesForPresentation(): never[] { + return [] + } + listWorkerTerminalReleaseBacklog(): never[] { return [] } diff --git a/src/main/runtime/orca-runtime-test-scenario-builders.spec.ts b/src/main/runtime/orca-runtime-test-scenario-builders.spec.ts index a177004bcc7f..6ad2123f22d8 100644 --- a/src/main/runtime/orca-runtime-test-scenario-builders.spec.ts +++ b/src/main/runtime/orca-runtime-test-scenario-builders.spec.ts @@ -215,6 +215,7 @@ function makePostRevealWorkerRecoveryHarness( ) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This recovery fixture reaches only the listed planner, terminal settlement and authority lookup methods. runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], reconcileMissingWorkerTerminal: vi.fn(), getActiveDispatchForTerminal: () => undefined, listLegacyWorkerTerminalRecoveryRows: () => [ diff --git a/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-04.spec.ts b/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-04.spec.ts index 6e8d9bb57da5..e301b60c8fda 100644 --- a/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-04.spec.ts +++ b/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-04.spec.ts @@ -209,6 +209,7 @@ describe('OrcaRuntimeService', () => { const workerHandle = runtime.preAllocateHandleForPty('pty-worker') const coordinatorHandle = runtime.preAllocateHandleForPty('pty-coordinator') runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], getActiveDispatchForTerminal: vi.fn(() => ({ task_id: 'task-1' })), @@ -311,6 +312,7 @@ describe('OrcaRuntimeService', () => { const workerHandle = runtime.preAllocateHandleForPty('pty-worker') const coordinatorHandle = runtime.preAllocateHandleForPty('pty-coordinator') runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], getActiveDispatchForTerminal: vi.fn((handle: string) => handle === workerHandle ? { @@ -345,6 +347,9 @@ describe('OrcaRuntimeService', () => { getRun: vi.fn(() => ({ id: 'run-1', coordinator_handle: coordinatorHandle, + coordinator_orca_session_id: null, + coordinator_orca_session_id_generation: null, + consumer_generation: 0, legacy: 0 })) } as never) @@ -415,6 +420,7 @@ describe('OrcaRuntimeService', () => { coordinator_handle: coordinatorHandle })) runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], getActiveDispatchForTerminal: vi.fn((handle: string) => handle === workerHandle ? { diff --git a/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-05.spec.ts b/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-05.spec.ts index a7114a2ab2fb..5a01ba597085 100644 --- a/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-05.spec.ts +++ b/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-05.spec.ts @@ -461,6 +461,7 @@ describe('OrcaRuntimeService', () => { const workerHandle = runtime.preAllocateHandleForPty('pty-worker') const coordinatorHandle = runtime.preAllocateHandleForPty('pty-coordinator') runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], getActiveDispatchForTerminal: vi.fn(() => undefined), getLatestDispatchForTerminal: vi.fn((handle: string) => handle === workerHandle @@ -482,6 +483,9 @@ describe('OrcaRuntimeService', () => { getRun: vi.fn(() => ({ id: 'run-1', coordinator_handle: coordinatorHandle, + coordinator_orca_session_id: null, + coordinator_orca_session_id_generation: null, + consumer_generation: 0, legacy: 0 })) } as never) @@ -539,6 +543,7 @@ describe('OrcaRuntimeService', () => { const workerPaneKey = makePaneKey('tab-worker', workerLeafId) const workerHandle = runtime.preAllocateHandleForPty('pty-worker') runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], getActiveDispatchForTerminal: vi.fn(() => undefined), getLatestDispatchForTerminal: vi.fn((handle: string) => handle === workerHandle diff --git a/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-06.spec.ts b/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-06.spec.ts index 1470ff8cf21f..705f26fd0ebb 100644 --- a/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-06.spec.ts +++ b/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-06.spec.ts @@ -33,6 +33,7 @@ describe('OrcaRuntimeService', () => { coordinator_handle: 'term_unrelated' })) runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], getActiveDispatchForTerminal: vi.fn(() => undefined), getLatestDispatchForTerminal: vi.fn(() => ({ id: 'ctx-settled', @@ -81,6 +82,7 @@ describe('OrcaRuntimeService', () => { const workerLeafId = '77777777-7777-4777-8777-777777777777' const workerHandle = runtime.preAllocateHandleForPty('pty-worker') runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], getActiveDispatchForTerminal: vi.fn(() => undefined), getLatestDispatchForTerminal: vi.fn((handle: string) => handle === workerHandle @@ -258,6 +260,7 @@ describe('OrcaRuntimeService', () => { const runtime = new OrcaRuntimeService(runtimeStore as never) const workerHandle = runtime.preAllocateHandleForPty('pty-worker') runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], getDispatchContext: vi.fn(() => ({ task_id: 'task_abc123', assignee_handle: workerHandle, @@ -356,6 +359,7 @@ describe('OrcaRuntimeService', () => { const runtime = new OrcaRuntimeService(runtimeStore as never) const parentHandle = runtime.preAllocateHandleForPty('pty-parent') runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], getDispatchContext: vi.fn(() => undefined), getTask: vi.fn(() => ({ id: 'task_creator123', diff --git a/src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts index 2783a95a9807..b3a89528ce91 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts @@ -457,6 +457,7 @@ describe('OrcaRuntimeService', () => { }) const workerHandle = runtime.preAllocateHandleForPty('pty-1') runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], getActiveDispatchForTerminal: vi.fn((handle: string) => handle === workerHandle ? { diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-02.spec.ts index a371aa8b48bd..09771aceee57 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-02.spec.ts @@ -113,6 +113,7 @@ describe('OrcaRuntimeService', () => { } ) runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], getActiveDispatchForTerminal: (handle: string) => handle === 'term_ssh_retained' ? { id: 'dispatch-ssh', task_id: 'task-ssh', status: 'dispatched' } diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts index 79ffa8813ad1..476db2ac7690 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts @@ -470,6 +470,7 @@ describe('OrcaRuntimeService', () => { } ) runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], getActiveDispatchForTerminal: () => undefined, listLegacyWorkerTerminalRecoveryRows: () => [ { diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts index e2250a93fc0a..050e19921102 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts @@ -47,6 +47,7 @@ describe('OrcaRuntimeService', () => { { canRecoverPersistentLocalPtys: () => true } ) runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], getActiveDispatchForTerminal: () => undefined, listLegacyWorkerTerminalRecoveryRows: () => [ { @@ -462,6 +463,7 @@ describe('OrcaRuntimeService', () => { { canRecoverPersistentLocalPtys: () => true } ) runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], listLegacyWorkerTerminalRecoveryRows: () => [ { dispatch_id: 'dispatch-persistence-failure', diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts index ca20cbb0ac2e..20effb11ce2b 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts @@ -279,6 +279,7 @@ describe('OrcaRuntimeService', () => { ) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This isolated recovery path reaches only the supplied planner and missing-terminal settlement methods. runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], reconcileMissingWorkerTerminal: vi.fn(), listLegacyWorkerTerminalRecoveryRows: () => [ { @@ -391,6 +392,7 @@ describe('OrcaRuntimeService', () => { { canRecoverPersistentLocalPtys: () => true } ) runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], listLegacyWorkerTerminalRecoveryRows: () => [ { dispatch_id: 'dispatch-inventory-unavailable', diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-05.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-05.spec.ts index b13db8acaa33..cb1e31caccda 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-05.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-05.spec.ts @@ -79,6 +79,7 @@ describe('OrcaRuntimeService', () => { ) // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This isolated recovery path reaches only the supplied planner and missing-terminal settlement methods. runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], reconcileMissingWorkerTerminal: vi.fn(), listLegacyWorkerTerminalRecoveryRows: () => cases.map(({ name, leafId, terminalHandle }) => ({ @@ -202,6 +203,7 @@ describe('OrcaRuntimeService', () => { { canRecoverPersistentLocalPtys: () => true } ) runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], listLegacyWorkerTerminalRecoveryRows: () => [ { dispatch_id: 'dispatch-folder', @@ -330,6 +332,7 @@ describe('OrcaRuntimeService', () => { { canRecoverPersistentLocalPtys: () => true } ) runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], listLegacyWorkerTerminalRecoveryRows: () => [ { dispatch_id: 'dispatch-ssh-folder', diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-06.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-06.spec.ts index 433fd1496f6f..072e39ca7e8e 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-06.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-06.spec.ts @@ -96,6 +96,7 @@ describe('OrcaRuntimeService', () => { { canRecoverPersistentLocalPtys: () => true } ) runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], listLegacyWorkerTerminalRecoveryRows: () => [ { dispatch_id: 'dispatch-ssh', @@ -229,6 +230,7 @@ describe('OrcaRuntimeService', () => { { canRecoverPersistentLocalPtys: () => true } ) runtime.setOrchestrationDb({ + listSessionDispatchesForPresentation: () => [], listLegacyWorkerTerminalRecoveryRows: () => [ { dispatch_id: 'dispatch-wsl', diff --git a/src/renderer/src/components/sidebar/WorktreeCard.affiliate-list-mode.test.tsx b/src/renderer/src/components/sidebar/WorktreeCard.affiliate-list-mode.test.tsx index 2fbdf69f29cb..48c74a2684e3 100644 --- a/src/renderer/src/components/sidebar/WorktreeCard.affiliate-list-mode.test.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCard.affiliate-list-mode.test.tsx @@ -46,6 +46,7 @@ vi.mock('@/store', () => { sshConnectionStates: new Map(), sshTargetLabels: new Map(), tabsByWorktree: {}, + unifiedTabsByWorktree: {}, updateWorktreeMeta, workspacePortScan: null, worktreeCardProperties From de1f4d1d0df133d654674f5164d853c73f5a4be1 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 07:43:04 -0700 Subject: [PATCH 018/164] test: seed benchmark facts from active dispatches --- .../runtime-agent-orchestration-benchmark.test-fixture.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/runtime/runtime-agent-orchestration-benchmark.test-fixture.ts b/src/main/runtime/runtime-agent-orchestration-benchmark.test-fixture.ts index 91628db3c425..6ae41034e3db 100644 --- a/src/main/runtime/runtime-agent-orchestration-benchmark.test-fixture.ts +++ b/src/main/runtime/runtime-agent-orchestration-benchmark.test-fixture.ts @@ -62,7 +62,7 @@ export function benchmarkPresentationCorpus( } if (nullAddress) { db.db.exec( - "UPDATE dispatch_contexts SET assignee_handle = NULL, assignee_pane_key = NULL WHERE status = 'pending'" + "UPDATE dispatch_contexts SET assignee_handle = NULL, assignee_pane_key = NULL WHERE status IN ('pending', 'dispatched')" ) } const task = db.createTask({ runId: run.id, spec: 'history' }) @@ -77,8 +77,11 @@ export function benchmarkPresentationCorpus( insert.run(terminalHistory, 'terminal-history-', run.id, task.id, 0, 0, 0) } const active = db.db - .prepare("SELECT id, task_id FROM dispatch_contexts WHERE status = 'pending' ORDER BY rowid") + .prepare( + "SELECT id, task_id FROM dispatch_contexts WHERE status IN ('pending', 'dispatched') ORDER BY rowid" + ) .all() + expect(active.map((row) => row.id)).toEqual([...expected.values()]) const insertFact = db.db.prepare( `INSERT INTO attempt_observation_facts(id, dispatch_id, task_id, sequence, authority_id, authority_clock, facet, payload, home_received_at) VALUES (?, ?, ?, ?, 'home', 'home', 'process_turn', '{"process":"running","turn":"working"}', ?)` ) From 30a8f2301eeea6eb38e7498c1ded22f786d799bf Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 08:25:23 -0700 Subject: [PATCH 019/164] test: replace partial orchestration DB casts with typed fixtures --- .../lineage-and-scan-cache-part-04.spec.ts | 98 ++++++++++------ .../lineage-and-scan-cache-part-05.spec.ts | 65 ++++++---- .../lineage-and-scan-cache-part-06.spec.ts | 75 +++++++----- .../mobile-summaries.spec.ts | 42 ++++--- ...nal-creation-and-readiness-part-02.spec.ts | 23 ++-- ...output-and-worker-recovery-part-02.spec.ts | 38 +++--- ...output-and-worker-recovery-part-03.spec.ts | 72 ++++++------ ...output-and-worker-recovery-part-04.spec.ts | 35 +++--- ...output-and-worker-recovery-part-05.spec.ts | 69 +++++------ ...output-and-worker-recovery-part-06.spec.ts | 70 +++++------ .../runtime-orchestration-db.test-fixture.ts | 111 ++++++++++++++++++ 11 files changed, 435 insertions(+), 263 deletions(-) create mode 100644 src/main/runtime/runtime-orchestration-db.test-fixture.ts diff --git a/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-04.spec.ts b/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-04.spec.ts index e301b60c8fda..1b49011b7614 100644 --- a/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-04.spec.ts +++ b/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-04.spec.ts @@ -1,3 +1,10 @@ +import { + makeRuntimeOrchestrationDb, + dispatchContextRow, + coordinatorRunRow, + taskLineageRow, + runRow +} from '../runtime-orchestration-db.test-fixture' import { describe, expect, it, vi } from 'vitest' import { MOCK_GIT_WORKTREES, @@ -208,16 +215,20 @@ describe('OrcaRuntimeService', () => { const runtime = new OrcaRuntimeService(runtimeStore as never) const workerHandle = runtime.preAllocateHandleForPty('pty-worker') const coordinatorHandle = runtime.preAllocateHandleForPty('pty-coordinator') - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - getActiveDispatchForTerminal: vi.fn(() => ({ + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'getActiveDispatchForTerminal').mockImplementation(() => + dispatchContextRow({ task_id: 'task-1' - })), - getActiveCoordinatorRun: vi.fn(() => ({ + }) + ) + vi.spyOn(orchestrationDb, 'getActiveCoordinatorRun').mockImplementation(() => + coordinatorRunRow({ id: 'run-1', coordinator_handle: coordinatorHandle - })) - } as never) + }) + ) + runtime.setOrchestrationDb(orchestrationDb) runtime.attachWindow(1) runtime.syncWindowGraph(1, { tabs: [ @@ -311,48 +322,54 @@ describe('OrcaRuntimeService', () => { const coordinatorPaneKey = makePaneKey('tab-coordinator', coordinatorLeafId) const workerHandle = runtime.preAllocateHandleForPty('pty-worker') const coordinatorHandle = runtime.preAllocateHandleForPty('pty-coordinator') - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - getActiveDispatchForTerminal: vi.fn((handle: string) => + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'getActiveDispatchForTerminal').mockImplementation( + (handle: string) => handle === workerHandle - ? { + ? dispatchContextRow({ id: 'ctx-1', run_id: 'run-1', task_id: 'task-1', assignee_handle: workerHandle, status: 'dispatched' - } + }) : undefined - ), - getLatestDispatchForTerminal: vi.fn((handle: string) => + ) + vi.spyOn(orchestrationDb, 'getLatestDispatchForTerminal').mockImplementation( + (handle: string) => handle === workerHandle - ? { + ? dispatchContextRow({ id: 'ctx-done', run_id: 'run-1', task_id: 'task-done', assignee_handle: workerHandle, status: 'completed', completed_at: new Date(Date.now()).toISOString() - } + }) : undefined - ), - getTask: vi.fn(() => ({ + ) + vi.spyOn(orchestrationDb, 'getTask').mockImplementation(() => + taskLineageRow({ id: 'task-1', run_id: 'run-1', task_title: 'Dispatch prompt work', display_name: 'Review dispatch prompts and make worker labels distinct', spec: 'Review dispatch prompts\n\nand make worker labels distinct', created_by_terminal_handle: coordinatorHandle - })), - getRun: vi.fn(() => ({ + }) + ) + vi.spyOn(orchestrationDb, 'getRun').mockImplementation(() => + runRow({ id: 'run-1', coordinator_handle: coordinatorHandle, coordinator_orca_session_id: null, coordinator_orca_session_id_generation: null, consumer_generation: 0, legacy: 0 - })) - } as never) + }) + ) + runtime.setOrchestrationDb(orchestrationDb) runtime.attachWindow(1) const result = runtime.syncWindowGraph(1, { @@ -415,33 +432,38 @@ describe('OrcaRuntimeService', () => { const workerPaneKey = makePaneKey('tab-worker', workerLeafId) const workerHandle = runtime.preAllocateHandleForPty('pty-worker') const coordinatorHandle = runtime.preAllocateHandleForPty('pty-coordinator') - const getActiveCoordinatorRun = vi.fn(() => ({ - id: 'run-legacy-unrelated', - coordinator_handle: coordinatorHandle - })) - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - getActiveDispatchForTerminal: vi.fn((handle: string) => + const getActiveCoordinatorRun = vi.fn(() => + coordinatorRunRow({ + id: 'run-legacy-unrelated', + coordinator_handle: coordinatorHandle + }) + ) + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'getActiveDispatchForTerminal').mockImplementation( + (handle: string) => handle === workerHandle - ? { + ? dispatchContextRow({ id: 'ctx-missing-run', run_id: dispatchRunId, task_id: 'task-missing-run', assignee_handle: workerHandle, status: 'dispatched' - } + }) : undefined - ), - getLatestDispatchForTerminal: vi.fn(() => undefined), - getTask: vi.fn(() => ({ + ) + vi.spyOn(orchestrationDb, 'getLatestDispatchForTerminal').mockImplementation(() => undefined) + vi.spyOn(orchestrationDb, 'getTask').mockImplementation(() => + taskLineageRow({ id: 'task-missing-run', run_id: taskRunId, spec: 'modern task without proven Run', created_by_terminal_handle: coordinatorHandle - })), - getRun: vi.fn(() => undefined), - getActiveCoordinatorRun - } as never) + }) + ) + vi.spyOn(orchestrationDb, 'getRun').mockImplementation(() => undefined) + vi.spyOn(orchestrationDb, 'getActiveCoordinatorRun').mockImplementation(getActiveCoordinatorRun) + runtime.setOrchestrationDb(orchestrationDb) runtime.attachWindow(1) const result = runtime.syncWindowGraph(1, { diff --git a/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-05.spec.ts b/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-05.spec.ts index 5a01ba597085..805fd4157826 100644 --- a/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-05.spec.ts +++ b/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-05.spec.ts @@ -1,3 +1,10 @@ +import { + makeRuntimeOrchestrationDb, + dispatchContextRow, + taskLineageRow, + runRow, + coordinatorRunRow +} from '../runtime-orchestration-db.test-fixture' import { describe, expect, it, vi } from 'vitest' import { AGENT_STATUS_STALE_AFTER_MS, @@ -460,35 +467,40 @@ describe('OrcaRuntimeService', () => { const coordinatorPaneKey = makePaneKey('tab-coordinator', coordinatorLeafId) const workerHandle = runtime.preAllocateHandleForPty('pty-worker') const coordinatorHandle = runtime.preAllocateHandleForPty('pty-coordinator') - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - getActiveDispatchForTerminal: vi.fn(() => undefined), - getLatestDispatchForTerminal: vi.fn((handle: string) => + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'getActiveDispatchForTerminal').mockImplementation(() => undefined) + vi.spyOn(orchestrationDb, 'getLatestDispatchForTerminal').mockImplementation( + (handle: string) => handle === workerHandle - ? { + ? dispatchContextRow({ id: 'ctx-done', run_id: 'run-1', task_id: 'task-done', assignee_handle: workerHandle, status: 'completed', completed_at: new Date(Date.now()).toISOString() - } + }) : undefined - ), - getTask: vi.fn(() => ({ + ) + vi.spyOn(orchestrationDb, 'getTask').mockImplementation(() => + taskLineageRow({ id: 'task-done', run_id: 'run-1', created_by_terminal_handle: coordinatorHandle - })), - getRun: vi.fn(() => ({ + }) + ) + vi.spyOn(orchestrationDb, 'getRun').mockImplementation(() => + runRow({ id: 'run-1', coordinator_handle: coordinatorHandle, coordinator_orca_session_id: null, coordinator_orca_session_id_generation: null, consumer_generation: 0, legacy: 0 - })) - } as never) + }) + ) + runtime.setOrchestrationDb(orchestrationDb) runtime.attachWindow(1) const result = runtime.syncWindowGraph(1, { @@ -542,28 +554,33 @@ describe('OrcaRuntimeService', () => { const workerLeafId = '55555555-5555-4555-8555-555555555555' const workerPaneKey = makePaneKey('tab-worker', workerLeafId) const workerHandle = runtime.preAllocateHandleForPty('pty-worker') - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - getActiveDispatchForTerminal: vi.fn(() => undefined), - getLatestDispatchForTerminal: vi.fn((handle: string) => + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'getActiveDispatchForTerminal').mockImplementation(() => undefined) + vi.spyOn(orchestrationDb, 'getLatestDispatchForTerminal').mockImplementation( + (handle: string) => handle === workerHandle - ? { + ? dispatchContextRow({ id: 'ctx-done', task_id: 'task-done', assignee_handle: workerHandle, status: 'completed', completed_at: new Date(Date.now()).toISOString() - } + }) : undefined - ), - getTask: vi.fn(() => ({ + ) + vi.spyOn(orchestrationDb, 'getTask').mockImplementation(() => + taskLineageRow({ id: 'task-done' - })), - getActiveCoordinatorRun: vi.fn(() => ({ + }) + ) + vi.spyOn(orchestrationDb, 'getActiveCoordinatorRun').mockImplementation(() => + coordinatorRunRow({ id: 'run-unrelated', coordinator_handle: 'term_unrelated' - })) - } as never) + }) + ) + runtime.setOrchestrationDb(orchestrationDb) runtime.attachWindow(1) const result = runtime.syncWindowGraph(1, { diff --git a/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-06.spec.ts b/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-06.spec.ts index 705f26fd0ebb..dc637b9372c4 100644 --- a/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-06.spec.ts +++ b/src/main/runtime/orca-runtime-tests/lineage-and-scan-cache-part-06.spec.ts @@ -1,3 +1,9 @@ +import { + makeRuntimeOrchestrationDb, + dispatchContextRow, + taskLineageRow, + coordinatorRunRow +} from '../runtime-orchestration-db.test-fixture' import { describe, expect, it, vi } from 'vitest' import { AGENT_STATUS_STALE_AFTER_MS, @@ -28,22 +34,28 @@ describe('OrcaRuntimeService', () => { const workerLeafId = '66666666-6666-4666-8666-666666666666' const workerPaneKey = makePaneKey('tab-worker', workerLeafId) const workerHandle = runtime.preAllocateHandleForPty('pty-worker') - const getActiveCoordinatorRun = vi.fn(() => ({ - id: 'run-unrelated', - coordinator_handle: 'term_unrelated' - })) - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - getActiveDispatchForTerminal: vi.fn(() => undefined), - getLatestDispatchForTerminal: vi.fn(() => ({ + const getActiveCoordinatorRun = vi.fn(() => + coordinatorRunRow({ + id: 'run-unrelated', + coordinator_handle: 'term_unrelated' + }) + ) + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'getActiveDispatchForTerminal').mockImplementation(() => undefined) + vi.spyOn(orchestrationDb, 'getLatestDispatchForTerminal').mockImplementation(() => + dispatchContextRow({ id: 'ctx-settled', task_id: 'task-settled', assignee_handle: workerHandle, status: dispatchStatus, completed_at: new Date(Date.now()).toISOString() - })), + }) + ) + vi.spyOn(orchestrationDb, 'getActiveCoordinatorRun').mockImplementation( getActiveCoordinatorRun - } as never) + ) + runtime.setOrchestrationDb(orchestrationDb) runtime.attachWindow(1) const result = runtime.syncWindowGraph(1, { @@ -81,21 +93,22 @@ describe('OrcaRuntimeService', () => { const runtime = new OrcaRuntimeService(store) const workerLeafId = '77777777-7777-4777-8777-777777777777' const workerHandle = runtime.preAllocateHandleForPty('pty-worker') - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - getActiveDispatchForTerminal: vi.fn(() => undefined), - getLatestDispatchForTerminal: vi.fn((handle: string) => + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'getActiveDispatchForTerminal').mockImplementation(() => undefined) + vi.spyOn(orchestrationDb, 'getLatestDispatchForTerminal').mockImplementation( + (handle: string) => handle === workerHandle - ? { + ? dispatchContextRow({ id: 'ctx-stale', task_id: 'task-stale', assignee_handle: workerHandle, status: 'completed', completed_at: new Date(Date.now() - AGENT_STATUS_STALE_AFTER_MS - 1).toISOString() - } + }) : undefined - ) - } as never) + ) + runtime.setOrchestrationDb(orchestrationDb) runtime.attachWindow(1) const result = runtime.syncWindowGraph(1, { @@ -259,14 +272,16 @@ describe('OrcaRuntimeService', () => { } const runtime = new OrcaRuntimeService(runtimeStore as never) const workerHandle = runtime.preAllocateHandleForPty('pty-worker') - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - getDispatchContext: vi.fn(() => ({ + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'getDispatchContext').mockImplementation(() => + dispatchContextRow({ task_id: 'task_abc123', assignee_handle: workerHandle, status: 'completed' - })) - } as never) + }) + ) + runtime.setOrchestrationDb(orchestrationDb) runtime.attachWindow(1) runtime.syncWindowGraph(1, { tabs: [ @@ -358,14 +373,16 @@ describe('OrcaRuntimeService', () => { } const runtime = new OrcaRuntimeService(runtimeStore as never) const parentHandle = runtime.preAllocateHandleForPty('pty-parent') - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - getDispatchContext: vi.fn(() => undefined), - getTask: vi.fn(() => ({ + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'getDispatchContext').mockImplementation(() => undefined) + vi.spyOn(orchestrationDb, 'getTask').mockImplementation(() => + taskLineageRow({ id: 'task_creator123', created_by_terminal_handle: parentHandle - })) - } as never) + }) + ) + runtime.setOrchestrationDb(orchestrationDb) runtime.attachWindow(1) runtime.syncWindowGraph(1, { tabs: [ diff --git a/src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts b/src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts index b3a89528ce91..652b5c1c4e2d 100644 --- a/src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts +++ b/src/main/runtime/orca-runtime-tests/mobile-summaries.spec.ts @@ -1,6 +1,11 @@ +import { makeRuntimeOrchestrationDb } from '../runtime-orchestration-db.test-fixture' import { describe, expect, it, vi } from 'vitest' import { makeAgentStatusStoreWiring } from '../agent-status-store-wiring.test-fixture' -import { OrcaRuntimeService, listWorktrees } from '../orca-runtime-test-mocks.spec' +import { + OrcaRuntimeService, + createRootDispatch, + listWorktrees +} from '../orca-runtime-test-mocks.spec' import { HEADLESS_LEAF_ID, TEST_FOLDER_PROJECT_GROUP_ID, @@ -456,27 +461,20 @@ describe('OrcaRuntimeService', () => { ] }) const workerHandle = runtime.preAllocateHandleForPty('pty-1') - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - getActiveDispatchForTerminal: vi.fn((handle: string) => - handle === workerHandle - ? { - id: 'ctx-1', - task_id: 'task-1', - assignee_handle: workerHandle, - status: 'dispatched' - } - : undefined - ), - getLatestDispatchForTerminal: vi.fn(() => undefined), - getTask: vi.fn(() => ({ - id: 'task-1', - task_title: 'Dispatch prompt work', - display_name: 'Review dispatch prompts and make worker labels distinct', - spec: 'Review dispatch prompts\n\nand make worker labels distinct' - })), - getActiveCoordinatorRun: vi.fn(() => undefined) - } as never) + const orchestrationDb = makeRuntimeOrchestrationDb() + const run = orchestrationDb.createRun({ + objective: 'Hook summary projection', + coordinatorHandle: null, + coordinatorPaneKey: null + }) + const task = orchestrationDb.createTask({ + runId: run.id, + taskTitle: 'Dispatch prompt work', + displayName: 'Review dispatch prompts and make worker labels distinct', + spec: 'Review dispatch prompts\n\nand make worker labels distinct' + }) + createRootDispatch(orchestrationDb, task.id, workerHandle, paneKey) + runtime.setOrchestrationDb(orchestrationDb) runtime.attachWindow(1) runtime.syncWindowGraph(1, { tabs: [ diff --git a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-02.spec.ts index 09771aceee57..b492b4a11462 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-creation-and-readiness-part-02.spec.ts @@ -1,3 +1,7 @@ +import { + makeRuntimeOrchestrationDb, + dispatchContextRow +} from '../runtime-orchestration-db.test-fixture' import { describe, expect, it, vi } from 'vitest' import { OrcaRuntimeService, @@ -9,7 +13,6 @@ import { setTerminalViewAttributes, tmpdir } from '../orca-runtime-test-mocks.spec' -import type { OrchestrationDb } from '../orchestration/db' import { getTerminalViewerColors } from '../terminal-view-attribute-store' import type { TerminalViewAttributes, @@ -112,15 +115,17 @@ describe('OrcaRuntimeService', () => { retireAgentHookCompatibilityAuthority: retireAuthority } ) - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - getActiveDispatchForTerminal: (handle: string) => + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'getActiveDispatchForTerminal').mockImplementation( + (handle: string) => handle === 'term_ssh_retained' - ? { id: 'dispatch-ssh', task_id: 'task-ssh', status: 'dispatched' } - : undefined, - failDispatch, - getActiveCoordinatorRun: () => undefined - } as unknown as OrchestrationDb) + ? dispatchContextRow({ id: 'dispatch-ssh', task_id: 'task-ssh', status: 'dispatched' }) + : undefined + ) + vi.spyOn(orchestrationDb, 'failDispatch').mockImplementation(failDispatch) + vi.spyOn(orchestrationDb, 'getActiveCoordinatorRun').mockImplementation(() => undefined) + runtime.setOrchestrationDb(orchestrationDb) runtime.attachWindow(TEST_WINDOW_ID) runtime.syncWindowGraph(TEST_WINDOW_ID, { tabs: [ diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts index 476db2ac7690..c69bf570dfb4 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-02.spec.ts @@ -1,3 +1,4 @@ +import { makeRuntimeOrchestrationDb } from '../runtime-orchestration-db.test-fixture' import { withDurableRuntimeStore } from '../runtime-durable-store-fixture' import { describe, expect, it, vi } from 'vitest' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' @@ -6,7 +7,6 @@ import { getDefaultWorkspaceSession, makePaneKey } from '../orca-runtime-test-mocks.spec' -import type { OrchestrationDb } from '../orchestration/db' import type { WorkspaceSessionState } from '../orca-runtime-test-mocks.spec' import { HEADLESS_LEAF_ID, @@ -469,24 +469,24 @@ describe('OrcaRuntimeService', () => { : null } ) - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - getActiveDispatchForTerminal: () => undefined, - listLegacyWorkerTerminalRecoveryRows: () => [ - { - dispatch_id: 'dispatch-legacy', - task_id: 'task-legacy', - dispatch_status: 'completed', - contract_version: 0, - assignee_handle: 'term_legacy', - assignee_pane_key: workerPaneKey, - process_incarnation: `pty-legacy:${incarnationId}`, - worker_state: 'ready', - worktree_id: TEST_WORKTREE_ID, - agent_terminal_handle: 'term_legacy' - } - ] - } as unknown as OrchestrationDb) + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'getActiveDispatchForTerminal').mockImplementation(() => undefined) + vi.spyOn(orchestrationDb, 'listLegacyWorkerTerminalRecoveryRows').mockImplementation(() => [ + { + dispatch_id: 'dispatch-legacy', + task_id: 'task-legacy', + dispatch_status: 'completed', + contract_version: 0, + assignee_handle: 'term_legacy', + assignee_pane_key: workerPaneKey, + process_incarnation: `pty-legacy:${incarnationId}`, + worker_state: 'ready', + worktree_id: TEST_WORKTREE_ID, + agent_terminal_handle: 'term_legacy' + } + ]) + runtime.setOrchestrationDb(orchestrationDb) const write = vi.fn(() => true) const kill = vi.fn(() => true) const READY_SCREEN = diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts index 050e19921102..d3fd663a60fa 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-03.spec.ts @@ -1,8 +1,8 @@ +import { makeRuntimeOrchestrationDb } from '../runtime-orchestration-db.test-fixture' import { withDurableRuntimeStore } from '../runtime-durable-store-fixture' import { describe, expect, it, vi } from 'vitest' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' import { OrcaRuntimeService, getDefaultWorkspaceSession } from '../orca-runtime-test-mocks.spec' -import type { OrchestrationDb } from '../orchestration/db' import type { WorkspaceSessionState } from '../orca-runtime-test-mocks.spec' import { HEADLESS_LEAF_ID, @@ -46,24 +46,24 @@ describe('OrcaRuntimeService', () => { undefined, { canRecoverPersistentLocalPtys: () => true } ) - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - getActiveDispatchForTerminal: () => undefined, - listLegacyWorkerTerminalRecoveryRows: () => [ - { - dispatch_id: 'dispatch-reveal-retry', - task_id: 'task-reveal-retry', - dispatch_status: 'completed', - contract_version: 0, - assignee_handle: 'term_reveal_retry', - assignee_pane_key: workerPaneKey, - process_incarnation: `pty-reveal-retry:${incarnationId}`, - worker_state: 'ready', - worktree_id: TEST_WORKTREE_ID, - agent_terminal_handle: 'term_reveal_retry' - } - ] - } as unknown as OrchestrationDb) + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'getActiveDispatchForTerminal').mockImplementation(() => undefined) + vi.spyOn(orchestrationDb, 'listLegacyWorkerTerminalRecoveryRows').mockImplementation(() => [ + { + dispatch_id: 'dispatch-reveal-retry', + task_id: 'task-reveal-retry', + dispatch_status: 'completed', + contract_version: 0, + assignee_handle: 'term_reveal_retry', + assignee_pane_key: workerPaneKey, + process_incarnation: `pty-reveal-retry:${incarnationId}`, + worker_state: 'ready', + worktree_id: TEST_WORKTREE_ID, + agent_terminal_handle: 'term_reveal_retry' + } + ]) + runtime.setOrchestrationDb(orchestrationDb) runtime.setPtyController({ write: vi.fn(() => true), kill: vi.fn(() => true), @@ -462,23 +462,23 @@ describe('OrcaRuntimeService', () => { undefined, { canRecoverPersistentLocalPtys: () => true } ) - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - listLegacyWorkerTerminalRecoveryRows: () => [ - { - dispatch_id: 'dispatch-persistence-failure', - task_id: 'task-persistence-failure', - dispatch_status: 'completed', - contract_version: 0, - assignee_handle: 'term_persistence_failure', - assignee_pane_key: workerPaneKey, - process_incarnation: `pty-persistence-failure:${incarnationId}`, - worker_state: 'ready', - worktree_id: TEST_WORKTREE_ID, - agent_terminal_handle: 'term_persistence_failure' - } - ] - } as unknown as OrchestrationDb) + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'listLegacyWorkerTerminalRecoveryRows').mockImplementation(() => [ + { + dispatch_id: 'dispatch-persistence-failure', + task_id: 'task-persistence-failure', + dispatch_status: 'completed', + contract_version: 0, + assignee_handle: 'term_persistence_failure', + assignee_pane_key: workerPaneKey, + process_incarnation: `pty-persistence-failure:${incarnationId}`, + worker_state: 'ready', + worktree_id: TEST_WORKTREE_ID, + agent_terminal_handle: 'term_persistence_failure' + } + ]) + runtime.setOrchestrationDb(orchestrationDb) runtime.setPtyController({ write: vi.fn(() => true), kill: vi.fn(() => true), diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts index 20effb11ce2b..54527e355afc 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-04.spec.ts @@ -1,3 +1,4 @@ +import { makeRuntimeOrchestrationDb } from '../runtime-orchestration-db.test-fixture' import { withDurableRuntimeStore } from '../runtime-durable-store-fixture' import { describe, expect, it, vi } from 'vitest' import { @@ -391,23 +392,23 @@ describe('OrcaRuntimeService', () => { undefined, { canRecoverPersistentLocalPtys: () => true } ) - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - listLegacyWorkerTerminalRecoveryRows: () => [ - { - dispatch_id: 'dispatch-inventory-unavailable', - task_id: 'task-inventory-unavailable', - dispatch_status: 'completed', - contract_version: 0, - assignee_handle: 'term_inventory_unavailable', - assignee_pane_key: workerPaneKey, - process_incarnation: `pty-inventory-unavailable:${incarnationId}`, - worker_state: 'ready', - worktree_id: TEST_WORKTREE_ID, - agent_terminal_handle: 'term_inventory_unavailable' - } - ] - } as unknown as OrchestrationDb) + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'listLegacyWorkerTerminalRecoveryRows').mockImplementation(() => [ + { + dispatch_id: 'dispatch-inventory-unavailable', + task_id: 'task-inventory-unavailable', + dispatch_status: 'completed', + contract_version: 0, + assignee_handle: 'term_inventory_unavailable', + assignee_pane_key: workerPaneKey, + process_incarnation: `pty-inventory-unavailable:${incarnationId}`, + worker_state: 'ready', + worktree_id: TEST_WORKTREE_ID, + agent_terminal_handle: 'term_inventory_unavailable' + } + ]) + runtime.setOrchestrationDb(orchestrationDb) const listProcesses = vi .fn() .mockRejectedValueOnce(new Error('local provider unavailable')) diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-05.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-05.spec.ts index cb1e31caccda..1431f06eb564 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-05.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-05.spec.ts @@ -1,3 +1,4 @@ +import { makeRuntimeOrchestrationDb } from '../runtime-orchestration-db.test-fixture' import { withDurableRuntimeStore } from '../runtime-durable-store-fixture' import { describe, expect, it, vi } from 'vitest' import { @@ -202,23 +203,23 @@ describe('OrcaRuntimeService', () => { undefined, { canRecoverPersistentLocalPtys: () => true } ) - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - listLegacyWorkerTerminalRecoveryRows: () => [ - { - dispatch_id: 'dispatch-folder', - task_id: 'task-folder', - dispatch_status: 'completed', - contract_version: 0, - assignee_handle: 'term_folder', - assignee_pane_key: workerPaneKey, - process_incarnation: `pty-folder-legacy:${incarnationId}`, - worker_state: 'ready', - worktree_id: TEST_FOLDER_WORKSPACE_KEY, - agent_terminal_handle: 'term_folder' - } - ] - } as unknown as OrchestrationDb) + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'listLegacyWorkerTerminalRecoveryRows').mockImplementation(() => [ + { + dispatch_id: 'dispatch-folder', + task_id: 'task-folder', + dispatch_status: 'completed', + contract_version: 0, + assignee_handle: 'term_folder', + assignee_pane_key: workerPaneKey, + process_incarnation: `pty-folder-legacy:${incarnationId}`, + worker_state: 'ready', + worktree_id: TEST_FOLDER_WORKSPACE_KEY, + agent_terminal_handle: 'term_folder' + } + ]) + runtime.setOrchestrationDb(orchestrationDb) const listProcesses = vi.fn(async () => [ { id: 'pty-folder-legacy', @@ -331,23 +332,23 @@ describe('OrcaRuntimeService', () => { undefined, { canRecoverPersistentLocalPtys: () => true } ) - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - listLegacyWorkerTerminalRecoveryRows: () => [ - { - dispatch_id: 'dispatch-ssh-folder', - task_id: 'task-ssh-folder', - dispatch_status: 'completed', - contract_version: 0, - assignee_handle: 'term_ssh_folder', - assignee_pane_key: workerPaneKey, - process_incarnation: `${ptyId}:${incarnationId}`, - worker_state: 'ready', - worktree_id: TEST_FOLDER_WORKSPACE_KEY, - agent_terminal_handle: 'term_ssh_folder' - } - ] - } as unknown as OrchestrationDb) + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'listLegacyWorkerTerminalRecoveryRows').mockImplementation(() => [ + { + dispatch_id: 'dispatch-ssh-folder', + task_id: 'task-ssh-folder', + dispatch_status: 'completed', + contract_version: 0, + assignee_handle: 'term_ssh_folder', + assignee_pane_key: workerPaneKey, + process_incarnation: `${ptyId}:${incarnationId}`, + worker_state: 'ready', + worktree_id: TEST_FOLDER_WORKSPACE_KEY, + agent_terminal_handle: 'term_ssh_folder' + } + ]) + runtime.setOrchestrationDb(orchestrationDb) const listProcesses = vi.fn(async () => [ { id: ptyId, diff --git a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-06.spec.ts b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-06.spec.ts index 072e39ca7e8e..19859db558ff 100644 --- a/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-06.spec.ts +++ b/src/main/runtime/orca-runtime-tests/terminal-output-and-worker-recovery-part-06.spec.ts @@ -1,3 +1,4 @@ +import { makeRuntimeOrchestrationDb } from '../runtime-orchestration-db.test-fixture' import { withDurableRuntimeStore } from '../runtime-durable-store-fixture' import { describe, expect, it, vi } from 'vitest' import { @@ -5,7 +6,6 @@ import { getDefaultWorkspaceSession, setPlatform } from '../orca-runtime-test-mocks.spec' -import type { OrchestrationDb } from '../orchestration/db' import type { WorkspaceSessionState } from '../orca-runtime-test-mocks.spec' import { HEADLESS_LEAF_ID, @@ -95,23 +95,23 @@ describe('OrcaRuntimeService', () => { undefined, { canRecoverPersistentLocalPtys: () => true } ) - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - listLegacyWorkerTerminalRecoveryRows: () => [ - { - dispatch_id: 'dispatch-ssh', - task_id: 'task-ssh', - dispatch_status: 'completed', - contract_version: 0, - assignee_handle: 'term_ssh_legacy', - assignee_pane_key: workerPaneKey, - process_incarnation: `${ptyId}:${incarnationId}`, - worker_state: 'ready', - worktree_id: TEST_WORKTREE_ID, - agent_terminal_handle: 'term_ssh_legacy' - } - ] - } as unknown as OrchestrationDb) + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'listLegacyWorkerTerminalRecoveryRows').mockImplementation(() => [ + { + dispatch_id: 'dispatch-ssh', + task_id: 'task-ssh', + dispatch_status: 'completed', + contract_version: 0, + assignee_handle: 'term_ssh_legacy', + assignee_pane_key: workerPaneKey, + process_incarnation: `${ptyId}:${incarnationId}`, + worker_state: 'ready', + worktree_id: TEST_WORKTREE_ID, + agent_terminal_handle: 'term_ssh_legacy' + } + ]) + runtime.setOrchestrationDb(orchestrationDb) runtime.setPtyController({ write: vi.fn(() => true), kill: vi.fn(() => true), @@ -229,23 +229,23 @@ describe('OrcaRuntimeService', () => { undefined, { canRecoverPersistentLocalPtys: () => true } ) - runtime.setOrchestrationDb({ - listSessionDispatchesForPresentation: () => [], - listLegacyWorkerTerminalRecoveryRows: () => [ - { - dispatch_id: 'dispatch-wsl', - task_id: 'task-wsl', - dispatch_status: 'completed', - contract_version: 0, - assignee_handle: 'term_wsl_legacy', - assignee_pane_key: workerPaneKey, - process_incarnation: `pty-wsl-legacy:${incarnationId}`, - worker_state: 'ready', - worktree_id: TEST_WORKTREE_ID, - agent_terminal_handle: 'term_wsl_legacy' - } - ] - } as unknown as OrchestrationDb) + const orchestrationDb = makeRuntimeOrchestrationDb() + vi.spyOn(orchestrationDb, 'listSessionDispatchesForPresentation').mockImplementation(() => []) + vi.spyOn(orchestrationDb, 'listLegacyWorkerTerminalRecoveryRows').mockImplementation(() => [ + { + dispatch_id: 'dispatch-wsl', + task_id: 'task-wsl', + dispatch_status: 'completed', + contract_version: 0, + assignee_handle: 'term_wsl_legacy', + assignee_pane_key: workerPaneKey, + process_incarnation: `pty-wsl-legacy:${incarnationId}`, + worker_state: 'ready', + worktree_id: TEST_WORKTREE_ID, + agent_terminal_handle: 'term_wsl_legacy' + } + ]) + runtime.setOrchestrationDb(orchestrationDb) // Declare the scope parameter so mock.calls retains its type alongside the runtime deadline. const listProcesses = vi.fn(async (_connectionId?: string | null) => [ { diff --git a/src/main/runtime/runtime-orchestration-db.test-fixture.ts b/src/main/runtime/runtime-orchestration-db.test-fixture.ts new file mode 100644 index 000000000000..ee8a518910b1 --- /dev/null +++ b/src/main/runtime/runtime-orchestration-db.test-fixture.ts @@ -0,0 +1,111 @@ +import { afterEach, vi } from 'vitest' +import { OrchestrationDb } from './orchestration/db' +import type { TaskRuntimeLineageRow } from './orchestration/db/run-list-page' +import type { CoordinatorRun, DispatchContextRow, RunRow } from './orchestration/types' + +const databases = new Set() +const createdAt = '2026-10-27T12:00:00Z' + +afterEach(() => { + for (const db of databases) { + db.close() + } + databases.clear() +}) + +export function makeRuntimeOrchestrationDb(): OrchestrationDb { + const db = new OrchestrationDb(':memory:') + databases.add(db) + // These scenarios project supplied terminal contexts even without persisted Dispatches. + vi.spyOn(db, 'hasAnyDispatchContexts').mockReturnValue(true) + return db +} + +export function dispatchContextRow(fields: Partial): DispatchContextRow { + return { + id: 'fixture-dispatch', + run_id: 'fixture-run', + task_id: 'fixture-task', + contract_version: 0, + launch_token_hash: null, + assignee_handle: null, + assignee_pane_key: null, + assignee_orca_session_id: null, + capability_hash: null, + process_incarnation: null, + capability_revoked_at: null, + retry_of_dispatch_id: null, + creator_dispatch_id: null, + creator_handle: null, + creator_pane_key: null, + creator_orca_session_id: null, + host_scope: null, + status: 'dispatched', + failure_count: 0, + last_failure: null, + termination_reason: null, + depth: 1, + consumer_generation: 0, + dispatched_at: createdAt, + completed_at: null, + created_at: createdAt, + last_heartbeat_at: null, + ...fields + } +} + +export function taskLineageRow(fields: Partial): TaskRuntimeLineageRow { + return { + id: 'fixture-task', + run_id: 'fixture-run', + parent_id: null, + created_by_terminal_handle: null, + created_by_pane_key: null, + created_by_process_incarnation: null, + created_by_run_generation: null, + task_title: null, + display_name: null, + spec: '', + status: 'ready', + deps: '[]', + result: null, + created_at: createdAt, + completed_at: null, + creator_dispatch_id: null, + creator_dispatch_run_id: null, + creator_dispatch_pane_key: null, + creator_dispatch_process_incarnation: null, + ...fields + } +} + +export function runRow(fields: Partial): RunRow { + return { + id: 'fixture-run', + objective: '', + home_database: 'this_database', + coordinator_handle: null, + coordinator_pane_key: null, + coordinator_orca_session_id: null, + coordinator_orca_session_id_generation: null, + consumer_generation: 0, + legacy: 0, + created_at: createdAt, + updated_at: createdAt, + ...fields + } +} + +export function coordinatorRunRow(fields: Partial): CoordinatorRun { + return { + id: 'fixture-coordinator', + spec: '', + status: 'running', + coordinator_handle: 'term_fixture', + poll_interval_ms: 2000, + created_at: createdAt, + completed_at: null, + scheduler_lost_at: null, + ...fields + } +} From 403cd583e8bfc5e843ec23a09dc9b13041d7225c Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 08:49:22 -0700 Subject: [PATCH 020/164] test: complete stale-leaf mailbox fixture session input --- src/main/runtime/terminal-send-stale-leaf-liveness.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/runtime/terminal-send-stale-leaf-liveness.test.ts b/src/main/runtime/terminal-send-stale-leaf-liveness.test.ts index 354f4edd8558..bafa06103a36 100644 --- a/src/main/runtime/terminal-send-stale-leaf-liveness.test.ts +++ b/src/main/runtime/terminal-send-stale-leaf-liveness.test.ts @@ -418,6 +418,7 @@ function makeOrchestrationDbStub(toHandle: () => string) { }) }, db: { + listSessionDispatchesForPresentation: () => [], // Mirrors the real query: `read = 0 AND delivered_at IS NULL`. getUndeliveredUnreadMessages: (handle: string) => rows.filter((row) => row.to_handle === handle && row.read === 0 && !row.delivered_at), From 26ee0e30ee15f88be182e80330efb3acc218a5f3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 09:40:43 -0700 Subject: [PATCH 021/164] Derive durable crew parents from retained assignment proof --- .../construction/runtime-service-state.ts | 6 +- .../crew/crew-claim-origins.test.ts | 104 ++++++ .../crew/crew-claim-reduction.ts | 62 ++++ .../crew/crew-cli-addresses.test.ts | 2 +- .../crew/crew-host-derivation.ts | 9 +- .../crew/crew-identity-inputs.ts | 23 ++ .../crew/crew-mutation-notifications.ts | 9 + .../orchestration/crew/crew-parent-inputs.ts | 142 ++++++++ .../crew/crew-parent-persistence.test.ts | 76 ++++ .../crew/crew-parent-relations.test.ts | 340 ++++++++++++++++++ .../crew/crew-parent-relations.ts | 192 ++++++++++ .../crew/crew-parent-rpc.test.ts | 126 +++++++ .../orchestration/crew/crew-parties.ts | 10 +- .../orchestration/crew/crew-party-snapshot.ts | 28 +- .../runtime/orchestration/crew/crew-query.ts | 54 +-- .../crew/crew-read-model-performance.test.ts | 22 +- .../orchestration/crew/crew-read-model.ts | 12 +- .../orchestration/crew/crew-runtime-watch.ts | 5 +- .../orchestration/crew/crew-source-inputs.ts | 139 +++++++ .../db/schema/schema-column-probes.ts | 13 +- .../runtime-orchestration-crew-names.test.ts | 83 +++++ ...runtime-orchestration-sender-names.test.ts | 2 +- .../runtime-orchestration-sender-names.ts | 114 +++++- 23 files changed, 1484 insertions(+), 89 deletions(-) create mode 100644 src/main/runtime/orchestration/crew/crew-claim-origins.test.ts create mode 100644 src/main/runtime/orchestration/crew/crew-claim-reduction.ts create mode 100644 src/main/runtime/orchestration/crew/crew-identity-inputs.ts create mode 100644 src/main/runtime/orchestration/crew/crew-parent-inputs.ts create mode 100644 src/main/runtime/orchestration/crew/crew-parent-persistence.test.ts create mode 100644 src/main/runtime/orchestration/crew/crew-parent-relations.test.ts create mode 100644 src/main/runtime/orchestration/crew/crew-parent-relations.ts create mode 100644 src/main/runtime/orchestration/crew/crew-parent-rpc.test.ts create mode 100644 src/main/runtime/orchestration/crew/crew-source-inputs.ts create mode 100644 src/main/runtime/runtime-orchestration-crew-names.test.ts diff --git a/src/main/runtime/construction/runtime-service-state.ts b/src/main/runtime/construction/runtime-service-state.ts index 60894f2edc44..3a930d7d382d 100644 --- a/src/main/runtime/construction/runtime-service-state.ts +++ b/src/main/runtime/construction/runtime-service-state.ts @@ -304,10 +304,8 @@ export abstract class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWith getTerminalPaneKey: (handle) => this.getTerminalPaneKey(handle), getWorkspaceSession: (worktreeId) => this.getWorkspaceSessionForWorktree(worktreeId), getGeneratedTitlesEnabled: () => this.store?.getSettings?.()?.tabAutoGenerateTitle === true, - getAgentStatusSnapshotForPane: (paneKey) => - this.getAgentStatusSnapshotForPaneFn?.(paneKey) ?? - this.getAgentStatusSnapshotFn?.().filter((row) => row.paneKey === paneKey) ?? - [], + getAgentStatusSnapshot: () => this.getAgentStatusSnapshotFn?.() ?? [], + getAgentStatusSnapshotForPane: (paneKey) => this.getAgentStatusSnapshotForPaneFn?.(paneKey), getTrackedTitle: (ptyId) => this.getTrackedDisplayTitleForPty(ptyId) }) diff --git a/src/main/runtime/orchestration/crew/crew-claim-origins.test.ts b/src/main/runtime/orchestration/crew/crew-claim-origins.test.ts new file mode 100644 index 000000000000..e0f4f45fc0ea --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-claim-origins.test.ts @@ -0,0 +1,104 @@ +import { describe, expect, it } from 'vitest' +import { OrchestrationDb } from '../db' +import { createLegacyStorageCutoverFixture } from '../orchestration-legacy-storage-test-fixture' +import { recordFailedStartDispatchIdentity } from '../db/worker-terminal/failed-start-dispatch-identity' +import { fixture } from './crew-read-model.test-fixture' + +// These retained facts are evidence, not an origin certificate for rowid ordering. +describe('retained crew claim provenance', () => { + it('distinguishes insertion from acquisition and failed-start identity repair', () => { + const { db, run, assign, handles } = fixture() + const direct = assign('term_worker') + db.completeDispatch(direct.id) + const next = assign('term_worker', 'term_peer') + expect(next.assignee_pane_key).toBe(direct.assignee_pane_key) + db.completeDispatch(next.id) + const start = () => + db.createStartingWorkerDispatch({ + taskSpec: 'Delayed claim', + taskRunId: run.id, + startOptions: {}, + creator: { kind: 'system' }, + maxDepth: 10 + }) + const older = start() + const newer = start() + const attach = (id: string) => + db.prepareStartingWorkerAuthority({ + dispatchId: id, + handle: 'term_worker', + paneKey: handles.get('term_worker')!, + processIncarnation: 'process_one', + worktreeId: 'wt', + setupState: 'not_applicable', + effects: [] + }) + attach(newer.dispatch.id) + db.markWorkerDispatchReady(newer.dispatch.id) + db.completeDispatch(newer.dispatch.id) + attach(older.dispatch.id) + expect(db.getDispatchContextById(older.dispatch.id)?.assignee_handle).toBe('term_worker') + expect(db.db.prepare('SELECT id FROM dispatch_contexts ORDER BY rowid').all()).toEqual( + [direct, next, older.dispatch, newer.dispatch].map(({ id }) => ({ id })) + ) + db.markWorkerDispatchReady(older.dispatch.id) + db.completeDispatch(older.dispatch.id) + const failed = start() + db.recordCreatedWorkerTerminalCustody({ + dispatchId: failed.dispatch.id, + handle: 'term_worker', + paneKey: handles.get('term_worker')!, + processIncarnation: 'process_one', + worktreeId: 'wt' + }) + db.recordWorkerStage({ + dispatchId: failed.dispatch.id, + stage: 'agent_readiness', + terminalHandle: 'term_worker' + }) + expect(db.getDispatchContextById(failed.dispatch.id)?.assignee_handle).toBeNull() + db.failWorkerStart(failed.dispatch.id, 'agent_readiness', 'Agent did not start') + expect(db.getDispatchContextById(failed.dispatch.id)?.assignee_handle).toBe('term_worker') + // The production repair can be repeated after settlement without changing row birth. + recordFailedStartDispatchIdentity(db, db.getWorkerDispatch(failed.dispatch.id)!) + expect(db.getDispatchContextById(failed.dispatch.id)?.assignee_handle).toBe('term_worker') + const oldPane = handles.get('term_worker')! + const movedPane = oldPane.replace('tab_worker:', 'tab_moved:') + db.rekeyWorkerTerminalResourcePaneKey({ fromPaneKey: oldPane, toPaneKey: movedPane }) + expect(db.getWorkerTerminalResourceByOwner(failed.dispatch.id)?.pane_key).toBe(movedPane) + expect(db.getDispatchContextById(failed.dispatch.id)?.assignee_pane_key).toBe(oldPane) + console.log( + 'claim origin trace', + JSON.stringify({ + direct: direct.id, + sequential: next.id, + delayedBirth: [older.dispatch.id, newer.dispatch.id], + acquisition: [newer.dispatch.id, older.dispatch.id], + failedIdentity: failed.dispatch.id + }) + ) + }) + + it('reopens supported legacy storage without inventing an atomic origin certificate', () => { + const legacy = createLegacyStorageCutoverFixture() + // Kept as private fixture evidence; no user profile or login storage is read. + const db = new OrchestrationDb(legacy.fixture.dbPath) + try { + const retained = db.getDispatchContextById(legacy.fixture.legacyDispatchId)! + expect(retained.run_id).toBe(db.getLegacyAdoption()?.adopted_run_id) + expect(db.getWorkerDispatch(retained.id)).toBeUndefined() + expect(retained.assignee_handle).toBe('term_legacy_worker') + console.log( + 'legacy claim origin trace', + JSON.stringify({ + path: legacy.fixture.dbPath, + run: retained.run_id, + contract: retained.contract_version, + companion: false + }) + ) + } finally { + db.close() + } + }) +}) diff --git a/src/main/runtime/orchestration/crew/crew-claim-reduction.ts b/src/main/runtime/orchestration/crew/crew-claim-reduction.ts new file mode 100644 index 000000000000..3364b7412e10 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-claim-reduction.ts @@ -0,0 +1,62 @@ +/** Strongly connected components preserve corrupt cycles while reducing proven acyclic successors. */ +export function maximalCrewClaims( + keys: string[], + successors: ReadonlyMap> +): Set { + const reverse = new Map() + for (const [from, targets] of successors) { + for (const to of targets) { + const previous = reverse.get(to) ?? [] + previous.push(from) + reverse.set(to, previous) + } + } + const visited = new Set() + const finished: string[] = [] + for (const key of keys) { + const stack: { key: string; finish: boolean }[] = [{ key, finish: false }] + while (stack.length) { + const next = stack.pop()! + if (next.finish) { + finished.push(next.key) + } else if (!visited.has(next.key)) { + visited.add(next.key) + stack.push({ ...next, finish: true }) + for (const target of successors.get(next.key) ?? []) { + if (!visited.has(target)) { + stack.push({ key: target, finish: false }) + } + } + } + } + } + const component = new Map() + let count = 0 + for (const key of finished.toReversed()) { + if (component.has(key)) { + continue + } + const stack = [key] + component.set(key, count) + while (stack.length) { + for (const previous of reverse.get(stack.pop()!) ?? []) { + if (!component.has(previous)) { + component.set(previous, count) + stack.push(previous) + } + } + } + count++ + } + const sizes = new Map() + for (const id of component.values()) { + sizes.set(id, (sizes.get(id) ?? 0) + 1) + } + return new Set( + keys.filter( + (key) => + sizes.get(component.get(key)!)! > 1 || + ![...(successors.get(key) ?? [])].some((next) => component.get(next) !== component.get(key)) + ) + ) +} diff --git a/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts b/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts index b085b9e3ca5a..8539eb5b2977 100644 --- a/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts +++ b/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts @@ -285,7 +285,7 @@ it('keeps crew as the only observer for title, settings and mirrored-name source creator: { kind: 'system' }, maxDepth: 10 }) - const names = vi.spyOn(runtime.orchestrationSenderNames, 'nameOf') + const names = vi.spyOn(runtime.orchestrationSenderNames, 'captureCrewInputs') const selection = vi.spyOn(db, 'listSessionDispatchesForPresentation') const frames: unknown[] = [] const stop = subscribeCrew( diff --git a/src/main/runtime/orchestration/crew/crew-host-derivation.ts b/src/main/runtime/orchestration/crew/crew-host-derivation.ts index 1145fc4e8001..18016cdaa3fb 100644 --- a/src/main/runtime/orchestration/crew/crew-host-derivation.ts +++ b/src/main/runtime/orchestration/crew/crew-host-derivation.ts @@ -1,13 +1,15 @@ +import { captureCrewIdentityInputs } from './crew-identity-inputs' import type { FleetDurableWorker } from '../../../../shared/orchestration-fleet-projection' import { createFleetStatusIndex } from '../../../../shared/orchestration-fleet-status-index' import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-freshness' import { creatorFirstParent } from './crew-rules' import { createCrewPartyRegistry, type Party } from './crew-parties' import { readCrewAssignments, type CrewAssignmentRow } from './crew-query' +import { createCrewSourceInputs } from './crew-source-inputs' import type { CrewReadDependencies } from './crew-read-model' export function createCrewHostDerivation(deps: CrewReadDependencies, now: number) { - const { statuses, ...sources } = deps + const { statuses, ...sources } = captureCrewIdentityInputs(deps) const registry = createCrewPartyRegistry({ ...sources, statuses }) const { party, alias } = registry const selected = (rows: CrewAssignmentRow[]) => @@ -24,7 +26,8 @@ export function createCrewHostDerivation(deps: CrewReadDependencies, now: number row.assignee_orca_session_id, row.assignee_handle, row.assignee_pane_key, - `dispatch:${row.id}` + `dispatch:${row.id}`, + row.assignee_process )! assignmentParty.set(row.id, worker) alias(`dispatch:${row.id}`, worker.address) @@ -141,6 +144,7 @@ export function createCrewHostDerivation(deps: CrewReadDependencies, now: number return refreshCrewStatuses( { registry, + sourceInputs: createCrewSourceInputs(deps.db), deps: { ...sources, statuses, records: registry.records }, now, expiresAt, @@ -157,6 +161,7 @@ export function refreshCrewStatuses< workersById: Map } >(host: T, statuses: CrewReadDependencies['statuses']) { + statuses = structuredClone(statuses) const statusIndex = createFleetStatusIndex(statuses, [...host.workersById.values()]) const statusesByPane = new Map() for (const status of statuses) { diff --git a/src/main/runtime/orchestration/crew/crew-identity-inputs.ts b/src/main/runtime/orchestration/crew/crew-identity-inputs.ts new file mode 100644 index 000000000000..06212617d480 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-identity-inputs.ts @@ -0,0 +1,23 @@ +import type { CrewReadDependencies } from './crew-read-model' + +/** Capture each runtime identity fact once in the host input generation, including absent facts. */ +export function captureCrewIdentityInputs(deps: CrewReadDependencies): CrewReadDependencies { + const { statuses, ...sources } = deps + const capture = (read: (key: string) => T) => { + const facts = new Map() + return (key: string): T => { + if (!facts.has(key)) { + facts.set(key, read(key)) + } + return facts.get(key)! + } + } + return { + ...sources, + statuses: structuredClone(statuses), + liveHandle: capture(deps.liveHandle), + handleForPane: capture(deps.handleForPane), + paneForHandle: capture(deps.paneForHandle), + processForHandle: capture((handle) => deps.processForHandle?.(handle) ?? null) + } +} diff --git a/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts b/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts index 8df3744bd3b7..45ed448daa8f 100644 --- a/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts +++ b/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts @@ -81,6 +81,15 @@ const trafficMutations: ReadonlySet = new Set([ export function attachCrewMutationNotifications(ctor: { prototype: object }): void { // SAFETY: the database installer invokes this after installing the domain methods. const prototype = ctor.prototype as OrchestrationDb + const sourceIdentity = prototype.getOrCreateLocalMutationCallerFingerprint + prototype.getOrCreateLocalMutationCallerFingerprint = function () { + const known = this.localMutationCallerFingerprint + const result = sourceIdentity.call(this) + if (!known) { + this.crewChanges.notify() + } + return result + } const insert = prototype.insertMessage prototype.insertMessage = function (message) { const result = insert.call(this, message) diff --git a/src/main/runtime/orchestration/crew/crew-parent-inputs.ts b/src/main/runtime/orchestration/crew/crew-parent-inputs.ts new file mode 100644 index 000000000000..da8efc123ca6 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-parent-inputs.ts @@ -0,0 +1,142 @@ +import { z } from 'zod' +import { readCrewAssignmentIds } from './crew-query' +import type { OrchestrationDb } from '../db' +import { currentRunCoordinatorOrcaSessionIdSql } from '../db/runs/run-coordinator-orca-session' +import { parsePaneKey } from '../../../../shared/stable-pane-id' +import { + DISPATCH_PANE_KEY_MATCH_SUFFIX_SQL, + REMOTE_ATTACHMENT_PANE_KEY_MATCH_SUFFIX_SQL, + paneKeyMatchSuffix +} from '../db/pane-key-match' + +const nullable = z.string().nullable() +const claim = z.object({ + id: z.string(), + task: z.string(), + run: z.string(), + runHome: z.string(), + handle: nullable, + pane: nullable, + session: nullable, + process: nullable, + host: nullable, + endpoint: nullable, + creator: nullable, + creatorHandle: nullable, + creatorPane: nullable, + creatorSession: nullable, + retry: nullable, + home: nullable, + coordinator: nullable, + coordinatorPane: nullable, + coordinatorSession: nullable +}) +export type CrewParentClaim = z.infer & { family: 'local' | 'remote' } +const resource = z.object({ + id: z.string(), + origin: z.string(), + owner: z.string(), + prior: z.string(), + handle: z.string(), + pane: nullable, + process: nullable, + host: nullable, + endpoint: nullable, + endpointProcess: nullable, + ownership: z.string() +}) +export type CrewParentResource = z.infer + +const localColumns = `d.id, d.task_id AS task, d.run_id AS run, r.home_database AS runHome, d.assignee_handle AS handle, + d.assignee_pane_key AS pane, d.assignee_orca_session_id AS session, + d.process_incarnation AS process, d.host_scope AS host, w.runtime_epoch AS endpoint, + d.creator_dispatch_id AS creator, d.creator_handle AS creatorHandle, + d.creator_pane_key AS creatorPane, d.creator_orca_session_id AS creatorSession, + d.retry_of_dispatch_id AS retry, NULL AS home, r.coordinator_handle AS coordinator, + r.coordinator_pane_key AS coordinatorPane, + ${currentRunCoordinatorOrcaSessionIdSql('r')} AS coordinatorSession` + +export function readCrewParentInputs(db: OrchestrationDb, addresses: string[], panes: string[]) { + const handles = JSON.stringify(addresses.filter((value) => value.startsWith('term_'))) + const sessions = JSON.stringify( + addresses + .filter((value) => value.startsWith('orca_session_id:')) + .map((value) => value.slice(16)) + ) + const ids = JSON.stringify( + addresses.filter((value) => value.startsWith('dispatch:')).map((value) => value.slice(9)) + ) + const paneKeys = JSON.stringify(panes) + const leaves = JSON.stringify(panes.filter((pane) => parsePaneKey(pane)).map(paneKeyMatchSuffix)) + const local = claim + .array() + .parse( + db.db + .prepare(`SELECT ${localColumns} + FROM dispatch_contexts d JOIN runs r ON r.id = d.run_id + LEFT JOIN worker_dispatches w ON w.dispatch_id = d.id + WHERE d.rowid IN ( + SELECT rowid FROM dispatch_contexts WHERE assignee_handle IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM dispatch_contexts WHERE assignee_orca_session_id IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM dispatch_contexts WHERE assignee_pane_key IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM dispatch_contexts WHERE assignee_pane_key IS NOT NULL AND ${DISPATCH_PANE_KEY_MATCH_SUFFIX_SQL} IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM dispatch_contexts WHERE id IN (SELECT value FROM json_each(?))) + ORDER BY d.id`) + .all(handles, sessions, paneKeys, leaves, ids) + ) + .map((row): CrewParentClaim => ({ ...row, family: 'local' })) + const remote = claim + .array() + .parse( + db.db + .prepare(`SELECT dispatch_id AS id, task_id AS task, + home_run_id AS run, r.home_database AS runHome, terminal_handle AS handle, pane_key AS pane, NULL AS session, + process_incarnation AS process, NULL AS host, runtime_epoch AS endpoint, + NULL AS creator, NULL AS creatorHandle, NULL AS creatorPane, NULL AS creatorSession, + NULL AS retry, home_peer_fingerprint AS home, NULL AS coordinator, + NULL AS coordinatorPane, NULL AS coordinatorSession + FROM remote_dispatch_attachments a JOIN runs r ON r.id = a.home_run_id WHERE a.rowid IN ( + SELECT rowid FROM remote_dispatch_attachments WHERE terminal_handle IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM remote_dispatch_attachments WHERE pane_key IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM remote_dispatch_attachments WHERE pane_key IS NOT NULL AND ${REMOTE_ATTACHMENT_PANE_KEY_MATCH_SUFFIX_SQL} IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM remote_dispatch_attachments WHERE dispatch_id IN (SELECT value FROM json_each(?))) + ORDER BY dispatch_id`) + .all(handles, paneKeys, leaves, ids) + ) + .map((row): CrewParentClaim => ({ ...row, family: 'remote' })) + const claims = [...local, ...remote] + const creators = claim + .array() + .parse( + db.db + .prepare(`SELECT ${localColumns} + FROM dispatch_contexts d JOIN runs r ON r.id = d.run_id + LEFT JOIN worker_dispatches w ON w.dispatch_id = d.id + WHERE d.id IN (SELECT value FROM json_each(?)) ORDER BY d.id`) + .all( + JSON.stringify([...new Set(local.flatMap((row) => (row.creator ? [row.creator] : [])))]) + ) + ) + .map((row): CrewParentClaim => ({ ...row, family: 'local' })) + const resources = resource.array().parse( + db.db + .prepare(`SELECT id, origin_dispatch_id AS origin, + owner_dispatch_id AS owner, prior_owner_dispatch_ids AS prior, terminal_handle AS handle, + pane_key AS pane, process_incarnation AS process, host_scope AS host, endpoint_id AS endpoint, + endpoint_incarnation AS endpointProcess, ownership_state AS ownership + FROM worker_terminal_resources WHERE rowid IN ( + SELECT rowid FROM worker_terminal_resources WHERE terminal_handle IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM worker_terminal_resources WHERE pane_key IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM worker_terminal_resources WHERE pane_key IS NOT NULL AND ${REMOTE_ATTACHMENT_PANE_KEY_MATCH_SUFFIX_SQL} IN (SELECT value FROM json_each(?)) + UNION SELECT rowid FROM worker_terminal_resources WHERE owner_dispatch_id IN (SELECT value FROM json_each(?)))`) + .all(handles, paneKeys, leaves, JSON.stringify(claims.map((row) => row.id))) + ) + const creatorAssignments = readCrewAssignmentIds( + db, + creators.map((row) => row.id) + ) + return { claims, creators, resources, creatorAssignments } +} +export type CrewParentInputs = ReturnType & { + sourceFingerprint: string | null +} diff --git a/src/main/runtime/orchestration/crew/crew-parent-persistence.test.ts b/src/main/runtime/orchestration/crew/crew-parent-persistence.test.ts new file mode 100644 index 000000000000..a210c068cd70 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-parent-persistence.test.ts @@ -0,0 +1,76 @@ +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it } from 'vitest' +import { OrchestrationDb } from '../db' +import { ensureMutationReceiptCapacity } from '../mutation-receipt-capacity' +import { federatedStubHomeRunId } from '../db/contract-constants' +import { buildCrewSnapshot, CrewReadModel } from './crew-read-model' +import { subscribeCrew } from './crew-stream' +import { fixture } from './crew-read-model.test-fixture' + +it('reconstructs old-writer stub parents after real receipt pruning and reopen, and separates reset scopes', async () => { + const dir = mkdtempSync(join(tmpdir(), 'orca-crew-parent-')) + const path = join(dir, 'orchestration.db') + const { deps, handles } = fixture() + let db = new OrchestrationDb(path) + try { + // Supported rollback writer shape: empty home_run_id is repaired only by normal DB open. + db.db + .prepare(`INSERT INTO remote_dispatch_attachments + (dispatch_id, task_id, home_peer_fingerprint, runtime_epoch, terminal_handle, pane_key, process_incarnation, state) + VALUES (?, ?, ?, ?, ?, ?, ?, 'succeeded')`) + .run( + 'ctx_old_writer', + 'task_old', + 'home', + 'epoch', + 'term_worker', + handles.get('term_worker')!, + 'process_one' + ) + db.db + .prepare(`INSERT INTO mutation_receipts + (caller_fingerprint, request_id, method, payload_hash, state, updated_at) + VALUES ('home', 'old', 'orchestration.federationAttachStart', 'hash', 'completed', '2000-01-01')`) + .run() + ensureMutationReceiptCapacity(db.db) + expect(db.getMutationReceipt('home', 'old')).toBeUndefined() + db.close() + db = new OrchestrationDb(path) + deps.db = db + const stub = federatedStubHomeRunId('ctx_old_writer') + expect(db.getRunRaw(stub)?.home_database).toBe('remote') + const model = new CrewReadModel(() => deps, db.crewChanges.subscribe) + let current = buildCrewSnapshot('term_worker', deps) + const stop = subscribeCrew( + () => { + current = model.read('term_worker') + return current + }, + model.subscribe, + () => {} + ) + try { + const before = current.sections.managedBy + expect(before.map((row) => row.sendAddress)).toEqual([`run:${stub}`]) + db.resetMessages() + await Promise.resolve() + await Promise.resolve() + expect(current.sections.managedBy).toEqual(before) + db.resetTasks() + await Promise.resolve() + await Promise.resolve() + expect(current.sections.managedBy).toEqual([]) + db.resetAll() + await Promise.resolve() + await Promise.resolve() + expect(current.status).toBe('ok') + } finally { + stop() + } + } finally { + db.close() + rmSync(dir, { recursive: true, force: true }) + } +}) diff --git a/src/main/runtime/orchestration/crew/crew-parent-relations.test.ts b/src/main/runtime/orchestration/crew/crew-parent-relations.test.ts new file mode 100644 index 000000000000..4f178f6ccc23 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-parent-relations.test.ts @@ -0,0 +1,340 @@ +import { describe, expect, it, vi } from 'vitest' +import { buildCrewSnapshot, CrewReadModel } from './crew-read-model' +import { fixture } from './crew-read-model.test-fixture' +import { subscribeCrew } from './crew-stream' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../shared/protocol-version' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-freshness' +import { federatedStubHomeRunId } from '../db/contract-constants' +import { maximalCrewClaims } from './crew-claim-reduction' +import { isEquivalentPaneKey } from '../db/pane-key-match' + +describe('durable crew parents', () => { + it('composes incomparable local and remote claims through terminal outcomes without re-aging Managing', async () => { + const { db, deps, handles, assign } = fixture() + deps.processForHandle = () => 'process_one' + const local = assign('term_worker') + const now = Date.now() + db.completeDispatch(local.id) + db.db + .prepare('UPDATE dispatch_contexts SET completed_at = ? WHERE id = ?') + .run(new Date(now - AGENT_STATUS_STALE_AFTER_MS - 1).toISOString(), local.id) + const acquire = vi.fn(() => deps) + const model = new CrewReadModel(acquire, db.crewChanges.subscribe) + let current = buildCrewSnapshot('term_worker', deps) + const stop = subscribeCrew( + () => { + current = model.read('term_worker') + return current + }, + model.subscribe, + () => {} + ) + const attach = (id: string, home: string, runId?: string) => { + db.createRemoteDispatchAttachment({ + dispatchId: id, + runId, + taskId: `task_${id}`, + homePeerFingerprint: home, + runtimeEpoch: 'epoch', + protocolVersion: ORCHESTRATION_CONTRACT_VERSION, + mutationReceipt: { + callerFingerprint: home, + requestId: id, + method: 'orchestration.federationAttachStart', + payloadHash: id + } + }) + db.prepareRemoteAttachmentAuthority({ + dispatchId: id, + terminalHandle: 'term_worker', + paneKey: handles.get('term_worker')!, + processIncarnation: 'process_one', + worktreeId: 'wt', + setupState: 'not_applicable', + effects: [] + }) + } + attach('ctx_remote', 'home', 'run_home') + db.markRemoteAttachmentReady('ctx_remote') + await Promise.resolve() + await Promise.resolve() + const expected = [ + JSON.stringify(['test-host', 'term_coord']), + JSON.stringify(['home', 'run:run_home']) + ].sort() + expect(current.sections.managedBy.map((row) => row.partyKey).sort()).toEqual(expected) + expect(buildCrewSnapshot('term_coord', deps).sections.managing).toEqual([]) + db.beginRemoteAttachmentStop('ctx_remote') + db.markRemoteAttachmentStopUnknown('ctx_remote', 'Unknown stop') + await Promise.resolve() + await Promise.resolve() + expect(current.sections.managedBy.map((row) => row.partyKey).sort()).toEqual(expected) + db.recordRemoteAttachmentStage({ + dispatchId: 'ctx_remote', + stage: 'reconciled', + state: 'start_unknown' + }) + db.beginRemoteAttachmentStop('ctx_remote') + db.settleRemoteAttachmentStop('ctx_remote') + await Promise.resolve() + await Promise.resolve() + expect(current.sections.managedBy.map((row) => row.partyKey).sort()).toEqual(expected) + for (const state of [ + 'start_unknown', + 'stopping', + 'stop_unknown', + 'succeeded', + 'failed', + 'stopped', + 'abandoned' + ] as const) { + const before = acquire.mock.calls.length + db.recordRemoteAttachmentStage({ dispatchId: 'ctx_remote', stage: state, state }) + db.updateRemoteAttachmentSetupEvidence({ + dispatchId: 'ctx_remote', + setupState: 'late', + effects: [] + }) + await Promise.resolve() + await Promise.resolve() + expect(acquire).toHaveBeenCalledTimes(before + 1) + expect(current.sections.managedBy.map((row) => row.partyKey).sort()).toEqual(expected) + expect(buildCrewSnapshot('term_coord', deps).sections.managing).toEqual([]) + } + attach('ctx_legacy_remote', 'home') + db.failRemoteAttachment('ctx_legacy_remote', 'start', 'Failed', false) + const stub = federatedStubHomeRunId('ctx_legacy_remote') + expect(db.getRunRaw(stub)?.home_database).toBe('remote') + expect( + buildCrewSnapshot('term_worker', deps).sections.managedBy.map((row) => row.sendAddress) + ).toContain(`run:${stub}`) + db.recordRemoteAttachmentStage({ dispatchId: 'ctx_legacy_remote', stage: 'released' }) + deps.processForHandle = () => 'process_replaced' + db.crewChanges.notify() + await Promise.resolve() + await Promise.resolve() + expect(current.sections.managedBy.map((row) => row.sendAddress)).not.toContain('run:run_home') + stop() + }) + + it('hydrates retained creator IDs and reduces retries only after same-worker acquisition, then dedupes managers', () => { + const { db, deps, run, handles, assign } = fixture() + const creator = assign('term_helper', 'term_coord', 'Creator') + const child = assign('term_worker', 'term_helper') + db.completeDispatch(creator.id) + db.db + .prepare('UPDATE dispatch_contexts SET completed_at = ? WHERE id = ?') + .run('2000-01-01T00:00:00.000Z', creator.id) + expect(buildCrewSnapshot('term_worker', deps).sections.managedBy[0].sendAddress).toBe( + `dispatch:${creator.id}` + ) + db.failDispatch(child.id, 'retry') + db.updateTaskStatus(child.task_id, 'failed') + const retry = db.createStartingWorkerDispatch({ + taskId: child.task_id, + retryOf: child.id, + startOptions: {}, + creator: { kind: 'terminal', handle: 'term_peer', paneKey: handles.get('term_peer')! }, + maxDepth: 10 + }) + const before = buildCrewSnapshot('term_worker', deps).sections.managedBy + expect(before).toHaveLength(1) + db.prepareStartingWorkerAuthority({ + dispatchId: retry.dispatch.id, + handle: 'term_outbound', + paneKey: handles.get('term_outbound')!, + processIncarnation: 'different', + worktreeId: 'wt', + effects: [], + setupState: 'not_applicable' + }) + expect(buildCrewSnapshot('term_worker', deps).sections.managedBy).toEqual(before) + expect(db.getRunRaw(run.id)).toBeDefined() + }) +}) + +it('finds retained claims after pane moves and handle remint without merging a known replacement process', () => { + const { db, deps, handles, assign } = fixture() + handles.set('term_worker', 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb') + const claim = assign('term_worker') + db.completeDispatch(claim.id) + db.db + .prepare('UPDATE dispatch_contexts SET completed_at = ?, process_incarnation = ? WHERE id = ?') + .run('2000-01-01', 'process_one', claim.id) + const moved = handles.get('term_worker')!.replace('tab_worker:', 'tab_moved:') + handles.delete('term_worker') + handles.set('term_reminted', moved) + deps.handleForPane = (pane) => + [...handles].find(([, value]) => isEquivalentPaneKey(value, pane))?.[0] ?? null + deps.processForHandle = () => 'process_one' + expect( + buildCrewSnapshot('term_reminted', deps).sections.managedBy.map((row) => row.sendAddress) + ).toEqual(['term_coord']) + deps.processForHandle = () => 'process_two' + expect(buildCrewSnapshot('term_reminted', deps).sections.managedBy).toEqual([]) +}) + +it('reduces a validated same-worker retry before deduping managers with other surviving claims', () => { + const { db, deps, handles, run } = fixture() + deps.processForHandle = () => 'process_one' + const creator = (handle: string) => ({ + kind: 'terminal' as const, + handle, + paneKey: handles.get(handle)! + }) + const first = db.createStartingWorkerDispatch({ + taskSpec: 'Original', + taskRunId: run.id, + startOptions: {}, + runtimeEpoch: 'epoch', + creator: creator('term_coord'), + maxDepth: 10 + }) + const attach = (id: string, ownership?: 'created' | 'external') => + db.prepareStartingWorkerAuthority({ + dispatchId: id, + handle: 'term_worker', + paneKey: handles.get('term_worker')!, + processIncarnation: 'process_one', + worktreeId: 'wt', + setupState: 'not_applicable', + effects: [], + terminalOwnership: ownership + }) + attach(first.dispatch.id) + db.failWorkerStart(first.dispatch.id, 'boot', 'Failed') + const retry = db.createStartingWorkerDispatch({ + taskId: first.task.id, + retryOf: first.dispatch.id, + startOptions: {}, + runtimeEpoch: 'epoch', + creator: creator('term_peer'), + maxDepth: 10 + }) + expect( + buildCrewSnapshot('term_worker', deps).sections.managedBy.map((row) => row.partyKey) + ).toEqual([JSON.stringify(['test-host', 'term_coord'])]) + attach(retry.dispatch.id) + expect( + buildCrewSnapshot('term_worker', deps).sections.managedBy.map((row) => row.partyKey) + ).toEqual([JSON.stringify(['test-host', 'term_peer'])]) + db.markWorkerDispatchReady(retry.dispatch.id) + db.completeDispatch(retry.dispatch.id) + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'Independent' }).id, + assigneeHandle: 'term_worker', + assigneePaneKey: handles.get('term_worker')!, + processIncarnation: 'process_one', + creator: creator('term_coord'), + maxDepth: 10 + }) + expect( + buildCrewSnapshot('term_worker', deps).sections.managedBy.map((row) => row.partyKey) + ).toEqual(['term_coord', 'term_peer'].map((address) => JSON.stringify(['test-host', address]))) +}) + +it('uses an exact owned transfer chain and refuses external or corrupt history as replacement proof', () => { + for (const ownership of ['created', 'external'] as const) { + const { db, deps, handles, run } = fixture() + const start = (manager: string) => + db.createStartingWorkerDispatch({ + taskSpec: 'Transfer', + taskRunId: run.id, + startOptions: {}, + runtimeEpoch: 'epoch', + creator: { kind: 'terminal', handle: manager, paneKey: handles.get(manager)! }, + maxDepth: 10 + }) + const attach = (id: string, terminalOwnership: 'created' | 'external') => + db.prepareStartingWorkerAuthority({ + dispatchId: id, + handle: 'term_worker', + paneKey: handles.get('term_worker')!, + processIncarnation: 'process_one', + worktreeId: 'wt', + effects: [], + setupState: 'not_applicable', + terminalOwnership + }) + const first = start('term_coord') + attach(first.dispatch.id, ownership) + db.failWorkerStart(first.dispatch.id, 'boot', 'Failed') + const next = start('term_peer') + attach(next.dispatch.id, 'external') + const keys = () => + buildCrewSnapshot('term_worker', deps).sections.managedBy.map((row) => row.partyKey) + expect(keys()).toHaveLength(ownership === 'created' ? 1 : 2) + if (ownership === 'created') { + const resource = db.getWorkerTerminalResourceByOwner(next.dispatch.id)! + db.db + .prepare('UPDATE worker_terminal_resources SET prior_owner_dispatch_ids = ? WHERE id = ?') + .run(JSON.stringify(['ctx_missing', first.dispatch.id]), resource.id) + expect(keys()).toHaveLength(2) + } + } +}) + +it('retains every member of a corrupt replacement cycle even when one member has another successor', () => { + expect( + maximalCrewClaims( + ['a', 'b', 'c', 'd'], + new Map([ + ['a', new Set(['b'])], + ['b', new Set(['a', 'c'])], + ['d', new Set(['c'])] + ]) + ) + ).toEqual(new Set(['a', 'b', 'c'])) +}) + +it('collapses loopback representations only with existing source, worker, task and Run provenance', () => { + const { db, deps, run, handles } = fixture() + const home = db.getOrCreateLocalMutationCallerFingerprint() + const local = db.createStartingWorkerDispatch({ + taskRunId: run.id, + taskSpec: 'Loopback', + startOptions: {}, + runtimeEpoch: 'epoch', + creator: { kind: 'system' }, + maxDepth: 10 + }) + db.prepareStartingWorkerAuthority({ + dispatchId: local.dispatch.id, + handle: 'term_worker', + paneKey: handles.get('term_worker')!, + processIncarnation: 'process_one', + worktreeId: 'wt', + effects: [], + setupState: 'not_applicable' + }) + db.createRemoteDispatchAttachment({ + dispatchId: local.dispatch.id, + runId: run.id, + taskId: local.task.id, + homePeerFingerprint: home, + runtimeEpoch: 'epoch', + protocolVersion: ORCHESTRATION_CONTRACT_VERSION, + mutationReceipt: { + callerFingerprint: home, + requestId: 'loopback', + method: 'orchestration.federationAttachStart', + payloadHash: 'loopback' + } + }) + db.prepareRemoteAttachmentAuthority({ + dispatchId: local.dispatch.id, + terminalHandle: 'term_worker', + paneKey: handles.get('term_worker')!, + processIncarnation: 'process_one', + worktreeId: 'wt', + effects: [], + setupState: 'not_applicable' + }) + expect(buildCrewSnapshot('term_worker', deps).sections.managedBy).toHaveLength(1) + db.db + .prepare( + 'UPDATE remote_dispatch_attachments SET home_peer_fingerprint = ? WHERE dispatch_id = ?' + ) + .run('another-home', local.dispatch.id) + expect(buildCrewSnapshot('term_worker', deps).sections.managedBy).toHaveLength(2) +}) diff --git a/src/main/runtime/orchestration/crew/crew-parent-relations.ts b/src/main/runtime/orchestration/crew/crew-parent-relations.ts new file mode 100644 index 000000000000..9bb5d0570e49 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-parent-relations.ts @@ -0,0 +1,192 @@ +import { z } from 'zod' +import type { CrewAssignmentRow } from './crew-query' +import { maximalCrewClaims } from './crew-claim-reduction' +import { isEquivalentPaneKey } from '../db/pane-key-match' +import type { CrewParentClaim, CrewParentInputs } from './crew-parent-inputs' +import type { createCrewPartyRegistry, Party } from './crew-parties' +import type { CrewReadDependencies } from './crew-read-model' + +type Registry = ReturnType +export type CrewParentRelation = { + parent: Party + address: string + key: string + assignment?: CrewAssignmentRow +} +const claimKey = (row: CrewParentClaim) => JSON.stringify([row.family, row.home, row.id]) + +function sameWorker(a: CrewParentClaim, b: CrewParentClaim, registry: Registry): boolean { + if (a.session && b.session) { + const identity = registry.addressOf(`orca_session_id:${a.session}`) + return Boolean(identity && identity === registry.addressOf(`orca_session_id:${b.session}`)) + } + return Boolean( + a.process && + a.process === b.process && + (a.host === b.host || + ((a.family === 'remote' || b.family === 'remote') && + a.endpoint && + a.endpoint === b.endpoint)) && + a.pane && + b.pane && + isEquivalentPaneKey(a.pane, b.pane) + ) +} + +/** Only retained causal edges order claims; birth, status and metadata clocks cannot do so. */ +export function crewParentRelations( + inputs: CrewParentInputs, + self: Party, + registry: Registry, + deps: CrewReadDependencies +): CrewParentRelation[] { + const bound = (row: CrewParentClaim) => { + if (!row.session && !row.handle && !row.pane) { + return false + } + const currentProcess = self.terminalHandle ? deps.processForHandle?.(self.terminalHandle) : null + if (currentProcess && row.process && currentProcess !== row.process) { + return false + } + if (row.session) { + return registry.addressOf(`orca_session_id:${row.session}`) === self.address + } + return Boolean( + (row.handle && registry.addressOf(row.handle) === self.address) || + (row.pane && self.paneKey && isEquivalentPaneKey(row.pane, self.paneKey)) + ) + } + const boundClaims = inputs.claims.filter(bound) + const localRepresentations = new Map( + boundClaims.filter((row) => row.family === 'local').map((row) => [row.id, row]) + ) + const claims = boundClaims.filter((row) => { + const local = localRepresentations.get(row.id) + return !( + row.family === 'remote' && + local && + inputs.sourceFingerprint && + row.home === inputs.sourceFingerprint && + local.runHome !== 'remote' && + local.run === row.run && + local.task === row.task && + sameWorker(local, row, registry) && + (!local.endpoint || !row.endpoint || local.endpoint === row.endpoint) + ) + }) + const byId = new Map() + for (const row of claims) { + const group = byId.get(row.id) ?? [] + group.push(row) + byId.set(row.id, group) + } + const successors = new Map>() + const edge = (a: CrewParentClaim, b: CrewParentClaim) => { + if (claimKey(a) === claimKey(b) || !sameWorker(a, b, registry)) { + return + } + const next = successors.get(claimKey(a)) ?? new Set() + next.add(claimKey(b)) + successors.set(claimKey(a), next) + } + for (const row of claims) { + if (row.family === 'local' && row.retry) { + for (const prior of byId.get(row.retry) ?? []) { + if (prior.family === 'local' && prior.task === row.task && prior.run === row.run) { + edge(prior, row) + } + } + } + } + for (const resource of inputs.resources) { + const prior = z.array(z.string()).safeParse( + (() => { + try { + return JSON.parse(resource.prior) + } catch { + return null + } + })() + ) + if ( + !prior.success || + resource.ownership === 'external' || + !resource.process || + !resource.pane || + resource.endpointProcess !== resource.process || + prior.data[0] !== resource.origin || + new Set([...prior.data, resource.owner]).size !== prior.data.length + 1 + ) { + continue + } + const chain = [...prior.data, resource.owner].map((id) => byId.get(id) ?? []) + if (chain.some((group) => group.length !== 1)) { + continue + } + const rows = chain.flat() + const owner = rows.at(-1)! + if ( + owner.endpoint !== resource.endpoint || + rows.some( + (row) => + row.process !== resource.process || + (row.host !== resource.host && + !(row.family === 'remote' && row.endpoint && row.endpoint === resource.endpoint)) || + !row.pane || + !isEquivalentPaneKey(row.pane, resource.pane!) + ) + ) { + continue + } + for (let i = 1; i < rows.length; i++) { + edge(rows[i - 1], rows[i]) + } + } + const maximalKeys = maximalCrewClaims(claims.map(claimKey), successors) + const maximal = claims.filter((row) => maximalKeys.has(claimKey(row))) + const creators = new Map(inputs.creators.map((row) => [row.id, row])) + const creatorAssignments = new Map(inputs.creatorAssignments.map((row) => [row.id, row])) + const managers = new Map() + for (const row of maximal.sort((a, b) => claimKey(a).localeCompare(claimKey(b)))) { + if (row.family === 'remote') { + const address = `run:${row.run}` + const parent: Party = { address, terminalHandle: null, orcaSessionId: null, paneKey: null } + const key = JSON.stringify([row.home, address]) + managers.set(key, { parent, address, key }) + continue + } + const creator = row.creator ? creators.get(row.creator) : undefined + const parent = + (creator + ? registry.party( + creator.session, + creator.handle, + creator.pane, + `dispatch:${creator.id}`, + creator.process + ) + : undefined) ?? registry.party(row.creatorSession, row.creatorHandle, row.creatorPane) + const coordinator = registry.party( + row.coordinatorSession, + row.coordinator, + row.coordinatorPane, + `run:${row.run}` + ) + const chosen = parent?.address !== self.address ? (parent ?? coordinator) : coordinator + if (!chosen || chosen.address === self.address) { + continue + } + const address = + chosen === parent ? (creator ? `dispatch:${creator.id}` : chosen.address) : `run:${row.run}` + const key = JSON.stringify([deps.hostKey, chosen.address]) + if (!managers.has(key)) { + managers.set(key, { + parent: chosen, + address, + key, + assignment: creator && chosen === parent ? creatorAssignments.get(creator.id) : undefined + }) + } + } + return [...managers.values()].sort((a, b) => a.key.localeCompare(b.key)) +} diff --git a/src/main/runtime/orchestration/crew/crew-parent-rpc.test.ts b/src/main/runtime/orchestration/crew/crew-parent-rpc.test.ts new file mode 100644 index 000000000000..09e15fbcd1b5 --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-parent-rpc.test.ts @@ -0,0 +1,126 @@ +import '../../rpc/unused-default-rpc-methods.test-fixture' +import { afterEach, expect, it, vi } from 'vitest' +import { z } from 'zod' +import { dispatch } from '../../../../cli/dispatch' +import { RuntimeClient, RuntimeClientError } from '../../../../cli/runtime-client' +import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../shared/protocol-version' +import { + createSessionCallerHarness, + orchestrationRequest +} from '../../rpc/orchestration-session-caller-test-fixture' +import { configureFederationWorkerRuntime } from '../../rpc/methods/orchestration/federation/federation-runtime.test-support' +import { buildCrewSnapshot } from './crew-read-model' + +const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) +vi.mock('../../../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), + name: () => 'Manager' + } + const parents = buildCrewSnapshot(handle, deps).sections.managedBy + expect(parents.map((row) => row.sendAddress).sort()).toEqual( + ['term_coord', 'run:run_remote_home'].sort() + ) + expect( + parents.find((row) => row.sendAddress === 'run:run_remote_home')?.openTarget + ).toBeUndefined() + 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) + } + // SAFETY: the real dispatcher validates the result; only the in-memory CLI transport is substituted. + return { + ...response, + result: response.result as T, + _meta: { runtimeId: 'crew-parent-test' } + } + }) + 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([]) + } finally { + h.close() + } + } +}) diff --git a/src/main/runtime/orchestration/crew/crew-parties.ts b/src/main/runtime/orchestration/crew/crew-parties.ts index 86203f187c86..2e106ab3e9cd 100644 --- a/src/main/runtime/orchestration/crew/crew-parties.ts +++ b/src/main/runtime/orchestration/crew/crew-parties.ts @@ -85,12 +85,16 @@ export function createCrewPartyRegistry(deps: CrewReadDependencies) { session: string | null, storedHandle: string | null, pane: string | null, - fallback?: string + fallback?: string, + process?: string | null ): Party | undefined => { const sessionId = session ? root(session) : null const liveHandle = pane ? deps.handleForPane(pane) : null - const handle = + const candidateHandle = liveHandle ?? (storedHandle && deps.liveHandle(storedHandle) ? storedHandle : null) + const currentProcess = candidateHandle ? deps.processForHandle?.(candidateHandle) : null + const mismatch = Boolean(process && currentProcess && process !== currentProcess) + const handle = mismatch ? null : candidateHandle const publicHandle = handle?.startsWith('term_') ? handle : null const publicAddress = sessionId && isOrcaSessionId(sessionId) @@ -113,7 +117,7 @@ export function createCrewPartyRegistry(deps: CrewReadDependencies) { for (const alias of [ publicAddress, ...(sessionId ? (lineageAliases.get(sessionId) ?? []) : []), - storedHandle, + mismatch ? null : storedHandle, handle, session && isOrcaSessionId(session) ? formatOrcaSessionAddress(session) : null ]) { diff --git a/src/main/runtime/orchestration/crew/crew-party-snapshot.ts b/src/main/runtime/orchestration/crew/crew-party-snapshot.ts index afc2bb8b8364..e485aedc6173 100644 --- a/src/main/runtime/orchestration/crew/crew-party-snapshot.ts +++ b/src/main/runtime/orchestration/crew/crew-party-snapshot.ts @@ -15,15 +15,14 @@ import { } from '../structured-session-lineage' import { crewDisplayName, crewTaskDisplay } from './crew-rules' import { - readCrewProvenance, readCrewOwnedRunAddresses, readCrewQuestions, - readCrewRuns, readCrewTraffic, type CrewAssignmentRow } from './crew-query' import type { Party } from './crew-parties' +import { crewParentRelations } from './crew-parent-relations' import { createCrewHostDerivation } from './crew-host-derivation' import { statusForFleetWorker } from '../../../../shared/orchestration-fleet-status-index' import { projectLiveness } from '../../../../shared/orchestration-fleet-worker-projection' @@ -40,6 +39,7 @@ export type CrewReadDependencies = { taskName: string | null, records: AgentSessionRecordReader | null ) => string | null + processForHandle?: (handle: string) => string | null statuses: readonly FleetAgentStatusEvidence[] now?: number } @@ -59,6 +59,7 @@ export function buildCrewSnapshot( deps: CrewReadDependencies, host = createCrewHostDerivation(deps, deps.now ?? Date.now()) ): OrchestrationCrewSnapshot { + deps = { ...host.deps, now: deps.now } const db = deps.db if (!db) { return emptyCrew(deps.retainedDbExists ? 'unknown' : 'ok') @@ -69,10 +70,10 @@ export function buildCrewSnapshot( const { party, alias, addressOf, getParty, aliasesFor } = registry const records = host.deps.records const hydrate = (addresses: string[], panes: string[] = []) => { - const provenance = readCrewProvenance(db, addresses, panes) + const provenance = host.sourceInputs.provenance(addresses, panes) for (const family of [provenance.local, provenance.remote]) { for (const row of family) { - const worker = party(row.session, row.handle, row.pane, `dispatch:${row.id}`) + const worker = party(row.session, row.handle, row.pane, `dispatch:${row.id}`, row.process) if (worker) { alias(`dispatch:${row.id}`, worker.address) } @@ -92,7 +93,7 @@ export function buildCrewSnapshot( hydrate(aliasesFor(self.address), self.paneKey ? [self.paneKey] : []) self = getParty(addressOf(self.address) ?? self.address) ?? self const ownedRunAddresses = readCrewOwnedRunAddresses(db, self) - for (const current of readCrewRuns(db, ownedRunAddresses)) { + for (const current of host.sourceInputs.runInputs(ownedRunAddresses)) { const coordinator = party(current.session, current.handle, current.pane, `run:${current.id}`) if (coordinator) { alias(`run:${current.id}`, coordinator.address) @@ -101,10 +102,7 @@ export function buildCrewSnapshot( const selfAliases = () => aliasesFor(self.address) const traffic = readCrewTraffic(db, selfAliases(), cutoff) hydrate(traffic.map((message) => message.peer)) - for (const run of readCrewRuns( - db, - traffic.map((message) => message.peer) - )) { + for (const run of host.sourceInputs.runInputs(traffic.map((message) => message.peer))) { const coordinator = party(run.session, run.handle, run.pane, `run:${run.id}`) if (coordinator) { alias(`run:${run.id}`, coordinator.address) @@ -182,17 +180,19 @@ export function buildCrewSnapshot( return row } const snapshot = emptyCrew('ok') - for (const { assignment, worker, parent, parentAssignment, parentAddress } of host.relations.get( - self.address - ) ?? []) { + for (const { assignment, worker, parent } of host.relations.get(self.address) ?? []) { if (parent.address === self.address) { snapshot.sections.managing.push( decorate(worker, 'worker', assignment, `dispatch:${assignment.id}`) ) - } else if (!rows.has(parent.address)) { - snapshot.sections.managedBy.push(decorate(parent, 'manager', parentAssignment, parentAddress)) } } + const parents = host.sourceInputs.parentInputs(selfAliases(), self.paneKey ? [self.paneKey] : []) + for (const relation of crewParentRelations(parents, self, registry, deps)) { + const row = decorate(relation.parent, 'manager', relation.assignment, relation.address) + row.partyKey = relation.key + snapshot.sections.managedBy.push(row) + } for (const message of traffic) { let targetAddress = addressOf(message.peer) if (!targetAddress) { diff --git a/src/main/runtime/orchestration/crew/crew-query.ts b/src/main/runtime/orchestration/crew/crew-query.ts index 79bdcb420f3d..28b74c217869 100644 --- a/src/main/runtime/orchestration/crew/crew-query.ts +++ b/src/main/runtime/orchestration/crew/crew-query.ts @@ -28,6 +28,7 @@ export const CrewAssignment = z.object({ stage: nullable, agent: nullable, host_label: nullable, + assignee_process: nullable, resource_incarnation: nullable, resource_host_scope: nullable }) @@ -39,7 +40,7 @@ const assignmentColumns = `d.rowid AS ordinal, d.id, d.run_id, d.task_id, d.status, d.completed_at, t.spec, t.task_title, t.display_name, t.status AS task_status, r.coordinator_handle, r.coordinator_pane_key, ${currentRunCoordinatorOrcaSessionIdSql('r')} AS coordinator_session, - w.stage, json_extract(w.start_options, '$.agent') AS agent, f.environment_name AS host_label, resource.process_incarnation AS resource_incarnation, + d.process_incarnation AS assignee_process, w.stage, json_extract(w.start_options, '$.agent') AS agent, f.environment_name AS host_label, resource.process_incarnation AS resource_incarnation, resource.host_scope AS resource_host_scope` const assignmentJoins = `JOIN tasks t ON t.id = d.task_id JOIN runs r ON r.id = d.run_id LEFT JOIN worker_dispatches w ON w.dispatch_id = d.id @@ -69,50 +70,17 @@ export function readCrewAssignments(db: OrchestrationDb, now: number): CrewAssig ) } -const Provenance = z.object({ - id: z.string(), - handle: nullable, - pane: nullable, - session: nullable -}) - -/** Retained aliases are narrow provenance, never eligible relationship membership. */ -export function readCrewProvenance(db: OrchestrationDb, addresses: string[], panes: string[] = []) { - const handles = JSON.stringify(addresses.filter((address) => address.startsWith('term_'))) - const sessions = JSON.stringify( - addresses - .filter((address) => address.startsWith('orca_session_id:')) - .map((address) => address.slice('orca_session_id:'.length)) - ) - const ids = JSON.stringify( - addresses - .filter((address) => address.startsWith('dispatch:')) - .map((address) => address.slice(9)) - ) - const local = Provenance.array().parse( - db.db - .prepare(`SELECT d.id, d.assignee_handle AS handle, - d.assignee_pane_key AS pane, d.assignee_orca_session_id AS session - FROM dispatch_contexts d WHERE d.rowid IN ( - SELECT rowid FROM dispatch_contexts WHERE assignee_handle IN (SELECT value FROM json_each(?)) - UNION SELECT rowid FROM dispatch_contexts WHERE assignee_orca_session_id IN (SELECT value FROM json_each(?)) - UNION SELECT rowid FROM dispatch_contexts WHERE assignee_pane_key IN (SELECT value FROM json_each(?)) - UNION SELECT rowid FROM dispatch_contexts WHERE id IN (SELECT value FROM json_each(?))) - ORDER BY d.rowid DESC`) - .all(handles, sessions, JSON.stringify(panes), ids) - ) - const remote = Provenance.array().parse( +export function readCrewAssignmentIds(db: OrchestrationDb, ids: string[]): CrewAssignmentRow[] { + if (!ids.length) { + return [] + } + return CrewAssignment.array().parse( db.db - .prepare(`SELECT dispatch_id AS id, - terminal_handle AS handle, pane_key AS pane, NULL AS session - FROM remote_dispatch_attachments WHERE rowid IN ( - SELECT rowid FROM remote_dispatch_attachments WHERE terminal_handle IN (SELECT value FROM json_each(?)) - UNION SELECT rowid FROM remote_dispatch_attachments WHERE pane_key IN (SELECT value FROM json_each(?)) - UNION SELECT rowid FROM remote_dispatch_attachments WHERE dispatch_id IN (SELECT value FROM json_each(?))) - ORDER BY rowid DESC`) - .all(handles, JSON.stringify(panes), ids) + .prepare(`SELECT ${assignmentColumns} + FROM dispatch_contexts d ${assignmentJoins} + WHERE d.id IN (SELECT value FROM json_each(?))`) + .all(JSON.stringify(ids)) ) - return { local, remote } } const Traffic = z.object({ diff --git a/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts b/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts index 4a6808dbba85..7110a734ef14 100644 --- a/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts +++ b/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts @@ -1,4 +1,5 @@ -import { readCrewTraffic, readCrewProvenance } from './crew-query' +import { readCrewTraffic } from './crew-query' +import { readCrewParentInputs } from './crew-parent-inputs' import type { AgentStatusIpcPayload } from '../../../../shared/agent-status-ipc-payload' import { RuntimeAgentOrchestrationProjection } from '../../runtime-agent-orchestration-projection' @@ -215,14 +216,15 @@ it('counts the real status qualification/projection SQL on a decoration wake wit tabsByWorktree: { folder: [{ id: 'tab_worker', title, customTitle: null }] } }), getGeneratedTitlesEnabled: () => true, + getAgentStatusSnapshot: () => raw, getAgentStatusSnapshotForPane: (pane) => raw.filter((row) => row.paneKey === pane), getTrackedTitle: () => null }) - deps.name = (party, task, records) => names.nameOf(party, undefined, task, records) const wake = new CrewChanges() const model = new CrewReadModel( () => ({ ...deps, + name: names.captureCrewInputs(), get statuses() { return acquireStatus() } @@ -279,6 +281,7 @@ it('counts the real status qualification/projection SQL on a decoration wake wit expect(listRecords).not.toHaveBeenCalled() expect(executed.get).toBeGreaterThan(population * 2) expect(sql.some((text) => text.includes('attempt_observation_facts'))).toBe(true) + expect(sql.some((text) => text.includes('retry_of_dispatch_id AS retry'))).toBe(false) expect(model.read('term_coord').sections.managing[0].status).toBe('waiting') measurements.push({ population, ...executed }) acquireStatus.mockClear() @@ -288,6 +291,7 @@ it('counts the real status qualification/projection SQL on a decoration wake wit expect(acquireStatus).not.toHaveBeenCalled() expect(globalSelection).not.toHaveBeenCalled() expect(model.read('term_coord').sections.managing[0].label).toBe(title) + expect(sql.some((text) => text.includes('retry_of_dispatch_id AS retry'))).toBe(false) for (const stop of streams) { stop() } @@ -300,7 +304,8 @@ it('counts the real status qualification/projection SQL on a decoration wake wit console.log('crew actual status operation contract', JSON.stringify(measurements)) }) it('selects peer maxima without losing bodies and uses indexed historical provenance', () => { - const { db, run, assign } = fixture() + const { db, run, assign, handles } = fixture() + handles.set('term_worker', 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb') assign('term_worker') db.insertMessage({ runId: run.id, @@ -336,12 +341,11 @@ it('selects peer maxima without losing bodies and uses indexed historical proven expect(traffic).toMatchObject([ { peer: 'term_worker', direction: 'from', sequence: winner.sequence, body: 'latest' } ]) - const provenance = readCrewProvenance( - db, - ['term_worker'], - ['tab_worker:aaaaaaaa-aaaa-4aaa-8aaa-workeraaaaaa'] - ) - expect(provenance.local).toHaveLength(1) + const provenance = readCrewParentInputs(db, ['term_worker'], [handles.get('term_worker')!]) + expect(provenance.claims.filter((row) => row.family === 'local')).toHaveLength(1) + expect(JSON.stringify(plans)).toContain('idx_crew_dispatch_leaf') + expect(JSON.stringify(plans)).toContain('idx_crew_remote_leaf') + expect(JSON.stringify(plans)).toContain('idx_crew_resource_leaf') const plan = JSON.stringify(plans) expect(plan).toContain('idx_messages_crew_from') expect(plan).toContain('idx_messages_crew_to') diff --git a/src/main/runtime/orchestration/crew/crew-read-model.ts b/src/main/runtime/orchestration/crew/crew-read-model.ts index 3d31956522ae..3f68801c5145 100644 --- a/src/main/runtime/orchestration/crew/crew-read-model.ts +++ b/src/main/runtime/orchestration/crew/crew-read-model.ts @@ -1,3 +1,4 @@ +import { isDeepStrictEqual } from 'node:util' import type { CrewFacet, CrewInvalidation } from './crew-changes' import { buildCrewSnapshot, type CrewReadDependencies } from './crew-party-snapshot' import type { OrchestrationCrewSnapshot } from '../../../../shared/orchestration-crew' @@ -73,7 +74,16 @@ export class CrewReadModel { const previous = this.host this.host = undefined const deps = this.readDependencies() - this.host = dirty.has('status') ? refreshCrewStatuses(previous, deps.statuses) : previous + if (dirty.has('status')) { + const statuses = deps.statuses + const identities = (rows: typeof statuses) => + new Map(rows.map((row) => [row.activity.paneKey, row.binding])) + this.host = isDeepStrictEqual(identities(previous.deps.statuses), identities(statuses)) + ? refreshCrewStatuses(previous, statuses) + : createCrewHostDerivation({ ...deps, statuses }, now) + } else { + this.host = previous + } let records = this.host.deps.records if (renamed.size && records) { const captured = new Map(records.listRecords().map((record) => [record.sessionId, record])) diff --git a/src/main/runtime/orchestration/crew/crew-runtime-watch.ts b/src/main/runtime/orchestration/crew/crew-runtime-watch.ts index 3804431414b2..e97082f0c8cc 100644 --- a/src/main/runtime/orchestration/crew/crew-runtime-watch.ts +++ b/src/main/runtime/orchestration/crew/crew-runtime-watch.ts @@ -61,6 +61,7 @@ export function readCrewRuntimeInputs( runtime: Pick< OrcaRuntimeService, | 'getTerminalWorktreeIdForHandle' + | 'getTerminalProcessIncarnation' | 'getTerminalHandleForPaneKey' | 'getPaneKeyForTerminalHandle' | 'getOrchestrationFleetAgentStatusSnapshot' @@ -76,11 +77,11 @@ export function readCrewRuntimeInputs( retainedDbExists, hostKey, records: store ? conversationRecordReader(store) : null, + processForHandle: (handle) => runtime.getTerminalProcessIncarnation(handle), liveHandle: (handle) => runtime.getTerminalWorktreeIdForHandle(handle) !== null, handleForPane: (pane) => runtime.getTerminalHandleForPaneKey(pane), paneForHandle: (handle) => runtime.getPaneKeyForTerminalHandle(handle), - name: (identity, taskName, records) => - runtime.orchestrationSenderNames.nameOf(identity, undefined, taskName, records), + name: runtime.orchestrationSenderNames.captureCrewInputs(), get statuses() { return runtime.getOrchestrationFleetAgentStatusSnapshot() } diff --git a/src/main/runtime/orchestration/crew/crew-source-inputs.ts b/src/main/runtime/orchestration/crew/crew-source-inputs.ts new file mode 100644 index 000000000000..2e8ed6db739a --- /dev/null +++ b/src/main/runtime/orchestration/crew/crew-source-inputs.ts @@ -0,0 +1,139 @@ +import { z } from 'zod' +import type { OrchestrationDb } from '../db' +import { + readCrewParentInputs, + type CrewParentClaim, + type CrewParentResource +} from './crew-parent-inputs' +import { readCrewRuns, type CrewAssignmentRow } from './crew-query' +import { parsePaneKey } from '../../../../shared/stable-pane-id' +import { paneKeyMatchSuffix } from '../db/pane-key-match' + +type ProvenanceRow = Pick +type Provenance = { local: ProvenanceRow[]; remote: ProvenanceRow[] } +type Run = ReturnType[number] + +/** Disposable host input indexes contain source facts, never projected parties or selected parents. */ +export function createCrewSourceInputs(db: OrchestrationDb | null) { + const sourceFingerprint = + z + .object({ caller_fingerprint: z.string() }) + .optional() + .parse( + db?.db + .prepare( + "SELECT caller_fingerprint FROM mutation_caller_identities WHERE transport = 'local_authenticated_transport'" + ) + .get() + )?.caller_fingerprint ?? null + const claims = new Map() + const claimsByKey = new Map>() + const creators = new Map() + const creatorAssignments = new Map() + const resources = new Map() + const resourcesByKey = new Map>() + const covered = new Set() + const runs = new Map() + const knownRuns = new Set() + const index = (map: Map>, key: string | null, id: string) => { + if (!key) { + return + } + const ids = map.get(key) ?? new Set() + ids.add(id) + map.set(key, ids) + } + const parentInputs = (addresses: string[], panes: string[] = []) => { + const paneKey = (pane: string) => + parsePaneKey(pane) ? `leaf:${paneKeyMatchSuffix(pane)}` : `pane:${pane}` + const keys = [...addresses, ...panes.map(paneKey)] + const missing = keys.filter((key) => !covered.has(key)) + if (db && missing.length) { + const input = readCrewParentInputs( + db, + addresses.filter((key) => !covered.has(key)), + panes.filter((pane) => !covered.has(paneKey(pane))) + ) + for (const row of input.claims) { + const id = JSON.stringify([row.family, row.home, row.id]) + claims.set(id, Object.freeze(row)) + for (const key of [ + row.handle, + row.pane ? paneKey(row.pane) : null, + row.session ? `orca_session_id:${row.session}` : null, + `dispatch:${row.id}` + ]) { + index(claimsByKey, key, id) + } + } + for (const row of input.creators) { + creators.set(row.id, Object.freeze(row)) + } + for (const row of input.creatorAssignments) { + creatorAssignments.set(row.id, Object.freeze(row)) + } + for (const row of input.resources) { + resources.set(row.id, Object.freeze(row)) + for (const key of [ + row.handle, + row.pane ? paneKey(row.pane) : null, + `dispatch:${row.owner}` + ]) { + index(resourcesByKey, key, row.id) + } + } + for (const key of missing) { + covered.add(key) + } + } + const ids = new Set(keys.flatMap((key) => [...(claimsByKey.get(key) ?? [])])) + const selected = [...ids].map((id) => claims.get(id)!) + const resourceIds = new Set( + [...keys, ...selected.map((row) => `dispatch:${row.id}`)].flatMap((key) => [ + ...(resourcesByKey.get(key) ?? []) + ]) + ) + return { + claims: selected, + sourceFingerprint, + creatorAssignments: selected.flatMap((row) => + row.creator && creatorAssignments.has(row.creator) + ? [creatorAssignments.get(row.creator)!] + : [] + ), + creators: selected.flatMap((row) => + row.creator && creators.has(row.creator) ? [creators.get(row.creator)!] : [] + ), + resources: [...resourceIds].map((id) => resources.get(id)!) + } + } + const provenance = (addresses: string[], panes: string[] = []): Provenance => { + const input = parentInputs(addresses, panes) + const rows = (family: CrewParentClaim['family']) => + input.claims + .filter((row) => row.family === family) + .map((row) => ({ + id: row.id, + handle: row.handle, + pane: row.pane, + session: row.session, + process: row.process + })) + return { local: rows('local'), remote: rows('remote') } + } + const runInputs = (addresses: string[]) => { + const missing = addresses.filter( + (address) => address.startsWith('run:') && !knownRuns.has(address) + ) + if (db && missing.length) { + for (const row of readCrewRuns(db, missing)) { + runs.set(`run:${row.id}`, Object.freeze(row)) + } + for (const address of missing) { + knownRuns.add(address) + } + } + return addresses.flatMap((address) => (runs.has(address) ? [runs.get(address)!] : [])) + } + return { parentInputs, provenance, runInputs } +} diff --git a/src/main/runtime/orchestration/db/schema/schema-column-probes.ts b/src/main/runtime/orchestration/db/schema/schema-column-probes.ts index dee28e5a33b0..8f306e47bc5d 100644 --- a/src/main/runtime/orchestration/db/schema/schema-column-probes.ts +++ b/src/main/runtime/orchestration/db/schema/schema-column-probes.ts @@ -1,5 +1,9 @@ import type { OrchestrationDb } from '../orchestration-db' import { OUTSTANDING_MAILBOX_INDEX_SQL } from './migrate-v41' +import { + DISPATCH_PANE_KEY_MATCH_SUFFIX_SQL, + REMOTE_ATTACHMENT_PANE_KEY_MATCH_SUFFIX_SQL +} from '../pane-key-match' export function hasColumn(this: OrchestrationDb, table: string, column: string): boolean { const rows = this.db.pragma(`table_info(${table})`) as { name: string }[] @@ -32,14 +36,21 @@ export function createMailboxDeliveryIndexesIfPossible(this: OrchestrationDb): v } if (this.hasColumn('dispatch_contexts', 'assignee_pane_key')) { this.db.exec(`CREATE INDEX IF NOT EXISTS idx_crew_dispatch_pane - ON dispatch_contexts(assignee_pane_key) WHERE assignee_pane_key IS NOT NULL`) + ON dispatch_contexts(assignee_pane_key) WHERE assignee_pane_key IS NOT NULL; + CREATE INDEX IF NOT EXISTS idx_crew_dispatch_leaf + ON dispatch_contexts(${DISPATCH_PANE_KEY_MATCH_SUFFIX_SQL}) WHERE assignee_pane_key IS NOT NULL`) } if (this.hasColumn('remote_dispatch_attachments', 'terminal_handle')) { this.db.exec(` CREATE INDEX IF NOT EXISTS idx_crew_remote_handle ON remote_dispatch_attachments(terminal_handle); CREATE INDEX IF NOT EXISTS idx_crew_remote_pane ON remote_dispatch_attachments(pane_key); + CREATE INDEX IF NOT EXISTS idx_crew_remote_leaf ON remote_dispatch_attachments(${REMOTE_ATTACHMENT_PANE_KEY_MATCH_SUFFIX_SQL}) WHERE pane_key IS NOT NULL; `) } + if (this.hasColumn('worker_terminal_resources', 'pane_key')) { + this.db.exec(`CREATE INDEX IF NOT EXISTS idx_crew_resource_leaf + ON worker_terminal_resources(${REMOTE_ATTACHMENT_PANE_KEY_MATCH_SUFFIX_SQL}) WHERE pane_key IS NOT NULL`) + } if (this.hasColumn('question_threads', 'status')) { this.db.exec(`CREATE INDEX IF NOT EXISTS idx_crew_pending_questions ON question_threads(message_id) WHERE status = 'pending'`) diff --git a/src/main/runtime/runtime-orchestration-crew-names.test.ts b/src/main/runtime/runtime-orchestration-crew-names.test.ts new file mode 100644 index 000000000000..7ddb51242814 --- /dev/null +++ b/src/main/runtime/runtime-orchestration-crew-names.test.ts @@ -0,0 +1,83 @@ +import { expect, it, vi } from 'vitest' +import { RuntimeOrchestrationSenderNames } from './runtime-orchestration-sender-names' + +type NamingDeps = ConstructorParameters[0] +type Session = NonNullable> + +it('captures actual raw naming reads once at N/10N and preserves naming precedence across consumers', () => { + for (const population of [3, 30]) { + const handles = Array.from({ length: population }, (_, i) => `term_${i}`) + const session: Session = { + tabsByWorktree: { + workspace: handles.map((handle) => ({ + id: `tab_${handle}`, + title: `Generated ${handle}`, + customTitle: `Named ${handle}` + })) + } + } + const deps: NamingDeps = { + getDb: vi.fn(() => null), + getWorkspaceSession: vi.fn(() => session), + getGeneratedTitlesEnabled: vi.fn(() => true), + getHandleRecord: vi.fn((handle) => ({ + worktreeId: 'workspace', + tabId: `tab_${handle}`, + ptyId: handle + })), + getPtyAgents: vi.fn(() => ({ launchAgent: 'codex' })), + getTerminalPaneKey: vi.fn((handle) => `tab_${handle}:leaf`), + getAgentStatusSnapshot: vi.fn(() => + handles.map((handle) => ({ + paneKey: `tab_${handle}:leaf`, + worktreeId: 'workspace', + agentType: 'codex' as const, + receivedAt: 1 + })) + ), + getAgentStatusSnapshotForPane: vi.fn(() => []), + getTrackedTitle: vi.fn(() => null) + } + const names = new RuntimeOrchestrationSenderNames(deps) + const parties = handles.map((handle) => ({ + address: handle, + terminalHandle: handle, + orcaSessionId: null + })) + const expected = parties.map((party) => names.nameOf(party, undefined, 'Task', null)) + for (const read of Object.values(deps)) { + vi.mocked(read).mockClear() + } + const captured = names.captureCrewInputs() + for (let consumer = 0; consumer < population; consumer++) { + expect(parties.map((party) => captured(party, 'Task', null))).toEqual(expected) + } + expect(deps.getWorkspaceSession).toHaveBeenCalledTimes(1) + expect(deps.getAgentStatusSnapshot).toHaveBeenCalledTimes(1) + expect(deps.getAgentStatusSnapshotForPane).not.toHaveBeenCalled() + for (const read of [ + deps.getHandleRecord, + deps.getPtyAgents, + deps.getTerminalPaneKey, + deps.getTrackedTitle + ]) { + expect(read).toHaveBeenCalledTimes(population) + } + session.tabsByWorktree = { workspace: [{ id: 'tab_term_0', customTitle: 'Changed' }] } + expect(captured(parties[0], 'Task', null)).toBe(expected[0]) + expect(names.captureCrewInputs()(parties[0], 'Task', null)).toBe('Changed') + console.log( + 'crew raw naming operations', + JSON.stringify({ + population, + consumers: population, + workspace: 1, + hookSnapshots: 1, + handles: population, + ptys: population, + panes: population, + titles: population + }) + ) + } +}) diff --git a/src/main/runtime/runtime-orchestration-sender-names.test.ts b/src/main/runtime/runtime-orchestration-sender-names.test.ts index 835f9c5e67f0..d008a6b99f5a 100644 --- a/src/main/runtime/runtime-orchestration-sender-names.test.ts +++ b/src/main/runtime/runtime-orchestration-sender-names.test.ts @@ -30,7 +30,7 @@ type Session = NonNullable< > > type SenderNamingDeps = ConstructorParameters[0] -type HookRow = ReturnType[number] +type HookRow = NonNullable>[number] let db: OrchestrationDb let session: Session diff --git a/src/main/runtime/runtime-orchestration-sender-names.ts b/src/main/runtime/runtime-orchestration-sender-names.ts index cca95f63bfcf..1b97e641a467 100644 --- a/src/main/runtime/runtime-orchestration-sender-names.ts +++ b/src/main/runtime/runtime-orchestration-sender-names.ts @@ -37,7 +37,8 @@ type RuntimeSenderNameDeps = { getWorkspaceSession: (worktreeId: string) => MirroredTabs | null | undefined /** The person's "generate tab titles" setting, which decides whether a generated title names a tab. */ getGeneratedTitlesEnabled: () => boolean - getAgentStatusSnapshotForPane: (paneKey: string) => readonly SenderHookRow[] + getAgentStatusSnapshotForPane: (paneKey: string) => readonly SenderHookRow[] | undefined + getAgentStatusSnapshot?: () => readonly SenderHookRow[] getTrackedTitle: (ptyId: string) => string | null } @@ -103,20 +104,117 @@ export class RuntimeOrchestrationSenderNames { ) } - private terminalNaming(handle: string): TerminalSenderNaming | null { + captureCrewInputs() { + const generatedTitlesEnabled = this.deps.getGeneratedTitlesEnabled() + const db = this.deps.getDb() + const snapshots = new WeakMap() + const workspaces = new Map() + const terminalTabs = new Map< + string, + Map & Partial> + >() + const chatTabs = new Map< + string, + Map> + >() + const session = (id: string) => { + if (!workspaces.has(id)) { + const live = this.deps.getWorkspaceSession(id) + let captured = live ? snapshots.get(live) : null + if (live && !captured) { + captured = structuredClone(live) + snapshots.set(live, captured) + } + workspaces.set(id, captured ?? null) + const terminals = new Map & Partial>() + for (const tab of captured?.tabsByWorktree?.[id] ?? []) { + if (!terminals.has(tab.id)) { + terminals.set(tab.id, tab) + } + } + terminalTabs.set(id, terminals) + const chats = new Map< + string, + Pick + >() + for (const tab of captured?.unifiedTabs?.[id] ?? []) { + if (tab.contentType === 'agent-session' && !chats.has(tab.entityId)) { + chats.set(tab.entityId, tab) + } + } + chatTabs.set(id, chats) + } + return workspaces.get(id) + } + const statuses = new Map() + const allStatuses = this.deps.getAgentStatusSnapshot?.() + for (const row of allStatuses ?? []) { + const rows = statuses.get(row.paneKey) ?? [] + rows.push(structuredClone(row)) + statuses.set(row.paneKey, rows) + } + const terminals = new Map() + return ( + party: AgentMessageSender['party'], + taskName: string | null, + records: AgentSessionRecordReader | null + ) => + orchestrationSenderName( + party, + { + db, + records, + generatedTitlesEnabled, + chatTab: (worktreeId, sessionId) => { + session(worktreeId) + return chatTabs.get(worktreeId)?.get(sessionId) ?? null + }, + terminal: (handle) => { + if (!terminals.has(handle)) { + const naming = this.terminalNaming( + handle, + session, + (worktreeId, tabId) => terminalTabs.get(worktreeId)?.get(tabId), + allStatuses ? (pane) => statuses.get(pane) ?? [] : this.statusRowsForPane + ) + terminals.set(handle, naming ? structuredClone(naming) : null) + } + return terminals.get(handle) ?? null + } + }, + undefined, + taskName + ) + } + + private statusRowsForPane = (pane: string): readonly SenderHookRow[] => + this.deps.getAgentStatusSnapshotForPane(pane) ?? + this.deps.getAgentStatusSnapshot?.().filter((row) => row.paneKey === pane) ?? + [] + + private terminalNaming( + handle: string, + readSession = this.deps.getWorkspaceSession, + readTab?: ( + worktreeId: string, + tabId: string + ) => (Pick & Partial) | undefined, + readStatuses = this.statusRowsForPane + ): TerminalSenderNaming | null { const record = this.deps.getHandleRecord(handle) if (!record) { return null } const pty = record.ptyId ? this.deps.getPtyAgents(record.ptyId) : undefined - const session = this.deps.getWorkspaceSession(record.worktreeId) - const tab = session?.tabsByWorktree?.[record.worktreeId]?.find( - (candidate) => candidate.id === record.tabId - ) + const session = readSession(record.worktreeId) + const tab = readTab + ? readTab(record.worktreeId, record.tabId) + : session?.tabsByWorktree?.[record.worktreeId]?.find( + (candidate) => candidate.id === record.tabId + ) const paneKey = this.deps.getTerminalPaneKey(handle) const status = paneKey - ? this.deps - .getAgentStatusSnapshotForPane(paneKey) + ? readStatuses(paneKey) .filter( (row) => row.paneKey === paneKey && From 65fa3aeae2d2df6a79c65a10f6d50d8acf4d6375 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 09:52:42 -0700 Subject: [PATCH 022/164] fix(test): render worker lineage fixture with production list --- .../components/sidebar/WorkerLineage.fixture.tsx | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/renderer/src/components/sidebar/WorkerLineage.fixture.tsx b/src/renderer/src/components/sidebar/WorkerLineage.fixture.tsx index 23ad40070193..204a79182ae9 100644 --- a/src/renderer/src/components/sidebar/WorkerLineage.fixture.tsx +++ b/src/renderer/src/components/sidebar/WorkerLineage.fixture.tsx @@ -1,5 +1,5 @@ import { defineFixture } from '../../component-fixtures/component-fixture' -import { CompactAgentRow } from './worktree-card-compact-agent-row' +import WorktreeCardAgents from './WorktreeCardAgents' import { applyAgentRowLineage } from '../dashboard/agent-row-lineage' import { buildWorktreeAgentRows } from './worktree-agent-rows' import { structuredAgentSessionPaneKey } from '../../../../shared/structured-agent-session-projection' @@ -52,17 +52,10 @@ const rows = applyAgentRowLineage( export const nestedChatWorker = defineFixture({ width: 380, + store: { agentActivityDisplayMode: 'compact' }, render: () => (
- {rows.map((agent) => ( - {}} - cacheTimerActive={false} - /> - ))} +
) }) From c600430c93b510a3749829becf314144f0de0459 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:41:08 -0700 Subject: [PATCH 023/164] fix: preserve crew pane controls and summary identity --- ...veChatStructuredSession.crew-pane.test.tsx | 111 ++++++++++++++++ .../OrchestrationCrewPanel.test.tsx | 70 ++++++++++- .../OrchestrationCrewPanel.tsx | 119 ++++++++++++------ 3 files changed, 260 insertions(+), 40 deletions(-) create mode 100644 src/renderer/src/components/native-chat/NativeChatStructuredSession.crew-pane.test.tsx diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.crew-pane.test.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.crew-pane.test.tsx new file mode 100644 index 000000000000..47bb02693454 --- /dev/null +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.crew-pane.test.tsx @@ -0,0 +1,111 @@ +// @vitest-environment happy-dom +import '@testing-library/jest-dom/vitest' +import { cleanup, fireEvent, render, screen, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { TooltipProvider } from '@/components/ui/tooltip' +import { testOrcaSessionId } from '../../../../shared/orca-session-address-test-fixture' + +const { mocks, moduleFactories, resetStructuredSessionMocks } = await vi.hoisted(async () => + (await import('./NativeChatStructuredSession.test-harness')).createStructuredSessionMocks() +) +vi.mock('@/runtime/structured-agent-session-client', () => + moduleFactories.structuredAgentSessionClient() +) +vi.mock('./use-structured-agent-session', () => moduleFactories.useStructuredAgentSession()) +vi.mock('./use-native-chat-font-size', () => moduleFactories.useNativeChatFontSize()) +vi.mock('./use-native-chat-file-link-context', () => moduleFactories.useNativeChatFileLinkContext()) +vi.mock('./use-native-chat-tab-owner', () => moduleFactories.useNativeChatTabOwner()) +vi.mock('./use-native-chat-file-link-click', () => moduleFactories.useNativeChatFileLinkClick()) +vi.mock('./NativeChatMessageList', () => moduleFactories.nativeChatMessageList()) +vi.mock('./NativeChatComposer', () => moduleFactories.nativeChatComposer()) +vi.mock('./NativeChatEmptyState', () => moduleFactories.nativeChatEmptyState()) +vi.mock('./NativeChatApprovalCard', () => moduleFactories.nativeChatApprovalCard()) +vi.mock('./NativeChatQuestionCard', () => moduleFactories.nativeChatQuestionCard()) +vi.mock('./use-orchestration-crew', () => ({ + useOrchestrationCrew: () => ({ + status: 'ok', + sections: { + managedBy: [], + talkingWith: [], + managing: [ + { + partyKey: 'worker', + role: 'worker', + label: 'Worker', + agentKind: 'codex', + status: 'working', + sendAddress: 'dispatch:d1', + task: { title: 'Check the result', state: 'active' } + } + ] + } + }) +})) +import { NativeChatStructuredSession } from './NativeChatStructuredSession' + +const first = testOrcaSessionId('11111111-1111-4111-8111-111111111111') +const second = testOrcaSessionId('22222222-2222-4222-8222-222222222222') +beforeEach(() => { + resetStructuredSessionMocks() +}) +afterEach(() => { + cleanup() + localStorage.clear() +}) + +it('handles sibling-composer Escape at the actual native pane boundary and keeps other panes and nested menus independent', async () => { + const user = userEvent.setup() + const view = render( + + + + + ) + const roots = view.container.querySelectorAll('[data-native-chat-root]') + expect(roots).toHaveLength(2) + const pane = within(roots[0]), + other = within(roots[1]) + await user.click(pane.getByRole('button', { name: 'Show crew: 1 workers' })) + await user.click(other.getByRole('button', { name: 'Show crew: 1 workers' })) + const composer = pane.getByRole('textbox', { name: 'Message' }) + const otherComposer = other.getByRole('textbox', { name: 'Message' }) + await user.type(composer, 'Keep this draft') + fireEvent.keyDown(composer, { key: 'Escape', isComposing: true }) + expect(pane.getByRole('complementary', { name: 'Agent crew' })).toBeInTheDocument() + const ownsEscape = (event: KeyboardEvent) => event.preventDefault() + document.addEventListener('keydown', ownsEscape, { capture: true }) + fireEvent.keyDown(composer, { key: 'Escape' }) + document.removeEventListener('keydown', ownsEscape, { capture: true }) + expect(pane.getByRole('complementary', { name: 'Agent crew' })).toBeInTheDocument() + await user.click(pane.getByRole('button', { name: 'More for Worker' })) + expect(screen.getByRole('menu')).toBeInTheDocument() + await user.keyboard('{Escape}') + expect(screen.queryByRole('menu')).not.toBeInTheDocument() + expect(pane.getByRole('complementary', { name: 'Agent crew' })).toBeInTheDocument() + composer.focus() + await user.keyboard('{Escape}') + expect(pane.queryByRole('complementary', { name: 'Agent crew' })).not.toBeInTheDocument() + expect(pane.getByRole('button', { name: 'Show crew: 1 workers' })).toHaveFocus() + expect(composer).toHaveValue('Keep this draft') + expect(other.getByRole('complementary', { name: 'Agent crew' })).toBeInTheDocument() + otherComposer.focus() + await user.keyboard('{Escape}') + expect(other.queryByRole('complementary', { name: 'Agent crew' })).not.toBeInTheDocument() + expect(mocks.send).not.toHaveBeenCalled() + expect(mocks.stop).not.toHaveBeenCalled() +}) diff --git a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.test.tsx b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.test.tsx index 426c2d80d017..9ae090acbcf6 100644 --- a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.test.tsx +++ b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.test.tsx @@ -1,6 +1,6 @@ // @vitest-environment happy-dom import '@testing-library/jest-dom/vitest' -import { cleanup, render, screen } from '@testing-library/react' +import { cleanup, render, screen, waitFor, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { afterEach, expect, it, vi } from 'vitest' import { TooltipProvider } from '@/components/ui/tooltip' @@ -87,8 +87,14 @@ it('keeps keyboard/body disclosure, chevron, Open, Copy, Escape and collapse ind await user.keyboard('{Enter}') expect(rig.open).toHaveBeenCalledTimes(2) expect(rig.open).toHaveBeenLastCalledWith(worker, host) + await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument()) expect(body).toHaveAttribute('aria-expanded', 'true') screen.getByRole('button', { name: 'Collapse crew panel' }).focus() + expect(await screen.findByRole('tooltip')).toHaveTextContent('Collapse crew panel') + await user.keyboard('{Escape}') + expect(screen.queryByRole('tooltip')).not.toBeInTheDocument() + expect(screen.getByRole('complementary', { name: 'Agent crew' })).toBeInTheDocument() + body.focus() await user.keyboard('{Escape}') expect(screen.queryByRole('complementary', { name: 'Agent crew' })).not.toBeInTheDocument() expect(screen.getByRole('button', { name: 'Show crew: 1 workers' })).toHaveFocus() @@ -108,3 +114,65 @@ it('starts pending questions expanded without navigating or copying', async () = expect(rig.open).not.toHaveBeenCalled() expect(rig.copy).not.toHaveBeenCalled() }) + +it('keeps the stable first manager label, names every manager in the tooltip and expands every manager', async () => { + const user = userEvent.setup() + const first = { + ...worker, + role: 'manager' as const, + partyKey: 'host-a:manager', + label: 'First manager' + } + const second = { + ...worker, + role: 'manager' as const, + partyKey: 'host-b:manager', + label: 'Other manager' + } + rig.snapshot = { + ...emptyCrew('ok'), + sections: { managedBy: [first, second], managing: [], talkingWith: [] } + } + render( + + + + ) + const tab = screen.getByRole('button', { name: 'Show crew: Managed by First manager' }) + await user.hover(tab) + expect(await screen.findByRole('tooltip')).toHaveTextContent( + 'Managed by First manager, Other manager' + ) + await user.click(tab) + expect(screen.getByRole('region', { name: 'Managed by' })).toHaveTextContent('First manager') + expect(screen.getByRole('region', { name: 'Managed by' })).toHaveTextContent('Other manager') +}) + +it('shows one collapsed avatar and question per party with reverse-role relationships while keeping both sections', async () => { + const user = userEvent.setup() + const error = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + const question = { preview: 'Which option?', at: '2026-10-28T01:00:00Z' } + const manager = { ...worker, role: 'manager' as const, pendingQuestion: question } + const reverseWorker = { ...worker, pendingQuestion: question } + const peer = { ...worker, partyKey: 'other-worker', label: 'Other worker' } + rig.snapshot = { + ...emptyCrew('ok'), + sections: { managedBy: [manager], managing: [reverseWorker, peer], talkingWith: [] } + } + render( + + + + ) + const tab = screen.getByRole('button', { name: 'Show crew: 2 workers' }) + expect(tab.querySelectorAll('span[aria-hidden="true"]')).toHaveLength(2) + expect(error).not.toHaveBeenCalled() + expect(within(tab).getByText('1')).toBeInTheDocument() + await user.click(tab) + expect(screen.getByRole('region', { name: 'Managed by' })).toHaveTextContent('Worker') + expect(screen.getByRole('region', { name: 'Managing' })).toHaveTextContent('Worker') + } finally { + error.mockRestore() + } +}) diff --git a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx index 169851d3774d..adad074f4fe7 100644 --- a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx +++ b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx @@ -1,4 +1,4 @@ -import { useLayoutEffect, useRef, useState } from 'react' +import { useEffect, useLayoutEffect, useRef, useState } from 'react' import { ChevronDown, ChevronRight, @@ -27,6 +27,8 @@ import type { RuntimeClientTarget } from '../../../../shared/runtime-client-targ import { useOrchestrationCrew } from '../native-chat/use-orchestration-crew' import { openOrchestrationCrewAgent } from '@/lib/open-agent-message-sender' import { cn } from '@/lib/utils' +import { hasVisibleOverlay } from '@/lib/visible-overlay' +import { isImeOwnedKeyboardEvent } from '@/lib/ime-composition-keyboard-event' function Avatar({ row }: { row: OrchestrationCrewRow }) { return ( @@ -97,6 +99,7 @@ function CrewPanelContent({ snapshot }: PanelProps & { snapshot: OrchestrationCrewSnapshot }): React.JSX.Element | null { const [open, setOpen] = useState(false) + const root = useRef(null) const tab = useRef(null) const collapse = useRef(null) const restore = useRef(false) @@ -109,10 +112,42 @@ function CrewPanelContent({ }, [open]) const { managedBy, managing, talkingWith } = snapshot.sections const all = [...managedBy, ...managing, ...talkingWith] - if (snapshot.status !== 'ok' || all.length === 0) { + const visible = snapshot.status === 'ok' && all.length > 0 + useEffect(() => { + const pane = + root.current?.closest('[data-native-chat-root], .pane') ?? root.current + if (!open || !visible || !pane) { + return + } + const onKeyDown = (event: KeyboardEvent) => { + if ( + event.key !== 'Escape' || + event.defaultPrevented || + isImeOwnedKeyboardEvent(event) || + hasVisibleOverlay() + ) { + return + } + event.preventDefault() + event.stopPropagation() + restore.current = true + setOpen(false) + } + pane.addEventListener('keydown', onKeyDown, true) + return () => pane.removeEventListener('keydown', onKeyDown, true) + }, [open, visible]) + if (!visible) { return null } - const pending = all.filter((row) => row.pendingQuestion).length + const seen = new Set() + const summary = all.filter((row) => { + if (seen.has(row.partyKey)) { + return false + } + seen.add(row.partyKey) + return true + }) + const pending = new Set(all.filter((row) => row.pendingQuestion).map((row) => row.partyKey)).size const label = managing.length ? `${managing.length} workers` : managedBy.length @@ -129,18 +164,15 @@ function CrewPanelContent({ ] as const return (
event.stopPropagation()} onMouseDown={(event) => event.stopPropagation()} onKeyDown={(event) => { event.stopPropagation() - if (event.key === 'Escape' && open) { - event.preventDefault() - changeOpen(false) - } }} > {open ? ( @@ -174,38 +206,47 @@ function CrewPanelContent({
) : ( - + + {managedBy.length > 0 ? ( + + Managed by {managedBy.map((row) => row.label).join(', ')} + ) : null} - + )}
) From f8223307f88278af5f8cd4a7c4c6f846bd0fe905 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:59:10 -0700 Subject: [PATCH 024/164] refactor: extract crew row details presentation --- .../orchestration-crew/CrewRowDetails.tsx | 59 +++++++++++++++++++ .../OrchestrationCrewPanel.tsx | 55 +---------------- 2 files changed, 61 insertions(+), 53 deletions(-) create mode 100644 src/renderer/src/components/orchestration-crew/CrewRowDetails.tsx diff --git a/src/renderer/src/components/orchestration-crew/CrewRowDetails.tsx b/src/renderer/src/components/orchestration-crew/CrewRowDetails.tsx new file mode 100644 index 000000000000..caae8deb5b29 --- /dev/null +++ b/src/renderer/src/components/orchestration-crew/CrewRowDetails.tsx @@ -0,0 +1,59 @@ +import { Badge } from '@/components/ui/badge' +import type { OrchestrationCrewRow } from '../../../../shared/orchestration-crew' + +export function CrewRowTime({ at }: { at?: string }) { + if (!at) { + return null + } + const date = new Date(at.includes('T') ? at : `${at.replace(' ', 'T')}Z`) + return Number.isFinite(date.getTime()) ? ( + + ) : null +} + +export function CrewRowDetails({ row }: { row: OrchestrationCrewRow }) { + return ( +
+
Task
+
+ {row.task ? ( + <> + + {row.task.state} + + {row.task.title} + + ) : ( + 'No shared task' + )} +
+ {row.progress ? ( + <> +
Progress
+
{row.progress}
+ + ) : null} + {row.pendingQuestion ? ( + <> +
Asks you
+
{row.pendingQuestion.preview}
+ + ) : row.latest ? ( + <> +
Latest
+
+ + {row.latest.direction === 'to' ? 'To' : 'From'} {row.label} ·{' '} + + +
+ {row.latest.preview} +
+
+ + ) : null} +
+ ) +} diff --git a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx index adad074f4fe7..ee9629e87f58 100644 --- a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx +++ b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx @@ -29,6 +29,7 @@ import { openOrchestrationCrewAgent } from '@/lib/open-agent-message-sender' import { cn } from '@/lib/utils' import { hasVisibleOverlay } from '@/lib/visible-overlay' import { isImeOwnedKeyboardEvent } from '@/lib/ime-composition-keyboard-event' +import { CrewRowDetails, CrewRowTime as Time } from './CrewRowDetails' function Avatar({ row }: { row: OrchestrationCrewRow }) { return ( @@ -55,17 +56,6 @@ function Dot({ row }: { row: OrchestrationCrewRow }) { /> ) } -function Time({ at }: { at?: string }) { - if (!at) { - return null - } - const date = new Date(at.includes('T') ? at : `${at.replace(' ', 'T')}Z`) - return Number.isFinite(date.getTime()) ? ( - - ) : null -} function IconButton({ label, children, @@ -330,48 +320,7 @@ function CrewRowView({ row, target }: { row: OrchestrationCrewRow; target: Runti
- {expanded ? ( -
-
Task
-
- {row.task ? ( - <> - - {row.task.state} - - {row.task.title} - - ) : ( - 'No shared task' - )} -
- {row.progress ? ( - <> -
Progress
-
{row.progress}
- - ) : null} - {row.pendingQuestion ? ( - <> -
Asks you
-
{row.pendingQuestion.preview}
- - ) : row.latest ? ( - <> -
Latest
-
- - {row.latest.direction === 'to' ? 'To' : 'From'} {row.label} ·{' '} - -
- {row.latest.preview} -
-
- - ) : null} -
- ) : null} + {expanded ? : null} ) } From e79237b102bcaacaaa5f5c189bc6fa03c2ef3738 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:57:14 -0700 Subject: [PATCH 025/164] Add scoped terminal identity acquisition and preserve crew source wakes --- .../runtime-construction-services.ts | 27 +- .../crew/crew-parent-relations.test.ts | 7 +- .../orchestration/crew/crew-parties.ts | 3 +- .../crew/crew-read-model-performance.test.ts | 16 +- .../orchestration/crew/crew-read-model.ts | 4 +- .../terminal-pane-mail-routing.ts | 68 ++-- .../prune-mobile-session-tab-group-layout.ts | 18 +- .../session-tabs/session-tabs-inventory.ts | 16 +- .../adopt-terminal-orphans-from-inventory.ts | 17 +- .../identity/terminal-handle-bindings.ts | 86 ++++- .../output/headless-buffer-snapshot.ts | 20 +- .../terminal-orchestration-authority.ts | 32 +- .../terminal/query/pty-terminal-summary.ts | 94 +++-- .../terminal-identity-read-context.test.ts | 362 ++++++++++++++++++ .../query/terminal-identity-read-context.ts | 223 +++++++++++ .../surface/main-terminal-acquisition.test.ts | 81 ++++ .../surface/main-terminal-surfaces.ts | 21 +- .../terminal/surface/pty-pane-query.ts | 47 +++ .../wait/terminal-interactive-wait.ts | 28 +- 19 files changed, 996 insertions(+), 174 deletions(-) create mode 100644 src/main/runtime/terminal/query/terminal-identity-read-context.test.ts create mode 100644 src/main/runtime/terminal/query/terminal-identity-read-context.ts create mode 100644 src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts diff --git a/src/main/runtime/construction/runtime-construction-services.ts b/src/main/runtime/construction/runtime-construction-services.ts index a5e6b47ad495..7b4c79b7afc3 100644 --- a/src/main/runtime/construction/runtime-construction-services.ts +++ b/src/main/runtime/construction/runtime-construction-services.ts @@ -1,3 +1,4 @@ +import type { TerminalIdentityReadContext } from '../terminal/query/terminal-identity-read-context' import type * as Calls from './runtime-host-service-calls' import type { IPtyProvider } from '../../providers/pty-provider-contract' import type { @@ -115,8 +116,12 @@ export abstract class RuntimeConstructionServices { ): Promise protected abstract getLeafKey(tabId: string, leafId: string): string /** L80: sole reader of a PTY record's tab/pane copies. */ + protected abstract captureTerminalPaneReader(): (pty: PtyPaneSource) => PtyPane protected abstract paneOfPty(pty: PtyPaneSource | null | undefined): PtyPane - protected abstract getLivePtyForHandle(handle: string): { + protected abstract getLivePtyForHandle( + handle: string, + context?: TerminalIdentityReadContext + ): { record: TerminalHandleRecord pty: RuntimePtyWorktreeRecord } | null @@ -147,14 +152,26 @@ export abstract class RuntimeConstructionServices { protected abstract getOrchestrationDbIfAvailable(): OrchestrationDb | null protected abstract listResolvedWorktrees(): Promise abstract showTerminal(handle: string): Promise - protected abstract issueHandle(leaf: RuntimeLeafRecord): string - protected abstract issuePtyHandle(pty: RuntimePtyWorktreeRecord): string + protected abstract issueHandle( + leaf: RuntimeLeafRecord, + context?: TerminalIdentityReadContext + ): string + protected abstract issuePtyHandle( + pty: RuntimePtyWorktreeRecord, + context?: TerminalIdentityReadContext + ): string protected abstract makeRuntimePaneKey( leaf: Pick ): string abstract getTerminalWorktreeIdForHandle(handle: string): string | null - abstract getTerminalHandleForPaneKey(paneKey: string): string | null - protected abstract getPaneKeyForTerminalHandle(handle: string): string | null + abstract getTerminalHandleForPaneKey( + paneKey: string, + context?: TerminalIdentityReadContext + ): string | null + protected abstract getPaneKeyForTerminalHandle( + handle: string, + context?: TerminalIdentityReadContext + ): string | null abstract getOrchestrationDispatchAuthority( terminalHandle: string ): OrchestrationCompatibilityTerminalAuthority | null diff --git a/src/main/runtime/orchestration/crew/crew-parent-relations.test.ts b/src/main/runtime/orchestration/crew/crew-parent-relations.test.ts index 4f178f6ccc23..e934a5cdd077 100644 --- a/src/main/runtime/orchestration/crew/crew-parent-relations.test.ts +++ b/src/main/runtime/orchestration/crew/crew-parent-relations.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { buildCrewSnapshot, CrewReadModel } from './crew-read-model' import { fixture } from './crew-read-model.test-fixture' import { subscribeCrew } from './crew-stream' @@ -8,12 +8,15 @@ import { federatedStubHomeRunId } from '../db/contract-constants' import { maximalCrewClaims } from './crew-claim-reduction' import { isEquivalentPaneKey } from '../db/pane-key-match' +afterEach(() => vi.useRealTimers()) + describe('durable crew parents', () => { it('composes incomparable local and remote claims through terminal outcomes without re-aging Managing', async () => { const { db, deps, handles, assign } = fixture() deps.processForHandle = () => 'process_one' const local = assign('term_worker') - const now = Date.now() + const now = 1_800_000_000_000 + vi.useFakeTimers({ now }) db.completeDispatch(local.id) db.db .prepare('UPDATE dispatch_contexts SET completed_at = ? WHERE id = ?') diff --git a/src/main/runtime/orchestration/crew/crew-parties.ts b/src/main/runtime/orchestration/crew/crew-parties.ts index 2e106ab3e9cd..b0876adf81da 100644 --- a/src/main/runtime/orchestration/crew/crew-parties.ts +++ b/src/main/runtime/orchestration/crew/crew-parties.ts @@ -5,8 +5,7 @@ import { parseOrcaSessionAddress } from '../../../../shared/orca-session-address' import { isPublicOrchestrationAddress } from '../../../../shared/orchestration-agent-reference' -import { createCanonicalSessionPaneResolver } from '../structured-session-lineage' -import { clearedInto } from '../structured-session-lineage' +import { createCanonicalSessionPaneResolver, clearedInto } from '../structured-session-lineage' import type { CrewReadDependencies } from './crew-read-model' export type Party = AgentMessageSender['party'] & { paneKey: string | null } diff --git a/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts b/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts index 7110a734ef14..27659c9ec71a 100644 --- a/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts +++ b/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts @@ -6,7 +6,7 @@ import { RuntimeAgentOrchestrationProjection } from '../../runtime-agent-orchest import { readOrchestrationFleetAgentStatusSnapshot } from '../../orchestration-fleet-agent-status-snapshot' import { RuntimeOrchestrationSenderNames } from '../../runtime-orchestration-sender-names' -import { expect, it, vi } from 'vitest' +import { afterEach, expect, it, vi } from 'vitest' import { CrewReadModel } from './crew-read-model' import { CrewChanges } from './crew-changes' @@ -16,6 +16,8 @@ import { agentSessionRecordFixture } from '../../../native-chat/agent-session-re import { agentSessionConversationView } from '../../../../shared/agent-session-conversation-view' import { fixture } from './crew-read-model.test-fixture' +afterEach(() => vi.useRealTimers()) + it('shares complete host derivation across N/10N handled assignments and subscribers on real wakes', async () => { const flush = async () => { await Promise.resolve() @@ -145,6 +147,8 @@ it('shares complete host derivation across N/10N handled assignments and subscri } }) it('counts the real status qualification/projection SQL on a decoration wake without global reacquisition', async () => { + const now = 1_800_000_000_000 + vi.useFakeTimers({ now }) const measurements = [] for (const population of [3, 30]) { const { db, deps, assign, handles } = fixture() @@ -190,8 +194,8 @@ it('counts the real status qualification/projection SQL on a decoration wake wit agentType: 'codex', prompt: '', connectionId: null, - receivedAt: Date.now(), - stateStartedAt: Date.now() + receivedAt: now, + stateStartedAt: now })) const acquireStatus = vi.fn(() => readOrchestrationFleetAgentStatusSnapshot({ @@ -292,6 +296,12 @@ it('counts the real status qualification/projection SQL on a decoration wake wit expect(globalSelection).not.toHaveBeenCalled() expect(model.read('term_coord').sections.managing[0].label).toBe(title) expect(sql.some((text) => text.includes('retry_of_dispatch_id AS retry'))).toBe(false) + acquireStatus.mockClear() + handles.delete('term_worker') + wake.notify(new Set(['status'])) + await Promise.resolve() + expect(acquireStatus).toHaveBeenCalledTimes(1) + expect(globalSelection).toHaveBeenCalledTimes(1) for (const stop of streams) { stop() } diff --git a/src/main/runtime/orchestration/crew/crew-read-model.ts b/src/main/runtime/orchestration/crew/crew-read-model.ts index 3f68801c5145..20904e5c278b 100644 --- a/src/main/runtime/orchestration/crew/crew-read-model.ts +++ b/src/main/runtime/orchestration/crew/crew-read-model.ts @@ -75,12 +75,12 @@ export class CrewReadModel { this.host = undefined const deps = this.readDependencies() if (dirty.has('status')) { - const statuses = deps.statuses + const { statuses, ...sources } = deps const identities = (rows: typeof statuses) => new Map(rows.map((row) => [row.activity.paneKey, row.binding])) this.host = isDeepStrictEqual(identities(previous.deps.statuses), identities(statuses)) ? refreshCrewStatuses(previous, statuses) - : createCrewHostDerivation({ ...deps, statuses }, now) + : createCrewHostDerivation({ ...sources, statuses }, now) } else { this.host = previous } diff --git a/src/main/runtime/orchestration/terminal-pane-mail-routing.ts b/src/main/runtime/orchestration/terminal-pane-mail-routing.ts index f42f9b9e87da..885fbdcc90c6 100644 --- a/src/main/runtime/orchestration/terminal-pane-mail-routing.ts +++ b/src/main/runtime/orchestration/terminal-pane-mail-routing.ts @@ -1,7 +1,11 @@ +import { + ptyRecordForPaneKey, + type TerminalIdentityReadContext +} from '../terminal/query/terminal-identity-read-context' import type { RuntimeTerminalAgentPresenceOptions } from '../runtime-terminal-agent-presence' import { OrcaRuntimeWithPruneMobileSessionTabGroupLayout } from '../session-lifecycle/projection/prune-mobile-session-tab-group-layout' import type { RuntimePtyWorktreeRecord } from '../runtime-terminal-state-records' -import { isTerminalLeafId, makePaneKey, parsePaneKey } from '../../../shared/stable-pane-id' +import { isTerminalLeafId, makePaneKey } from '../../../shared/stable-pane-id' import { detectAgentStatusFromTitle, isClaudeManagementTitle @@ -28,43 +32,28 @@ import { OPERATOR_CLOSE_EXIT_CAUSE } from '../../../shared/terminal-exit-cause' import { resolveTerminalIdentityFromProbes } from '../terminal-identity-probe' export abstract class OrcaRuntimeWithGetPtyRecordForPaneKey extends OrcaRuntimeWithPruneMobileSessionTabGroupLayout { - protected getPtyRecordForPaneKey(paneKey: string): RuntimePtyWorktreeRecord | null { - const parsed = parsePaneKey(paneKey) - let leafPty: RuntimePtyWorktreeRecord | null = null - if (parsed) { - const leaf = this.leaves.get(this.getLeafKey(parsed.tabId, parsed.leafId)) - const pty = leaf?.ptyId ? this.ptysById.get(leaf.ptyId) : undefined - if (pty?.connected) { - return pty - } - leafPty = pty ?? null - for (const candidate of this.leaves.values()) { - if (candidate.leafId !== parsed.leafId || !candidate.ptyId) { - continue - } - const remintedPty = this.ptysById.get(candidate.ptyId) - if (remintedPty?.connected) { - return remintedPty - } - leafPty ??= remintedPty ?? null - } - } - let newestMatch: RuntimePtyWorktreeRecord | null = null - for (const pty of this.ptysById.values()) { - const recordedPaneKey = this.paneOfPty(pty).paneKey - const ptyPane = parsePaneKey(recordedPaneKey ?? '') - if (recordedPaneKey === paneKey || (parsed && ptyPane && parsed.leafId === ptyPane.leafId)) { - if (pty.connected) { - return pty - } - newestMatch = pty - } - } - return leafPty ?? newestMatch + protected getPtyRecordForPaneKey( + paneKey: string, + context?: TerminalIdentityReadContext + ): RuntimePtyWorktreeRecord | null { + return ptyRecordForPaneKey( + paneKey, + { + leaves: this.leaves, + ptys: this.ptysById, + leafKey: (tab, leaf) => this.getLeafKey(tab, leaf), + paneOf: (pty) => this.paneOfPty(pty) + }, + context + ) } - protected getPaneKeyForTerminalHandle(handle: string): string | null { - const livePaneKey = this.paneOfPty(this.getLivePtyForHandle(handle)?.pty).paneKey + protected getPaneKeyForTerminalHandle( + handle: string, + context?: TerminalIdentityReadContext + ): string | null { + const pty = this.getLivePtyForHandle(handle, context)?.pty + const livePaneKey = (context && pty ? context.paneOf(pty) : this.paneOfPty(pty)).paneKey if (livePaneKey) { return livePaneKey } @@ -75,8 +64,11 @@ export abstract class OrcaRuntimeWithGetPtyRecordForPaneKey extends OrcaRuntimeW return makePaneKey(record.tabId, record.leafId) } - getTerminalWorktreeIdForHandle(handle: string): string | null { - const livePty = this.getLivePtyForHandle(handle) + getTerminalWorktreeIdForHandle( + handle: string, + context?: TerminalIdentityReadContext + ): string | null { + const livePty = this.getLivePtyForHandle(handle, context) if (livePty?.pty.worktreeId) { return livePty.pty.worktreeId } diff --git a/src/main/runtime/session-lifecycle/projection/prune-mobile-session-tab-group-layout.ts b/src/main/runtime/session-lifecycle/projection/prune-mobile-session-tab-group-layout.ts index 9f30759bc70a..5d5a8527d482 100644 --- a/src/main/runtime/session-lifecycle/projection/prune-mobile-session-tab-group-layout.ts +++ b/src/main/runtime/session-lifecycle/projection/prune-mobile-session-tab-group-layout.ts @@ -21,7 +21,7 @@ import type { } from '../../../../shared/agent-status-types' import { buildRuntimeMobileAgentStatus } from '../../runtime-mobile-agent-status-builder' import { FIRST_PANE_ID } from '../../../../shared/pane-key' -import { isTerminalLeafId, makePaneKey, parsePaneKey } from '../../../../shared/stable-pane-id' +import { isTerminalLeafId, makePaneKey } from '../../../../shared/stable-pane-id' import { getStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' import { structuredWorkerHandleAgentStatus } from '../../orchestration/structured-worker-group-addressing' import { @@ -306,20 +306,4 @@ export abstract class OrcaRuntimeWithPruneMobileSessionTabGroupLayout extends Or getAgentStatusTerminalHandleForPaneKey(paneKey: string): string | undefined { return this.getTerminalHandleForPaneKey(paneKey) ?? undefined } - - getTerminalHandleForPaneKey(paneKey: string): string | null { - const parsed = parsePaneKey(paneKey) - const leaf = parsed ? this.leaves.get(this.getLeafKey(parsed.tabId, parsed.leafId)) : undefined - if (leaf?.ptyId && leaf.connected) { - return this.issueHandle(leaf) - } - const panePty = this.getPtyRecordForPaneKey(paneKey) - if (panePty?.connected) { - return this.issuePtyHandle(panePty) - } - if (leaf?.ptyId) { - return this.issueHandle(leaf) - } - return panePty ? this.issuePtyHandle(panePty) : null - } } diff --git a/src/main/runtime/session-tabs/session-tabs-inventory.ts b/src/main/runtime/session-tabs/session-tabs-inventory.ts index 24a48b9ec932..d3d2a8fe06e0 100644 --- a/src/main/runtime/session-tabs/session-tabs-inventory.ts +++ b/src/main/runtime/session-tabs/session-tabs-inventory.ts @@ -1,3 +1,4 @@ +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' import { visibleGraphChangedWorktrees } from '../session-graph/visible-graph-changed-worktrees' import type { RuntimeSessionTabsInventoryPublication as SessionTabsInventoryPublicationMethods } from './session-tabs-inventory-publication' import type { OrcaRuntimeWithScheduleMobileSessionTabsChanged as ScheduleMobileSessionTabsChangedMethods } from './session-tabs-change-publication' @@ -22,7 +23,12 @@ import type { RuntimeLeafRecord } from '../runtime-terminal-state-records' import type { PtyControllerInventory } from '../runtime-pty-controller-contract' import { parseExecutionHostId } from '../../../shared/execution-host' import type { PaneStartStatuses } from '../pane-start-statuses' -import { paneOfPty, type PtyPane, type PtyPaneSource } from '../terminal/surface/pty-pane-query' +import { + paneOfPty, + type PtyPane, + type PtyPaneSource, + type PtyPaneOf +} from '../terminal/surface/pty-pane-query' export abstract class OrcaRuntimeWithCollectMobileVisibleGraphChangedWorktrees extends OrcaRuntimeWithSyncWindowGraph { abstract get workspaceLayoutReads(): WorkspaceLayoutReads @@ -41,6 +47,14 @@ export abstract class OrcaRuntimeWithCollectMobileVisibleGraphChangedWorktrees e return paneOfPty(pty, (ptyId) => this.mainSurfaces().findPaneForPty(ptyId)) } + protected captureTerminalPaneReader(): PtyPaneOf { + if (!ORCA_LAYOUT_OWNER_IS_MAIN) { + return (pty) => paneOfPty(pty, () => null) + } + const mainPane = this.mainSurfaces().capturePaneLookup() + return (pty) => paneOfPty(pty, mainPane) + } + private mainSurfaces(): ReturnType { const host = (): MainTerminalSurfacesHost => ({ store: () => this.store, diff --git a/src/main/runtime/terminal/adoption/adopt-terminal-orphans-from-inventory.ts b/src/main/runtime/terminal/adoption/adopt-terminal-orphans-from-inventory.ts index e8726338da46..debaabfa03db 100644 --- a/src/main/runtime/terminal/adoption/adopt-terminal-orphans-from-inventory.ts +++ b/src/main/runtime/terminal/adoption/adopt-terminal-orphans-from-inventory.ts @@ -1,3 +1,4 @@ +import type { TerminalIdentityReadContext } from '../query/terminal-identity-read-context' import { recordPtySurface, spawnSurfaceClaimSequence, @@ -21,9 +22,15 @@ import { getLatestPtyTitle } from '../../runtime-worktree-status-projection' import type { PtyLivenessVerdict } from '../../../../shared/pty-liveness-verdict' export abstract class OrcaRuntimeWithAdoptTerminalOrphansFromInventory extends OrcaRuntimeWithSubscribeToTerminalResize { - protected abstract issueHandle(leaf: RuntimeLeafRecord): string + protected abstract issueHandle( + leaf: RuntimeLeafRecord, + context?: TerminalIdentityReadContext + ): string - protected abstract getPaneKeyForTerminalHandle(handle: string): string | null + protected abstract getPaneKeyForTerminalHandle( + handle: string, + context?: TerminalIdentityReadContext + ): string | null abstract assertGraphReady(): void @@ -191,12 +198,12 @@ export abstract class OrcaRuntimeWithAdoptTerminalOrphansFromInventory extends O } // Dispatch uses remint-stable pane keys; unresolved handles return null so best-effort dispatch can proceed. - getTerminalPaneKey(handle: string): string | null { + getTerminalPaneKey(handle: string, context?: TerminalIdentityReadContext): string | null { return ( resolveStructuredWorkerAuthority(handle, this.getOrchestrationDbIfAvailable?.() ?? null) ?.identity.paneKey ?? - this.getPaneKeyForTerminalHandle(handle) ?? - this.getOrchestrationCompatibilitySshTerminal(handle)?.paneKey ?? + this.getPaneKeyForTerminalHandle(handle, context) ?? + this.getOrchestrationCompatibilitySshTerminal(handle, context)?.paneKey ?? null ) } diff --git a/src/main/runtime/terminal/identity/terminal-handle-bindings.ts b/src/main/runtime/terminal/identity/terminal-handle-bindings.ts index 49a8d540f7c8..965c166a98a6 100644 --- a/src/main/runtime/terminal/identity/terminal-handle-bindings.ts +++ b/src/main/runtime/terminal/identity/terminal-handle-bindings.ts @@ -1,3 +1,4 @@ +import type { TerminalIdentityReadContext } from '../query/terminal-identity-read-context' import { OrcaRuntimeWithBuildPtyTerminalSummary } from '../query/pty-terminal-summary' import type { PtyIncarnationHandleRecord } from '../../orca-runtime-core' import type { @@ -98,24 +99,32 @@ export abstract class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntim return preAllocated } - protected issuePtyHandle(pty: RuntimePtyWorktreeRecord): string { - const handle = this.issuePtyHandleRecord(pty) + protected issuePtyHandle( + pty: RuntimePtyWorktreeRecord, + context?: TerminalIdentityReadContext + ): string { + const handle = this.issuePtyHandleRecord(pty, context) // An unbound terminal retains its issued pane stamp for recovery, including after replacement. const record = ORCA_LAYOUT_OWNER_IS_MAIN ? this.handles.get(handle) : undefined - const issuedForPaneKey = record && this.paneOfPty(pty).paneKey + const issuedForPaneKey = record && (context ? context.paneOf(pty) : this.paneOfPty(pty)).paneKey if (record && issuedForPaneKey && record.issuedForPaneKey !== issuedForPaneKey) { this.handles.set(handle, { ...record, issuedForPaneKey }) } + context?.changedHandle(handle) + context?.changedReverseBinding(pty.ptyId) return handle } - private issuePtyHandleRecord(pty: RuntimePtyWorktreeRecord): string { + private issuePtyHandleRecord( + pty: RuntimePtyWorktreeRecord, + context?: TerminalIdentityReadContext + ): string { const retained = this.handleByPtyIncarnation.get(pty.ptyId) if (retained?.incarnationId === pty.incarnationId) { return retained.handle } const existingHandle = - this.handleByPtyId.get(pty.ptyId) ?? this.findHandleForPtyRecord(pty.ptyId) + this.handleByPtyId.get(pty.ptyId) ?? this.findHandleForPtyRecord(pty.ptyId, context) if (existingHandle) { const existingRecord = this.handles.get(existingHandle) if ( @@ -147,8 +156,16 @@ export abstract class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntim return handle } - protected findHandleForPtyRecord(ptyId: string): string | null { - for (const [handle, record] of this.handles) { + protected findHandleForPtyRecord( + ptyId: string, + context?: TerminalIdentityReadContext + ): string | null { + const candidates = context ? context.syntheticHandles(ptyId) : this.handles.keys() + for (const handle of candidates) { + const record = this.handles.get(handle) + if (!record) { + continue + } if ( record.runtimeId === this.runtimeId && record.ptyId === ptyId && @@ -203,4 +220,59 @@ export abstract class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntim } } } + protected issueHandle(leaf: RuntimeLeafRecord, context?: TerminalIdentityReadContext): string { + const retained = leaf.ptyId ? this.handleByPtyIncarnation.get(leaf.ptyId)?.handle : undefined + const handle = this.issueLeafHandleRecord(leaf) + if (retained) { + context?.changedHandle(retained) + } + context?.changedHandle(handle) + return handle + } + + private issueLeafHandleRecord(leaf: RuntimeLeafRecord): string { + const leafKey = this.getLeafKey(leaf.tabId, leaf.leafId) + const existingHandle = this.handleByLeafKey.get(leafKey) + if (existingHandle) { + const existingRecord = this.handles.get(existingHandle) + if ( + existingRecord && + existingRecord.rendererGraphEpoch === this.rendererGraphEpoch && + existingRecord.ptyId === leaf.ptyId && + existingRecord.ptyGeneration === leaf.ptyGeneration + ) { + return existingHandle + } + } + + const preAllocatedHandle = this.adoptPreAllocatedHandle(leaf) + if (preAllocatedHandle) { + return preAllocatedHandle + } + const incarnationId = leaf.ptyId ? (this.ptysById.get(leaf.ptyId)?.incarnationId ?? null) : null + const retained = leaf.ptyId ? this.handleByPtyIncarnation.get(leaf.ptyId) : undefined + if (retained && leaf.ptyId && retained.incarnationId !== incarnationId) { + this.invalidatePtyIncarnationHandle(leaf.ptyId) + } else if (retained) { + this.bindPtyIncarnationHandle(retained, leaf) + return retained.handle + } + const handle = `term_${randomUUID()}` + this.syntheticTerminalHandles.add(handle) + this.handles.set(handle, { + handle, + runtimeId: this.runtimeId, + rendererGraphEpoch: this.rendererGraphEpoch, + worktreeId: leaf.worktreeId, + tabId: leaf.tabId, + leafId: leaf.leafId, + ptyId: leaf.ptyId, + ptyGeneration: leaf.ptyGeneration + }) + this.handleByLeafKey.set(leafKey, handle) + if (leaf.ptyId) { + this.handleByPtyIncarnation.set(leaf.ptyId, { handle, incarnationId, leafKey }) + } + return handle + } } diff --git a/src/main/runtime/terminal/output/headless-buffer-snapshot.ts b/src/main/runtime/terminal/output/headless-buffer-snapshot.ts index d2b5b36cbf29..22202143a5fc 100644 --- a/src/main/runtime/terminal/output/headless-buffer-snapshot.ts +++ b/src/main/runtime/terminal/output/headless-buffer-snapshot.ts @@ -1,3 +1,4 @@ +import type { TerminalIdentityReadContext } from '../query/terminal-identity-read-context' import { OrcaRuntimeWithVisibleSnapshotPreview } from './terminal-visible-state' import type { TerminalOscLinkRange } from '../../../../shared/terminal-osc-link-ranges' import { parseTerminalKittyKeyboardFlags } from '../../../../shared/terminal-kitty-keyboard-flags' @@ -149,12 +150,17 @@ export abstract class OrcaRuntimeWithSerializeHeadlessTerminalBuffer extends Orc Object.freeze({ ...terminal }) ) } + if (terminal) { + this.crewChanges.notify() + } return authority } releaseOrchestrationCompatibilitySshAttachment(attachmentId: string): void { this.orchestrationCompatibilitySshAttachments.delete(attachmentId) - this.orchestrationCompatibilitySshTerminals.delete(attachmentId) + if (this.orchestrationCompatibilitySshTerminals.delete(attachmentId)) { + this.crewChanges.notify() + } } /** @@ -162,10 +168,18 @@ export abstract class OrcaRuntimeWithSerializeHeadlessTerminalBuffer extends Orc * claiming one handle name nobody: neither may borrow the other's pane or process. */ protected getOrchestrationCompatibilitySshTerminal( - handle: string + handle: string, + context?: TerminalIdentityReadContext ): OrchestrationCompatibilitySshTerminal | undefined { let found: { targetId: string; terminal: OrchestrationCompatibilitySshTerminal } | undefined - for (const [attachmentId, terminal] of this.orchestrationCompatibilitySshTerminals) { + const candidates = context + ? context.sshAttachmentIds(handle) + : this.orchestrationCompatibilitySshTerminals.keys() + for (const attachmentId of candidates) { + const terminal = this.orchestrationCompatibilitySshTerminals.get(attachmentId) + if (!terminal) { + continue + } const targetId = this.orchestrationCompatibilitySshAttachments.get(attachmentId)?.targetId if (terminal.handle !== handle || !targetId) { continue diff --git a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts index 72407433b5ce..25d5bec020a6 100644 --- a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts +++ b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts @@ -1,3 +1,4 @@ +import type { TerminalIdentityReadContext } from '../query/terminal-identity-read-context' import type { AgentStatusOrchestrationContext } from '../../../../shared/agent-status-types' import type { OrchestrationDb } from '../../orchestration/db/orchestration-db' import { OrcaRuntimeWithVerifyOrchestrationCompatibilityCaller } from '../../orchestration/terminal-authority/verify-orchestration-compatibility-caller' @@ -30,11 +31,38 @@ import { matchesProcessIncarnation } from '../../orchestration/worker-terminal-p export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends OrcaRuntimeWithVerifyOrchestrationCompatibilityCaller { protected abstract getExistingTerminalHandlesForPtyId(ptyId: string): string[] protected abstract getOrchestrationDbIfAvailable(): OrchestrationDb | null - abstract getTerminalProcessIncarnation(handle: string): string | null + getTerminalProcessIncarnation( + handle: string, + context?: TerminalIdentityReadContext + ): string | null { + const structured = resolveStructuredWorkerAuthority( + handle, + this.getOrchestrationDbIfAvailable?.() ?? null + ) + if (structured) { + return structured.identity.processIncarnation + } + const live = this.getLivePtyForHandle(handle, context) + const record = live?.record ?? this.handles.get(handle) + if (!record?.ptyId) { + return ( + this.getOrchestrationCompatibilitySshTerminal(handle, context)?.processIncarnation ?? null + ) + } + const incarnationId = live?.pty.incarnationId ?? this.ptysById.get(record.ptyId)?.incarnationId + if (incarnationId) { + return `${record.ptyId}:${incarnationId}` + } + // Legacy providers retain the runtime/PTY/generation fence. + return `${this.runtimeId}:${record.ptyId}:${record.ptyGeneration}` + } abstract getAgentStatusOrchestrationContextForPaneKey( paneKey: string ): AgentStatusOrchestrationContext | undefined - protected abstract issuePtyHandle(pty: RuntimePtyWorktreeRecord): string + protected abstract issuePtyHandle( + pty: RuntimePtyWorktreeRecord, + context?: TerminalIdentityReadContext + ): string /** Every pane key this PTY could be addressed by, including restored receipts. */ protected collectPaneKeysForPty(ptyId: string): Set { diff --git a/src/main/runtime/terminal/query/pty-terminal-summary.ts b/src/main/runtime/terminal/query/pty-terminal-summary.ts index 3e152c8652c8..dd39ae710339 100644 --- a/src/main/runtime/terminal/query/pty-terminal-summary.ts +++ b/src/main/runtime/terminal/query/pty-terminal-summary.ts @@ -1,3 +1,4 @@ +import { TerminalIdentityReadContext } from './terminal-identity-read-context' import { OrcaRuntimeWithGetPtyRecordForPaneKey } from '../../orchestration/terminal-pane-mail-routing' import type { RuntimeLeafRecord, @@ -17,7 +18,6 @@ import type { PtyIncarnationHandleRecord } from '../../orca-runtime-core' import type { TerminalHandleRecord } from '../../runtime-terminal-contracts' import { readTerminalTail } from '../../terminal-tail-read' import { structuredWorkerTerminalRefusal } from '../../structured-worker-terminal-refusal' -import { randomUUID } from 'node:crypto' import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' import type { OrchestrationMailboxLeaf } from '../../orchestration/mailbox-owner' import { ptyMailboxLeaf } from '../../orchestration/pty-mailbox-leaf' @@ -35,6 +35,17 @@ export abstract class OrcaRuntimeWithBuildPtyTerminalSummary extends OrcaRuntime leaf: RuntimeLeafRecord ): void + createTerminalIdentityReadContext(): TerminalIdentityReadContext { + return new TerminalIdentityReadContext({ + handles: this.handles, + sshTerminals: this.orchestrationCompatibilitySshTerminals, + reverse: this.handleByPtyId, + leaves: this.leaves, + ptys: this.ptysById, + capturePaneOf: () => this.captureTerminalPaneReader() + }) + } + protected ptySurfaceTopology(): PtySurfaceTopology { return { graphSequence: this.graphSequence, @@ -200,26 +211,29 @@ export abstract class OrcaRuntimeWithBuildPtyTerminalSummary extends OrcaRuntime return this.authoritativeWindowId === HEADLESS_RUNTIME_WINDOW_ID && this.graphStatus === 'ready' } - protected getLivePtyForHandle(handle: string): { + protected getLivePtyForHandle( + handle: string, + context?: TerminalIdentityReadContext + ): { record: TerminalHandleRecord pty: RuntimePtyWorktreeRecord } | null { let record = this.handles.get(handle) if (!record) { - const ptyId = [...this.handleByPtyId.entries()].find( - ([, mappedHandle]) => mappedHandle === handle - )?.[0] + const ptyId = context + ? context.reversePtyIds(handle)[0] + : [...this.handleByPtyId.entries()].find(([, mappedHandle]) => mappedHandle === handle)?.[0] const pty = ptyId ? this.ptysById.get(ptyId) : null if (pty) { // Why: graph reload clears renderer handle records, but runtime-owned PTY handles remain the caller's control identity. - this.issuePtyHandle(pty) + this.issuePtyHandle(pty, context) record = this.handles.get(handle) } } if ( !record || record.runtimeId !== this.runtimeId || - !(record.tabId.startsWith('pty:') || this.mainPaneOwnHandle(handle, record)) + !(record.tabId.startsWith('pty:') || this.mainPaneOwnHandle(handle, record, context)) ) { return null } @@ -232,11 +246,16 @@ export abstract class OrcaRuntimeWithBuildPtyTerminalSummary extends OrcaRuntime } // Why: renderer adoption can race with CLI reads; keep ptyId → handle populated so summaries don't mint a second handle for the same terminal. this.handleByPtyId.set(record.ptyId, handle) + context?.changedReverseBinding(record.ptyId) return { record, pty } } /** Main-owned panes adopt the terminal's original handle; own-handle checks fence epochs because replacement incarnations drop that handle. */ - private mainPaneOwnHandle(handle: string, record: TerminalHandleRecord): boolean { + private mainPaneOwnHandle( + handle: string, + record: TerminalHandleRecord, + context?: TerminalIdentityReadContext + ): boolean { if ( !ORCA_LAYOUT_OWNER_IS_MAIN || !record.ptyId || @@ -246,8 +265,9 @@ export abstract class OrcaRuntimeWithBuildPtyTerminalSummary extends OrcaRuntime ) { return false } + const pty = this.ptysById.get(record.ptyId) return ( - this.paneOfPty(this.ptysById.get(record.ptyId)).paneKey === + (context && pty ? context.paneOf(pty) : this.paneOfPty(pty)).paneKey === makePaneKey(record.tabId, record.leafId) ) } @@ -283,50 +303,22 @@ export abstract class OrcaRuntimeWithBuildPtyTerminalSummary extends OrcaRuntime limit: opts.limit }) } - - protected issueHandle(leaf: RuntimeLeafRecord): string { - const leafKey = this.getLeafKey(leaf.tabId, leaf.leafId) - const existingHandle = this.handleByLeafKey.get(leafKey) - if (existingHandle) { - const existingRecord = this.handles.get(existingHandle) - if ( - existingRecord && - existingRecord.rendererGraphEpoch === this.rendererGraphEpoch && - existingRecord.ptyId === leaf.ptyId && - existingRecord.ptyGeneration === leaf.ptyGeneration - ) { - return existingHandle - } - } - - const preAllocatedHandle = this.adoptPreAllocatedHandle(leaf) - if (preAllocatedHandle) { - return preAllocatedHandle + getTerminalHandleForPaneKey( + paneKey: string, + context?: TerminalIdentityReadContext + ): string | null { + const parsed = parsePaneKey(paneKey) + const leaf = parsed ? this.leaves.get(this.getLeafKey(parsed.tabId, parsed.leafId)) : undefined + if (leaf?.ptyId && leaf.connected) { + return this.issueHandle(leaf, context) } - const incarnationId = leaf.ptyId ? (this.ptysById.get(leaf.ptyId)?.incarnationId ?? null) : null - const retained = leaf.ptyId ? this.handleByPtyIncarnation.get(leaf.ptyId) : undefined - if (retained && leaf.ptyId && retained.incarnationId !== incarnationId) { - this.invalidatePtyIncarnationHandle(leaf.ptyId) - } else if (retained) { - this.bindPtyIncarnationHandle(retained, leaf) - return retained.handle + const panePty = this.getPtyRecordForPaneKey(paneKey, context) + if (panePty?.connected) { + return this.issuePtyHandle(panePty, context) } - const handle = `term_${randomUUID()}` - this.syntheticTerminalHandles.add(handle) - this.handles.set(handle, { - handle, - runtimeId: this.runtimeId, - rendererGraphEpoch: this.rendererGraphEpoch, - worktreeId: leaf.worktreeId, - tabId: leaf.tabId, - leafId: leaf.leafId, - ptyId: leaf.ptyId, - ptyGeneration: leaf.ptyGeneration - }) - this.handleByLeafKey.set(leafKey, handle) - if (leaf.ptyId) { - this.handleByPtyIncarnation.set(leaf.ptyId, { handle, incarnationId, leafKey }) + if (leaf?.ptyId) { + return this.issueHandle(leaf, context) } - return handle + return panePty ? this.issuePtyHandle(panePty, context) : null } } diff --git a/src/main/runtime/terminal/query/terminal-identity-read-context.test.ts b/src/main/runtime/terminal/query/terminal-identity-read-context.test.ts new file mode 100644 index 000000000000..2e2bf90d36f8 --- /dev/null +++ b/src/main/runtime/terminal/query/terminal-identity-read-context.test.ts @@ -0,0 +1,362 @@ +import { expect, it, vi } from 'vitest' +import '../../orca-runtime-test-mocks.spec' +import { createRuntime, TEST_WORKTREE_ID } from '../../orca-runtime-test-fixtures.spec' +import type { + RuntimeLeafRecord, + RuntimePtyWorktreeRecord +} from '../../runtime-terminal-state-records' +import type { + OrchestrationCompatibilitySshTerminal, + TerminalHandleRecord +} from '../../runtime-terminal-contracts' +import type { PtyIncarnationHandleRecord } from '../../orca-runtime-core' +import type { CrewChanges } from '../../orchestration/crew/crew-changes' +import type { RuntimeTerminalWaiterRegistry } from '../wait/terminal-waiter-registry' +import type { TerminalIdentityReadContext } from './terminal-identity-read-context' + +const LEAF = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' +const COLD = 'cold:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' +const PANE = `tab-original:${LEAF}` + +type Owner = { + terminalWaiters: RuntimeTerminalWaiterRegistry + crewChanges: CrewChanges + orchestrationCompatibilitySshTerminals: Map + getOrchestrationCompatibilitySshTerminal: ( + handle: string, + context?: TerminalIdentityReadContext + ) => OrchestrationCompatibilitySshTerminal | undefined + runtimeId: string + rendererGraphEpoch: number + handles: Map + handleByPtyId: Map + handleByLeafKey: Map + handleByPtyIncarnation: Map + syntheticTerminalHandles: Set + leaves: Map + ptysById: Map + recordPtyWorktree: ( + id: string, + worktree: string, + state?: Partial + ) => RuntimePtyWorktreeRecord + getLivePtyForHandle: ( + handle: string, + context?: TerminalIdentityReadContext + ) => { record: TerminalHandleRecord; pty: RuntimePtyWorktreeRecord } | null + getPtyRecordForPaneKey: ( + pane: string, + context?: TerminalIdentityReadContext + ) => RuntimePtyWorktreeRecord | null + beginGraphReload: (windowId: number) => number + findHandleForPtyRecord: (ptyId: string, context?: TerminalIdentityReadContext) => string | null + issueHandle: (leaf: RuntimeLeafRecord, context?: TerminalIdentityReadContext) => string + rejectWaitersForHandle: (handle: string, reason: string) => void +} + +function fixture() { + const runtime = createRuntime() + // SAFETY: this fixture exercises the existing protected map/effect owner with its production shapes. + const owner = runtime as unknown as Owner + const rejected = vi.spyOn(owner, 'rejectWaitersForHandle') + const add = (id: string, handle: string, paneKey = PANE, connected = true) => { + owner.recordPtyWorktree(id, TEST_WORKTREE_ID, { paneKey, connected }) + owner.handleByPtyId.set(id, handle) + } + const stamp = (handle: string, ptyId: string) => { + owner.handles.set(handle, { + handle, + runtimeId: owner.runtimeId, + rendererGraphEpoch: owner.rendererGraphEpoch, + worktreeId: TEST_WORKTREE_ID, + tabId: `pty:${ptyId}`, + leafId: `pty:${ptyId}`, + ptyId, + ptyGeneration: 0 + }) + } + const state = () => ({ + handles: [...owner.handles].map(([key, record]) => [ + key, + { ...record, runtimeId: '' } + ]), + reverse: [...owner.handleByPtyId], + leaf: [...owner.handleByLeafKey], + retained: [...owner.handleByPtyIncarnation].map(([key, value]) => [key, { ...value }]), + synthetic: [...owner.syntheticTerminalHandles], + rejected: rejected.mock.calls + }) + return { runtime, owner, add, stamp, state } +} + +it('matches separate production runtimes across reverse repair, stale first mapping, adoption and dependent reads in either order', () => { + for (const reverseOrder of [false, true]) { + for (const absentFirst of [false, true]) { + const baseline = fixture() + const candidate = fixture() + for (const f of [baseline, candidate]) { + f.owner.handleByPtyId.set('absent-first', 'term_shared') + if (!absentFirst) { + f.add('absent-first', 'term_shared', 'malformed-pane', false) + } + f.add('live-second', 'term_shared', 'repaired-second') + f.add('cold', 'term_cold', COLD) + f.stamp('term_cold', 'cold') + f.owner.handleByPtyId.delete('cold') + f.add('adopted', 'term_adopted', `tab-new:${LEAF}`) + f.runtime.attachWindow(1) + f.runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-new', + worktreeId: TEST_WORKTREE_ID, + title: 'Terminal', + activeLeafId: LEAF, + layout: null + } + ], + leaves: [ + { + tabId: 'tab-new', + worktreeId: TEST_WORKTREE_ID, + leafId: LEAF, + paneRuntimeId: 1, + ptyId: 'adopted' + } + ] + }) + // The production reload writer clears handle records while retaining CLI reverse mappings. + f.owner.beginGraphReload(1) + expect(f.owner.handles.has('term_adopted')).toBe(false) + f.stamp('term_cold', 'cold') + } + const context = candidate.runtime.createTerminalIdentityReadContext() + const read = (f: ReturnType, ctx?: TerminalIdentityReadContext) => { + const actions = [ + () => f.owner.getLivePtyForHandle('term_absent', ctx)?.pty.ptyId ?? null, + () => f.owner.getLivePtyForHandle('term_shared', ctx)?.pty.ptyId ?? null, + () => f.runtime.getTerminalHandleForPaneKey('repaired-second', ctx), + () => f.owner.getLivePtyForHandle('term_shared', ctx)?.pty.ptyId ?? null, + () => f.owner.getPtyRecordForPaneKey(PANE, ctx)?.ptyId ?? null, + () => f.runtime.getTerminalHandleForPaneKey(`tab-new:${LEAF}`, ctx), + () => f.owner.getLivePtyForHandle('term_adopted', ctx)?.pty.ptyId ?? null, + () => f.runtime.getTerminalHandleForPaneKey('malformed-pane', ctx) + ] + if (reverseOrder) { + actions.reverse() + } + const result = actions.map((action) => action()) + // Cold synthetic-record acquisition, then a lookup dependent on the owner's reverse-map write. + result.push(f.runtime.getTerminalHandleForPaneKey(COLD, ctx)) + result.push(f.owner.getLivePtyForHandle('term_cold', ctx)?.pty.ptyId ?? null) + return result + } + expect(read(candidate, context)).toEqual(read(baseline)) + expect(candidate.state()).toEqual(baseline.state()) + } + } +}) + +function countIterations( + map: Map, + counts: { entries: number; get: number; set: number; delete: number } +) { + for (const method of ['get', 'set', 'delete'] as const) { + const original = map[method].bind(map) + Object.defineProperty(map, method, { + configurable: true, + value: (...args: Parameters) => { + counts[method]++ + // SAFETY: this transparent fixture wrapper forwards the exact selected native Map method's arguments. + return (original as (...input: Parameters) => unknown)(...args) + } + }) + } + for (const method of ['entries', 'keys', 'values', Symbol.iterator] as const) { + const original = map[method].bind(map) + Object.defineProperty(map, method, { + configurable: true, + value: function* () { + for (const value of original()) { + counts.entries++ + yield value + } + } + }) + } +} + +it('charges actual native map visits at N/10N for missing, moved and cold identities and leaves fast hits lazy', () => { + const measure = (population: number, indexed: boolean, fast: boolean) => { + const f = fixture() + for (let i = 0; i < population; i++) { + const pane = `tab-${i}:aaaaaaaa-aaaa-4aaa-8aaa-${String(i).padStart(12, '0')}` + f.add(`pty-${i}`, `term_${i}`, pane) + f.stamp(`term_${i}`, `pty-${i}`) + } + const counts = { entries: 0, get: 0, set: 0, delete: 0 } + countIterations(f.owner.handles, counts) + countIterations(f.owner.handleByPtyId, counts) + countIterations(f.owner.leaves, counts) + countIterations(f.owner.ptysById, counts) + const context = indexed ? f.runtime.createTerminalIdentityReadContext() : undefined + for (let i = 0; i < population; i++) { + f.owner.getLivePtyForHandle(fast ? `term_${i}` : `term_missing_${i}`, context) + if (!fast) { + expect(f.owner.getPtyRecordForPaneKey(`missing-${i}:${LEAF}`, context)).toBeNull() + } + } + return counts + } + const baseline = [measure(3, false, false), measure(30, false, false)] + const candidate = [measure(3, true, false), measure(30, true, false)] + expect(baseline[1].entries).toBe(baseline[0].entries * 100) + expect(candidate[1].entries).toBe(candidate[0].entries * 10) + expect(measure(30, true, true).entries).toBe(0) + const cold = (population: number, indexed: boolean) => { + const f = fixture() + for (let i = 0; i < population; i++) { + f.add(`cold-${i}`, `term_cold_${i}`, `cold-pane-${i}`) + f.stamp(`term_cold_${i}`, `cold-${i}`) + f.owner.handleByPtyId.delete(`cold-${i}`) + } + const counts = { entries: 0, get: 0, set: 0, delete: 0 } + countIterations(f.owner.handles, counts) + countIterations(f.owner.ptysById, counts) + countIterations(f.owner.handleByPtyId, counts) + const context = indexed ? f.runtime.createTerminalIdentityReadContext() : undefined + for (let i = 0; i < population; i++) { + expect(f.runtime.getTerminalHandleForPaneKey(`cold-pane-${i}`, context)).toBe( + `term_cold_${i}` + ) + expect(f.owner.getLivePtyForHandle(`term_cold_${i}`, context)?.pty.ptyId).toBe(`cold-${i}`) + } + return counts + } + const coldBaseline = [cold(3, false), cold(30, false)] + const coldCandidate = [cold(3, true), cold(30, true)] + expect(coldBaseline[1].entries).toBeGreaterThan(coldBaseline[0].entries * 50) + expect(coldCandidate[1].entries).toBe(coldCandidate[0].entries * 10) + console.log('cold synthetic native operations', { + baseline: coldBaseline, + candidate: coldCandidate + }) + console.log('terminal acquisition native operations', { + baseline, + candidate, + fast: measure(30, true, true) + }) +}) + +it('invalidates actual SSH-held facts on register and finally-release with equal and conflicting claims', async () => { + const f = fixture() + const wake = vi.fn() + const stop = f.owner.crewChanges.subscribe(wake) + const terminal = { handle: 'term_ssh', paneKey: PANE, processIncarnation: 'remote-process' } + const first = f.runtime.registerOrchestrationCompatibilitySshAttachment('target', 'one', terminal) + const equal = f.runtime.registerOrchestrationCompatibilitySshAttachment('target', 'two', terminal) + expect(wake).toHaveBeenCalledTimes(2) + expect(f.runtime.getTerminalPaneKey(terminal.handle)).toBe(PANE) + const ctx = f.runtime.createTerminalIdentityReadContext() + expect(f.owner.getOrchestrationCompatibilitySshTerminal(terminal.handle, ctx)).toEqual(terminal) + expect(f.runtime.getTerminalProcessIncarnation(terminal.handle, ctx)).toBe('remote-process') + const conflict = f.runtime.registerOrchestrationCompatibilitySshAttachment( + 'other-target', + 'three', + terminal + ) + try { + // A changed source owns a fresh finite context; the old context is never retained as authority. + expect( + f.owner.getOrchestrationCompatibilitySshTerminal( + terminal.handle, + f.runtime.createTerminalIdentityReadContext() + ) + ).toBeUndefined() + expect(f.runtime.getTerminalPaneKey(terminal.handle)).toBeNull() + await Promise.resolve() + } finally { + f.runtime.releaseOrchestrationCompatibilitySshAttachment(conflict.attachmentId) + } + expect(f.runtime.getTerminalPaneKey(terminal.handle)).toBe(PANE) + f.runtime.releaseOrchestrationCompatibilitySshAttachment(first.attachmentId) + expect(f.runtime.getTerminalPaneKey(terminal.handle)).toBe(PANE) + f.runtime.releaseOrchestrationCompatibilitySshAttachment(equal.attachmentId) + expect(f.runtime.getTerminalPaneKey(terminal.handle)).toBeNull() + expect(wake).toHaveBeenCalledTimes(6) + f.runtime.releaseOrchestrationCompatibilitySshAttachment(equal.attachmentId) + expect(wake).toHaveBeenCalledTimes(6) + stop() +}) + +it('keeps cold candidates coherent through real retained-handle invalidation and waiter rejection', () => { + const run = (indexed: boolean) => { + const f = fixture() + f.add('retained-pty', 'term_retained', PANE) + f.runtime.attachWindow(1) + f.runtime.syncWindowGraph(1, { + tabs: [ + { + tabId: 'tab-original', + worktreeId: TEST_WORKTREE_ID, + title: 'Terminal', + activeLeafId: LEAF, + layout: null + } + ], + leaves: [ + { + tabId: 'tab-original', + worktreeId: TEST_WORKTREE_ID, + leafId: LEAF, + paneRuntimeId: 1, + ptyId: 'retained-pty' + } + ] + }) + const leaf = f.owner.leaves.get(`tab-original::${LEAF}`)! + f.owner.handleByLeafKey.clear() + f.owner.handleByPtyId.clear() + f.stamp('term_retained', 'retained-pty') + f.owner.syntheticTerminalHandles.add('term_retained') + f.owner.handleByPtyIncarnation.set('retained-pty', { + handle: 'term_retained', + incarnationId: 'old-process', + leafKey: `tab-original::${LEAF}` + }) + const context = indexed ? f.runtime.createTerminalIdentityReadContext() : undefined + expect(f.owner.findHandleForPtyRecord('retained-pty', context)).toBe('term_retained') + const waiterRejected = vi.fn() + f.owner.terminalWaiters.add({ + handle: 'term_retained', + condition: 'exit', + resolve: vi.fn(), + reject: waiterRejected, + timeout: null, + cancelIdlePoll: null, + abortCleanup: null + }) + const handle = f.owner.issueHandle(leaf, context) + expect(waiterRejected).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ message: 'terminal_handle_stale' }) + ) + expect(f.owner.terminalWaiters.get('term_retained')).toBeUndefined() + expect(handle).not.toBe('term_retained') + expect(f.owner.findHandleForPtyRecord('retained-pty', context)).toBeNull() + expect(f.owner.handles.has('term_retained')).toBe(false) + expect(f.owner.syntheticTerminalHandles.has('term_retained')).toBe(false) + expect(f.owner.handleByLeafKey.get(`tab-original::${LEAF}`)).toBe(handle) + expect(f.owner.handles.get(handle)?.ptyId).toBe('retained-pty') + expect(f.owner.handleByPtyIncarnation.get('retained-pty')?.handle).toBe(handle) + expect(f.owner.rejectWaitersForHandle).toHaveBeenCalledWith( + 'term_retained', + 'terminal_handle_stale' + ) + return { + retainedRemoved: !f.owner.handles.has('term_retained'), + synthetic: f.owner.syntheticTerminalHandles.size, + rejected: vi.mocked(f.owner.rejectWaitersForHandle).mock.calls + } + } + expect(run(true)).toEqual(run(false)) +}) diff --git a/src/main/runtime/terminal/query/terminal-identity-read-context.ts b/src/main/runtime/terminal/query/terminal-identity-read-context.ts new file mode 100644 index 000000000000..cac42e824b11 --- /dev/null +++ b/src/main/runtime/terminal/query/terminal-identity-read-context.ts @@ -0,0 +1,223 @@ +import { parsePaneKey } from '../../../../shared/stable-pane-id' +import type { + OrchestrationCompatibilitySshTerminal, + TerminalHandleRecord +} from '../../runtime-terminal-contracts' +import type { + RuntimeLeafRecord, + RuntimePtyWorktreeRecord +} from '../../runtime-terminal-state-records' +import type { PtyPane } from '../surface/pty-pane-query' + +type IdentitySources = { + handles: ReadonlyMap + reverse: ReadonlyMap + leaves: ReadonlyMap + ptys: ReadonlyMap + sshTerminals: ReadonlyMap + capturePaneOf: () => (pty: RuntimePtyWorktreeRecord) => PtyPane +} + +type OrderedKeys = Map + +/** Finite owner-read scratch: candidates retain source order; the existing getters select and repair. */ +export class TerminalIdentityReadContext { + private ssh: Map | undefined + private reverse: Map | undefined + private synthetic: Map | undefined + private leafKeys: Map | undefined + private panePtys: Map | undefined + private leafPtys: Map | undefined + private paneReader: ((pty: RuntimePtyWorktreeRecord) => PtyPane) | undefined + private readonly reverseOrder = new Map() + private readonly handleOrder = new Map() + private readonly reverseFacts = new Map() + private readonly handleFacts = new Map() + + constructor(private readonly source: IdentitySources) {} + + paneOf(pty: RuntimePtyWorktreeRecord): PtyPane { + this.paneReader ??= this.source.capturePaneOf() + return this.paneReader(pty) + } + + sshAttachmentIds(handle: string): Iterable { + if (!this.ssh) { + this.ssh = new Map() + for (const [id, terminal] of this.source.sshTerminals) { + const ids = this.ssh.get(terminal.handle) ?? [] + ids.push(id) + this.ssh.set(terminal.handle, ids) + } + } + return this.ssh.get(handle) ?? [] + } + + reversePtyIds(handle: string): readonly string[] { + if (!this.reverse) { + this.reverse = new Map() + for (const [ptyId, mapped] of this.source.reverse) { + this.reverseOrder.set(ptyId, this.reverseOrder.size) + this.reverseFacts.set(ptyId, mapped) + this.add(this.reverse, mapped, ptyId, this.reverseOrder.get(ptyId)!) + } + } + return this.ordered(this.reverse.get(handle)) + } + + syntheticHandles(ptyId: string): Iterable { + if (!this.synthetic) { + this.synthetic = new Map() + for (const [handle, record] of this.source.handles) { + this.handleOrder.set(handle, this.handleOrder.size) + this.indexHandle(handle, record) + } + } + return this.ordered(this.synthetic.get(ptyId)) + } + + leavesForId(leafId: string): Iterable { + if (!this.leafKeys) { + this.leafKeys = new Map() + for (const [key, leaf] of this.source.leaves) { + const keys = this.leafKeys.get(leaf.leafId) ?? [] + keys.push(key) + this.leafKeys.set(leaf.leafId, keys) + } + } + return this.leafKeys.get(leafId) ?? [] + } + + ptysForPane(paneKey: string): Iterable { + if (!this.panePtys) { + this.panePtys = new Map() + this.leafPtys = new Map() + let order = 0 + for (const [ptyId, pty] of this.source.ptys) { + const pane = this.paneOf(pty).paneKey + if (pane !== null) { + this.add(this.panePtys, pane, ptyId, order) + const parsed = parsePaneKey(pane) + if (parsed) { + this.add(this.leafPtys, parsed.leafId, ptyId, order) + } + } + order++ + } + } + const exact = this.panePtys.get(paneKey) + const parsed = parsePaneKey(paneKey) + const suffix = parsed ? this.leafPtys?.get(parsed.leafId) : undefined + return this.ordered(new Map([...(exact ?? []), ...(suffix ?? [])])) + } + + /** Only keys written by the issuing owner are reconciled; no inventory rebuild follows repair. */ + changedReverseBinding(ptyId: string): void { + if (!this.reverse) { + return + } + const prior = this.reverseFacts.get(ptyId) + if (prior !== undefined) { + this.reverse.get(prior)?.delete(ptyId) + } + const handle = this.source.reverse.get(ptyId) + if (handle !== undefined) { + if (!this.reverseOrder.has(ptyId)) { + this.reverseOrder.set(ptyId, this.reverseOrder.size) + } + this.add(this.reverse, handle, ptyId, this.reverseOrder.get(ptyId)!) + this.reverseFacts.set(ptyId, handle) + } else { + this.reverseFacts.delete(ptyId) + } + } + + changedHandle(handle: string): void { + if (!this.synthetic) { + return + } + const prior = this.handleFacts.get(handle) + if (prior !== undefined) { + this.synthetic.get(prior)?.delete(handle) + this.handleFacts.delete(handle) + } + const record = this.source.handles.get(handle) + if (record) { + if (!this.handleOrder.has(handle)) { + this.handleOrder.set(handle, this.handleOrder.size) + } + this.indexHandle(handle, record) + } + } + + private indexHandle(handle: string, record: TerminalHandleRecord): void { + if (record.ptyId && record.tabId.startsWith('pty:')) { + this.add(this.synthetic!, record.ptyId, handle, this.handleOrder.get(handle)!) + this.handleFacts.set(handle, record.ptyId) + } + } + + private add(index: Map, key: string, value: string, order: number): void { + const bucket = index.get(key) ?? new Map() + bucket.set(value, order) + index.set(key, bucket) + } + + private ordered(keys: OrderedKeys | undefined): string[] { + return [...(keys ?? [])].sort((a, b) => a[1] - b[1]).map(([key]) => key) + } +} + +export function ptyRecordForPaneKey( + paneKey: string, + source: { + leaves: ReadonlyMap + ptys: ReadonlyMap + leafKey: (tab: string, leaf: string) => string + paneOf: (pty: RuntimePtyWorktreeRecord) => PtyPane + }, + context?: TerminalIdentityReadContext +): RuntimePtyWorktreeRecord | null { + const parsed = parsePaneKey(paneKey) + let leafPty: RuntimePtyWorktreeRecord | null = null + if (parsed) { + const leaf = source.leaves.get(source.leafKey(parsed.tabId, parsed.leafId)) + const pty = leaf?.ptyId ? source.ptys.get(leaf.ptyId) : undefined + if (pty?.connected) { + return pty + } + leafPty = pty ?? null + const candidates = context ? context.leavesForId(parsed.leafId) : source.leaves.keys() + for (const key of candidates) { + const candidate = source.leaves.get(key) + if (!candidate) { + continue + } + if (candidate.leafId !== parsed.leafId || !candidate.ptyId) { + continue + } + const remintedPty = source.ptys.get(candidate.ptyId) + if (remintedPty?.connected) { + return remintedPty + } + leafPty ??= remintedPty ?? null + } + } + let newestMatch: RuntimePtyWorktreeRecord | null = null + const candidates = context ? context.ptysForPane(paneKey) : source.ptys.keys() + for (const ptyId of candidates) { + const pty = source.ptys.get(ptyId) + if (!pty) { + continue + } + const recordedPaneKey = (context ? context.paneOf(pty) : source.paneOf(pty)).paneKey + const ptyPane = parsePaneKey(recordedPaneKey ?? '') + if (recordedPaneKey === paneKey || (parsed && ptyPane && parsed.leafId === ptyPane.leafId)) { + if (pty.connected) { + return pty + } + newestMatch = pty + } + } + return leafPty ?? newestMatch +} diff --git a/src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts b/src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts new file mode 100644 index 000000000000..fdd1fee77acf --- /dev/null +++ b/src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts @@ -0,0 +1,81 @@ +import { expect, it, vi } from 'vitest' +import { getDefaultSettings, getDefaultWorkspaceSession } from '../../../../shared/constants' +import { loadWorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-load' +import { nameBasedLoadContext } from '../../../../shared/workspace-layout/workspace-layout-minted-ids' +import { toRemoteRuntimePtyId } from '../../../../shared/remote-runtime/remote-runtime-pty-id' +import { mainTerminalSurfaces, type MainTerminalSurfacesHost } from './main-terminal-surfaces' + +vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true })) + +function fixture(population: number) { + const session = getDefaultWorkspaceSession() + const registered = new Map() + const ids = Array.from({ length: population }, (_, i) => + i === 0 ? toRemoteRuntimePtyId('term_foreign', 'paired') : `pty-${i}` + ) + for (const [i, ptyId] of ids.entries()) { + const worktree = i % 2 === 0 ? 'folder:notes' : 'repo::/tmp/worktree' + const tabId = `tab-${i}` + const leafId = `aaaaaaaa-aaaa-4aaa-8aaa-${String(i).padStart(12, '0')}` + session.tabsByWorktree[worktree] = [ + ...(session.tabsByWorktree[worktree] ?? []), + { + id: tabId, + worktreeId: worktree, + ptyId, + title: 'Terminal', + customTitle: null, + color: null, + sortOrder: i, + createdAt: 1 + } + ] + session.terminalLayoutsByTabId[tabId] = { + root: { type: 'leaf', leafId }, + activeLeafId: leafId, + expandedLeafId: null, + ptyIdsByLeafId: { [leafId]: ptyId } + } + if (i !== 0) { + registered.set(ptyId, { worktreeId: worktree, incarnationId: null }) + } + } + const loaded = loadWorkspaceLayout('local', session, nameBasedLoadContext()) + const partition = vi.fn(() => loaded) + const host: MainTerminalSurfacesHost = { + store: () => ({ + getWorkspaceSessionHostIds: () => ['local'], + getSettings: () => getDefaultSettings('/tmp/crew-main-capture') + }), + reads: () => ({ readPartition: partition, onLayoutOperationCommitted: () => () => {} }), + homeHostId: () => 'local', + registered: (id) => registered.get(id) ?? null, + exited: () => false, + live: () => true, + paneStartFact: () => null, + readyGraphPublisher: () => null, + publish: () => {}, + heldRows: () => new Map(), + replaceHeldRows: () => {}, + fenceExited: (rows) => rows + } + return { owner: mainTerminalSurfaces({}, () => host), partition, registered, ids } +} + +it('captures real main partitions once and keeps paired/local/folder qualification and source ordering', () => { + for (const population of [3, 30]) { + const baseline = fixture(population) + const candidate = fixture(population) + const captured = candidate.owner.capturePaneLookup() + for (const id of candidate.ids) { + expect(captured(id)).toEqual(baseline.owner.findPaneForPty(id)) + } + expect(candidate.partition).toHaveBeenCalledTimes(1) + expect(baseline.partition).toHaveBeenCalledTimes(population) + candidate.registered.get('pty-1')!.worktreeId = 'other-workspace' + expect(captured('pty-1')).not.toBeNull() + expect(candidate.owner.capturePaneLookup()('pty-1')).toBeNull() + expect(captured(candidate.ids[0])).not.toBeNull() + console.log('main partition acquisitions', { population, baseline: population, candidate: 1 }) + } +}) diff --git a/src/main/runtime/terminal/surface/main-terminal-surfaces.ts b/src/main/runtime/terminal/surface/main-terminal-surfaces.ts index c250516d7c32..cfa86ff6238c 100644 --- a/src/main/runtime/terminal/surface/main-terminal-surfaces.ts +++ b/src/main/runtime/terminal/surface/main-terminal-surfaces.ts @@ -1,3 +1,4 @@ +import { captureMainTerminalPaneLookup, findMainTerminalPane } from './pty-pane-query' // Publish main-owned workspace panes from Store layout changes, even without a window graph. import type { PaneStartFactOf } from '../../pane-start-statuses' @@ -14,8 +15,6 @@ import type { RuntimeStore } from '../../runtime-store-contract' import type { WorkspaceLayoutReads } from '../../workspace-layout-stream' import { composeMainTerminalSurfaces, - pairedRuntimeHostOfBinding, - terminalHoldsPane, TerminalSurfaceIndex, type BoundTerminal, type MainTerminalSurfaces @@ -120,17 +119,13 @@ class MainSurfacePublisher { findPaneForPty(ptyId: string): { worktreeId: string; tabId: string; leafId: string } | null { const surfaces = this.index.surfaces() const terminal = this.host.registered(ptyId) - const pane = surfaces.leaves.find( - (leaf) => - leaf.ptyId === ptyId && - (pairedRuntimeHostOfBinding(ptyId) !== null || - terminalHoldsPane( - terminal, - leaf, - surfaces.paneFacts.get(`${leaf.tabId}::${leaf.leafId}`) - )) - ) - return pane ? { worktreeId: pane.worktreeId, tabId: pane.tabId, leafId: pane.leafId } : null + return findMainTerminalPane(ptyId, surfaces.leaves, surfaces.paneFacts, terminal) + } + + capturePaneLookup(): ( + ptyId: string + ) => { worktreeId: string; tabId: string; leafId: string } | null { + return captureMainTerminalPaneLookup(this.index.surfaces(), this.host.registered) } /** Return the main-owned binding; start/failure/sleep status prevents treating its stored terminal as live. */ diff --git a/src/main/runtime/terminal/surface/pty-pane-query.ts b/src/main/runtime/terminal/surface/pty-pane-query.ts index d1963246d8b4..d2d8ea259432 100644 --- a/src/main/runtime/terminal/surface/pty-pane-query.ts +++ b/src/main/runtime/terminal/surface/pty-pane-query.ts @@ -1,3 +1,9 @@ +import { + pairedRuntimeHostOfBinding, + terminalHoldsPane, + type MainTerminalSurfaces, + type BoundTerminal +} from './terminal-surface-index' // Read pane copies only in the window-owned branch; main-owned builds use layout alone. Delete these copies with the legacy branch (L80). import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' @@ -54,3 +60,44 @@ export function paneOfPty( recordedAtGraphSequence: pty.surfaceRecordedAtGraphSequence ?? 0 } } + +export function captureMainTerminalPaneLookup( + surfaces: MainTerminalSurfaces, + registered: (ptyId: string) => BoundTerminal | null +): (ptyId: string) => { worktreeId: string; tabId: string; leafId: string } | null { + const candidates = new Map() + const terminals = new Map() + const facts = new Map([...surfaces.paneFacts].map(([key, value]) => [key, { ...value }])) + for (const leaf of surfaces.leaves) { + if (!leaf.ptyId) { + continue + } + const bucket = candidates.get(leaf.ptyId) ?? [] + bucket.push({ ...leaf }) + candidates.set(leaf.ptyId, bucket) + if (!terminals.has(leaf.ptyId)) { + const terminal = registered(leaf.ptyId) + terminals.set( + leaf.ptyId, + terminal ? { worktreeId: terminal.worktreeId, incarnationId: terminal.incarnationId } : null + ) + } + } + return (ptyId) => + findMainTerminalPane(ptyId, candidates.get(ptyId) ?? [], facts, terminals.get(ptyId) ?? null) +} + +export function findMainTerminalPane( + ptyId: string, + leaves: MainTerminalSurfaces['leaves'], + facts: MainTerminalSurfaces['paneFacts'], + terminal: BoundTerminal | null +): { worktreeId: string; tabId: string; leafId: string } | null { + const pane = leaves.find( + (leaf) => + leaf.ptyId === ptyId && + (pairedRuntimeHostOfBinding(ptyId) !== null || + terminalHoldsPane(terminal, leaf, facts.get(`${leaf.tabId}::${leaf.leafId}`))) + ) + return pane ? { worktreeId: pane.worktreeId, tabId: pane.tabId, leafId: pane.leafId } : null +} diff --git a/src/main/runtime/terminal/wait/terminal-interactive-wait.ts b/src/main/runtime/terminal/wait/terminal-interactive-wait.ts index e81d5fe5b941..c23b829f9dc0 100644 --- a/src/main/runtime/terminal/wait/terminal-interactive-wait.ts +++ b/src/main/runtime/terminal/wait/terminal-interactive-wait.ts @@ -1,5 +1,5 @@ +import type { TerminalIdentityReadContext } from '../query/terminal-identity-read-context' import { getRepoRoutingConnectionId } from '../../../../shared/execution-host' -import { resolveStructuredWorkerAuthority } from '../../structured-worker-authority' import { OrcaRuntimeWithAdoptTerminalOrphansFromInventory } from '../adoption/adopt-terminal-orphans-from-inventory' import type { RuntimeTerminalAgentStatus, @@ -63,7 +63,10 @@ export abstract class OrcaRuntimeWithGetTerminalInteractiveWait extends OrcaRunt protected abstract getLeafKey(tabId: string, leafId: string): string - protected abstract getPtyRecordForPaneKey(paneKey: string): RuntimePtyWorktreeRecord | null + protected abstract getPtyRecordForPaneKey( + paneKey: string, + context?: TerminalIdentityReadContext + ): RuntimePtyWorktreeRecord | null protected abstract getOrchestrationDbIfAvailable(): OrchestrationDb | null @@ -169,27 +172,6 @@ export abstract class OrcaRuntimeWithGetTerminalInteractiveWait extends OrcaRunt } } - getTerminalProcessIncarnation(handle: string): string | null { - const structured = resolveStructuredWorkerAuthority( - handle, - this.getOrchestrationDbIfAvailable?.() ?? null - ) - if (structured) { - return structured.identity.processIncarnation - } - const live = this.getLivePtyForHandle(handle) - const record = live?.record ?? this.handles.get(handle) - if (!record?.ptyId) { - return this.getOrchestrationCompatibilitySshTerminal(handle)?.processIncarnation ?? null - } - const incarnationId = live?.pty.incarnationId ?? this.ptysById.get(record.ptyId)?.incarnationId - if (incarnationId) { - return `${record.ptyId}:${incarnationId}` - } - // Why: legacy providers may omit process incarnation; retain the prior restart-degraded fence. - return `${this.runtimeId}:${record.ptyId}:${record.ptyGeneration}` - } - getExactWorkerProviderSession( handle: string, observedAfter: number From 6bc231a9b33c030fd9cfa1987bb594402da2abc3 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:16:25 -0700 Subject: [PATCH 026/164] Share raw crew identity inputs through scoped production readers --- .../agent-session-store-transactions.test.ts | 2 +- .../construction/runtime-service-state.ts | 48 +- ...chestration-fleet-agent-status-snapshot.ts | 37 ++ .../crew/crew-cli-addresses.test.ts | 16 +- .../crew/crew-host-derivation.ts | 5 +- .../crew/crew-identity-inputs.ts | 3 + .../crew/crew-mutation-notifications.ts | 28 +- .../crew/crew-parent-rpc.test.ts | 5 +- .../orchestration/crew/crew-parties.ts | 15 +- .../orchestration/crew/crew-party-snapshot.ts | 21 +- .../crew/crew-read-model-performance.test.ts | 2 +- .../orchestration/crew/crew-read-model.ts | 14 +- .../orchestration/crew/crew-runtime-watch.ts | 49 +- ...ctured-session-lineage-acquisition.test.ts | 327 +++++++++++++ .../structured-session-lineage.ts | 94 ++++ .../terminal-pane-mail-routing.ts | 9 + .../runtime-orchestration-crew-names.test.ts | 6 + .../runtime-orchestration-sender-names.ts | 11 +- .../session-graph-reload-lifecycle.ts | 1 + .../runtime/structured-worker-authority.ts | 76 ++- src/main/runtime/structured-worker-custody.ts | 38 +- .../adopt-terminal-orphans-from-inventory.ts | 7 +- .../terminal/identity/pty-worktree-record.ts | 38 ++ .../identity/terminal-handle-bindings.ts | 43 ++ .../lifecycle/floating-session-liveness.ts | 12 +- .../terminal/lifecycle/pty-exit-lifecycle.ts | 4 + .../lifecycle/pty-handle-invalidation.ts | 9 + .../terminal/output/pty-output-ingestion.ts | 4 + .../terminal-orchestration-authority.ts | 49 +- .../terminal/query/pty-terminal-summary.ts | 26 +- .../terminal-identity-read-context.test.ts | 462 +++++++++++++++++- .../query/terminal-identity-read-context.ts | 243 ++++++--- .../surface/main-terminal-acquisition.test.ts | 160 ++++++ .../terminal/surface/pty-pane-query.ts | 53 ++ .../automation-operations.ts | 5 +- 35 files changed, 1730 insertions(+), 192 deletions(-) create mode 100644 src/main/runtime/orchestration/structured-session-lineage-acquisition.test.ts diff --git a/src/main/runtime/agent-session-store-transactions.test.ts b/src/main/runtime/agent-session-store-transactions.test.ts index 1368c2f8a122..b4e6cfaf38cd 100644 --- a/src/main/runtime/agent-session-store-transactions.test.ts +++ b/src/main/runtime/agent-session-store-transactions.test.ts @@ -289,7 +289,7 @@ it.each([3, 30])( const stops = [db.crewChanges.subscribe(wake), sessionCrewChanges.subscribe(wake)] return () => stops.forEach((stop) => stop()) }) - const publications = Array.from({ length: population }, () => [] as OrchestrationCrewFrame[]) + const publications = Array.from({ length: population }, (): OrchestrationCrewFrame[] => []) const stops = publications.map((frames, i) => subscribeCrew( () => model.read(i === 0 ? 'term_coord' : `orca_session_id:chat-empty-${i}`), diff --git a/src/main/runtime/construction/runtime-service-state.ts b/src/main/runtime/construction/runtime-service-state.ts index 3a930d7d382d..d102236adbcd 100644 --- a/src/main/runtime/construction/runtime-service-state.ts +++ b/src/main/runtime/construction/runtime-service-state.ts @@ -1,3 +1,4 @@ +import { readAgentOrchestrationProjectionRecords } from '../orchestration-fleet-agent-status-snapshot' import { CrewChanges } from '../orchestration/crew/crew-changes' import { OrchestrationStructuredMailboxPointerDelivery } from '../orchestration/structured-mailbox-pointer-delivery' @@ -24,6 +25,7 @@ import type { EmulatorBridge } from '../../emulator/emulator-bridge' import { RuntimeResolvedWorktreeCache } from '../runtime-resolved-worktree-cache' import { RuntimeWorktreeLineageController } from '../runtime-worktree-lineage-controller' import { RuntimeAgentOrchestrationProjection } from '../runtime-agent-orchestration-projection' +import type { RuntimeAgentOrchestrationDependencies } from '../runtime-agent-orchestration-projection' import { RuntimeTerminalList } from '../runtime-terminal-list' import { RuntimeManagedWorktreeQueries } from '../runtime-managed-worktree-queries' import { RuntimePtyForegroundAgent } from '../runtime-pty-foreground-agent' @@ -45,9 +47,8 @@ import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../shared/layout-owner-switch' import { mainListsEveryPane } from '../terminal/surface/main-terminal-surfaces' import { TUI_IDLE_QUIESCENCE_MS } from '../orca-runtime-postlude' import { screenClearsBlockedTail } from '../blocked-tail-screen-clear' -import { conversationRecordReader } from '../orchestration/structured-session-lineage' -import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/structured-agent-session-registry' -import { peekOpenedAgentSessionRecordStore } from '../agent-session-record-store-slot' + +type ProjectionRead = Partial export abstract class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWithRuntimeId { protected readonly stopRequestedPtyIds = new Set() @@ -116,25 +117,28 @@ export abstract class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWith showTerminal: (handle) => this.showTerminal(handle) }) - protected readonly agentOrchestrationProjection = new RuntimeAgentOrchestrationProjection({ - getDb: () => this.getOrchestrationDbIfAvailable(), - getLeaves: () => this.leaves.values(), - getPtys: () => this.ptysById.values(), - paneOf: (pty) => this.paneOfPty(pty), - issueLeafHandle: (leaf) => this.issueHandle(leaf), - issuePtyHandle: (pty) => this.issuePtyHandle(pty), - makePaneKey: (leaf) => this.makeRuntimePaneKey(leaf), - getWorktreeId: (handle) => this.getTerminalWorktreeIdForHandle(handle), - getHandleForPaneKey: (paneKey) => this.getTerminalHandleForPaneKey(paneKey), - getPaneKey: (handle) => this.getPaneKeyForTerminalHandle(handle), - getDispatchAuthority: (handle) => this.getOrchestrationDispatchAuthority(handle), - getAgentStatusSnapshot: () => this.getOrchestrationFleetAgentStatusSnapshot(), - getSessionRecords: () => { - const store = - getStructuredAgentSessionHost()?.deps.store ?? peekOpenedAgentSessionRecordStore() - return store ? conversationRecordReader(store) : null - } - }) + protected agentOrchestrationDependencies(bound?: ProjectionRead) { + return { + getDb: () => this.getOrchestrationDbIfAvailable(), + getLeaves: () => this.leaves.values(), + getPtys: () => this.ptysById.values(), + paneOf: (pty) => this.paneOfPty(pty), + issueLeafHandle: (leaf) => this.issueHandle(leaf), + issuePtyHandle: (pty) => this.issuePtyHandle(pty), + makePaneKey: (leaf) => this.makeRuntimePaneKey(leaf), + getWorktreeId: (handle) => this.getTerminalWorktreeIdForHandle(handle), + getHandleForPaneKey: (paneKey) => this.getTerminalHandleForPaneKey(paneKey), + getPaneKey: (handle) => this.getPaneKeyForTerminalHandle(handle), + getDispatchAuthority: (handle) => this.getOrchestrationDispatchAuthority(handle), + getAgentStatusSnapshot: () => this.getOrchestrationFleetAgentStatusSnapshot(), + getSessionRecords: () => readAgentOrchestrationProjectionRecords(), + ...bound + } satisfies RuntimeAgentOrchestrationDependencies + } + + protected readonly agentOrchestrationProjection = new RuntimeAgentOrchestrationProjection( + this.agentOrchestrationDependencies() + ) protected readonly terminalList = new RuntimeTerminalList({ getGraphEpoch: () => (this.graphStatus === 'ready' ? this.rendererGraphEpoch : null), diff --git a/src/main/runtime/orchestration-fleet-agent-status-snapshot.ts b/src/main/runtime/orchestration-fleet-agent-status-snapshot.ts index 34382a61e62b..84f141bdaec9 100644 --- a/src/main/runtime/orchestration-fleet-agent-status-snapshot.ts +++ b/src/main/runtime/orchestration-fleet-agent-status-snapshot.ts @@ -1,3 +1,12 @@ +import type { TerminalIdentityReadContext } from './terminal/query/terminal-identity-read-context' +import { conversationRecordReader } from './orchestration/structured-session-lineage' +import { getStructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-registry' +import { peekOpenedAgentSessionRecordStore } from './agent-session-record-store-slot' +import { + RuntimeAgentOrchestrationProjection, + type RuntimeAgentOrchestrationDependencies +} from './runtime-agent-orchestration-projection' +import { createOrchestrationProjectionScope } from './runtime-agent-orchestration-scope' import type { AgentStatusIpcPayload } from '../../shared/agent-status-ipc-payload' import type { FleetAgentStatusEvidence } from '../../shared/orchestration-fleet-agent-status-evidence' import { @@ -24,3 +33,31 @@ export function readOrchestrationFleetAgentStatusSnapshot( ) ) } + +export function readCapturedOrchestrationFleetAgentStatusSnapshot( + source: Omit, + dependencies: RuntimeAgentOrchestrationDependencies +): readonly FleetAgentStatusEvidence[] { + const projection = new RuntimeAgentOrchestrationProjection(dependencies) + let scope: ReturnType | undefined + return readOrchestrationFleetAgentStatusSnapshot({ + ...source, + getAgentStatusOrchestrationContextForPaneKey: (paneKey) => { + const handle = source.getAgentStatusTerminalHandleForPaneKey?.(paneKey) + if (!handle) { + return undefined + } + const db = dependencies.getDb() + scope ??= createOrchestrationProjectionScope(db, dependencies) + return projection.getForHandle(handle, db, { paneKey }, scope) + } + }) +} + +export function readAgentOrchestrationProjectionRecords(context?: TerminalIdentityReadContext) { + const read = () => { + const store = getStructuredAgentSessionHost()?.deps.store ?? peekOpenedAgentSessionRecordStore() + return store ? conversationRecordReader(store) : null + } + return context ? context.captureProjectionRecords(read) : read() +} diff --git a/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts b/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts index 8539eb5b2977..e9ab331b0d98 100644 --- a/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts +++ b/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts @@ -136,15 +136,14 @@ it('executes snapshot addresses through CLI send and the dispatcher into the pro ]) ) const client = new RuntimeClient('/tmp/crew-address-client', 1000, null, null) - vi.spyOn(client, 'call').mockImplementation(async (method: string, params: unknown) => { + 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) } - // SAFETY: the real dispatcher validates each method's result; this is only the in-memory transport boundary. - return { ...response, result: response.result as T, _meta: { runtimeId: 'crew-test' } } + return { ...response, result: response.result, _meta: { runtimeId: 'crew-test' } } }) for (const to of addresses) { await dispatch(['orchestration', 'send'], { @@ -300,9 +299,14 @@ it('keeps crew as the only observer for title, settings and mirrored-name source selection.mockClear() names.mockClear() // RuntimeClientEventBus is the real production filter. Crew is its only enrolled consumer. - // SAFETY: the protected method is this class's client-event publication boundary, exercised without OS input. - const events = runtime as unknown as { - emitClientEvent(event: RuntimeClientEvent): void + const publish: unknown = Reflect.get(runtime, 'emitClientEvent') + if (typeof publish !== 'function') { + throw new Error('Missing runtime client-event publication boundary') + } + const events = { + emitClientEvent: (event: RuntimeClientEvent): void => { + Reflect.apply(publish, runtime, [event]) + } } events.emitClientEvent({ type: 'terminalSideEffects', diff --git a/src/main/runtime/orchestration/crew/crew-host-derivation.ts b/src/main/runtime/orchestration/crew/crew-host-derivation.ts index 18016cdaa3fb..32c1cb31bdff 100644 --- a/src/main/runtime/orchestration/crew/crew-host-derivation.ts +++ b/src/main/runtime/orchestration/crew/crew-host-derivation.ts @@ -11,7 +11,10 @@ import type { CrewReadDependencies } from './crew-read-model' export function createCrewHostDerivation(deps: CrewReadDependencies, now: number) { const { statuses, ...sources } = captureCrewIdentityInputs(deps) const registry = createCrewPartyRegistry({ ...sources, statuses }) - const { party, alias } = registry + const { alias } = registry + const identity = deps.openIdentityRead?.() + const party: typeof registry.party = (session, handle, pane, fallback, process) => + registry.party(session, handle, pane, fallback, process, identity) const selected = (rows: CrewAssignmentRow[]) => rows.sort( (a, b) => diff --git a/src/main/runtime/orchestration/crew/crew-identity-inputs.ts b/src/main/runtime/orchestration/crew/crew-identity-inputs.ts index 06212617d480..9d98a20e028c 100644 --- a/src/main/runtime/orchestration/crew/crew-identity-inputs.ts +++ b/src/main/runtime/orchestration/crew/crew-identity-inputs.ts @@ -3,6 +3,9 @@ import type { CrewReadDependencies } from './crew-read-model' /** Capture each runtime identity fact once in the host input generation, including absent facts. */ export function captureCrewIdentityInputs(deps: CrewReadDependencies): CrewReadDependencies { const { statuses, ...sources } = deps + if (deps.openIdentityRead) { + return { ...sources, statuses: structuredClone(statuses) } + } const capture = (read: (key: string) => T) => { const facts = new Map() return (key: string): T => { diff --git a/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts b/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts index 45ed448daa8f..7d161cd284dc 100644 --- a/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts +++ b/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts @@ -79,10 +79,15 @@ const trafficMutations: ReadonlySet = new Set([ /** Wake after the synchronous outer mutation; nested writes coalesce and rolled-back reads compare equal. */ export function attachCrewMutationNotifications(ctor: { prototype: object }): void { - // SAFETY: the database installer invokes this after installing the domain methods. - const prototype = ctor.prototype as OrchestrationDb + const prototype = ctor.prototype + if ( + !hasDomainMethod(prototype, 'getOrCreateLocalMutationCallerFingerprint') || + !hasDomainMethod(prototype, 'insertMessage') + ) { + throw new Error('Crew notifications require installed orchestration methods') + } const sourceIdentity = prototype.getOrCreateLocalMutationCallerFingerprint - prototype.getOrCreateLocalMutationCallerFingerprint = function () { + prototype.getOrCreateLocalMutationCallerFingerprint = function (this: OrchestrationDb) { const known = this.localMutationCallerFingerprint const result = sourceIdentity.call(this) if (!known) { @@ -91,7 +96,7 @@ export function attachCrewMutationNotifications(ctor: { prototype: object }): vo return result } const insert = prototype.insertMessage - prototype.insertMessage = function (message) { + prototype.insertMessage = function (this: OrchestrationDb, message) { const result = insert.call(this, message) if (result.type !== 'heartbeat') { this.crewChanges.notify(new Set(['traffic'])) @@ -99,17 +104,15 @@ export function attachCrewMutationNotifications(ctor: { prototype: object }): vo return result } for (const name of mutations) { - const original = prototype[name] - if (typeof original !== 'function') { + if (!hasDomainMethod(prototype, name)) { continue } + const original = prototype[name] Object.defineProperty(ctor.prototype, name, { configurable: true, writable: true, value(this: OrchestrationDb, ...args: unknown[]) { - const invoke: (...values: never[]) => unknown = original - // SAFETY: the wrapper forwards the unmodified arguments to the selected domain method. - const result = invoke.apply(this, args as never[]) + const result: unknown = Reflect.apply(original, this, args) if ( typeof result === 'object' && result !== null && @@ -125,3 +128,10 @@ export function attachCrewMutationNotifications(ctor: { prototype: object }): vo }) } } + +function hasDomainMethod( + prototype: object, + name: K +): prototype is object & Pick { + return name in prototype && typeof Reflect.get(prototype, name) === 'function' +} diff --git a/src/main/runtime/orchestration/crew/crew-parent-rpc.test.ts b/src/main/runtime/orchestration/crew/crew-parent-rpc.test.ts index 09e15fbcd1b5..31b1647bda8a 100644 --- a/src/main/runtime/orchestration/crew/crew-parent-rpc.test.ts +++ b/src/main/runtime/orchestration/crew/crew-parent-rpc.test.ts @@ -89,17 +89,16 @@ it('composes actual local and paired RPC claims in either order and preserves de parents.find((row) => row.sendAddress === 'run:run_remote_home')?.openTarget ).toBeUndefined() const client = new RuntimeClient('/tmp/crew-parent-routing', 1000, null, null) - vi.spyOn(client, 'call').mockImplementation(async (method: string, params: unknown) => { + 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) } - // SAFETY: the real dispatcher validates the result; only the in-memory CLI transport is substituted. return { ...response, - result: response.result as T, + result: response.result, _meta: { runtimeId: 'crew-parent-test' } } }) diff --git a/src/main/runtime/orchestration/crew/crew-parties.ts b/src/main/runtime/orchestration/crew/crew-parties.ts index b0876adf81da..bb1057033e28 100644 --- a/src/main/runtime/orchestration/crew/crew-parties.ts +++ b/src/main/runtime/orchestration/crew/crew-parties.ts @@ -7,6 +7,7 @@ import { import { isPublicOrchestrationAddress } from '../../../../shared/orchestration-agent-reference' import { createCanonicalSessionPaneResolver, clearedInto } from '../structured-session-lineage' import type { CrewReadDependencies } from './crew-read-model' +import type { CrewIdentityRead } from './crew-party-snapshot' export type Party = AgentMessageSender['party'] & { paneKey: string | null } @@ -63,7 +64,7 @@ export function createCrewPartyRegistry(deps: CrewReadDependencies) { } : null const canonicalPane = createCanonicalSessionPaneResolver(records) - const build = (base?: CrewPartyLookup) => { + const build = (base?: CrewPartyLookup, identity?: CrewIdentityRead) => { const parties = new Map() const aliases = new Map() const aliasesByParty = new Map>() @@ -85,13 +86,15 @@ export function createCrewPartyRegistry(deps: CrewReadDependencies) { storedHandle: string | null, pane: string | null, fallback?: string, - process?: string | null + process?: string | null, + read?: CrewIdentityRead ): Party | undefined => { + const inputs = read ?? identity ?? deps.openIdentityRead?.() ?? deps const sessionId = session ? root(session) : null - const liveHandle = pane ? deps.handleForPane(pane) : null + const liveHandle = pane ? inputs.handleForPane(pane) : null const candidateHandle = - liveHandle ?? (storedHandle && deps.liveHandle(storedHandle) ? storedHandle : null) - const currentProcess = candidateHandle ? deps.processForHandle?.(candidateHandle) : null + liveHandle ?? (storedHandle && inputs.liveHandle(storedHandle) ? storedHandle : null) + const currentProcess = candidateHandle ? inputs.processForHandle?.(candidateHandle) : null const mismatch = Boolean(process && currentProcess && process !== currentProcess) const handle = mismatch ? null : candidateHandle const publicHandle = handle?.startsWith('term_') ? handle : null @@ -141,7 +144,7 @@ export function createCrewPartyRegistry(deps: CrewReadDependencies) { alias, party, records, - fork: () => build(lookup) + fork: (identity?: CrewIdentityRead) => build(lookup, identity) } } return build() diff --git a/src/main/runtime/orchestration/crew/crew-party-snapshot.ts b/src/main/runtime/orchestration/crew/crew-party-snapshot.ts index e485aedc6173..10a322124a97 100644 --- a/src/main/runtime/orchestration/crew/crew-party-snapshot.ts +++ b/src/main/runtime/orchestration/crew/crew-party-snapshot.ts @@ -1,3 +1,4 @@ +import type { TerminalIdentityReadContext } from '../../terminal/query/terminal-identity-read-context' import type { AgentMessageSender } from '../../../../shared/agent-session/agent-session-message-source' import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-freshness' import { @@ -10,7 +11,7 @@ import type { FleetAgentStatusEvidence } from '../../../../shared/orchestration- import { isPublicOrchestrationAddress } from '../../../../shared/orchestration-agent-reference' import type { OrchestrationDb } from '../db' import { - resolveLineageRunningSession, + createLineageRunningSessionResolver, type AgentSessionRecordReader } from '../structured-session-lineage' import { crewDisplayName, crewTaskDisplay } from './crew-rules' @@ -42,8 +43,15 @@ export type CrewReadDependencies = { processForHandle?: (handle: string) => string | null statuses: readonly FleetAgentStatusEvidence[] now?: number + openIdentityRead?: () => CrewIdentityRead + openRuntimeIdentityRead?: () => TerminalIdentityReadContext } +export type CrewIdentityRead = Pick< + CrewReadDependencies, + 'liveHandle' | 'handleForPane' | 'paneForHandle' | 'processForHandle' | 'name' +> + function preview(body: string): string { const bytes = Buffer.from(body) return bytes.length <= 1024 @@ -66,9 +74,14 @@ export function buildCrewSnapshot( } const now = deps.now ?? Date.now() const cutoff = new Date(now - AGENT_STATUS_STALE_AFTER_MS).toISOString() - const registry = host.registry.fork() + const identity = deps.openIdentityRead?.() + if (identity) { + deps = { ...deps, ...identity } + } + const registry = host.registry.fork(identity) const { party, alias, addressOf, getParty, aliasesFor } = registry const records = host.deps.records + const runningSession = createLineageRunningSessionResolver(records) const hydrate = (addresses: string[], panes: string[] = []) => { const provenance = host.sourceInputs.provenance(addresses, panes) for (const family of [provenance.local, provenance.remote]) { @@ -117,9 +130,7 @@ export function buildCrewSnapshot( ): OrchestrationCrewRow => { const display = crewTaskDisplay(assignment) const title = display.taskTitle || display.displayName - const live = target.orcaSessionId - ? resolveLineageRunningSession(records, target.orcaSessionId) - : null + const live = target.orcaSessionId ? runningSession(target.orcaSessionId) : null const worker = assignment ? host.workersById.get(assignment.id) : undefined const evidence = worker && !target.orcaSessionId diff --git a/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts b/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts index 27659c9ec71a..347a26435b4a 100644 --- a/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts +++ b/src/main/runtime/orchestration/crew/crew-read-model-performance.test.ts @@ -83,7 +83,7 @@ it('shares complete host derivation across N/10N handled assignments and subscri const dependencies = vi.fn(() => deps) const watch = vi.fn(db.crewChanges.subscribe) const model = new CrewReadModel(dependencies, watch) - const publications = Array.from({ length: subscribers }, () => [] as OrchestrationCrewFrame[]) + const publications = Array.from({ length: subscribers }, (): OrchestrationCrewFrame[] => []) const stops = publications.map((frames, i) => subscribeCrew( () => model.read(i === 0 ? 'term_coord' : `orca_session_id:chat-empty-${i}`), diff --git a/src/main/runtime/orchestration/crew/crew-read-model.ts b/src/main/runtime/orchestration/crew/crew-read-model.ts index 20904e5c278b..80782a902141 100644 --- a/src/main/runtime/orchestration/crew/crew-read-model.ts +++ b/src/main/runtime/orchestration/crew/crew-read-model.ts @@ -18,7 +18,7 @@ export class CrewReadModel { private unwatch: (() => void) | undefined constructor( - private readonly readDependencies: () => CrewReadDependencies, + private readonly readDependencies: (previous?: CrewReadDependencies) => CrewReadDependencies, private readonly watch: (wake: (facets: CrewInvalidation) => void) => () => void ) {} @@ -73,7 +73,7 @@ export class CrewReadModel { } else if (dirty.has('status') || dirty.has('names')) { const previous = this.host this.host = undefined - const deps = this.readDependencies() + const deps = this.readDependencies(previous.deps) if (dirty.has('status')) { const { statuses, ...sources } = deps const identities = (rows: typeof statuses) => @@ -99,7 +99,15 @@ export class CrewReadModel { listRecords: () => [...captured.values()] } } - this.host = { ...this.host, deps: { ...this.host.deps, records, name: deps.name } } + this.host = { + ...this.host, + deps: { + ...this.host.deps, + records, + name: deps.name, + openIdentityRead: deps.openIdentityRead + } + } } return buildCrewSnapshot(address, { ...this.host.deps, now }, this.host) } diff --git a/src/main/runtime/orchestration/crew/crew-runtime-watch.ts b/src/main/runtime/orchestration/crew/crew-runtime-watch.ts index e97082f0c8cc..0854b48e8185 100644 --- a/src/main/runtime/orchestration/crew/crew-runtime-watch.ts +++ b/src/main/runtime/orchestration/crew/crew-runtime-watch.ts @@ -1,3 +1,6 @@ +import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switch' +import { mainTerminalSourceInputs } from '../../terminal/surface/pty-pane-query' +import { runtimeLayoutLoadContext } from '../../workspace-layout-projection' import type { OrcaRuntimeService } from '../../orca-runtime' import type { OrchestrationDb } from '../db' import type { CrewReadDependencies } from './crew-read-model' @@ -27,12 +30,27 @@ export function watchCrewRuntimeSources( crewWorkspaceNames(deps.store?.getWorkspaceSession?.(hostId)) ]) ) + const topology = (id: ReturnType[number]) => + mainTerminalSourceInputs( + deps.store?.getWorkspaceSession?.(id), + runtimeLayoutLoadContext(deps.store, id) + ) + const topologyByHost = new Map( + ORCA_LAYOUT_OWNER_IS_MAIN ? hostIds().map((id) => [id, topology(id)]) : [] + ) const disposers = [ deps.watchChanges(wake), sessionCrewChanges.subscribe(wake), deps.watchTransitions(() => wake(new Set(['status', 'names']))), deps.store?.onWorkspaceSessionWritten?.((hostId) => { for (const id of hostId === null ? hostIds() : [hostId]) { + if (ORCA_LAYOUT_OWNER_IS_MAIN) { + const next = topology(id) + if (!isDeepStrictEqual(topologyByHost.get(id), next)) { + topologyByHost.set(id, next) + wake(new Set(['topology'])) + } + } const next = crewWorkspaceNames(deps.store?.getWorkspaceSession?.(id)) if (!isDeepStrictEqual(namesByHost.get(id), next)) { namesByHost.set(id, next) @@ -64,16 +82,41 @@ export function readCrewRuntimeInputs( | 'getTerminalProcessIncarnation' | 'getTerminalHandleForPaneKey' | 'getPaneKeyForTerminalHandle' + | 'getTerminalPaneKey' | 'getOrchestrationFleetAgentStatusSnapshot' + | 'createTerminalIdentityRawInputs' + | 'createTerminalIdentityReadContext' | 'orchestrationSenderNames' >, db: OrchestrationDb | null, retainedDbExists: boolean, - hostKey: string + hostKey: string, + previous?: CrewReadDependencies ): CrewReadDependencies { const store = peekOpenedAgentSessionRecordStore() + const openContext = + previous?.openRuntimeIdentityRead ?? + (() => { + const raw = runtime.createTerminalIdentityRawInputs() + return () => runtime.createTerminalIdentityReadContext(raw) + })() + const name = runtime.orchestrationSenderNames.captureCrewInputs() + const openIdentityRead = () => { + const context = openContext() + return { + processForHandle: (handle: string) => runtime.getTerminalProcessIncarnation(handle, context), + liveHandle: (handle: string) => + runtime.getTerminalWorktreeIdForHandle(handle, context) !== null, + handleForPane: (pane: string) => runtime.getTerminalHandleForPaneKey(pane, context), + paneForHandle: (handle: string) => runtime.getPaneKeyForTerminalHandle(handle, context), + name: (...args: Parameters) => + name(...args, (handle) => runtime.getTerminalPaneKey(handle, context)) + } + } return { db, + openIdentityRead, + openRuntimeIdentityRead: openContext, retainedDbExists, hostKey, records: store ? conversationRecordReader(store) : null, @@ -81,9 +124,9 @@ export function readCrewRuntimeInputs( liveHandle: (handle) => runtime.getTerminalWorktreeIdForHandle(handle) !== null, handleForPane: (pane) => runtime.getTerminalHandleForPaneKey(pane), paneForHandle: (handle) => runtime.getPaneKeyForTerminalHandle(handle), - name: runtime.orchestrationSenderNames.captureCrewInputs(), + name, get statuses() { - return runtime.getOrchestrationFleetAgentStatusSnapshot() + return runtime.getOrchestrationFleetAgentStatusSnapshot(openContext()) } } } diff --git a/src/main/runtime/orchestration/structured-session-lineage-acquisition.test.ts b/src/main/runtime/orchestration/structured-session-lineage-acquisition.test.ts new file mode 100644 index 000000000000..724af6e9a52a --- /dev/null +++ b/src/main/runtime/orchestration/structured-session-lineage-acquisition.test.ts @@ -0,0 +1,327 @@ +import '../rpc/unused-default-rpc-methods.test-fixture' +import { afterEach, expect, it, vi } from 'vitest' +import { agentSessionConversationView } from '../../../shared/agent-session-conversation-view' +import type { AgentSessionConversationView } from '../../../shared/agent-session-conversation-view' +import { + createSessionCallerHarness, + sessionRecord, + SESSION_X, + SESSION_Y +} from '../rpc/orchestration-session-caller-test-fixture' +import { getStructuredAgentSessionHost } from '../../native-chat/agent-session-wire/structured-agent-session-registry' +import { + createStructuredWorkerReadContext, + holdStructuredWorker, + resolveStructuredWorkerAuthority, + structuredWorkerSession +} from '../structured-worker-authority' +import { + structuredWorkerIdentities, + structuredWorkerProcessIncarnation +} from '../structured-worker-identity' +import { + createLineageRunningSessionResolver, + resolveLineageRunningSession, + type AgentSessionRecordReader +} from './structured-session-lineage' + +const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) +vi.mock('../../native-chat/agent-session-wire/structured-agent-session-registry', () => ({ + getStructuredAgentSessionHost: () => hostRef.current +})) + +afterEach(() => vi.restoreAllMocks()) + +function record(id: string, next?: string): AgentSessionConversationView { + const base = agentSessionConversationView(sessionRecord(id)) + return next === undefined + ? base + : { + ...base, + conversationCommand: { + command: 'clear', + state: 'completed', + callerKey: 'lineage-fixture', + phase: 'committed', + operationId: `clear-${id}`, + replacementSessionId: next + } + } +} + +function reader(records: readonly AgentSessionConversationView[], thrown = '') { + const byId = new Map(records.map((value) => [value.sessionId, value])) + const reads: string[] = [] + const store: AgentSessionRecordReader = { + getRecord: (id) => { + reads.push(id) + if (id === thrown) { + throw new Error('unreadable record') + } + return byId.get(id) ?? null + }, + listRecords: () => { + throw new Error('unrelated inventory must not be acquired') + } + } + return { store, reads } +} + +it('preserves the entire root-relative authority result for shared, failed and cyclic captured chains in either order', () => { + const base = record('pending', 'C') + const committed = base.conversationCommand! + const records = [ + record('A', 'B'), + record('B', 'C'), + record('C'), + record('D', 'B'), + record('missing', 'absent'), + record('throwing', 'throws'), + record('self', 'self'), + record('X', 'Y'), + record('Y', 'X'), + record('prefix', 'X'), + record('falsy', ''), + { ...base, conversationCommand: { ...committed, phase: 'prepared' as const } }, + { ...record('remote'), location: { ...record('remote').location, executionHostId: 'ssh:box' } }, + { + ...record('wsl'), + provider: 'codex' as const, + location: { ...record('wsl').location, wslDistro: 'Ubuntu' } + } + ] + const roots = [...records.map((value) => value.sessionId), 'absent', 'throws'] + for (const reversed of [false, true]) { + const baseline = reader(structuredClone(records), 'throws') + const candidate = reader(structuredClone(records), 'throws') + const resolve = createLineageRunningSessionResolver(candidate.store) + for (const root of reversed ? roots.toReversed() : roots) { + expect(resolve(root)).toEqual(resolveLineageRunningSession(baseline.store, root)) + expect(resolve(root)).toEqual(resolveLineageRunningSession(baseline.store, root)) + } + expect(new Set(candidate.reads).size).toBe(candidate.reads.length) + const result = resolve('A') + if (Array.isArray(result.lineage)) { + result.lineage.push('caller-mutation') + } + expect(resolve('A').lineage).toEqual(['A', 'B', 'C']) + expect(resolve('B').lineage).toEqual(['B', 'C']) + } + expect(createLineageRunningSessionResolver(null)('A')).toEqual( + resolveLineageRunningSession(null, 'A') + ) +}) + +it('charges raw/suffix discovery once, output paths separately, and reacquires on a new capture at N/10N', () => { + for (const population of [3, 30]) { + for (const ending of ['terminal', 'missing', 'cycle'] as const) { + const chain = Array.from({ length: population }, (_, i) => + record(`node-${i}`, i + 1 < population ? `node-${i + 1}` : undefined) + ) + const last = `node-${population - 1}` + if (ending === 'missing') { + chain[population - 1] = record(last, 'absent') + } + if (ending === 'cycle') { + chain[population - 1] = record(last, 'node-0') + } + const candidate = reader(chain) + let mapGets = 0 + let mapSets = 0 + let setAdds = 0 + const get = Map.prototype.get + const set = Map.prototype.set + const add = Set.prototype.add + vi.spyOn(Map.prototype, 'get').mockImplementation(function ( + this: Map, + key + ) { + mapGets++ + return get.call(this, key) + }) + vi.spyOn(Map.prototype, 'set').mockImplementation(function ( + this: Map, + key, + value + ) { + mapSets++ + return set.call(this, key, value) + }) + vi.spyOn(Set.prototype, 'add').mockImplementation(function (this: Set, value) { + setAdds++ + return add.call(this, value) + }) + const resolve = createLineageRunningSessionResolver(candidate.store) + let outputIds = 0 + let outputBytes = 0 + for (let i = 0; i < population; i++) { + const result = resolve(`node-${i}`) + outputIds += result.lineage.length + outputBytes += Buffer.byteLength(JSON.stringify(result.lineage)) + } + vi.restoreAllMocks() + const nodes = population + Number(ending === 'missing') + expect(candidate.reads.length).toBe(nodes) + expect(mapSets).toBe(nodes) + expect(mapGets).toBeLessThanOrEqual(outputIds + 5 * nodes) + expect(setAdds).toBe(nodes + (ending === 'cycle' ? outputIds : 0)) + console.log('lineage acquisition operations', { + population, + ending, + nodes, + mapGets, + mapSets, + setAdds, + outputIds, + outputBytes + }) + const fresh = reader(chain) + expect(createLineageRunningSessionResolver(fresh.store)('node-0')).toEqual(resolve('node-0')) + expect(fresh.reads.length).toBe(nodes) + } + } +}) + +it('uses installed-host production authority and custody with the same full result, lazy effects and fresh source boundaries', () => { + const exercise = ( + captured: boolean, + state: + | 'live' + | 'listed' + | 'retired' + | 'visibility-fault' + | 'missing' + | 'cycle' + | 'remote' + | 'uninstalled' + ) => { + let visibilityReads = 0 + const h = createSessionCallerHarness(hostRef, () => { + visibilityReads++ + if (state === 'visibility-fault') { + throw new Error('unreadable index') + } + return { present: true, sessionIds: state === 'listed' ? [SESSION_Y] : [] } + }) + try { + const root = h.records.get(SESSION_X)! + const successor = h.records.get(SESSION_Y)! + h.records.set(SESSION_X, { + ...root, + conversationCommand: { + command: 'clear', + state: 'completed', + phase: 'committed', + operationId: 'clear', + callerKey: 'fixture', + replacementSessionId: SESSION_Y + } + }) + h.records.set(SESSION_Y, { + ...successor, + provider: 'codex', + lease: { + ...successor.lease, + claimStatus: + state === 'listed' || state === 'retired' || state === 'visibility-fault' + ? 'released' + : 'live' + }, + location: { + ...successor.location, + executionHostId: state === 'remote' ? 'ssh:box' : 'local' + }, + ...(state === 'cycle' + ? { + conversationCommand: { + command: 'clear' as const, + state: 'completed' as const, + phase: 'committed' as const, + operationId: 'cycle', + callerKey: 'fixture', + replacementSessionId: SESSION_X + } + } + : {}) + }) + if (state === 'missing') { + h.records.delete(SESSION_Y) + } + const installed = getStructuredAgentSessionHost()! + const reads = vi.spyOn(installed.deps.store, 'getConversation') + if (state === 'uninstalled') { + hostRef.current = null + } + const identity = structuredWorkerIdentities.register({ + handle: 'structworker_acquisition-fixture', + sessionId: SESSION_X, + agent: null, + paneKey: 'session-fixture:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + processIncarnation: structuredWorkerProcessIncarnation(SESSION_X), + worktreeId: 'workspace', + hostScope: { kind: 'local', hostId: 'local' } + }) + vi.mocked(h.runtime.getTerminalPaneKey).mockRestore() + vi.mocked(h.runtime.getLiveTerminalPaneKey).mockRestore() + const terminal = captured ? h.runtime.createTerminalIdentityReadContext() : undefined + const context = terminal?.structured + const result = structuredWorkerSession(identity, context) + const hold = holdStructuredWorker(identity, h.db, undefined, context) + const authority = resolveStructuredWorkerAuthority(identity.handle, h.db, context) + const dispatchAuthority = h.runtime.getOrchestrationDispatchAuthority( + identity.handle, + terminal + ) + const runtimeOutput = { + process: h.runtime.getTerminalProcessIncarnation(identity.handle, terminal), + pane: h.runtime.getTerminalPaneKey(identity.handle, terminal), + authority: dispatchAuthority ? { ...dispatchAuthority, runtimeId: '' } : null + } + const calls = reads.mock.calls.map(([id]) => id) + // A new source generation must not retain the prior absence/location/failed suffix. + hostRef.current = installed + h.records.set(SESSION_Y, successor) + const fresh = structuredWorkerSession(identity, createStructuredWorkerReadContext()) + return { + result, + runtimeOutput, + hold, + authority, + fresh, + calls, + visibilityReads, + registry: structuredWorkerIdentities.get(identity.handle) + } + } finally { + h.close() + } + } + for (const state of [ + 'live', + 'listed', + 'retired', + 'visibility-fault', + 'missing', + 'cycle', + 'remote', + 'uninstalled' + ] as const) { + const baseline = exercise(false, state) + const candidate = exercise(true, state) + const { calls: originalCalls, visibilityReads: originalVisibility, ...expected } = baseline + const { calls, visibilityReads, ...actual } = candidate + expect(actual).toEqual(expected) + expect(calls.length).toBeLessThanOrEqual(2) + expect(visibilityReads).toBeLessThanOrEqual(1) + if (state === 'live') { + expect(visibilityReads).toBe(0) + } + console.log('installed authority acquisition', { + state, + originalCalls: originalCalls.length, + calls: calls.length, + originalVisibility, + visibilityReads + }) + } +}) diff --git a/src/main/runtime/orchestration/structured-session-lineage.ts b/src/main/runtime/orchestration/structured-session-lineage.ts index 5c87456247bd..56195988638c 100644 --- a/src/main/runtime/orchestration/structured-session-lineage.ts +++ b/src/main/runtime/orchestration/structured-session-lineage.ts @@ -154,3 +154,97 @@ export function createCanonicalSessionPaneResolver( return structuredAgentSessionPaneKey(structuredAgentSessionTabId(id), id) } } + +type LineageSuffix = + | { kind: 'terminal'; sessionId: string; record: AgentSessionConversationView; here: boolean } + | { kind: 'missing'; sessionId: string } + | { kind: 'cycle' } + +type LineageNode = { next: string | null; suffix?: LineageSuffix } + +/** Discover each captured edge once; only requested lineage output is materialized per call. */ +export function createLineageRunningSessionResolver( + store: AgentSessionRecordReader | null +): (sessionId: string) => LineageRunningSession { + const nodes = new Map() + const discover = (root: string): LineageSuffix => { + const path: string[] = [] + const active = new Set() + let current = root + let suffix: LineageSuffix + for (;;) { + const known = nodes.get(current)?.suffix + if (known) { + suffix = known + break + } + if (active.has(current)) { + suffix = { kind: 'cycle' } + break + } + active.add(current) + path.push(current) + let record: AgentSessionConversationView | null + try { + record = store?.getRecord(current) ?? null + } catch { + record = null + } + if (!record) { + nodes.set(current, { next: null }) + suffix = { kind: 'missing', sessionId: current } + break + } + const next = clearedInto(record) + nodes.set(current, { next: next || null }) + if (!next) { + suffix = { + kind: 'terminal', + sessionId: current, + record, + here: Boolean(structuredWorkerHostScope(record.location)) + } + break + } + current = next + } + for (const member of path) { + nodes.get(member)!.suffix = suffix + } + return suffix + } + return (sessionId) => { + if (!store) { + return { + kind: 'unverifiable', + reason: 'The structured agent-session host is not installed in this runtime generation.', + lineage: [sessionId] + } + } + const suffix = discover(sessionId) + const lineage: string[] = [] + const visited = suffix.kind === 'cycle' ? new Set() : null + let current: string | null = sessionId + while (current !== null && !visited?.has(current)) { + lineage.push(current) + visited?.add(current) + current = nodes.get(current)!.next + } + if (suffix.kind === 'terminal') { + return { + kind: suffix.here ? 'here' : 'other-host', + sessionId: suffix.sessionId, + record: suffix.record, + lineage + } + } + return { + kind: 'unverifiable', + reason: + suffix.kind === 'missing' + ? `No durable record backs structured session ${suffix.sessionId}.` + : `The /clear lineage of structured session ${sessionId} loops back on itself.`, + lineage + } + } +} diff --git a/src/main/runtime/orchestration/terminal-pane-mail-routing.ts b/src/main/runtime/orchestration/terminal-pane-mail-routing.ts index 885fbdcc90c6..a742b45172e2 100644 --- a/src/main/runtime/orchestration/terminal-pane-mail-routing.ts +++ b/src/main/runtime/orchestration/terminal-pane-mail-routing.ts @@ -32,6 +32,15 @@ import { OPERATOR_CLOSE_EXIT_CAUSE } from '../../../shared/terminal-exit-cause' import { resolveTerminalIdentityFromProbes } from '../terminal-identity-probe' export abstract class OrcaRuntimeWithGetPtyRecordForPaneKey extends OrcaRuntimeWithPruneMobileSessionTabGroupLayout { + protected terminalIdentitySources = () => ({ + handles: this.handles, + sshTerminals: this.orchestrationCompatibilitySshTerminals, + reverse: this.handleByPtyId, + leaves: this.leaves, + ptys: this.ptysById, + capturePaneOf: () => this.captureTerminalPaneReader() + }) + protected getPtyRecordForPaneKey( paneKey: string, context?: TerminalIdentityReadContext diff --git a/src/main/runtime/runtime-orchestration-crew-names.test.ts b/src/main/runtime/runtime-orchestration-crew-names.test.ts index 7ddb51242814..ef5eafbb94c1 100644 --- a/src/main/runtime/runtime-orchestration-crew-names.test.ts +++ b/src/main/runtime/runtime-orchestration-crew-names.test.ts @@ -63,6 +63,12 @@ it('captures actual raw naming reads once at N/10N and preserves naming preceden ]) { expect(read).toHaveBeenCalledTimes(population) } + const capturedPane = vi.fn((handle: string) => `tab_${handle}:leaf`) + vi.mocked(deps.getTerminalPaneKey).mockClear() + const scoped = names.captureCrewInputs() + expect(parties.map((party) => scoped(party, 'Task', null, capturedPane))).toEqual(expected) + expect(capturedPane).toHaveBeenCalledTimes(population) + expect(deps.getTerminalPaneKey).not.toHaveBeenCalled() session.tabsByWorktree = { workspace: [{ id: 'tab_term_0', customTitle: 'Changed' }] } expect(captured(parties[0], 'Task', null)).toBe(expected[0]) expect(names.captureCrewInputs()(parties[0], 'Task', null)).toBe('Changed') diff --git a/src/main/runtime/runtime-orchestration-sender-names.ts b/src/main/runtime/runtime-orchestration-sender-names.ts index 1b97e641a467..a6a1ad4d75f6 100644 --- a/src/main/runtime/runtime-orchestration-sender-names.ts +++ b/src/main/runtime/runtime-orchestration-sender-names.ts @@ -157,7 +157,8 @@ export class RuntimeOrchestrationSenderNames { return ( party: AgentMessageSender['party'], taskName: string | null, - records: AgentSessionRecordReader | null + records: AgentSessionRecordReader | null, + readPane = this.deps.getTerminalPaneKey ) => orchestrationSenderName( party, @@ -175,7 +176,8 @@ export class RuntimeOrchestrationSenderNames { handle, session, (worktreeId, tabId) => terminalTabs.get(worktreeId)?.get(tabId), - allStatuses ? (pane) => statuses.get(pane) ?? [] : this.statusRowsForPane + allStatuses ? (pane) => statuses.get(pane) ?? [] : this.statusRowsForPane, + readPane ) terminals.set(handle, naming ? structuredClone(naming) : null) } @@ -199,7 +201,8 @@ export class RuntimeOrchestrationSenderNames { worktreeId: string, tabId: string ) => (Pick & Partial) | undefined, - readStatuses = this.statusRowsForPane + readStatuses = this.statusRowsForPane, + readPane = this.deps.getTerminalPaneKey ): TerminalSenderNaming | null { const record = this.deps.getHandleRecord(handle) if (!record) { @@ -212,7 +215,7 @@ export class RuntimeOrchestrationSenderNames { : session?.tabsByWorktree?.[record.worktreeId]?.find( (candidate) => candidate.id === record.tabId ) - const paneKey = this.deps.getTerminalPaneKey(handle) + const paneKey = readPane(handle) const status = paneKey ? readStatuses(paneKey) .filter( diff --git a/src/main/runtime/session-graph/session-graph-reload-lifecycle.ts b/src/main/runtime/session-graph/session-graph-reload-lifecycle.ts index dc828c1b1a5f..f215be674f6d 100644 --- a/src/main/runtime/session-graph/session-graph-reload-lifecycle.ts +++ b/src/main/runtime/session-graph/session-graph-reload-lifecycle.ts @@ -123,6 +123,7 @@ export abstract class OrcaRuntimeWithHasTerminalsForWorktree extends OrcaRuntime } this.handles.clear() this.handleByLeafKey.clear() + this.crewChanges.notify() // Preserve CLI handles and incarnation waiters across reload; graph adoption may rejoin the same PTY. this.refreshWritableFlags() return revision diff --git a/src/main/runtime/structured-worker-authority.ts b/src/main/runtime/structured-worker-authority.ts index a7776ae5ae89..9abe0330a847 100644 --- a/src/main/runtime/structured-worker-authority.ts +++ b/src/main/runtime/structured-worker-authority.ts @@ -10,12 +10,15 @@ import { canonicalOrcaSessionId } from './orchestration/canonical-orca-session-i import type { OrchestrationDb } from './orchestration/db' import { OrchestrationError } from './orchestration/orchestration-error' import { + createLineageRunningSessionResolver, readAgentSessionRecordStore, resolveLineageRunningSession, + type AgentSessionRecordReader, type LineageRunningSession, type RunningStructuredSession } from './orchestration/structured-session-lineage' import { + captureStructuredWorkerTabVisibility, structuredSessionTabRetired, structuredWorkerAddressable } from './structured-worker-custody' @@ -115,16 +118,21 @@ export function isRecordedStructuredWorkerSession( /** The session running this worker now: the one minted for it, or its `/clear` successor. */ export function structuredWorkerSession( - identity: Pick + identity: Pick, + context?: StructuredWorkerReadContext ): LineageRunningSession { + if (context) { + return context.resolveSession(identity.sessionId) + } return resolveLineageRunningSession(readAgentSessionRecordStore(), identity.sessionId) } /** The worker's running session on this host, or the typed refusal an actor answers instead. */ function locateStructuredWorker( - identity: Pick + identity: Pick, + context?: StructuredWorkerReadContext ): { running: RunningStructuredSession } | { reason: string; refusal: OrchestrationError } { - const located = structuredWorkerSession(identity) + const located = structuredWorkerSession(identity, context) if (located.kind === 'here') { return { running: located } } @@ -163,13 +171,14 @@ export function requireRunningStructuredWorker( export function holdStructuredWorker( identity: StructuredWorkerIdentity, db: OrchestrationDb | null | undefined, - row = db?.getWorkerTerminalResourceByHandle?.(identity.handle) + row = db?.getWorkerTerminalResourceByHandle?.(identity.handle), + context?: StructuredWorkerReadContext ): StructuredWorkerHold { - const located = locateStructuredWorker(identity) + const located = locateStructuredWorker(identity, context) if ('refusal' in located) { return { kind: 'unverifiable', identity, reason: located.reason, refusal: located.refusal } } - const addressable = structuredWorkerAddressable(db, located.running, row) + const addressable = structuredWorkerAddressable(db, located.running, row, context?.visibility) if (addressable === null) { return { kind: 'unverifiable', @@ -188,10 +197,11 @@ export function holdStructuredWorker( /** A worker this runtime owns and its orchestration has not released, with its running session. */ export function resolveStructuredWorkerAuthority( handle: string, - db: OrchestrationDb | null | undefined + db: OrchestrationDb | null | undefined, + context?: StructuredWorkerReadContext ): StructuredWorkerAuthority | null { const identity = resolveStructuredWorkerIdentity(handle, db) - const hold = identity ? holdStructuredWorker(identity, db) : null + const hold = identity ? holdStructuredWorker(identity, db, undefined, context) : null return hold?.kind === 'held' ? { identity: hold.identity, running: hold.running } : null } @@ -268,3 +278,53 @@ export function observeStructuredSession(sessionId: string): StructuredWorkerObs reason: 'The session has no attached provider child in this runtime generation.' } } + +export type StructuredWorkerReadContext = { + resolveSession: (sessionId: string) => LineageRunningSession + visibility: ReturnType +} + +export function captureAgentSessionRecordInputs( + source: AgentSessionRecordReader | null +): AgentSessionRecordReader | null { + const facts = new Map< + string, + { record: AgentSessionConversationView | null } | { error: unknown } + >() + return source + ? { + ...source, + getRecord: (id) => { + let fact = facts.get(id) + if (!fact) { + try { + fact = { record: structuredClone(source.getRecord(id)) } + } catch (error) { + fact = { error } + } + facts.set(id, fact) + } + if ('error' in fact) { + throw fact.error + } + return fact.record + } + } + : null +} + +export function captureStructuredWorkerReadInputs() { + return { + records: captureAgentSessionRecordInputs(readAgentSessionRecordStore()), + visibility: captureStructuredWorkerTabVisibility() + } +} + +export function createStructuredWorkerReadContext( + inputs = captureStructuredWorkerReadInputs() +): StructuredWorkerReadContext { + return { + resolveSession: createLineageRunningSessionResolver(inputs.records), + visibility: inputs.visibility + } +} diff --git a/src/main/runtime/structured-worker-custody.ts b/src/main/runtime/structured-worker-custody.ts index df793c26a83c..5c19588ec0f0 100644 --- a/src/main/runtime/structured-worker-custody.ts +++ b/src/main/runtime/structured-worker-custody.ts @@ -20,7 +20,19 @@ import { } from './structured-worker-identity' /** Judge ownership on the resolved successor session; absent host returns null because reading storage would install it. */ -export function structuredWorkerOwned(running: RunningStructuredSession): boolean | null { +export function structuredWorkerOwned( + running: RunningStructuredSession, + visibility?: ReturnType +): boolean | null { + if (visibility) { + return visibility.installed + ? structuredWorkerRecordIsCurrent( + running.record, + running.record.ownerObservation.claimStatus === 'released' && + visibility.isListed(running.sessionId) + ) + : null + } const host = getStructuredAgentSessionHost() if (!host) { return null @@ -76,9 +88,10 @@ function ownerState( export function structuredWorkerAddressable( db: OrchestrationDb | null | undefined, running: RunningStructuredSession, - row: CustodyRow | undefined + row: CustodyRow | undefined, + visibility?: ReturnType ): boolean | null { - const owned = structuredWorkerOwned(running) + const owned = structuredWorkerOwned(running, visibility) if (owned === null) { return null } @@ -162,3 +175,22 @@ function ownedWorkerIncarnation( .get(incarnation, JSON.stringify(hostScope)) return owned === undefined ? null : incarnation } + +/** Finite captured membership; unreadable visibility never proves an open released session. */ +export function captureStructuredWorkerTabVisibility() { + const host = getStructuredAgentSessionHost() + let listed: ReadonlySet | undefined + return { + installed: Boolean(host), + isListed: (sessionId: string): boolean => { + if (!listed) { + try { + listed = new Set(host?.getPersistedVisibleSessionTabIndex?.().sessionIds ?? []) + } catch { + listed = new Set() + } + } + return listed.has(sessionId) + } + } +} diff --git a/src/main/runtime/terminal/adoption/adopt-terminal-orphans-from-inventory.ts b/src/main/runtime/terminal/adoption/adopt-terminal-orphans-from-inventory.ts index debaabfa03db..22dfcfcbbed3 100644 --- a/src/main/runtime/terminal/adoption/adopt-terminal-orphans-from-inventory.ts +++ b/src/main/runtime/terminal/adoption/adopt-terminal-orphans-from-inventory.ts @@ -200,8 +200,11 @@ export abstract class OrcaRuntimeWithAdoptTerminalOrphansFromInventory extends O // Dispatch uses remint-stable pane keys; unresolved handles return null so best-effort dispatch can proceed. getTerminalPaneKey(handle: string, context?: TerminalIdentityReadContext): string | null { return ( - resolveStructuredWorkerAuthority(handle, this.getOrchestrationDbIfAvailable?.() ?? null) - ?.identity.paneKey ?? + resolveStructuredWorkerAuthority( + handle, + this.getOrchestrationDbIfAvailable?.() ?? null, + context?.structured + )?.identity.paneKey ?? this.getPaneKeyForTerminalHandle(handle, context) ?? this.getOrchestrationCompatibilitySshTerminal(handle, context)?.paneKey ?? null diff --git a/src/main/runtime/terminal/identity/pty-worktree-record.ts b/src/main/runtime/terminal/identity/pty-worktree-record.ts index 45f87f7f91d2..a7e22c3ae5e5 100644 --- a/src/main/runtime/terminal/identity/pty-worktree-record.ts +++ b/src/main/runtime/terminal/identity/pty-worktree-record.ts @@ -31,11 +31,15 @@ export abstract class OrcaRuntimeWithRecordPtyWorktree extends RuntimeWorkspaceR /** An inventory's connection verdict; main's panes that bind the terminal re-compose. */ protected setPtyConnected(pty: RuntimePtyWorktreeRecord, connected: boolean): void { const prior = mainPaneRecordFacts(pty) + const changed = pty.connected !== connected pty.connected = connected pty.disconnectedAt = connected ? null : (pty.disconnectedAt ?? Date.now()) if (ORCA_LAYOUT_OWNER_IS_MAIN) { noteMainPaneRecordChange(this, prior, pty) } + if (changed) { + this.crewChanges.notify() + } } protected abstract nextTitleObservationSequence(): number @@ -78,6 +82,19 @@ export abstract class OrcaRuntimeWithRecordPtyWorktree extends RuntimeWorkspaceR state = withoutPaneClaim(state) } let pty = this.ptysById.get(ptyId) + const identityMayChange = + !pty || + pty.worktreeId !== worktreeId || + state.connected !== undefined || + state.tabId !== undefined || + state.paneKey !== undefined || + state.surfaceRecordedAtGraphSequence !== undefined || + state.connectionId !== undefined || + state.incarnationId !== undefined || + state.wslDistro !== undefined || + state.isWsl !== undefined + const previousCrewIdentity = identityMayChange ? crewPtyIdentity(pty) : undefined + const previousTitle = pty?.title if (!pty) { const titleObservedAt = state.title ? this.nextTitleObservationSequence() : null const connectionId = state.connectionId ?? parseAppSshPtyId(ptyId)?.connectionId ?? null @@ -161,6 +178,7 @@ export abstract class OrcaRuntimeWithRecordPtyWorktree extends RuntimeWorkspaceR if (prior !== null) { noteMainPaneRecordChange(this, prior, pty) } + this.crewChanges.notify() return pty } @@ -253,6 +271,11 @@ export abstract class OrcaRuntimeWithRecordPtyWorktree extends RuntimeWorkspaceR if (prior !== null) { noteMainPaneRecordChange(this, prior, pty) } + if (identityMayChange && previousCrewIdentity !== crewPtyIdentity(pty)) { + this.crewChanges.notify() + } else if (previousTitle !== pty.title) { + this.crewChanges.notify(new Set(['names'])) + } return pty } @@ -282,3 +305,18 @@ export abstract class OrcaRuntimeWithRecordPtyWorktree extends RuntimeWorkspaceR return this.recordPtyWorktree(ptyId, inferredWorktreeId) } } + +function crewPtyIdentity(pty: RuntimePtyWorktreeRecord | undefined): string | undefined { + const facts = pty && [ + pty.worktreeId, + pty.connected, + pty.tabId, + pty.paneKey, + pty.surfaceRecordedAtGraphSequence, + pty.connectionId, + pty.incarnationId, + pty.wslDistro, + pty.isWsl + ] + return facts && JSON.stringify(facts) +} diff --git a/src/main/runtime/terminal/identity/terminal-handle-bindings.ts b/src/main/runtime/terminal/identity/terminal-handle-bindings.ts index 965c166a98a6..008da1568cec 100644 --- a/src/main/runtime/terminal/identity/terminal-handle-bindings.ts +++ b/src/main/runtime/terminal/identity/terminal-handle-bindings.ts @@ -1,5 +1,6 @@ import type { TerminalIdentityReadContext } from '../query/terminal-identity-read-context' import { OrcaRuntimeWithBuildPtyTerminalSummary } from '../query/pty-terminal-summary' +import type { TerminalHandleRecord } from '../../runtime-terminal-contracts' import type { PtyIncarnationHandleRecord } from '../../orca-runtime-core' import type { RuntimeLeafRecord, @@ -17,6 +18,7 @@ export abstract class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntim retained: PtyIncarnationHandleRecord, leaf: RuntimeLeafRecord ): void { + const before = this.handles.get(retained.handle) const leafKey = this.getLeafKey(leaf.tabId, leaf.leafId) if (retained.leafKey !== leafKey) { if (this.handleByLeafKey.get(retained.leafKey) === retained.handle) { @@ -35,6 +37,9 @@ export abstract class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntim ptyGeneration: leaf.ptyGeneration }) this.handleByLeafKey.set(leafKey, retained.handle) + if (!sameCrewHandle(before, this.handles.get(retained.handle))) { + this.crewChanges.notify() + } } protected invalidatePtyIncarnationHandle(ptyId: string): void { @@ -49,6 +54,7 @@ export abstract class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntim this.handles.delete(retained.handle) this.syntheticTerminalHandles.delete(retained.handle) this.rejectWaitersForHandle(retained.handle, 'terminal_handle_stale') + this.crewChanges.notify() } protected clearPtyIncarnationHandles(): void { @@ -85,6 +91,7 @@ export abstract class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntim return null } const leafKey = this.getLeafKey(leaf.tabId, leaf.leafId) + const before = this.handles.get(preAllocated) this.handles.set(preAllocated, { handle: preAllocated, runtimeId: this.runtimeId, @@ -96,6 +103,9 @@ export abstract class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntim ptyGeneration: leaf.ptyGeneration }) this.handleByLeafKey.set(leafKey, preAllocated) + if (!sameCrewHandle(before, this.handles.get(preAllocated))) { + this.crewChanges.notify() + } return preAllocated } @@ -103,6 +113,8 @@ export abstract class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntim pty: RuntimePtyWorktreeRecord, context?: TerminalIdentityReadContext ): string { + const previousHandle = this.handleByPtyId.get(pty.ptyId) + const before = previousHandle ? this.handles.get(previousHandle) : undefined const handle = this.issuePtyHandleRecord(pty, context) // An unbound terminal retains its issued pane stamp for recovery, including after replacement. const record = ORCA_LAYOUT_OWNER_IS_MAIN ? this.handles.get(handle) : undefined @@ -112,6 +124,9 @@ export abstract class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntim } context?.changedHandle(handle) context?.changedReverseBinding(pty.ptyId) + if (previousHandle !== handle || !sameCrewHandle(before, this.handles.get(handle))) { + this.crewChanges.notify() + } return handle } @@ -196,6 +211,7 @@ export abstract class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntim this.handles.delete(handle) this.syntheticTerminalHandles.delete(handle) this.rejectWaitersForHandle(handle, 'terminal_handle_stale') + this.crewChanges.notify() } protected adoptFirstPtyForLeafHandle( @@ -209,6 +225,7 @@ export abstract class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntim return false } this.handles.set(handle, { ...record, ptyId, ptyGeneration }) + this.crewChanges.notify() return true } @@ -222,11 +239,17 @@ export abstract class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntim } protected issueHandle(leaf: RuntimeLeafRecord, context?: TerminalIdentityReadContext): string { const retained = leaf.ptyId ? this.handleByPtyIncarnation.get(leaf.ptyId)?.handle : undefined + const previousHandle = + this.handleByLeafKey.get(this.getLeafKey(leaf.tabId, leaf.leafId)) ?? retained + const before = previousHandle ? this.handles.get(previousHandle) : undefined const handle = this.issueLeafHandleRecord(leaf) if (retained) { context?.changedHandle(retained) } context?.changedHandle(handle) + if (!sameCrewHandle(before, this.handles.get(handle))) { + this.crewChanges.notify() + } return handle } @@ -276,3 +299,23 @@ export abstract class OrcaRuntimeWithBindPtyIncarnationHandle extends OrcaRuntim return handle } } + +function sameCrewHandle( + a: TerminalHandleRecord | undefined, + b: TerminalHandleRecord | undefined +): boolean { + if (!a || !b) { + return a === b + } + return ( + a.handle === b.handle && + a.runtimeId === b.runtimeId && + a.rendererGraphEpoch === b.rendererGraphEpoch && + a.worktreeId === b.worktreeId && + a.tabId === b.tabId && + a.leafId === b.leafId && + a.ptyId === b.ptyId && + a.ptyGeneration === b.ptyGeneration && + a.issuedForPaneKey === b.issuedForPaneKey + ) +} diff --git a/src/main/runtime/terminal/lifecycle/floating-session-liveness.ts b/src/main/runtime/terminal/lifecycle/floating-session-liveness.ts index 02f7eb5ba4ac..39465a341d07 100644 --- a/src/main/runtime/terminal/lifecycle/floating-session-liveness.ts +++ b/src/main/runtime/terminal/lifecycle/floating-session-liveness.ts @@ -57,14 +57,22 @@ export abstract class OrcaRuntimeWithRefreshFloatingWorkspacePtyLiveness extends }) } if (pty) { + const wasConnected = pty.connected pty.connected = true pty.disconnectedAt = null + if (!wasConnected) { + this.crewChanges.notify() + } this.markPtyLivenessLive(ptyId) this.refreshPtyForegroundAgent(ptyId) } } else if (pty && !this.leafExistsForPty(ptyId)) { + const wasConnected = pty.connected pty.connected = false pty.disconnectedAt ??= Date.now() + if (wasConnected) { + this.crewChanges.notify() + } } } this.pruneDisconnectedPtyRecords() @@ -113,7 +121,9 @@ export abstract class OrcaRuntimeWithRefreshFloatingWorkspacePtyLiveness extends } this.advancePtyLifecycleGeneration(ptyId) this.pairedRendererSessionOwnedPtyIds.delete(ptyId) - this.ptysById.delete(ptyId) + if (this.ptysById.delete(ptyId)) { + this.crewChanges.notify() + } this.pendingPtyHandleReplacementFences.delete(ptyId) this.recentPtyOutputById.delete(ptyId) this.setupCompletionTokenByPtyId.delete(ptyId) diff --git a/src/main/runtime/terminal/lifecycle/pty-exit-lifecycle.ts b/src/main/runtime/terminal/lifecycle/pty-exit-lifecycle.ts index d6011d9cb730..40a85b5db42a 100644 --- a/src/main/runtime/terminal/lifecycle/pty-exit-lifecycle.ts +++ b/src/main/runtime/terminal/lifecycle/pty-exit-lifecycle.ts @@ -233,10 +233,14 @@ export abstract class OrcaRuntimeWithOnPtyExit extends OrcaRuntimeWithOnClientDi this.rememberPtyLivenessVerdict(ptyId, { status: 'exited' }) } if (pty) { + const wasConnected = pty.connected pty.connected = false pty.runtimeSessionOwned = false this.setPairedRendererSessionOwnership(pty.ptyId, false) pty.disconnectedAt = Date.now() + if (wasConnected) { + this.crewChanges.notify() + } pty.lastExitCode = exitCode pty.lastExitCause = exitCause // Same-id replacements must earn live idle evidence before delivery; retain status only for display. diff --git a/src/main/runtime/terminal/lifecycle/pty-handle-invalidation.ts b/src/main/runtime/terminal/lifecycle/pty-handle-invalidation.ts index 146aaa6afbbd..92e667852fea 100644 --- a/src/main/runtime/terminal/lifecycle/pty-handle-invalidation.ts +++ b/src/main/runtime/terminal/lifecycle/pty-handle-invalidation.ts @@ -22,6 +22,7 @@ export abstract class OrcaRuntimeWithInvalidateAllHandlesForPty extends OrcaRunt } protected invalidateAllHandlesForPty(ptyId: string, preserveHandle?: string): Set { + const preservedRecord = preserveHandle !== undefined && this.handles.has(preserveHandle) const incarnationHandle = this.handleByPtyIncarnation.get(ptyId)?.handle const preallocatedHandle = this.handleByPtyId.get(ptyId) const invalidated = new Set() @@ -56,6 +57,9 @@ export abstract class OrcaRuntimeWithInvalidateAllHandlesForPty extends OrcaRunt this.handles.delete(preserveHandle) this.syntheticTerminalHandles.delete(preserveHandle) } + if (invalidated.size || preservedRecord) { + this.crewChanges.notify() + } return invalidated } @@ -145,6 +149,8 @@ export abstract class OrcaRuntimeWithInvalidateAllHandlesForPty extends OrcaRunt ): void { this.invalidatePtyControllerInventoryForLifecycle(ptyId) const existingPty = this.ptysById.get(ptyId) + const previousConnected = existingPty?.connected + const previousIncarnation = existingPty?.incarnationId if ( existingPty && incarnationId !== undefined && @@ -184,6 +190,9 @@ export abstract class OrcaRuntimeWithInvalidateAllHandlesForPty extends OrcaRunt } pty.connected = true pty.disconnectedAt = null + if (previousConnected !== pty.connected || previousIncarnation !== pty.incarnationId) { + this.crewChanges.notify() + } } for (const leaf of this.getLeavesForPty(ptyId)) { leaf.connected = true diff --git a/src/main/runtime/terminal/output/pty-output-ingestion.ts b/src/main/runtime/terminal/output/pty-output-ingestion.ts index d7041487eb25..ca580ed8d3b2 100644 --- a/src/main/runtime/terminal/output/pty-output-ingestion.ts +++ b/src/main/runtime/terminal/output/pty-output-ingestion.ts @@ -130,8 +130,12 @@ export abstract class OrcaRuntimeWithOnPtyData extends OrcaRuntimeWithPreparePty let ptyTailAfter: ReturnType | null = null let ptyNormalized: ReturnType | null = null if (pty) { + const wasConnected = pty.connected pty.connected = true pty.disconnectedAt = null + if (!wasConnected) { + this.crewChanges.notify() + } pty.lastOutputAt = at const normalized = normalizeTerminalChunk(data, pty.tailPendingAnsi) ptyNormalized = normalized diff --git a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts index 25d5bec020a6..421e244dd300 100644 --- a/src/main/runtime/terminal/output/terminal-orchestration-authority.ts +++ b/src/main/runtime/terminal/output/terminal-orchestration-authority.ts @@ -22,7 +22,11 @@ import { resolveTerminalOrchestrationCliCommand, runtimeOrchestrationCliCommand } from '../../orchestration/cli-command' -import { readOrchestrationFleetAgentStatusSnapshot } from '../../orchestration-fleet-agent-status-snapshot' +import { + readOrchestrationFleetAgentStatusSnapshot, + readAgentOrchestrationProjectionRecords, + readCapturedOrchestrationFleetAgentStatusSnapshot +} from '../../orchestration-fleet-agent-status-snapshot' import { resolveStructuredWorkerAuthority } from '../../structured-worker-authority' import { isStructuredWorkerHandle } from '../../../../shared/structured-worker-handle' import { parseOrcaSessionAddress } from '../../../../shared/orca-session-address' @@ -37,7 +41,8 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O ): string | null { const structured = resolveStructuredWorkerAuthority( handle, - this.getOrchestrationDbIfAvailable?.() ?? null + this.getOrchestrationDbIfAvailable?.() ?? null, + context?.structured ) if (structured) { return structured.identity.processIncarnation @@ -108,11 +113,13 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O } getOrchestrationDispatchAuthority( - terminalHandle: string + terminalHandle: string, + context?: TerminalIdentityReadContext ): OrchestrationCompatibilityTerminalAuthority | null { const structured = resolveStructuredWorkerAuthority( terminalHandle, - this.getOrchestrationDbIfAvailable?.() ?? null + this.getOrchestrationDbIfAvailable?.() ?? null, + context?.structured ) if (structured) { return { @@ -130,7 +137,7 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O let ptyId: string | null try { ptyId = - this.getLivePtyForHandle(terminalHandle)?.pty.ptyId ?? + this.getLivePtyForHandle(terminalHandle, context)?.pty.ptyId ?? this.resolveLiveLeafForHandle(terminalHandle)?.ptyId ?? null } catch { @@ -152,8 +159,8 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O terminalHandle, ptyId, worktreeId: pty.worktreeId, - processIncarnation: this.getTerminalProcessIncarnation(terminalHandle), - paneKey: this.paneOfPty(pty).paneKey, + processIncarnation: this.getTerminalProcessIncarnation(terminalHandle, context), + paneKey: (context ? context.paneOf(pty) : this.paneOfPty(pty)).paneKey, launchTokenHash: pty.launchToken ? createHash('sha256').update(pty.launchToken).digest('hex') : null, @@ -239,8 +246,32 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O ) } - getOrchestrationFleetAgentStatusSnapshot() { - return readOrchestrationFleetAgentStatusSnapshot(this) + getOrchestrationFleetAgentStatusSnapshot(context?: TerminalIdentityReadContext) { + if (!context) { + return readOrchestrationFleetAgentStatusSnapshot(this) + } + const dependencies = this.agentOrchestrationDependencies({ + paneOf: (pty) => context.paneOf(pty), + issueLeafHandle: (leaf) => this.issueHandle(leaf, context), + issuePtyHandle: (pty) => this.issuePtyHandle(pty, context), + getWorktreeId: (handle) => this.getTerminalWorktreeIdForHandle(handle, context), + getHandleForPaneKey: (pane) => this.getTerminalHandleForPaneKey(pane, context), + getPaneKey: (handle) => this.getPaneKeyForTerminalHandle(handle, context), + getDispatchAuthority: (handle) => this.getOrchestrationDispatchAuthority(handle, context), + getSessionRecords: () => readAgentOrchestrationProjectionRecords(context) + }) + return readCapturedOrchestrationFleetAgentStatusSnapshot( + { + getAgentStatusSnapshotFn: this.getAgentStatusSnapshotFn, + readObservedAgentStatusPaneIdentityFn: (pane) => + this.readObservedAgentStatusPaneIdentityFn(pane), + getAgentStatusTerminalHandleForPaneKey: (pane) => + this.getTerminalHandleForPaneKey(pane, context) ?? undefined, + getTerminalProcessIncarnation: (handle) => + this.getTerminalProcessIncarnation(handle, context) + }, + dependencies + ) } getTerminalOrchestrationCliCommand(handle: string) { diff --git a/src/main/runtime/terminal/query/pty-terminal-summary.ts b/src/main/runtime/terminal/query/pty-terminal-summary.ts index dd39ae710339..3449a0e08eab 100644 --- a/src/main/runtime/terminal/query/pty-terminal-summary.ts +++ b/src/main/runtime/terminal/query/pty-terminal-summary.ts @@ -1,4 +1,7 @@ -import { TerminalIdentityReadContext } from './terminal-identity-read-context' +import { + TerminalIdentityRawInputs, + TerminalIdentityReadContext +} from './terminal-identity-read-context' import { OrcaRuntimeWithGetPtyRecordForPaneKey } from '../../orchestration/terminal-pane-mail-routing' import type { RuntimeLeafRecord, @@ -35,15 +38,14 @@ export abstract class OrcaRuntimeWithBuildPtyTerminalSummary extends OrcaRuntime leaf: RuntimeLeafRecord ): void - createTerminalIdentityReadContext(): TerminalIdentityReadContext { - return new TerminalIdentityReadContext({ - handles: this.handles, - sshTerminals: this.orchestrationCompatibilitySshTerminals, - reverse: this.handleByPtyId, - leaves: this.leaves, - ptys: this.ptysById, - capturePaneOf: () => this.captureTerminalPaneReader() - }) + createTerminalIdentityRawInputs(): TerminalIdentityRawInputs { + return new TerminalIdentityRawInputs(this.terminalIdentitySources()) + } + + createTerminalIdentityReadContext( + inputs?: TerminalIdentityRawInputs + ): TerminalIdentityReadContext { + return new TerminalIdentityReadContext(this.terminalIdentitySources(), inputs) } protected ptySurfaceTopology(): PtySurfaceTopology { @@ -245,7 +247,11 @@ export abstract class OrcaRuntimeWithBuildPtyTerminalSummary extends OrcaRuntime return null } // Why: renderer adoption can race with CLI reads; keep ptyId → handle populated so summaries don't mint a second handle for the same terminal. + const previousHandle = this.handleByPtyId.get(record.ptyId) this.handleByPtyId.set(record.ptyId, handle) + if (previousHandle !== handle) { + this.crewChanges.notify() + } context?.changedReverseBinding(record.ptyId) return { record, pty } } diff --git a/src/main/runtime/terminal/query/terminal-identity-read-context.test.ts b/src/main/runtime/terminal/query/terminal-identity-read-context.test.ts index 2e2bf90d36f8..70124848523b 100644 --- a/src/main/runtime/terminal/query/terminal-identity-read-context.test.ts +++ b/src/main/runtime/terminal/query/terminal-identity-read-context.test.ts @@ -1,6 +1,18 @@ +import { AgentHookServer } from '../../../agent-hooks/server' +import { agentHookRuntimeDeps } from '../../../agent-hooks/agent-hook-runtime-deps' +import { + AgentStatusObservedPaneIdentities, + recordObservedAgentStatusPaneIdentity +} from '../../agent-status-observed-pane-identity' +import type { AgentStatusIpcPayload } from '../../../../shared/agent-status-ipc-payload' +import type { ObservedAgentStatusPaneIdentity } from '../../../ipc/agent-status-ipc-boundary' +import { enrichAgentStatusIpcPayload } from '../../../ipc/agent-status-ipc-boundary' +import { OrchestrationDb } from '../../orchestration/db' +import { CrewReadModel } from '../../orchestration/crew/crew-read-model' +import { readCrewRuntimeInputs } from '../../orchestration/crew/crew-runtime-watch' import { expect, it, vi } from 'vitest' import '../../orca-runtime-test-mocks.spec' -import { createRuntime, TEST_WORKTREE_ID } from '../../orca-runtime-test-fixtures.spec' +import { store, TEST_WORKTREE_ID } from '../../orca-runtime-test-fixtures.spec' import type { RuntimeLeafRecord, RuntimePtyWorktreeRecord @@ -12,6 +24,7 @@ import type { import type { PtyIncarnationHandleRecord } from '../../orca-runtime-core' import type { CrewChanges } from '../../orchestration/crew/crew-changes' import type { RuntimeTerminalWaiterRegistry } from '../wait/terminal-waiter-registry' +import { OrcaRuntimeService } from '../../orca-runtime' import type { TerminalIdentityReadContext } from './terminal-identity-read-context' const LEAF = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' @@ -48,17 +61,81 @@ type Owner = { pane: string, context?: TerminalIdentityReadContext ) => RuntimePtyWorktreeRecord | null + setPtyConnected: (pty: RuntimePtyWorktreeRecord, connected: boolean) => void + dropDisconnectedPtyRecord: (id: string) => void beginGraphReload: (windowId: number) => number findHandleForPtyRecord: (ptyId: string, context?: TerminalIdentityReadContext) => string | null issueHandle: (leaf: RuntimeLeafRecord, context?: TerminalIdentityReadContext) => string rejectWaitersForHandle: (handle: string, reason: string) => void } -function fixture() { - const runtime = createRuntime() - // SAFETY: this fixture exercises the existing protected map/effect owner with its production shapes. - const owner = runtime as unknown as Owner - const rejected = vi.spyOn(owner, 'rejectWaitersForHandle') +class IdentityRuntime extends OrcaRuntimeService { + identityOwner(): Owner { + const current = () => this + return { + get runtimeId() { + return current().runtimeId + }, + get rendererGraphEpoch() { + return current().rendererGraphEpoch + }, + get terminalWaiters() { + return current().terminalWaiters + }, + get crewChanges() { + return current().crewChanges + }, + get syntheticTerminalHandles() { + return current().syntheticTerminalHandles + }, + get handles() { + return current().handles + }, + get handleByPtyId() { + return current().handleByPtyId + }, + get handleByLeafKey() { + return current().handleByLeafKey + }, + get handleByPtyIncarnation() { + return current().handleByPtyIncarnation + }, + get leaves() { + return current().leaves + }, + get ptysById() { + return current().ptysById + }, + get orchestrationCompatibilitySshTerminals() { + return current().orchestrationCompatibilitySshTerminals + }, + getOrchestrationCompatibilitySshTerminal: + this.getOrchestrationCompatibilitySshTerminal.bind(this), + recordPtyWorktree: this.recordPtyWorktree.bind(this), + getLivePtyForHandle: this.getLivePtyForHandle.bind(this), + getPtyRecordForPaneKey: this.getPtyRecordForPaneKey.bind(this), + setPtyConnected: this.setPtyConnected.bind(this), + dropDisconnectedPtyRecord: this.dropDisconnectedPtyRecord.bind(this), + beginGraphReload: this.beginGraphReload.bind(this), + findHandleForPtyRecord: this.findHandleForPtyRecord.bind(this), + issueHandle: this.issueHandle.bind(this), + rejectWaitersForHandle: this.rejectWaitersForHandle.bind(this) + } + } +} + +function fixture(deps?: ConstructorParameters[2]) { + const runtime = new IdentityRuntime(store, undefined, deps) + const owner = runtime.identityOwner() + const rejected = vi.fn<(handle: string, reason: string) => void>() + const reject = owner.rejectWaitersForHandle + Object.defineProperty(runtime, 'rejectWaitersForHandle', { + value: (handle: string, reason: string) => { + rejected(handle, reason) + reject(handle, reason) + }, + configurable: true + }) const add = (id: string, handle: string, paneKey = PANE, connected = true) => { owner.recordPtyWorktree(id, TEST_WORKTREE_ID, { paneKey, connected }) owner.handleByPtyId.set(id, handle) @@ -86,7 +163,7 @@ function fixture() { synthetic: [...owner.syntheticTerminalHandles], rejected: rejected.mock.calls }) - return { runtime, owner, add, stamp, state } + return { runtime, owner, add, stamp, state, rejected } } it('matches separate production runtimes across reverse repair, stale first mapping, adoption and dependent reads in either order', () => { @@ -161,16 +238,20 @@ function countIterations( map: Map, counts: { entries: number; get: number; set: number; delete: number } ) { - for (const method of ['get', 'set', 'delete'] as const) { - const original = map[method].bind(map) - Object.defineProperty(map, method, { - configurable: true, - value: (...args: Parameters) => { - counts[method]++ - // SAFETY: this transparent fixture wrapper forwards the exact selected native Map method's arguments. - return (original as (...input: Parameters) => unknown)(...args) - } - }) + const get = map.get.bind(map) + const set = map.set.bind(map) + const remove = map.delete.bind(map) + map.get = (key: K) => { + counts.get++ + return get(key) + } + map.set = (key: K, value: V) => { + counts.set++ + return set(key, value) + } + map.delete = (key: K) => { + counts.delete++ + return remove(key) } for (const method of ['entries', 'keys', 'values', Symbol.iterator] as const) { const original = map[method].bind(map) @@ -348,15 +429,352 @@ it('keeps cold candidates coherent through real retained-handle invalidation and expect(f.owner.handleByLeafKey.get(`tab-original::${LEAF}`)).toBe(handle) expect(f.owner.handles.get(handle)?.ptyId).toBe('retained-pty') expect(f.owner.handleByPtyIncarnation.get('retained-pty')?.handle).toBe(handle) - expect(f.owner.rejectWaitersForHandle).toHaveBeenCalledWith( - 'term_retained', - 'terminal_handle_stale' - ) + expect(f.rejected).toHaveBeenCalledWith('term_retained', 'terminal_handle_stale') return { retainedRemoved: !f.owner.handles.has('term_retained'), synthetic: f.owner.syntheticTerminalHandles.size, - rejected: vi.mocked(f.owner.rejectWaitersForHandle).mock.calls + rejected: f.rejected.mock.calls } } expect(run(true)).toEqual(run(false)) }) + +it('reuses raw inputs for new historical parties through the production Crew boundary and retires them on real owner writes', () => { + vi.useFakeTimers() + vi.setSystemTime('2026-10-28T20:00:00.000Z') + const measure = (population: number, captured: boolean) => { + const f = fixture() + const db = new OrchestrationDb(':memory:') + f.runtime.setOrchestrationDb(db) + f.add('coordinator', 'term_coord') + f.stamp('term_coord', 'coordinator') + for (let i = 0; i < population; i++) { + f.add(`unrelated-${i}`, `term_inventory_${i}`, `inventory-${i}`) + } + const counts = { entries: 0, get: 0, set: 0, delete: 0 } + countIterations(f.owner.handles, counts) + countIterations(f.owner.ptysById, counts) + countIterations(f.owner.handleByPtyId, counts) + const capture = vi.spyOn(f.runtime, 'createTerminalIdentityRawInputs') + const model = new CrewReadModel( + (previous) => { + const inputs = readCrewRuntimeInputs(f.runtime, db, true, 'same-host', previous) + if (captured) { + return inputs + } + delete inputs.openIdentityRead + delete inputs.openRuntimeIdentityRead + return inputs + }, + (wake) => { + const stops = [f.owner.crewChanges.subscribe(wake), db.crewChanges.subscribe(wake)] + return () => stops.forEach((stop) => stop()) + } + ) + const wake = vi.fn() + const stop = model.subscribe(wake) + try { + expect(model.read('term_coord').sections.talkingWith).toEqual([]) + for (let i = 0; i < population; i++) { + db.insertMessage({ + from: `term_late_${i}`, + to: 'term_coord', + subject: 'Hello', + body: `message-${i}` + }) + } + db.db.prepare("UPDATE messages SET created_at = '2026-10-28 20:00:00'").run() + const output = model.read('term_coord') + expect(output.sections.talkingWith).toHaveLength(population) + const acquisition = { ...counts } + if (captured) { + const captures = capture.mock.calls.length + f.owner.crewChanges.notify(new Set(['status', 'names'])) + expect(model.read('term_coord')).toEqual(output) + expect(capture).toHaveBeenCalledTimes(captures) + expect(counts.entries).toBe(acquisition.entries) + // Register's actual controller handle, without another DB/status mutation, retires captured absence. + f.runtime.registerPty('late-pty', TEST_WORKTREE_ID, null, { + tabId: 'tab-late', + leafId: 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', + terminalHandle: 'term_late_0' + }) + const installed = model + .read('term_coord') + .sections.talkingWith.find((row) => row.sendAddress === 'term_late_0') + expect(installed?.openTarget).toEqual({ kind: 'terminal', handle: 'term_late_0' }) + expect(capture.mock.calls.length).toBeGreaterThan(captures) + // Owner repair may dirty the generation once; the next read must settle, never feed a rebuild loop. + model.read('term_coord') + expect(capture.mock.calls.length).toBeLessThanOrEqual(captures + 2) + const afterInstallation = capture.mock.calls.length + f.owner.recordPtyWorktree('late-pty', TEST_WORKTREE_ID, { + lastOutputAt: 500, + preview: 'unconsumed output' + }) + model.read('term_coord') + expect(capture).toHaveBeenCalledTimes(afterInstallation) + const mutation = (write: () => unknown) => { + const before = capture.mock.calls.length + write() + model.read('term_coord') + expect(capture.mock.calls.length).toBeGreaterThan(before) + model.read('term_coord') + const settled = capture.mock.calls.length + model.read('term_coord') + expect(capture).toHaveBeenCalledTimes(settled) + } + const pty = f.owner.ptysById.get('late-pty')! + mutation(() => f.owner.setPtyConnected(pty, false)) + const disconnected = capture.mock.calls.length + f.owner.setPtyConnected(pty, false) + model.read('term_coord') + expect(capture).toHaveBeenCalledTimes(disconnected) + mutation(() => f.runtime.onPtyData('late-pty', 'resume', 500)) + const resumed = capture.mock.calls.length + const normalEntries = counts.entries + const normalWakes = wake.mock.calls.length + for (let i = 0; i < population; i++) { + f.runtime.onPtyData('late-pty', 'ordinary output', 501 + i) + model.read('term_coord') + } + expect(capture).toHaveBeenCalledTimes(resumed) + expect(counts.entries).toBe(normalEntries) + expect(wake).toHaveBeenCalledTimes(normalWakes) + mutation(() => f.owner.setPtyConnected(pty, false)) + mutation(() => f.runtime.onPtySpawned('late-pty', 'new-process')) + mutation(() => + f.owner.recordPtyWorktree('late-pty', TEST_WORKTREE_ID, { + paneKey: 'tab-moved:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb' + }) + ) + f.runtime.attachWindow(1) + mutation(() => f.owner.beginGraphReload(1)) + mutation(() => f.owner.dropDisconnectedPtyRecord('late-pty')) + expect( + model + .read('term_coord') + .sections.talkingWith.find((row) => row.sendAddress === 'term_late_0')?.openTarget + ).toBeUndefined() + stop() + const beforeReenroll = capture.mock.calls.length + const release = model.subscribe(wake) + model.read('term_coord') + expect(capture).toHaveBeenCalledTimes(beforeReenroll + 1) + release() + } + return { output, acquisition } + } finally { + stop() + db.close() + } + } + try { + for (const population of [3, 30]) { + const baseline = measure(population, false) + const candidate = measure(population, true) + expect(candidate.output).toEqual(baseline.output) + expect(candidate.acquisition.entries).toBeLessThan(baseline.acquisition.entries) + expect(candidate.acquisition.entries).toBeLessThan(10 * (population + 1)) + console.log('production Crew native acquisition', { + population, + baseline: baseline.acquisition, + candidate: candidate.acquisition + }) + } + } finally { + vi.useRealTimers() + } +}) + +it('preserves actual fleet binding, ingestion Dispatch, ordinary attention faults and default IPC effects in separate production runtimes', () => { + vi.useFakeTimers({ now: 1_800_000_000_000 }) + const run = (captured: boolean, fault: boolean) => { + const raw: AgentStatusIpcPayload[] = [] + const observed = new Map() + const effectOrder: string[] = [] + let db: OrchestrationDb + const f = fixture({ + getAgentStatusSnapshot: () => raw, + readObservedAgentStatusPaneIdentity: (pane) => { + effectOrder.push(pane) + if (fault && effectOrder.length === 2) { + db.db.exec('DROP TABLE attempt_observation_facts') + } + return observed.get(pane) ?? { kind: 'unobserved' } + } + }) + db = new OrchestrationDb(':memory:') + f.runtime.setOrchestrationDb(db) + const run = db.createRun({ + objective: 'Fleet', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: PANE + }) + const dispatches: string[] = [] + for (let i = 0; i < 6; i++) { + const paneKey = `fleet-${i}:aaaaaaaa-aaaa-4aaa-8aaa-${String(i).padStart(12, '0')}` + const handle = `term_fleet_${i}` + f.add(`fleet-pty-${i}`, handle, paneKey) + f.owner.recordPtyWorktree(`fleet-pty-${i}`, TEST_WORKTREE_ID, { + incarnationId: `process-${i}` + }) + const task = db.createTask({ runId: run.id, spec: 'Fleet contract' }) + const dispatch = db.createDispatchContext({ + taskId: task.id, + assigneeHandle: handle, + assigneePaneKey: paneKey, + processIncarnation: `fleet-pty-${i}:process-${i}`, + creator: { kind: 'system' }, + maxDepth: 10 + }) + dispatches.push(dispatch.id) + raw.push({ + paneKey, + agentType: 'codex', + state: 'working', + prompt: '', + connectionId: null, + receivedAt: 1_800_000_000_000, + stateStartedAt: 1_800_000_000_000, + ...(i === 3 ? { restoredUnconfirmed: true, isReplay: true } : {}), + ...(i === 4 ? { providerSessionOnly: true } : {}) + }) + if (i !== 1) { + observed.set(paneKey, { + kind: 'observed', + terminalHandle: handle, + processIncarnation: i === 2 ? 'replaced-process' : `fleet-pty-${i}:process-${i}`, + dispatchId: i === 5 ? null : `ingestion-${i}` + }) + } + } + // Late row still belongs to its ingestion Dispatch, even when the ordinary current projection differs. + expect(f.runtime.getAgentStatusOrchestrationContextForPaneKey(raw[0].paneKey)?.dispatchId).toBe( + dispatches[0] + ) + const context = captured ? f.runtime.createTerminalIdentityReadContext() : undefined + let evidence: + | ReturnType + | undefined + let failure: unknown + try { + evidence = f.runtime.getOrchestrationFleetAgentStatusSnapshot(context) + } catch (error) { + failure = error + } + try { + if (fault) { + expect(failure).toBeInstanceOf(Error) + expect(String(failure)).toContain('attempt_observation_facts') + expect(effectOrder).toEqual(raw.slice(0, 2).map((row) => row.paneKey)) + } else { + expect(failure).toBeUndefined() + expect(evidence?.[0].binding).toMatchObject({ kind: 'worker', dispatchId: 'ingestion-0' }) + expect(evidence?.[1].binding).toMatchObject({ kind: 'worker', dispatchId: dispatches[1] }) + expect(evidence?.[2].binding).toEqual({ kind: 'unresolved', reason: 'stale_incarnation' }) + expect(evidence?.[5].binding.kind).toBe('pane') + // Default IPC still acquires the full public context, including attention. + expect(enrichAgentStatusIpcPayload(raw[0], f.runtime).orchestration).toMatchObject({ + dispatchId: dispatches[0], + attention: expect.any(Object) + }) + } + const normalize = (value: unknown) => { + let text = JSON.stringify(value) + for (let i = 0; i < dispatches.length; i++) { + text = text.replaceAll(dispatches[i], `current-${i}`) + } + return JSON.parse(text) + } + return { + evidence: normalize(evidence ?? null), + state: f.state(), + effectOrder, + error: String(failure) + } + } finally { + db.close() + } + } + try { + for (const fault of [false, true]) { + expect(run(true, fault)).toEqual(run(false, fault)) + } + } finally { + vi.useRealTimers() + } +}) + +it('keeps the real OSC hook producer and observation owner authoritative after a newer current Dispatch', () => { + vi.useFakeTimers({ now: 1_800_000_000_000 }) + const run = (captured: boolean) => { + const server = new AgentHookServer() + const observations = new AgentStatusObservedPaneIdentities() + const f = fixture( + agentHookRuntimeDeps(server, observations, () => ({ agentStatusHooksEnabled: false })) + ) + const detach = f.runtime.attachAgentStatusStore(server) + const stop = server.subscribeEnrichedStatus((event) => + recordObservedAgentStatusPaneIdentity(observations, event, f.runtime) + ) + const db = new OrchestrationDb(':memory:') + f.runtime.setOrchestrationDb(db) + f.add('hook-pty', 'term_hook', PANE) + f.owner.recordPtyWorktree('hook-pty', TEST_WORKTREE_ID, { incarnationId: 'hook-process' }) + f.stamp('term_hook', 'hook-pty') + const group = db.createRun({ + objective: 'Observed', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: PANE + }) + const assign = () => + db.createDispatchContext({ + taskId: db.createTask({ runId: group.id, spec: 'Hook contract' }).id, + assigneeHandle: 'term_hook', + assigneePaneKey: PANE, + processIncarnation: 'hook-pty:hook-process', + creator: { kind: 'system' }, + maxDepth: 10 + }) + try { + const first = assign() + f.runtime.onPtyData( + 'hook-pty', + '\x1b]9999;{"state":"working","prompt":"busy","agentType":"codex"}\x07', + 1_800_000_000_000 + ) + expect(server.getStatusSnapshot()).toHaveLength(1) + expect(observations.read(PANE)).toMatchObject({ kind: 'observed', dispatchId: first.id }) + db.completeDispatch(first.id) + const second = assign() + expect(f.runtime.getAgentStatusOrchestrationContextForPaneKey(PANE)?.dispatchId).toBe( + second.id + ) + const evidence = f.runtime.getOrchestrationFleetAgentStatusSnapshot( + captured ? f.runtime.createTerminalIdentityReadContext() : undefined + ) + expect(evidence[0].binding).toMatchObject({ + kind: 'worker', + dispatchId: first.id, + processIncarnation: 'hook-pty:hook-process' + }) + return evidence.map((row) => ({ + ...row, + binding: + row.binding.kind === 'worker' + ? { ...row.binding, dispatchId: '' } + : row.binding + })) + } finally { + stop() + detach() + db.close() + } + } + try { + expect(run(true)).toEqual(run(false)) + } finally { + vi.useRealTimers() + } +}) diff --git a/src/main/runtime/terminal/query/terminal-identity-read-context.ts b/src/main/runtime/terminal/query/terminal-identity-read-context.ts index cac42e824b11..59cdcfb2b3d1 100644 --- a/src/main/runtime/terminal/query/terminal-identity-read-context.ts +++ b/src/main/runtime/terminal/query/terminal-identity-read-context.ts @@ -1,3 +1,10 @@ +import type { AgentSessionRecordReader } from '../../orchestration/structured-session-lineage' +import { + captureAgentSessionRecordInputs, + captureStructuredWorkerReadInputs, + createStructuredWorkerReadContext, + type StructuredWorkerReadContext +} from '../../structured-worker-authority' import { parsePaneKey } from '../../../../shared/stable-pane-id' import type { OrchestrationCompatibilitySshTerminal, @@ -18,21 +25,47 @@ type IdentitySources = { capturePaneOf: () => (pty: RuntimePtyWorktreeRecord) => PtyPane } -type OrderedKeys = Map +type OrderedKeys = ReadonlyMap +type IndexedKeys = Map> -/** Finite owner-read scratch: candidates retain source order; the existing getters select and repair. */ -export class TerminalIdentityReadContext { - private ssh: Map | undefined - private reverse: Map | undefined - private synthetic: Map | undefined +function add(index: IndexedKeys, key: string, value: string, order: number): void { + const bucket = index.get(key) ?? new Map() + bucket.set(value, order) + index.set(key, bucket) +} + +function ordered(keys: OrderedKeys | undefined): string[] { + return [...(keys ?? [])].sort((a, b) => a[1] - b[1]).map(([key]) => key) +} + +/** Lazy immutable candidate facts, shared only within the existing observed input generation. */ +export class TerminalIdentityRawInputs { + private structuredInputs: ReturnType | undefined + private projectionRecords: AgentSessionRecordReader | null | undefined + + captureProjectionRecords( + read: () => AgentSessionRecordReader | null + ): AgentSessionRecordReader | null { + if (this.projectionRecords === undefined) { + this.projectionRecords = captureAgentSessionRecordInputs(read()) + } + return this.projectionRecords + } + + openStructured(): StructuredWorkerReadContext { + this.structuredInputs ??= captureStructuredWorkerReadInputs() + return createStructuredWorkerReadContext(this.structuredInputs) + } + private reverse: IndexedKeys | undefined + private synthetic: IndexedKeys | undefined private leafKeys: Map | undefined - private panePtys: Map | undefined - private leafPtys: Map | undefined + private panePtys: IndexedKeys | undefined + private leafPtys: IndexedKeys | undefined + private ssh: Map | undefined private paneReader: ((pty: RuntimePtyWorktreeRecord) => PtyPane) | undefined - private readonly reverseOrder = new Map() - private readonly handleOrder = new Map() - private readonly reverseFacts = new Map() - private readonly handleFacts = new Map() + private readonly reverseFacts = new Map() + private handleCount = 0 + private readonly handleFacts = new Map() constructor(private readonly source: IdentitySources) {} @@ -41,39 +74,51 @@ export class TerminalIdentityReadContext { return this.paneReader(pty) } - sshAttachmentIds(handle: string): Iterable { - if (!this.ssh) { - this.ssh = new Map() - for (const [id, terminal] of this.source.sshTerminals) { - const ids = this.ssh.get(terminal.handle) ?? [] - ids.push(id) - this.ssh.set(terminal.handle, ids) - } - } - return this.ssh.get(handle) ?? [] + get reverseCaptured(): boolean { + return this.reverse !== undefined + } + get reverseSize(): number { + return this.reverseFacts.size + } + get handlesSize(): number { + return this.handleCount + } + get handlesCaptured(): boolean { + return this.synthetic !== undefined + } + reverseFact(ptyId: string) { + return this.reverseFacts.get(ptyId) + } + handleFact(handle: string) { + return this.handleFacts.get(handle) } - reversePtyIds(handle: string): readonly string[] { + reverseKeys(handle: string): OrderedKeys | undefined { if (!this.reverse) { this.reverse = new Map() for (const [ptyId, mapped] of this.source.reverse) { - this.reverseOrder.set(ptyId, this.reverseOrder.size) - this.reverseFacts.set(ptyId, mapped) - this.add(this.reverse, mapped, ptyId, this.reverseOrder.get(ptyId)!) + const order = this.reverseFacts.size + this.reverseFacts.set(ptyId, { handle: mapped, order }) + add(this.reverse, mapped, ptyId, order) } } - return this.ordered(this.reverse.get(handle)) + return this.reverse.get(handle) } - syntheticHandles(ptyId: string): Iterable { + syntheticKeys(ptyId: string): OrderedKeys | undefined { if (!this.synthetic) { this.synthetic = new Map() + let order = 0 for (const [handle, record] of this.source.handles) { - this.handleOrder.set(handle, this.handleOrder.size) - this.indexHandle(handle, record) + if (record.ptyId && record.tabId.startsWith('pty:')) { + this.handleFacts.set(handle, { ptyId: record.ptyId, order }) + add(this.synthetic, record.ptyId, handle, order) + } + order++ } + this.handleCount = order } - return this.ordered(this.synthetic.get(ptyId)) + return this.synthetic.get(ptyId) } leavesForId(leafId: string): Iterable { @@ -96,10 +141,10 @@ export class TerminalIdentityReadContext { for (const [ptyId, pty] of this.source.ptys) { const pane = this.paneOf(pty).paneKey if (pane !== null) { - this.add(this.panePtys, pane, ptyId, order) + add(this.panePtys, pane, ptyId, order) const parsed = parsePaneKey(pane) if (parsed) { - this.add(this.leafPtys, parsed.leafId, ptyId, order) + add(this.leafPtys, parsed.leafId, ptyId, order) } } order++ @@ -108,63 +153,119 @@ export class TerminalIdentityReadContext { const exact = this.panePtys.get(paneKey) const parsed = parsePaneKey(paneKey) const suffix = parsed ? this.leafPtys?.get(parsed.leafId) : undefined - return this.ordered(new Map([...(exact ?? []), ...(suffix ?? [])])) + return ordered(new Map([...(exact ?? []), ...(suffix ?? [])])) } - /** Only keys written by the issuing owner are reconciled; no inventory rebuild follows repair. */ + sshAttachmentIds(handle: string): Iterable { + if (!this.ssh) { + this.ssh = new Map() + for (const [id, terminal] of this.source.sshTerminals) { + const ids = this.ssh.get(terminal.handle) ?? [] + ids.push(id) + this.ssh.set(terminal.handle, ids) + } + } + return this.ssh.get(handle) ?? [] + } +} + +/** Finite owner-read scratch; retained inputs contain raw candidates, never a selected answer. */ +export class TerminalIdentityReadContext { + private structuredContext: StructuredWorkerReadContext | undefined + private readonly reverseEdits: IndexedKeys = new Map() + private readonly handleEdits: IndexedKeys = new Map() + private readonly reverseFacts = new Map() + private readonly handleFacts = new Map() + private nextReverseOrder: number | undefined + private nextHandleOrder: number | undefined + + constructor( + private readonly source: IdentitySources, + private readonly inputs = new TerminalIdentityRawInputs(source) + ) {} + + get structured(): StructuredWorkerReadContext { + return (this.structuredContext ??= this.inputs.openStructured()) + } + + paneOf = (pty: RuntimePtyWorktreeRecord): PtyPane => this.inputs.paneOf(pty) + captureProjectionRecords = (read: () => AgentSessionRecordReader | null) => + this.inputs.captureProjectionRecords(read) + + leavesForId = (id: string): Iterable => this.inputs.leavesForId(id) + ptysForPane = (pane: string): Iterable => this.inputs.ptysForPane(pane) + sshAttachmentIds = (handle: string): Iterable => this.inputs.sshAttachmentIds(handle) + reversePtyIds = (handle: string): readonly string[] => + ordered(this.reverseEdits.get(handle) ?? this.inputs.reverseKeys(handle)) + syntheticHandles = (ptyId: string): Iterable => + ordered(this.handleEdits.get(ptyId) ?? this.inputs.syntheticKeys(ptyId)) + changedReverseBinding(ptyId: string): void { - if (!this.reverse) { + if (!this.inputs.reverseCaptured) { return } - const prior = this.reverseFacts.get(ptyId) - if (prior !== undefined) { - this.reverse.get(prior)?.delete(ptyId) - } + const prior = this.reverseFacts.has(ptyId) + ? this.reverseFacts.get(ptyId) + : this.inputs.reverseFact(ptyId) const handle = this.source.reverse.get(ptyId) + if (prior?.handle === handle) { + return + } + if (prior) { + this.edit(this.reverseEdits, prior.handle, this.inputs.reverseKeys(prior.handle)).delete( + ptyId + ) + } if (handle !== undefined) { - if (!this.reverseOrder.has(ptyId)) { - this.reverseOrder.set(ptyId, this.reverseOrder.size) - } - this.add(this.reverse, handle, ptyId, this.reverseOrder.get(ptyId)!) - this.reverseFacts.set(ptyId, handle) + this.nextReverseOrder ??= this.inputs.reverseSize + const order = prior?.order ?? this.nextReverseOrder++ + this.edit(this.reverseEdits, handle, this.inputs.reverseKeys(handle)).set(ptyId, order) + this.reverseFacts.set(ptyId, { handle, order }) } else { - this.reverseFacts.delete(ptyId) + this.reverseFacts.set(ptyId, undefined) } } changedHandle(handle: string): void { - if (!this.synthetic) { + if (!this.inputs.handlesCaptured) { return } - const prior = this.handleFacts.get(handle) - if (prior !== undefined) { - this.synthetic.get(prior)?.delete(handle) - this.handleFacts.delete(handle) - } + const prior = this.handleFacts.has(handle) + ? this.handleFacts.get(handle) + : this.inputs.handleFact(handle) const record = this.source.handles.get(handle) - if (record) { - if (!this.handleOrder.has(handle)) { - this.handleOrder.set(handle, this.handleOrder.size) - } - this.indexHandle(handle, record) + if (prior?.ptyId === record?.ptyId && record?.tabId.startsWith('pty:')) { + return } - } - - private indexHandle(handle: string, record: TerminalHandleRecord): void { - if (record.ptyId && record.tabId.startsWith('pty:')) { - this.add(this.synthetic!, record.ptyId, handle, this.handleOrder.get(handle)!) - this.handleFacts.set(handle, record.ptyId) + if (prior) { + this.edit(this.handleEdits, prior.ptyId, this.inputs.syntheticKeys(prior.ptyId)).delete( + handle + ) + } + if (record?.ptyId && record.tabId.startsWith('pty:')) { + this.nextHandleOrder ??= this.inputs.handlesSize + const order = prior?.order ?? this.nextHandleOrder++ + this.edit(this.handleEdits, record.ptyId, this.inputs.syntheticKeys(record.ptyId)).set( + handle, + order + ) + this.handleFacts.set(handle, { ptyId: record.ptyId, order }) + } else { + this.handleFacts.set(handle, undefined) } } - private add(index: Map, key: string, value: string, order: number): void { - const bucket = index.get(key) ?? new Map() - bucket.set(value, order) - index.set(key, bucket) - } - - private ordered(keys: OrderedKeys | undefined): string[] { - return [...(keys ?? [])].sort((a, b) => a[1] - b[1]).map(([key]) => key) + private edit( + index: IndexedKeys, + key: string, + base: OrderedKeys | undefined + ): Map { + let values = index.get(key) + if (!values) { + values = new Map(base) + index.set(key, values) + } + return values } } diff --git a/src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts b/src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts index fdd1fee77acf..2369b8830499 100644 --- a/src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts +++ b/src/main/runtime/terminal/surface/main-terminal-acquisition.test.ts @@ -1,3 +1,15 @@ +import '../../orca-runtime-test-mocks.spec' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { OrcaRuntimeService } from '../../orca-runtime' +import { OrchestrationDb } from '../../orchestration/db' +import { + openTopologyStoreWithAuthority, + emptyTerminalSessionProfile, + FIXTURE_GIT_WORKTREE_ID +} from '../../../persistence/terminal-topology/terminal-topology-profile-fixture' +import { WindowSession } from '../../../persistence/terminal-topology/terminal-topology-window-session-fixture' import { expect, it, vi } from 'vitest' import { getDefaultSettings, getDefaultWorkspaceSession } from '../../../../shared/constants' import { loadWorkspaceLayout } from '../../../../shared/workspace-layout/workspace-layout-load' @@ -79,3 +91,151 @@ it('captures real main partitions once and keeps paired/local/folder qualificati console.log('main partition acquisitions', { population, baseline: population, candidate: 1 }) } }) + +class MainCrewRuntime extends OrcaRuntimeService { + seedPty(id: string, handle: string): void { + this.recordPtyWorktree(id, FIXTURE_GIT_WORKTREE_ID, { connected: true }) + this.handleByPtyId.set(id, handle) + this.handles.set(handle, { + handle, + runtimeId: this.runtimeId, + rendererGraphEpoch: this.rendererGraphEpoch, + worktreeId: FIXTURE_GIT_WORKTREE_ID, + tabId: `pty:${id}`, + leafId: `pty:${id}`, + ptyId: id, + ptyGeneration: 0 + }) + } +} + +it('retires raw main bindings on real Store-only writes with Crew as sole observer and no installed graph', async () => { + for (const population of [3, 30]) { + const directory = mkdtempSync(join(tmpdir(), 'orca-pr34890-main-')) + const { store, authority } = await openTopologyStoreWithAuthority( + directory, + emptyTerminalSessionProfile() + ) + const db = new OrchestrationDb(':memory:') + let stop = () => {} + try { + const saved = new WindowSession(getDefaultWorkspaceSession()) + for (let i = 0; i < population; i++) { + const leaf = `aaaaaaaa-aaaa-4aaa-8aaa-${String(i).padStart(12, '0')}` + saved.addTab(FIXTURE_GIT_WORKTREE_ID, `tab-main-${i}`, leaf) + saved.bind(`tab-main-${i}`, leaf, `pty-main-${i}`) + } + store.setWorkspaceSession(saved.snapshot(), 'local') + await store.flushPendingOrThrowAsync() + const runtime = new MainCrewRuntime(store) + runtime.setOrchestrationDb(db) + runtime.seedPty('coord', 'term_coord') + for (let i = 0; i < population; i++) { + runtime.seedPty(`pty-main-${i}`, `term_main_${i}`) + } + runtime.seedPty('replacement', 'term_replacement') + const pane = 'tab-main-0:aaaaaaaa-aaaa-4aaa-8aaa-000000000000' + const run = db.createRun({ + objective: 'Main source', + coordinatorHandle: 'term_coord', + coordinatorPaneKey: 'coord-pane' + }) + db.createDispatchContext({ + taskId: db.createTask({ runId: run.id, spec: 'Main worker' }).id, + assigneeHandle: 'term_missing_stored', + assigneePaneKey: pane, + creator: { kind: 'system' }, + maxDepth: 10 + }) + const capture = vi.spyOn(runtime, 'createTerminalIdentityRawInputs') + const generations = vi.spyOn(store, 'getPtyBindingGeneration') + stop = runtime.watchOrchestrationCrew(() => {}) + const read = () => runtime.getOrchestrationCrewSnapshot('term_coord').sections.managing[0] + expect(read().openTarget).toEqual({ kind: 'terminal', handle: 'term_main_0' }) + expect(runtime.getTerminalHandleForPaneKey(pane)).toBe('term_main_0') + read() + const initial = capture.mock.calls.length + const visits = generations.mock.calls.length + const irrelevant = store.getWorkspaceSession() + store.setWorkspaceSession({ ...irrelevant, activeTabId: 'tab-main-1' }, 'local') + await store.flushPendingOrThrowAsync() + read() + expect(capture).toHaveBeenCalledTimes(initial) + expect(generations.mock.calls.length - visits).toBe(population) + await store.applyLayoutCommand({ + type: 'renameTab', + workspace: FIXTURE_GIT_WORKTREE_ID, + tabId: 'tab-main-0', + kind: 'custom', + title: 'Named main worker' + }) + expect(read().label).toBe( + runtime.orchestrationSenderNames.nameOf( + { address: 'term_main_0', terminalHandle: 'term_main_0', orcaSessionId: null }, + undefined, + 'Main worker', + null + ) ?? 'Main worker' + ) + expect(capture).toHaveBeenCalledTimes(initial) + const current = store.getWorkspaceSession() + const layout = current.terminalLayoutsByTabId['tab-main-0'] + store.setWorkspaceSession( + { + ...current, + terminalLayoutsByTabId: { + ...current.terminalLayoutsByTabId, + 'tab-main-0': { + ...layout, + ptyIdsByLeafId: { + ...layout.ptyIdsByLeafId, + 'aaaaaaaa-aaaa-4aaa-8aaa-000000000000': 'replacement' + } + } + } + }, + 'local' + ) + await store.flushPendingOrThrowAsync() + expect(runtime.getTerminalHandleForPaneKey(pane)).toBe('term_replacement') + expect(read().openTarget).toEqual({ kind: 'terminal', handle: 'term_replacement' }) + expect(capture.mock.calls.length).toBeGreaterThan(initial) + const leaf = 'aaaaaaaa-aaaa-4aaa-8aaa-000000000000' + const beforeGeneration = store.getPtyBindingGeneration('local', leaf) ?? 0 + const beforeCapture = capture.mock.calls.length + const binding = { + worktreeId: FIXTURE_GIT_WORKTREE_ID, + tabId: 'tab-main-0', + leafId: leaf, + ptyId: 'replacement', + correctStartupCwd: '/main-source' + } + expect(await store.persistPtyBinding(binding, 'local')).toBe(true) + expect(store.getPtyBindingGeneration('local', leaf)).toBe(beforeGeneration + 1) + expect(read().openTarget).toEqual({ kind: 'terminal', handle: 'term_replacement' }) + expect(capture.mock.calls.length).toBeGreaterThan(beforeCapture) + const stable = capture.mock.calls.length + authority.failNextWrite() + await expect( + store.persistPtyBinding({ ...binding, correctStartupCwd: '/rolled-back' }, 'local') + ).rejects.toThrow('profile_state_write_failed') + expect(read().openTarget).toEqual({ kind: 'terminal', handle: 'term_replacement' }) + expect( + store.getWorkspaceSession().tabsByWorktree[FIXTURE_GIT_WORKTREE_ID][0].startupCwd + ).toBe('/main-source') + read() + expect(capture.mock.calls.length).toBeLessThanOrEqual(stable + 1) + console.log('main Store source contract', { + population, + initial, + final: capture.mock.calls.length, + generationReads: generations.mock.calls.length + }) + } finally { + stop() + db.close() + await store.freezeWritesAsync() + rmSync(directory, { recursive: true, force: true }) + } + } +}) diff --git a/src/main/runtime/terminal/surface/pty-pane-query.ts b/src/main/runtime/terminal/surface/pty-pane-query.ts index d2d8ea259432..014952e7e482 100644 --- a/src/main/runtime/terminal/surface/pty-pane-query.ts +++ b/src/main/runtime/terminal/surface/pty-pane-query.ts @@ -1,3 +1,7 @@ +import type { WorkspaceSessionState } from '../../../../shared/workspace-session-state-types' +import { collectLayoutLeafIdsInOrder } from '../../../../shared/workspace-layout/terminal-pane-tree' +import type { WorkspaceLayoutLoadContext } from '../../../../shared/workspace-layout/workspace-layout-load-types' +import { isPaneSleepRecord } from '../../../../shared/agent-session-resume' import { pairedRuntimeHostOfBinding, terminalHoldsPane, @@ -101,3 +105,52 @@ export function findMainTerminalPane( ) return pane ? { worktreeId: pane.worktreeId, tabId: pane.tabId, leafId: pane.leafId } : null } + +/** Raw invalidation inputs only; main's loader and pane qualifier still select every binding. */ +export function mainTerminalSourceInputs( + session: WorkspaceSessionState | null | undefined, + context: WorkspaceLayoutLoadContext +) { + if (!session) { + return null + } + return structuredClone({ + tabs: Object.entries(session.tabsByWorktree ?? {}).map(([key, rows]) => [ + key, + rows.map((row) => [row.id, row.worktreeId, row.ptyId, row.sortOrder, row.createdAt]) + ]), + tabBar: Object.entries(session.unifiedTabs ?? {}).map(([key, rows]) => [ + key, + rows.map((row) => [ + row.id, + row.contentType, + row.entityId, + row.groupId, + row.sortOrder, + row.createdAt + ]) + ]), + groups: Object.entries(session.tabGroups ?? {}).map(([key, groups]) => [ + key, + groups.map((group) => [group.id, group.tabOrder]) + ]), + groupLayouts: session.tabGroupLayouts, + layouts: Object.entries(session.terminalLayoutsByTabId ?? {}).map(([id, layout]) => [ + id, + collectLayoutLeafIdsInOrder(layout.root), + layout.ptyIdsByLeafId, + collectLayoutLeafIdsInOrder(layout.root).map((leaf) => [ + leaf, + context.ptyGenerationOf?.(leaf) + ]) + ]), + incarnations: session.terminalPtyIncarnationsByPaneKey, + sleeping: Object.entries(session.sleepingAgentSessionsByPaneKey ?? {}).map(([key, record]) => [ + key, + isPaneSleepRecord(record) + ]), + retired: session.terminalSurfaceTombstonesByPaneKey, + closedTabs: session.closedTerminalTabTombstonesByTabId, + closedPanes: session.closedTerminalPanesByPaneKey + }) +} diff --git a/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts b/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts index 45bc1be3352e..36ab9d919edc 100644 --- a/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts +++ b/src/main/runtime/workspaces/persisted-surfaces/automation-operations.ts @@ -196,12 +196,13 @@ export abstract class OrcaRuntimeWithAutomationOperations extends OrcaRuntimeWit } private readonly crewReadModel = new CrewReadModel( - () => + (previous) => readCrewRuntimeInputs( this, this._orchestrationDb, existsSync(this.orchestrationDbPath()), - getPublishedHostDescriptor(this.runtimeId)?.installationId ?? this.runtimeId + getPublishedHostDescriptor(this.runtimeId)?.installationId ?? this.runtimeId, + previous ), (wake) => watchCrewRuntimeSources( From 8c343891bb6a064d99ceac86a5c1d05c7dd36438 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:24:34 -0700 Subject: [PATCH 027/164] Exercise crew generation retirement through actual source owners --- .../agent-session-record-store-slot.test.ts | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) diff --git a/src/main/runtime/agent-session-record-store-slot.test.ts b/src/main/runtime/agent-session-record-store-slot.test.ts index f70dcdea5cfc..dea1e4bcd917 100644 --- a/src/main/runtime/agent-session-record-store-slot.test.ts +++ b/src/main/runtime/agent-session-record-store-slot.test.ts @@ -1,3 +1,9 @@ +import './orca-runtime-test-mocks.spec' +import { store as runtimeStore } from './orca-runtime-test-fixtures.spec' +import { OrcaRuntimeService } from './orca-runtime' +import { OrchestrationDb } from './orchestration/db' +import { subscribeCrew } from './orchestration/crew/crew-stream' +import { setStructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-registry' import { sessionCrewChanges } from './orchestration/crew/crew-changes' /** Early launch admission and the later chat host must share one record-store writer. */ @@ -117,3 +123,102 @@ it('publishes source installation and release even when opening an empty record stop() } }) + +it('retires a sole Crew observer generation on empty-source open, real name writes, host install/replacement and release', async () => { + const now = 1_800_000_000_000 + vi.useFakeTimers({ now }) + const runtime = new OrcaRuntimeService(runtimeStore) + const db = new OrchestrationDb(':memory:') + runtime.setOrchestrationDb(db) + const captures = vi.spyOn(runtime, 'createTerminalIdentityRawInputs') + const frames: unknown[] = [] + const flush = async () => { + await Promise.resolve() + await Promise.resolve() + } + const read = () => runtime.getOrchestrationCrewSnapshot('term_source_coordinator') + const stop = subscribeCrew(read, runtime.watchOrchestrationCrew, (frame) => frames.push(frame)) + try { + await flush() + expect(captures).toHaveBeenCalledOnce() + const opened = await openAgentSessionRecordStoreOnce(location()) + await flush() + expect(captures).toHaveBeenCalledTimes(2) + await openAgentSessionRecordStoreOnce(location()) + await flush() + expect(captures).toHaveBeenCalledTimes(2) + const sessionId = 'chat-source-availability-0001' + await opened.store.reserveOwner({ + sessionId, + location: { + executionHostId: 'local', + wslDistro: null, + workspaceId: 'workspace-1', + workspaceKind: 'folder' + }, + provider: 'codex', + accountHome: { variable: 'CODEX_HOME', path: '/tmp/unused-source-fixture' }, + expectedFence: null, + spawnToken: 'source-only-no-process', + claimKeyId: 'key-1', + handoffOperationId: null, + probe: { outcome: 'reservation-unused' }, + operation: { + callerKey: 'fixture', + operationId: `${now}-${'a'.repeat(32)}`, + fingerprint: 'source-availability' + }, + now + }) + await opened.store.setConversationName(sessionId, 'Available chat') + const message = db.insertMessage({ + from: 'term_source_coordinator', + to: `orca_session_id:${sessionId}`, + subject: 'Recent peer' + }) + db.db + .prepare('UPDATE messages SET created_at = ? WHERE sequence = ?') + .run(new Date(now).toISOString(), message.sequence) + await flush() + expect(read().sections.talkingWith[0].label).toBe('Available chat') + const host = await ensureStructuredAgentSessionHost({ + ...location(), + claimKeyId: 'key-1', + resolveWorkspacePath: async () => stateDirectory, + resolveClaudeAuthPolicy: () => ({ account: 'managed' }), + resolveEnvironment: async () => ({}), + resolveLaunchArgs: () => [] + }) + await flush() + const afterInstall = captures.mock.calls.length + setStructuredAgentSessionHost(host) + await flush() + expect(captures).toHaveBeenCalledTimes(afterInstall) + setStructuredAgentSessionHost(null) + await flush() + expect(captures).toHaveBeenCalledTimes(afterInstall + 1) + setStructuredAgentSessionHost(host) + await flush() + expect(captures).toHaveBeenCalledTimes(afterInstall + 2) + const beforeRename = captures.mock.calls.length + await opened.store.setConversationName(sessionId, 'Renamed without process') + await flush() + expect(captures).toHaveBeenCalledTimes(beforeRename) + expect(read().sections.talkingWith[0].label).toBe('Renamed without process') + await stopStructuredAgentSessionRuntime() + await flush() + expect(captures.mock.calls.length).toBeGreaterThan(beforeRename) + expect(read().sections.talkingWith[0].label).not.toBe('Renamed without process') + stop() + const afterStop = captures.mock.calls.length + await openAgentSessionRecordStoreOnce(location()) + await flush() + expect(captures).toHaveBeenCalledTimes(afterStop) + expect(frames.length).toBeGreaterThan(2) + } finally { + stop() + await stopStructuredAgentSessionRuntime() + db.close() + vi.useRealTimers() + } +}) From 734e2e97f03459e5cb8f283653cf4fbfd0a99f22 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:38:39 -0700 Subject: [PATCH 028/164] Retire crew inputs on consumed ownership and visibility writes --- .../agent-session-record-store-slot.test.ts | 115 ++++++++++++++++++ .../agent-session-store-transactions.ts | 2 + .../crew/crew-mutation-notifications.ts | 22 ++++ 3 files changed, 139 insertions(+) diff --git a/src/main/runtime/agent-session-record-store-slot.test.ts b/src/main/runtime/agent-session-record-store-slot.test.ts index dea1e4bcd917..17ae6cc27091 100644 --- a/src/main/runtime/agent-session-record-store-slot.test.ts +++ b/src/main/runtime/agent-session-record-store-slot.test.ts @@ -5,6 +5,8 @@ import { OrchestrationDb } from './orchestration/db' import { subscribeCrew } from './orchestration/crew/crew-stream' import { setStructuredAgentSessionHost } from '../native-chat/agent-session-wire/structured-agent-session-registry' import { sessionCrewChanges } from './orchestration/crew/crew-changes' +import { holdStructuredWorker } from './structured-worker-authority' +import type { StructuredWorkerIdentity } from './structured-worker-identity' /** Early launch admission and the later chat host must share one record-store writer. */ import { mkdtemp, rm, writeFile } from 'node:fs/promises' @@ -200,6 +202,119 @@ it('retires a sole Crew observer generation on empty-source open, real name writ setStructuredAgentSessionHost(host) await flush() expect(captures).toHaveBeenCalledTimes(afterInstall + 2) + const identity: StructuredWorkerIdentity = { + handle: 'structworker_source-availability', + sessionId, + agent: 'codex', + paneKey: 'session-source:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', + processIncarnation: `structured:${sessionId}`, + worktreeId: 'workspace-1', + hostScope: { kind: 'local', hostId: 'local' } + } + const held = (worker = identity) => { + const latest = captures.mock.results.at(-1) + if (latest?.type !== 'return') { + throw new Error('Crew did not capture raw identity inputs') + } + const context = runtime.createTerminalIdentityReadContext(latest.value) + const actual = holdStructuredWorker(worker, db, undefined, context.structured) + const expected = holdStructuredWorker(worker, db) + expect(actual.kind).toBe(expected.kind) + if ('running' in actual && 'running' in expected) { + expect(actual.running.record.ownerObservation.claimStatus).toBe( + expected.running.record.ownerObservation.claimStatus + ) + } + return actual.kind + } + expect(held()).toBe('held') + const fence = opened.store.getRecord(sessionId)!.lease.runtimeFence + await opened.store.commitProcessIdentity({ + sessionId, + fence, + process: { + hostId: 'local', + pid: 999999, + processStartTimeMs: now, + spawnToken: 'source-only-no-process' + }, + now + }) + await opened.store.proveOwner({ sessionId, fence, now }) + await flush() + expect(held()).toBe('held') + await opened.store.evictProvenDeadOwner({ + sessionId, + expectedFence: fence, + probe: { outcome: 'pid-absent' }, + now: now + 1 + }) + await flush() + expect(held()).toBe('not-held') + const beforeShow = captures.mock.calls.length + await opened.store.showSessionTabs([sessionId]) + await flush() + expect(captures).toHaveBeenCalledTimes(beforeShow + 1) + expect(held()).toBe('held') + await opened.store.setSessionTabVisibility(sessionId, true) + await flush() + expect(captures).toHaveBeenCalledTimes(beforeShow + 1) + await opened.store.setSessionTabVisibility(sessionId, false) + await flush() + expect(captures).toHaveBeenCalledTimes(beforeShow + 2) + expect(held()).toBe('not-held') + await opened.store.setSessionTabVisibility(sessionId, true) + const run = db.createRun({ + objective: 'Source custody', + coordinatorHandle: 'term_source_coordinator', + coordinatorPaneKey: 'source-coordinator:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' + }) + for (const mode of ['archived', 'dead'] as const) { + const worker = { ...identity, handle: `${identity.handle}_${mode}` } + const start = db.createStartingWorkerDispatch({ + taskSpec: `Custody ${mode}`, + taskRunId: run.id, + startOptions: {}, + creator: { kind: 'system' }, + maxDepth: 10 + }) + db.prepareStartingWorkerAuthority({ + dispatchId: start.dispatch.id, + handle: worker.handle, + paneKey: worker.paneKey, + processIncarnation: worker.processIncarnation, + worktreeId: worker.worktreeId, + hostScope: JSON.stringify(worker.hostScope), + terminalOwnership: 'created', + setupState: 'not_applicable', + effects: [] + }) + db.failWorkerStart(start.dispatch.id, 'agent_readiness', 'Agent did not start') + const resource = db.getWorkerTerminalResourceByOwner(start.dispatch.id)! + if (mode === 'archived') { + db.requestWorkerTerminalRelease(start.dispatch.id) + } + await flush() + expect(held(worker)).toBe('held') + const beforeRelease = captures.mock.calls.length + const release = () => + mode === 'archived' + ? db.settleWorkerTerminalRelease(resource.id) + : db.settleDeadWorkerTerminalRelease({ + requestingDispatchId: start.dispatch.id, + resourceId: resource.id, + processIncarnation: worker.processIncarnation + }) + release() + await flush() + expect(captures).toHaveBeenCalledTimes(beforeRelease + 1) + expect(held(worker)).toBe('not-held') + release() + await flush() + expect(captures).toHaveBeenCalledTimes(beforeRelease + 1) + } + db.resetTasks() + await flush() const beforeRename = captures.mock.calls.length await opened.store.setConversationName(sessionId, 'Renamed without process') await flush() diff --git a/src/main/runtime/agent-session-store-transactions.ts b/src/main/runtime/agent-session-store-transactions.ts index e3c5122835b5..e58808732fd3 100644 --- a/src/main/runtime/agent-session-store-transactions.ts +++ b/src/main/runtime/agent-session-store-transactions.ts @@ -229,6 +229,7 @@ export class AgentSessionStoreTransactions { freezeRows(draft, writes) this.published = draft const topologyChanged = + writes.sessionTabs !== null || writes.records.remove.length > 0 || writes.records.upsert.some(([id]) => { const before = published.records.get(id) @@ -236,6 +237,7 @@ export class AgentSessionStoreTransactions { return ( !before || !after || + before.lease.claimStatus !== after.lease.claimStatus || before.provider !== after.provider || before.location !== after.location || before.conversationCommand !== after.conversationCommand diff --git a/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts b/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts index 7d161cd284dc..e126392db592 100644 --- a/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts +++ b/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts @@ -86,6 +86,28 @@ export function attachCrewMutationNotifications(ctor: { prototype: object }): vo ) { throw new Error('Crew notifications require installed orchestration methods') } + if (hasDomainMethod(prototype, 'settleWorkerTerminalRelease')) { + const release = prototype.settleWorkerTerminalRelease + prototype.settleWorkerTerminalRelease = function (this: OrchestrationDb, resourceId) { + const before = this.getWorkerTerminalResource(resourceId)?.release_state + const result = release.call(this, resourceId) + if (before !== result.release_state) { + this.crewChanges.notify(new Set(['topology'])) + } + return result + } + } + if (hasDomainMethod(prototype, 'settleDeadWorkerTerminalRelease')) { + const release = prototype.settleDeadWorkerTerminalRelease + prototype.settleDeadWorkerTerminalRelease = function (this: OrchestrationDb, params) { + const before = this.getWorkerTerminalResource(params.resourceId)?.release_state + const result = release.call(this, params) + if (before !== result.resource.release_state) { + this.crewChanges.notify(new Set(['topology'])) + } + return result + } + } const sourceIdentity = prototype.getOrCreateLocalMutationCallerFingerprint prototype.getOrCreateLocalMutationCallerFingerprint = function (this: OrchestrationDb) { const known = this.localMutationCallerFingerprint From 61695edcbc2d02f737cf9c9323d8b0656175cd69 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 19:53:32 -0700 Subject: [PATCH 029/164] Use typed crew mutation and fixture access --- .../crew/crew-cli-addresses.test.ts | 20 +++++++--------- .../crew/crew-mutation-notifications.ts | 24 +++++++++++++------ 2 files changed, 25 insertions(+), 19 deletions(-) diff --git a/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts b/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts index e9ab331b0d98..a6830199d171 100644 --- a/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts +++ b/src/main/runtime/orchestration/crew/crew-cli-addresses.test.ts @@ -220,7 +220,12 @@ it('keeps crew as the only observer for title, settings and mirrored-name source return () => sessionListeners.delete(listener) } }) - const runtime = new OrcaRuntimeService(store) + class CrewNameRuntime extends OrcaRuntimeService { + publishClientEvent(event: RuntimeClientEvent): void { + this.emitClientEvent(event) + } + } + const runtime = new CrewNameRuntime(store) const { OrchestrationDb } = await import('../db') const { subscribeCrew } = await import('./crew-stream') const db = new OrchestrationDb(':memory:') @@ -299,23 +304,14 @@ it('keeps crew as the only observer for title, settings and mirrored-name source selection.mockClear() names.mockClear() // RuntimeClientEventBus is the real production filter. Crew is its only enrolled consumer. - const publish: unknown = Reflect.get(runtime, 'emitClientEvent') - if (typeof publish !== 'function') { - throw new Error('Missing runtime client-event publication boundary') - } - const events = { - emitClientEvent: (event: RuntimeClientEvent): void => { - Reflect.apply(publish, runtime, [event]) - } - } - events.emitClientEvent({ + runtime.publishClientEvent({ type: 'terminalSideEffects', batch: { ptyId: 'pty', seq: 1, facts: [{ kind: 'bell' }] } }) await Promise.resolve() expect(selection).not.toHaveBeenCalled() expect(names).not.toHaveBeenCalled() - events.emitClientEvent({ + runtime.publishClientEvent({ type: 'terminalSideEffects', batch: { ptyId: 'pty', diff --git a/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts b/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts index e126392db592..bf91088f0f91 100644 --- a/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts +++ b/src/main/runtime/orchestration/crew/crew-mutation-notifications.ts @@ -1,5 +1,8 @@ import type { OrchestrationDb } from '../db' +type CrewMutationPrototype = Partial +type CrewMutationInvocation = (this: OrchestrationDb, ...args: unknown[]) => unknown + const mutations = [ 'createRemoteDispatchAttachment', 'prepareRemoteAttachmentAuthority', @@ -78,7 +81,7 @@ const trafficMutations: ReadonlySet = new Set([ ]) /** Wake after the synchronous outer mutation; nested writes coalesce and rolled-back reads compare equal. */ -export function attachCrewMutationNotifications(ctor: { prototype: object }): void { +export function attachCrewMutationNotifications(ctor: { prototype: CrewMutationPrototype }): void { const prototype = ctor.prototype if ( !hasDomainMethod(prototype, 'getOrCreateLocalMutationCallerFingerprint') || @@ -126,15 +129,15 @@ export function attachCrewMutationNotifications(ctor: { prototype: object }): vo return result } for (const name of mutations) { - if (!hasDomainMethod(prototype, name)) { + if (!hasCrewMutationInvocation(prototype, name)) { continue } - const original = prototype[name] + const original: CrewMutationInvocation = prototype[name] Object.defineProperty(ctor.prototype, name, { configurable: true, writable: true, value(this: OrchestrationDb, ...args: unknown[]) { - const result: unknown = Reflect.apply(original, this, args) + const result = original.apply(this, args) if ( typeof result === 'object' && result !== null && @@ -152,8 +155,15 @@ export function attachCrewMutationNotifications(ctor: { prototype: object }): vo } function hasDomainMethod( - prototype: object, + prototype: CrewMutationPrototype, + name: K +): prototype is CrewMutationPrototype & Pick { + return name in prototype && typeof prototype[name] === 'function' +} + +function hasCrewMutationInvocation( + prototype: CrewMutationPrototype, name: K -): prototype is object & Pick { - return name in prototype && typeof Reflect.get(prototype, name) === 'function' +): prototype is CrewMutationPrototype & Record { + return hasDomainMethod(prototype, name) } From 95fcb77155427237ed6e201288b2a3a34bbd8084 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Wed, 28 Oct 2026 20:06:32 -0700 Subject: [PATCH 030/164] fix: use owned crew styles and committed render counters --- ...veChatStructuredSession.crew-pane.test.tsx | 10 ++++-- .../use-orchestration-crew.test.tsx | 34 +++++++++++-------- .../orchestration-crew/CrewRowDetails.tsx | 2 +- .../OrchestrationCrewPanel.tsx | 9 ++--- 4 files changed, 33 insertions(+), 22 deletions(-) diff --git a/src/renderer/src/components/native-chat/NativeChatStructuredSession.crew-pane.test.tsx b/src/renderer/src/components/native-chat/NativeChatStructuredSession.crew-pane.test.tsx index 47bb02693454..c39d95398528 100644 --- a/src/renderer/src/components/native-chat/NativeChatStructuredSession.crew-pane.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatStructuredSession.crew-pane.test.tsx @@ -76,10 +76,14 @@ it('handles sibling-composer Escape at the actual native pane boundary and keeps /> ) - const roots = view.container.querySelectorAll('[data-native-chat-root]') + const roots = view.container.querySelectorAll('[data-native-chat-root]') expect(roots).toHaveLength(2) - const pane = within(roots[0]), - other = within(roots[1]) + const [firstRoot, secondRoot] = roots + if (!(firstRoot instanceof HTMLElement) || !(secondRoot instanceof HTMLElement)) { + throw new Error('Expected two native chat pane elements') + } + const pane = within(firstRoot), + other = within(secondRoot) await user.click(pane.getByRole('button', { name: 'Show crew: 1 workers' })) await user.click(other.getByRole('button', { name: 'Show crew: 1 workers' })) const composer = pane.getByRole('textbox', { name: 'Message' }) diff --git a/src/renderer/src/components/native-chat/use-orchestration-crew.test.tsx b/src/renderer/src/components/native-chat/use-orchestration-crew.test.tsx index 9a2f377f5cd1..4c196a0b23b3 100644 --- a/src/renderer/src/components/native-chat/use-orchestration-crew.test.tsx +++ b/src/renderer/src/components/native-chat/use-orchestration-crew.test.tsx @@ -1,29 +1,33 @@ // @vitest-environment happy-dom import { act, cleanup, render } from '@testing-library/react' +import { useLayoutEffect } from 'react' import { afterEach, expect, it, vi } from 'vitest' import type { RuntimeClientTarget } from '../../../../shared/runtime-client-target' import type { RuntimeRpcSubscriptionHandlers } from '@/runtime/runtime-rpc-subscribe' import { replaceRuntimeEnvironmentRevisions } from '@/runtime/runtime-environment-revision' import { useOrchestrationCrew } from './use-orchestration-crew' -const rig = vi.hoisted(() => ({ - streams: [] as { +const rig = vi.hoisted(() => { + const streams: { target: RuntimeClientTarget party: string handlers: RuntimeRpcSubscriptionHandlers unsubscribe: ReturnType - }[], - listeners: new Set<() => void>(), - state: { - unusedLocalState: 0, - runtimeStatusByEnvironmentId: new Map([ - [ - 'crew-host', - { status: { runtimeId: 'runtime-one' }, connectionGeneration: 1, hostContactEpoch: 1 } - ] - ]) + }[] = [] + return { + streams, + listeners: new Set<() => void>(), + state: { + unusedLocalState: 0, + runtimeStatusByEnvironmentId: new Map([ + [ + 'crew-host', + { status: { runtimeId: 'runtime-one' }, connectionGeneration: 1, hostContactEpoch: 1 } + ] + ]) + } } -})) +}) vi.mock('@/runtime/runtime-rpc-subscribe', () => ({ subscribeRuntimeRpc: vi.fn( async ( @@ -67,7 +71,9 @@ function Pane({ renderCount: () => void }) { const crew = useOrchestrationCrew(target, party) - renderCount() + useLayoutEffect(() => { + renderCount() + }) return ( <> diff --git a/src/renderer/src/components/orchestration-crew/CrewRowDetails.tsx b/src/renderer/src/components/orchestration-crew/CrewRowDetails.tsx index caae8deb5b29..bff891319159 100644 --- a/src/renderer/src/components/orchestration-crew/CrewRowDetails.tsx +++ b/src/renderer/src/components/orchestration-crew/CrewRowDetails.tsx @@ -20,7 +20,7 @@ export function CrewRowDetails({ row }: { row: OrchestrationCrewRow }) {
{row.task ? ( <> - + {row.task.state} {row.task.title} diff --git a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx index ee9629e87f58..be0f4ff85871 100644 --- a/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx +++ b/src/renderer/src/components/orchestration-crew/OrchestrationCrewPanel.tsx @@ -202,7 +202,7 @@ function CrewPanelContent({ ref={tab} variant="outline" size="xs" - className="absolute right-0 top-2 max-w-80 rounded-r-none bg-card text-card-foreground" + className="absolute right-0 top-2 max-w-80" aria-label={`Show crew: ${label}`} aria-expanded={false} onClick={() => changeOpen(true)} @@ -222,8 +222,8 @@ function CrewPanelContent({ {pending > 0 ? ( - - {pending} + + {pending} {pending} waiting for you @@ -257,7 +257,8 @@ function CrewRowView({ row, target }: { row: OrchestrationCrewRow; target: Runti