diff --git a/src/main/runtime/orca-runtime-stop-requested-pty-ids.ts b/src/main/runtime/orca-runtime-stop-requested-pty-ids.ts index 4989245fdf6a..d29682f4bef1 100644 --- a/src/main/runtime/orca-runtime-stop-requested-pty-ids.ts +++ b/src/main/runtime/orca-runtime-stop-requested-pty-ids.ts @@ -20,6 +20,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 { RuntimeDelegatedWorktreeEdgeProjection } from './runtime-delegated-worktree-edge-projection' import { RuntimeTerminalList } from './runtime-terminal-list' import { RuntimeManagedWorktreeQueries } from './runtime-managed-worktree-queries' import { RuntimePtyForegroundAgent } from './runtime-pty-foreground-agent' @@ -114,6 +115,12 @@ export class OrcaRuntimeWithStopRequestedPtyIds extends OrcaRuntimeWithRuntimeId getAgentStatusSnapshot: () => this.getOrchestrationFleetAgentStatusSnapshot() }) + protected readonly delegatedWorktreeEdgeProjection = new RuntimeDelegatedWorktreeEdgeProjection({ + getDb: () => this.getOrchestrationDbIfAvailable(), + getWorktreeId: (handle) => this.getTerminalWorktreeIdForHandle(handle), + getHandleForPaneKey: (paneKey) => this.getTerminalHandleForPaneKey(paneKey) + }) + protected readonly terminalList = new RuntimeTerminalList({ getGraphEpoch: () => (this.graphStatus === 'ready' ? this.rendererGraphEpoch : null), assertGraphEpoch: (epoch) => this.assertStableReadyGraph(epoch), diff --git a/src/main/runtime/orca-runtime-sync-window-graph.ts b/src/main/runtime/orca-runtime-sync-window-graph.ts index 893c51c68cce..1b7c8e2e4aa8 100644 --- a/src/main/runtime/orca-runtime-sync-window-graph.ts +++ b/src/main/runtime/orca-runtime-sync-window-graph.ts @@ -315,6 +315,7 @@ export class OrcaRuntimeWithSyncWindowGraph extends OrcaRuntimeWithAttachWindow } const agentOrchestrationByPaneKey = this.agentOrchestrationProjection.buildByPaneKey() + const delegatedEdges = this.delegatedWorktreeEdgeProjection.build() const nativeChatLaunchDraftResolutions = this.getNativeChatLaunchDraftResolutionClientEventSnapshot().map( ({ tabId, text, createdAt }) => ({ tabId, text, createdAt }) @@ -322,6 +323,11 @@ export class OrcaRuntimeWithSyncWindowGraph extends OrcaRuntimeWithAttachWindow return { ...this.getStatus(), ...(agentOrchestrationByPaneKey ? { agentOrchestrationByPaneKey } : {}), + // An unanswerable db publishes the unavailable flag instead of `[]`, so readers + // keep the edges they already have rather than un-nesting every delegated card. + ...(delegatedEdges.known + ? { delegatedWorktreeEdges: delegatedEdges.edges } + : { delegatedWorktreeEdgesUnavailable: true }), ...(nativeChatLaunchDraftResolutions.length > 0 ? { nativeChatLaunchDraftResolutions } : {}), ...(mobileSessionResyncWorktrees.size > 0 ? { mobileSessionResyncWorktrees: [...mobileSessionResyncWorktrees] } diff --git a/src/main/runtime/orchestration/db/federation/federated-dispatch-store.ts b/src/main/runtime/orchestration/db/federation/federated-dispatch-store.ts index 2fa06dcb37a6..991775028d89 100644 --- a/src/main/runtime/orchestration/db/federation/federated-dispatch-store.ts +++ b/src/main/runtime/orchestration/db/federation/federated-dispatch-store.ts @@ -84,6 +84,40 @@ export function isFederatedDispatchRelayEligible( ) } +export type DelegatedWorktreePlacementRow = { + dispatch_id: string + environment_id: string + remote_worktree_id: string + creator_handle: string | null + creator_pane_key: string | null +} + +/** + * Where each remote worker landed, and which coordinator terminal sent it. + * + * Settled Dispatches are included on purpose: a released worker keeps its + * workspace, and its card should not jump out of the tree when it finishes. + * Newest first, so the cap keeps the most recent placements. + */ +export function listDelegatedWorktreePlacements( + this: OrchestrationDb, + limit: number +): DelegatedWorktreePlacementRow[] { + const rows = this.db + .prepare( + `SELECT fd.dispatch_id, fd.environment_id, fd.remote_worktree_id, + dc.creator_handle, dc.creator_pane_key + FROM federated_dispatches fd + INNER JOIN dispatch_contexts dc ON dc.id = fd.dispatch_id + WHERE fd.remote_worktree_id IS NOT NULL + ORDER BY fd.rowid DESC + LIMIT ?` + ) + .all(limit) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the SELECT list names exactly these five columns. + return rows as DelegatedWorktreePlacementRow[] +} + export function updateFederatedDispatchResources( this: OrchestrationDb, params: { @@ -129,6 +163,7 @@ export type FederatedDispatchStoreMethods = { getFederatedDispatch: typeof getFederatedDispatch listFederatedDispatchesByIds: typeof listFederatedDispatchesByIds listActiveFederatedDispatches: typeof listActiveFederatedDispatches + listDelegatedWorktreePlacements: typeof listDelegatedWorktreePlacements findNextTerminalFederatedDispatchPendingAcknowledgment: typeof findNextTerminalFederatedDispatchPendingAcknowledgment isFederatedDispatchRelayEligible: typeof isFederatedDispatchRelayEligible updateFederatedDispatchResources: typeof updateFederatedDispatchResources @@ -140,6 +175,7 @@ export function attachFederatedDispatchStore(ctor: { prototype: object }): void getFederatedDispatch, listFederatedDispatchesByIds, listActiveFederatedDispatches, + listDelegatedWorktreePlacements, findNextTerminalFederatedDispatchPendingAcknowledgment, isFederatedDispatchRelayEligible, updateFederatedDispatchResources, diff --git a/src/main/runtime/runtime-delegated-worktree-edge-projection.test.ts b/src/main/runtime/runtime-delegated-worktree-edge-projection.test.ts new file mode 100644 index 000000000000..5ac95c4eb1cb --- /dev/null +++ b/src/main/runtime/runtime-delegated-worktree-edge-projection.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, it } from 'vitest' +import { RuntimeDelegatedWorktreeEdgeProjection } from './runtime-delegated-worktree-edge-projection' + +type Placement = { + dispatch_id: string + environment_id: string + remote_worktree_id: string + creator_handle: string | null + creator_pane_key: string | null +} + +function projection(args: { + placements?: Placement[] + worktreeByHandle?: Record + handleByPaneKey?: Record + db?: 'missing' | 'without-query' +}): RuntimeDelegatedWorktreeEdgeProjection { + const db = + args.db === 'missing' + ? null + : args.db === 'without-query' + ? {} + : { listDelegatedWorktreePlacements: () => args.placements ?? [] } + return new RuntimeDelegatedWorktreeEdgeProjection({ + getDb: () => db, + getWorktreeId: (handle) => args.worktreeByHandle?.[handle] ?? null, + getHandleForPaneKey: (paneKey) => args.handleByPaneKey?.[paneKey] ?? null + }) +} + +const placement: Placement = { + dispatch_id: 'ctx_1', + environment_id: 'env-1', + remote_worktree_id: 'repo-remote::/home/ubuntu/worker', + creator_handle: 'term_coordinator', + creator_pane_key: 'pane-1' +} + +describe('RuntimeDelegatedWorktreeEdgeProjection', () => { + it('pairs the remote worktree with the coordinator terminal that dispatched it', () => { + const edges = projection({ + placements: [placement], + worktreeByHandle: { term_coordinator: 'repo-1::/home/alex/coordinator' } + }).build() + expect(edges).toEqual({ + known: true, + edges: [ + { + parentWorktreeId: 'repo-1::/home/alex/coordinator', + childHostId: 'runtime:env-1', + childWorktreeId: 'repo-remote::/home/ubuntu/worker', + dispatchId: 'ctx_1' + } + ] + }) + }) + + it('falls back to the pane key when the handle was reminted by a restart', () => { + const edges = projection({ + placements: [placement], + handleByPaneKey: { 'pane-1': 'term_reminted' }, + worktreeByHandle: { term_reminted: 'repo-1::/home/alex/coordinator' } + }).build() + expect(edges.known && edges.edges[0]?.parentWorktreeId).toBe('repo-1::/home/alex/coordinator') + }) + + it('drops a placement whose coordinator terminal is gone', () => { + expect(projection({ placements: [placement] }).build()).toEqual({ known: true, edges: [] }) + }) + + it('keeps an edge whose coordinator and worker share a bare id on different hosts', () => { + const edges = projection({ + placements: [placement], + worktreeByHandle: { term_coordinator: placement.remote_worktree_id } + }).build() + expect(edges).toEqual({ + known: true, + edges: [ + { + parentWorktreeId: placement.remote_worktree_id, + childHostId: 'runtime:env-1', + childWorktreeId: placement.remote_worktree_id, + dispatchId: 'ctx_1' + } + ] + }) + }) + + it('separates a db that cannot answer from a db that answers zero', () => { + expect(projection({ db: 'missing' }).build()).toEqual({ known: false }) + expect(projection({ db: 'without-query' }).build()).toEqual({ known: false }) + expect(projection({ placements: [] }).build()).toEqual({ known: true, edges: [] }) + }) +}) diff --git a/src/main/runtime/runtime-delegated-worktree-edge-projection.ts b/src/main/runtime/runtime-delegated-worktree-edge-projection.ts new file mode 100644 index 000000000000..ebd5a77ac6e6 --- /dev/null +++ b/src/main/runtime/runtime-delegated-worktree-edge-projection.ts @@ -0,0 +1,82 @@ +import { toRuntimeExecutionHostId } from '../../shared/execution-host' +import type { DelegatedWorktreeEdge } from '../../shared/worktree/delegated-worktree-edge' +import type { DelegatedWorktreePlacementRow } from './orchestration/db/federation/federated-dispatch-store' + +/** Enough for any realistic sidebar; the renderer drops edges whose rows it cannot see anyway. */ +const MAX_DELEGATED_EDGES = 500 + +/** Only the placement query, so a test — and an older db without it — needs no stand-in for the rest. */ +type DelegatedWorktreePlacementSource = { + listDelegatedWorktreePlacements?: (limit: number) => DelegatedWorktreePlacementRow[] +} + +type DelegatedWorktreeEdgeDependencies = { + getDb(): DelegatedWorktreePlacementSource | null + /** Worktree the coordinator terminal runs in, by handle. */ + getWorktreeId(handle: string): string | null + /** Handles are minted per process; after a restart only the pane identity still names the terminal. */ + getHandleForPaneKey(paneKey: string): string | null +} + +/** + * What this runtime knows about its coordinated placements right now. + * + * `known: true` with no edges is a real answer — this runtime coordinated + * nothing. A db that is not up yet, or predates the placement query, cannot + * answer at all, and publishing that as emptiness would wipe live edges from + * every reader until the db returns. + */ +export type DelegatedWorktreeEdgeProjectionResult = + | { known: true; edges: DelegatedWorktreeEdge[] } + | { known: false } + +/** + * The coordinator side of a cross-host delegation, for the sidebar. + * + * Only this runtime can build it: the worker host knows nothing about the + * coordinator's workspace, and the edge would fail the same-repository, + * same-host rule that git lineage enforces there. + */ +export class RuntimeDelegatedWorktreeEdgeProjection { + constructor(private readonly deps: DelegatedWorktreeEdgeDependencies) {} + + build(): DelegatedWorktreeEdgeProjectionResult { + const db = this.deps.getDb() + if (!db?.listDelegatedWorktreePlacements) { + return { known: false } + } + const edges: DelegatedWorktreeEdge[] = [] + for (const placement of db.listDelegatedWorktreePlacements(MAX_DELEGATED_EDGES)) { + // No bare-id comparison here: ids collide across hosts, and a genuine + // self-reference is only decidable once both ends are host-qualified, + // which resolveDelegatedWorktreeNesting already does. + const parentWorktreeId = this.resolveCoordinatorWorktreeId(placement) + if (!parentWorktreeId) { + continue + } + edges.push({ + parentWorktreeId, + childHostId: toRuntimeExecutionHostId(placement.environment_id), + childWorktreeId: placement.remote_worktree_id, + dispatchId: placement.dispatch_id + }) + } + return { known: true, edges } + } + + private resolveCoordinatorWorktreeId(placement: { + creator_handle: string | null + creator_pane_key: string | null + }): string | null { + const byHandle = placement.creator_handle + ? this.deps.getWorktreeId(placement.creator_handle) + : null + if (byHandle) { + return byHandle + } + const handle = placement.creator_pane_key + ? this.deps.getHandleForPaneKey(placement.creator_pane_key) + : null + return handle ? this.deps.getWorktreeId(handle) : null + } +} diff --git a/src/renderer/src/components/sidebar/WorktreeList.tsx b/src/renderer/src/components/sidebar/WorktreeList.tsx index d50f06c00265..f30062d4276e 100644 --- a/src/renderer/src/components/sidebar/WorktreeList.tsx +++ b/src/renderer/src/components/sidebar/WorktreeList.tsx @@ -63,6 +63,7 @@ const WorktreeList = React.memo(function WorktreeList({ const worktreeMap = useWorktreeMap() const repos = useAppStore((s) => s.repos) const worktreeLineageById = useAppStore((s) => s.worktreeLineageById) + const delegatedWorktreeEdges = useAppStore((s) => s.delegatedWorktreeEdges) const workspaceLineageByChildKey = useAppStore((s) => s.workspaceLineageByChildKey) const detectedWorktreesByRepo = useAppStore((s) => s.detectedWorktreesByRepo) const activeWorktreeId = useAppStore((s) => s.activeWorktreeId) @@ -163,6 +164,7 @@ const WorktreeList = React.memo(function WorktreeList({ repoMap, worktreeMap, worktreeLineageById, + delegatedWorktreeEdges, prCache, settings, workspaceStatuses, diff --git a/src/renderer/src/components/sidebar/rendered-sidebar-worktree-order.ts b/src/renderer/src/components/sidebar/rendered-sidebar-worktree-order.ts index 2a5f01530927..66becf80a7e1 100644 --- a/src/renderer/src/components/sidebar/rendered-sidebar-worktree-order.ts +++ b/src/renderer/src/components/sidebar/rendered-sidebar-worktree-order.ts @@ -82,7 +82,8 @@ export function computeRenderedSidebarWorktrees( // Why no hostLabelById: it only feeds display-only host context labels, never row order. undefined, defaultHostId, - pinnedDisplayPolicy + pinnedDisplayPolicy, + state.delegatedWorktreeEdges ) // Why lazy: with no host filter, addHostSectionRows is a pass-through, so skip building the whole host registry on a keystroke. diff --git a/src/renderer/src/components/sidebar/worktree-list/grouping/build-rows.ts b/src/renderer/src/components/sidebar/worktree-list/grouping/build-rows.ts index 7a3041ce0780..2717ebb5a665 100644 --- a/src/renderer/src/components/sidebar/worktree-list/grouping/build-rows.ts +++ b/src/renderer/src/components/sidebar/worktree-list/grouping/build-rows.ts @@ -9,7 +9,10 @@ import type { AppState } from '../../../../store/types' import { LOCAL_EXECUTION_HOST_ID } from '../../../../../../shared/execution-host' import type { ExecutionHostId } from '../../../../../../shared/execution-host' import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity' -import { getCyclicProjectedWorktreeLineageIds } from '../../worktree-lineage-projection' +import { + getCyclicProjectedWorktreeLineageIds, + getLineageRenderInfo +} from '../../worktree-lineage-projection' import { ALL_GROUP_KEY, ALL_GROUP_META } from './group-keys' import { appendOrderedGroups } from './group-sections' import type { SectionAppendContext } from './group-sections' @@ -43,6 +46,8 @@ import type { WorktreeGroupBy } from './row-types' import { getRenderedNaturalAnchorRepoIds, withRepoSectionDisplayLabels } from './section-order' +import { resolveDelegatedWorktreeNesting } from './delegated-worktree-nesting' +import type { DelegatedWorktreeEdge } from '../../../../../../shared/worktree/delegated-worktree-edge' import { buildOrderedGroups } from './worktree-grouping' export function buildRows( @@ -70,7 +75,8 @@ export function buildRows( folderWorkspaces: readonly FolderWorkspace[] = [], hostLabelById?: ReadonlyMap, defaultHostId: ExecutionHostId = LOCAL_EXECUTION_HOST_ID, - pinnedDisplayPolicy: PinnedWorktreeDisplayPolicy = getPinnedWorktreeDisplayPolicy(settings) + pinnedDisplayPolicy: PinnedWorktreeDisplayPolicy = getPinnedWorktreeDisplayPolicy(settings), + delegatedWorktreeEdges: readonly DelegatedWorktreeEdge[] = [] ): Row[] { const result: Row[] = [] const projectIndex = buildProjectGroupingIndex(projectGrouping) @@ -80,6 +86,25 @@ export function buildRows( const cyclicLineageIds = nestLineage ? getCyclicProjectedWorktreeLineageIds(lineageById, worktreeMap) : new Set() + // Sections are per repo and repo ids are per host, so a delegated child is + // rendered in its coordinator's section; anywhere else there is no parent row + // to nest under. Status and PR lanes keep lane membership, as lineage does. + const delegatedNesting = + nestLineage && delegatedWorktreeEdges.length > 0 + ? resolveDelegatedWorktreeNesting({ + worktrees, + edges: delegatedWorktreeEdges, + // Not defaultHostId: the edges arrive on this window's own graph sync, so their + // coordinator is always a local row, while the focused host follows the host filter. + homeHostId: LOCAL_EXECUTION_HOST_ID, + getLineageParentIdentity: (worktree) => { + const info = getLineageRenderInfo(worktree, lineageById, worktreeMap, cyclicLineageIds) + return info.state === 'valid' ? getWorktreeHostIdentity(info.parent) : undefined + } + }) + : undefined + const sectionAnchorByChildIdentity = + groupBy === 'repo' ? delegatedNesting?.sectionAnchorByChildIdentity : undefined const pendingByRepo = new Map() for (const creation of pendingCreations) { @@ -183,7 +208,8 @@ export function buildRows( groupDepth: 0, sectionKey: ALL_GROUP_KEY, hostContextLabelByWorktreeIdentity: mixedWorktreeHostContextLabels, - cyclicLineageIds + cyclicLineageIds, + delegatedParentIdentityByChildIdentity: delegatedNesting?.parentIdentityByChildIdentity }) for (const pair of [...renderableFolderWorkspaces].sort((left, right) => compareFolderWorkspacesForDisplay(left.folderWorkspace, right.folderWorkspace) @@ -209,7 +235,8 @@ export function buildRows( pendingByRepo, repoOrder, projectOrderBy, - folderWorkspaces: renderableFolderWorkspaces + folderWorkspaces: renderableFolderWorkspaces, + sectionAnchorByChildIdentity }) const sectionContext: SectionAppendContext = { @@ -229,7 +256,8 @@ export function buildRows( lineageById, worktreeMap, nestLineage, - cyclicLineageIds + cyclicLineageIds, + delegatedParentIdentityByChildIdentity: delegatedNesting?.parentIdentityByChildIdentity } if (groupBy !== 'repo' || projectGroups.length === 0) { diff --git a/src/renderer/src/components/sidebar/worktree-list/grouping/delegated-worktree-nesting.test.ts b/src/renderer/src/components/sidebar/worktree-list/grouping/delegated-worktree-nesting.test.ts new file mode 100644 index 000000000000..c9d37cd143da --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/grouping/delegated-worktree-nesting.test.ts @@ -0,0 +1,301 @@ +import { describe, expect, it } from 'vitest' +import { getSettingsFocusedExecutionHostId } from '../../../../../../shared/execution-host' +import type { ExecutionHostId } from '../../../../../../shared/execution-host' +import { buildRows } from './build-rows' +import { resolveDelegatedWorktreeNesting } from './delegated-worktree-nesting' +import { repo, remoteRepo, worktree } from '../../worktree-list-groups-test-fixtures' +import type { DelegatedWorktreeEdge } from '../../../../../../shared/worktree/delegated-worktree-edge' +import type { WorktreeLineage } from '../../../../../../shared/worktree/lineage-types' +import type { Repo } from '../../../../../../shared/repo-types' +import type { Worktree } from '../../../../../../shared/worktree/types' +import type { + ImportedWorktreesCardCandidate, + NewExternalWorktreesInboxCandidate, + PendingCreationRef, + Row +} from './row-types' + +const REMOTE_HOST = 'runtime:env-1' as const + +const coordinator: Worktree = { + ...worktree, + id: 'repo-1::/home/alex/orca/coordinator', + hostId: 'local', + instanceId: 'coordinator-instance', + displayName: 'coordinator' +} + +const remoteWorker: Worktree = { + ...worktree, + id: 'repo-remote::/home/ubuntu/orca/worker', + repoId: remoteRepo.id, + hostId: REMOTE_HOST, + instanceId: 'worker-instance', + displayName: 'worker' +} + +// Why: a second, undelegated worktree in the child's repo is what gives that repo a +// section of its own, which is the case where the fallback rows could be emitted twice. +const remoteSibling: Worktree = { + ...worktree, + id: 'repo-remote::/home/ubuntu/orca/sibling', + repoId: remoteRepo.id, + hostId: REMOTE_HOST, + instanceId: 'sibling-instance', + displayName: 'sibling' +} + +const otherRepo: Repo = { ...remoteRepo, id: 'repo-other', displayName: 'other' } + +// Why: a second coordinator in a different repo section, with its own delegated child of the +// same remote repo — the case where two sections each claim that repo. +const otherCoordinator: Worktree = { + ...worktree, + id: 'repo-other::/home/alex/orca/other-coordinator', + repoId: otherRepo.id, + hostId: 'local', + instanceId: 'other-coordinator-instance', + displayName: 'other-coordinator' +} + +const secondRemoteWorker: Worktree = { + ...worktree, + id: 'repo-remote::/home/ubuntu/orca/worker-2', + repoId: remoteRepo.id, + hostId: REMOTE_HOST, + instanceId: 'worker-2-instance', + displayName: 'worker-2' +} + +const edge: DelegatedWorktreeEdge = { + parentWorktreeId: coordinator.id, + childHostId: REMOTE_HOST, + childWorktreeId: remoteWorker.id, + dispatchId: 'ctx_1' +} + +function nest(args: { + worktrees: readonly Worktree[] + edges: readonly DelegatedWorktreeEdge[] + lineageParentIdentity?: (worktree: Worktree) => string | undefined +}): ReadonlyMap { + return resolveDelegatedWorktreeNesting({ + worktrees: args.worktrees, + edges: args.edges, + homeHostId: 'local', + getLineageParentIdentity: args.lineageParentIdentity ?? (() => undefined) + }).parentIdentityByChildIdentity +} + +describe('resolveDelegatedWorktreeNesting', () => { + it('nests a remote worker under the coordinator that dispatched it', () => { + expect(nest({ worktrees: [coordinator, remoteWorker], edges: [edge] })).toEqual( + new Map([[`${REMOTE_HOST}|${remoteWorker.id}`, `local|${coordinator.id}`]]) + ) + }) + + it('ignores an edge whose coordinator row is not on this machine', () => { + const elsewhere = { ...coordinator, hostId: 'runtime:env-2' as const } + expect(nest({ worktrees: [elsewhere, remoteWorker], edges: [edge] }).size).toBe(0) + }) + + it('leaves git lineage in charge when the child already has a parent', () => { + expect( + nest({ + worktrees: [coordinator, remoteWorker], + edges: [edge], + lineageParentIdentity: (candidate) => + candidate.id === remoteWorker.id ? `${REMOTE_HOST}|repo-remote::/other` : undefined + }).size + ).toBe(0) + }) + + it('refuses an edge that would close a cycle', () => { + const backEdge: DelegatedWorktreeEdge = { + parentWorktreeId: coordinator.id, + childHostId: REMOTE_HOST, + childWorktreeId: remoteWorker.id, + dispatchId: 'ctx_2' + } + const resolved = resolveDelegatedWorktreeNesting({ + worktrees: [coordinator, remoteWorker], + edges: [backEdge], + homeHostId: REMOTE_HOST, + // The coordinator is itself a delegated child of the worker in this shape. + getLineageParentIdentity: (candidate) => + candidate.id === coordinator.id ? `${REMOTE_HOST}|${remoteWorker.id}` : undefined + }) + expect(resolved.parentIdentityByChildIdentity.size).toBe(0) + }) + + it('keeps the first edge when a worktree was reused by a later dispatch', () => { + const reused: DelegatedWorktreeEdge = { + ...edge, + parentWorktreeId: 'repo-1::/other', + dispatchId: 'ctx_3' + } + expect(nest({ worktrees: [coordinator, remoteWorker], edges: [edge, reused] })).toEqual( + new Map([[`${REMOTE_HOST}|${remoteWorker.id}`, `local|${coordinator.id}`]]) + ) + }) +}) + +function findItem( + rows: readonly Row[], + worktreeId: string +): Extract | undefined { + return rows.find( + (row): row is Extract => + row.type === 'item' && row.worktree.id === worktreeId + ) +} + +describe('buildRows with delegated edges', () => { + const repoMapWithRemote = new Map([ + [repo.id, repo], + [remoteRepo.id, remoteRepo], + [otherRepo.id, otherRepo] + ]) + const lineage: Record = {} + + function rowsFor( + edges: readonly DelegatedWorktreeEdge[], + overrides: { + defaultHostId?: ExecutionHostId + importedWorktreesByRepo?: ReadonlyMap + newExternalWorktreesInboxByRepo?: ReadonlyMap + pendingCreations?: readonly PendingCreationRef[] + extraWorktrees?: readonly Worktree[] + } = {} + ) { + const worktrees = [coordinator, remoteWorker, ...(overrides.extraWorktrees ?? [])] + return buildRows( + 'repo', + worktrees, + repoMapWithRemote, + null, + new Set(), + undefined, + undefined, + 'manual', + lineage, + new Map(worktrees.map((w) => [w.id, w])), + true, + undefined, + [], + new Set(), + overrides.importedWorktreesByRepo ?? new Map(), + overrides.newExternalWorktreesInboxByRepo ?? new Map(), + overrides.pendingCreations ?? [], + undefined, + [], + undefined, + overrides.defaultHostId ?? 'local', + 'single-location', + edges + ) + } + + it('renders the remote worker nested inside the coordinator repo section', () => { + const rows = rowsFor([edge]) + const worker = findItem(rows, remoteWorker.id) + const parent = findItem(rows, coordinator.id) + expect(worker).toMatchObject({ depth: 1, sectionKey: parent?.sectionKey }) + expect(parent).toMatchObject({ depth: 0, lineageChildCount: 1 }) + expect( + rows.filter((row) => row.type === 'item' && row.worktree.id === remoteWorker.id) + ).toHaveLength(1) + }) + + it('still nests while a remote runtime environment is the focused host', () => { + // Focus is a filter over every host's rows; the edges still come from this + // window's own runtime, so the coordinator is still looked up as a local row. + const rows = rowsFor([edge], { + defaultHostId: getSettingsFocusedExecutionHostId({ activeRuntimeEnvironmentId: 'env-1' }) + }) + expect(findItem(rows, remoteWorker.id)).toMatchObject({ depth: 1 }) + }) + + it('leaves the remote worker top-level in its own section without an edge', () => { + const rows = rowsFor([]) + const worker = findItem(rows, remoteWorker.id) + const parent = findItem(rows, coordinator.id) + expect(worker).toMatchObject({ depth: 0 }) + expect(worker?.sectionKey).not.toBe(parent?.sectionKey) + }) + + it("renders the anchored child repo's fallback rows once, in the section that shows it", () => { + const rows = rowsFor([edge], { + importedWorktreesByRepo: new Map([ + [remoteRepo.id, { repo: remoteRepo, hiddenWorktrees: [] }] + ]), + newExternalWorktreesInboxByRepo: new Map([ + [remoteRepo.id, { repo: remoteRepo, inboxWorktrees: [] }] + ]), + pendingCreations: [{ creationId: 'create-1', repoId: remoteRepo.id }] + }) + const coordinatorSection = findItem(rows, coordinator.id)?.sectionKey + const headers = rows.filter((row) => row.type === 'header') + // One section, not two: the child's repo has no section of its own to fall back to. + expect(headers.map((header) => header.key)).toEqual([coordinatorSection]) + expect(rows.filter((row) => row.type === 'imported-worktrees-card')).toHaveLength(1) + expect(rows.filter((row) => row.type === 'new-external-worktrees-inbox')).toHaveLength(1) + expect(rows.filter((row) => row.type === 'pending-creation')).toHaveLength(1) + }) + + it("emits the child repo's fallback rows once when that repo has its own section", () => { + const rows = rowsFor([edge], { + extraWorktrees: [remoteSibling], + importedWorktreesByRepo: new Map([ + [remoteRepo.id, { repo: remoteRepo, hiddenWorktrees: [] }] + ]), + newExternalWorktreesInboxByRepo: new Map([ + [remoteRepo.id, { repo: remoteRepo, inboxWorktrees: [] }] + ]), + pendingCreations: [{ creationId: 'create-1', repoId: remoteRepo.id }] + }) + const coordinatorSection = findItem(rows, coordinator.id)?.sectionKey + const siblingSection = findItem(rows, remoteSibling.id)?.sectionKey + // The child's repo has a section of its own here, so the coordinator section must not + // also claim it — the repo-keyed row ids are identical and would collide. + expect(siblingSection).not.toBe(coordinatorSection) + expect(rows.filter((row) => row.type === 'imported-worktrees-card')).toHaveLength(1) + expect(rows.filter((row) => row.type === 'new-external-worktrees-inbox')).toHaveLength(1) + expect(rows.filter((row) => row.type === 'pending-creation')).toHaveLength(1) + // The repo-keyed notice rows carry the same id in whichever section emits them, so a + // second emission is a duplicate React key, not just a redundant card. + const noticeKeys = rows + .filter( + (row) => + row.type === 'imported-worktrees-card' || + row.type === 'new-external-worktrees-inbox' || + row.type === 'pending-creation' + ) + .map((row) => row.key) + expect(new Set(noticeKeys).size).toBe(noticeKeys.length) + }) + + it('leaves one claim when two coordinators in different sections anchor the same repo', () => { + const secondEdge: DelegatedWorktreeEdge = { + parentWorktreeId: otherCoordinator.id, + childHostId: REMOTE_HOST, + childWorktreeId: secondRemoteWorker.id, + dispatchId: 'ctx_2' + } + const rows = rowsFor([edge, secondEdge], { + extraWorktrees: [otherCoordinator, secondRemoteWorker], + importedWorktreesByRepo: new Map([ + [remoteRepo.id, { repo: remoteRepo, hiddenWorktrees: [] }] + ]), + newExternalWorktreesInboxByRepo: new Map([ + [remoteRepo.id, { repo: remoteRepo, inboxWorktrees: [] }] + ]), + pendingCreations: [{ creationId: 'create-1', repoId: remoteRepo.id }] + }) + // Both coordinators bucket a child of remoteRepo, so both claimed it. Only one may keep + // the claim, or the repo-keyed notice rows are emitted from each section. + expect(rows.filter((row) => row.type === 'imported-worktrees-card')).toHaveLength(1) + expect(rows.filter((row) => row.type === 'new-external-worktrees-inbox')).toHaveLength(1) + expect(rows.filter((row) => row.type === 'pending-creation')).toHaveLength(1) + }) +}) diff --git a/src/renderer/src/components/sidebar/worktree-list/grouping/delegated-worktree-nesting.ts b/src/renderer/src/components/sidebar/worktree-list/grouping/delegated-worktree-nesting.ts new file mode 100644 index 000000000000..d1c7b43338c0 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/grouping/delegated-worktree-nesting.ts @@ -0,0 +1,100 @@ +import type { ExecutionHostId } from '../../../../../../shared/execution-host' +import type { DelegatedWorktreeEdge } from '../../../../../../shared/worktree/delegated-worktree-edge' +import type { Worktree } from '../../../../../../shared/worktree/types' +import { + composeWorktreeHostIdentity, + getWorktreeHostIdentity +} from '../../../../../../shared/worktree/host-qualified-identity' + +export type DelegatedWorktreeNesting = { + /** Child identity → parent identity, host-qualified on both ends (STA-4343). */ + parentIdentityByChildIdentity: ReadonlyMap + /** Child identity → the worktree whose section the child is rendered in. */ + sectionAnchorByChildIdentity: ReadonlyMap +} + +const EMPTY_NESTING: DelegatedWorktreeNesting = { + parentIdentityByChildIdentity: new Map(), + sectionAnchorByChildIdentity: new Map() +} + +/** + * Which delegated edges the sidebar may actually draw. + * + * Git lineage wins wherever it exists: an edge is only a fallback for a card + * whose real parent cannot be recorded because it sits on another host. + */ +export function resolveDelegatedWorktreeNesting(args: { + worktrees: readonly Worktree[] + edges: readonly DelegatedWorktreeEdge[] + /** Host the runtime that published the edges stamps its own worktrees with. Not the + * focused host: focus is a filter over every host's rows, not a claim about the publisher. */ + homeHostId: ExecutionHostId + /** Parent identity already proven by git lineage, when the row has one. */ + getLineageParentIdentity: (worktree: Worktree) => string | undefined +}): DelegatedWorktreeNesting { + const { worktrees, edges, homeHostId, getLineageParentIdentity } = args + if (edges.length === 0) { + return EMPTY_NESTING + } + const byIdentity = new Map( + worktrees.map((worktree) => [getWorktreeHostIdentity(worktree), worktree]) + ) + const parentIdentityByChildIdentity = new Map() + const sectionAnchorByChildIdentity = new Map() + for (const edge of edges) { + const childIdentity = composeWorktreeHostIdentity(edge.childHostId, edge.childWorktreeId) + if (parentIdentityByChildIdentity.has(childIdentity)) { + continue + } + const child = byIdentity.get(childIdentity) + if (!child || getLineageParentIdentity(child)) { + continue + } + // The coordinator's worktree belongs to the runtime that published the edge. + // An unqualified row cannot be proven to be that one, so it is not a parent. + const parentIdentity = composeWorktreeHostIdentity(homeHostId, edge.parentWorktreeId) + const parent = byIdentity.get(parentIdentity) + if (!parent || parentIdentity === childIdentity) { + continue + } + if ( + reachesDescendant({ + fromIdentity: parentIdentity, + targetIdentity: childIdentity, + byIdentity, + parentIdentityByChildIdentity, + getLineageParentIdentity + }) + ) { + continue + } + parentIdentityByChildIdentity.set(childIdentity, parentIdentity) + sectionAnchorByChildIdentity.set(childIdentity, parent) + } + return { parentIdentityByChildIdentity, sectionAnchorByChildIdentity } +} + +/** Walks git lineage and delegated edges together: a cycle through both still hangs the emitter. */ +function reachesDescendant(args: { + fromIdentity: string + targetIdentity: string + byIdentity: ReadonlyMap + parentIdentityByChildIdentity: ReadonlyMap + getLineageParentIdentity: (worktree: Worktree) => string | undefined +}): boolean { + const { fromIdentity, targetIdentity, byIdentity, parentIdentityByChildIdentity } = args + const visited = new Set() + let cursor: string | undefined = fromIdentity + while (cursor && !visited.has(cursor)) { + if (cursor === targetIdentity) { + return true + } + visited.add(cursor) + const worktree = byIdentity.get(cursor) + cursor = + parentIdentityByChildIdentity.get(cursor) ?? + (worktree ? args.getLineageParentIdentity(worktree) : undefined) + } + return false +} diff --git a/src/renderer/src/components/sidebar/worktree-list/grouping/group-sections.ts b/src/renderer/src/components/sidebar/worktree-list/grouping/group-sections.ts index bbba41b609b7..90638c8ea549 100644 --- a/src/renderer/src/components/sidebar/worktree-list/grouping/group-sections.ts +++ b/src/renderer/src/components/sidebar/worktree-list/grouping/group-sections.ts @@ -50,6 +50,7 @@ export type SectionAppendContext = { worktreeMap: Map nestLineage: boolean cyclicLineageIds: ReadonlySet + delegatedParentIdentityByChildIdentity?: ReadonlyMap } export function appendOrderedGroups( @@ -208,7 +209,8 @@ export function appendOrderedGroups( sectionKey: key, hostContextLabelByRepoId, hostContextLabelByWorktreeIdentity, - cyclicLineageIds + cyclicLineageIds, + delegatedParentIdentityByChildIdentity: ctx.delegatedParentIdentityByChildIdentity }) for (const pair of folderPairs) { result.push(buildFolderWorkspaceRow(pair, projectGroupDepth)) diff --git a/src/renderer/src/components/sidebar/worktree-list/grouping/row-builders.ts b/src/renderer/src/components/sidebar/worktree-list/grouping/row-builders.ts index e62d0f9ec705..67cea60fd5b3 100644 --- a/src/renderer/src/components/sidebar/worktree-list/grouping/row-builders.ts +++ b/src/renderer/src/components/sidebar/worktree-list/grouping/row-builders.ts @@ -111,6 +111,7 @@ export function appendWorktreeRows( hostContextLabelByRepoId?: ReadonlyMap hostContextLabelByWorktreeIdentity?: ReadonlyMap cyclicLineageIds: ReadonlySet + delegatedParentIdentityByChildIdentity?: ReadonlyMap } ): void { const { @@ -120,7 +121,8 @@ export function appendWorktreeRows( sectionKey, hostContextLabelByRepoId, hostContextLabelByWorktreeIdentity, - cyclicLineageIds + cyclicLineageIds, + delegatedParentIdentityByChildIdentity } = options if (!nestLineage) { for (const worktree of worktrees) { @@ -148,7 +150,22 @@ export function appendWorktreeRows( ) const childrenByParentIdentity = new Map() const childIdentities = new Set() + const attachChild = (worktree: Worktree, parentIdentity: string): void => { + childIdentities.add(getWorktreeHostIdentity(worktree)) + const children = childrenByParentIdentity.get(parentIdentity) ?? [] + children.push(worktree) + childrenByParentIdentity.set(parentIdentity, children) + } for (const worktree of worktrees) { + // A worker on another server has no recordable git lineage, so its edge + // comes from the coordinator's dispatch records instead. + const delegatedParentIdentity = delegatedParentIdentityByChildIdentity?.get( + getWorktreeHostIdentity(worktree) + ) + if (delegatedParentIdentity && visibleByIdentity.has(delegatedParentIdentity)) { + attachChild(worktree, delegatedParentIdentity) + continue + } const projectedLineage = getProjectedWorktreeLineage(worktree, lineageById) const inlineLineage = (worktree as Worktree & { lineage?: WorktreeLineage | null }).lineage const lineage = @@ -166,11 +183,7 @@ export function appendWorktreeRows( if (!parent || !isValidResolvedWorktreeLineageEdge(worktree, parent, lineage)) { continue } - const childIdentity = getWorktreeHostIdentity(worktree) - childIdentities.add(childIdentity) - const children = childrenByParentIdentity.get(parentIdentity) ?? [] - children.push(worktree) - childrenByParentIdentity.set(parentIdentity, children) + attachChild(worktree, parentIdentity) } const emitted = new Set() diff --git a/src/renderer/src/components/sidebar/worktree-list/grouping/worktree-grouping.ts b/src/renderer/src/components/sidebar/worktree-list/grouping/worktree-grouping.ts index b6449acd2a14..ac4b9e60a9ac 100644 --- a/src/renderer/src/components/sidebar/worktree-list/grouping/worktree-grouping.ts +++ b/src/renderer/src/components/sidebar/worktree-list/grouping/worktree-grouping.ts @@ -14,6 +14,7 @@ import { } from './folder-workspace-lanes' import { PR_GROUP_META, PR_GROUP_ORDER, getPRGroupKey, getPRLaneKey } from './group-keys' import type { PRGroupKey } from './group-keys' +import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity' import { addRepoIdToGroup, getProjectGroupingForRepo } from './project-grouping' import type { OrderedGroupEntry, @@ -60,6 +61,8 @@ export function buildOrderedGroups(args: { repoOrder: Map | undefined projectOrderBy: ProjectOrderBy folderWorkspaces?: readonly RenderableFolderWorkspace[] + /** Delegated children bucket with their coordinator, not their own repo (see delegated-worktree-nesting). */ + sectionAnchorByChildIdentity?: ReadonlyMap }): OrderedGroupEntry[] { const { groupBy, @@ -75,16 +78,25 @@ export function buildOrderedGroups(args: { pendingByRepo, repoOrder, projectOrderBy, - folderWorkspaces = [] + folderWorkspaces = [], + sectionAnchorByChildIdentity } = args const grouped = new Map() + // Where a delegated child's own repo ended up. It renders in its coordinator's + // section, so the repo gets no section of its own and its notice rows must + // follow it there rather than open an empty second section for the same repo. + const anchoredSectionKeyByRepoId = new Map() + // Every section that took a claim on a repo this way. Two children of one repo can anchor + // to coordinators in different sections, and all but one must give the claim back. + const claimedSectionKeysByRepoId = new Map>() for (const w of naturalWorktrees) { let key: string let label: string let repo: Repo | undefined + const anchor = sectionAnchorByChildIdentity?.get(getWorktreeHostIdentity(w)) ?? w if (groupBy === 'repo') { - const grouping = getProjectGroupingForRepo(w.repoId, repoMap, projectIndex) + const grouping = getProjectGroupingForRepo(anchor.repoId, repoMap, projectIndex) key = grouping.key label = grouping.label repo = grouping.repo @@ -103,7 +115,34 @@ export function buildOrderedGroups(args: { } const group = grouped.get(key)! group.items.push(w) - addRepoIdToGroup(group, w.repoId) + addRepoIdToGroup(group, anchor.repoId) + if (anchor !== w) { + addRepoIdToGroup(group, w.repoId) + anchoredSectionKeyByRepoId.set(w.repoId, key) + const claims = claimedSectionKeysByRepoId.get(w.repoId) ?? new Set() + claims.add(key) + claimedSectionKeysByRepoId.set(w.repoId, claims) + } + } + for (const [repoId, claimedKeys] of claimedSectionKeysByRepoId) { + const ownKey = getProjectGroupingForRepo(repoId, repoMap, projectIndex).key + // Exactly one section may carry a repo's notice rows. Their ids are repo-keyed, so a + // second emission duplicates the card and collides the key. The repo's own section wins + // when it has one; otherwise the last coordinator to anchor a child of it does. + const keeper = + claimedKeys.has(ownKey) || grouped.has(ownKey) + ? ownKey + : (anchoredSectionKeyByRepoId.get(repoId) ?? ownKey) + for (const key of claimedKeys) { + if (key !== keeper) { + grouped.get(key)?.repoIds.delete(repoId) + } + } + if (keeper === ownKey) { + anchoredSectionKeyByRepoId.delete(repoId) + } else { + anchoredSectionKeyByRepoId.set(repoId, keeper) + } } // Why: folder workspaces are not worktrees, so they never appear in the loop // above. Bucketing them here — and creating the lane when no worktree opened @@ -153,7 +192,7 @@ export function buildOrderedGroups(args: { if (groupBy === 'repo') { for (const [repoId, candidate] of importedWorktreesByRepo) { const grouping = getProjectGroupingForRepo(repoId, repoMap, projectIndex) - const key = grouping.key + const key = anchoredSectionKeyByRepoId.get(repoId) ?? grouping.key if (!grouped.has(key)) { grouped.set(key, { label: grouping.label, @@ -169,7 +208,7 @@ export function buildOrderedGroups(args: { if (groupBy === 'repo') { for (const [repoId, candidate] of newExternalWorktreesInboxByRepo) { const grouping = getProjectGroupingForRepo(repoId, repoMap, projectIndex) - const key = grouping.key + const key = anchoredSectionKeyByRepoId.get(repoId) ?? grouping.key if (!grouped.has(key)) { // Why: the default policy removes pinned worktrees from natural groups, // but actionable inbox rows still need a project section to render in. @@ -187,7 +226,7 @@ export function buildOrderedGroups(args: { if (groupBy === 'repo') { for (const repoId of pendingByRepo.keys()) { const grouping = getProjectGroupingForRepo(repoId, repoMap, projectIndex) - const key = grouping.key + const key = anchoredSectionKeyByRepoId.get(repoId) ?? grouping.key if (!grouped.has(key)) { // Why: creating the first worktree in a repo leaves it with no group yet; // ensure one so the in-progress row nests under its repo instead of being diff --git a/src/renderer/src/components/sidebar/worktree-list/listing/use-section-rows.ts b/src/renderer/src/components/sidebar/worktree-list/listing/use-section-rows.ts index ddd91a236532..a49ee114656a 100644 --- a/src/renderer/src/components/sidebar/worktree-list/listing/use-section-rows.ts +++ b/src/renderer/src/components/sidebar/worktree-list/listing/use-section-rows.ts @@ -8,6 +8,7 @@ import type { ProjectOrderBy } from '../../../../../../shared/ui-chrome-types' import type { Repo } from '../../../../../../shared/repo-types' import type { WorkspaceStatusDefinition, Worktree } from '../../../../../../shared/worktree/types' import type { WorktreeLineage } from '../../../../../../shared/worktree/lineage-types' +import type { DelegatedWorktreeEdge } from '../../../../../../shared/worktree/delegated-worktree-edge' import type { ExecutionHostId } from '../../../../../../shared/execution-host' import { folderWorkspaceKey } from '../../../../../../shared/workspace-scope' import { getHostDisplayLabelOverrides } from '../../../../../../shared/host-setting-overrides' @@ -31,6 +32,7 @@ type SectionRowsArgs = { repoMap: Map worktreeMap: Map worktreeLineageById: Record + delegatedWorktreeEdges: readonly DelegatedWorktreeEdge[] prCache: AppState['prCache'] | null settings: AppState['settings'] workspaceStatuses: readonly WorkspaceStatusDefinition[] @@ -165,7 +167,8 @@ export function useSidebarSectionRows(args: SectionRowsArgs) { args.visibleFolderWorkspacesForRows, hostLabelById, defaultHostId, - args.pinnedDisplayPolicy + args.pinnedDisplayPolicy, + args.delegatedWorktreeEdges ), [ args.groupBy, @@ -178,6 +181,7 @@ export function useSidebarSectionRows(args: SectionRowsArgs) { args.workspaceStatuses, args.projectOrderBy, args.worktreeLineageById, + args.delegatedWorktreeEdges, args.worktreeMap, args.settings, args.projectGrouping, diff --git a/src/renderer/src/runtime/sync-runtime-graph-delegated-worktree-edges.test.ts b/src/renderer/src/runtime/sync-runtime-graph-delegated-worktree-edges.test.ts new file mode 100644 index 000000000000..64729d5a3487 --- /dev/null +++ b/src/renderer/src/runtime/sync-runtime-graph-delegated-worktree-edges.test.ts @@ -0,0 +1,108 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type { DelegatedWorktreeEdge } from '../../../shared/worktree/delegated-worktree-edge' +import type { RuntimeSyncWindowGraphResult } from '../../../shared/runtime-session-contracts' +import type { AppState } from '../store/types' + +vi.mock('@/components/terminal-pane/pty-dispatcher', async (importOriginal) => { + const actual = await importOriginal>() + return { ...actual, getEagerPtyBufferHandle: vi.fn(() => undefined) } +}) + +import { + scheduleRuntimeGraphSync, + setRuntimeGraphStoreStateGetter, + setRuntimeGraphSyncEnabled +} from './sync-runtime-graph' + +const EDGE: DelegatedWorktreeEdge = { + parentWorktreeId: 'repo-1::/home/alex/coordinator', + childHostId: 'runtime:env-1', + childWorktreeId: 'repo-remote::/home/ubuntu/worker', + dispatchId: 'ctx_1' +} + +afterEach(() => { + setRuntimeGraphSyncEnabled(false) + setRuntimeGraphStoreStateGetter(null) + vi.useRealTimers() + vi.unstubAllGlobals() +}) + +/** + * Drives real graph syncs against a store that only records what the delegated-edge + * setter was given, and returns the store's value after each scripted host reply. + */ +async function publishedEdgesAfter( + replies: readonly Partial[] +): Promise { + vi.useFakeTimers() + let published: readonly DelegatedWorktreeEdge[] = [] + const syncWindowGraph = vi.fn() + for (const reply of replies) { + syncWindowGraph.mockResolvedValueOnce(reply) + } + vi.stubGlobal('window', { api: { runtime: { syncWindowGraph } } }) + vi.stubGlobal('HTMLElement', class HTMLElement {}) + const storeState = { + tabsByWorktree: {}, + terminalLayoutsByTabId: {}, + runtimePaneTitlesByTabId: {}, + groupsByWorktree: {}, + activeGroupIdByWorktree: {}, + layoutByWorktree: {}, + unifiedTabsByWorktree: {}, + tabBarOrderByWorktree: {}, + activeFileId: null, + activeFileIdByWorktree: {}, + openFiles: [], + editorDrafts: {}, + activeTabId: null, + setDelegatedWorktreeEdges: (edges: readonly DelegatedWorktreeEdge[]) => { + published = edges + } + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the graph publication path reads only the members declared above; the rest of AppState is never touched on this path. + setRuntimeGraphStoreStateGetter(() => storeState as unknown as AppState) + setRuntimeGraphSyncEnabled(true) + for (let index = 0; index < replies.length; index += 1) { + if (index > 0) { + scheduleRuntimeGraphSync() + } + await vi.advanceTimersByTimeAsync(20) + await Promise.resolve() + await Promise.resolve() + } + expect(syncWindowGraph).toHaveBeenCalledTimes(replies.length) + return published +} + +describe('syncRuntimeGraph delegated worktree edges', () => { + it('commits the edges the host published', async () => { + expect(await publishedEdgesAfter([{ delegatedWorktreeEdges: [EDGE] }])).toEqual([EDGE]) + }) + + it('keeps the live edges through a window where the host db cannot answer', async () => { + // The placements still exist; only the db is momentarily unreachable. Committing + // [] here would un-nest every delegated card until the next successful sync. + expect( + await publishedEdgesAfter([ + { delegatedWorktreeEdges: [EDGE] }, + { delegatedWorktreeEdgesUnavailable: true } + ]) + ).toEqual([EDGE]) + }) + + it('clears the edges when the host answers that it coordinated none', async () => { + expect( + await publishedEdgesAfter([ + { delegatedWorktreeEdges: [EDGE] }, + { delegatedWorktreeEdges: [] } + ]) + ).toEqual([]) + }) + + it('clears the edges against a host that predates the field', async () => { + // Rule 1 skew: an older host omits both members, which still reads as zero. + expect(await publishedEdgesAfter([{ delegatedWorktreeEdges: [EDGE] }, {}])).toEqual([]) + }) +}) diff --git a/src/renderer/src/runtime/sync-runtime-graph/graph-publication.ts b/src/renderer/src/runtime/sync-runtime-graph/graph-publication.ts index f74c97f6e410..edf2e628a848 100644 --- a/src/renderer/src/runtime/sync-runtime-graph/graph-publication.ts +++ b/src/renderer/src/runtime/sync-runtime-graph/graph-publication.ts @@ -190,6 +190,11 @@ export async function syncRuntimeGraph(): Promise { commitMobileSessionPublication(mobileSessionTabs, result?.mobileSessionResyncWorktrees) const currentState = graphState.getStoreState() currentState?.setRuntimeAgentOrchestrationByPaneKey?.(result?.agentOrchestrationByPaneKey ?? {}) + // Absent edges with the unavailable flag means the host could not ask its db, not zero + // placements; committing [] there un-nests every delegated card until the db returns. + if (!result?.delegatedWorktreeEdgesUnavailable) { + currentState?.setDelegatedWorktreeEdges?.(result?.delegatedWorktreeEdges ?? []) + } for (const resolution of result?.nativeChatLaunchDraftResolutions ?? []) { if (currentState) { applyNativeChatLaunchDraftResolved(currentState, { diff --git a/src/renderer/src/store/slices/worktree-helpers.ts b/src/renderer/src/store/slices/worktree-helpers.ts index f17c0513fef5..45d210e6dec3 100644 --- a/src/renderer/src/store/slices/worktree-helpers.ts +++ b/src/renderer/src/store/slices/worktree-helpers.ts @@ -14,6 +14,7 @@ import type { } from '../../../../shared/worktree/create-types' import type { WorktreeStartupLaunch } from '../../../../shared/worktree/launch-types' import type { WorkspaceLineage, WorktreeLineage } from '../../../../shared/worktree/lineage-types' +import type { DelegatedWorktreeEdge } from '../../../../shared/worktree/delegated-worktree-edge' import type { WorktreeMeta } from '../../../../shared/worktree/meta-types' import type { DetectedWorktree, @@ -98,6 +99,9 @@ export type WorktreeSlice = { detectedWorktreesByRepo: Record worktreeLineageById: Readonly> workspaceLineageByChildKey: Readonly> + /** Cross-host worker placements published by this runtime's own graph sync. */ + delegatedWorktreeEdges: readonly DelegatedWorktreeEdge[] + setDelegatedWorktreeEdges: (edges: readonly DelegatedWorktreeEdge[]) => void activeWorktreeId: string | null activeWorkspaceKey: WorkspaceKey | null activeWorkspaceExecutionHostId: ExecutionHostId | null diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts index 330d27e7bb2d..dc85c751d218 100644 --- a/src/renderer/src/store/slices/worktrees.ts +++ b/src/renderer/src/store/slices/worktrees.ts @@ -1,6 +1,7 @@ import type { StateCreator } from 'zustand' import type { AppState } from '../types' import type { WorktreeSlice } from './worktree-helpers' +import type { DelegatedWorktreeEdge } from '../../../../shared/worktree/delegated-worktree-edge' import { worktreeSliceInitialState } from './worktrees/session/worktree-slice-initial-state' import { createFetchDetectedWorktrees } from './worktrees/listing/fetch-detected-worktrees' import { createFetchWorktrees } from './worktrees/listing/fetch-worktrees' @@ -74,12 +75,37 @@ export { resetAuthoritativelyRemovedWorktreeMemoryForTests } from './worktrees/l export type { DirectSshDetectedWorktreeRefresh } from './worktrees/listing/known-ssh-worktree-fetch' export { acquireDirectSshDetectedWorktreeRefresh } from './worktrees/listing/known-ssh-worktree-fetch' +function delegatedWorktreeEdgesEqual( + left: readonly DelegatedWorktreeEdge[], + right: readonly DelegatedWorktreeEdge[] +): boolean { + return ( + left.length === right.length && + left.every((edge, index) => { + const other = right[index] + return ( + edge.dispatchId === other.dispatchId && + edge.parentWorktreeId === other.parentWorktreeId && + edge.childHostId === other.childHostId && + edge.childWorktreeId === other.childWorktreeId + ) + }) + ) +} + export const createWorktreeSlice: StateCreator = (set, get) => ({ ...worktreeSliceInitialState, fetchDetectedWorktrees: createFetchDetectedWorktrees(set, get), fetchWorktrees: createFetchWorktrees(set, get), fetchAllWorktrees: createFetchAllWorktrees(set, get), fetchWorktreeLineage: createFetchWorktreeLineage(set, get), + // Republished whole on every graph sync, so identity is reused when nothing moved. + setDelegatedWorktreeEdges: (edges) => + set((state) => + delegatedWorktreeEdgesEqual(state.delegatedWorktreeEdges, edges) + ? state + : { delegatedWorktreeEdges: edges } + ), updateWorktreeLineage: createUpdateWorktreeLineage(set, get), assignWorktreeParent: createAssignWorktreeParent(set, get), updateWorktreeGitIdentity: createUpdateWorktreeGitIdentity(set, get), diff --git a/src/renderer/src/store/slices/worktrees/session/worktree-slice-initial-state.ts b/src/renderer/src/store/slices/worktrees/session/worktree-slice-initial-state.ts index 73dfa75478f1..a8ede49b478d 100644 --- a/src/renderer/src/store/slices/worktrees/session/worktree-slice-initial-state.ts +++ b/src/renderer/src/store/slices/worktrees/session/worktree-slice-initial-state.ts @@ -6,6 +6,7 @@ export const worktreeSliceInitialState: Pick< | 'detectedWorktreesByRepo' | 'worktreeLineageById' | 'workspaceLineageByChildKey' + | 'delegatedWorktreeEdges' | 'activeWorktreeId' | 'activeWorkspaceKey' | 'activeWorkspaceExecutionHostId' @@ -25,6 +26,7 @@ export const worktreeSliceInitialState: Pick< detectedWorktreesByRepo: {}, worktreeLineageById: {}, workspaceLineageByChildKey: {}, + delegatedWorktreeEdges: [], activeWorktreeId: null, activeWorkspaceKey: null, activeWorkspaceExecutionHostId: null, diff --git a/src/shared/runtime-session-contracts.ts b/src/shared/runtime-session-contracts.ts index 99b4fbe4d6f2..8ec4641a5d1b 100644 --- a/src/shared/runtime-session-contracts.ts +++ b/src/shared/runtime-session-contracts.ts @@ -1,4 +1,5 @@ import type { AgentStatusOrchestrationContext } from './agent-status-types' +import type { DelegatedWorktreeEdge } from './worktree/delegated-worktree-edge' import type { RemoteServerUpdateSupport } from './remote-server-update' import type { RemoteRuntimeSharedConnectionDiagnostics } from './remote-runtime-shared-control-types' import type { RuntimeHostConnectionState } from './runtime-host-connection-state' @@ -166,6 +167,10 @@ export type RuntimeNativeChatLaunchDraftResolution = { export type RuntimeSyncWindowGraphResult = RuntimeStatus & { agentOrchestrationByPaneKey?: Record + /** Cross-host worker placements this runtime coordinated; `[]` means none. */ + delegatedWorktreeEdges?: DelegatedWorktreeEdge[] + /** The orchestration db could not be asked; readers keep their last edges instead of clearing. */ + delegatedWorktreeEdgesUnavailable?: boolean nativeChatLaunchDraftResolutions?: RuntimeNativeChatLaunchDraftResolution[] mobileSessionResyncWorktrees?: string[] } diff --git a/src/shared/worktree/delegated-worktree-edge.ts b/src/shared/worktree/delegated-worktree-edge.ts new file mode 100644 index 000000000000..7b9c472abf1e --- /dev/null +++ b/src/shared/worktree/delegated-worktree-edge.ts @@ -0,0 +1,19 @@ +import type { ExecutionHostId } from '../execution-host' + +/** + * One supervised worker a coordinator on this runtime placed on another Orca + * server. + * + * Git lineage cannot record it: a child worktree's parent must be in the same + * repository on the same execution host, and each host mints its own repo ids. + * The home runtime's dispatch records are the only place that knows both ends, + * so the sidebar nests these cards from here instead. Presentation only — + * removal, base branches and every other lineage rule stay host-local. + */ +export type DelegatedWorktreeEdge = { + /** Coordinator's worktree, on the runtime that published the edge, so unqualified. */ + parentWorktreeId: string + childHostId: ExecutionHostId + childWorktreeId: string + dispatchId: string +}