Skip to content

fix(runtime): stop a throwing client-event listener from wedging worktree sleep + harden fan-out - #10052

Merged
OrcaWin merged 2 commits into
mainfrom
fix/worktree-sleep-mutation-leak
Jul 23, 2026
Merged

OrcaWin merged 2 commits into
mainfrom
fix/worktree-sleep-mutation-leak

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Sleeping a workspace failed with "Failed to sleep workspace — The host could not confirm terminal shutdown." Persistent (survived retries), hit both the local host and a paired remote client, and only cleared on app restart.

Root cause — a regression from #9874

The sleep RPC (sleepResolvedWorktreeTerminals) must first acquire a per-worktree terminal mutation before it can stop any PTY. That mutation was leaked by the sibling acquirer acquireWorktreeTerminalSpawn, added by #9874:

const release = await this.acquireWorktreeTerminalMutation(worktreeId) // mutation taken
// ...
this.emitClientEvent({ ...phase: 'woken'... })                        // fallible, runs BEFORE returning release
return release

emitClientEvent fanned out to every subscriber with no error isolation (long-standing, since #4715). The only production subscriber is the streaming-RPC emit in runtime.clientEvents.subscribe that forwards each event to a connected client. When that emit throws synchronously — a paired/remote client whose stream is broken/closed — the throw escaped acquireWorktreeTerminalSpawn after it took the mutation but before returning the release. The caller in src/main/ipc/pty.ts never received the release, so its finally { releaseWorktreeSpawn?.() } was a no-op and the mutation stayed pending forever. Every later sleep then blocked on it for WORKTREE_TERMINAL_SLEEP_TIMEOUT_MS (12s) and threw terminal_worktree_sleep_timeout → the toast.

The unguarded fan-out was a dormant footgun for over a year; #9874 made it exploitable by adding the first caller that holds a lock across the emit. Not platform-specific — it correlates with a client being attached, not with Windows (Windows just surfaced the daemon-log evidence).

Diagnostic evidence: daemon.log showed the wedged worktree's PTY sessions were never killed (no session-killed events) though the daemon was healthy and killed other worktrees' sessions seconds later — i.e. sleep failed before issuing any stop, exactly at the mutation gate, and worktree-scoped.

Fix

  1. Targeted fix: isolate listeners in emitClientEvent so a throwing subscriber can't abort the emitting operation or leak the mutation.
  2. Systemic hardening: the same footgun existed unguarded across every runtime listener fan-out (mobile-notification, pty-data, pty-driver, pty-resize, fit-override). Introduce notifyRuntimeListeners(listeners, deliver, context) and route the low-frequency fan-outs through it; the terminal-output hot path keeps an inlined try/catch to avoid a per-chunk closure allocation.

Tests

  • releases the worktree terminal mutation when a wake client-event listener throws — reproduces the exact wedge; fails on revert (mutation leaks, relay_send_failed propagates), passes with the fix.
  • isolates a throwing subscriber across runtime listener fan-out — proves the shared helper keeps sibling fan-outs (mobile notifications) alive past a throwing subscriber.

Verification

  • New tests pass; fail on revert.
  • orca-runtime.test.ts: 852 pass (1 pre-existing, unrelated Windows \tmp path-separator failure in preserves existing badgeColor on runtime createRepo dedupe, present on main).
  • oxlint + tsc --noEmit -p config/tsconfig.node.json: clean.

…tree sleep

A synchronously-throwing client-event subscriber (e.g. a paired-client relay
that throws on a broken pipe) propagated out of emitClientEvent and escaped
acquireWorktreeTerminalSpawn *after* it had taken the per-worktree terminal
mutation but before returning the release. The release was never handed back to
the pty spawn caller, so its `finally` no-op'd and the mutation leaked. Every
later sleep of that worktree then blocked on the wedged mutation for 12s and
threw terminal_worktree_sleep_timeout, surfacing as "The host could not confirm
terminal shutdown" — permanently, until app restart, and worse with a remote
client attached.

Isolate each listener in emitClientEvent so one failing subscriber can never
abort the emitting operation. This fixes the class at the single fan-out point
all events flow through, not just the wake path.

Adds a regression test that fails (leaks the mutation) when the guard is
reverted.
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Updated runtime listener fan-out to catch and log individual subscriber errors while continuing delivery across client events, notifications, PTY events, and fit overrides. Added regression tests covering terminal wake and subsequent sleeping, plus notification subscriber isolation.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the bug and fix, but it misses required template sections like Summary, Screenshots, AI Review Report, Security Audit, and Notes. Rewrite it to match the template with Summary, Screenshots (or 'No visual change'), Testing checklist, AI Review Report with cross-platform verification, Security Audit, and Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 accurately summarizes the main change: isolating throwing client-event listeners so worktree sleep and fan-out keep working.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

🧹 Nitpick comments (1)
src/main/runtime/orca-runtime.test.ts (1)

27960-27998: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Consider asserting the error was actually logged.

The test verifies isolation (second listener still fires) and convergence (subsequent sleep succeeds), but doesn't assert that the thrown error from the first listener was caught and logged, which is part of the stated fix behavior. A spy on the logger (if injectable/mocked in this suite) would tighten the regression coverage.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7400dde0-4280-4f3e-aa46-7c99d542942b

📥 Commits

Reviewing files that changed from the base of the PR and between 4fce2de and c15a354.

📒 Files selected for processing (2)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts

Comment on lines +27982 to +27983
const releaseSpawn = await runtime.acquireWorktreeTerminalSpawn(TEST_WORKTREE_ID)
releaseSpawn()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect the signature/behavior of acquireWorktreeTerminalSpawn's release function
ast-grep run --pattern 'acquireWorktreeTerminalSpawn($$$) {
  $$$
}' --lang typescript src/main/runtime/orca-runtime.ts

rg -n -A5 -B2 'acquireWorktreeTerminalSpawn' src/main/runtime/orca-runtime.ts

Repository: stablyai/orca

Length of output: 1348


🏁 Script executed:

#!/bin/bash
set -euo pipefail
sed -n '22690,22745p' src/main/runtime/orca-runtime.ts
printf '\n--- tests around releaseSpawn ---\n'
sed -n '27950,28005p' src/main/runtime/orca-runtime.test.ts
printf '\n--- all release spawn declarations/usages ---\n'
rg -n 'acquireWorktreeTerminalSpawn|releaseSpawn|release =|Promise<\(\) => void>|Promise<\(.*=>.*\)|\(wait_until.*=>.*\)' src/main/runtime/orca-runtime.ts

Repository: stablyai/orca

Length of output: 5004


Await releaseSpawn() before exercising the post-release behavior.

acquireWorktreeTerminalSpawn() returns Promise<() => void>, but acquireWorktreeTerminalMutation() may await waitForWorktreeTerminalMutation(...) before returning the async release callback, so releaseSpawn() without await can let the assertions and next sleepTerminalsForWorktree() run before the mutation tail has actually resolved.

The wedged-sleep bug was one instance of a broader latent footgun: every
runtime listener fan-out looped and called subscribers with no error
isolation, so any synchronously-throwing subscriber could abort the emitting
operation. Only emitClientEvent had a proven critical consequence (a leaked
per-worktree mutation), but the pattern was repeated across mobile
notifications, pty data, driver-state, resize, and fit-override fan-outs.

Introduce notifyRuntimeListeners(listeners, deliver, context) and route the
low-frequency fan-outs (client-event, mobile-notification, pty-driver,
pty-resize, fit-override) through it so one failing subscriber is caught,
logged, and the rest still receive the event. The terminal-output hot path
keeps an inlined try/catch to avoid a per-chunk closure allocation.

Adds a test that a throwing mobile-notification subscriber no longer breaks
dispatch for the others, mirroring the client-event regression test.
@OrcaWin OrcaWin changed the title fix(runtime): stop a throwing client-event listener from wedging worktree sleep fix(runtime): stop a throwing client-event listener from wedging worktree sleep + harden fan-out Jul 23, 2026

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

🧹 Nitpick comments (1)
src/main/runtime/orca-runtime.ts (1)

29697-29713: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Other listener fan-outs (mobileSessionTabListeners, graphSyncCallbacks) remain unisolated.

The new notifyRuntimeListeners helper fixes the exact wedge bug for client events, fit overrides, mobile notifications, PTY driver, and PTY resize, but emitMobileSessionTabsSnapshot/notifyMobileSessionTabsChangedNow/notifyMobileSessionTabSnapshots (around lines 25219-25230, 25164-25179, 25181-25193) and the graphSyncCallbacks drain loops (e.g. lines 3950-3952, 22064-22067) still call subscriber callbacks with no per-listener try/catch. A throwing mobile session listener or graph-sync callback could abort the same kind of caller-held-mutation loop this PR was written to fix, just via a different fan-out.

Out of scope for this PR's fix, but worth a follow-up pass to route these through notifyRuntimeListeners too for consistency.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4d865727-3342-4ec1-8869-f8f315373d60

📥 Commits

Reviewing files that changed from the base of the PR and between c15a354 and f5e7caa.

📒 Files selected for processing (2)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/runtime/orca-runtime.test.ts

@OrcaWin
OrcaWin merged commit 8685cdb into main Jul 23, 2026
1 check passed
@OrcaWin
OrcaWin deleted the fix/worktree-sleep-mutation-leak branch July 23, 2026 05:03
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant