Skip to content

perf(ai-vault): scope-aware Session History reads + conditional local refresh - #37372

Closed
jamesjfoong wants to merge 2 commits into
stablyai:mainfrom
jamesjfoong:perf/ai-vault-scoped-session-scan
Closed

jamesjfoong wants to merge 2 commits into
stablyai:mainfrom
jamesjfoong:perf/ai-vault-scoped-session-scan

Conversation

@jamesjfoong

@jamesjfoong jamesjfoong commented Nov 2, 2026 •

Copy link
Copy Markdown

ELI5

Your machine may hold thousands of old agent transcripts (Claude, Codex, Cursor, Droid, Grok...), but Session History in Workspace scope shows only the sessions that belong to your current workspace. Before this change, every cold open walked and read every transcript file on the machine to find the few that belong — "Scanned 2,327 files" to show "2 of 250 sessions", taking about 3.5 seconds and sending ~500KB to the window on each refresh. This change makes the walk deterministic and lets it stop once a workspace's in-scope budget is satisfied, and makes an unchanged refresh answer "nothing changed" instead of shipping the full list again. The reported 2-of-250 cold scan is not yet solved: first-seen transcripts still require a head read to learn their cwd.

What Changed

  • src/main/ai-vault/session-scanner-scope-walk.ts: the non-bucket scope walk (codex, omp, droid, cursor, grok, rovo, cline, kiro, opencode legacy, etc.) now enumerates its candidates newest-mtime first instead of discovery traversal order, so the existing canStopParsingSessions cutoff stops head-reads (and per-file cwd resolution) once the in-scope budget is satisfied. Traversal order never satisfied the cutoff's newest-first premise.
  • src/main/ai-vault/cached-session-list.ts: local scans now answer content-conditional refreshes the way runtime hosts already do: a cached serve and a fresh scan compare the caller's afterFingerprint and reply unchanged: true with no session body when content matches.
  • ai-vault-session-list-request.ts (renderer): afterFingerprint is now sent for every execution-host scope (previously only runtime hosts), reusing the existing conditional-refresh plumbing and result-cache snapshot unchanged.
  • New regression suite session-scanner-scoped-cutoff.test.ts: scoped membership across the recency cap, warm-scan cwd-read reuse, and the scoped merge shape.

Why

The scoped walk exists to recover in-scope sessions older than the global recency cap, but nothing told it the walk could stop: candidates arrived in directory traversal order while the stop rule compares mtimes. Sorting newest-first makes the same stop rule effective and keeps admission correct — a candidate only stops being read when enough newer in-scope sessions already satisfy the budget, so out-of-scope coverage and All scope behavior are untouched. The fingerprint reuse closes the local half of the refresh cost: the 60-second cache already served repeat reads, but each post-TTL refresh still shipped the entire session list (~500KB for 250 sessions with previews) whether or not anything changed. Runtime hosts already had this optimization; local machines did not.

Linked Issue

Addresses #37215 (partial: refresh payload + ordering; first-seen cold reads remain open)

Visual Proof

N/A — no UI or interaction change: the panel, scope switcher and progress strip behave identically; only elapsed time and IPC payload change.

Testing

  • New: session-scanner-scoped-cutoff.test.ts — 3 tests (scoped membership, warm-scan cache reuse of cwd reads, conditional local refresh hash stability)
  • Focused: ai-vault/ main suites 163 files/1378 pass; renderer conditional-refresh suites 41 pass; cached-session-list + IPC routing 46 pass
  • Full local validation: pnpm lint (38/38), pnpm tc:node, pnpm tc:web clean (one pre-existing unrelated scaling-test module error present on origin/main too)
  • Platforms: scanner is a forked child process with per-platform root resolution unchanged; only ordering and reply-shape changed. No path logic touched.

AI Disclosure

Implemented with GLM 5.3-flash coding agent under omp/OpenCode: pipeline scoping, walk ordering, conditional local replies, tests, and this PR text. All checks executed locally.

Review

  • Self-review: correct (cutoff premise now holds; admission unchanged), security (no new reads outside transcript roots; fingerprint is sha256 of the result body, no secrets), performance (one sort over scoped candidates; hash over result JSON per conditional refresh), cross-platform (mtime semantics already platform-normalized in scanner; no new platform branches), SSH/remote (runtime legs unchanged; All merge path untouched), mobile (same runtime RPC benefits since the local cache now answers conditionals for any caller).

Agent skill upstream boundary

  • Not applicable — no upstream skill-installer source copied or translated.

Notes

  • Workspace scope still needs one head-read per previously-unseen transcript; the win is bounded reads (stop at budget) + skip on warm scans + no full body on unchanged refreshes. Bucket agents (claude/pi/codebuddy) were already directory-prefix filtered and are untouched.
  • The afterFingerprint local support reuses the runtime contract and its existing tests (ai-vault-host-leg-cache-retention.test.ts, runtime scanner tests); new local coverage added where the cached local serve and fresh scans meet the caller fingerprint.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, before/after, mechanism, alternatives)
  • Visual proof: N/A with reason (no UI/interaction change)
  • Self-reviewed for correctness, security, performance
  • Cross-platform, SSH/remote, path/shortcut impact considered (N/A for paths/shortcuts)
  • pnpm lint, pnpm typecheck (tc:node + tc:web), and targeted pnpm test pass locally; full suite + build to CI

Copilot AI balanced review requested due to automatic review settings November 2, 2026 06:30

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Walkthrough

Scoped scans prioritize Antigravity transcripts, exclude Codex hardlink aliases, and sort candidates by file time. Finite-limit refreshes set an afterFingerprint for all execution hosts. Cache hits and fresh scans use conditional results when a fingerprint is supplied. Fingerprints exclude scan metadata. Tests cover scoped scans, repeated scans, fingerprint stability, and conditional refresh requests.

Merge Risk: Low · up to 3cf1d

Overlapping local refreshes can return the wrong conditional result, causing unnecessary payload transfers or stale UI state. The issue is localized but should be corrected before relying on the refresh optimization.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title "perf(ai-vault): scope-aware Session History reads + conditional local refresh" matches the two main changes: scoped candidate walking that enables the cutoff, and conditional (fingerprint-b…
Description check Passed The description follows the repository template closely. It has ELI5, What Changed, Why, Linked Issue (partial link to #37215, not a fully closed issue), Visual Proof marked N/A with a reason, Testing…
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.
Full details: Title check

Explanation

The title "perf(ai-vault): scope-aware Session History reads + conditional local refresh" matches the two main changes: scoped candidate walking that enables the cutoff, and conditional (fingerprint-based) local refresh replies. It is specific and follows conventional commit style. It omits the newest-first ordering detail, which is expected for a title.

Full details: Description check

Explanation

The description follows the repository template closely. It has ELI5, What Changed, Why, Linked Issue (partial link to #37215, not a fully closed issue), Visual Proof marked N/A with a reason, Testing with a checklist, Risk, AI Disclosure, Review, Agent skill boundary, Notes, and Checklist. The Risk section lacks an explicit risk level (the template asks for Low, Medium, or High) and does not describe how to back out the change. The Linked Issue uses 'Addresses #37215' rather than the template's 'Fixes #'. Testing lacks a manual-testing confirmation: the first checkbox is unchecked. Its Risk section is also missing the rollback plan.

Resolution

Optional improvements: state the risk level (Low, Medium, or High) under Risk, and describe how to back out the change (plain revert or what a revert would not undo). Also confirm whether the manual local test box applies.

Full details: Docstring Coverage

Explanation

Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 4 functions across 8 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Tip

🎯 Customize your risk assessments

Guide how CodeRabbit assesses merge risk and security architecture risk. Highlight sensitive changes and explain your security boundaries using Merge Risk Instructions and Security Risk Instructions in your review settings. Security architecture risk assessments require the Advanced plan or above.

✅ Automatic approvals, with your rules

Let CodeRabbit approve pull requests once required threads are resolved, pre-merge checks pass, and your risk limits are met. Enable Automatic approvals in review settings, with overrides for teams or file paths.

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

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.

@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: 2


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6fe29b37-6b9c-4bb9-bb00-16e2f153fcea
Commits

Reviewing files that changed from the base of the PR and between 5846caf and c2d9b68.

Files selected for processing: 5
  • src/main/ai-vault/cached-session-list.ts
  • src/main/ai-vault/session-scanner-scope-walk.ts
  • src/main/ai-vault/session-scanner-scoped-cutoff.test.ts
  • src/renderer/src/components/right-sidebar/ai-vault-session-list-request.ts
  • src/shared/ai-vault-types.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +210 to +212
return args?.afterFingerprint === undefined
? result
: conditionalAiVaultListResult(result, args.afterFingerprint, args.force === true)

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.

Major · Performance & Scalability · Quick win

Exclude scanId from the local content fingerprint.

After the 60-second cache expires, a fresh scan receives a new scanId even when its sessions and issues are identical. conditionalAiVaultListResult hashes that ID, so the previous afterFingerprint cannot match and the fresh-scan path sends the full body again. Hash only stable list content before comparing fingerprints; add a test that compares two identical scans with different scanId values. (raw.githubusercontent.com)

@jamesjfoong

Copy link
Copy Markdown
Author

Correction to the PR description (scoped to what this change demonstrably does):

  1. Newest-first scope walk — this only pays off when a workspace has ≥ limit in-scope sessions (e.g. many worktree sessions, unlimited scans). For the case in the issue (2 in-scope of a 250 budget), the walk still resolves each previously-unseen transcript's cwd with a bounded head read — that cold cost is unchanged by this PR. Sorting does make the walk deterministic and lets an already-satisfied budget stop reading stale files.
  2. Conditional local refresh — the demonstrable payload win: when a local scan's content is unchanged, the reply is unchanged: true with no session body, instead of ~500KB per refresh. This matches what runtime hosts already did (runtime-session-scanner.ts, session-list-fingerprint.ts); local legs now answer the same way (SQLite-backed scope_cwds + parse-cache rows persist across app restarts via the scanner service, so warm scans after the first-seen/changed files are substantially cheaper).

What remains open from the issue's acceptance list: the first-seen head-read cost for walk-able agents (codex, omp, droid, cursor, grok, rovo, cline, kiro, opencode legacy) on a machine with many transcripts — no correctness-safe shortcut exists while cwd lives inside the file unless a persisted full-coverage cwd index is built first. We'd rather not claim that fixed without a real benchmark from the reported environment (the reported 3.5s could be WSL readdir/stat latency, native-discovery slot contention, or head reads — a main.trace.ndjson snippet with aiVault.scan span attributes candidates/bytesRead/fullParses at a cold open would tell which).

Happy to iterate on a persisted cwd prober if maintainers want that direction, or narrow this PR to the two safe wins.

…refresh

Session History in Workspace scope walked every walk-able agent transcript
(codex, omp, droid, cursor, grok, rovo, cline, kiro, opencode legacy) in
traversal order and head-read each for its cwd before the parser's cutoff
rule could stop it, so a cold open read every transcript on the machine to
show the few in-scope sessions (stablyai#37215).

- Order the scope walk newest-mtime first so the shared
  canStopParsingSessions cutoff stops head-reads once the in-scope budget
  is satisfied; traversal order never could.
- Local scans now answer content-conditional refreshes like runtime hosts:
  the cached-session list and fresh scans compare the requested
  afterFingerprint and reply unchanged with no session body, so a refresh
  of an unchanged machine no longer ships the full list again.

The 60-second local cache and renderer result cache behavior is unchanged;
All scope keeps the same recency-capped result it shows today.

Regression: session-scanner-scoped-cutoff.test.ts covers scoped membership,
warm-scan head-read reuse, and the deterministic merge shape.

Fixes stablyai#37215
@jamesjfoong
jamesjfoong force-pushed the perf/ai-vault-scoped-session-scan branch from fd56d3f to 3cf1d3b Compare November 3, 2026 12:19

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Minor · Apply afterFingerprint per waiter, not per shared scan. · cached-session-list.ts:210-212

src/main/ai-vault/cached-session-list.ts:210-212
Minor · Functional Correctness · Quick win

Apply afterFingerprint per waiter, not per shared scan.

This conditional result is created inside the coordinator's shared start callback. The coordinator returns that same result to every waiter, while local coalescing keys omit afterFingerprint. If two local refreshes overlap with different markers, the first caller's marker controls both replies. A caller can receive unchanged: true without owning the previous body, or receive the full body despite a matching marker. The renderer repairs the first case with a second full request, which defeats the refresh optimization. Apply conditionalAiVaultListResult per caller after coalescing, or preserve the marker in the coalescing contract. (raw.githubusercontent.com)

Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: dd3d433a-e2c8-4480-b622-65d3d171ea3b
Commits

Reviewing files that changed from the base of the PR and between fd56d3f and 3cf1d3b.

Files selected for processing: 2
  • src/main/ai-vault/cached-session-list.ts
  • src/main/ai-vault/session-scanner-scope-walk.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@OrcaWin

OrcaWin commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator

Closing. (1) The headline change is redundant on main: walkCandidates already returns prioritizeAntigravityTranscriptCandidates, which sorts every candidate newest-first by file time (session-scanner-scope-walk.ts and antigravity-transcript-candidates.ts), so the parse already sees recency order. (2) The remaining conditional-refresh change overlaps #39306, which is the scope-first fix that also touches cached-session-list.ts, and it is on a stale base with conflicts against several main moves. (3) No measurement is attached, and the new tests assert read counts and do not exercise the conditional path, which the repo's test policy does not allow. The fingerprint saving can be reconsidered as a small, rebased follow-up on top of #39306.

@OrcaWin OrcaWin closed this Nov 8, 2026
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.

3 participants