Skip to content

fix(terminal): safely prune stale remote tab ghosts - #17798

Closed
Jinwoo-H wants to merge 3 commits into
mainfrom
triage-sta3110-ghost-terminal-ghosts
Closed

Jinwoo-H wants to merge 3 commits into
mainfrom
triage-sta3110-ghost-terminal-ghosts

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​470 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​469
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​144 $\color{#cf222e}{\Huge{\mathbf{−}}}$​20 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​124

ELI5

A paired viewer could keep blank terminal tabs after the owning host had stopped publishing them. This waits through a short create window, then removes only viewer-side ghosts when a published host inventory and explicit worktree owner agree. Closing a real remote tab can also reach its host during a catalog hydration gap, but ambiguous ownership fails closed.

What Changed

  • prune null-PTY placeholders after 30 seconds only when the authoritative host inventory is published, the worktree owner matches that environment, and no PTY/reconnect evidence remains
  • preserve exact structured-create handoffs, fresh placeholders, unpublished restart frames, cross-environment collisions, and unverifiable PTY loss
  • resolve catalog-gap explicit closes from one agreeing live remote PTY owner; reject conflicting, persisted-layout-only, and unresolved SSH ownership
  • register the lifecycle contracts and focused regressions in the reliability gate

Why

Current origin/main reproduced both failures deterministically: an aged null-PTY viewer placeholder survived an authoritative omission, and a catalog-gap close dispatched no host call. Pruning belongs in renderer mirror reconciliation and must never infer PTY death; explicit close routing belongs at the live PTY ownership boundary.

Linked Issue

Fixes #11800

Related: #17767. Supersedes #11801; the implementations should not be combined.

Visual Proof

N/A — this changes renderer state reconciliation and close routing without adding or changing UI.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

Deterministic oracle:

  • baseline origin/main (f8a3f2c7c0 when reproduced): stale ghost remained; catalog-gap close issued zero host calls
  • candidate: 5 focused files, 72 tests passed
  • causal reverts: removing only age pruning made the stale-ghost regression red; disabling only live-owner resolution made the catalog-gap close regression red
  • restored candidate: both regressions green and git diff HEAD empty

Validation:

  • related reliability suite: 23 files, 1500 passed, 1 skipped
  • pnpm tc
  • pnpm tc:web
  • focused oxlint --deny-warnings
  • pnpm run check:code-quality:changed
  • pnpm run check:max-lines-ratchet
  • pnpm run check:reliability-gates
  • pnpm run build:electron-vite
  • git diff --check

AI Disclosure

Review

Three fresh gpt-5.6-luna Codex reviewers independently assessed the ownership boundary, product/compatibility decisions, and regression risk. Valid initial findings were reproduced and fixed; all three final bounded reviews returned CLEAN.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Null-PTY pruning mutates only the viewer mirror and never invokes a host close or PTY kill.
  • No RPC fields, stream opcodes, or other remote-wire contracts changed.
  • SSH-shaped PTYs remain fail-closed without catalog ownership because their IDs do not identify a paired runtime.
  • Folder-workspace ownership is explicit; no git-worktree assumption or platform-specific path/process behavior was added.
  • The older fix(terminal): prune stale remote tab ghosts #11801 trusts persisted layout PTY evidence and lacks the published-inventory, owner-match, reconnect, and conflict guards; this PR is the safer replacement.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@greptile-apps

greptile-apps Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

The PR adds conservative pruning for stale null-PTY remote-tab mirrors and routes catalog-gap closes using environment-qualified live PTY ownership.

  • Requires an authoritative host inventory, matching worktree ownership, elapsed creation grace period, and no reconnect evidence before pruning.
  • Resolves close ownership from agreeing live remote PTY bindings and fails closed on conflicts.
  • Adds focused reconciliation, ownership-routing, and reliability-gate coverage.

Confidence Score: 4/5

The PR is not yet safe to merge because a failed or sufficiently delayed host close can restore a remote tab that was already removed locally.

The renderer still prunes the local mirror before the host close succeeds, while snapshot suppression expires before the RPC timeout and is cleared on failure, allowing unchanged authoritative host state to rematerialize the tab.

Files Needing Attention: src/renderer/src/components/terminal/terminal-tab-actions.ts, src/renderer/src/runtime/web-session-close-intent.ts, src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts

Important Files Changed

Filename Overview
src/renderer/src/components/terminal/terminal-tab-actions.ts Adds live-PTY owner routing for catalog gaps, but the previously reported failed-close restoration path remains.
src/renderer/src/components/terminal/terminal-tab-runtime-environment.ts Conservatively resolves one environment-qualified PTY owner and reports conflicting ownership.
src/renderer/src/runtime/web-session-tabs-sync.ts Adds age-, authority-, ownership-, and reconnect-gated pruning for stale null-PTY mirror tabs.
src/renderer/src/components/terminal/terminal-tab-runtime-close-routing.test.ts Covers agreeing catalog-gap ownership, conflicts, and persisted-layout-only evidence.
src/renderer/src/runtime/web-session-tabs-sync.test.ts Adds extensive regression coverage for stale ghost pruning and preservation guards.
config/reliability-gates.jsonc Registers the new close-routing and reconciliation contracts in the terminal reliability gate.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Remote terminal tab] --> B{Live PTY owners agree?}
  B -->|No conflict| C{Runtime owner available?}
  B -->|Conflict| X[Cancel close]
  C -->|Yes| D[Prune local mirror]
  D --> E[Send close to owning host]
  C -->|No route or owner| X
  F[Authoritative host inventory] --> G{Null PTY older than grace period?}
  G -->|No| H[Retain placeholder]
  G -->|Yes| I{Owner matches and no reconnect evidence?}
  I -->|Yes| J[Prune stale viewer ghost]
  I -->|No| H
Loading

Reviews (4): Last reviewed commit: "fix(terminal): preserve pending host mir..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 9d7f8497-824a-4195-b1d0-47fc97921b8d

📥 Commits

Reviewing files that changed from the base of the PR and between 40f060f15f5925b8bfe67a499acfd55ace38f01e and ef39f9c.

📒 Files selected for processing (2)
  • src/renderer/src/runtime/web-session-tabs-sync.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

The renderer now resolves terminal runtime ownership from live PTY bindings and routes catalog-gap closes to the owning remote runtime. Conflicting or layout-only evidence cancels the close. Web session synchronization now uses host authority, runtime ownership, reconnect evidence, and grace periods when retaining or pruning null-PTY terminal tabs. Snapshot APIs and the test harness accept the expanded synchronization state. Tests cover runtime resolution, close routing, and terminal-tab reconciliation cases.

Merge Risk: 🔵 Low · up to ef39f

This change removes stale remote terminal tabs only after authoritative ownership and grace-period checks, and improves close routing during catalog gaps without terminating host processes. A bounded stale-message history could still allow an unusually delayed snapshot to remove a current viewer tab after many runtime rotations, so merge is reasonable with explicit owner awareness and follow-up.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.75% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 8 files. 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 clearly identifies the terminal fix and the stale remote tab pruning that addresses the primary issue. It is concise, although it does not mention the related close-routing change.
Description check ✅ Passed The description follows the required template and explains the problem, changes, rationale, linked issue, visual impact, testing, review, compatibility considerations, and checklist status. Automated …
Linked Issues check ✅ Passed The implementation addresses issue #11800 [#11800] by adding bounded pruning for stale null-PTY placeholders, preserving valid and ambiguous states, routing closes from unambiguous live remote PTY own…
Out of Scope Changes check ✅ Passed The production changes, focused tests, test harness update, and reliability-gate updates support the stale terminal ghost and close-routing objectives. No unrelated feature, UI, or remote-wire changes…
Full details: Description check

Explanation

The description follows the required template and explains the problem, changes, rationale, linked issue, visual impact, testing, review, compatibility considerations, and checklist status. Automated validation is documented in detail.

Full details: Linked Issues check

Explanation

The implementation addresses issue #11800 [#11800] by adding bounded pruning for stale null-PTY placeholders, preserving valid and ambiguous states, routing closes from unambiguous live remote PTY ownership, and preventing local pruning from killing remote PTYs.

Full details: Out of Scope Changes check

Explanation

The production changes, focused tests, test harness update, and reliability-gate updates support the stale terminal ghost and close-routing objectives. No unrelated feature, UI, or remote-wire changes are evident.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 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.

@Jinwoo-H
Jinwoo-H force-pushed the triage-sta3110-ghost-terminal-ghosts branch from 40f060f to db340b7 Compare September 1, 2026 03:48

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

Caution

This PR breaks an existing unit test (src/renderer/src/runtime/web-session-tabs-sync-terminal-mirroring.test.ts → "removes a null-pty pending activation tab when the host publishes the initial terminal") and reintroduces a duplicate-tab regression whenever a worktree's explicit runtime owner is not yet resolved — the same catalog-hydration gap this PR is meant to handle safely.

Reviewed changes

  • Ghost pruning — shouldReplaceTerminalTab now prunes an aged (>= 30s) null-PTY placeholder when the host snapshot affirms worktree contents, the worktree's explicit owner matches the publishing environment, and no reconnect evidence remains; a new nullPtyTabHasRetentionEvidence helper covers unverifiedPtyLossTabIds and the reconnect maps.
  • Close routing — a new resolveTerminalTabRuntimeEnvironment resolves a tab's remote owner from live PTY bindings (none / runtime / conflict), and closeTerminalTab routes explicit close to that live owner during a worktree-catalog gap, failing closed on conflicting or unresolved ownership.
  • State/type widening — applyWebSessionTabsSnapshot* now accept WebSessionTabsSyncState & WorktreeRuntimeOwnerState, with four reconnect maps added to the partial pick.
  • Tests & gates — new focused suites for pruning and close routing, plus reliability-gate invariant/oracle text and command-list updates.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

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

Important

The new test models a resolved worktree owner, but it does not address the production regression it was red for. When the owner is unresolved — the catalog-hydration gap this PR otherwise handles — shouldReplaceTerminalTab still retains a pendingActivationSpawn null-PTY placeholder alongside the host-published mirror, producing a duplicate tab that main removed.

Reviewed changes

  • web-session-tabs-sync-terminal-mirroring.test.ts — the previously failing "removes a null-pty pending activation tab when the host publishes the initial terminal" test now supplies repos/worktreesByRepo so getExplicitRuntimeEnvironmentIdForWorktree resolves to the publishing environment, making tabBelongsToEnvironment true again.
  • No production code changed in this commit — the tabBelongsToEnvironment guard on the pendingActivationSpawn replacement branch remains as first reviewed.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

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

✅ No new issues found.

Reviewed changes

Since the prior review (db340b7), one commit landed that resolves the placeholder-parity regression during unresolved worktree ownership.

  • shouldReplaceTerminalTab now replaces on a missing worktree route — the pendingActivationSpawn branch accepts tabBelongsToEnvironment || worktreeOwnerIsMissing, where worktreeOwnerIsMissing is resolveWorktreeOperationRouteResult(state, worktreeId).kind === 'missing', so a catalog-hydration gap no longer strands a null-PTY placeholder next to the host-published mirror.
  • Ambiguous ownership still fails closed — the new "keeps a pending activation tab when worktree ownership is ambiguous" test pins conflicting detected hosts to the retain path.
  • Reverted the test-only workaround — the repos/worktreesByRepo fixtures previously added to web-session-tabs-sync-terminal-mirroring.test.ts are removed; the original minimal-state test now passes through the production guard.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker

nwparker commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

Superseded by #33949 (host close records retire the ghost rows) and #27132 (close routing), which shipped this. Closing.

@nwparker nwparker closed this Nov 1, 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.

Paired viewer retains unclosable null-PTY terminal ghosts after host topology advances

2 participants