Repository navigation
Conversation
…ents `orca environment rm` runs in its own CLI process and only rewrites the environment store, so the running app kept the environment's shared-control WebSocket open and kept reconnecting after every drop until restart. The GUI removal path already retires the transport; the CLI path had no way to reach it. Teach the shared-control connection a third reason not to be connected, next to manual disconnect and capability pause: the environment is gone from the store. The existing 10s liveness heartbeat -- the only level-triggered hook an open socket has -- checks it and hands retirement to the same invalidateRuntimeEnvironmentTransport the GUI uses, and the reconnect scheduler refuses to re-arm if a close wins the race. Removal is only believed on positive observation: the store file exists, parses, and the id is absent. A missing store reads as zero environments rather than throwing, so anything weaker would retire every environment at once. Fixes stablyai#20995
…lectron main process The registration that hands the removal watch its user-data path runs only inside the shipped main process, and the retirement rides the socket's own liveness timer, so neither was reachable from a vitest-only harness. This boots the real main process over a real shared-control server, rewrites the store from the test process the way `orca environment rm` does, and watches the socket go away.
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe change adds a runtime-environment removal watch that records stored environments and detects their later removal. Shared-control connections check this state during liveness handling, close removed environments, and skip reconnection. Runtime handler registration installs the watch with transport invalidation. Unit, request-connection, shared-control, and Electron integration tests verify removal detection, teardown, and the absence of reconnects. Priority: ➖ Normal Severity of issue fixed: Medium Merge Risk: 🔵 Low · up to If an environment is removed while reconnection is pending, stale connection state can remain until later cleanup. Retire it in the scheduler branch before merging. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: e6f950fa-4881-4b31-88fb-a56c0b60af26
📒 Files selected for processing (13)
src/main/ipc/runtime-environment-cli-removal.electron.test.tssrc/main/ipc/runtime-environment-removal-watch.test.tssrc/main/ipc/runtime-environment-removal-watch.tssrc/main/ipc/runtime-environment-request-connections.test.tssrc/main/ipc/runtime-environment-request-connections.tssrc/main/ipc/runtime-environments.tssrc/shared/remote-runtime-shared-control-connection.test.tssrc/shared/remote-runtime-shared-control-connection.tssrc/shared/remote-runtime-shared-control-open.tssrc/shared/remote-runtime-shared-control-reconnect.test.tssrc/shared/remote-runtime-shared-control-reconnect.tssrc/shared/remote-runtime-shared-control-test-server.tssrc/shared/remote-runtime-shared-control-types.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
There was a problem hiding this comment.
ℹ️ No blocking issues — the fix and its differential test hold up. A few minor suggestions inline.
Reviewed changes
Reviewed the full diff at f4f56ab (2 commits, 13 files): the new CLI-removal watch, the shared-control retirement hooks, and their tests.
- New
runtime-environment-removal-watch.ts— module-level{ getUserDataPath, retire }watch plus astoredEnvironmentIdspositive-observation set; missing/unreadable/foreign stores stay connected. - Shared-control retirement hooks — optional
isEnvironmentRemoved/onEnvironmentRemoved; the livenesspinginvokesonRetiredwhenisRetiredis true;scheduleAfterSocketClosegains anenvironmentRemovedgate with a positive-control test. - Main wiring —
runtime-environments.tsinstalls the watch withinvalidateRuntimeEnvironmentTransportbefore the startupactivate()loop;getSharedControlConnectionrecords the id at construction. - Drive-by —
diagnosticsInputs()now backs bothpublishDiagnosticsandgetDiagnostics. - Tests — new Electron e2e differential test, removal-watch unit suite, request-connection gate, and two test-server accessors.
ℹ️ The "removed during status verification" window is closed only by an unrelated throw
RuntimeHostStatusOwner.verified calls markEnvironmentUsed(...) before transport.establish(). For an environment removed during the status round trip, markEnvironmentUsed throws (resolveEnvironmentFromStore → Unknown environment), which incidentally prevents the socket from ever opening — so there is no live socket for the watch to retire. That is the pre-existing defect recorded as Note 5. Repairing Note 5 without also gating establish() would open a transport for an id the watch never recorded (noteRuntimeEnvironmentStored reads after removal), and nothing would retire it.
Technical details
# Removal-during-verification coupling
## Affected sites
- `src/main/ipc/runtime-environment-status-owner.ts:63-69` — `markEnvironmentUsed` runs before `transport.establish()`; its throw is currently the only reason a removed id never reaches `establish()`.
- `src/main/ipc/runtime-environment-removal-watch.ts:22-26` — `noteRuntimeEnvironmentStored` records nothing when the id is already absent, so any connection built after removal is unjudgeable and never retired.
## Required outcome
- `establish()` must not open a transport for an environment that is already gone, independent of whether `markEnvironmentUsed` throws.
## Open questions for the human
- Is Note 5 in scope for a follow-up, and if so should that follow-up also gate `establish()` on the removal verdict?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…oval detection Review on stablyai#21048 found both; each makes the removal check fail to fire and fall back to the old behaviour, rather than regressing anything. The reconnect scheduler took its verdict before the backoff and never asked again, so a removal landing mid-wait still opened one more transport. Pass the check as a thunk and re-ask when the timer fires. It lives in the scheduler because the connection file is at its max-lines ceiling and gating open() there does not fit. The presence observation that lets an id be judged at all was recorded by re-reading the store at connection construction. A removal between the caller's own successful resolve and that second read left no observation, and since the note only runs on the construction branch, the environment could never be judged again. Take the evidence from the resolve that already succeeded, keyed by the user-data path it came from so a foreign store still cannot record one.
|
On the docstring-coverage pre-merge check (18.75% against an 80% threshold): I am deliberately not acting on this one.
The non-obvious decisions in this diff are commented, which is where I think the value is: why removal is only believed on positive observation, why the presence evidence comes from the caller's resolve rather than a second store read, why the reconnect re-asks at fire time, and why the end-to-end probe needs a real Electron process. Happy to add more if a maintainer wants them — I would just rather follow the repo's rule than the bot's default threshold, and say so out loud instead of quietly ignoring the check. Both Major findings from the review are fixed in 639e0e0, with replies on the two threads. |
There was a problem hiding this comment.
ℹ️ No new issues in the delta — the two race fixes hold up. One scope question below.
Reviewed changes
Reviewed the incremental delta at 639e0e0 (f4f56ab..639e0e0, 7 files): the removal-observation race fixes and their tests.
- Path-aware observation recording —
noteRuntimeEnvironmentStored(id, userDataPath?)now records from the caller's resolve rather than re-reading the store, andgetRuntimeEnvironmentStatusOwnercalls it withuserDataPathright afterresolveEnvironmentsucceeds, so a removal landing between that read and the connection's own re-read can no longer erase the positive observation. - Reconnect gate re-evaluated at fire time —
scheduleAfterSocketClose'senvironmentRemovedis now a thunk, and theopenhanded to the backoff scheduler re-checks it when the timer fires, dropping a reconnect armed before removal. - Tests — new cases for removed-then-recorded, foreign-user-data-path, trailing-separator, and mid-backoff removal; the focused suites (
removal-watch,request-connections,reconnect,shared-control-connection) pass locally (51 tests).
️ CLI-removal retirement is only reachable through a shared-control socket
The watch's teardown is invoked only from the shared-control liveness hook, so an environment whose host never advertises REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY has no retirement trigger at all when the CLI removes it. For such a host the status owner pauses instead of establishing, and the retained terminal/browser subscriptions stay open until the renderer closes them or the app restarts — the same "CLI removal leaves a socket" class as #20995, just on a different transport. Flagging as an open scope question rather than a defect in this delta.
Technical details
# CLI-removal retirement is gated behind the shared-control liveness hook
## Affected sites
- `src/shared/remote-runtime-shared-control-connection.ts:192` — `onRetired` is the only caller of `onEnvironmentRemoved`, which is the only caller of `retireRemovedRuntimeEnvironment` (`src/main/ipc/runtime-environment-request-connections.ts:230`).
- `src/main/ipc/runtime-environment-status-owner.ts:68-72` — `verified` calls `transport.establish()` only when the host advertises `REMOTE_RUNTIME_SHARED_CONTROL_CAPABILITY`; otherwise `transport.pause()`, so no shared-control socket (and no liveness hook) exists.
- `src/main/ipc/runtime-environments.ts:65-80` — `invalidateRuntimeEnvironmentTransport` is what closes `remoteRuntimeSubscriptions` (`closeSubscriptionsForEnvironment`) and the request connection; for CLI removal it is reached only through the watch's `retire`, which the liveness hook drives.
- `src/main/ipc/runtime-environment-support-routing.ts:52-63` — `terminal.multiplex` / `browser.screencast` subscriptions are deliberately not support-routed, so they persist as `RemoteRuntimeSubscription`s in `remoteRuntimeSubscriptions` independent of shared control.
## Required outcome
- Decide whether CLI-removal retirement must cover transports on hosts without a shared-control socket. If yes, the watch's `retire` needs a trigger independent of the shared-control liveness tick (the guard predicate already answers "is this environment gone?").
## Open questions for the human
- Is this an accepted scope boundary for #20995 (whose reproduction used shared-control-capable hosts), or should the watch drive `invalidateRuntimeEnvironmentTransport` directly?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
… an untested branch Review on stablyai#21048 caught three things in the removal work. The end-to-end probe hard-coded the 10s liveness cadence and hand-rolled the Linux xvfb wrapper. It now imports REMOTE_RUNTIME_SOCKET_PING_INTERVAL_MS so the wait tracks production, and calls resolveElectronProbeLaunch, which reuses an inherited DISPLAY instead of nesting a private X server per probe -- the race that helper exists to avoid. isRuntimeEnvironmentRemoved recorded a still-listed id so a later check could judge it, and deleting that line left the whole suite green. It is the only evidence a connection gets when its construction-time observation never landed, so pin it with a case that never records a resolve.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the incremental delta at 78b942c (2 files, 639e0e0..78b942c): the follow-up to the prior review's three threads.
- Reused the Electron probe launch helper — the new e2e probe now calls
resolveElectronProbeLaunchinstead of hand-rolling the Linuxxvfb-runwrapper, so it reuses an inheritedDISPLAYand stops racing sibling probes for a display number. - Imported the production liveness cadence — the local
LIVENESS_PING_INTERVAL_MS = 10_000is gone; both the socket-loss wait and the post-close delay now trackREMOTE_RUNTIME_SOCKET_PING_INTERVAL_MS. - Pinned the previously untested
listedbranch — a newjudges a removal seen only through repeated checks, with no resolve recordedcase records an id only from alistedcheck, so deleting thestoredEnvironmentIds.addinisRuntimeEnvironmentRemovednow goes red (confirmed by ablation).
All three prior pullfrog threads are addressed and resolved. The open scope question from the 639e0e0 review — CLI-removal retirement is only reachable through a shared-control socket, so hosts without the capability keep their subscriptions until restart — remains open and is not touched by this delta.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟠 Major · Guard request-driven readiness after removal. · remote-runtime-shared-control-connection.ts:190-192
src/shared/remote-runtime-shared-control-connection.ts:190-192
🎯 Functional Correctness | 🟠 Major | ⚡ Quick winGuard request-driven readiness after removal. When a socket is in reconnect backoff,
SharedControlReconnectScheduleronly skips the delayedopen; it does not invalidate the cached connection.executeSupportRoutedCallcan retain the environment acrosssupportsSharedControland then callsendRemoteRuntimeSharedControlRequest. The cached connection then reachesensureReadyWithTimeoutandopenIfSocketClosed, which callsopen()for a closed socket. This can create a new socket to the removed environment before liveness triggers invalidation. Apply the removal check to the direct readiness/open path, or invalidate the cached connection when removal is detected.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 1e2470d9-9c2a-4ca2-bf42-052b6e61572e
📒 Files selected for processing (2)
src/main/ipc/runtime-environment-cli-removal.electron.test.tssrc/main/ipc/runtime-environment-removal-watch.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
…vironment The reconnect scheduler re-asks for removal at fire time, but that only gates the backoff timer. A request arriving while the socket is down reaches `ensureReadyWithTimeout` -> `openIfSocketClosed` -> `open()`, which checked only `intentionallyClosed` and dialled a fresh socket to an environment the CLI had already removed. The cached connection left inert by the declining scheduler was therefore reopenable, not inert. `open()` now re-asks the same predicate, so every entry into it is gated rather than just the scheduled one. Reusing the existing `intentionallyClosed` branch keeps the waiter semantics identical: waiters are pushed before `open()` runs, so the caller is rejected instead of hanging to its timeout. The guard is inline rather than an extracted predicate because this file sits at exactly 300/300 of the `*.ts` max-lines ceiling and AGENTS.md forbids a max-lines disable; the change adds no countable line. Verified by mutation: with the removal clause deleted, the new case fails because the request *resolves* over a second socket, while the other 29 cases in the file stay green, which pins the readiness path rather than the timer path.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 43348bb6-8da9-42cc-add1-898c9665d6b5
📒 Files selected for processing (2)
src/shared/remote-runtime-shared-control-connection.test.tssrc/shared/remote-runtime-shared-control-connection.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the incremental delta at 7e908d8 (78b942c..7e908d8, 2 files): the follow-up to the "guard request-driven readiness after removal" finding.
- Gated
open()on removal — a request reaching a closed socket opens one directly throughensureReadyWithTimeout, bypassing the reconnect backoff gate.open()now declines that path whenisEnvironmentRemoved()is true, rejecting ready waiters instead of dialing a removed environment. - Pinned the path with a test —
declines a request-driven reopen once its environment is removeddrops the socket, confirms removal, then asserts the next request rejects and the server-sideconnectionCountstays at1. Deleting the gate makes the test fail (verified by mutation), so it is not vacuous.
ℹ️ PR body Note 2 still says open() is deliberately not gated
The description's Note 2 reads "open() is deliberately not gated — the connection file has no room under max-lines and it would need its own test for no behavioural gain." This delta reverses exactly that: open() is now gated and has its own test. The code is correct — the note is stale and could lead a reader to believe the request-driven reopen is still unhandled.
Technical details
# Stale Note 2 in the PR description
## Affected sites
- PR body, Notes item 2 — "open() is deliberately not gated".
- `src/shared/remote-runtime-shared-control-connection.ts:168-177` — `open()` now early-returns on `isEnvironmentRemoved()`.
- `src/shared/remote-runtime-shared-control-connection.test.ts:715-744` — the matching test.
## Required outcome
- Note 2 reflects the shipped behaviour: the gate is present and a request-driven reopen is declined.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…it removed 7e908d8 gated `open()` on removal so a request reaching a closed socket stops dialling an environment the CLI already removed. It returns before `openSharedControlSocket`, which is also the only place a liveness monitor is built -- and `onRetired` on that monitor is the sole production caller of `onEnvironmentRemoved`. Declining the dial therefore traded one stray socket for a transport that never retires: the cached connection, its status owner and its subscriptions outlive the environment, because nothing reaches `invalidateRuntimeEnvironmentTransport`. Removal is detected by polling the store, so no other producer compensates. `open()` now fires the retirement callback from the same guard. Waiters are rejected first, so the caller keeps the message it already had and the re-entrant `close()` that retirement performs finds an empty waiter array -- `rejectSharedControlReadyWaiters` splices, so the second pass is a no-op. The `intentionallyClosed` gate keeps retirement to once per connection: retirement closes the connection, and every later caller finding the same retired transport takes the `intentionallyClosed` branch without re-firing. An intentional close must not retire an environment that is still there. Folding the waiter rejection onto one line via a named import pays for the guard, so the file stays at exactly 300/300 of the `*.ts` max-lines ceiling that AGENTS.md forbids disabling. Verified by mutation in both directions: deleting the callback fails the new case with 0 calls, and dropping the `intentionallyClosed` gate fails it with 2, while the other 30 cases in the file stay green.
|
On pullfrog's review (#21048 (review)): good catch on stale Note 2 — and it applied twice over. Note 2 said Both are rewritten in the description. Note 1 now separates what is still true — the scheduler's fire-time re-check returns before |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟡 Minor · Retire the shared-control connection when… · remote-runtime-shared-control-reconnect.ts:63-78
src/shared/remote-runtime-shared-control-reconnect.ts:63-78
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winRetire the shared-control connection when removal is detected at reconnect fire time. The scheduler clears its timer and pending callback before invoking
open. The fire-time removal branch then returns without invokingonEnvironmentRemoved. The closed connection and its logical subscriptions can remain insharedControlConnectionsuntil another teardown path runs. Invoke the existing retirement callback in this branch. The reconnect timer itself is already cleared.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 9a587bcd-7284-410b-9db8-35ab45ed7f7b
📒 Files selected for processing (2)
src/shared/remote-runtime-shared-control-connection.test.tssrc/shared/remote-runtime-shared-control-connection.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/shared/remote-runtime-shared-control-connection.test.ts
- src/shared/remote-runtime-shared-control-connection.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
Removal was still unhandled on one path into the transport. A removal landing while a reconnect was already armed hit the scheduler's fire-time re-check, which returned before open(). Nothing dialled -- but nothing retired either, so the cached connection, its status owner, its subscriptions and the paired browser client host outlived the environment until restart. The timer is spent once it fires, and the routes that would otherwise reach open() re-resolve the store and throw for a removed id before they get there, so nothing later compensated. That re-check was added when open() had no removal gate of its own. Gating open() and retiring from that guard made it redundant in the one thing it prevented -- the dial -- and harmful in the one thing it skipped. Hand the fire to open() and let the single gate decide: it rejects waiters, retires, and returns before openSharedControlSocket, so the timer still costs no socket. Verified by mutation in four directions: restoring the re-check fails the new case with 0 retirements; deleting the retirement call fails it the same way; dropping removal from the guard condition fails it and both request-path cases; and letting the guard retire without returning fails its dial assertion with 2 sockets instead of 1.
|
Pushed
That re-check dates from when New case: Note 1 and the mutation list in the description are updated. One ordering is still not retired, and it is now stated there rather than implied: when removal is already known as the socket closes, the scheduler declines to arm a timer at all, so nothing dials and nothing retires until a later request reaches Verification after the last edit: the five affected files run 56 cases green, |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the incremental delta at 1237dcb (7e908d8..1237dcb, 2 files): the follow-up that retires the transport from the request path.
- Retired from the
open()gate — whenopen()declines a dial becauseisEnvironmentRemoved()is true, it now also callsonEnvironmentRemoved?.()(only when notintentionallyClosed), so a request finding a closed socket on a removed environment no longer leaves the cached transport, its status owner, and its subscriptions alive with no liveness monitor left to retire them. - Pinned the retirement path — the new
retires a removed environment when a request finds the socket closedcase drops the socket, confirms removal, asserts the next request rejects and retires exactly once, then asserts a second request does not re-fire. Removing the new call makes it fail (verified by mutation: 0 calls vs expected 1). - Narrowed an import — the namespace
sharedControlStateimport became a namedrejectSharedControlReadyWaitersimport; the namespace was unused elsewhere in the file.
The stale Note 2 from the prior review (open() is deliberately not gated) has been rewritten in the PR body to describe the gate and its retirement, so that informational finding is addressed. The scheduler fire-time early-return (remote-runtime-shared-control-reconnect.ts:74-76) still detects removal without retiring — the lazily-retired state documented in Note 1 — but that path predates this delta.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…et closed The scheduler's early return covered the last ordering that detected removal and retired nothing: when the environment is already gone as the socket closes, it declines to arm a timer, and a closed socket has no liveness tick left to notice. Nothing dialled, but the cached connection, its status owner, its subscriptions and the paired browser client host stayed until restart, because the routes that would otherwise reach open() re-resolve the store and throw for a removed id first. Reaching it needs the drop to land inside the ping interval that would otherwise have retired it. Hand that branch to open() as well, so both halves of the close path go through the one gate that re-asks removal: it rejects waiters, retires, and returns before openSharedControlSocket, which costs the call site no line and leaves the connection file at 300/300. Two cases moved rather than broke. The scheduler still arms nothing, so its case now pins one open() call and no second one after the backoff. The cached connection is now evicted on close instead of settling on 'closed', so the integration case waits for the entry to disappear -- a stronger assertion, since eviction is what leaves nothing behind to retry. The request-path case keeps its attribution by pausing the standing retry first, which leaves no armed timer to race it. Verified by mutation: reverting the branch to a bare return fails the new case with 0 retirements, the scheduler case with 0 calls and the integration case on the entry that never disappears; retiring without returning arms a timer for a removed environment and fails the scheduler case; and deleting the retirement call in the open() guard fails all three retirement cases.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the incremental delta at 01a1f24 (1237dcb..01a1f24, 3 files): the follow-up that retires a transport removed during its reconnect backoff.
- Handed the reconnect fire to
open()—scheduleAfterSocketClosedropped its fire-timeenvironmentRemovedwrapper and now schedulesargs.opendirectly, so a timer fire (andretryNow()) reachesopen(), which re-asks the predicate, rejects waiters, and retires instead of returning before the gate.open()still returns beforeopenSharedControlSocket, so the timer costs no dial. - Repointed the scheduler test —
drops a pending reconnect when the environment is removed during its backoffbecamefires a pending reconnect after a mid-backoff removal so open() can retire it, now assertingopenis called once. - Added an end-to-end retirement case —
retires a removed environment when its reconnect timer firesflips removal fromonDiagnosticsChangedafter the timer is armed, then asserts the retirement callback fires once and the server-sideconnectionCountstays at 1. Restoring the old fire-time gate makes it fail (verified by mutation: 0 vs 1 retirements).
The remaining ordering — removal already known when the socket closes, so no timer is armed and retirement waits for a later request — is the gap the PR body Note 1 now documents explicitly, and the scheduler's stops reconnecting once the environment is gone from the store test pins that early return as intentional.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Followed through on the gap I flagged above: The scheduler's other early return was the remaining one. When the environment is already gone as the socket closes it arms no timer, and a closed socket has no liveness tick left, so nothing dialled and nothing retired — until restart in practice, since the routes that would otherwise reach Two existing cases moved rather than broke, and both got stronger:
Mutation-checked: reverting the branch to a bare return fails the new case with 0 retirements, the scheduler case with 0 calls and the integration case as above; retiring without returning arms a timer for a removed environment and fails the scheduler case on After the last edit: the five affected files run 57 cases green, and |
…s boundary Keep one strict store contract and move the leniency to the caller that cannot report a failure to anyone. - Revert markEnvironmentUsedIfPresent: drawing the line around one error string left corrupt, unreadable and oversized store files still fatal on the same unguarded socket callback. - Add recordRuntimeEnvironmentUsage, a named main-process boundary that says lastUsedAt is advisory and swallows every store failure. Route only the three sites with no observer through it (subscription onResponse in transport- and support-routing, and the status owner's verified hook, where a throw skips settleWaiters and hangs refresh callers). Awaited request paths stay strict. - Guard onResponse/onBinary in the subscription frame router the way the sibling request router already guards validateStatus, so no consumer throw can reach the ws 'message' emitter and become main_uncaught_exception. - Drop the status-owner `capable && present` gate: pauseStandingRetry no-ops while subscriptions exist, and removal teardown belongs to stablyai#21048's watcher. Co-authored-by: mmarabel <[email protected]>
|
Sequencing note from #22517 (the crash fix your Note 5 defers): the two compose cleanly and neither blocks
#22517 originally added a Remaining overlap between the two branches is zero by file. Merge in either order. |
…CLI still responds (#22517) * fix(runtime-environments): don't crash when a server removed via the CLI still responds orca environment rm edits the environment store behind the running app, so the next ok response on a live socket called markEnvironmentUsed, which threw 'Unknown environment' out of an unguarded socket callback. Main-process callers now use markEnvironmentUsedIfPresent, which skips a missing environment and keeps every other store error; the status owner pauses shared control instead of re-establishing it for a removed server. * fix(runtime-environments): guard usage bookkeeping at the main-process boundary Keep one strict store contract and move the leniency to the caller that cannot report a failure to anyone. - Revert markEnvironmentUsedIfPresent: drawing the line around one error string left corrupt, unreadable and oversized store files still fatal on the same unguarded socket callback. - Add recordRuntimeEnvironmentUsage, a named main-process boundary that says lastUsedAt is advisory and swallows every store failure. Route only the three sites with no observer through it (subscription onResponse in transport- and support-routing, and the status owner's verified hook, where a throw skips settleWaiters and hangs refresh callers). Awaited request paths stay strict. - Guard onResponse/onBinary in the subscription frame router the way the sibling request router already guards validateStatus, so no consumer throw can reach the ws 'message' emitter and become main_uncaught_exception. - Drop the status-owner `capable && present` gate: pauseStandingRetry no-ops while subscriptions exist, and removal teardown belongs to #21048's watcher. Co-authored-by: mmarabel <[email protected]> * test(runtime-environments): cover the real socket path a consumer throw escapes The existing tests invoke the captured onResponse directly, which never touches the surface that actually kills the app. Drive a real WebSocket server through subscribeRemoteRuntimeRequest so the throw travels ws 'message' -> handleFrame -> consumer; without the frame-router guard vitest reports it as an unhandled error, which is main_uncaught_exception in production. --------- Co-authored-by: Neil <[email protected]> Co-authored-by: mmarabel <[email protected]>

ELI5
If you remove a server with the GUI trash button, Orca hangs up on it. If you remove the same server with
orca environment rm, Orca does not — the desktop app keeps the WebSocket open and keeps dialling back every time the link drops, until you restart the app. The server is gone fromorca environment list, so the only way to see the connection islsof. This makes the CLI hang up too.What Changed
The shared-control connection learns a third reason not to be connected, alongside the two it already has (
isManuallyDisconnected,isCapabilityPaused): the environment is no longer in the store.runtime-environment-removal-watch.ts(new,src/main/ipc/) answers "is this environment gone?" and owns the retirement callback.runtime-environments.tsinstalls it next to the other registrations, handing it the samegetUserDataPathevery other handler gets andinvalidateRuntimeEnvironmentTransport— literally the function the GUI removal path already passes asinvalidateTransport— as the teardown, so both removal paths converge instead of growing a second one.remote-runtime-socket-liveness.ts) checks the predicate on its own cadence. It is the only level-triggered hook an open socket has, so no new polling was introduced.SharedControlReconnectScheduler.scheduleAfterSocketCloserefuses to re-arm when the environment is gone, which covers the case where a disconnect beats the tick.max-linesceiling:publishDiagnosticsandgetDiagnosticsbuilt the identical five-field object; they now share onediagnosticsInputs().Removal is believed only on positive observation: the watch is installed, the store file exists, it parses, the id is absent from it, and that store previously listed the id. Two reasons this is strict rather than a plain
!listEnvironments().some(...):readEnvironmentStorereturns zero environments for a missing file instead of throwing, so a weaker check would retire every environment at once.getCanonicalUserDataPath, the dev redirect). An id a given store never listed says nothing about that id, so it is never judged. Where the paths diverge this degrades to today's behaviour rather than dropping a live connection.Why
orca environment rmruns in its own process and only rewritesorca-environments.json. Nothing in the app re-reads that file, and the cached connection captured its pairing at construction, so "is this environment still in the store?" was never asked anywhere.runtimeEnvironments:remove(the GUI path) already retires the transport; the CLI path had no way to reach it.Gating only the reconnect would have left the live socket up until the next network blip — the symptom in the issue is the socket that is still there right now. Since every open socket already runs a liveness timer, closing it properly cost no new machinery.
Linked Issue
Fixes #20995
Visual Proof
N/A— no UI or interaction change. This gates and retires a background transport; nothing renders differently.Testing
Platform tested: macOS (Darwin 25.6.0, Apple Silicon).
Differential proof.
src/main/ipc/runtime-environment-cli-removal.electron.test.tsboots a real Electron main process, runs the shippedregisterRuntimeEnvironmentHandlersagainst a real shared-control server, and rewrites the store from the test process — which is whatorca environment rmis. The same file onmain, without the fix:30 seconds after removal the app is still holding the socket. That is the reported bug, reproduced. On this branch the test passes, three runs in a row, and the measured latency from store rewrite to socket close is 10030 ms — one liveness interval.
To re-run the control:
Unit and integration. New cases cover the reconnect gate (with a positive control so it cannot pass vacuously), and the predicate's branches: id present, id removed, store file missing, store NUL-filled (#18766), watch not installed, id never listed by this store, and recorded-then-removed.
Mutation-tested. Every new assertion was confirmed to fail against a deliberately broken implementation, restoring from a file copy rather than
git checkout: droppingenvironmentRemovedfrom the early return; forcing the predicate tofalse; removing the liveness short-circuit; removing the construction-time observation; widening the never-listed guard to always-true; deleting the retirement call in theopen()guard, and separately dropping itsintentionallyClosedgate; restoring the scheduler's fire-time re-check; dropping removal from theopen()guard condition; letting that guard retire without returning, which dials a second socket and fails the new timer case on itsconnectionCountassertion rather than on retirement; reverting the scheduler's close branch to a bare return, which fails the new close case with 0 retirements, the scheduler case with 0 calls and the integration case on a cache entry that never disappears; and retiring from that branch without returning, which arms a timer for a removed environment.Full local run.
pnpm test: 13 tests across 8 files fail — the identical set fails on a cleanupstream/maincheckout (they need a realclaudebinary, release refs a blobless clone lacks, network/relay access, or they flag this machine's own username). Zero new failures from this branch.pnpm lint: one error, in a renderer file this branch does not touch (see Notes 6); no other errors repo-wide.pnpm run build:cliandpnpm run build:electron-viteboth succeed.Test-infra note.
remote-runtime-shared-control-test-server.tsgainsopenClientCount()(sockets open right now, unlike the cumulativeconnectionCount) andendpointPort(); the end-to-end assertion needs them.AI Disclosure
Written with Claude Opus 5 (Claude Code). The root cause analysis, implementation, tests, and the differential verification above were done in that session; every claim in this PR was checked against the code or a command output rather than taken from the model's summary.
Review
AI code review summary, per
CONTRIBUTING.md:getEnvironmentStorePathhelper. The new Electron test carries the repo'sxvfb-run --auto-servernum ... --no-sandboxwrapper on Linux, matching the other*.electron.test.tsprobes. Verified on macOS only; nothing in the change is platform-sensitive.docs/reference/remote-wire-compatibility.mddoes not apply. The two new connection options are optional, so any construction site that omits them behaves exactly as before.src/shared/changes are optional type fields only.mobile/'s own typecheck could not be run locally (its dependencies are not installed in this checkout).Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Scope limits worth knowing, stated rather than papered over:
open()is the single gate (Note 2), and the reconnect scheduler routes both of its removal branches into it rather than short-circuiting: the fire of an already-armed timer, and the close that finds the environment already gone. Each used to stop the dial and retire nothing, which left the cached connection, its status owner, its subscriptions and the paired browser client host alive until restart — the timer is spent once it fires,retryNow()replays the same callback, and the routes that would otherwise reachopen()re-resolve the store and throw for a removed id before they get there. Neither branch dials:open()rejects its waiters, retires, and returns beforeopenSharedControlSocket. The three ways in — a live socket's liveness tick, a request that finds it closed, and the scheduler's two branches — now end the same way, which is whatruntimeEnvironments:removehas always done.open()is gated on removal, and retires from there. A request arriving while the socket is down reachesensureReadyWithTimeout→openIfSocketClosed→open(), which never consults the reconnect backoff gate, so the predicate is re-asked there and the request is rejected instead of dialling a removed environment (declines a request-driven reopen once its environment is removed). That guard also fires the retirement callback, because returning early skips the liveness monitor that is otherwise the only caller of it — without this the cached transport, its status owner and its subscriptions would outlive the environment (retires a removed environment when a request finds the socket closed). Both live inremote-runtime-shared-control-connection.ts:168-179, and the file stays at exactly 300/300 of the*.tsmax-linesceiling, whichAGENTS.mdforbids disabling.orca serve.RuntimeHostStatusOwner.complete()callsmarkEnvironmentUsed, which throws, skippingsettleWaiters()and leaving anyrefresh()waiter hanging until its own timeout. Separate issue; out of scope for this one.mainbreakage, not from this branch.src/renderer/src/components/native-chat/NativeChatMessageList.windowing.test.tsx:12has an unused import (from Native chat keeps scrolling to bottom #20898), which fails bothpnpm lintand the web project ofpnpm typecheck, and thereforepnpm buildtoo, sincebuild:desktopruns typecheck first. Reproduced on a cleanmaincheckout. This branch does not touchsrc/renderer/ormobile/at all, andoxlintreports no other errors anywhere in the repo. CI will be red on those jobs until it is fixed upstream; happy to rebase once it is.Author
GitHub: @GodCC6 · X: @Cccanon52
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred) — see Notes 6: all four were run locally;lint,typecheckandbuildstop on one pre-existing error onmainin a file this branch does not touch, so this box is left honest rather than ticked. Details below.