Repository navigation
Cap installed skill discovery cache - #7670
brennanb2025 merged 12 commits into
Conversation
📝 WalkthroughWalkthroughThis PR adds a new in-memory cache module for installed agent skill discovery results, bounded to a maximum of 256 entries with LRU-style eviction. Changes
Sequence Diagram(s)sequenceDiagram
participant Hook as useInstalledAgentSkills
participant Cache as installed-agent-skill-discovery-cache
Hook->>Cache: readInstalledAgentSkillDiscoveryCache(key)
Cache-->>Hook: cached result or null
Hook->>Cache: writeInstalledAgentSkillDiscoveryCache(key, result)
Cache->>Cache: evict oldest entry if over max size
Hook->>Cache: clearInstalledAgentSkillDiscoveryCache()
Related issues: None specified. Related PRs: None specified. Suggested labels: renderer, refactor, tests Suggested reviewers: None specified. 🥕 A rabbit hops through cache and key, 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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 |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/renderer/src/hooks/useInstalledAgentSkills.ts (1)
153-161: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winUnconditional
readbumps recency even when the result is discarded on a forced refresh.
readInstalledAgentSkillDiscoveryCache(key)is called before checkingforce, so it always deletes+reinserts the entry (bumping LRU recency) even whenforceistrueand the cached value is never used. Worse, if an in-flight forced-refresh promise already exists for this key (pendingDiscoverySatisfiesForcedRefreshByTarget.get(key)true), the function returns that promise without ever callingwriteInstalledAgentSkillDiscoveryCacheafterward — so the stale entry's recency was bumped for nothing. This partially undermines the PR's goal: a target that is only ever force-refreshed (never genuinely "used" via a real cache hit) keeps getting treated as most-recently-used, potentially causing a truly active target to be evicted first.Since the return value of
readInstalledAgentSkillDiscoveryCacheis only used in the!forcebranch, gate the read so the side effect only happens when it's meaningful.🛠️ Proposed fix
const key = getSkillDiscoveryTargetKey(target) - const cachedDiscovery = readInstalledAgentSkillDiscoveryCache(key) - if (!force && cachedDiscovery) { - return cachedDiscovery + if (!force) { + const cachedDiscovery = readInstalledAgentSkillDiscoveryCache(key) + if (cachedDiscovery) { + return cachedDiscovery + } }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 67486821-1800-429f-af49-5cbc0c572583
📥 Commits
Reviewing files that changed from the base of the PR and between eed0058 and e942730973a433d78e3f51776209ba425dfe4924.
📒 Files selected for processing (3)
src/renderer/src/hooks/installed-agent-skill-discovery-cache.tssrc/renderer/src/hooks/useInstalledAgentSkills.test.tssrc/renderer/src/hooks/useInstalledAgentSkills.ts
e942730 to
71bb29e
Compare
71bb29e to
b57382b
Compare
The shared change event moved to its own module on main; keep both imports.
The 256-entry LRU already bounds retention, and cache keys are per project
(`${projectId}:...`), so retention was never unbounded churn. The 5-minute TTL
bought no freshness the window-focus forced refresh does not already provide,
and cost a self-rescheduling renderer timer plus a re-scan and loading flash on
surfaces that render instantly from cache today.
`refresh` listed the `discoveryTarget` object in its deps, and callers derive that object inside a store-backed useMemo, so an unrelated store write handed the hook a new identity and re-fired the discovery effect. A failed scan caches nothing, so an unreachable runtime host produced one discovery IPC per store write for as long as it stayed unreachable. Key on the target key, which already determines the scan, and read the object from a ref.
- The generation-guard test settled the stale scan first, so it passed with the guard deleted. Settle the post-install scan first; the stale scan landing last is the only ordering the guard exists for. - The mobile emulator setup hook was the one caller left with no discovery target, so on web it filed the paired runtime's result under the local key and never re-keyed on an environment switch. - Assert the host id is stripped before discovery reaches the main process. - Drop the 'local' sentinel; an environment literally named local shared the unpartitioned key.
- Revert the mobile emulator hook to main. Routing it through the project runtime target was drive-by scope, and a repair-required Windows project makes discovery throw, so the emulator panel would surface a runtime-repair error where it used to show a plain not-installed state. - Replace the render-mutated target ref with a key-scoped useMemo. Only the dep-array change was load-bearing, and a ref written during render is a live data channel a discarded concurrent render can clobber. - Cover the pending-map identity guard, LRU promotion on rewrite, and the runtime-host branch of useActiveProjectSkillRuntime. All three stayed green under mutation before this. - Fix oxfmt drift in CliSection and CliSkillRuntimeSetup tests.
- Replace the key-scoped useMemo with a ref latch. React may discard a useMemo, which would silently restore the rescan-per-store-write regression; the latch is guaranteed and drops the exhaustive-deps suppression. - Only read the cache on an unforced scan. A forced refresh promoted an entry it was about to discard. - Cover the forced-refresh-over-warm-cache contract, the resolved Windows project-runtime branch, and the CliSection host wiring. All three stayed green under mutation before this. - Correct the SkillDiscoveryTargetSchema comment: the schema is wire-bound and deliberately omits executionHostId.
Every gap below survived mutation before this commit. - notifyInstalledAgentSkillsChanged's cache invalidation: assert the cache directly, since a mounted component forces a rescan and hides its absence. - Warm-cache hydration: assert the first render pass, before effects run, or a settled post-effect state passes with the peek removed. - The host id must not reach the main process on the resolved-WSL, resolved-host and repair-required project branches, not just bare targets. - getLinearPromptSkillDiscoveryTarget: cover all three branches. - WSL cache keys must include the distro.
- Settle-time pending cleanup: without it the pending map grows forever and every later forced refresh resolves the first, already-settled scan. - Forced-refresh dedup: an install notification fans out to every mounted skill surface at once, and they must collapse onto one scan rather than serialize. - Also cover warm-cache hydration on a target change, the change event that drives every mounted surface, and the CliSection host-id trim. - Narrow SkillDiscoveryTargetSchema's declared type to match what it parses.
Scoping the discovery cache key by `settings.activeRuntimeEnvironmentId` is a second feature in a PR about bounding a cache. It is also inert on desktop — src/main/ipc/skills.ts always scans the local machine and never reads the active environment, so the partition only forces a redundant rescan per switch. Only the web client routes skills.discover to the paired runtime, and host-aware discovery belongs to stablyai#6887. Reverts the eight production files it threaded through, and with them the `executionHostId` field on the shared SkillDiscoveryTarget, which reused the `ExecutionHostId` name for a raw environment id. Keeps the cache bound, the generation guard and the rescan fix, and keeps the target-shape and cache-key coverage the scoping work motivated.
|
Thanks Neil — reviewed this end to end and pushed review fixes on top of your commit. Your commit is untouched; I merged latest A bug your version shipped, which is the most valuable thing here. Removed the 5-minute TTL. The 256-entry LRU already bounds retention, and freshness is already covered by the window-focus Removed the
I kept the target-shape and cache-key test coverage that work motivated. On the framing. The retention here is bounded by project count, not the unbounded churn the description implies — every key is Other fixes: the generation-guard test resolved the stale scan first, so it passed with the guard deleted (reordered); added coverage for the settle-time pending cleanup and forced-refresh dedup, which both survived mutation; and the file split is confirmed forced rather than a lint dodge — Validated: Final shape is 6 files (3 production) rather than 17. Queued behind #6887 since that one fixes a user-visible correctness bug and both split the same file — whichever lands first forces a rewrite of the other, and re-deriving a cache bound on top of a new discovery module is much cheaper than the reverse. |
| import type { SkillDiscoveryResult } from '../../../shared/skills' | ||
|
|
||
| // Why: project and runtime identity change across a long renderer session, so the | ||
| // keyed results accumulate; keep the most recent targets instead of every target | ||
| // the window has ever resolved. | ||
| export const INSTALLED_AGENT_SKILL_DISCOVERY_CACHE_MAX = 256 | ||
|
|
||
| let cachedDiscoveryByTarget = new Map<string, SkillDiscoveryResult>() | ||
|
|
||
| // Why: render reads must not reorder recency — React can discard a render pass. | ||
| export function peekInstalledAgentSkillDiscoveryCache(key: string): SkillDiscoveryResult | null { | ||
| return cachedDiscoveryByTarget.get(key) ?? null | ||
| } | ||
|
|
||
| export function readInstalledAgentSkillDiscoveryCache(key: string): SkillDiscoveryResult | null { | ||
| const result = cachedDiscoveryByTarget.get(key) | ||
| if (!result) { | ||
| return null | ||
| } | ||
| cachedDiscoveryByTarget.delete(key) | ||
| cachedDiscoveryByTarget.set(key, result) | ||
| return result | ||
| } | ||
|
|
||
| export function writeInstalledAgentSkillDiscoveryCache( | ||
| key: string, | ||
| result: SkillDiscoveryResult | ||
| ): void { | ||
| cachedDiscoveryByTarget.delete(key) | ||
| cachedDiscoveryByTarget.set(key, result) | ||
| while (cachedDiscoveryByTarget.size > INSTALLED_AGENT_SKILL_DISCOVERY_CACHE_MAX) { | ||
| const oldestKey = cachedDiscoveryByTarget.keys().next().value | ||
| if (oldestKey === undefined) { | ||
| break | ||
| } | ||
| cachedDiscoveryByTarget.delete(oldestKey) | ||
| } | ||
| } | ||
|
|
||
| export function clearInstalledAgentSkillDiscoveryCache(): void { | ||
| cachedDiscoveryByTarget.clear() | ||
| } | ||
|
|
||
| export function getInstalledAgentSkillDiscoveryCacheSizeForTests(): number { | ||
| return cachedDiscoveryByTarget.size | ||
| } | ||
|
|
||
| export function hasInstalledAgentSkillDiscoveryCacheEntryForTests(key: string): boolean { | ||
| return cachedDiscoveryByTarget.has(key) | ||
| } | ||
|
|
||
| export function resetInstalledAgentSkillDiscoveryCacheForTests(): void { | ||
| cachedDiscoveryByTarget = new Map() | ||
| } |
There was a problem hiding this comment.
TTL expiry described but not implemented
The PR description states the cache "expires resolved results after five minutes with one shared one-shot cleanup timer" and lists "Expiry coverage proves the cache reaches zero retained results and zero timers after five minutes" as evidence. The actual implementation is a pure LRU-bounded cache with no timer, no scannedAt-based staleness check, and no corresponding expiry test. Results persist until evicted by the 256-entry LRU cap or an explicit invalidateInstalledAgentSkillDiscovery() call (install/uninstall). In a long-running renderer session where the user stays focused and doesn't install/uninstall skills, a scanned result for a target is served indefinitely — the only automatic staleness protection is the focus event forced-refresh in the hook.
Greptile SummaryThis PR bounds the renderer-side skill-discovery cache to the 256 most-recently-used targets, replacing an unbounded
Confidence Score: 5/5Safe to merge — the change introduces a well-bounded LRU cache and generation-guarded invalidation with no correctness regressions identified. The LRU eviction is correct (Map insertion order, delete-then-set promotion, at-most-one eviction per write). The generation counter reliably prevents stale scans from writing to the cache after invalidation. The latched-target pattern in the hook correctly uses React's derived-state escape hatch and does not introduce stale-closure or double-fire risks. Test coverage is thorough across overflow, race conditions, deduplication, per-runtime key scoping, and hook lifecycle scenarios. No data loss, memory leak, or incorrect-state paths were found in the changed code. Files Needing Attention: No files require special attention.
|
| Filename | Overview |
|---|---|
| src/renderer/src/hooks/installed-agent-skill-discovery-cache.ts | New LRU cache module backed by Map insertion-order; correctly evicts the oldest entry on overflow and separates peek (no LRU promotion) from read (promotes); no issues found. |
| src/renderer/src/hooks/installed-agent-skill-discovery.ts | Replaces the unbounded Map with the new LRU cache and adds a generation counter to prevent stale in-flight scans from writing to the cache after invalidation; logic is sound. |
| src/renderer/src/hooks/useInstalledAgentSkills.ts | Adds a latched-target pattern via derived state to stabilize the discovery target reference across store-driven re-renders; uses peek during render to avoid LRU promotion on discarded render passes. |
| src/renderer/src/hooks/installed-agent-skill-discovery-cache.test.ts | Covers LRU overflow at 10 000 entries, rewrite-in-place, LRU promotion on write, peek-does-not-promote, and clear; all behaviorally meaningful. |
| src/renderer/src/hooks/installed-agent-skill-discovery.test.ts | Comprehensive tests for race conditions, deduplication, forced-refresh ordering, runtime key scoping, and cross-environment isolation; no gaps observed. |
| src/renderer/src/hooks/useInstalledAgentSkills.react.test.tsx | Adds integration tests for stable-target identity, warm-cache hydration on first render, and install-notification invalidation; covers the new hook behaviour end-to-end. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[discoverInstalledAgentSkills\nforce, target, runtimeTarget] --> B{force = false?}
B -- Yes --> C[readInstalledAgentSkillDiscoveryCache\nkey — promotes LRU]
C -- hit --> D[Return cached result]
C -- miss --> E{In-flight pending?}
B -- No\nforced refresh --> E
E -- Yes, satisfies force --> F[Return in-flight promise]
E -- Yes, does not satisfy force --> G[await in-flight\nthen check for newer pending]
G -- newer pending exists --> F
G -- no newer pending --> H
E -- No --> H[startInstalledAgentSkillDiscovery\ncapture generation]
H --> I[discoverSkillsForRuntimeTarget IPC]
I -- resolves --> J{generation ===\ndiscoveryGeneration?}
J -- Yes --> K[writeInstalledAgentSkillDiscoveryCache\nevict oldest if size > 256]
J -- No stale scan --> L[Drop — do not write cache]
K --> M[Remove from pendingDiscoveryByTarget\nif still the same promise]
L --> M
N[invalidateInstalledAgentSkillDiscovery\ninstall / uninstall] --> O[discoveryGeneration++]
O --> P[clearInstalledAgentSkillDiscoveryCache]
P --> Q[Clear pendingDiscoveryByTarget\nand satisfiesForcedRefresh map]
R[getCachedSkillDiscovery\nrender path] --> S[peekInstalledAgentSkillDiscoveryCache\nno LRU promotion]
Reviews (3): Last reviewed commit: "Merge origin/main (#6887) into nwparker/..." | Re-trigger Greptile
|
Correcting two things I said above, both of which understated this PR rather than overstated it. The removal of 1. "It is inert on desktop" — wrong, or about to be. I based that on The removal is still right, on the other reason alone: host-awareness belongs to #6887, and #6887 ships it as Worth recording why your version would not have been the right shape anyway, independent of ownership: it derived the key from raw 2. "Bounded-retention insurance rather than a leak fix" — true on So after #6887 this PR is a real leak fix on that path, not just hygiene. That is a better justification than the one in the description, and it is the number I would lead with. Two follow-ups I am carrying into the rebase rather than asking you to do:
Sequencing unchanged: this lands after #6887, so there is never a window where desktop routes remotely without environment-scoped keys. |
…d ref react-doctor's changed-lines gate flagged the ref write as "Ref mutated during render" — React can replay or discard a render, so the write can leak from UI that never commits. A useMemo is not the answer either: React may discard it, which silently restores the rescan-per-store-write regression this latch exists to prevent. Render-phase state is retained and is the documented pattern for adjusting derived state, which the surrounding block already uses.
…ills-cache stablyai#6887 landed the runtime-scoped discovery module this PR also creates, so the add/add collision is resolved in its favour and the cap layers on top. Kept from stablyai#6887, unchanged: - getRuntimeScopedSkillDiscoveryKey, and it stays THE key producer for both the cache read and the pending map. Keying off getSkillDiscoveryTargetKey would bound every remote under the local 'host' key; pinned by two new tests. - discoverSkillsForRuntimeTarget as the scan, so remote runtimes are still scanned over RPC rather than the client's disk. - notifyInstalledAgentSkillsChanged stays in this store-free module. It must never import @/store or the store -> repos slice -> hook -> store cycle returns; it now invalidates the bounded cache instead of clearing a raw Map. Kept from this PR: - the 256-entry LRU, now keyed by the runtime-scoped key. - the discoveryGeneration guard, so a pre-install scan cannot repopulate. - the render-phase state latch. stablyai#6887 landed with the discoveryTarget object still in refresh's deps, so main now carries the rescan-per-store-write bug: an unreachable runtime host issued one discovery IPC per store write. Verified the 6-vs-1 regression test still fails when the latch is defeated on this tree.
…discovery cache (stablyai#7670) Two fixes to installed-skill discovery in the renderer. **Stops one discovery IPC per unrelated store write.** `refresh`'s `useCallback` depended on the `discoveryTarget` *object*, which callers rebuild inside a store-backed `useMemo`. Any unrelated store write handed the hook a fresh identity, recreated `refresh`, and re-fired `useEffect(() => void refresh(false), [refresh])`. On a cache hit that is only extra renders — but on a *rejecting* scan nothing is cached and the pending entry is cleared, so it becomes one discovery IPC per store write, indefinitely. That is the remote-runtime-unreachable and SSH case. Measured 6 scans where 1 was correct. This dep also exists on `main`, so this repairs a pre-existing bug rather than only one introduced here. Fixed with a render-phase `useState` latch keyed on the already-present `discoveryTargetKey` string — deliberately not a `useMemo` (React documents those as discardable, so a discarded one silently restores the regression while the test stays green) and not a ref (react-doctor correctly flags a render-phase ref mutation). **Bounds the discovery cache.** The module-level maps were unbounded, cleared only wholesale by `notifyInstalledAgentSkillsChanged`. Now a 256-entry LRU keyed by `getRuntimeScopedSkillDiscoveryKey`, with a `discoveryGeneration` guard and a read/peek split so only the unforced cache-serving path promotes recency. This matters more after stablyai#6887 than before it. Local keys are bounded by project count (~47 KB/entry, ~240 KB for 5 repos), but once remote scans key on `runtime:<environmentId>`, ephemeral VMs mint `orca-${randomUUID()}` per start (`ephemeral-vm-runtime-service.ts` + `ephemeral-vm-recipe-runner.ts`), so every VM start creates a permanently-retained entry — ~18.8 KB each, ~1.8 MB after ~100 starts, and it does not stop. Scoped down during review: an `executionHostId` change touching 8 production files was removed as a second feature (host-awareness landed in stablyai#6887 instead), taking this from 17 files to 6. New tests pin that the cap keys off the runtime-scoped key, that two environments never share an entry, and that one environment collapses to a single entry across differing client target shapes. Known gap, not addressed here: cache entries are not evicted when a runtime environment is removed, so a removed environment's skill list is retained until LRU pressure or an install notification clears it. That needs a store subscription to `runtimeEnvironments` removals and is filed separately. Co-authored-by: nwparker <[email protected]>
Description
Bounds the renderer cache used to remember installed agent-skill discovery results across project and runtime targets.
Discovery ownership and cache policy now live in focused modules, keeping
useInstalledAgentSkills.tsbelow the enforced 300-line limit without a lint suppression.Evidence
Reproduction on current
main:expected 257 to be less than or equal to 256.Proof of fix:
Validation:
pnpm typecheck:web: passed with a fresh locked dependency install.oxlint: passed.pnpm check:max-lines-ratchet: passed.git diff --check origin/main...HEAD: passed.94467d12dd8be0d5150c61effff847c0975dcb15exactly.ELI5
Orca used to keep every answer it had ever collected about installed skills, even after you switched through many projects or remote machines. It now keeps a recent, short-lived set of answers, throws older ones away, and labels each answer with the machine it came from so results cannot get mixed together.
Trade-offs
No end-user regressions.
If a target has not been scanned for five minutes, or more than 256 distinct targets are used in one renderer lifetime, Orca may perform the normal skill discovery scan again the next time that target is needed. This bounded, user-triggered IPC/disk work replaces unbounded renderer memory retention. The cache uses one shared one-shot timer, adds no polling or background fanout, and normal cache hits still avoid discovery IPC.