Repository navigation
fix(runtime-environments): prune orphaned terminal host session when an environment is removed - #9514
Conversation
…an environment is removed Removing a runtime environment left its `workspaceSessionsByHostId["runtime:<id>"]` partition behind in the persisted store. On the next launch the renderer restored those terminal tabs and resubscribed against the now-unknown environment, so the main `runtimeEnvironments:subscribe` handler rejected every attempt with `Unknown environment: <id>` — flooding the renderer with errors that look like an infinite loop. Fix, mirroring the existing `selfHealRuntimeEnvironmentFocus` precedent: - Add `Store.deleteHostWorkspaceSession` and `Store.pruneOrphanedRuntimeHostWorkspaceSessions`. Both only touch `runtime:` host partitions; `local` and `ssh:` partitions are never removed. - Add `selfHealRuntimeHostWorkspaceSessions`, wired into boot right after the focus self-heal (before the main window loads), so orphaned partitions are gone before the renderer can restore them. This repairs installs that were already broken by a removal in an older build, with no user action. It skips pruning when the environment registry file is absent so a transient absence never wipes a surviving host's sessions. - Prune-on-remove in the `runtimeEnvironments:remove` IPC handler and the ephemeral-VM cleanup path, so a removal while the app is running never persists a stale partition. `disconnect` stays non-destructive. Adds unit + integration coverage for the two Store methods, the boot self-heal (including the missing-registry guard), and the remove/disconnect IPC behavior. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
📝 WalkthroughWalkthroughThe change retires runtime host workspace sessions when environments are removed. It blocks later session, snapshot, and PTY writes to retired hosts. Startup now prunes orphaned runtime host sessions after validating the environment registry. Environment cleanup and removal handlers delete matching sessions. Tests cover persistence fencing, startup self-healing, lifecycle ordering, and unchanged disconnect behavior. Priority: ⬇️ Low Merge Risk: 🟡 Moderate · up to Some orphaned runtime terminal sessions can survive startup cleanup and return after reload when their stored host key contains whitespace. This cleanup regression should be fixed before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description is detailed and covers the change, rationale, testing, limitations, and checklist. However, the required Linked Issue section does not provide an issue link and explicitly states that no separate issue exists.
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: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 9784f658-f40d-44ef-8078-61e2a6ee6931
📒 Files selected for processing (8)
src/main/index.tssrc/main/ipc/ephemeral-vm-runtime-handlers.tssrc/main/ipc/runtime-environments.test.tssrc/main/ipc/runtime-environments.tssrc/main/persistence.test.tssrc/main/persistence.tssrc/main/runtime-environment-host-session-self-heal.test.tssrc/main/runtime-environment-host-session-self-heal.ts
| export function selfHealRuntimeHostWorkspaceSessions({ | ||
| store, | ||
| userDataPath, | ||
| listKnownEnvironments = listEnvironments, | ||
| environmentStoreExists = (path) => existsSync(getEnvironmentStorePath(path)), | ||
| log | ||
| }: SelfHealRuntimeHostWorkspaceSessionsArgs): void { | ||
| // Why: listEnvironments returns [] for a MISSING registry file (it only throws | ||
| // for a corrupt one). A transiently-absent file at boot (e.g. a mount/sync | ||
| // race) must not be read as "zero saved environments" and permanently wipe | ||
| // every runtime host's terminal session — deleting a host session is not | ||
| // recoverable, unlike the focus id the sibling self-heal clears. So skip | ||
| // pruning entirely unless the registry file actually exists; a genuinely | ||
| // empty-but-present registry still prunes correctly. | ||
| if (!environmentStoreExists(userDataPath)) { | ||
| return | ||
| } | ||
|
|
||
| let environments: KnownRuntimeEnvironment[] | ||
| try { | ||
| environments = listKnownEnvironments(userDataPath) | ||
| } catch { | ||
| // Why: an unreadable/corrupt registry must not delete possibly-valid host | ||
| // sessions; keep them and let a later launch heal once it reads again. | ||
| return | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Inspect listEnvironments' handling of missing vs. corrupt registry files.
fd 'runtime-environment-store' --extension ts
rg -n -A 20 'export function listEnvironments' src/main/shared/runtime-environment-store.ts 2>/dev/null || rg -n -A 20 'export function listEnvironments'Repository: stablyai/orca
Length of output: 236
🏁 Script executed:
#!/bin/bash
set -euo pipefail
ast-grep outline src/shared/runtime-environment-store.ts --view expanded || true
printf '\n--- FILE ---\n'
wc -l src/shared/runtime-environment-store.ts src/shared/runtime-environment-store.test.ts
printf '\n--- TARGETED READ: runtime-environment-store.ts ---\n'
sed -n '1,220p' src/shared/runtime-environment-store.ts
printf '\n--- TARGETED READ: runtime-environment-store.test.ts ---\n'
sed -n '1,260p' src/shared/runtime-environment-store.test.tsRepository: stablyai/orca
Length of output: 12359
Avoid the existence check here
listEnvironments() returns [] when orca-environments.json is missing, so if the file disappears between environmentStoreExists() and this call, the self-heal path still treats it as “no environments” and can wipe all runtime host sessions. Read the registry once and distinguish missing from empty instead.
…string coverage Extract the registry-existence check into a documented runtimeEnvironmentStoreExists helper and replace the inline .map arrow with an explicit loop, so every function in the new module carries a docstring (addresses CodeRabbit's docstring-coverage check). No behavior change; existing tests still pass. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ring coverage Add docstrings to the `environment` and `makeStore` test helpers so the new module's docstring coverage crosses CodeRabbit's 80% threshold. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…f-9514 # Conflicts: # src/main/index.ts # src/main/ipc/ephemeral-vm-runtime-handlers.ts # src/main/ipc/runtime-environments.test.ts # src/main/ipc/runtime-environments.ts # src/main/persistence.test.ts # src/main/persistence.ts
…g pruned hosts - Skip the startup orphan prune when orca-environments.json parses but lists zero environments; a lost concurrent write (desktop + CLI both rewrite the file without locking) would otherwise wipe every runtime terminal partition. - Log the prune at warn level with the count and the pruned host ids so a user who loses tabs can find out why. - Regression tests: valid-but-empty registry preserves partitions; pruned host ids appear in the log.
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: e5832c46-46a4-46a6-8ba4-f849472d1604
📒 Files selected for processing (19)
src/main/ipc/ephemeral-vm-runtime-handlers.tssrc/main/ipc/ephemeral-vm.test.tssrc/main/ipc/runtime-environment-connectivity-handlers.tssrc/main/ipc/runtime-environment-removal-storage.test.tssrc/main/ipc/runtime-environments-call-routing.test.tssrc/main/ipc/runtime-environments-capability-cache.test.tssrc/main/ipc/runtime-environments-pairing.test.tssrc/main/ipc/runtime-environments-status-diagnostics.test.tssrc/main/ipc/runtime-environments-subscription-lifecycle.test.tssrc/main/ipc/runtime-environments-subscription-routing.test.tssrc/main/ipc/runtime-environments-subscription-teardown.test.tssrc/main/persistence-retired-runtime-host-sessions.test.tssrc/main/persistence/loading-store/pty-binding-persistence.tssrc/main/persistence/loading-store/session-host-partitions.tssrc/main/persistence/loading-store/session-snapshot-operations.tssrc/main/runtime-environment-host-session-self-heal.test.tssrc/main/runtime-environment-host-session-self-heal.tssrc/main/startup/main-process-ready-foundation.tssrc/shared/runtime-environment-store.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| continue | ||
| } | ||
| context.retiredRuntimeHostIds.add(hostId) | ||
| delete next[hostId] |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="$(fd -a '^execution-host\.ts$' | head -n 1)"
ast-grep outline "$file" --items all --match 'normalizeHostPart|normalizeExecutionHostId|parseExecutionHostId' --view expanded
rg -n -C 8 '\bfunction\s+normalizeHostPart\b|\bworkspaceSessionsByHostId\b' "$file" src/mainRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- session-host-partitions.ts ---'
sed -n '1,135p' src/main/persistence/loading-store/session-host-partitions.ts
printf '%s\n' '--- execution-host.ts ---'
sed -n '45,135p' src/shared/execution-host.ts
printf '%s\n' '--- direct tests for whitespace/alias keys ---'
rg -n -C 6 'workspaceSessionsByHostId|normalizeExecutionHostId|parseExecutionHostId|runtime:' src/main/persistence/*test.ts src/main/persistence/loading-store/*test.ts src/shared/*test.ts | head -n 260Repository: stablyai/orca
Length of output: 31182
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings
Length of output: 19127
Delete the original persisted key.
normalizeExecutionHostId(key) trims whitespace, so an accepted key such as ' runtime:env-a ' becomes runtime:env-a. Line 102 deletes next[hostId], leaving the original key in next while the method reports it as removed and persists the orphan.
context.retiredRuntimeHostIds.add(hostId)
- delete next[hostId]
+ delete next[key]
removed.push(hostId)Keep the canonical hostId for fencing and return. Add a regression case for a whitespace-padded runtime key.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| delete next[hostId] | |
| delete next[key] |
|
@dogfooter8750 this is legit, but how much is it bothering you? Just prioritizing |
ELI5
Deleting a saved runtime environment left its terminal tabs in storage. Restarting Orca restored those tabs and repeatedly subscribed to a server it no longer knew. Removal now retires that host's saved session, and startup cleans up partitions left by older builds.
What Changed
runtime:<environmentId>session after successful removal, including ephemeral-VM cleanup. Late full snapshots, patches, unload saves, and PTY bindings cannot recreate it in the same Store.Why
A one-time deletion can be undone by a queued renderer save. Store-scoped retirement fences those writes. The registry reader's new optional strict mode avoids treating a file that disappears between an existence check and a read as an empty registry; ordinary registry readers retain their existing behavior.
Linked Issue
No separate linked issue; this PR addresses the removed-environment subscribe loop described above.
Visual Proof
N/A — persistence and startup cleanup; no UI components or interaction design changed.
Testing
Validated against main
eedd35645e585e9d257d702e5f8a90733953d600on macOS withORCA_BACKGROUND_LAUNCH=1:pnpm tc:nodeand all three changed-code quality checks pass.AI Disclosure
Codex updated the contributor branch for the current Store/IPC architecture, added late-write fencing and strict registry reads, and ran the checks above. Original contributor history is preserved.
Review
Self-reviewed; no new human review or all-platform CI result is claimed.
Agent skill upstream boundary
Notes
This retires client-side saved session state. It does not stop or infer the death of remote processes. Current readers still preserve sessions when registry membership cannot be established. Retired environment IDs remain in a Store-local set until that Store closes; re-adding a removed environment creates a new environment ID.
Stale runtime-owned repository/sidebar rows remain outside this terminal-session fix.
Known gap:
orca environment rmrun while the desktop app is open only rewrites the registry file. The running app keeps its in-memory environment, so it continues subscribing to and saving sessions for the removed server until it restarts; the startup pass then prunes the orphaned partition. The registry has no locking and no change watcher, so closing this needs a file watcher or IPC notification and is left for a follow-up.Safety valve: the startup prune refuses to run when the registry parses but lists zero environments (a lost concurrent write between the desktop app and the CLI could produce that state), and it logs the pruned host ids at warn level.
Checklist