Skip to content

perf(vault): look up resume worktrees through the shared index - #11317

Merged
nwparker merged 1 commit into
mainfrom
perf/ai-vault-resume-worktree-index
Jul 29, 2026
Merged

nwparker merged 1 commit into
mainfrom
perf/ai-vault-resume-worktree-index

Conversation

@nwparker

Copy link
Copy Markdown
Contributor

Small follow-up to #11303 / #11314. Uses an index that already exists rather than adding anything.

What

Resolving a session's resume target scanned every worktree in every repo, three times over:

// ai-vault-resume-target.ts:135 and :161
const worktree = Object.values(state.worktreesByRepo ?? {})
  .flat()
  .find((candidate) => candidate.id === worktreeId)

// ai-vault-session-resume.ts:148
return Object.values(state.worktreesByRepo).some((worktrees) =>
  worktrees.some((worktree) => worktree.id === worktreeId)
)

The two .flat() calls also allocate a fresh 1124-element array each time. All three run per visible session row, so one panel render repeats them ~20 times.

getIndexedWorktreeMap (store/worktree-repo-index.ts) already does exactly this and is WeakMap-cached on worktreesByRepo, so the index is built once per store snapshot instead of once per call. connection-owner-resolution.ts:63 already resolves worktrees this way — this just brings the vault path in line.

Result

~1.6ms → ~0.002ms per render pass at 1124 worktrees. Net -4 lines.

To be clear about scale: this is a small win, not a fix for a visible stall. The real ones were #11303 (map rebuilds) and #11314 (189.7ms → 0.8ms). This is the tidy-up that was left over, and it's worth doing mainly because it deletes code and reuses an existing helper.

Behavior

Unchanged. The one place a Map could differ from .find() is a duplicate id resolving to a different object — find() takes the first, the map takes the last writer.

That can't happen here: worktree ids are repoId::path, so a duplicate id within a repo array (the documented createWorktree/fetchWorktrees race the index was built to absorb) necessarily refers to the same worktree. Verified against a real 1124-worktree profile: zero ids appear under more than one repo.

Verification

  • 4810 tests pass across right-sidebar/ and lib/
  • tsc --noEmit -p config/tsconfig.tc.web.json clean
  • oxlint clean

No new tests: this is a swap to an existing helper with no behavior change, and the resume paths are already covered by ai-vault-session-resume.test.ts.

Resolving a session's resume target scanned every worktree in every repo:
two `Object.values(worktreesByRepo).flat().find(...)` calls, which also
allocate a fresh 1124-element array each time, plus an equivalent `some()`
walk. All three run per visible session row, so a panel render repeated
them ~20 times.

`getIndexedWorktreeMap` already exists for this and is WeakMap-cached on
`worktreesByRepo`, so the index is built once per store snapshot rather
than per call. `connection-owner-resolution.ts` already resolves worktrees
this way.

~1.6ms -> ~0.002ms per render pass at 1124 worktrees. Net -4 lines.

Behavior is unchanged: the map dedupes by id, which only diverges from
`find()` when one id appears twice with different objects. Worktree ids are
`repoId::path`, so a duplicate id within a repo array — the documented race
the index was built for — refers to the same worktree.
@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b28996ed-fcd3-440a-8519-a966f42e7e89

📥 Commits

Reviewing files that changed from the base of the PR and between 6cc579a and 9e1dedd.

📒 Files selected for processing (2)
  • src/renderer/src/components/right-sidebar/ai-vault-session-resume.ts
  • src/renderer/src/lib/ai-vault-resume-target.ts

📝 Walkthrough

Walkthrough

AI Vault workspace resume logic now imports and uses getIndexedWorktreeMap. Known-target validation checks worktree existence through the indexed map, while execution-host and target-status resolution retrieve worktrees directly by ID instead of scanning repository worktree collections. No exported APIs or function signatures changed.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it does not follow the required template sections like Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes. Reformat the description to match the template and add the missing sections, including screenshots or 'No visual change' and the required testing, review, security, and notes details.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: using the shared worktree index to look up vault resume worktrees.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Jul 29, 2026

Copy link
Copy Markdown

Greptile Summary

This PR replaces three manual worktree lookups (Object.values(...).flat().find() / .some()) in the vault resume path with calls to getIndexedWorktreeMap, a WeakMap-cached helper that builds the worktree-by-id Map once per store snapshot. The change is a pure performance optimisation with no intended behaviour change.

  • ai-vault-resume-target.ts: Two .flat().find() lookups replaced with a single indexed .get().
  • ai-vault-session-resume.ts: The nested .some().some() existence check replaced with a .has() call on the same cached map.

Confidence Score: 5/5

Safe to merge — the swap to the cached index is a straight drop-in with no logic change on any code path.

Both changed files replace linear worktree scans with calls to an already-tested, WeakMap-cached helper. The one semantic difference (Map takes the last writer for a duplicate id vs find taking the first) is correctly ruled out by the structure of worktree ids. The ?? {} fallback retained in ai-vault-resume-target.ts matches the original code. TypeScript and lint checks are clean.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/renderer/src/lib/ai-vault-resume-target.ts Two .flat().find() worktree lookups replaced with getIndexedWorktreeMap(...).get(); nullish fallback ?? {} preserved from original code; no logic change.
src/renderer/src/components/right-sidebar/ai-vault-session-resume.ts Nested .some() existence check replaced with getIndexedWorktreeMap(state.worktreesByRepo).has(worktreeId); no fallback needed as worktreesByRepo is non-nullable in AiVaultSessionResumeTargetState.

Sequence Diagram

sequenceDiagram
    participant Panel as Vault Panel
    participant Resume as ai-vault-session-resume
    participant Target as ai-vault-resume-target
    participant Index as worktree-repo-index
    participant Cache as WeakMap cache

    Note over Panel,Cache: Before
    Panel->>Resume: isKnownAiVaultResumeWorkspaceTarget
    Resume->>Resume: Object.values().some().some() O(n)
    Panel->>Target: getAiVaultResumeWorkspaceExecutionHostId
    Target->>Target: Object.values().flat().find() O(n)

    Note over Panel,Cache: After
    Panel->>Resume: isKnownAiVaultResumeWorkspaceTarget
    Resume->>Index: getIndexedWorktreeMap(worktreesByRepo)
    Index->>Cache: WeakMap.get()
    Cache-->>Index: cached Map
    Resume->>Resume: Map.has() O(1)
    Panel->>Target: getAiVaultResumeWorkspaceExecutionHostId
    Target->>Index: getIndexedWorktreeMap(worktreesByRepo)
    Index->>Cache: WeakMap.get() cache hit
    Cache-->>Index: cached Map
    Target->>Target: Map.get() O(1)
Loading

Reviews (1): Last reviewed commit: "perf(vault): look up resume worktrees th..." | Re-trigger Greptile

@nwparker
nwparker merged commit b4b3bcd into main Jul 29, 2026
26 checks passed
@nwparker
nwparker deleted the perf/ai-vault-resume-worktree-index branch July 29, 2026 07:21
nwparker added a commit that referenced this pull request Jul 29, 2026
* test(vault): guard the workspace-switch regression #11303 fixed (#11311)

#11303 removed the O(sessions x roots) path normalization from the session
worktree map, but nothing fails if that shape comes back. Adds the two
checks that were missing, plus the tool that would have caught it.

- timing guard: 1200 worktrees x 400 sessions must build in <150ms.
  Verified fail-first — restoring the pre-#11303 per-session
  buildWorktreeCandidates call takes it to 238ms; it is ~15ms as merged.
- path boundary: '/repo/alpha-sibling' must not be attributed to
  '/repo/alpha'. Hoisting the root normalization out of the loop must not
  degrade containment into a bare startsWith.

Also adds tools/benchmarks/workspace-switch-paint-latency.mjs, which
attaches over CDP and measures first-paint-after-click and max frame gap.
The existing worktree-switch-responsiveness.spec.ts only times the
synchronous click task, which stays ~1ms because the highlight is a direct
DOM mutation — that is why a ~1s stall could ship without tripping a
budget. On the affected build it read maxFrameGap p50=973ms.

(cherry picked from commit c5102e1)

* perf(vault): dedupe scope paths by key instead of rescanning (#11314)

* perf(vault): dedupe scope paths by key instead of rescanning

#11303 took the session maps off the workspace-switch path, but scope path
derivation still follows the active worktree and stayed quadratic.

addAiVaultWorkspaceScopePath deduped by re-normalizing every already
accepted path on each insert, so accepting K paths cost O(K^2)
normalize('NFC') calls — ~632k at 1124 workspaces. isAiVaultWorkspaceScopePathClaimed
separately rescanned every live worktree per prior id, and runs twice per
switch via activeWorktreePaths and scopePaths.

- carry a Set of comparison keys alongside the paths, so each insert is one
  normalize plus one Set lookup
- thread that accumulator from the workspace pass into the project pass
  rather than restarting deduplication against a plain array
- build one comparison-path -> worktree id map for the claim check, keeping
  first-writer-wins to match the previous some() short-circuit

deriveAiVaultScopeSessionPaths on a real 1124-workspace profile:
189.7ms -> 0.8ms. Output is unchanged, including ordering: verified against
the previous implementation across 117 scenario/option combinations
covering monorepo and mixed-repo layouts, priors both claimed and
unclaimed, duplicate paths, NFD/NFC, WSL UNC, trailing and doubled
separators, relative and blank paths, and four project-key shapes.

Adds the first test file for this module: scope semantics (priors, claimed
priors, cross-repo rejection, dedupe, NFD/NFC) plus a timing guard.
Verified fail-first — the guard reports 220ms on the previous
implementation. Path length is chosen deliberately, since normalize() cost
scales with it and short synthetic paths understate the old shape.

* fix(vault): make the claim check independent of worktree ordering

Review catch on the first pass: keying claims by comparison path meant a
duplicate path had to pick one owner, and picking the active worktree
masked a real claimant later in the list. Concretely, with the active
worktree also listed at its own prior path, the prior was reported
unclaimed where the previous some() reported it claimed.

Excludes the active worktree while building the set instead of comparing
ids at read time, so any surviving entry is a claim by construction and
ordering cannot decide the result.

Adds a test over four orderings, verified fail-first against the previous
commit. Also adds a timing guard for deriveAiVaultWorkspaceScopePaths,
which the session-scope guard did not cover.

Equivalence rerun against the pre-optimization implementation: 156
scenario/option combinations, identical paths and ordering.

(cherry picked from commit 6cc579a)

* perf(vault): look up resume worktrees through the shared index (#11317)

Resolving a session's resume target scanned every worktree in every repo:
two `Object.values(worktreesByRepo).flat().find(...)` calls, which also
allocate a fresh 1124-element array each time, plus an equivalent `some()`
walk. All three run per visible session row, so a panel render repeated
them ~20 times.

`getIndexedWorktreeMap` already exists for this and is WeakMap-cached on
`worktreesByRepo`, so the index is built once per store snapshot rather
than per call. `connection-owner-resolution.ts` already resolves worktrees
this way.

~1.6ms -> ~0.002ms per render pass at 1124 worktrees. Net -4 lines.

Behavior is unchanged: the map dedupes by id, which only diverges from
`find()` when one id appears twice with different objects. Worktree ids are
`repoId::path`, so a duplicate id within a repo array — the documented race
the index was built for — refers to the same worktree.

(cherry picked from commit b4b3bcd)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…yai#11317)

Resolving a session's resume target scanned every worktree in every repo:
two `Object.values(worktreesByRepo).flat().find(...)` calls, which also
allocate a fresh 1124-element array each time, plus an equivalent `some()`
walk. All three run per visible session row, so a panel render repeated
them ~20 times.

`getIndexedWorktreeMap` already exists for this and is WeakMap-cached on
`worktreesByRepo`, so the index is built once per store snapshot rather
than per call. `connection-owner-resolution.ts` already resolves worktrees
this way.

~1.6ms -> ~0.002ms per render pass at 1124 worktrees. Net -4 lines.

Behavior is unchanged: the map dedupes by id, which only diverges from
`find()` when one id appears twice with different objects. Worktree ids are
`repoId::path`, so a duplicate id within a repo array — the documented race
the index was built for — refers to the same worktree.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant