Skip to content

fix(runtime-environments): retire transports for CLI-removed environments - #21048

Open
GodCC6 wants to merge 8 commits into
stablyai:mainfrom
GodCC6:fix/environment-rm-stops-reconnect
Open

GodCC6 wants to merge 8 commits into
stablyai:mainfrom
GodCC6:fix/environment-rm-stops-reconnect

Conversation

@GodCC6

@GodCC6 GodCC6 commented Sep 16, 2026 •

Copy link
Copy Markdown

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 from orca environment list, so the only way to see the connection is lsof. 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.ts installs it next to the other registrations, handing it the same getUserDataPath every other handler gets and invalidateRuntimeEnvironmentTransport — literally the function the GUI removal path already passes as invalidateTransport — as the teardown, so both removal paths converge instead of growing a second one.
  • The socket's existing 10s liveness heartbeat (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.scheduleAfterSocketClose refuses to re-arm when the environment is gone, which covers the case where a disconnect beats the tick.
  • Drive-by in the same file, required by its 300-line max-lines ceiling: publishDiagnostics and getDiagnostics built the identical five-field object; they now share one diagnosticsInputs().

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(...):

  • readEnvironmentStore returns zero environments for a missing file instead of throwing, so a weaker check would retire every environment at once.
  • Some callers resolve environments from a different user-data path (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 rm runs in its own process and only rewrites orca-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.ts boots a real Electron main process, runs the shipped registerRuntimeEnvironmentHandlers against a real shared-control server, and rewrites the store from the test process — which is what orca environment rm is. The same file on main, without the fix:

× drops the live socket the desktop app was holding and never reconnects
  Timed out waiting for the removed environment to lose its socket (open=1)

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:

git switch -c verify-control main
git checkout <this-branch> -- \
  src/main/ipc/runtime-environment-cli-removal.electron.test.ts \
  src/shared/remote-runtime-shared-control-test-server.ts
pnpm test src/main/ipc/runtime-environment-cli-removal.electron.test.ts   # must fail

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: dropping environmentRemoved from the early return; forcing the predicate to false; removing the liveness short-circuit; removing the construction-time observation; widening the never-listed guard to always-true; deleting the retirement call in the open() guard, and separately dropping its intentionallyClosed gate; restoring the scheduler's fire-time re-check; dropping removal from the open() guard condition; letting that guard retire without returning, which dials a second socket and fails the new timer case on its connectionCount assertion 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 clean upstream/main checkout (they need a real claude binary, 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:cli and pnpm run build:electron-vite both succeed.

Test-infra note. remote-runtime-shared-control-test-server.ts gains openClientCount() (sockets open right now, unlike the cumulative connectionCount) and endpointPort(); the end-to-end assertion needs them.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

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:

  • Cross-platform (macOS / Linux / Windows) — pure logic, no platform branches. Paths go through the existing getEnvironmentStorePath helper. The new Electron test carries the repo's xvfb-run --auto-servernum ... --no-sandbox wrapper on Linux, matching the other *.electron.test.ts probes. Verified on macOS only; nothing in the change is platform-sensitive.
  • Remote / SSH / local — the execution host is untouched. This changes only the client's local decision about whether to hold a transport, not what it reports about remote work, and no verdict vocabulary is involved.
  • Agents, integrations, git providers — not touched; nothing here is provider- or agent-specific.
  • Backwards compatibility / wire — no RPC params, stream frames, or published content change, so docs/reference/remote-wire-compatibility.md does not apply. The two new connection options are optional, so any construction site that omits them behaves exactly as before.
  • Performance — one synchronous store read per connection per ~10s liveness tick, plus one per socket close. Secure-file hardening is cached per process, though the cache is invalidated when the CLI rewrites the file (new inode). Worst case is N environments re-reading the same ≤1 MB file once per tick. Called out in Notes rather than optimised, since correctness here is cheap and the read is already how every other environment lookup works.
  • Security — no new file, network, or credential surface. The predicate only reads a store the process already reads, and it fails closed toward "stay connected", never toward acting on an unreadable or foreign store.
  • UI — not applicable.
  • Mobile — 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

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and 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:

  1. Every path that observes the removal now retires. 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 reach open() re-resolve the store and throw for a removed id before they get there. Neither branch dials: open() rejects its waiters, retires, and returns before openSharedControlSocket. 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 what runtimeEnvironments:remove has always done.
  2. open() is gated on removal, and retires from there. A request arriving while the socket is down reaches ensureReadyWithTimeout → 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 in remote-runtime-shared-control-connection.ts:168-179, and the file stays at exactly 300/300 of the *.ts max-lines ceiling, which AGENTS.md forbids disabling.
  3. Store read cost — see Performance above.
  4. Not covered by the end-to-end test: the "drops first, then removed, must not reconnect" ordering. That half is covered by the integration test plus mutation, not by the real app. The end-to-end peer is the repo's shared-control test server — it speaks the real e2ee handshake and is what every other shared-control test uses, but it is not a real orca serve.
  5. Not fixed here, found while tracing — for a removed environment, RuntimeHostStatusOwner.complete() calls markEnvironmentUsed, which throws, skipping settleWaiters() and leaving any refresh() waiter hanging until its own timeout. Separate issue; out of scope for this one.
  6. Pre-existing main breakage, not from this branch. src/renderer/src/components/native-chat/NativeChatMessageList.windowing.test.tsx:12 has an unused import (from Native chat keeps scrolling to bottom #20898), which fails both pnpm lint and the web project of pnpm typecheck, and therefore pnpm build too, since build:desktop runs typecheck first. Reproduced on a clean main checkout. This branch does not touch src/renderer/ or mobile/ at all, and oxlint reports 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

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred) — see Notes 6: all four were run locally; lint, typecheck and build stop on one pre-existing error on main in a file this branch does not touch, so this box is left honest rather than ticked. Details below.

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

coderabbitai Bot commented Sep 16, 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
📝 Walkthrough

Walkthrough

The 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 1237d

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.65% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 13 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The description links the change to issue #20995 with a valid Fixes #20995`` reference, and the implementation directly addresses that issue.
Out of Scope Changes check ✅ Passed The changes remain focused on retiring transports for CLI-removed environments. The added tests, test-server helpers, reconnect guards, and diagnostics deduplication support the stated objective and d…
Title check ✅ Passed The title clearly and concisely describes the main change: retiring transports for environments removed through the CLI.
Description check ✅ Passed The description is complete and follows the required template. It explains the user impact, implementation, rationale, linked issue, testing, platform considerations, scope limits, and known pre-exist…
  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: e6f950fa-4881-4b31-88fb-a56c0b60af26

📥 Commits

Reviewing files that changed from the base of the PR and between 0b28d35 and f4f56ab.

📒 Files selected for processing (13)
  • src/main/ipc/runtime-environment-cli-removal.electron.test.ts
  • src/main/ipc/runtime-environment-removal-watch.test.ts
  • src/main/ipc/runtime-environment-removal-watch.ts
  • src/main/ipc/runtime-environment-request-connections.test.ts
  • src/main/ipc/runtime-environment-request-connections.ts
  • src/main/ipc/runtime-environments.ts
  • src/shared/remote-runtime-shared-control-connection.test.ts
  • src/shared/remote-runtime-shared-control-connection.ts
  • src/shared/remote-runtime-shared-control-open.ts
  • src/shared/remote-runtime-shared-control-reconnect.test.ts
  • src/shared/remote-runtime-shared-control-reconnect.ts
  • src/shared/remote-runtime-shared-control-test-server.ts
  • src/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.

@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 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 a storedEnvironmentIds positive-observation set; missing/unreadable/foreign stores stay connected.
  • Shared-control retirement hooks — optional isEnvironmentRemoved / onEnvironmentRemoved; the liveness ping invokes onRetired when isRetired is true; scheduleAfterSocketClose gains an environmentRemoved gate with a positive-control test.
  • Main wiring — runtime-environments.ts installs the watch with invalidateRuntimeEnvironmentTransport before the startup activate() loop; getSharedControlConnection records the id at construction.
  • Drive-by — diagnosticsInputs() now backs both publishDiagnostics and getDiagnostics.
  • 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?

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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.
@GodCC6

GodCC6 commented Sep 16, 2026

Copy link
Copy Markdown
Author

On the docstring-coverage pre-merge check (18.75% against an 80% threshold): I am deliberately not acting on this one.

AGENTS.md in this repo asks for the opposite — "Concise/Brief Non-obvious Comments ONLY: do not be verbose, do not explain the obvious, WHY not HOW, 1 line if possible". Adding docstrings to the sixteen touched functions to clear a coverage threshold would mean writing exactly the kind of comment the repo's own style guide rules out.

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.

@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 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, and getRuntimeEnvironmentStatusOwner calls it with userDataPath right after resolveEnvironment succeeds, 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's environmentRemoved is now a thunk, and the open handed 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?

Pullfrog  | Fix it ➔ | View workflow run | Using 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.

@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

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 resolveElectronProbeLaunch instead of hand-rolling the Linux xvfb-run wrapper, so it reuses an inherited DISPLAY and stops racing sibling probes for a display number.
  • Imported the production liveness cadence — the local LIVENESS_PING_INTERVAL_MS = 10_000 is gone; both the socket-loss wait and the post-close delay now track REMOTE_RUNTIME_SOCKET_PING_INTERVAL_MS.
  • Pinned the previously untested listed branch — a new judges a removal seen only through repeated checks, with no resolve recorded case records an id only from a listed check, so deleting the storedEnvironmentIds.add in isRuntimeEnvironmentRemoved now 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.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (1)

🟠 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 win

Guard request-driven readiness after removal. When a socket is in reconnect backoff, SharedControlReconnectScheduler only skips the delayed open; it does not invalidate the cached connection. executeSupportRoutedCall can retain the environment across supportsSharedControl and then call sendRemoteRuntimeSharedControlRequest. The cached connection then reaches ensureReadyWithTimeout and openIfSocketClosed, which calls open() 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

📥 Commits

Reviewing files that changed from the base of the PR and between 639e0e0 and 78b942c.

📒 Files selected for processing (2)
  • src/main/ipc/runtime-environment-cli-removal.electron.test.ts
  • src/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.

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 43348bb6-8da9-42cc-add1-898c9665d6b5

📥 Commits

Reviewing files that changed from the base of the PR and between 78b942c and 7e908d8.

📒 Files selected for processing (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.

@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

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 through ensureReadyWithTimeout, bypassing the reconnect backoff gate. open() now declines that path when isEnvironmentRemoved() 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 removed drops the socket, confirms removal, then asserts the next request rejects and the server-side connectionCount stays at 1. 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.

Pullfrog  | View workflow run | Using 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.
@GodCC6

GodCC6 commented Sep 18, 2026

Copy link
Copy Markdown
Author

On pullfrog's review (#21048 (review)): good catch on stale Note 2 — and it applied twice over.

Note 2 said open() is deliberately not gated. 7e908d883 reversed that by gating it, and 1237dcb5d went further: the guard fires the retirement callback too, because declining the dial skips the liveness monitor that is otherwise the callback's only production caller. Note 1 rested on the same assumption ("only the liveness path calls retire", state "persists until restart"), so it was stale for the same reason.

Both are rewritten in the description. Note 1 now separates what is still true — the scheduler's fire-time re-check returns before open(), and retryNow() replays that same gated callback, so no timer retires — from what changed: the first dial after removal clears the cached transport, which makes retirement lazy rather than restart-bound. If nothing ever dials, the inert entry still persists; that is stated rather than papered over.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (1)

🟡 Minor · 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 win

Retire 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 invoking onEnvironmentRemoved. The closed connection and its logical subscriptions can remain in sharedControlConnections until 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7e908d8 and 1237dcb.

📒 Files selected for processing (2)
  • src/shared/remote-runtime-shared-control-connection.test.ts
  • src/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.
@GodCC6

GodCC6 commented Sep 18, 2026

Copy link
Copy Markdown
Author

Pushed 01a1f24f5c, which closes the remaining case where removal was detected and nothing was retired.

scheduleAfterSocketClose re-asked the removal predicate when its backoff timer fired and returned before open(). That stopped the dial, but it was also the only thing left that would have run: the timer is spent once it fires, retryNow() replays the same callback, and the routes that would otherwise reach open() re-resolve the store and throw for a removed id before they get there. So a removal landing mid-backoff left the cached connection, its status owner, its subscriptions and the paired browser client host alive until restart.

That re-check dates from when open() had no removal gate of its own. Now that it has one that also retires, the re-check is redundant in the one thing it prevented — the dial — and harmful in the one thing it skipped, so the fire is handed straight to open(): it rejects waiters, retires, and returns before openSharedControlSocket, so the timer still costs no socket. Net −6 lines in the scheduler, and no production change in the connection file, which stays at exactly 300/300.

New case: retires a removed environment when its reconnect timer fires. It flips the predicate from the diagnostics callback, which is published right after the timer is armed, so the removal deterministically lands in the window between arming and firing. Mutation-checked four ways: restoring the re-check fails it with 0 retirements; deleting the retirement call fails it the same way; dropping removal from the open() guard condition fails it and both request-path cases; and letting the guard retire without returning fails its connectionCount assertion with 2 sockets instead of 1, which is what keeps that assertion from being decoration. The scheduler's own case was retargeted from "drops a pending reconnect" to "fires it so open() can retire", so re-adding the gate goes red there too.

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 open(). It needs the drop to land inside the ≤10s window before the liveness tick that would otherwise have retired it, and the leftover state is inert. Happy to close it here as well — it wants the same treatment at that earlier return, and it would change what retires a removed environment when a request finds the socket closed currently attributes retirement to, so I left it visible rather than folding it in unasked.

Verification after the last edit: the five affected files run 56 cases green, tc:node, tc:cli, oxlint and the changed-code quality gate are clean.

@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

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 — when open() declines a dial because isEnvironmentRemoved() is true, it now also calls onEnvironmentRemoved?.() (only when not intentionallyClosed), 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 closed case 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 sharedControlState import became a named rejectSharedControlReadyWaiters import; 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.

Pullfrog  | View workflow run | Using 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.

@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

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() — scheduleAfterSocketClose dropped its fire-time environmentRemoved wrapper and now schedules args.open directly, so a timer fire (and retryNow()) reaches open(), which re-asks the predicate, rejects waiters, and retires instead of returning before the gate. open() still returns before openSharedControlSocket, so the timer costs no dial.
  • Repointed the scheduler test — drops a pending reconnect when the environment is removed during its backoff became fires a pending reconnect after a mid-backoff removal so open() can retire it, now asserting open is called once.
  • Added an end-to-end retirement case — retires a removed environment when its reconnect timer fires flips removal from onDiagnosticsChanged after the timer is armed, then asserts the retirement callback fires once and the server-side connectionCount stays 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.

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

@GodCC6

GodCC6 commented Sep 18, 2026

Copy link
Copy Markdown
Author

Followed through on the gap I flagged above: dd807b8fc5 closes it, so no ordering is left that observes the removal and retires nothing.

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 open() re-resolve the store and throw for a removed id first. That branch is now handed to open() as well, which rejects waiters, retires, and returns before openSharedControlSocket. Both halves of the close path therefore go through the one gate that re-asks removal. The call site gains no line and the connection file stays at 300/300.

Two existing cases moved rather than broke, and both got stronger:

  • never retries a connection whose environment the CLI removed from the store waited for the cached transport to settle on closed. It is now evicted instead, so the case waits for the cache entry to disappear — eviction is the thing that leaves nothing behind to retry, and reverting the branch fails it on an entry that never goes away.
  • retires a removed environment when a request finds the socket closed kept its attribution by pausing the standing retry before the removal lands, which leaves no armed timer to race the request. That removes a timing assumption the case previously relied on.

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 isScheduled; deleting the retirement call in the open() guard fails all three retirement cases.

After the last edit: the five affected files run 57 cases green, and src/shared/ plus src/main/ipc/ — every suite the change can reach — run 12 250 cases with no failures. tc:node, tc:cli, oxlint, oxfmt --check and the changed-code quality gate are clean. Note 1 and the mutation list in the description are updated to match.

nwparker added a commit to mmarabel/orca that referenced this pull request Sep 25, 2026
…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]>
@nwparker

Copy link
Copy Markdown
Contributor

Sequencing note from #22517 (the crash fix your Note 5 defers): the two compose cleanly and neither blocks
the other.

#22517 originally added a capable && present gate in runtime-environment-status-owner.ts that routed
through pauseRemoteRuntimeSharedControlRetry, overlapping your removal policy in
runtime-environment-request-connections.ts. That gate has been removed, so #22517 no longer touches
runtime-environment-request-connections.ts, remote-runtime-shared-control-connection.ts, or
runtime-environment-status-owner.ts's establish/pause logic. Removal policy stays single-owner in your
runtime-environment-removal-watch.ts.

Remaining overlap between the two branches is zero by file. Merge in either order.

nwparker added a commit that referenced this pull request Sep 25, 2026
…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]>

This branch has not been deployed

No deployments
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.

[Bug]: orca environment rm does not stop the connection — the running app keeps reconnecting to the removed environment until restart

2 participants