Skip to content

fix(memory): release stale session registries - #21734

Merged
OrcaWin merged 45 commits into
mainfrom
OrcaWin/np-oom-09-19
Sep 20, 2026
Merged

OrcaWin merged 45 commits into
mainfrom
OrcaWin/np-oom-09-19

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 42 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​770 $\color{#cf222e}{\Huge{\mathbf{−}}}$​18 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​752
Prod 70 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1150 $\color{#cf222e}{\Huge{\mathbf{−}}}$​216 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​934

What users experienced

Orca kept short-lived bookkeeping forever. Over a long session, SSH targets, runtime environments, repositories, browser pages, WSL routes, terminal panes, shell startup paths, and GitHub lookups could leave old keys and callback state behind. The Star-Nag notification could also retain its React tree after it was closed.

This PR makes those lifetimes finite. It closes the notification cleanly, retires repository and runtime state when their owners go away, releases sidecar queues after work settles, and bounds generation, retry, route, locale, browser, recovery, host-mirror, and shell-startup, and GitLab host-context, SSH connection-generation, and sparse-checkout, WSL home, SSH capability, and Codex trust-cooldown registries. The host-mirror cap is conservative: forgetting an old verdict can only cause one extra bounded wait; it cannot resume a terminal early. The shell-startup cap only causes an occasional file reread after extreme home/host churn, the GitLab cap may re-run one auth-status probe after extreme reconnect churn, and the sparse-checkout cap may re-run one small filesystem probe after extreme worktree churn.

ELI5

The app had several todo lists where finished names were never crossed out. This patch crosses out finished names and keeps only a recent safety window. When a notice is closed, we also throw away its old paperwork.

Merge risk

Low. The changes preserve active entries, recent fencing, and all existing teardown behavior. The new caps affect only very old inactive keys after sustained churn. The shell-startup cache may reread a startup file after its old key is evicted, and GitLab may re-run one host discovery probe after an old connection context is evicted; sparse-checkout may re-run one filesystem probe after an old worktree entry is evicted; permanently removed SSH targets also release their generation entry. Results and normal behavior stay the same. Frequently reused cache entries now move to the newest position on reads, so historical churn evicts inactive entries before hot ones.

Negative user-facing tradeoffs

None expected in normal use. Under extreme host-mirror churn, an evicted verdict may make one pane wait for the existing bounded recovery timeout again; it will not create a duplicate terminal or resume an uncertain session. Under extreme home/host churn, Orca may perform one extra small startup-file read, GitLab auth-status probe, WSL/SSH capability probe, Codex trust attempt, or WSL auth-drain pass, Linear credential reread, Git capability reprobe, or WSL Git environment or preflight reprobe; removed SSH targets no longer retain their old generation metadata.

Safety hardening

Generation fences now use monotonic sequences that remain ahead of every evicted value, so bounded maps cannot reuse an old generation after identifier churn. This includes strict effective-upstream probes that bypass normal in-flight coalescing. Repo-slug resolution also requires the original in-flight promise before committing a result. The Codex app-server host capability cache is bounded as well.

Validation

  • 614 tests passed across 46 changed test files, including the strict effective-upstream eviction regression and browser/WSL and shell-startup regressions.
  • pnpm tc:node, pnpm tc:web, and pnpm tc:cli passed.
  • pnpm run check:code-quality:changed passed.
  • Full oxlint passed with only the repository's two existing mobile warnings.
  • Max-lines ratchet and formatter hooks passed.
  • Audited more than 100 module-level Map/Set state holders; this PR changes only the ones with verified lifetime gaps.

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

Important

The bounded generation maps delete a key on eviction, so a later register/advance can reassign a generation value the key already used earlier in the process. These values are the sole fence against stale responses and a component of cache identities, so reuse can let stale state pass as current.

Reviewed changes

  • Bounded fence/generation maps — ssh-git-dispatch.ts, runtime-environment-transport-generation.ts, runtime-environment-ssh.ts, ssh.ts, runtime-repo-catalog-actions.ts, repo-slug-index.ts now evict the oldest entry past a per-map cap (512–4096).
  • Explicit retirement — local-worktree-scan-generation.ts gains forget/retire; repo-lifecycle-operations.ts retires on repo removal, last-host removal, and orphan pruning.
  • Sidecar queues — sidecar-snapshot-file.ts deletes per-file queue and temp-cleanup entries when they settle instead of retaining them.
  • Enrichment / fork-sync cleanup — repo-git-username-enrichment.ts drops attempted locations for repos no longer live; safe-auto-fork-sync.ts prunes completed attempts and bounds at 512.
  • Star-nag toast — StarNagToastHost.tsx dismisses the infinite toast on unmount (resolving first, so no dismissal telemetry).
  • Workspace cleanup scan — workspace-cleanup-scan-snapshot.ts bounds its persisted-scan-time cache to 512.
  • Tests — new bounds/cleanup assertions across seven test files, plus the repo-removal re-probe and unmount-dismiss cases; each assertion would fail without its corresponding change.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/providers/ssh-git-dispatch.ts Resolved

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

ℹ️ Minor suggestions only.

Reviewed changes (delta since the prior review)

  • Five follow-up commits bounded more registries — WSL route quarantine (512 plus a strike-decay sweep), terminal-history repair dedup set (512), profile dev org rosters (64), shell startup env cache (256), locale formatters (32), browser page insets (512), shell relay recovery generations (512), and PTY controller inventory generations (512).
  • New shared helper — src/main/runtime/prune-oldest-map-entry.ts deletes a single oldest entry; its only caller sets once before pruning, so it stays at the bound.
  • Retirement and cleanup — unchanged in direction from the first commit; the new caps follow the same FIFO eviction pattern already flagged in the prior review (now also on sshRelayRecoveryGenerationByTargetId and ptyControllerInventoryGenerationByProvider).

ℹ️ The "known leak" block is stale after the verdict cap

host-mirror-handle-gap-wait.ts documents a retracted-row verdict as a "KNOWN LEAK, deliberately not drained" whose entry "outlives the session" and keeps the store subscription alive. The new 512-entry cap now evicts the oldest verdict, so that claim is no longer guaranteed. Since that block is explicitly written to be re-read against the code and warns that the prose drifts from the invariants, it should name the cap.

Technical details
# Host-mirror verdict comment block predates the eviction cap

## Affected sites
- `src/renderer/src/lib/host-mirror-handle-gap-wait.ts` — the "KNOWN LEAK, deliberately not drained" paragraph (file lines ~80-96) and the "FOUR drains" enumeration (lines ~53-68) do not mention the new `MAX_EXPIRED_HANDLE_GAP_VERDICTS = 512` eviction in `recordExpiredWait` (lines 204-216).

## Required outcome
- The block reflects that an orphaned verdict is now eventually evicted by churn, so it is bounded rather than session-lifetime, and that the cap is a backstop distinct from the four named drains.

## Open questions for the human
- Is the cap meant as a backstop for the known leak, or only as memory protection that should not be read as closing it? The block's existing warning about prose/pretest drift is why this is worth pinning either way.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

}
const seeded = seedDevRoster()
devRostersByOrg.set(orgId, seeded)
while (devRostersByOrg.size > MAX_DEV_ORG_ROSTERS) {

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.

devRostersByOrg is not a cache — inviteDevOrcaCloudOrgMember/changeDevOrcaCloudOrgMemberRole/removeDevOrcaCloudOrgMember mutate the roster in place and listDevOrcaCloudOrgMembers reads it back, so evicting an org's entry silently discards that org's pending invites and role changes. Bounding a source-of-truth store this way is a different tradeoff from bounding the other memoization maps; either drop this cap or evict only rosters with no mutations.

Technical details
# Bounding a mutable dev-auth store discards state

## Affected sites
- `src/main/orca-profiles/profile-cloud-dev-org-members.ts:62` — `getDevRoster` seeds then evicts the oldest roster past `MAX_DEV_ORG_ROSTERS`.
- `src/main/orca-profiles/profile-cloud-dev-org-members.ts:93`, `:106`, `:121`, `:136` — mutations write into the retained `DevOrgRoster` object.

## Required outcome
- Dev-auth member state must not be silently reset by an unrelated org's activity, or the cap must be documented as intentionally discarding it.

## Open questions for the human (optional)
- Is 64 orgs in dev-auth mode reachable at all? If not, the cap buys nothing and can be dropped.

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

ℹ️ No new issues in the latest two commits. The prior review's two notes (the stale host-mirror "known leak" block and the bounded dev-auth roster store) remain open.

Reviewed changes (delta since the prior review)

  • GitLab host-context caches bounded — knownHostsCacheByExecutionContext and unauthenticatedHostExpiries are each capped at 128, trimmed on every write; eviction only costs a re-probe, and entries already invalidate on provider-generation change.
  • SSH connection generations released on removal — new forgetSshConnectionGeneration, called from SshProfileOperations.removeSshTarget (the store's only production removal path). This is the explicit-removal pattern rather than an arbitrary cap, and it is not prone to value reuse: the session-scoped base plus random per-add target ids (ssh-${Date.now()}-${random}) mean a forgotten id is never minted again.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: ac00a436-b70b-44ce-895e-3b8e2cd33b53

📥 Commits

Reviewing files that changed from the base of the PR and between b2b3ae9 and 9bf533f.

📒 Files selected for processing (3)
  • src/main/git/source-control/effective-upstream-status-cache.ts
  • src/main/git/source-control/effective-upstream-status-probe.ts
  • src/main/git/status-upstream-negative-cache.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

The pull request bounds many backend and renderer caches, generation maps, retained activities, intent stores, and waiter stores. It adds eviction, expiry pruning, lifecycle cleanup, and test-only size accessors. New tests exercise churn beyond configured limits. WSL home caching moves into a bounded shared module. Toast cleanup now dismisses active toasts on unmount.

Priority: ➖ Normal

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description gives a detailed summary, rationale, trade-offs, and validation results. However, it omits required template sections and information, including a Linked Issue, Visual Proof or the req… Add all required template sections. Provide the linked issue after Fixes #. Add N/A with a reason for Visual Proof if no visual change exists. Complete Testing with manual-test status, automated-test status, and tested platforms. Comple…
Docstring Coverage ⚠️ Warning Docstring coverage is 10.57% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 123 functions across 77 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: releasing stale session registries and reducing memory retention across the application.
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: Description check

Explanation

The description gives a detailed summary, rationale, trade-offs, and validation results. However, it omits required template sections and information, including a Linked Issue, Visual Proof or the required N/A explanation, Testing checkboxes and platform details, AI Disclosure, Review, Agent skill upstream boundary, Notes, and the Checklist.

Resolution

Add all required template sections. Provide the linked issue after Fixes #. Add N/A with a reason for Visual Proof if no visual change exists. Complete Testing with manual-test status, automated-test status, and tested platforms. Complete AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist items.

✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

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

Important

The automation authority-generation eviction guard can still reopen the fence it was added to keep closed: generationFloor is overwritten on every advance, so a brand-new authority resets it to 1, and an evicted authority's reported generation can fall back to a value a request already captured.

Reviewed changes

  • Expired ambiguous cloud-refresh replay attempts on read and capped the registry at 512.
  • Released plugin worker generations when a key goes idle, and bounded plugin log buffers to 256 keys.
  • Bounded automation authority generations with an eviction-aware floor, native chat model enrichment (256 settled entries), web session tracking generations (512, floor-guarded), and codex credential-absence paths (512).
  • Bounded web session reorder intents (512 partitions / 256 per partition) and focus intents (512).
  • Bounded the WSL canonical-path cache, sparse-checkout cache, configured shared-directory cache, advertised-URL scan snapshots, and external automation manager cache (all 512, with insertion-order refresh on read/write).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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

ℹ️ No critical issues — one stale doc line worth updating.

Reviewed changes (delta since the prior pullfrog review)

  • Bounded the WSL home cache — moved wslHomeCache out of wsl.ts into the new src/main/wsl-home-cache.ts, capped at 64 entries with LRU refresh on read and write; wsl.ts re-exports hasCachedWslHome and routes getWslHome/getWslHomeAsync through the module.
  • Added a churn test — wsl.test.ts seeds 68 distros, then asserts a recent distro stays cached without re-probing and an evicted one re-probes (69 calls), pinning both eviction and MRU retention.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/wsl.ts
export function getWslHome(distro: string): string | null {
if (wslHomeCache.has(distro)) {
return wslHomeCache.get(distro)!
const cachedHome = getCachedWslHome(distro)

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.

getWslHome's JSDoc still says the result is cached "per distro for the process lifetime", but rememberWslHome now evicts the oldest entry past 64, so a cached home can be dropped under distro churn. Worth updating the doc to name the bound so it does not contradict the new behavior.

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

ℹ️ No critical issues — the four new caps are clean; one scope question on a sibling cache.

Reviewed changes (delta since the prior pullfrog review)

  • Bounded the Windows write-capability host cache — capabilitiesByExecutionHost in system-ssh-windows-write-capabilities.ts is capped at 256 and now refreshed on every access, so a frequently used host survives churn.
  • Bounded Codex trust-grant transient cooldowns — transientRetryAfterByHost in codex-hook-trust-grant.ts is capped at 256; expired entries are still dropped on read.
  • Bounded legacy WSL auth-drain distro state — completedDistroKeys and pendingSessionBridgeRouteByDistro are each capped at 128 in legacy-wsl-runtime-auth-drain.ts; re-draining an evicted distro re-inspects and re-bridges, which is idempotent.
  • Bounded Linear workspace credential caches — cachedTokens and credentialErrors are each capped at 128 in linear-workspace-registry.ts.
  • Tests — one churn test per registry; all four files run green (45 passed).

ℹ️ The sibling codex capability cache shares the host key space and is still unbounded

grantManagedCodexHookTrust now bounds transientRetryAfterByHost (256) keyed by CodexAppServerHostKey, but the codexAppServerCapabilityCache it consults on that same key is a process-lifetime singleton whose supportedCapabilities set grows one entry per host key and is never evicted. The Windows write-capability commit in this same PR bounded the analogous host-keyed CapabilityProbeCache map, so it is worth confirming this one is intentionally out of scope rather than missed.

Technical details
# Unbounded codex app-server capability cache keyed by host

## Affected sites
- `src/main/codex/codex-app-server-capability-cache.ts:30` — the `codexAppServerCapabilityCache` singleton is created once and cleared only from tests.
- `src/shared/capability-probe-cache.ts:13-15` — `supportedCapabilities`, `retryAfterByCapability`, and `probesByCapability` are keyed by `TCapability`; only `probesByCapability` is self-clearing (`:85-87`).
- `src/main/codex/codex-hook-trust-grant.ts:43` — this commit bounds `transientRetryAfterByHost` for the same `CodexAppServerHostKey` at 256.
- `src/main/ssh/system-ssh-windows-write-capabilities.ts:15-36` — the sibling pattern that was bounded in this PR.

## Required outcome
- Either confirm `codexAppServerCapabilityCache` is deliberately exempt, or bound it by host key so `wsl:<distro>` churn cannot grow it for the process lifetime.

## Suggested approach (optional)
- Reuse the same FIFO/LRU host-key eviction used by `rememberCapabilityCache`, or evict a host key when its distro/target is retired (the explicit-removal pattern used for `ssh-connection-generation`).

## Open questions for the human
- Is WSL distro churn low enough that this is intentionally left unbounded, or was it overlooked while auditing module-level holders?

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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

ℹ️ No critical issues — the four new caps are clean; one coverage gap worth a small test.

Reviewed changes (delta since the prior pullfrog review)

  • Bounded the local Git capability cache — localCapabilitiesByExecutionHost in git-capability-state.ts is capped at 128, with insertion order refreshed on every access.
  • Bounded the WSL Git read-environment cache — wsl-git-read-environment.ts now prunes settledEnvironmentByDistro, environmentByDistro, and transientRetryAfterByDistro together at 128 from touchDistroState.
  • Bounded the WSL preflight cache — new preflight-wsl-cache.ts drops expired entries and caps cachedByWslDistro / latestPreflightRun at 128; agent-detection.ts calls it on entry and after caching. The run-generation fence stays sound because preflightRunCounter is monotonic, so an evicted latestPreflightRun entry can only make a run fail to cache, never accept a stale one.
  • Tests — churn tests for the Git capability and WSL read-environment caps; both files run green (34 passed).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

cached.delete(key)
}
}
while (cached.size > maxEntries) {

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.

Every other cap in this PR ships with a churn test that fails without it, but prunePreflightWslCache has none — preflight-host-cli-status.test.ts only ever uses two distros, so neither the expiry sweep nor the 128-entry cap is exercised. A small unit test over prunePreflightWslCache (or a >128-distro churn test through runPreflightCheck) would pin both loops.

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: c3d38aae-324a-4bd0-ac3f-5fc950c8c70e

📥 Commits

Reviewing files that changed from the base of the PR and between 93d245e and 968ab90.

📒 Files selected for processing (95)
  • src/main/automations/dispatch-tokens.test.ts
  • src/main/automations/dispatch-tokens.ts
  • src/main/automations/external-automation-manager-cache.test.ts
  • src/main/automations/external-automation-manager-cache.ts
  • src/main/codex-accounts/codex-credential-absence-grace.test.ts
  • src/main/codex-accounts/codex-credential-absence-grace.ts
  • src/main/codex-accounts/legacy-wsl-runtime-auth-drain.test.ts
  • src/main/codex-accounts/legacy-wsl-runtime-auth-drain.ts
  • src/main/codex/codex-hook-trust-grant.test.ts
  • src/main/codex/codex-hook-trust-grant.ts
  • src/main/codex/codex-wsl-hook-install-plan.test.ts
  • src/main/codex/codex-wsl-hook-install-plan.ts
  • src/main/daemon/terminal-history-permission-repair.ts
  • src/main/git/git-capability-state.test.ts
  • src/main/git/git-capability-state.ts
  • src/main/git/runner-wsl-direct-read.test.ts
  • src/main/git/worktree-shared-directories.test.ts
  • src/main/git/worktree-shared-directories.ts
  • src/main/git/worktree-sparse-checkout-cache.test.ts
  • src/main/git/worktree-sparse-checkout-cache.ts
  • src/main/git/wsl-git-read-environment.ts
  • src/main/gitlab/gitlab-known-host-probe.test.ts
  • src/main/gitlab/gitlab-known-host-probe.ts
  • src/main/ipc/runtime-environment-transport-generation.test.ts
  • src/main/ipc/runtime-environment-transport-generation.ts
  • src/main/linear/linear-workspace-registry.test.ts
  • src/main/linear/linear-workspace-registry.ts
  • src/main/local-worktree-scan-generation.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-activity-retention.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.ts
  • src/main/native-chat/wsl-transcript-fs-route-quarantine.test.ts
  • src/main/native-chat/wsl-transcript-fs-route-quarantine.ts
  • src/main/orca-profiles/profile-cloud-dev-org-members.ts
  • src/main/orca-profiles/profile-cloud-refresh-replay-guard.test.ts
  • src/main/orca-profiles/profile-cloud-refresh-replay-guard.ts
  • src/main/orca-profiles/profile-cloud-session-store.test.ts
  • src/main/orca-profiles/profile-cloud-session-store.ts
  • src/main/persistence-repo-lifecycle.test.ts
  • src/main/persistence/loading-store/repo-lifecycle-operations.ts
  • src/main/persistence/loading-store/ssh-profile-operations.ts
  • src/main/plugins/plugin-log-buffer.ts
  • src/main/plugins/plugin-worker-manager.test.ts
  • src/main/plugins/plugin-worker-manager.ts
  • src/main/plugins/plugin-worker-output-retention.test.ts
  • src/main/ports/advertised-url-watcher.test.ts
  • src/main/ports/advertised-url-watcher.ts
  • src/main/preflight-wsl-cache.ts
  • src/main/preflight/agent-detection.ts
  • src/main/providers/ssh-git-dispatch.test.ts
  • src/main/providers/ssh-git-dispatch.ts
  • src/main/pty/shell-startup-env.test.ts
  • src/main/pty/shell-startup-env.ts
  • src/main/repo-git-username-enrichment.test.ts
  • src/main/repo-git-username-enrichment.ts
  • src/main/runtime/orca-runtime-notify-ssh-state-changed.ts
  • src/main/runtime/orca-runtime-refresh-pty-worktree-records-with-controller-inventory.ts
  • src/main/runtime/prune-oldest-map-entry.ts
  • src/main/sidecar-snapshot-file.test.ts
  • src/main/sidecar-snapshot-file.ts
  • src/main/ssh/ssh-connection-generation.test.ts
  • src/main/ssh/ssh-connection-generation.ts
  • src/main/ssh/system-ssh-windows-write-capabilities.test.ts
  • src/main/ssh/system-ssh-windows-write-capabilities.ts
  • src/main/workspace-cleanup-scan-snapshot.ts
  • src/main/wsl-home-cache.ts
  • src/main/wsl.test.ts
  • src/main/wsl.ts
  • src/renderer/src/components/automations/automation-host-catalog-generation.test.ts
  • src/renderer/src/components/automations/automation-host-catalog-generation.ts
  • src/renderer/src/components/browser-pane/host-guest/browser-page-viewport.test.ts
  • src/renderer/src/components/browser-pane/host-guest/browser-page-viewport.ts
  • src/renderer/src/components/github-project/roadmap-tick-format.ts
  • src/renderer/src/components/native-chat/native-chat-session-option-enrichment.test.ts
  • src/renderer/src/components/native-chat/native-chat-session-option-enrichment.ts
  • src/renderer/src/components/star-nag/StarNagToastHost.test.tsx
  • src/renderer/src/components/star-nag/StarNagToastHost.tsx
  • src/renderer/src/lib/host-mirror-handle-gap-verdict-union.test.ts
  • src/renderer/src/lib/host-mirror-handle-gap-wait.ts
  • src/renderer/src/lib/repo-slug-index.ts
  • src/renderer/src/runtime/host-session-mirror-hydration-drain.test.ts
  • src/renderer/src/runtime/host-session-mirror-hydration.ts
  • src/renderer/src/runtime/web-agent-session-handoff.ts
  • src/renderer/src/runtime/web-session-close-intent.ts
  • src/renderer/src/runtime/web-session-focus-intent.ts
  • src/renderer/src/runtime/web-session-intent-owner.test.ts
  • src/renderer/src/runtime/web-session-reorder-intent.ts
  • src/renderer/src/runtime/web-session-tabs-sync-agent-handoff.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync/tracking-lifecycle.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync/tracking-lifecycle.ts
  • src/renderer/src/store/repos/runtime-repo-catalog-actions.ts
  • src/renderer/src/store/repos/safe-auto-fork-sync.test.ts
  • src/renderer/src/store/repos/safe-auto-fork-sync.ts
  • src/renderer/src/store/slices/runtime-environment-ssh.ts
  • src/renderer/src/store/slices/ssh.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

Comment on lines +112 to +118
while (scheduledBasePaths.size > MAX_SCHEDULED_BASE_PATHS) {
const oldest = scheduledBasePaths.values().next()
if (oldest.done) {
break
}
scheduledBasePaths.delete(oldest.value)
}

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Do not evict a path while its repair timer is pending.

The set represents scheduled work, not completed cache state. If more than 512 paths are scheduled during the 10-second delay, the oldest pending path is removed. A repeated call for that path then schedules a second concurrent tree repair.

Keep pending paths until their timers settle. Apply any retention limit only to completed paths.

Comment on lines +63 to +68
while (memorySessions.size > MAX_MEMORY_CLOUD_SESSIONS) {
const oldest = memorySessions.keys().next()
if (oldest.done || oldest.value === key) {
break
}
memorySessions.delete(oldest.value)

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Do not evict memory-only sessions.

For persistence: 'memory-only', this map is the only session store. Saving more than 64 profile sessions can evict an active profile's access and refresh tokens. A later read then returns missing because no disk copy exists.

Evict only sessions with encrypted or development-plaintext persistence, or keep memory-only sessions until explicit sign-out.

Comment on lines +18 to +19
export function forgetSshConnectionGeneration(targetId: string): void {
connectionGenerationByTarget.delete(targetId)

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

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- target file ---'
cat -n src/main/ssh/ssh-connection-generation.ts
printf '%s\n' '--- references ---'
rg -n -C 4 'advanceSshConnectionGeneration|forgetSshConnectionGeneration|SshConnectionGeneration|connectionGenerationByTarget|sessionGenerationBase' .
printf '%s\n' '--- ssh files ---'
git ls-files | rg '(^|/)ssh|SSH' | head -80

Repository: stablyai/orca

Length of output: 50370


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions

Length of output: 40234


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- exact generation references ---'
rg -n 'advanceSshConnectionGeneration|forgetSshConnectionGeneration|initializeSshConnectionGenerationSession|getSshConnectionGeneration|setSshConnectionGeneration|assertSshMutationExpectation' src/main src/renderer mobile --glob '!**/*.json'
printf '%s\n' '--- profile operations ---'
cat -n src/main/persistence/loading-store/ssh-profile-operations.ts
printf '%s\n' '--- generation files/tests ---'
fd -i 'ssh-connection-generation' src
fd -i 'ssh.*generation' src
rg -n -C 5 'targetId|removeSshTarget|addSshTarget|createSshTarget|SshTarget' src/main/ssh src/main/persistence/loading-store --glob '*.ts' | head -500

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- target identity ---'
cat -n src/main/ssh/ssh-target-identity.ts
printf '%s\n' '--- target generation helpers ---'
cat -n src/shared/ssh-target-generation.ts
printf '%s\n' '--- target ID creation/reassignment references ---'
rg -n -C 5 'randomUUID|crypto.*random|reassignSshTargetId|addSshTarget\(|id:.*ssh|targetId.*UUID|targetId.*random' src/main src/shared --glob '*.ts' | head -400
printf '%s\n' '--- authority ---'
cat -n src/main/ssh/ssh-provider-authority.ts
printf '%s\n' '--- generation tests ---'
cat -n src/main/ssh/ssh-connection-generation.test.ts

Repository: stablyai/orca

Length of output: 48875


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- relevant files ---'
git ls-files src/main src/shared | rg 'ssh-target-state|ssh-target-reassignment|ssh-profile|ssh-target|target-generation|target.*creation|connection.*generation'
printf '%s\n' '--- target state outline and key definitions ---'
ast-grep outline src/main/persistence/leasing-ssh-ptys/ssh-target-state.ts
rg -n -C 8 'function (addSshTarget|removeSshTarget|updateSshTarget)|export function (addSshTarget|removeSshTarget|updateSshTarget)|targetGeneration|id:' src/main/persistence/leasing-ssh-ptys/ssh-target-state.ts
printf '%s\n' '--- reassignment ---'
cat -n src/main/persistence/leasing-ssh-ptys/ssh-target-reassignment.ts
printf '%s\n' '--- target ID and generation creation in persistence ---'
rg -n -C 5 'randomUUID|nextSshTargetGeneration|allocateSshTargetGeneration|targetGeneration|addSshTarget\(' src/main/persistence src/main/ssh --glob '*.ts' | head -500

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- target CRUD ---'
cat -n src/main/ipc/ssh-target-crud-handlers.ts
printf '%s\n' '--- target registry ---'
cat -n src/main/ssh/ssh-target-registry.ts
printf '%s\n' '--- target lifecycle queue ---'
cat -n src/main/ipc/ssh-target-lifecycle-queue.ts
printf '%s\n' '--- target add/readoption/migration ID references ---'
rg -n -C 8 'randomUUID|addSshTarget|newTargetId|target\.id|id:|re-add|readd|readopt' src/main/ipc/ssh-target-crud-handlers.ts src/main/ipc/ssh-target-lifecycle-queue.ts src/main/ssh/ssh-target-registry.ts src/main/ssh/ssh-target-readoption.ts src/main/ssh/ssh-target-id-migration.ts --glob '*.ts'

Repository: stablyai/orca

Length of output: 32537


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- connection store add/import methods ---'
rg -n -C 12 'addTarget|importFromSshConfig|SshTargetCreateInput|randomUUID|readoptOrphaned' src/main/ssh/ssh-connection-store.ts src/shared/ssh-types.ts src/main --glob '*.ts' | rg -v '(^|:) [0-9]+-.*randomUUID' | head -500
printf '%s\n' '--- store file locations ---'
git ls-files | rg 'ssh-connection-store'

Repository: stablyai/orca

Length of output: 39088


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- removal teardown ---'
rg -n -C 20 'removeRegisteredSshTarget|removeSshTarget|runTargetLifecycle|awaitTargetLifecycle|dispose|abort' src/main/ssh/ssh-session-teardown.ts src/main/ipc/ssh.ts src/main/ipc --glob '*.ts' | head -500
printf '%s\n' '--- mutation paths and generation checks ---'
cat -n src/main/ipc/filesystem-mutations.ts | sed -n '1,210p'
cat -n src/main/ipc/filesystem-mutations.ts | sed -n '250,315p'

Repository: stablyai/orca

Length of output: 50369


Do not reset the connection-generation fence after target removal. SshConnectionStore.addTarget creates IDs with a timestamp and Math.random() and does not check for collisions. If a removed ID is reused while stale work remains, forgetSshConnectionGeneration deletes its entry, so the next advanceSshConnectionGeneration returns sessionGenerationBase + 1 again. assertSshMutationExpectation can then accept the stale target ID and generation for the new target. Allocate generations from a monotonic session-wide sequence instead of resetting the target to the session floor.

Source: Learnings

Comment thread src/main/wsl.ts
return wslHomeCache.has(distro)
}

/** Pure cache lookup — never probes. */

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Correct the getWslHomeAsync documentation.

The function is not a pure cache lookup. On a cache miss, it starts wsl.exe through execFileUtf8().

Proposed fix
-/** Pure cache lookup — never probes. */
+/** Returns a cached home or starts an asynchronous WSL probe. */
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/** Pure cache lookup — never probes. */
/** Returns a cached home or starts an asynchronous WSL probe. */
🧰 Tools
🪛 ast-grep (0.45.3)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFile, execFileSync } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

Comment on lines +22 to +27
while (safeAutoForkSyncAttempts.size > MAX_SAFE_AUTO_FORK_SYNC_ATTEMPTS) {
const oldest = safeAutoForkSyncAttempts.keys().next()
if (oldest.done) {
return
}
safeAutoForkSyncAttempts.delete(oldest.value)

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.

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Do not evict in-flight attempts.

If one call schedules more than 512 eligible repositories, this loop removes entries that still contain a promise. A later call then cannot detect that attempt at Lines 43-47 and starts a second concurrent syncRuntimeGitForkDefaultBranch call for the same repository. Evict only settled attempts. Keep pending attempts until their finally handler clears the promise.

Proposed fix
   while (safeAutoForkSyncAttempts.size > MAX_SAFE_AUTO_FORK_SYNC_ATTEMPTS) {
-    const oldest = safeAutoForkSyncAttempts.keys().next()
-    if (oldest.done) {
+    const evictable = [...safeAutoForkSyncAttempts].find(([, attempt]) => !attempt.promise)
+    if (!evictable) {
       return
     }
-    safeAutoForkSyncAttempts.delete(oldest.value)
+    safeAutoForkSyncAttempts.delete(evictable[0])
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
while (safeAutoForkSyncAttempts.size > MAX_SAFE_AUTO_FORK_SYNC_ATTEMPTS) {
const oldest = safeAutoForkSyncAttempts.keys().next()
if (oldest.done) {
return
}
safeAutoForkSyncAttempts.delete(oldest.value)
while (safeAutoForkSyncAttempts.size > MAX_SAFE_AUTO_FORK_SYNC_ATTEMPTS) {
const evictable = [...safeAutoForkSyncAttempts].find(([, attempt]) => !attempt.promise)
if (!evictable) {
return
}
safeAutoForkSyncAttempts.delete(evictable[0])

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

ℹ️ No critical issues — the warm-on-read change is correct; one small note on test coverage and one inline simplification.

Reviewed changes (delta since the prior pullfrog review)

  • Warm-on-read for three FIFO caches — getGlabKnownHosts (gitlab-known-host-probe.ts), getCachedToken / getCredentialError (linear-workspace-registry.ts), and readShellStartupEnvVar (shell-startup-env.ts) now delete and re-set on a hit so a frequently read key moves to the newest position. Each still trims past its cap on write, so the size bound is unchanged, and these are pure caches (no generation/fence values), so reordering on read is safe.
  • Updated JSDoc — readShellStartupEnvVar's "memoized … for the process lifetime" line now describes the bounded recent window.

ℹ️ The warm-on-read behavior is not asserted by any test

The commit's stated effect — a hot key survives churn because a read moves it newest — is not pinned by the existing tests: gitlab-known-host-probe.test.ts asserts only the cap size, linear-workspace-registry.test.ts asserts only that the oldest key was evicted, and the shell-startup test asserts only that an evicted key is re-read. None would fail if the read-path refresh were removed.

Technical details
# Warm-on-read has no failing test

## Affected sites
- `src/main/gitlab/gitlab-known-host-probe.ts:164-172` — read-path refresh; `gitlab-known-host-probe.test.ts` only checks `_getKnownHostsCacheSize()`.
- `src/main/linear/linear-workspace-registry.ts:29-36,76-83` — read-path refresh; `linear-workspace-registry.test.ts` checks only that `workspace-0` was evicted.
- `src/main/pty/shell-startup-env.ts:238-245` — read-path refresh; the churn test only asserts an evicted key is re-read (`readFileSyncMock` call count grows).

## Required outcome
- A churn test per cache that touches one hot key, overflows the cap, then asserts the hot key is still served without recompute/fault, so a regression to plain FIFO fails.

## Open questions for the human
- Optional: warmth is an optimization, so this can be skipped if you consider the cap tests sufficient.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

const { key, cacheKey } = knownHostsCacheContext(connectionId, localGitOptions)
const cached = knownHostsCacheByExecutionContext.get(cacheKey)?.hosts
if (cached) {
const entry = knownHostsCacheByExecutionContext.get(cacheKey)

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.

cached and entry are the same lookup: when the outer .hosts was truthy the inner get can never return undefined, so the second get and its if are dead. Collapsing to a single get (returning entry.hosts) reads more directly and matches the single-lookup shape used by getCachedToken/getCredentialError.

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

Important

The new CapabilityProbeCache bound is not applied on the path the codex capability cache actually uses, so the cache this PR claims to bound still grows for the process lifetime.

Reviewed changes

  • Replaced the per-key (get ?? 0) + 1 generation counters with monotonic sequences plus an evictedGeneration fallback in ssh-git-dispatch, runtime-environment-transport-generation, runtime-environment-ssh, ssh.ts, web-session-tabs-sync/tracking-lifecycle, and automation-host-catalog-generation, removing the automation evictedAuthorityKeys / generationFloor guard. This closes the eviction value-reuse and floor-fallback fences flagged in earlier reviews.
  • Added a maxEntries bound and a trimSettledEntries sweep to CapabilityProbeCache, and passed 256 from CodexAppServerCapabilityCache.
  • Tightened repo-slug-index so a resolution only commits if it is still the tracked in-flight promise, not merely if its generation is current.
  • Added eviction-regression tests to the transport-generation, ssh-git-dispatch, automation-catalog, and host-session-mirror-drain suites.
  • Rewrote the host-mirror-handle-gap-wait "KNOWN LEAK" block to describe the 512-entry bounded backstop instead of session-lifetime retention.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment thread src/shared/capability-probe-cache.ts Resolved

@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

Caution

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

⚠️ Outside diff range comments (1)

🟠 Major · Apply the entry limit after a successful preferred probe. · capability-probe-cache.ts:137

src/shared/capability-probe-cache.ts:137
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Apply the entry limit after a successful preferred probe.

runPreferredOrFallback adds successful capabilities directly to supportedCapabilities. This path bypasses trimSettledEntries. Distinct hosts with successful probes can therefore grow the set without a bound, despite the configured maxEntries.

Use rememberSupported(capability) so this primary success path also refreshes and trims the entry.

Proposed fix
     const outcome = this.retryAfterByCapability.has(capability) ? 'unsupported' : 'supported'
     if (outcome === 'supported') {
-      this.supportedCapabilities.add(capability)
+      this.rememberSupported(capability)
     }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: bc722dba-891e-4ac3-9866-63671a0ea15d

📥 Commits

Reviewing files that changed from the base of the PR and between ce761b9 and a4cbedb.

📒 Files selected for processing (28)
  • config/tsconfig.tc.web.json
  • src/main/agent-hooks/wsl-hook-relay-manager.test.ts
  • src/main/agent-hooks/wsl-hook-relay-manager.ts
  • src/main/codex/codex-app-server-capability-cache.test.ts
  • src/main/codex/codex-app-server-capability-cache.ts
  • src/main/codex/codex-hook-trust-grant.test.ts
  • src/main/git/git-capability-state.test.ts
  • src/main/ipc/runtime-environment-transport-generation.test.ts
  • src/main/ipc/runtime-environment-transport-generation.ts
  • src/main/plugins/plugin-log-buffer.ts
  • src/main/plugins/plugin-worker-manager.ts
  • src/main/providers/ssh-git-dispatch.test.ts
  • src/main/providers/ssh-git-dispatch.ts
  • src/main/runtime/orca-runtime-notify-ssh-state-changed.ts
  • src/main/runtime/orca-runtime-refresh-pty-worktree-records-with-controller-inventory.ts
  • src/renderer/src/components/automations/automation-host-catalog-generation.test.ts
  • src/renderer/src/components/automations/automation-host-catalog-generation.ts
  • src/renderer/src/lib/host-mirror-handle-gap-wait.ts
  • src/renderer/src/lib/monaco-setup.ts
  • src/renderer/src/lib/repo-slug-index.ts
  • src/renderer/src/runtime/web-session-tabs-sync/tracking-lifecycle.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync/tracking-lifecycle.ts
  • src/renderer/src/store/repos/runtime-repo-catalog-actions.ts
  • src/renderer/src/store/slices/runtime-environment-ssh.ts
  • src/renderer/src/store/slices/ssh.ts
  • src/shared/capability-probe-cache.ts
  • src/shared/commit-message-agent-spec.test.ts
  • src/shared/commit-message-agent-specs-primary.ts
💤 Files with no reviewable changes (2)
  • src/renderer/src/lib/monaco-setup.ts
  • src/shared/commit-message-agent-spec.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/lib/host-mirror-handle-gap-wait.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

Comment on lines +77 to +79
evictedGeneration = Math.max(evictedGeneration, generationByAuthorityKey.get(key) ?? 0)
generationByAuthorityKey.delete(key)
fingerprintByAuthorityKey.delete(key)

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 | 🟠 Major | 🏗️ Heavy lift

Preserve fingerprints for active authorities.

When a catalog contains more than 512 authorities, trimAuthorityGenerations deletes fingerprints for authorities that remain in that catalog. The next identical sync treats those authorities as changed and advances their generations again. Frequent catalog synchronization can then invalidate current requests even though the catalog did not change.

Bound retired authority state separately. Do not evict fingerprints for authorities in the current catalog.

// failure on every poll/search wastes subprocesses and trace space.
this.supportedCapabilities.delete(capability)
this.retryAfterByCapability.set(capability, nowMs + this.retryIntervalMs)
this.trimSettledEntries()

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

Refresh an unsupported entry before eviction.

Map.set does not change insertion order for an existing key. A newly observed unsupported result can remain the oldest entry and be deleted by this trim when the next capability is added. shouldTry then permits an immediate probe instead of preserving the renewed retry interval.

Delete the key before setting the new deadline.

Proposed fix
   rememberUnsupported(capability: TCapability, nowMs = Date.now()): void {
     this.supportedCapabilities.delete(capability)
+    this.retryAfterByCapability.delete(capability)
     this.retryAfterByCapability.set(capability, nowMs + this.retryIntervalMs)
     this.trimSettledEntries()
   }

@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

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: c09fcfdb-253d-411b-ba22-46dd3b3b2a77

📥 Commits

Reviewing files that changed from the base of the PR and between a4cbedb and b2b3ae9.

📒 Files selected for processing (11)
  • src/main/agent-hooks/wsl-hook-default-distro.ts
  • src/main/agent-hooks/wsl-hook-relay-manager.ts
  • src/main/agent-hooks/wsl-hook-relay-resume.ts
  • src/main/git/source-control/effective-upstream-status-cache.ts
  • src/main/git/status-upstream-negative-cache.test.ts
  • src/main/persistence/loading-store/repo-lifecycle-operations.ts
  • src/main/persistence/loading-store/repo-lifecycle-ui-residue.ts
  • src/main/plugins/plugin-log-buffer.ts
  • src/main/plugins/plugin-worker-generation-retention.ts
  • src/main/plugins/plugin-worker-lifecycle.ts
  • src/main/plugins/plugin-worker-manager.ts

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

cacheKey,
(effectiveUpstreamStatusWriteGeneration.get(cacheKey) ?? 0) + 1
)
effectiveUpstreamStatusWriteGeneration.set(cacheKey, ++writeGenerationSequence)

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.

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Trim generations after clearing a key.

Each call creates a generation entry, but this path does not trim it. Clearing more than 512 distinct inactive identities without a later rememberEffectiveUpstreamStatus call leaves effectiveUpstreamStatusWriteGeneration above its configured bound. Call trimEffectiveUpstreamStatusGeneration() after this update.

Proposed fix
   effectiveUpstreamStatusWriteGeneration.set(cacheKey, ++writeGenerationSequence)
+  trimEffectiveUpstreamStatusGeneration()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
effectiveUpstreamStatusWriteGeneration.set(cacheKey, ++writeGenerationSequence)
effectiveUpstreamStatusWriteGeneration.set(cacheKey, ++writeGenerationSequence)
trimEffectiveUpstreamStatusGeneration()

Comment on lines +140 to +141
(effectiveUpstreamStatusWriteGeneration.get(cacheKey) ?? evictedWriteGeneration) !==
writeGeneration

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.

🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -euo pipefail

ast-grep outline src/main/git/source-control/effective-upstream-status-cache.ts --items all
ast-grep run --lang typescript \
  --pattern 'rememberEffectiveUpstreamStatus($$$)' \
  src/main/git
rg -n -C 5 \
  'effectiveUpstreamStatusWriteGeneration\.get\(|rememberEffectiveUpstreamStatus\(|writeGeneration' \
  src/main/git

Repository: stablyai/orca

Length of output: 12548


Use the eviction floor when starting a probe.

When cacheKey has been evicted, effective-upstream-status-probe.ts initializes writeGeneration to 0, but this check compares it with the nonzero evictedWriteGeneration. The negative result is discarded, so subsequent polls cannot use negative caching for that key. Initialize writeGeneration with the eviction floor, or allocate a new generation before probing.

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

Important

The effective-upstream generation fence now compares against an evicted-value fallback that the probe does not use when capturing, so the negative cache silently stops caching new worktrees after the first generation eviction.

Reviewed changes

  • Reworked the effective-upstream write generation into a monotonic sequence with an evictedWriteGeneration fallback, and added a regression test that an evicted strict probe cannot republish a stale negative (status-upstream-negative-cache.test.ts).
  • Extracted resolveWslHookDefaultDistro (wsl-hook-default-distro.ts) and resumeStoppedWslHookRelays (wsl-hook-relay-resume.ts) out of wsl-hook-relay-manager.ts — behavior-preserving.
  • Extracted pruneDeregisteredRepoUiResidue into repo-lifecycle-ui-residue.ts.
  • Extracted plugin worker generation/lifecycle helpers into plugin-worker-generation-retention.ts and plugin-worker-lifecycle.ts, and added a PluginLogBuffer.size getter.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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

✅ No new issues found.

Reviewed changes (delta since the prior pullfrog review at b2b3ae9)

  • Aligned the effective-upstream generation fence — added getEffectiveUpstreamStatusWriteGeneration (map.get(key) ?? evictedWriteGeneration) and switched the probe's capture in effective-upstream-status-probe.ts:49 from ?? 0 to it, so capture and compare now share the evicted-value floor. This closes the prior [!IMPORTANT] finding: a never-written key captures the floor instead of 0, so rememberEffectiveUpstreamStatus no longer rejects every fresh negative after the first generation eviction.
  • Added a regression test — status-upstream-negative-cache.test.ts seeds 513 positive writes, then asserts a fresh negative key still caches, pinning the capture/compare agreement.

I ran pnpm test src/main/git/status-upstream-negative-cache.test.ts — 8 passed.

The codex capability cache finding from review 5258748051 (runPreferredOrFallback adding to supportedCapabilities without trimming) is unchanged and remains open, so this review is not an approval.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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

ℹ️ No critical issues — the prior [!IMPORTANT] finding is resolved; one coverage note inline.

Reviewed changes (delta since the prior pullfrog review at 9bf533f)

  • Routed the preferred-probe success path through the bound — runPreferredOrFallback now calls rememberSupported(capability) instead of adding to supportedCapabilities directly, so the codex app-server cache trims on the path codex-hook-trust-grant.ts actually uses. This closes the open [!IMPORTANT] finding from review 5258748051; the unsupported-signal guard (only mark supported when no retry cooldown is present) is preserved.

I ran pnpm test src/main/codex/codex-app-server-capability-cache.test.ts src/shared — all green.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

const outcome = this.retryAfterByCapability.has(capability) ? 'unsupported' : 'supported'
if (outcome === 'supported') {
this.supportedCapabilities.add(capability)
this.rememberSupported(capability)

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.

No test pins the bound on this success path. The churn test in codex-app-server-capability-cache.test.ts only calls rememberUnsupported, and the other success-path tests never overflow the cap, so reverting this line to a direct supportedCapabilities.add would leave every test green. A churn test that resolves successful runWithFallback probes for CODEX_APP_SERVER_CAPABILITY_MAX_ENTRIES + N distinct wsl:<distro> keys and then asserts an early key reports isKnownSupported(...) === false would fail against the pre-fix code.

Technical details
# Bound on the preferred-probe success path is untested

## Affected sites
- `src/shared/capability-probe-cache.ts:136-138` — the newly re-routed success path (`rememberSupported`).
- `src/main/codex/codex-app-server-capability-cache.test.ts:78-86` — churn test exercises only `rememberUnsupported`.

## Required outcome
- A regression test that fails if this success path stops trimming (i.e. reverts to a bare `supportedCapabilities.add`).

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

Important

The new clock-rollback branch in the replay guard allows a refresh-token replay that the previous code blocked, and deletes the attempt evidence the replay warning depends on. Details inline.

Reviewed changes (delta since the prior pullfrog review at 1aef160)

  • Retained expired replay evidence — added a bounded expiredAmbiguousRefreshAttempts map and a preserveKey parameter to pruneAmbiguousRefreshAttempts, so an expired attempt is moved rather than deleted and wasRefreshTokenAmbiguouslyAttempted still classifies a later 401 as a possible replay. This restores the behavior the existing profile-cloud-session-refresh.test.ts replay-warning test depends on.
  • Restructured blocksAmbiguousRefreshReplay — moved pruning off the entry path and added a now < attempt.attemptedAt clock-rollback branch that drops the active attempt and returns false.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +89 to +93
if (now < attempt.attemptedAt) {
// A clock rollback must not resurrect an already-expired replay window.
ambiguousRefreshAttempts.delete(key)
return false
}

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.

This branch turns a call the previous code blocked into an allow, and it deletes the attempt instead of moving it to expiredAmbiguousRefreshAttempts, so the replay warning loses the evidence too. now < attempt.attemptedAt only fires on a backward wall-clock step — it cannot distinguish a stale attempt from a just-recorded one — and the parent returned true there because now - attempt.attemptedAt was negative. If un-blocking on rollback is intended, the attempt should at least be retained as evidence; otherwise clamp now or keep blocking.

Technical details
# Clock rollback now fails open and drops replay evidence

## Affected sites
- `src/main/orca-profiles/profile-cloud-refresh-replay-guard.ts:89-93` — `now < attempt.attemptedAt` deletes the active attempt and returns `false`; the parent (`1aef160d5c`) fell through to `now - attempt.attemptedAt < DELAY`, which is `true` for a negative elapsed time, and kept the entry.
- `src/main/orca-profiles/profile-cloud-session-refresh.ts:182` — the only gate before `refreshOrcaCloudSession`; `false` lets the same refresh token be re-POSTed.
- `src/main/orca-profiles/profile-cloud-session-refresh.ts:106` — `wasRefreshTokenAmbiguouslyAttempted` reads both maps, so after this branch it returns `false` and the 401 is not classified as `orca_cloud_refresh_possible_replay`.
- `src/main/orca-profiles/profile-cloud-refresh-replay-guard.test.ts:14-31` — exercises only forward time (`1_000`, `1_000 + DELAY`); no `now < attemptedAt` case, so this branch is untested.

## Required outcome
- A backward wall-clock step must not lift the replay block for a still-fresh ambiguous attempt, and the attempt should remain available as evidence so a later 401 is still classified as a possible replay.

## Suggested approach (optional)
- Keep blocking on rollback (return `true`), or clamp the effective `now` to `attemptedAt`. If dropping the block is intended, at minimum move the attempt into `expiredAmbiguousRefreshAttempts` before deleting it and add a test asserting `blocksAmbiguousRefreshReplay(key, token, attemptedAt - 1)`.

@OrcaWin
OrcaWin merged commit 4085e1c into main Sep 20, 2026
77 of 79 checks passed
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