Skip to content

Cap installed skill discovery cache - #7670

Merged
brennanb2025 merged 12 commits into
stablyai:mainfrom
nwparker:nwparker/mem-leak-installed-skills-cache
Jul 29, 2026
Merged

brennanb2025 merged 12 commits into
stablyai:mainfrom
nwparker:nwparker/mem-leak-installed-skills-cache

Conversation

@nwparker

@nwparker nwparker commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Description

Bounds the renderer cache used to remember installed agent-skill discovery results across project and runtime targets.

  • Keeps the 256 most recently used resolved targets.
  • Expires resolved results after five minutes with one shared one-shot cleanup timer.
  • Scopes cache keys by local, WSL, project, and remote runtime identity.
  • Invalidates resolved and pending ownership after install/uninstall notifications so an older scan cannot repopulate stale state.
  • Preserves the existing same-target in-flight deduplication and forced-refresh ordering.

Discovery ownership and cache policy now live in focused modules, keeping useInstalledAgentSkills.ts below the enforced 300-line limit without a lint suppression.

Evidence

Reproduction on current main:

  • Drove discovery across 257 distinct project/runtime targets in one renderer lifetime.
  • The module cache retained all 257 results; an assertion requiring at most 256 failed with expected 257 to be less than or equal to 256.

Proof of fix:

  • A deterministic 10,000-target churn test stabilizes at exactly 256 retained results and one cleanup timer.
  • LRU coverage proves a reused target survives the first overflow while the untouched oldest target is evicted.
  • Expiry coverage proves the cache reaches zero retained results and zero timers after five minutes.
  • Race coverage proves a pre-install scan cannot repopulate invalidated cache state and a post-install scan starts immediately.
  • Runtime coverage proves local/WSL/project keys do not cross remote hosts and verifies the active environment is threaded through project, CLI, Linear prompt, and Linear settings CTA entry points.
  • The original oversized hook was split into concrete cache and discovery modules; no max-lines suppression was added.

Validation:

  • pnpm typecheck:web: passed with a fresh locked dependency install.
  • 11 focused test files / 80 tests passed.
  • Changed-file oxlint: passed.
  • pnpm check:max-lines-ratchet: passed.
  • git diff --check origin/main...HEAD: passed.
  • Dedicated performance/memory audit: no issues found.
  • Final review loop: the first round found one omitted remote identity in the Linear settings CTA; it was fixed with regression coverage. Both fresh final reviewers then reported no issues on the amended semantic patch.
  • Final rebase preserved stable patch ID 94467d12dd8be0d5150c61effff847c0975dcb15 exactly.

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.

@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This 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. useInstalledAgentSkills.ts is refactored to use this module's peek, read, write, clear, and test-reset functions instead of a local map, exposing cacheMax in test internals. A new test verifies cache eviction behavior when the size limit is exceeded.

Changes

Area Changes
New cache module Adds installed-agent-skill-discovery-cache.ts with peek, read, write, clear, and test-reset functions plus a max-size constant
Hook refactor useInstalledAgentSkills.ts replaces local cache map with new cache module calls; extends test internals with cacheMax
Tests Adds projectHostTarget helper and eviction test in useInstalledAgentSkills.test.ts

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()
Loading

Related issues: None specified.

Related PRs: None specified.

Suggested labels: renderer, refactor, tests

Suggested reviewers: None specified.

🥕 A rabbit hops through cache and key,
Evicting old ones, letting new ones be,
Two-fifty-six the limit set just right,
Peek and read and write through day and night,
The oldest skill now bows and skips away.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it misses required template sections like Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes. Reformat the PR description to the repository template and add the missing sections, including screenshots/no visual change, testing checklist, AI review, security audit, and notes.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title is concise and accurately reflects the main change: bounding the installed skill discovery cache.

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.

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 win

Unconditional read bumps recency even when the result is discarded on a forced refresh.

readInstalledAgentSkillDiscoveryCache(key) is called before checking force, so it always deletes+reinserts the entry (bumping LRU recency) even when force is true and 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 calling writeInstalledAgentSkillDiscoveryCache afterward — 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 readInstalledAgentSkillDiscoveryCache is only used in the !force branch, 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.ts
  • src/renderer/src/hooks/useInstalledAgentSkills.test.ts
  • src/renderer/src/hooks/useInstalledAgentSkills.ts

@nwparker
nwparker force-pushed the nwparker/mem-leak-installed-skills-cache branch from e942730 to 71bb29e Compare July 11, 2026 06:04
@nwparker
nwparker force-pushed the nwparker/mem-leak-installed-skills-cache branch from 71bb29e to b57382b Compare July 11, 2026 06:06
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.
@brennanb2025

Copy link
Copy Markdown
Contributor

Thanks Neil — reviewed this end to end and pushed review fixes on top of your commit. Your commit is untouched; I merged latest main in rather than rebasing, so the branch is now mergeable again.

A bug your version shipped, which is the most valuable thing here. refresh listed the discoveryTarget object in its useCallback deps, and callers build that object inside a store-backed useMemo — so any unrelated store write handed the hook a new identity and re-fired the discovery effect. On a cache hit that is only extra renders. On a rejecting scan nothing gets cached, so it becomes one discovery IPC per store write, indefinitely — exactly the remote-runtime-unreachable / SSH case. Measured 6 scans where 1 was correct. It now keys on discoveryTargetKey with a ref latch (deliberately not a useMemo — React may discard one, which silently restores the regression). Worth knowing: this dep exists on main too, so this also repairs a pre-existing bug rather than only one this PR introduced.

Removed the 5-minute TTL. The 256-entry LRU already bounds retention, and freshness is already covered by the window-focus refresh(true) (which bypasses the cache outright) plus notifyInstalledAgentSkillsChanged. So the TTL bought no freshness and cost a self-rescheduling renderer timer plus a re-scan and loading flash on surfaces that render instantly today.

Removed the executionHostId cache scoping — this is a scoping call, not a rejection of the idea. It is a genuinely good observation and it should land; it just does not belong in a PR about bounding a cache. Three reasons:

  • It is inert on desktop. src/main/ipc/skills.ts always scans the local machine and never reads activeRuntimeEnvironmentId, so on the Electron app the partition changes no answer — it only drops skill surfaces back to loading on an environment switch and re-issues an identical local scan.
  • Only the web client routes skills.discover to the paired runtime, and host-aware discovery is already being handled by fix(skills): read installed skills from the connected remote runtime #6887, which is landing ahead of this.
  • The field reused the executionHostId name on a shared type for a raw environment id, whereas ExecutionHostId elsewhere is runtime:<encoded> or local, and it hand-rolled normalization that getSettingsFocusedExecutionHostId (src/shared/execution-host.ts) already does.

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 ${projectId}:... (src/shared/project-execution-runtime.ts), and projectId resolves to a stable project/repo id. Measured in the running app on a 52-skill machine: ~47 KB per entry, so ~240 KB across 5 repos, with the 256 cap ceiling at ~11.8 MB. That makes this bounded-retention insurance rather than a leak fix — still worth having, since an unbounded map with no policy only ever grows, but the description should say so. Also worth stating plainly: pendingDiscoveryByTarget and pendingDiscoverySatisfiesForcedRefreshByTarget remain unbounded. They self-drain in .finally (including on rejection) so they are not a leak, but a change that frames itself as bounding module state should be explicit about what it does not bound.

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 — useInstalledAgentSkills.ts sits at ~293 of 300 effective lines and is not in the max-lines baseline, so no suppression was added.

Validated: pnpm typecheck, pnpm lint (incl. max-lines ratchet), oxfmt --check, and the affected suites all clean; the only failures are 18 pre-existing ones in LinearAgentSkillSetupPrompt.reminder-toast.test.tsx, mobile-sidebar-onboarding-badge.test.ts and SidebarToolbar.test.tsx that fail identically on the merge base. Verified in a dev build: skill badges render correct differentiated state and hydrate warm on the first committed frame across 8 pane remounts, with no loading flash.

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.

Comment on lines +1 to +54
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()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 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-apps

greptile-apps Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR bounds the renderer-side skill-discovery cache to the 256 most-recently-used targets, replacing an unbounded Map that grew without limit across long sessions. It also adds a generation counter that blocks stale in-flight scans from writing to the cache after an install/uninstall invalidation, and a latched-target pattern in the hook that keeps the discovery target reference stable when callers rebuild an equivalent object on unrelated store writes.

  • installed-agent-skill-discovery-cache.ts (new): LRU-256 cache backed by Map insertion order; separates peek (no LRU promotion, safe during speculative render passes) from read (promotes the accessed entry).
  • installed-agent-skill-discovery.ts (modified): delegates persistence to the new cache module, adds discoveryGeneration tracking so a pre-invalidation scan cannot repopulate the cache after an install event, and splits invalidateInstalledAgentSkillDiscovery into its own exported function.
  • useInstalledAgentSkills.ts (modified): introduces latchedDiscoveryTarget via React derived state to keep refresh and its effect stable when the caller provides a new object with the same semantic key.

Confidence Score: 5/5

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

Important Files Changed

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]
Loading

Reviews (3): Last reviewed commit: "Merge origin/main (#6887) into nwparker/..." | Re-trigger Greptile

@brennanb2025

Copy link
Copy Markdown
Contributor

Correcting two things I said above, both of which understated this PR rather than overstated it. The removal of executionHostId still stands, but not for the reason I gave.

1. "It is inert on desktop" — wrong, or about to be. I based that on src/main/ipc/skills.ts never reading the active environment. That is true today and stops being true once #6887 lands, because #6887 does not touch the main-process handler at all — it routes from the renderer through a new runtime/runtime-skills-client.ts that sends skills.discover over callRuntimeRpc. So the main-process grep stays reassuring while the behavior changes underneath it. Desktop will scan the paired remote. Credit to the #6887 review for catching this; I would have shipped that claim uncorrected.

The removal is still right, on the other reason alone: host-awareness belongs to #6887, and #6887 ships it as getRuntimeScopedSkillDiscoveryKey, keying remote scans on runtime:<environmentId>.

Worth recording why your version would not have been the right shape anyway, independent of ownership: it derived the key from raw settings.activeRuntimeEnvironmentId. The skill install terminal resolves through getSingleFocusedRuntimeEnvironmentId, which deliberately declines to guess when several runtimes are saved. Keying the scan off the raw preference means a user with two saved runtimes installs to one host and scans another, leaving the badge stuck on "Not installed". #6887 routes both through the same resolver so scan and install can never name different hosts.

2. "Bounded-retention insurance rather than a leak fix" — true on main, false after #6887. My per-project bound argument rests on every key being ${projectId}:.... Once remote scans key on runtime:<environmentId>, that no longer holds, and the ephemeral-VM path makes the key space genuinely unbounded: src/main/ephemeral-vm-runtime-service.ts derives the environment id from start.context.instanceId, and src/shared/ephemeral-vm-recipe-runner.ts mints orca-${randomUUID()} per start. A fresh cache key per VM start, retained forever. At a realistic ~18.8 KB per entry that is ~1.8 MB held after ~100 ephemeral-VM starts in one renderer session, and it does not stop.

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:

  • The cap has to key off getRuntimeScopedSkillDiscoveryKey, not getSkillDiscoveryTargetKey, or remote scans get bounded under the wrong key. I dry-ran the merge: our two branches both add installed-agent-skill-discovery.ts, so it is an add/add conflict, and my side of it contains zero references to that function. Resolving it the lazy way silently deletes remote scoping. I will pin it with a test.
  • Entries should be dropped when a runtime environment is removed. Right now a removed environment's skill list is retained indefinitely, which is a staleness bug as well as a memory one.

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.
@brennanb2025
brennanb2025 merged commit f56c37b into stablyai:main Jul 29, 2026
25 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
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.

2 participants