Skip to content

fix(terminal): restore live background terminal projections - #11819

Closed
lightofjeju wants to merge 3 commits into
stablyai:mainfrom
lightofjeju:fix/live-background-terminal-projection
Closed

lightofjeju wants to merge 3 commits into
stablyai:mainfrom
lightofjeju:fix/live-background-terminal-projection

Conversation

@lightofjeju

@lightofjeju lightofjeju commented Jul 31, 2026 •

Copy link
Copy Markdown

Summary

Fixes a renderer state-synchronization race that could make existing live terminal sessions disappear from Orca after a background/non-focus CLI terminal was created.

The main process can durably create the terminal backing row and PTY binding before the renderer session writer runs. When the renderer subsequently adopted that row, it could skip tab creation and leave the renderer-owned unifiedTabs / tab-group projection missing. The PTY remained alive, but the UI no longer had a renderable projection.

This change:

  • adds an idempotent exact-one terminal projection repair owned by the renderer
  • repairs the projection immediately after IPC terminal adoption and during startup after recovery/reconnect
  • only repairs bindings confirmed live by the existing PTY provider and rechecks fresh state before mutation
  • preserves background/non-focus behavior, active worktree/tab/group state, backing rows, PTY bindings, and layouts
  • keeps concurrent liveness probes bounded while applying projection updates in deterministic candidate order
  • retains coherent projection fields across temporary session-write suppression
  • pins the main process as backing/binding/layout-only rather than a second projection writer

Screenshots

No visual styling change. This restores terminal tabs that should already be visible. Native Electron automation verifies exact-one projection recovery, unchanged foreground state, PTY survival, and buffered output replay on first visible mount.

Testing

  • pnpm lint — not run; pnpm check:code-quality:changed passed with 0 new findings across all 16 changed files
  • pnpm typecheck
  • pnpm test — final branch used the focused suite below rather than the entire repository suite
  • pnpm build — not invoked directly; the Electron Playwright run completed its application and bundled CLI build successfully
  • Added or updated high-quality tests that would catch regressions

Focused verification on current origin/main:

  • 59 suites / 686 tests passed across persistence, startup routing, IPC adoption, projection repair, tab reconciliation, delayed session persistence, suppression recovery, readiness-gate retention, serialized writes, and sync/async persistence retries
  • deterministic pooled-probe reversed-completion regression passed
  • Electron headless hidden-terminal first-visible-mount scenario: 1 passed, 0 unexpected, 0 flaky
  • pnpm check:code-quality:changed passed
  • pnpm check:max-lines-ratchet passed
  • git diff --check origin/main...HEAD passed

AI Review Report

The review covered architecture, product behavior, and code quality against the approved repair contract. It checked renderer/main ownership, exact-one projection invariants, focus preservation, startup ordering, IPC reply semantics, liveness failure handling, stale-binding races, destructive reconciliation, writer suppression, and native Electron behavior.

An independent red-team pass found a real deterministic-order blocker in the first implementation: sorted candidates were being applied in PTY probe completion order. The implementation was changed to collect bounded concurrent probe results first and then apply projection mutations synchronously in deterministic candidate order. A three-candidate/concurrency-two reversed-completion regression now pins both the pool boundary and final tab order. Final architecture review returned CLEAR/APPROVE and final red-team QA passed with no blockers.

GitHub automated review then identified three additional gaps: empty projection patches still notified Zustand subscribers, suppression recovery still depended on a later store mutation, and rejected local session writes could lose their captured field batch. The follow-up commit skips no-op set() calls, self-schedules retained work until suppression lifts, returns and handles the local persistence Promise, restores and retries both synchronous and asynchronous failures, reports the first failure without log spam, and adds regressions for cleanup and concurrent in-flight changes.

A second automated pass found that a retained batch could still be cleared if the hydration gate closed while its timer fired, and that multiple asynchronous local patches could overlap. The final follow-up keeps batches across gate closure and serializes Promise-backed writes; dedicated regressions cover gate-only reopen and deferred first-write completion.

Cross-platform compatibility was explicitly reviewed for macOS, Linux, and Windows. The change adds no shortcuts, labels, platform paths, shell commands, or OS-specific branches. It uses existing Electron IPC/store APIs and platform-neutral Promise/timer behavior; no platform-specific follow-up is required.

Security Audit

  • No dependency, authentication, secret, network endpoint, or command-execution changes
  • No new IPC channel; the repair uses the existing pty.hasPty contract
  • Only literal true liveness results can create UI projection state; false, null, rejection, timeout, deadline exhaustion, and abort all fail closed
  • Probe concurrency and total startup time are bounded
  • Fresh backing/binding state is rechecked after asynchronous probes to reject stale or rebound PTYs
  • The projector is structurally limited to the four renderer projection fields and cannot kill PTYs, rewrite backing rows, navigate, reveal, or steal focus

No security blocker or follow-up was identified.

Notes

The affected sessions were not terminated; they became invisible because their renderer projection was absent. This PR repairs that projection while retaining the existing PTY lifecycle and main/renderer ownership boundary.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds terminal-tab projection invariants, canonical projection repair, and live PTY probing with bounded concurrency, timeouts, deadlines, and abort handling. Startup and terminal adoption invoke repair with diagnostic logging. Main-process tests cover fresh PTY binding persistence. Session persistence now supports asynchronous writes, retains suppressed fields, serializes writes, retries failures, and preserves pending state during cleanup.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.35% 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
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 and concisely describes restoring live background terminal projections, which is the primary change.
Description check ✅ Passed The description includes all required sections and provides clear scope, testing evidence, AI review details, security audit, and platform notes.

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/renderer/src/store/slices/tabs.ts (1)

634-648: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Avoid a no-op store notification when the projection patch is empty.

ensureTerminalTabProjection returns outcome.patch, which is {} for the unchanged and skipped outcomes. Zustand still builds a new state object for a partial update and notifies every subscriber. Startup repair calls this once per candidate tab, and onCreateTerminal calls it on every terminal adoption, so each miss re-runs full-state selectors. The rest of this slice already guards against that pattern (see the "no-op alloc that re-runs full-state selectors" comments).

Return the current state reference when the patch is empty so Zustand skips the notification.

♻️ Proposed fix
   ensureTerminalTabProjection: (worktreeId, tabId, targetGroupId) => {
     let result!: EnsureTerminalTabProjectionResult
     set((state) => {
       const outcome = buildTerminalTabProjectionPatch(
         state,
         worktreeId,
         tabId,
         targetGroupId,
         createBrowserUuid
       )
       result = outcome.result
-      return outcome.patch
+      // Why: an empty patch must keep the state reference so subscribers and selectors don't re-run.
+      return Object.keys(outcome.patch).length === 0 ? state : outcome.patch
     })
     return result
   },

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8e731685-4bd9-44c9-85cb-de3deda89855

📥 Commits

Reviewing files that changed from the base of the PR and between bd490b1 and 1932e03.

📒 Files selected for processing (16)
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/renderer/src/App.tsx
  • src/renderer/src/app-startup-routing.test.ts
  • src/renderer/src/hooks/ipc-events-test-harness.ts
  • src/renderer/src/hooks/useIpcEvents.test.ts
  • src/renderer/src/hooks/useIpcEvents.ts
  • src/renderer/src/lib/session-write-subscriber.test.ts
  • src/renderer/src/lib/session-write-subscriber.ts
  • src/renderer/src/lib/terminal-tab-projection-repair.test.ts
  • src/renderer/src/lib/terminal-tab-projection-repair.ts
  • src/renderer/src/store/slices/tabs.test.ts
  • src/renderer/src/store/slices/tabs.ts
  • src/renderer/src/store/slices/terminal-tab-projection-invariant.ts
  • src/renderer/src/store/slices/terminal-tab-projection.test.ts
  • src/renderer/src/store/slices/terminal-tab-projection.ts

@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR restores live terminal sessions that became invisible when a background/non-focus CLI terminal was created before the renderer session writer ran. The fix adds an idempotent projection repair step owned by the renderer that runs after startup reconnect, and also invokes repair synchronously on each IPC terminal adoption.

  • New repairLiveTerminalTabProjections: collects all backing tabs without a valid projection invariant, bounds concurrent PTY liveness probes to a configurable pool, collects results, then applies projection mutations in deterministic candidate order to prevent tab-order non-determinism from probe completion races.
  • New ensureTerminalTabProjection store action: pure function that computes a Zustand patch for the four renderer-owned projection fields, calling set() only when the patch is non-empty to avoid spurious subscriber notifications.
  • session-write-subscriber hardening: failed writes restore the exact captured field batch and retry after a bounded delay; suppression now self-schedules a retry timer so pending fields flush without requiring a subsequent Zustand mutation.

Confidence Score: 5/5

Safe to merge. The change restores missing terminal tab projections without altering PTY lifecycle, backing rows, layouts, or focus state.

The repair is idempotent, fail-closed, and deterministic. Session subscriber hardening is covered by a thorough test suite. The single finding is a cosmetic diagnostic string with no runtime impact.

Files Needing Attention: No files require special attention. The diagnostic issue in src/renderer/src/App.tsx is cosmetic.

Important Files Changed

Filename Overview
src/renderer/src/lib/terminal-tab-projection-repair.ts New orchestrator: collects candidates, runs bounded concurrent PTY liveness probes, applies mutations in deterministic candidate order. Handles abort, deadline, timeout, false, null, and rejection cleanly.
src/renderer/src/store/slices/terminal-tab-projection.ts New pure function computing an exact-one projection patch with alias deduplication, group topology validation, and layout fixup. Patch is empty on unchanged or skipped paths.
src/renderer/src/store/slices/terminal-tab-projection-invariant.ts New helper checking the exact-one projection invariant: one backing tab, one unified projection, correct group membership, layout coverage, single tab-order occurrence.
src/renderer/src/lib/session-write-subscriber.ts Hardened: persist is async-aware, failed batches are restored and retried, suppression handled via self-scheduled polling, disposal prevents post-cleanup retries.
src/renderer/src/store/slices/tabs.ts Adds ensureTerminalTabProjection store action calling set() only when the patch has keys, preventing no-op Zustand notifications.
src/renderer/src/App.tsx Adds startup projection repair step after reconnect; fixes discarded localWrite promise so IPC write failures can be retried.
src/renderer/src/hooks/useIpcEvents.ts Calls ensureTerminalTabProjection after IPC terminal adoption with structured error logging; errors are non-fatal so projection issues cannot block a successful PTY spawn reply.
src/main/persistence.ts Minor comment clarification: main process documented as backing/binding/layout-only; renderer owns projection. No logic change.

Reviews (3): Last reviewed commit: "fix(session): serialize durable projecti..." | Re-trigger Greptile

Comment thread src/renderer/src/store/slices/tabs.ts Resolved

@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: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 67f5e583-b481-4f19-a7fb-785a4bdd65af

📥 Commits

Reviewing files that changed from the base of the PR and between 1932e03 and f8f2706.

📒 Files selected for processing (5)
  • src/renderer/src/App.tsx
  • src/renderer/src/lib/session-write-subscriber.test.ts
  • src/renderer/src/lib/session-write-subscriber.ts
  • src/renderer/src/store/slices/tabs.test.ts
  • src/renderer/src/store/slices/tabs.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/renderer/src/App.tsx
  • src/renderer/src/store/slices/tabs.test.ts
  • src/renderer/src/store/slices/tabs.ts

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

Run ID: 5041c01e-0bf2-495b-b121-d733e91a7520

📥 Commits

Reviewing files that changed from the base of the PR and between f8f2706 and 06e7a8b.

📒 Files selected for processing (2)
  • src/renderer/src/lib/session-write-subscriber.test.ts
  • src/renderer/src/lib/session-write-subscriber.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/lib/session-write-subscriber.ts

@Jinwoo-H

Copy link
Copy Markdown
Contributor

Closing this submitted branch and routing the disappearing live-terminal projection behavior to canonical issue #15710. That issue owns the current unifiedTabs/tabGroups reconciliation work; we will carry the fix on current main. Full contributor credit is preserved for @lightofjeju. No action is requested from you. Thank you.

@Jinwoo-H Jinwoo-H closed this Aug 31, 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.

5 participants