Skip to content

fix(runtime-environments): prune orphaned terminal host session when an environment is removed - #9514

Open
dogfooter8750 wants to merge 6 commits into
stablyai:mainfrom
dogfooter8750:fix/prune-removed-runtime-host-workspace-session
Open

dogfooter8750 wants to merge 6 commits into
stablyai:mainfrom
dogfooter8750:fix/prune-removed-runtime-host-workspace-session

Conversation

@dogfooter8750

@dogfooter8750 dogfooter8750 commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Retire the exact 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.
  • Repair already-orphaned runtime partitions before the first window loads. Cleanup requires a successfully read, valid environment registry; missing, unreadable, corrupt, or unsupported registries preserve saved sessions.
  • Preserve local/SSH partitions, saved runtime environments, and folder workspace tabs. Disconnect does not retire a session. Reuse the existing Store domains, debounced writes, registry parser, and metadata-prune invalidation.

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

  • Automated tests added/updated.
  • Manual desktop testing.

Validated against main eedd35645e585e9d257d702e5f8a90733953d600 on macOS with ORCA_BACKGROUND_LAUNCH=1:

  • Persistence and environment suites: 1,019 passed, 1 existing skip across 96 files; final focused suite: 13 passed.
  • pnpm tc:node and all three changed-code quality checks pass.
  • A 512-orphan fixture retains only the saved runtime, local, and SSH partitions after cleanup.
  • Removing cleanup fails 8 regressions; removing the write fence fails 7; allowing a missing registry to read as empty fails 2. Restored implementation passes.
  • Tests cover real Store persistence/reload, missing/disappearing registry reads, removal-write failure, disconnect, canonical environment IDs, VM cleanup, and late writes. No Electron app or native-focus test was launched.

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

  • Not applicable; no upstream skill-installer material copied or translated.

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 rm run 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

  • Problem, scope, and validation explained.
  • Cross-platform, SSH/runtime, and folder-workspace behavior considered.
  • Targeted tests, Node typecheck, and changed-code quality pass.
  • Full application build and other-platform CI.

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

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The 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 71165

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 19 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning 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 … Add the linked issue reference in the required format, such as Fixes #123``, or create and link an issue that tracks the removed-environment subscribe loop. Preserve the existing explanation if the issue is created after this review.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly describes the primary removal-time cleanup change. It is concise and related to the pull request scope, although it does not mention startup pruning.
Full details: Description check

Explanation

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.

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 9784f658-f40d-44ef-8078-61e2a6ee6931

📥 Commits

Reviewing files that changed from the base of the PR and between e90dc38 and 7b5f884.

📒 Files selected for processing (8)
  • 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
  • src/main/runtime-environment-host-session-self-heal.test.ts
  • src/main/runtime-environment-host-session-self-heal.ts

Comment on lines +32 to +57
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ 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.ts

Repository: 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]>

@dogfooter8750 dogfooter8750 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

completed

@AmethystLiang
AmethystLiang requested a review from Jinwoo-H July 20, 2026 18:25
@AmethystLiang AmethystLiang assigned OrcaWin and unassigned Jinwoo-H Jul 20, 2026
@AmethystLiang
AmethystLiang requested review from OrcaWin and removed request for Jinwoo-H July 20, 2026 18:35
@AmethystLiang AmethystLiang added the orca-remote-server Remote Orca Server / orca serve / paired remote runtime label Jul 22, 2026
…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]>
@nwparker nwparker added the bug Something isn't working label Jul 27, 2026
m4air and others added 3 commits September 11, 2026 23:06
…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.

@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: e5832c46-46a4-46a6-8ba4-f849472d1604

📥 Commits

Reviewing files that changed from the base of the PR and between 42b1505 and 7116511.

📒 Files selected for processing (19)
  • src/main/ipc/ephemeral-vm-runtime-handlers.ts
  • src/main/ipc/ephemeral-vm.test.ts
  • src/main/ipc/runtime-environment-connectivity-handlers.ts
  • src/main/ipc/runtime-environment-removal-storage.test.ts
  • src/main/ipc/runtime-environments-call-routing.test.ts
  • src/main/ipc/runtime-environments-capability-cache.test.ts
  • src/main/ipc/runtime-environments-pairing.test.ts
  • src/main/ipc/runtime-environments-status-diagnostics.test.ts
  • src/main/ipc/runtime-environments-subscription-lifecycle.test.ts
  • src/main/ipc/runtime-environments-subscription-routing.test.ts
  • src/main/ipc/runtime-environments-subscription-teardown.test.ts
  • src/main/persistence-retired-runtime-host-sessions.test.ts
  • src/main/persistence/loading-store/pty-binding-persistence.ts
  • src/main/persistence/loading-store/session-host-partitions.ts
  • src/main/persistence/loading-store/session-snapshot-operations.ts
  • src/main/runtime-environment-host-session-self-heal.test.ts
  • src/main/runtime-environment-host-session-self-heal.ts
  • src/main/startup/main-process-ready-foundation.ts
  • src/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]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

🔎 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/main

Repository: 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 260

Repository: 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.

Suggested change
delete next[hostId]
delete next[key]

@nwparker

Copy link
Copy Markdown
Contributor

@dogfooter8750 this is legit, but how much is it bothering you? Just prioritizing

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

bug Something isn't working orca-remote-server Remote Orca Server / orca serve / paired remote runtime

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants