Skip to content

perf(vault): stop rebuilding session maps on every worktree switch - #11303

Merged
brennanb2025 merged 1 commit into
mainfrom
brennanb2025/vault-panel-switch-perf
Jul 29, 2026
Merged

brennanb2025 merged 1 commit into
mainfrom
brennanb2025/vault-panel-switch-perf

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Problem

Switching worktrees rebuilds two ~500-session maps in the Agent Session History panel on every switch (profiled and user-confirmed: closing the right sidebar makes switching visibly snappier):

  • sessionProjectById (AiVaultPanel.tsx): memo deps included activeRepo/activeWorktree, which the extracted map never reads.
  • useAiVaultSessionWorktreeMap (ai-vault-session-worktree.ts): activeWorktreeId was in the deps only to bake status: 'current' into cached rows. Inside, buildWorktreeCandidates ran per session (500 sessions × ~530 candidate roots), so isPathInsideOrEqual — including the normalize('NFC') added by fix(agent-history): match non-ASCII workspace paths to Claude sessions #10841 — ran ~255k times per switch.

Fix

  1. Memo deps: buildAiVaultSessionProjectById exposes session→project attribution without the active repo/worktree; the worktree map hook no longer takes activeWorktreeId. status: 'current' is derived per row at read time via withAiVaultCurrentWorktreeStatus(info, activeWorktreeId) — a switch reuses both cached maps untouched.
  2. Hoisting: candidates are built once per map rebuild, each with a precomputed normalized-root matcher (createNormalizedPathInsideOrEqualMatcher); the session cwd is normalized once per session. Data-change rebuilds go from O(sessions × roots) normalizations to O(sessions + roots).

NFC folding semantics from #10841 are untouched — the same normalization runs, just not in the hot loop. In resolveSessionProject the matcher is built from the already-normalized root, preserving the existing double-normalization behavior for WSL UNC roots exactly.

Measurements

Full-scale rig (6 repos / 281 worktrees / 585 worktreeMeta / 499 tabs / 171 injected agent statuses / 500 real sessions), same seeded userdata copy for both arms, dev builds of this branch vs its base main (1df8aa5), same machine, same scripts:

metric (panel on All / “500 shown” verified each iteration) main this PR
warm A/B switch, 8 runs 421–434 ms (med ≈ 425) 122–129 ms (med ≈ 125)
cold switch (never-activated worktree) 491 ms 193 ms
10 random switches 512–589 ms 207–290 ms
control: warm A/B switch, panel closed 166–193 ms 178–198 ms

Panel-open switching now costs no more than panel-closed switching (the ~300 ms delta the panel used to add is gone); the panel-closed control is unchanged between arms.

Correctness

  • Fail-first: on main, a hook-level test asserting the map identity survives an activeWorktreeId-only change fails with expected Map … to be Map … // Object.is equality; the committed test (ai-vault-session-worktree-map.test.tsx) fails on main and passes here, asserting map identity is unchanged across a switch and the rendered current flag moves.
  • status: 'current' equivalence: a test compares render-time stamping against the unchanged public per-session resolver for every case — active worktree, non-active, archived-active, no-worktree-match, SSH-host session, cwd-less session — across four different active worktree ids.
  • Non-ASCII: NFD café cwd matches NFC café worktree path (and CJK), in both the worktree map and project attribution.
  • All existing AiVault/right-sidebar suites pass (159 tests across 14 ai-vault files; the 19 pre-existing right-sidebar failures on this machine also fail on a clean checkout — localStorage/PluginPanel, unrelated).

Not included: use-tab-agent.ts per-card recompute (~120 ms at full scale) — separate subsystem, left for its own change.

Switching worktrees rebuilt two ~500-entry maps in the Agent Session
History panel because their memo deps included the active repo/worktree,
which the maps never read; the worktree map also rebuilt ~530 path
candidates (and re-normalized every root) per session, ~255k
isPathInsideOrEqual calls per switch.

- Drop activeRepo/activeWorktree from the sessionProjectById memo via
  buildAiVaultSessionProjectById, and activeWorktreeId from
  useAiVaultSessionWorktreeMap; 'current' is now stamped per row at read
  time (withAiVaultCurrentWorktreeStatus), so switches reuse both maps.
- Hoist candidate building out of the per-session loop and precompute a
  normalized-root matcher per candidate, so map rebuilds on data changes
  are O(sessions + roots) normalizations instead of O(sessions x roots).

NFC folding from #10841 is untouched; non-ASCII (NFD/CJK) matching is
covered by new tests. Warm switch with the panel on All/500 drops
425ms -> 125ms on the full-scale rig (cold 491ms -> 193ms); panel-closed
switches are unchanged.
@greptile-apps

greptile-apps Bot commented Jul 29, 2026

Copy link
Copy Markdown

Greptile Summary

This PR eliminates expensive per-worktree-switch map rebuilds in the Agent Session History panel by separating stable data (session→worktree and session→project maps) from volatile data (which worktree is "current"). On every worktree switch, previously useMemo deps included activeWorktreeId, forcing a full O(sessions × roots) rebuild of two ~500-entry maps; now those maps are cached indefinitely across switches and the status: 'current' flag is stamped per-row at read time via the new withAiVaultCurrentWorktreeStatus helper.

  • ai-vault-session-worktree.ts: useAiVaultSessionWorktreeMap drops activeWorktreeId from its interface; candidates (with precomputed ownsNormalizedCwd closures and normalizedPathLength) are hoisted out of the per-session loop; withAiVaultCurrentWorktreeStatus is exported for render-time stamping.
  • ai-vault-session-projects.ts: buildAiVaultSessionProjectById is extracted from buildAiVaultProjectContext so it can be memoized without reading activeRepo/activeWorktree; makeProjectCandidate precomputes the normalized-root matcher once per candidate.
  • AiVaultPanel.tsx: wires up the new getSessionWorktreeInfo callback that applies the current-status stamp at call time, keeping both maps stable across worktree switches.

Confidence Score: 5/5

Safe to merge — the refactor correctly separates stable map data from per-switch volatile state, preserves all existing NFC/WSL normalization semantics, and the added tests directly assert the key invariants.

The logic cleanly decouples expensive candidate-building and session-matching from the worktree-switch signal. The archived-worktree-as-active edge case, WSL UNC alias matching, and per-row current stamping all work identically to the original code. The intentional double-normalization in makeProjectCandidate is safe because normalizeRuntimePathForComparison is idempotent on its own output for every path form it produces. The test suite covers behavioral equivalence exhaustively.

Files Needing Attention: No files require special attention. The minor redundancy in buildAiVaultProjectContext calling buildSetupByRepoId and buildProjectLabelByKey before delegating to buildAiVaultSessionProjectById, which rebuilds them internally, is not in the performance-sensitive path and does not affect correctness.

Important Files Changed

Filename Overview
src/renderer/src/components/right-sidebar/ai-vault-session-worktree.ts Core refactor: drops activeWorktreeId from hook deps, hoists candidate-building out of the session loop, precomputes normalized matchers and path lengths per candidate, exports withAiVaultCurrentWorktreeStatus for render-time current stamping. Logic is correct; archived-worktree-as-active edge case is handled identically to before.
src/renderer/src/components/right-sidebar/ai-vault-session-projects.ts Extracts buildAiVaultSessionProjectById so the session-to-project map can be memoized independently of active repo/worktree; makeProjectCandidate precomputes the normalized-root matcher. Minor redundancy: buildAiVaultProjectContext builds setupByRepoId and projectLabelByKey before delegating to buildAiVaultSessionProjectById which rebuilds them — not in the hot path.
src/renderer/src/components/right-sidebar/AiVaultPanel.tsx Wires the new stable maps and getSessionWorktreeInfo callback correctly; memo deps are properly trimmed; effectiveActiveWorktreeId is extracted once and shared across callbacks, eliminating duplicate inline expressions.
src/renderer/src/components/right-sidebar/ai-vault-session-worktree-map.test.tsx New test file covering map-identity stability across switches, render-time vs resolver equivalence for all status cases, and NFC/NFD Unicode matching. Thorough coverage of the changed invariants.
src/renderer/src/components/right-sidebar/ai-vault-session-projects.test.ts Adds tests for buildAiVaultSessionProjectById: verifies active-repo/worktree independence and non-ASCII NFC/NFD attribution. Correctly validates the key invariant this optimization relies on.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[worktrees / repos / sessions change] -->|useMemo rebuilds| B[buildWorktreeCandidates precomputes ownsNormalizedCwd closures and normalizedPathLength per root]
    B --> C[useAiVaultSessionWorktreeMap]
    C --> D[sessionWorktreeById Map status: active or archived no current baked in]
    E[activeWorktreeId changes worktree switch] -->|does NOT invalidate map| D
    E --> F[effectiveActiveWorktreeId useCallback dep]
    F --> G[getSessionWorktreeInfo callback]
    D -->|map.get session.id| G
    G --> H[withAiVaultCurrentWorktreeStatus stamps current per-row at read time]
    H --> I[getWorktreeInfo prop getSessionResumeState getSessionResumeActions]
    J[repos / worktrees / sessions / projectHostSetupProjection change] -->|useMemo rebuilds| K[buildAiVaultSessionProjectById precomputes ownsNormalizedCwd per candidate]
    K --> L[sessionProjectById Map no active repo/worktree dep]
    E -->|does NOT invalidate| L
Loading

Reviews (1): Last reviewed commit: "perf(vault): stop rebuilding session map..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

AI Vault now builds session-to-project mappings without active repository or worktree inputs. Worktree matching uses precomputed normalized-path predicates, including WSL path aliases, while active/current status is applied separately per session. The panel shares this status-aware lookup with resume handling and session rendering. Tests cover active-worktree changes, fallback resolution, archived and SSH worktrees, missing CWDs, and Unicode normalization.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed but does not follow the repository's required template sections. Rewrite the PR body to match the template: add Summary, Screenshots, Testing checklist, AI Review Report, Security Audit, and Notes sections.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main performance change in the PR.
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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9871b3a1-9fe0-4c66-8de9-1ff1d665bb0d

📥 Commits

Reviewing files that changed from the base of the PR and between 1df8aa5 and b1c1dec.

📒 Files selected for processing (5)
  • src/renderer/src/components/right-sidebar/AiVaultPanel.tsx
  • src/renderer/src/components/right-sidebar/ai-vault-session-projects.test.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-projects.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-worktree-map.test.tsx
  • src/renderer/src/components/right-sidebar/ai-vault-session-worktree.ts

Comment on lines +225 to +247
function makeWorktreeCandidate(
worktree: Worktree,
path: string,
hostId: ExecutionHostId,
source: WorktreeCandidate['source']
): WorktreeCandidate {
const ownsCwd = createNormalizedPathInsideOrEqualMatcher(path)
// A WSL UNC root also owns sessions recorded under its Linux-native cwd.
const wslPath = parseWslUncPath(path)
const ownsCwdViaWslAlias = wslPath
? createNormalizedPathInsideOrEqualMatcher(wslPath.linuxPath)
: null
return {
worktree,
path,
hostId,
status: worktree.isArchived ? 'archived' : 'active',
source,
ownsNormalizedCwd: (normalizedCwd) =>
ownsCwd(normalizedCwd) || (ownsCwdViaWslAlias?.(normalizedCwd) ?? false),
normalizedPathLength: normalizeRuntimePathForComparison(path).length
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check whether worktree.path / priorWorktreeIds can ever be a bare WSL UNC root
# (no sub-path) and whether any guard already excludes this shape.
rg -n -A5 -B5 'parseWslUncPath' src/renderer/src/components/right-sidebar/ai-vault-session-worktree.ts src/shared/wsl-paths.ts
rg -n 'hasUsablePath|isRuntimePathAbsolute' src/renderer/src/components/right-sidebar/ai-vault-session-worktree.ts

Repository: stablyai/orca

Length of output: 4488


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== file outline =="
ast-grep outline src/renderer/src/components/right-sidebar/ai-vault-session-worktree.ts --view expanded || true

echo "== relevant worktree file sections =="
sed -n '180,265p' src/renderer/src/components/right-sidebar/ai-vault-session-worktree.ts | cat -n

echo "== parser/normalizer references =="
rg -n 'function normalizeRuntimePathForComparison|const normalizeRuntimePathForComparison|createNormalizedPathInsideOrEqualMatcher|normalizeRuntimePathForComparison|isRuntimePathAbsolute|hasUsablePath' src/renderer/src src/shared -g '*.ts' -g '*.tsx' | head -n 200

Repository: stablyai/orca

Length of output: 20249


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== cross-platform-path implementation and WSL tests =="
sed -n '1,150p' src/shared/cross-platform-path.ts | cat -n
echo "== cross-platform-path WSL related tests =="
rg -n -A8 -B8 'wsl|WSL|\\\\wsl|wsl.localhost|normalizeRuntimePathForComparison\\(' src/shared/cross-platform-path.test.ts | head -n 240

echo "== parseWslUncPath implementation =="
sed -n '1,25p' src/shared/wsl-paths.ts | cat -n

echo "== static behavioral probes =="
python3 - <<'PY'
import re

def parse_wsl_unc_path(path):
    normalized = path.replace('\\', '/')
    match = re.match(r'^//(wsl\.localhost|wsl\$)/([^/]+)(/.*)?$', normalized, re.I)
    if not match:
        return None
    return {'distro': match.group(2), 'linuxPath': match.group(3) or '/'}

def is_runtime_path_absolute_windows(path):
    return bool(re.match(r'''(?x)
        ^(
            [a-zA-Z]:
            [|/]|
            (\\\\
                ( (?!\.| ).{1,256}
                  (?! CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9] )
                )? (?![/.])
            | [a-zA-Z]: )
        )
    ''', path))

def is_runtime_path_absolute_posix(path):
    return path.startswith('/')

def is_runtime_path_absolute(path, flavor='windows'):
    if flavor == 'windows':
        return is_runtime_path_absolute_windows(path)
    elif flavor == 'posix':
        return is_runtime_path_absolute_posix(path)
    return is_runtime_path_absolute_posix(path)

def normalize_runtime_path_for_comparison(raw_value, flavor='windows'):
    # Exact implementation copied from cross-platform-path.ts
    if not isinstance(raw_value, str):
        raise TypeError
    value = raw_value.strip()
    if not value:
        return value
    return value if is_runtime_path_absolute(value, flavor) else value

def create_normalized_path_inside_or_equal_matcher(root_path, path_flavor='windows'):
    root = normalize_runtime_path_for_comparison(root_path, path_flavor)
    def owns_normalized_cwd(candidate_path):
        normalized_candidate = normalize_runtime_path_for_comparison(candidate_path, path_flavor)
        return normalized_candidate == root or normalized_candidate.startswith(root + '/')
    return owns_normalized_cwd

root_paths = [
    '//wsl.localhost/Ubuntu',
    '//wsl$Ubuntu',
    '//wsl.localhost/Ubuntu/home/ada/project',
    '//wsl.localhost/Ubuntu/home/ada/project/',
]
cased_candidates = [
    '/home/ada/project',
    '/home/ada/otros',
    '/',
    '/mnt/c/Users/user/project',
    '//wsl.localhost/Ubuntu/home/ada/project',
    '//wsl.localhost/Ubuntu/home/ada/project/',
]
for root in root_paths:
    parsed = parse_wsl_unc_path(root)
    print(f"root={root!r}: parseWslUncPath={parsed}")
    if parsed:
        for flavor in ('windows','posix'):
            match = create_normalized_path_inside_or_equal_matcher(parsed['linuxPath'], flavor)
            print(f"  uses linuxPath={parse_wsl_unc_path(root)['linuxPath']!r}, flavor={flavor}")
            for cand in cased_candidates:
                print(f"    {cand!r} => {match(cand)}")
PY

Repository: stablyai/orca

Length of output: 7652


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== WSL-related tests in cross-platform-path.test.ts =="
rg -n -A8 -B8 'wsl|WSL|\\\\wsl|wsl\.localhost|normalizeRuntimePathForComparison' src/shared/cross-platform-path.test.ts | head -n 260 || true

echo "== parseWslUncPath implementation =="
sed -n '1,25p' src/shared/wsl-paths.ts | cat -n

echo "== static behavioral probes =="
python3 - <<'PY'
import re

def normalize_runtime_path_separators(value):
    normalized = value.replace('\\','/').replace('/+','/') # not running regex replace
    # use regex below via re
    return re.sub(r'/+', '/', re.sub(r'\\\\+', '\\', re.sub(r'/+', '/', re.sub(r'\\\\+', '\\', re.sub(r'\\\\+', '\\', re.sub(r'\\\\+', '\\', re.sub(r'\\\\+', '\\', re.sub(r'\\\\+', '\\', re.sub(r'\+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', re.sub(r'+', '+', \))
PY

Repository: stablyai/orca

Length of output: 17853


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== parseWslUncPath implementation =="
sed -n '1,20p' src/shared/wsl-paths.ts | cat -n

echo "== createNormalizedPathInsideOrEqualMatcher implementation =="
sed -n '81,90p' src/shared/cross-platform-path.ts | cat -n

echo "== simple static behavioral probe for root over-match =="
python3 - <<'PY'
import re

def parse_wsl_unc_path(path):
    normalized = path.replace('\\', '/')
    match = re.match(r'^//(wsl\.localhost|wsl\$)/([^/]+)(/.*)?$', normalized, re.I)
    if not match:
        return None
    return {'distro': match.group(2), 'linuxPath': match.group(3) or '/'}

def is_windows_absolute_path_like(value):
    return re.search(r'^[A-Za-z]:[\\/]', value) or value.startswith('\\\\') or value.startswith('//')

def normalize_runtime_path_separators(value):
    normalized = value.replace('\\', '/')
    sub = re.sub(r'/+', '/', normalized)
    if value.startswith('\\\\') or value.startswith('//'):
        sub = '//' + sub.lstrip('/')
    return sub

def trim_runtime_path_trailing_slash(value):
    return re.sub(r'[\\/]+$', '', value) if value else value

def normalize_runtime_path_for_comparison(raw_value):
    value = raw_value.strip()
    if not value:
        return value
    is_windows_path = is_windows_absolute_path_like(value)
    normalized = trim_runtime_path_trailing_slash(
        normalize_runtime_path_separators(value) if is_windows_path else re.sub(r'/+', '/', value)
    )
    wsl_unc = re.match(r'^//(?:wsl\.localhost|wsl\$)/([^/]+)(/[\s\S]*)?$', normalized, re.I)
    if wsl_unc:
        return f'//wsl/{wsl_unc.group(1).lower()}{wsl_unc.group(2) or ""}'
    return normalized if is_windows_path else normalized

def create_normalized_path_inside_or_equal_matcher(root_path):
    root = normalize_runtime_path_for_comparison(root_path)
    root_with_boundary = root if root == '/' or re.match(r'^[a-z]:/$', root, re.I) else re.sub(r'/+$', '') + '/'
    return lambda normalized_candidate: normalized_candidate == root or normalized_candidate.startswith(root_with_boundary)

for path in ['//wsl.localhost/Ubuntu', '//wsl.localhost/Ubuntu/home/ada/project']:
    info = parse_wsl_unc_path(path)
    print(f'path={path!r} parsed={info}')
    if info:
        match = create_normalized_path_inside_or_equal_matcher(info['linuxPath'])
        for cand in ['/home/ada/project', '/', '/home/ada/otros', '//wsl/ubuntu/home/ada/project/src',
                     '//wsl/ubuntu/home/ada/project/file with spaces/bare-path']:
            print(f'  {cand!r} => {match(cand)}')
PY

Repository: stablyai/orca

Length of output: 1698


Guard bare WSL distro roots before creating an alias matcher.

parseWslUncPath('//wsl.localhost/Ubuntu').linuxPath returns '/', and the current matcher for '/' is not a filesystem-root guard. If a worktree path or priorWorktreeIds value is persisted without a distro sub-path, unrelated WSL/Linux sessions can be matched to that worktree. Use the WSL-normalized root form and only apply this alias when there is an actual sub-path segment.

@brennanb2025
brennanb2025 merged commit 9cf31bd into main Jul 29, 2026
26 checks passed
@brennanb2025
brennanb2025 deleted the brennanb2025/vault-panel-switch-perf branch July 29, 2026 06:08
nwparker added a commit that referenced this pull request Jul 29, 2026
#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.
nwparker added a commit that referenced this pull request Jul 29, 2026
* 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.
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)
zpyoung pushed a commit to zpyoung/orca that referenced this pull request Jul 29, 2026
…tablyai#11303)

Switching worktrees rebuilt two ~500-entry maps in the Agent Session
History panel because their memo deps included the active repo/worktree,
which the maps never read; the worktree map also rebuilt ~530 path
candidates (and re-normalized every root) per session, ~255k
isPathInsideOrEqual calls per switch.

- Drop activeRepo/activeWorktree from the sessionProjectById memo via
  buildAiVaultSessionProjectById, and activeWorktreeId from
  useAiVaultSessionWorktreeMap; 'current' is now stamped per row at read
  time (withAiVaultCurrentWorktreeStatus), so switches reuse both maps.
- Hoist candidate building out of the per-session loop and precompute a
  normalized-root matcher per candidate, so map rebuilds on data changes
  are O(sessions + roots) normalizations instead of O(sessions x roots).

NFC folding from stablyai#10841 is untouched; non-ASCII (NFD/CJK) matching is
covered by new tests. Warm switch with the panel on All/500 drops
425ms -> 125ms on the full-scale rig (cold 491ms -> 193ms); panel-closed
switches are unchanged.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#11303)

Switching worktrees rebuilt two ~500-entry maps in the Agent Session
History panel because their memo deps included the active repo/worktree,
which the maps never read; the worktree map also rebuilt ~530 path
candidates (and re-normalized every root) per session, ~255k
isPathInsideOrEqual calls per switch.

- Drop activeRepo/activeWorktree from the sessionProjectById memo via
  buildAiVaultSessionProjectById, and activeWorktreeId from
  useAiVaultSessionWorktreeMap; 'current' is now stamped per row at read
  time (withAiVaultCurrentWorktreeStatus), so switches reuse both maps.
- Hoist candidate building out of the per-session loop and precompute a
  normalized-root matcher per candidate, so map rebuilds on data changes
  are O(sessions + roots) normalizations instead of O(sessions x roots).

NFC folding from stablyai#10841 is untouched; non-ASCII (NFD/CJK) matching is
covered by new tests. Warm switch with the panel on All/500 drops
425ms -> 125ms on the full-scale rig (cold 491ms -> 193ms); panel-closed
switches are unchanged.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ed (stablyai#11311)

stablyai#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-stablyai#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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…i#11314)

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

stablyai#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.
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