Skip to content

fix(automations): close hidden background tab/PTY on automation completion - #3337

Closed
BorjaLL wants to merge 4 commits into
stablyai:mainfrom
BorjaLL:BorjaLL/automation-pty-cleanup
Closed

BorjaLL wants to merge 4 commits into
stablyai:mainfrom
BorjaLL:BorjaLL/automation-pty-cleanup

Conversation

@BorjaLL

@BorjaLL BorjaLL commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Agent-authored PR — opened as a draft for Borja's review. Please review before marking ready.

Problem

Automation dispatch (useAutomationDispatchEvents) launches a hidden background tab + PTY via launchAgentBackgroundSession to run the scheduled/Run-Now agent. The returned result.tabId / result.ptyId were only used for markDispatchResult bookkeeping and focus restoration — they were never closed when the run finished.

A hidden automation tab never mounts a TerminalPane, and the only renderer path that issues pty.kill is the pane transport teardown. So closeTab alone wouldn't have reaped it either. The result: every automation run leaked one tab + one live PTY for the lifetime of the app (local, SSH, and remote-runtime alike).

Fix

Reap the launched background session when the run reaches a terminal state — agent completion (markCompletionResult), process exit (markExitResult), and dispatch failure (catch):

  1. Kill the PTY, runtime-aware:
    • closeWebRuntimeTerminal(ptyId) for remote-runtime handles (they aren't reachable via window.api.pty.kill — the worktree teardown path explicitly skips remote: ids).
    • falls back to window.api.pty.kill(ptyId) for local / SSH PTYs.
  2. store.closeTab(tabId, { recordInteraction: false }) for UI/store cleanup.

Guards (no regression to visible automation tabs)

  • Only the launched background session is reaped. Reused sessions (the session-reuse path) belong to the user and are never touched — launchedBackgroundSession is only set on the launchAgentBackgroundSession path.
  • Skipped if the user has the tab active/open, so an automation tab someone is watching is never yanked out from under them.

Scope / platforms

  • Covers local, SSH, and remote-runtime PTYs across macOS / Linux / Windows (no platform-specific code; reuses existing runtime-aware helpers).
  • Single-file change: src/renderer/src/hooks/useAutomationDispatchEvents.ts.

Verification

  • pnpm run typecheck:web — clean.
  • oxlint on the changed file — 0 warnings / 0 errors.
  • vitest run on store-session-cascades, store-cascades, and web-runtime-session (the closeTab / pty.kill cascade + runtime terminal-close behavior this relies on) — 118/118 pass.

No unit test exists for this hook (it's IPC/store-coupled and exercised via e2e); behavior was validated by typecheck + lint + the cascade tests above and by tracing the completion/exit/failure paths.

🤖 Generated with Claude Code

Risk assessment

Risk: HIGH

Historic risk metadata backfill based on the existing risk:high label.

Risk: high

Historic risk metadata backfill based on the existing risk:high label.

ELI5

Finished automations left hidden background terminal tabs open forever. Those tabs/PTYs are closed when the automation run completes.

@nwparker

Copy link
Copy Markdown
Contributor

Reviewer pass complete. I pushed commit d18834acb631f996d9aa595689f2da65f99c4b90 to cover and harden the automation background-session cleanup path.

What I verified/reproduced:

  • The bug path is non-visual renderer lifecycle cleanup: launchAgentBackgroundSession creates a hidden tab + PTY for automation runs, and that hidden tab never mounts a TerminalPane, so pane unmount cleanup cannot reap the PTY.
  • Added hook-seam regression coverage proving the dispatch hook itself closes the launched background session after automation completion.
  • Covered local/SSH-style PTYs via window.api.pty.kill, remote-runtime PTYs via closeWebRuntimeTerminal, and the active-tab guard so a tab the user is currently watching is not closed under them.
  • Tightened completion/exit cleanup to run in finally, so a failed run-result write cannot skip the hidden tab/PTY cleanup.

Validation run:

  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/useAutomationDispatchEvents.test.ts src/renderer/src/store/slices/store-session-cascades.test.ts src/renderer/src/store/slices/store-cascades.test.ts src/renderer/src/runtime/web-runtime-session.test.ts — 4 files / 121 tests passed.
  • pnpm run typecheck:web — passed.
  • pnpm exec oxlint src/renderer/src/hooks/useAutomationDispatchEvents.ts src/renderer/src/hooks/useAutomationDispatchEvents.test.ts — 0 warnings, 0 errors.
  • pnpm run lint — passed.
  • git diff --check HEAD~1..HEAD — passed.
  • git merge-tree --write-tree origin/main HEAD — clean, tree cb1f1beb0ae4248681381df0436797325332f096.

No Electron screenshot/video here because this is a hidden background PTY lifecycle leak rather than a visible UI state; the regression test exercises the ownership/cleanup seam directly. I did not merge and left draft status unchanged.

@nwparker
nwparker marked this pull request as ready for review May 30, 2026 04:45
@nwparker

Copy link
Copy Markdown
Contributor

Revalidated this bug-fix branch and moved it out of draft.

Reproduction/evidence focus:

  • The failing lifecycle is hidden automation execution: launchAgentBackgroundSession creates a background tab + PTY, but the hidden tab never mounts a TerminalPane, so pane unmount cleanup cannot reap the PTY.
  • The hook-seam regression tests exercise that ownership point directly: after automation completion the launched hidden session is closed, local/SSH-style PTYs go through window.api.pty.kill, remote-runtime PTYs go through closeWebRuntimeTerminal, and a tab the user is actively viewing is not closed under them.
  • No screenshot/video is useful here because the bug is a hidden background PTY lifecycle leak; the evidence is the direct ownership/cleanup regression coverage.

Fresh validation on head d18834acb631f996d9aa595689f2da65f99c4b90:

  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/useAutomationDispatchEvents.test.ts src/renderer/src/store/slices/store-session-cascades.test.ts src/renderer/src/store/slices/store-cascades.test.ts src/renderer/src/runtime/web-runtime-session.test.ts — 4 files / 121 tests passed.
  • pnpm run typecheck:web — passed.
  • pnpm exec oxlint src/renderer/src/hooks/useAutomationDispatchEvents.ts src/renderer/src/hooks/useAutomationDispatchEvents.test.ts — 0 warnings, 0 errors.
  • pnpm run lint — passed across 3046 files.
  • git diff --check origin/main...HEAD — passed.
  • git merge-tree --write-tree origin/main HEAD — clean, tree c7c82d350d2a74169da98a931fa4280d3bc2cd54.

No merge performed.

@nwparker nwparker added the risk:high High risk change label May 30, 2026
@AmethystLiang
AmethystLiang requested a review from Jinwoo-H June 3, 2026 16:51
@AmethystLiang AmethystLiang assigned Jinwoo-H and unassigned nwparker Jun 3, 2026
BorjaLL and others added 2 commits June 15, 2026 11:09
…etion

Automation dispatch spawns a hidden background tab + PTY via
launchAgentBackgroundSession to run the agent, but the captured
result.tabId/result.ptyId were never used after marking the result.
Because a hidden tab never mounts a TerminalPane (the only renderer
path that issues pty.kill), the tab and its live PTY leaked for the
lifetime of the app — accumulating one orphaned PTY per run.

On completion (markCompletionResult), process exit (markExitResult),
and dispatch failure, reap the launched session: kill the PTY
runtime-aware (closeWebRuntimeTerminal for remote-runtime handles,
window.api.pty.kill for local/SSH) then closeTab for UI/store cleanup.

Guards:
- Only the launched background session is reaped — reused sessions
  belong to the user and are never touched.
- Skip if the user has the tab active/open, so a visible automation
  tab is never yanked out from under them.

Covers local, SSH, and remote-runtime PTYs on all platforms.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@BorjaLL
BorjaLL force-pushed the BorjaLL/automation-pty-cleanup branch from 6561592 to 408bc1e Compare June 15, 2026 10:12
@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

useAutomationDispatchEvents gains a launchedBackgroundSession ref and a closeBackgroundAutomationTab() helper. The helper skips cleanup when the automation tab is the user's active tab, otherwise calls closeWebRuntimeTerminal, falls back to window.api.pty.kill, and closes the tab. Completion and exit handlers now wrap markDispatchResult in try/finally blocks to guarantee this cleanup runs. After launchAgentBackgroundSession, bookkeeping populates launchedBackgroundSession only when a tab ID is present. The failure catch path also calls closeBackgroundAutomationTab() before emitting dispatch_failed. A new Vitest suite covers all three cleanup branches: normal completion, remote-runtime close, and active-tab skip.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely describes the main fix: closing hidden background tabs and PTYs on automation completion, which directly addresses the resource leak problem.
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.
Description check ✅ Passed The description is detailed and covers the bug, fix, verification, scope, and risks; it only omits the template's explicit Screenshots and Security Audit headings.

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.

@BorjaLL

BorjaLL commented Jun 15, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto latest main and ready for review. Conflicts resolved, and validated locally on a clean install: pnpm typecheck, pnpm lint, and the touched test suites all pass. Mergeable now. Review appreciated when you get a chance. cc @nwparker

…y-cleanup

# Conflicts:
#	src/renderer/src/hooks/useAutomationDispatchEvents.ts
@ghost

ghost commented Jun 19, 2026

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 4 individual chapters for you:

Title
1 Clean up formatting in runtime and test files
2 Implement background session reaping logic
3 Wire session cleanup to automation lifecycle
4 Verify automation session reaping with tests
Open in Stage

Chapters generated by Stage for commit ce0bdba on Jun 19, 2026 10:00pm UTC.

@Jinwoo-H

Copy link
Copy Markdown
Contributor

This fix makes sense to me for truly background automation runs: we don’t want completed automations quietly leaving terminal sessions around forever.

I’m curious how you’d expect this to feel as a user, though. If an automation creates a terminal, would you generally expect that terminal to disappear after the run finishes, or would you sometimes want it to stick around so you can inspect what happened? I’m especially thinking about cases where you opened the workspace while it was running, used Run Now almost like starting an agent session, or the run failed and the terminal output might be useful.

My instinct is that successful runs that stayed fully in the background should clean themselves up, but sessions the user looked at or failed runs may be worth preserving. Curious if that matches your expectation.

@BorjaLL

BorjaLL commented Jun 27, 2026

Copy link
Copy Markdown
Contributor Author

@nwparker this one's drifted out of mergeable again after recent main changes. Before I rebase it another round, is it still something you'd want to take? Glad to resolve conflicts if it's on the path to merge, equally glad to close it if priorities have moved. Just let me know which.

@BorjaLL

BorjaLL commented Jun 30, 2026

Copy link
Copy Markdown
Contributor Author

@Jinwoo-H that matches my intent closely, and the PR already encodes most of it:

  • Successful, fully-background runs self-clean. That's the exact leak this targets: a hidden tab + PTY that never mounts a TerminalPane, so nothing on the normal pane-teardown path ever reaps it.
  • Anything the user owns is left alone. Reused sessions (the session-reuse path) are never touched; only the session launchAgentBackgroundSession actually launched gets reaped.
  • A tab you're actively viewing is skipped, so a run you opened via Run Now won't get yanked out from under you.

The one place it currently diverges from your instinct is failed runs. Cleanup fires on every terminal state: agent completion, process exit, and the dispatch catch, so a failed background run is reaped too and its output is lost. I think gating the reap on success (preserve failures for inspection) is clearly right and I'm happy to add it.

The softer edge is "I looked at it earlier, then switched away." Today the guard is active-at-completion, so a tab you viewed but aren't focused on when the run ends still gets reaped. I can extend that to "preserve if ever viewed," but it needs interaction tracking I'd rather only add if the failed-run gate alone isn't enough.

So two changes I can fold in:

  1. Preserve failed runs (gate the reap on success) - I lean yes.
  2. Preserve any run the user ever viewed, not just active-at-completion - optional, more bookkeeping.

Want both, or just (1)?

…y-cleanup

# Conflicts:
#	src/renderer/src/hooks/useAutomationDispatchEvents.test.ts
#	src/renderer/src/hooks/useAutomationDispatchEvents.ts
@AmethystLiang

Copy link
Copy Markdown
Contributor

reviewing it now

@AmethystLiang
AmethystLiang requested review from AmethystLiang and removed request for Jinwoo-H July 16, 2026 02:11
@chsong1

chsong1 commented Jul 19, 2026

Copy link
Copy Markdown
Contributor

Live operational evidence from a recurring Orca watchdog automation confirms this PR's leak path:

  • 32 hidden automation terminals accumulated with the same automation marker; sampled oldest/newest runs had printed their final checkpoint and returned to an idle interactive prompt.
  • After closing those exact tabs, 4 exact-marker orphan Codex parent processes remained outside the live terminal inventory and required targeted termination.
  • The runs were successful, fully background one-shot executions, so they match the safest cleanup case described in this PR. User-owned/unrelated terminals were left untouched.

One additional parity gap is worth resolving before closeout (or tracking explicitly as a follow-up): the headless serve dispatch path in src/main/index.ts launches an agent terminal, waits for tui-idle, snapshots/completes the run, but does not close the exact automation-owned terminal. The renderer hook fix covers desktop useAutomationDispatchEvents, but not that headless lifecycle.

Suggested acceptance evidence:

  1. successful, newly launched background sessions close their exact owned PTY/tab after result persistence;
  2. reused sessions and user-active/user-owned tabs are never reaped;
  3. local, SSH, remote-runtime, and headless paths have explicit coverage;
  4. a live canary leaves zero exact-marker automation tabs/processes after completion while a normal interactive terminal remains open.

This is not the recognition/transport-close problem in #9414; it is automation ownership cleanup after a known terminal state.

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

Follow-up code-path audit found several ownership/lifecycle cases that should be resolved before treating this as a complete automation reaper:

  • reuseSession: true only protects an already reused candidate. If no candidate exists, the newly launched session is the future reuse seed, but it is still classified as launchedBackgroundSession and reaped on completion.
  • The current background launch path mounts hidden automation panes through background-terminal-worktree-mount; the PR's premise that the hidden tab never mounts a pane is stale. Explicit PTY kill followed by tab close can race/double-teardown with unmount cleanup.
  • The active-at-completion guard does not preserve a session the user viewed or typed into and then left before completion. Ownership takeover needs durable evidence (activation/input), not only current focus.
  • Remote closeWebRuntimeTerminal() closes the runtime terminal but does not remove the host-authoritative persisted session-tab binding. A later host snapshot can resurrect a dead tab; the host session.tabs.close / closeMobileSessionTab() path owns both binding removal and PTY retirement.
  • Headless/serve and reload-recovery completion paths remain uncovered.
  • Failure/nonzero-exit cleanup removes the terminal evidence operators may need. The safest first contract is successful fresh one-shot runs only, after snapshot/result persistence.

A robust contract would make cleanup an idempotent, launch-owned disposer bound to exact tab/pane/PTY/runtime identity; call it once only for successful fresh non-reuse runs after result persistence; and refuse cleanup after reuse, user activation/input takeover, identity drift, or failure. Renderer local/SSH, remote host-authoritative, and headless paths need separate regression coverage.

The operational leak is real, but broad idle/tab cleanup is dangerous because it can delete ordinary interactive agent sessions. I would not merge the current ownership predicate without these guards or an explicitly scoped first slice.

@nwparker nwparker added the bug Something isn't working label Jul 27, 2026
@AmethystLiang

Copy link
Copy Markdown
Contributor

Closing as the underlying change is already implemented on main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working risk:high High risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants