fix: zombie worktree PTY cleanup (issue #218) (#1376)

* fix(runtime): kill all PTYs for a worktree on removal (design §4.3)

Worktree deletion only shut down renderer-tracked terminals, so PTYs owned
by background tabs, split panes, or pre-reload sessions survived the
removal and kept leaking memory. Introduce killAllProcessesForWorktree
with three sweeps (runtime leaves, provider-prefix scan of daemon session
ids, pty-registry by worktreeId) and wire it into both teardown paths:
the CLI-initiated removeManagedWorktree and the renderer-initiated
worktrees:remove IPC handler. OrcaRuntimeService gets a lazy
getLocalProvider thunk so construction order stays robust.

Co-authored-by: Orca <help@stably.ai>

* fix(renderer): purge worktree-scoped state on removal + hydration (design §4.4)

When a worktree is deleted, ~25 worktree-scoped maps (tabsByWorktree,
git caches, browser state, split-tab models, per-file editor drafts,
etc.) kept references to the gone worktree, so SessionsStatusSegment
kept mis-classifying orphaned PTYs as bound and dropdowns rendered stale
ids. Add purgeWorktreeTerminalState as a single atomic action that
wipes every scoped map plus cascades top-level actives. Fire it from
the worktrees:changed listener on the set-diff of removed ids, and once
more at hydration via fetchAllWorktrees to clean up persisted entries
from pre-fix sessions. The hydration-time purge is gated behind a
per-repo success check: a single transient IPC error or an all-empty
fetch defers the purge so a degraded launch cannot wipe legitimate
persisted state.

Co-authored-by: Orca <help@stably.ai>

* test(zombie-worktree): regression coverage for design §4.5

Adds tests for every layer of the zombie-worktree fix:
- worktree-teardown: unit coverage of the three-sweep helper including
  best-effort error swallowing across provider/registry.
- orca-runtime: RPC-initiated removeManagedWorktree kills PTYs before
  any git mutation + verifies the lazy getLocalProvider thunk resolves
  on each call.
- worktrees IPC: renderer-initiated remove kills PTYs before git and
  skips the kill helper for SSH-backed repos.
- renderer slice: fetchAllWorktrees defers the purge when any sibling
  repo fetch fails or every repo returns empty (F1 regression);
  happy-path fires the purge once and does not re-run on subsequent
  calls. Direct purgeWorktreeTerminalState coverage pins the cascade
  across worktree-keyed, tab-id-keyed, and file-id-keyed maps.

Co-authored-by: Orca <help@stably.ai>

* fix(runtime): log worktree-teardown kill counts (design §4.4 observability)

Breadcrumb lets ops distinguish a renderer-state-induced leak (diff-path
purge non-empty) from a backend-induced one (nothing to kill but memory
still pinned). Emit only when the sweep actually shut anything down so
steady-state logs stay quiet. Added at both call sites —
removeManagedWorktree (CLI path) and the worktrees:remove IPC handler.

Co-authored-by: Orca <help@stably.ai>

* test(zombie-worktree): fix ptyIdsByTabId seed shape to match production type

The purge unit test seeded ptyIdsByTabId as Record<string, string> when
the runtime type is Record<string, string[]>. The unit tests passed
because they never hit the UI renderer, but live e2e surfaced a
TypeError: (ptyIdsByTabId[tabId] ?? []).some is not a function.

Corrected to arrays; 21/21 tests still pass.

Co-authored-by: Orca <help@stably.ai>

---------

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-05-03 15:54:45 -07:00
committed by GitHub
co-authored by Orca
parent 943f64a906
commit 66d596fe11
14 changed files with 997 additions and 19 deletions
+50 -1
View File
@@ -105,6 +105,8 @@ import {
areWorktreePathsEqual
} from '../ipc/worktree-logic'
import { invalidateAuthorizedRootsCache } from '../ipc/filesystem-auth'
import { killAllProcessesForWorktree } from './worktree-teardown'
import type { IPtyProvider } from '../providers/types'
type RuntimeStore = {
getRepos: Store['getRepos']
@@ -240,12 +242,28 @@ export class OrcaRuntimeService {
private agentDetector: AgentDetector | null = null
private _orchestrationDb: OrchestrationDb | null = null
private messageWaitersByHandle = new Map<string, Set<MessageWaiter>>()
private readonly getLocalProviderFn: (() => IPtyProvider) | null
constructor(store: RuntimeStore | null = null, stats?: StatsCollector) {
constructor(
store: RuntimeStore | null = null,
stats?: StatsCollector,
deps?: { getLocalProvider?: () => IPtyProvider }
) {
this.store = store
if (stats) {
this.agentDetector = new AgentDetector(stats)
}
// Why: the daemon adapter is installed via `setLocalPtyProvider()` during
// attachMainWindowServices, AFTER this service is constructed. Capturing
// `getLocalPtyProvider()` at construction time would freeze a reference to
// the pre-daemon `LocalPtyProvider` and miss the routed adapter. Resolve
// lazily via thunk so teardown always sees the currently-installed
// provider (design §4.3 wire-up).
this.getLocalProviderFn = deps?.getLocalProvider ?? null
}
getLocalProvider(): IPtyProvider | null {
return this.getLocalProviderFn ? this.getLocalProviderFn() : null
}
// Why: lazy initialization — the DB path depends on Electron's userData
@@ -1128,6 +1146,37 @@ export class OrcaRuntimeService {
throw new Error('Folder mode does not support deleting worktrees.')
}
// Why: kill every PTY belonging to this worktree BEFORE the git-level
// removal. Some shells keep the worktree directory busy, and `git worktree
// remove` throws a confusing error if PTYs still hold it open. This also
// closes the headless-CLI leak (design §2a/§2b): without this call, the
// CLI path runs git removal and never touches PTYs, leaving zombies
// behind. Best-effort: any failure here must not prevent git removal —
// the worst case without the call is the status quo.
const localProvider = this.getLocalProvider()
if (localProvider) {
await killAllProcessesForWorktree(worktree.id, {
runtime: this,
localProvider
})
.then((r) => {
const total = r.runtimeStopped + r.providerStopped + r.registryStopped
if (total > 0) {
// Why (design §4.4 observability): breadcrumb lets ops
// distinguish a renderer-state-induced leak (diff-path purge
// non-empty) from a backend-induced one (nothing to kill but
// memory still pinned). Emit only when the sweep actually did
// work so steady-state logs stay quiet.
console.info(
`[worktree-teardown] ${worktree.id} killed runtime=${r.runtimeStopped} provider=${r.providerStopped} registry=${r.registryStopped}`
)
}
})
.catch((err) => {
console.warn(`[worktree-teardown] failed for ${worktree.id}:`, err)
})
}
const hooks = getEffectiveHooks(repo)
let warning: string | undefined
if (hooks?.scripts.archive && runHooks) {