Repository navigation
perf(vault): look up resume worktrees through the shared index - #11317
Conversation
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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
📝 WalkthroughWalkthroughAI Vault workspace resume logic now imports and uses 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
Greptile SummaryThis PR replaces three manual worktree lookups (
Confidence Score: 5/5Safe 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.
|
| 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)
Reviews (1): Last reviewed commit: "perf(vault): look up resume worktrees th..." | Re-trigger Greptile
* 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)
…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.
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:
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 onworktreesByRepo, so the index is built once per store snapshot instead of once per call.connection-owner-resolution.ts:63already 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
Mapcould 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 documentedcreateWorktree/fetchWorktreesrace 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
right-sidebar/andlib/tsc --noEmit -p config/tsconfig.tc.web.jsoncleanoxlintcleanNo 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.