From 2fc332e66a7c06755e6ba42350605c935e50ec1a Mon Sep 17 00:00:00 2001 From: Alexander Miller Date: Wed, 23 Sep 2026 10:43:33 -0400 Subject: [PATCH 1/5] fix(sidebar): nest a delegated remote worker under its coordinator A worker started with `--on ` becomes a top-level card, because git lineage only nests a worktree under a parent in the same repository on the same host and each host mints its own repo ids. The coordinator's own runtime already records which terminal dispatched the worker and which remote worktree it landed in, so publish that pairing to the sidebar and nest the card from it. Presentation only: the edge never becomes lineage, so removal, "delete all" and base-branch rules stay host-local. Co-Authored-By: Claude Opus 5 --- .../orca-runtime-stop-requested-pty-ids.ts | 7 + .../runtime/orca-runtime-sync-window-graph.ts | 2 + .../db/federation/federated-dispatch-store.ts | 36 ++++ ...delegated-worktree-edge-projection.test.ts | 81 +++++++++ ...time-delegated-worktree-edge-projection.ts | 67 +++++++ .../src/components/sidebar/WorktreeList.tsx | 2 + .../rendered-sidebar-worktree-order.ts | 3 +- .../worktree-list/grouping/build-rows.ts | 36 +++- .../delegated-worktree-nesting.test.ts | 168 ++++++++++++++++++ .../grouping/delegated-worktree-nesting.ts | 99 +++++++++++ .../worktree-list/grouping/group-sections.ts | 4 +- .../worktree-list/grouping/row-builders.ts | 25 ++- .../grouping/worktree-grouping.ts | 11 +- .../worktree-list/listing/use-section-rows.ts | 6 +- .../sync-runtime-graph/graph-publication.ts | 1 + .../src/store/slices/worktree-helpers.ts | 4 + src/renderer/src/store/slices/worktrees.ts | 26 +++ .../session/worktree-slice-initial-state.ts | 2 + src/shared/runtime-session-contracts.ts | 3 + .../worktree/delegated-worktree-edge.ts | 19 ++ 20 files changed, 585 insertions(+), 17 deletions(-) create mode 100644 src/main/runtime/runtime-delegated-worktree-edge-projection.test.ts create mode 100644 src/main/runtime/runtime-delegated-worktree-edge-projection.ts create mode 100644 src/renderer/src/components/sidebar/worktree-list/grouping/delegated-worktree-nesting.test.ts create mode 100644 src/renderer/src/components/sidebar/worktree-list/grouping/delegated-worktree-nesting.ts create mode 100644 src/shared/worktree/delegated-worktree-edge.ts 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..a48a7a48c9b0 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 delegatedWorktreeEdges = this.delegatedWorktreeEdgeProjection.build() const nativeChatLaunchDraftResolutions = this.getNativeChatLaunchDraftResolutionClientEventSnapshot().map( ({ tabId, text, createdAt }) => ({ tabId, text, createdAt }) @@ -322,6 +323,7 @@ export class OrcaRuntimeWithSyncWindowGraph extends OrcaRuntimeWithAttachWindow return { ...this.getStatus(), ...(agentOrchestrationByPaneKey ? { agentOrchestrationByPaneKey } : {}), + ...(delegatedWorktreeEdges ? { delegatedWorktreeEdges } : {}), ...(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..508a5212e3d0 --- /dev/null +++ b/src/main/runtime/runtime-delegated-worktree-edge-projection.test.ts @@ -0,0 +1,81 @@ +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([ + { + 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?.[0]?.parentWorktreeId).toBe('repo-1::/home/alex/coordinator') + }) + + it('drops a placement whose coordinator terminal is gone', () => { + expect(projection({ placements: [placement] }).build()).toBeUndefined() + }) + + it('drops a self-referential placement', () => { + expect( + projection({ + placements: [placement], + worktreeByHandle: { term_coordinator: placement.remote_worktree_id } + }).build() + ).toBeUndefined() + }) + + it('reports nothing rather than empty when the host cannot answer', () => { + expect(projection({ db: 'missing' }).build()).toBeUndefined() + expect(projection({ db: 'without-query' }).build()).toBeUndefined() + }) +}) 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..1104116c2ee0 --- /dev/null +++ b/src/main/runtime/runtime-delegated-worktree-edge-projection.ts @@ -0,0 +1,67 @@ +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 +} + +/** + * 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(): DelegatedWorktreeEdge[] | undefined { + const db = this.deps.getDb() + if (!db?.listDelegatedWorktreePlacements) { + return undefined + } + const edges: DelegatedWorktreeEdge[] = [] + for (const placement of db.listDelegatedWorktreePlacements(MAX_DELEGATED_EDGES)) { + const parentWorktreeId = this.resolveCoordinatorWorktreeId(placement) + if (!parentWorktreeId || parentWorktreeId === placement.remote_worktree_id) { + continue + } + edges.push({ + parentWorktreeId, + childHostId: toRuntimeExecutionHostId(placement.environment_id), + childWorktreeId: placement.remote_worktree_id, + dispatchId: placement.dispatch_id + }) + } + return edges.length > 0 ? edges : undefined + } + + 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..2ac37f8974e7 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,23 @@ 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, + homeHostId: defaultHostId, + 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 +206,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 +233,8 @@ export function buildRows( pendingByRepo, repoOrder, projectOrderBy, - folderWorkspaces: renderableFolderWorkspaces + folderWorkspaces: renderableFolderWorkspaces, + sectionAnchorByChildIdentity }) const sectionContext: SectionAppendContext = { @@ -229,7 +254,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..652c3b40ef35 --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/grouping/delegated-worktree-nesting.test.ts @@ -0,0 +1,168 @@ +import { describe, expect, it } from 'vitest' +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 { Worktree } from '../../../../../../shared/worktree/types' +import type { 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' +} + +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] + ]) + const lineage: Record = {} + + function rowsFor(edges: readonly DelegatedWorktreeEdge[]) { + return buildRows( + 'repo', + [coordinator, remoteWorker], + repoMapWithRemote, + null, + new Set(), + undefined, + undefined, + 'manual', + lineage, + new Map([ + [coordinator.id, coordinator], + [remoteWorker.id, remoteWorker] + ]), + true, + undefined, + [], + new Set(), + new Map(), + new Map(), + [], + undefined, + [], + undefined, + '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('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) + }) +}) 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..433704859f2f --- /dev/null +++ b/src/renderer/src/components/sidebar/worktree-list/grouping/delegated-worktree-nesting.ts @@ -0,0 +1,99 @@ +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 publishing runtime's own worktrees are stamped with. */ + 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..03a090cc0bc3 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,7 +78,8 @@ export function buildOrderedGroups(args: { pendingByRepo, repoOrder, projectOrderBy, - folderWorkspaces = [] + folderWorkspaces = [], + sectionAnchorByChildIdentity } = args const grouped = new Map() @@ -83,8 +87,9 @@ export function buildOrderedGroups(args: { 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 +108,7 @@ export function buildOrderedGroups(args: { } const group = grouped.get(key)! group.items.push(w) - addRepoIdToGroup(group, w.repoId) + addRepoIdToGroup(group, anchor.repoId) } // 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 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/graph-publication.ts b/src/renderer/src/runtime/sync-runtime-graph/graph-publication.ts index f74c97f6e410..414fea451b35 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,7 @@ export async function syncRuntimeGraph(): Promise { commitMobileSessionPublication(mobileSessionTabs, result?.mobileSessionResyncWorktrees) const currentState = graphState.getStoreState() currentState?.setRuntimeAgentOrchestrationByPaneKey?.(result?.agentOrchestrationByPaneKey ?? {}) + 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..ed0875ac1add 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,8 @@ export type RuntimeNativeChatLaunchDraftResolution = { export type RuntimeSyncWindowGraphResult = RuntimeStatus & { agentOrchestrationByPaneKey?: Record + /** Cross-host worker placements this runtime coordinated; absent means none, not unsupported. */ + delegatedWorktreeEdges?: DelegatedWorktreeEdge[] 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 +} From 67f213e70928064b073f25fc2dfdb9267528783d Mon Sep 17 00:00:00 2001 From: Alexander Miller Date: Wed, 23 Sep 2026 11:34:44 -0400 Subject: [PATCH 2/5] fix(sidebar): delegated edges name the publishing runtime, not the focused host MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The edges arrive on this window's own graph sync, so their coordinator is always a local row, but the lookup composed the parent identity with the focused execution host. Focusing a remote environment — the very case this nests for — made every edge miss and the cards fall back to top-level. Co-Authored-By: Claude Opus 5 --- .../worktree-list/grouping/build-rows.ts | 4 ++- .../delegated-worktree-nesting.test.ts | 33 +++++++++++++++++++ .../grouping/delegated-worktree-nesting.ts | 3 +- 3 files changed, 38 insertions(+), 2 deletions(-) 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 2ac37f8974e7..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 @@ -94,7 +94,9 @@ export function buildRows( ? resolveDelegatedWorktreeNesting({ worktrees, edges: delegatedWorktreeEdges, - homeHostId: defaultHostId, + // 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 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 index 652c3b40ef35..e94655790c2f 100644 --- 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 @@ -158,6 +158,39 @@ describe('buildRows with delegated edges', () => { ).toHaveLength(1) }) + it('still nests while the sidebar is focused on a remote host', () => { + // Focus is a filter; the edges still come from this window's own runtime. + const rows = buildRows( + 'repo', + [coordinator, remoteWorker], + repoMapWithRemote, + null, + new Set(), + undefined, + undefined, + 'manual', + lineage, + new Map([ + [coordinator.id, coordinator], + [remoteWorker.id, remoteWorker] + ]), + true, + undefined, + [], + new Set(), + new Map(), + new Map(), + [], + undefined, + [], + undefined, + REMOTE_HOST, + 'single-location', + [edge] + ) + 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) 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 index 433704859f2f..d1c7b43338c0 100644 --- 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 @@ -27,7 +27,8 @@ const EMPTY_NESTING: DelegatedWorktreeNesting = { export function resolveDelegatedWorktreeNesting(args: { worktrees: readonly Worktree[] edges: readonly DelegatedWorktreeEdge[] - /** Host the publishing runtime's own worktrees are stamped with. */ + /** 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 From 0537cf2cd7e9b45d20ffaef533c46c98f710490c Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 23 Sep 2026 13:04:14 -0400 Subject: [PATCH 3/5] fix(sidebar): an unanswerable db is not zero delegated edges Four review findings on delegated-worker nesting. The edge projection returned undefined for three different conditions, and the sync window omitted the field for all of them, so a renderer committing `[]` could not tell "this runtime coordinated nothing" from "the orchestration db is not up yet". A transient gap un-nested every delegated card until the db came back. build() now answers known/unknown, the window publishes delegatedWorktreeEdgesUnavailable instead of an empty list when the db cannot be asked, and the renderer keeps the edges it already holds. The flag is a new optional field, so an older client simply ignores it and behaves as it does today. The projection also dropped an edge whenever a coordinator and its worker happened to share a bare worktree id. Those ids collide legitimately across hosts, and a real self-reference is only decidable once both ends are host-qualified, which resolveDelegatedWorktreeNesting already does. A delegated child renders inside its coordinator's repo section, which left its own repo with no section and silently dropped that repo's imported -worktrees card, external-worktrees inbox and pending-creation rows. Those notice rows now follow the child into the section it actually renders in, unless the repo turns out to have a section of its own. The homeHostId fix the reviewers asked for is already present at the base commit; its test now derives the focused host through getSettingsFocusedExecutionHostId, the production path, so it fails if that regresses. Co-Authored-By: Claude Opus 5 (1M context) --- .../runtime/orca-runtime-sync-window-graph.ts | 8 +- ...delegated-worktree-edge-projection.test.ts | 53 +++++---- ...time-delegated-worktree-edge-projection.ts | 23 +++- .../delegated-worktree-nesting.test.ts | 82 +++++++------ .../grouping/worktree-grouping.ts | 21 +++- ...ime-graph-delegated-worktree-edges.test.ts | 108 ++++++++++++++++++ .../sync-runtime-graph/graph-publication.ts | 6 +- src/shared/runtime-session-contracts.ts | 4 +- 8 files changed, 238 insertions(+), 67 deletions(-) create mode 100644 src/renderer/src/runtime/sync-runtime-graph-delegated-worktree-edges.test.ts diff --git a/src/main/runtime/orca-runtime-sync-window-graph.ts b/src/main/runtime/orca-runtime-sync-window-graph.ts index a48a7a48c9b0..1b7c8e2e4aa8 100644 --- a/src/main/runtime/orca-runtime-sync-window-graph.ts +++ b/src/main/runtime/orca-runtime-sync-window-graph.ts @@ -315,7 +315,7 @@ export class OrcaRuntimeWithSyncWindowGraph extends OrcaRuntimeWithAttachWindow } const agentOrchestrationByPaneKey = this.agentOrchestrationProjection.buildByPaneKey() - const delegatedWorktreeEdges = this.delegatedWorktreeEdgeProjection.build() + const delegatedEdges = this.delegatedWorktreeEdgeProjection.build() const nativeChatLaunchDraftResolutions = this.getNativeChatLaunchDraftResolutionClientEventSnapshot().map( ({ tabId, text, createdAt }) => ({ tabId, text, createdAt }) @@ -323,7 +323,11 @@ export class OrcaRuntimeWithSyncWindowGraph extends OrcaRuntimeWithAttachWindow return { ...this.getStatus(), ...(agentOrchestrationByPaneKey ? { agentOrchestrationByPaneKey } : {}), - ...(delegatedWorktreeEdges ? { delegatedWorktreeEdges } : {}), + // 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/runtime-delegated-worktree-edge-projection.test.ts b/src/main/runtime/runtime-delegated-worktree-edge-projection.test.ts index 508a5212e3d0..5ac95c4eb1cb 100644 --- a/src/main/runtime/runtime-delegated-worktree-edge-projection.test.ts +++ b/src/main/runtime/runtime-delegated-worktree-edge-projection.test.ts @@ -42,14 +42,17 @@ describe('RuntimeDelegatedWorktreeEdgeProjection', () => { placements: [placement], worktreeByHandle: { term_coordinator: 'repo-1::/home/alex/coordinator' } }).build() - expect(edges).toEqual([ - { - parentWorktreeId: 'repo-1::/home/alex/coordinator', - childHostId: 'runtime:env-1', - childWorktreeId: 'repo-remote::/home/ubuntu/worker', - dispatchId: 'ctx_1' - } - ]) + 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', () => { @@ -58,24 +61,34 @@ describe('RuntimeDelegatedWorktreeEdgeProjection', () => { handleByPaneKey: { 'pane-1': 'term_reminted' }, worktreeByHandle: { term_reminted: 'repo-1::/home/alex/coordinator' } }).build() - expect(edges?.[0]?.parentWorktreeId).toBe('repo-1::/home/alex/coordinator') + 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()).toBeUndefined() + expect(projection({ placements: [placement] }).build()).toEqual({ known: true, edges: [] }) }) - it('drops a self-referential placement', () => { - expect( - projection({ - placements: [placement], - worktreeByHandle: { term_coordinator: placement.remote_worktree_id } - }).build() - ).toBeUndefined() + 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('reports nothing rather than empty when the host cannot answer', () => { - expect(projection({ db: 'missing' }).build()).toBeUndefined() - expect(projection({ db: 'without-query' }).build()).toBeUndefined() + 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 index 1104116c2ee0..ebd5a77ac6e6 100644 --- a/src/main/runtime/runtime-delegated-worktree-edge-projection.ts +++ b/src/main/runtime/runtime-delegated-worktree-edge-projection.ts @@ -18,6 +18,18 @@ type DelegatedWorktreeEdgeDependencies = { 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. * @@ -28,15 +40,18 @@ type DelegatedWorktreeEdgeDependencies = { export class RuntimeDelegatedWorktreeEdgeProjection { constructor(private readonly deps: DelegatedWorktreeEdgeDependencies) {} - build(): DelegatedWorktreeEdge[] | undefined { + build(): DelegatedWorktreeEdgeProjectionResult { const db = this.deps.getDb() if (!db?.listDelegatedWorktreePlacements) { - return undefined + 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 || parentWorktreeId === placement.remote_worktree_id) { + if (!parentWorktreeId) { continue } edges.push({ @@ -46,7 +61,7 @@ export class RuntimeDelegatedWorktreeEdgeProjection { dispatchId: placement.dispatch_id }) } - return edges.length > 0 ? edges : undefined + return { known: true, edges } } private resolveCoordinatorWorktreeId(placement: { 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 index e94655790c2f..4f64a6dcb0ff 100644 --- 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 @@ -1,11 +1,18 @@ 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 { Worktree } from '../../../../../../shared/worktree/types' -import type { Row } from './row-types' +import type { + ImportedWorktreesCardCandidate, + NewExternalWorktreesInboxCandidate, + PendingCreationRef, + Row +} from './row-types' const REMOTE_HOST = 'runtime:env-1' as const @@ -116,7 +123,15 @@ describe('buildRows with delegated edges', () => { ]) const lineage: Record = {} - function rowsFor(edges: readonly DelegatedWorktreeEdge[]) { + function rowsFor( + edges: readonly DelegatedWorktreeEdge[], + overrides: { + defaultHostId?: ExecutionHostId + importedWorktreesByRepo?: ReadonlyMap + newExternalWorktreesInboxByRepo?: ReadonlyMap + pendingCreations?: readonly PendingCreationRef[] + } = {} + ) { return buildRows( 'repo', [coordinator, remoteWorker], @@ -135,13 +150,13 @@ describe('buildRows with delegated edges', () => { undefined, [], new Set(), - new Map(), - new Map(), - [], + overrides.importedWorktreesByRepo ?? new Map(), + overrides.newExternalWorktreesInboxByRepo ?? new Map(), + overrides.pendingCreations ?? [], undefined, [], undefined, - 'local', + overrides.defaultHostId ?? 'local', 'single-location', edges ) @@ -158,36 +173,12 @@ describe('buildRows with delegated edges', () => { ).toHaveLength(1) }) - it('still nests while the sidebar is focused on a remote host', () => { - // Focus is a filter; the edges still come from this window's own runtime. - const rows = buildRows( - 'repo', - [coordinator, remoteWorker], - repoMapWithRemote, - null, - new Set(), - undefined, - undefined, - 'manual', - lineage, - new Map([ - [coordinator.id, coordinator], - [remoteWorker.id, remoteWorker] - ]), - true, - undefined, - [], - new Set(), - new Map(), - new Map(), - [], - undefined, - [], - undefined, - REMOTE_HOST, - 'single-location', - [edge] - ) + 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 }) }) @@ -198,4 +189,23 @@ describe('buildRows with delegated edges', () => { 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) + }) }) 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 03a090cc0bc3..32cd229ce8d2 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 @@ -83,6 +83,10 @@ export function buildOrderedGroups(args: { } = 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() for (const w of naturalWorktrees) { let key: string let label: string @@ -109,6 +113,17 @@ export function buildOrderedGroups(args: { const group = grouped.get(key)! group.items.push(w) addRepoIdToGroup(group, anchor.repoId) + if (anchor !== w) { + addRepoIdToGroup(group, w.repoId) + anchoredSectionKeyByRepoId.set(w.repoId, key) + } + } + for (const [repoId, sectionKey] of anchoredSectionKeyByRepoId) { + const ownKey = getProjectGroupingForRepo(repoId, repoMap, projectIndex).key + if (ownKey === sectionKey || grouped.has(ownKey)) { + // The repo has a section of its own after all; leave its notice rows there. + anchoredSectionKeyByRepoId.delete(repoId) + } } // 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 @@ -158,7 +173,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, @@ -174,7 +189,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. @@ -192,7 +207,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/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 414fea451b35..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,7 +190,11 @@ export async function syncRuntimeGraph(): Promise { commitMobileSessionPublication(mobileSessionTabs, result?.mobileSessionResyncWorktrees) const currentState = graphState.getStoreState() currentState?.setRuntimeAgentOrchestrationByPaneKey?.(result?.agentOrchestrationByPaneKey ?? {}) - currentState?.setDelegatedWorktreeEdges?.(result?.delegatedWorktreeEdges ?? []) + // 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/shared/runtime-session-contracts.ts b/src/shared/runtime-session-contracts.ts index ed0875ac1add..8ec4641a5d1b 100644 --- a/src/shared/runtime-session-contracts.ts +++ b/src/shared/runtime-session-contracts.ts @@ -167,8 +167,10 @@ export type RuntimeNativeChatLaunchDraftResolution = { export type RuntimeSyncWindowGraphResult = RuntimeStatus & { agentOrchestrationByPaneKey?: Record - /** Cross-host worker placements this runtime coordinated; absent means none, not unsupported. */ + /** 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[] } From 4b5d038f2d9f99fba0b759adab1785e0dfe8719e Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 23 Sep 2026 13:12:37 -0400 Subject: [PATCH 4/5] fix(sidebar): don't claim a child repo that kept its own section MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review follow-up on the previous commit. Redirecting a delegated child's notice rows into its coordinator's section dropped the redirect when the repo turned out to have a section of its own, but left that repo in the coordinator group's repoIds. Both sections then emitted the imported-worktrees card, the external-worktrees inbox and the pending-creation rows under identical repo-keyed ids — a duplicated card and a React key collision. Releasing the claim now releases the repoId too. A coordinator section that is already the repo's own section keeps it, since the rows belong there once. Co-Authored-By: Claude Opus 5 (1M context) --- .../delegated-worktree-nesting.test.ts | 52 +++++++++++++++++-- .../grouping/worktree-grouping.ts | 12 ++++- 2 files changed, 57 insertions(+), 7 deletions(-) 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 index 4f64a6dcb0ff..49ceb0398d85 100644 --- 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 @@ -33,6 +33,17 @@ const remoteWorker: Worktree = { 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 edge: DelegatedWorktreeEdge = { parentWorktreeId: coordinator.id, childHostId: REMOTE_HOST, @@ -130,11 +141,13 @@ describe('buildRows with delegated edges', () => { importedWorktreesByRepo?: ReadonlyMap newExternalWorktreesInboxByRepo?: ReadonlyMap pendingCreations?: readonly PendingCreationRef[] + extraWorktrees?: readonly Worktree[] } = {} ) { + const worktrees = [coordinator, remoteWorker, ...(overrides.extraWorktrees ?? [])] return buildRows( 'repo', - [coordinator, remoteWorker], + worktrees, repoMapWithRemote, null, new Set(), @@ -142,10 +155,7 @@ describe('buildRows with delegated edges', () => { undefined, 'manual', lineage, - new Map([ - [coordinator.id, coordinator], - [remoteWorker.id, remoteWorker] - ]), + new Map(worktrees.map((w) => [w.id, w])), true, undefined, [], @@ -208,4 +218,36 @@ describe('buildRows with delegated edges', () => { 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) + }) }) 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 32cd229ce8d2..6dd3513132aa 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 @@ -120,8 +120,16 @@ export function buildOrderedGroups(args: { } for (const [repoId, sectionKey] of anchoredSectionKeyByRepoId) { const ownKey = getProjectGroupingForRepo(repoId, repoMap, projectIndex).key - if (ownKey === sectionKey || grouped.has(ownKey)) { - // The repo has a section of its own after all; leave its notice rows there. + if (ownKey === sectionKey) { + // The coordinator's section is this repo's own section, so its rows already belong here. + anchoredSectionKeyByRepoId.delete(repoId) + continue + } + if (grouped.has(ownKey)) { + // The repo has a section of its own after all. Drop the claim here as well as the + // redirect: the repo-keyed row ids are identical in both sections, so emitting from + // each would duplicate the card and collide the keys. + grouped.get(sectionKey)?.repoIds.delete(repoId) anchoredSectionKeyByRepoId.delete(repoId) } } From 96c76d58d6d8d923263ed654b078f3b0fdbb400c Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 23 Sep 2026 13:21:33 -0400 Subject: [PATCH 5/5] fix(sidebar): one section owns a delegated child repo's notice rows Two delegated children of the same repo can anchor to coordinators in different sections. The redirect was last-write-wins, so the earlier coordinator kept the repo in its repoIds and emitted the imported-worktrees card, the inbox row and the pending-creation rows a second time under the same repo-keyed ids. Track every section that claims a repo this way and leave exactly one holding it: the repo's own section when it has one, otherwise the last coordinator to anchor a child of it. The others release the repoId along with the redirect. Co-Authored-By: Claude Opus 5 (1M context) --- .../delegated-worktree-nesting.test.ts | 50 ++++++++++++++++++- .../grouping/worktree-grouping.ts | 31 ++++++++---- 2 files changed, 70 insertions(+), 11 deletions(-) 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 index 49ceb0398d85..c9d37cd143da 100644 --- 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 @@ -6,6 +6,7 @@ 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, @@ -44,6 +45,28 @@ const remoteSibling: Worktree = { 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, @@ -130,7 +153,8 @@ function findItem( describe('buildRows with delegated edges', () => { const repoMapWithRemote = new Map([ [repo.id, repo], - [remoteRepo.id, remoteRepo] + [remoteRepo.id, remoteRepo], + [otherRepo.id, otherRepo] ]) const lineage: Record = {} @@ -250,4 +274,28 @@ describe('buildRows with delegated edges', () => { .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/worktree-grouping.ts b/src/renderer/src/components/sidebar/worktree-list/grouping/worktree-grouping.ts index 6dd3513132aa..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 @@ -87,6 +87,9 @@ export function buildOrderedGroups(args: { // 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 @@ -116,21 +119,29 @@ export function buildOrderedGroups(args: { 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, sectionKey] of anchoredSectionKeyByRepoId) { + for (const [repoId, claimedKeys] of claimedSectionKeysByRepoId) { const ownKey = getProjectGroupingForRepo(repoId, repoMap, projectIndex).key - if (ownKey === sectionKey) { - // The coordinator's section is this repo's own section, so its rows already belong here. - anchoredSectionKeyByRepoId.delete(repoId) - continue + // 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 (grouped.has(ownKey)) { - // The repo has a section of its own after all. Drop the claim here as well as the - // redirect: the repo-keyed row ids are identical in both sections, so emitting from - // each would duplicate the card and collide the keys. - grouped.get(sectionKey)?.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