From 00b6844d13a846fddd7dcff038a4d3df9fbaf0f5 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sun, 31 May 2026 04:28:55 -0700 Subject: [PATCH] perf: avoid sorting CLI worktree selectors (#4107) --- src/cli/index.test.ts | 1 + src/cli/selectors.ts | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index c3910f912..0cab307f7 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -198,6 +198,7 @@ describe('orca cli worktree awareness', () => { queueFixtures( callMock, worktreeListFixture([ + buildWorktree('/tmp/repo', 'main'), buildWorktree('/tmp/repo/feature', 'feature/foo'), buildWorktree('/tmp/repo/feature', 'feature/foo', 'abc', 'duplicate-repo') ]), diff --git a/src/cli/selectors.ts b/src/cli/selectors.ts index a94878ca8..94a668b46 100644 --- a/src/cli/selectors.ts +++ b/src/cli/selectors.ts @@ -1,5 +1,9 @@ import { isAbsolute, relative, resolve as resolvePath } from 'path' -import type { ComputerAppQuery, RuntimeWorktreeListResult } from '../shared/runtime-types' +import type { + ComputerAppQuery, + RuntimeWorktreeListResult, + RuntimeWorktreeRecord +} from '../shared/runtime-types' import { isPathInsideOrEqual } from '../shared/cross-platform-path' import type { RuntimeClient } from './runtime-client' import { RuntimeClientError } from './runtime-client' @@ -57,9 +61,16 @@ export async function resolveCurrentWorktreeSelector( const worktrees = await client.call('worktree.list', { limit: 10_000 }) - const enclosingWorktree = worktrees.result.worktrees - .filter((worktree) => isWithinPath(resolvePath(worktree.path), currentPath)) - .sort((left, right) => right.path.length - left.path.length)[0] + let enclosingWorktree: RuntimeWorktreeRecord | undefined + let enclosingPathLength = -1 + for (const worktree of worktrees.result.worktrees) { + const worktreePath = resolvePath(worktree.path) + if (!isWithinPath(worktreePath, currentPath) || worktreePath.length <= enclosingPathLength) { + continue + } + enclosingWorktree = worktree + enclosingPathLength = worktreePath.length + } if (!enclosingWorktree) { throw new RuntimeClientError(