Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/main/runtime/orca-runtime-stop-requested-pty-ids.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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),
Expand Down
6 changes: 6 additions & 0 deletions src/main/runtime/orca-runtime-sync-window-graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,13 +315,19 @@ export class OrcaRuntimeWithSyncWindowGraph extends OrcaRuntimeWithAttachWindow
}

const agentOrchestrationByPaneKey = this.agentOrchestrationProjection.buildByPaneKey()
const delegatedEdges = this.delegatedWorktreeEdgeProjection.build()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Republish edges when placements change

When a remote worker becomes ready after the renderer's last graph publication, updateFederatedDispatchResources changes only SQLite and does not schedule another renderer graph sync, while this projection is sampled only inside syncWindowGraph. The remote-worktree refresh can therefore make the worker card appear at top level, where it remains until an unrelated tab, title, or status event triggers another sync; publish or invalidate the edge projection when the placement is written.

Useful? React with 👍 / 👎.

const nativeChatLaunchDraftResolutions =
this.getNativeChatLaunchDraftResolutionClientEventSnapshot().map(
({ tabId, text, createdAt }) => ({ tabId, text, createdAt })
)
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] }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?`

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve live placements beyond the dispatch cap

Once the database contains more than 500 newer federated dispatch rows, this unconditional limit omits older placements even when their remote workspaces are still visible, causing those cards to jump back to top level. Repeated dispatches onto one shared workspace make this especially easy because duplicate placements consume the entire cap; deduplicate/filter by current child workspace before applying the limit so historical rows cannot evict unrelated live edges.

Useful? React with 👍 / 👎.

)
.all(limit)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the SELECT list names exactly these five columns.
return rows as DelegatedWorktreePlacementRow[]
}
Comment on lines +102 to +119

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 performance · medium

Per-graph-sync SQL scan of unbounded dispatch table

Every syncWindowGraph call now runs RuntimeDelegatedWorktreeEdgeProjection.build() (src/main/runtime/orca-runtime-sync-window-graph.ts:318), which executes listDelegatedWorktreePlacements synchronously on the main process (src/main/runtime/orchestration/db/federation/federated-dispatch-store.ts:102-119). Graph syncs are coalesced at 16ms and fire on every terminal title/status/store change, so the query sits on a hot per-frame path; it re-compiles the prepared statement on every call, filters remote_worktree_id IS NOT NULL with no index on that column, and scans an append-only table whose settled dispatches are deliberately retained forever. Main-process CPU cost per sync grows monotonically with accumulated dispatch history.

📋 Prompt for AI Agents

Two changes: (1) in src/main/runtime/orchestration/db/schema/create-graph-tables-sql.ts add a partial index CREATE INDEX IF NOT EXISTS idx_federated_dispatches_remote_worktree ON federated_dispatches(remote_worktree_id) WHERE remote_worktree_id IS NOT NULL so the placement query in federated-dispatch-store.ts:102-119 stops scanning the whole append-only table; also hoist the db.prepare call so the statement is compiled once. (2) In src/main/runtime/runtime-delegated-worktree-edge-projection.ts cache the built edges and invalidate on a dispatch-store mutation hook (or throttle rebuilds) instead of querying synchronously on every syncWindowGraph — syncs are coalesced at 16ms in src/renderer/src/runtime/sync-runtime-graph/graph-state.ts and fire on every terminal status change.


export function updateFederatedDispatchResources(
this: OrchestrationDb,
params: {
Expand Down Expand Up @@ -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
Expand All @@ -140,6 +175,7 @@ export function attachFederatedDispatchStore(ctor: { prototype: object }): void
getFederatedDispatch,
listFederatedDispatchesByIds,
listActiveFederatedDispatches,
listDelegatedWorktreePlacements,
findNextTerminalFederatedDispatchPendingAcknowledgment,
isFederatedDispatchRelayEligible,
updateFederatedDispatchResources,
Expand Down
Original file line number Diff line number Diff line change
@@ -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<string, string>
handleByPaneKey?: Record<string, string>
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: [] })
})
})
82 changes: 82 additions & 0 deletions src/main/runtime/runtime-delegated-worktree-edge-projection.ts
Original file line number Diff line number Diff line change
@@ -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 }
Comment on lines +48 to +64

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 bug · medium

500-placement cap evicts live edges over time

RuntimeDelegatedWorktreeEdgeProjection.build caps the placement query at MAX_DELEGATED_EDGES = 500 and still returns known: true (runtime-delegated-worktree-edge-projection.ts:48-64), so the sync result replaces the reader's prior edge set with the truncated list (orca-runtime-sync-window-graph.ts:328-330). Settled dispatches are included on purpose and federated_dispatches has no pruning path (federated-dispatch-store.ts:95-119), so the newest-first LIMIT 500 window is eventually filled with stale settled placements and the edges of still-live workers fall off the tail. Because this is published as a real answer, the affected delegated cards silently un-nest for readers.

📋 Prompt for AI Agents

In src/main/runtime/runtime-delegated-worktree-edge-projection.ts line 8 and src/main/runtime/orchestration/db/federation/federated-dispatch-store.ts lines 102-119, make the placement query retention-aware instead of a bare LIMIT 500 over all federated_dispatches history: settled dispatches are intentionally kept and the table has no pruning path, so the newest-first cap is eventually dominated by stale settled rows and silently evicts placements of still-live workers. Either join against worker_dispatches/dispatch status to restrict to live plus recently settled dispatches before applying the LIMIT, or signal truncation (e.g. return { known: false } when exactly MAX rows come back) so readers keep their prior edges; add a test that a live worker's edge survives when 500+ older settled dispatches exist.

}

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
Comment on lines +71 to +80

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 bug · medium

Pane-key fallback rebinds settled placements to wrong coordinator

The projection resolves the coordinator worktree by creator_handle first, then falls back to creator_pane_key → getHandleForPaneKey → getWorktreeId (src/main/runtime/runtime-delegated-worktree-edge-projection.ts:71-80). getTerminalHandleForPaneKey issues a handle for whatever terminal currently occupies that pane, and settled dispatches are retained forever, so after a restart — when the original handle no longer resolves — a placement whose coordinator terminal was closed or whose pane now hosts a different worktree's terminal is re-parented onto the pane's current occupant. The sidebar then nests the worker card under the wrong coordinator for as long as the stale placement row stays in the 500-row window.

📋 Prompt for AI Agents

In src/main/runtime/runtime-delegated-worktree-edge-projection.ts lines 67-81, tighten resolveCoordinatorWorktreeId: the creator_pane_key fallback must not bind a historical placement to the pane's current occupant. Either record and compare a terminal incarnation/pane-generation alongside creator_pane_key so a reminted handle for a different terminal is rejected, or drop placements whose creator_handle no longer resolves instead of falling back to the pane key. Settled placements are retained forever by listDelegatedWorktreePlacements, so the fallback can permanently re-parent an old worker under whichever coordinator terminal now occupies the reused pane after a restart.

}
}
2 changes: 2 additions & 0 deletions src/renderer/src/components/sidebar/WorktreeList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -163,6 +164,7 @@ const WorktreeList = React.memo(function WorktreeList({
repoMap,
worktreeMap,
worktreeLineageById,
delegatedWorktreeEdges,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Feed delegated ancestry into collapsed-group reveals

When the coordinator's repo section or lineage fold is collapsed, selecting its delegated worker through pending reveal or the agent-send picker cannot expose the card. The edge is passed only to row construction here, while useEffectiveCollapsedGroups and pending-reveal handling derive section and ancestor keys solely from the worker's own repo and Git lineage, so they open the wrong repo section and never open the coordinator's fold; use delegated ancestry when computing reveal keys as well.

Useful? React with 👍 / 👎.

prCache,
settings,
workspaceStatuses,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -70,7 +75,8 @@ export function buildRows(
folderWorkspaces: readonly FolderWorkspace[] = [],
hostLabelById?: ReadonlyMap<string, string>,
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)
Expand All @@ -80,6 +86,25 @@ export function buildRows(
const cyclicLineageIds = nestLineage
? getCyclicProjectedWorktreeLineageIds(lineageById, worktreeMap)
: new Set<string>()
// 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({
Comment on lines +92 to +94

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Propagate delegated descendants into the pinned section

With the default single-location pinned policy, pinning the coordinator does not pull its delegated child into the Pinned section because getPinnedSectionWorktrees traverses only git lineage and emitPinnedGroup never receives this delegated projection. The parent is removed from the natural groups while the worker remains there, so the worker is rendered top-level instead of beneath its pinned coordinator; delegated descendants need to participate in pinned membership and row emission just like lineage descendants.

Useful? React with 👍 / 👎.

worktrees,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include folder workspaces in delegated nesting

When either endpoint is an exact folder workspace—a supported federated placement—the edge can never match because only worktrees are passed into the resolver, while folder workspace cards are maintained and emitted separately. Consequently a remote worker delegated from or into a folder workspace remains top-level even though the dispatch records contain both endpoints; include folder workspace identities and row emission in the delegated projection.

AGENTS.md reference: AGENTS.md:L93-L95

Useful? React with 👍 / 👎.

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
Comment on lines +92 to +105

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 bug · medium

Delegated child of pinned coordinator renders unnested

A delegated worker whose coordinator worktree is pinned is anchored by sectionAnchorByChildIdentity into the coordinator's repo section (src/renderer/src/components/sidebar/worktree-list/grouping/build-rows.ts:92-105), but under the default pinned policy the coordinator row itself lives in the Pinned section, so visibleByIdentity in appendWorktreeRows does not contain the parent and the delegated attach is dropped — the child renders as a depth-0 root. Git-lineage children of the same pinned coordinator instead follow it into the Pinned section, so the two sibling kinds of one coordinator render in different places with different nesting.

📋 Prompt for AI Agents

In src/renderer/src/components/sidebar/worktree-list/grouping/build-rows.ts around lines 92-107, delegated nesting does not account for pinned coordinators: resolveDelegatedWorktreeNesting anchors a delegated child to its coordinator even when the coordinator is pinned, so buildOrderedGroups places the child in the coordinator's repo section while the coordinator row is in the Pinned section, and appendWorktreeRows (row-builders.ts:165) cannot find the parent in that section's visibleByIdentity — the child renders as an unnested root. Fix by skipping edges whose resolved parent is in pinnedSectionWorktrees when building sectionAnchorByChildIdentity, or by passing the delegated parent map into the pinned-section emission so the child nests there, matching how git-lineage children of pinned worktrees are handled. Add a test covering a pinned coordinator with a delegated remote worker.

const sectionAnchorByChildIdentity =
groupBy === 'repo' ? delegatedNesting?.sectionAnchorByChildIdentity : undefined

const pendingByRepo = new Map<string, PendingCreationRef[]>()
for (const creation of pendingCreations) {
Expand Down Expand Up @@ -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)
Expand All @@ -209,7 +235,8 @@ export function buildRows(
pendingByRepo,
repoOrder,
projectOrderBy,
folderWorkspaces: renderableFolderWorkspaces
folderWorkspaces: renderableFolderWorkspaces,
sectionAnchorByChildIdentity
})

const sectionContext: SectionAppendContext = {
Expand All @@ -229,7 +256,8 @@ export function buildRows(
lineageById,
worktreeMap,
nestLineage,
cyclicLineageIds
cyclicLineageIds,
delegatedParentIdentityByChildIdentity: delegatedNesting?.parentIdentityByChildIdentity
Comment on lines +259 to +260

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid orphaning nested rows in host-section views

When the user explicitly selects two or more hosts, addHostSectionRows later partitions rows by their actual host. This delegated map has already assigned the remote child depth 1 beneath a local parent, so the partition moves the child into the remote host section while leaving its parent and repo header in the local section, producing an indented orphan row. Cross-host nesting should be disabled or flattened for host-partitioned views, or the hierarchy must be kept together deliberately.

Useful? React with 👍 / 👎.

}

if (groupBy !== 'repo' || projectGroups.length === 0) {
Expand Down
Loading