Skip to content

Fix Codex pane output tearing after app occlusion - #7173

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/codex-hidden-output-tear
Jul 3, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/codex-hidden-output-tear

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes renderer-buffer tearing in Codex terminal panes after the app has been occluded while hidden-output snapshot recovery is active.

The failing layer is the renderer terminal buffer: raw PTY bytes and main-owned snapshots can be clean, while a late renderer delivery can still mutate the pane after a newer restore. This PR does not use orca terminal read as evidence because its retention-tail normalization is known to flatten spinner frames.

Root cause: after hidden snapshot restore or newer foreground bytes advanced the renderer to a later PTY seq, a delayed background-origin Codex chunk containing a stateful terminal query could still take the hidden live-write path when hiddenRendererStateDirty was false. That allowed an older redraw/query chunk to be written into the renderer after a newer snapshot rebuilt the buffer.

Fix: track the latest PTY seq accepted by the renderer for the current PTY through hidden snapshot restore and foreground drains/writes. Hidden/background renderer data is filtered against that ordered seq before it can reach the terminal. Fully covered stale chunks are dropped; unmappable overlap falls back to main snapshot recovery instead of risking duplicate/stale renderer bytes.

Review hardening

Review coverage for this PR: an independent adversarial agent pass over the seq-filter machinery and its lifecycle, maintainer diff review, and CodeRabbit. (A separate terminal-based reviewer agent was also attempted but could not run due to model-gateway errors.)

The adversarial pass found one real hole in the original fix, closed in the follow-up commit:

  • Stale ordered-seq baseline across pty stream restarts (silent data loss). Main deletes its per-pty seq counter on runtime.onPtyExit — including suppressed/synthetic kills — so a revived session that reuses the same ptyId (agent-hibernation wake, kill + cold-restore into a still-mounted pane) restarts seq near zero while the renderer still holds the old high-water mark. Every hidden/background chunk from the revived stream was then judged "already covered" and dropped without marking a snapshot restore, permanently freezing hidden output for that pane; foreground writes could only ratchet the stale baseline upward. Two constant-time guards close it: any observed pty exit clears the baseline for the exiting ptyId, and a per-pty channel seq-regression detector (pty:data is FIFO per pty with a monotonic counter, so an in-order arrival below the last seen seq can only mean a restarted counter) covers restarts whose exit never reached the renderer. Each guard has a regression test verified to fail with that guard removed.
  • The original regression test was reworked to deliver chunks in the only order the FIFO data channel can produce: the snapshot RPC outruns in-flight chunks, and the stale query frame then arrives in channel order after the restore completed. The reworked test still fails against the pre-fix renderer, so the original coverage is preserved.

Findings triaged and rejected (no code change):

  • Dropping a fully covered chunk without marking restore is sound under monotonic seq: coverage only advances via an applied snapshot or a chunk already written in channel order, so covered bytes are always represented in the buffer. The stream-restart case above was the one exception, now guarded.
  • The unmappable-partial-chunk fallback (markHiddenOutputRestoreNeeded) always has a snapshot source available: seq metadata is only attached by the local and SSH-relay data channels, both snapshot-capable; the remote-runtime transport sends no seq metadata, which leaves the filter inert there by design.
  • Chunks queued during an in-flight restore are never trimmed (trimming applies only to non-foreground chunks; only foreground chunks are queued), and the drain's unmappable-chunk path is loss-free — it discards the queue and refetches a fresher snapshot that already covers those bytes.
  • Stale stateful queries (CPR) are now dropped rather than answered against rebuilt buffer state. This matches the existing skip-path design, which already drops stateful queries whenever the hidden renderer state is dirty; answering a stale CPR after a newer restore was part of the corruption this PR fixes.
  • CodeRabbit's one nitpick (the regression test's frames all rewrite a single line, weakening the buffer-equality assertion) was reviewed and skipped: the equality compares against a reference parsed from the clean in-order stream, so it already proves every buffer row is free of stale residue, and the single-line rewrite shape mirrors the real Codex spinner frames the bug manifested in.

Reliability proof

  • Reliability invariant: terminal-session.snapshot-freshness / renderer hidden-output ordering. A hidden/background chunk must not mutate the renderer terminal buffer after the renderer has already accepted a snapshot or foreground stream position that covers that chunk's PTY seq — and that acceptance mark must not outlive the pty stream that produced it.
  • Material impact: makes the Codex occlusion tear class harder to reintroduce by locking the bug at the renderer write-order seam, including stateful-query chunks that previously bypassed hidden skipping when the hidden renderer looked clean, and protects revived sessions from silent hidden-output loss.
  • Product change type: mixed product hardening plus deterministic regression coverage.
  • Performance risk inventory: touches hidden output, PTY output, visibility resume, render/snapshot replay. Does not touch typing input routing, focus ownership, resize, startup awaits, provider listing, store subscribers, git/worktree scans, subprocesses, SSH process inspection, WSL path handling, or mobile/relay routing.
  • No-regression evidence: the fix adds no polling, timers, background wake loop, unbounded buffering, provider calls, PTY resizes, or scans. It performs constant-time seq checks on the existing per-chunk path and reuses existing snapshot drain offset logic. The review-hardening guards add two integer comparisons per chunk and an O(1) reset per pty exit.
  • Correctness evidence: three deterministic regression tests. The first records renderer writes, reconstructs the renderer buffer with a headless terminal parser, and compares it to a reference parse of the clean ordered raw stream; it fails before the fix because the stale background Codex query frame is written after restore. The other two cover session revival with a restarted seq counter — with and without an observed pty exit — and each fails when its guard is removed.
  • Provider/platform coverage: local and daemon PTY paths covered by the test's main snapshot + seq contract. SSH relay uses the same monotonic seq source and snapshot path. Remote-runtime providers send no seq metadata and keep existing behavior. macOS, Linux, and Windows are unaffected by platform-specific assumptions.
  • Residual gaps: no live macOS occlusion Playwright run in this PR; remote-runtime provider-specific ordering is not separately exercised; the known retention-tail normalizer limitation is not addressed here.
  • Manifest status / promotion: no config/reliability-gates.jsonc exists in this worktree, so there is no manifest entry to promote. Treat this as a partial gate carried by pty-connection.test.ts.
  • Rollback or demotion rule: if this test flakes or blocks legitimate hidden stateful-query replies for chunks newer than the renderer seq, demote the gate and capture the offending seq/rawLength/provider metadata before changing behavior.

Validation

  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts - 288 passed
  • pnpm run typecheck - passed
  • oxlint on changed files - clean

Made with Orca 🐋

Track the latest PTY seq accepted by hidden snapshot restore or foreground renderer writes, and drop hidden/background chunks already covered by that seq. This prevents late background stateful-query chunks from mutating xterm after a newer snapshot rebuilt the renderer buffer.

Co-authored-by: Orca <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This change adds per-PTY renderer output ordering in pty-connection.ts, including new ordering state and helper functions to track sequence baselines, detect regressions, and slice hidden renderer data. The hidden restore path now records ordering during snapshot replay and applies ordered bytes throughout live PTY handling, queueing, and writing. The test file adds headless xterm helpers and new cases covering stale background query chunks and sequence restart restore scenarios.

Changes

Related issues: None provided
Related PRs: None provided
Suggested labels: bug, renderer, terminal
Suggested reviewers: None provided

File Summary
src/renderer/src/components/terminal-pane/pty-connection.ts Adds renderer ordering state and helpers; updates snapshot restore, live data handling, and write paths to use ordered renderer bytes
src/renderer/src/components/terminal-pane/pty-connection.test.ts Adds headless terminal rendering helpers and restore-order regression tests

Sequence Diagram(s)

sequenceDiagram
  participant PTY
  participant pty-connection.ts
  participant getChunkDataAfterSnapshot
  participant xterm

  PTY->>pty-connection.ts: onData(chunk, meta.seq)
  pty-connection.ts->>pty-connection.ts: observeRendererOrderedSeqRegression(meta)
  pty-connection.ts->>getChunkDataAfterSnapshot: getHiddenRendererDataAfterOrderedSeq(data, meta)
  getChunkDataAfterSnapshot-->>pty-connection.ts: orderedRendererData or null
  alt orderedRendererData is available
    pty-connection.ts->>xterm: write orderedRendererData
  else orderedRendererData is null
    pty-connection.ts->>pty-connection.ts: mark hidden restore needed
    pty-connection.ts->>pty-connection.ts: schedule pending startup delivery
  end
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it does not follow the required template sections for screenshots, AI review report, security audit, or notes. Reformat the PR description to match the template and add a Screenshots section, a security audit, and an explicit AI review report with cross-platform coverage.
✅ 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 is concise and accurately summarizes the main renderer tearing fix after occlusion.
✨ 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.

🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/pty-connection.test.ts (1)

7024-7102: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The seq math (staleSeq < currentSeq, snapshot baseline = currentSeq) correctly models an out-of-order delayed background chunk, and the primary assertion (writes never contains staleQueryFrame) directly validates the drop.

Minor note (optional): because every frame is prefixed with \r\x1b[2K (carriage-return + erase-line), all three frames collapse onto the same buffer line, so referenceBuffer reduces to just the final frame's content. The toEqual(referenceBuffer) comparison is therefore a fairly weak buffer-state check — the not.toContain assertion is doing the real work. If you want the equality check to also guard against a mis-sliced partial write landing on screen, consider frames that render to distinct lines (e.g. without the leading erase) so residual stale bytes would actually diverge the buffers.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 56f14c45-c147-438d-ab80-77a79651f037

📥 Commits

Reviewing files that changed from the base of the PR and between 087ad66 and e42a61b.

📒 Files selected for processing (2)
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts

Review of the ordered-seq filter found one real data-loss hole: the
baseline outlives the pty stream that produced it. Main deletes its
per-pty byte counter on runtime.onPtyExit, so a revived session that
reuses the same ptyId (agent-hibernation wake, kill + cold-restore in a
still-mounted pane) restarts seq near zero while the renderer still
holds the old high-water mark. Every hidden/background chunk from the
revived stream then reads as "already covered" and is dropped without
marking a snapshot restore, permanently freezing hidden output for that
pane; foreground writes can only ratchet the stale baseline upward.

Two guards close it, each pinned by a regression test that fails with
the guard removed:

- Exit reset: any observed pty exit clears the ordered baseline for the
  exiting ptyId, since the exit ends that ptyId's seq domain. This
  covers all kill/revive flows that deliver pty:exit to the renderer,
  including suppressed-exit restarts that rebind the same id.
- Channel-seq regression reset: pty:data delivery is FIFO per pty and
  main assigns seq from a monotonic counter, so an in-order arrival
  below the last seen seq can only mean the counter restarted without
  an observed exit (e.g. a failed shutdown that already tore down
  runtime state). Detecting that regression drops the stale baseline
  instead of letting it cover the new stream's bytes.

The existing stale-query regression test was also reworked to deliver
chunks in the only order the FIFO channel can produce (snapshot RPC
outruns in-flight chunks; the stale query frame then arrives in order
after the restore), instead of delivering a newer-seq chunk before an
older one, which the regression detector now correctly treats as a
stream restart. The reworked test still fails against the pre-fix
renderer, so the original coverage is preserved.

Both guards are constant-time comparisons on the existing per-chunk
path: no allocations, polling, buffering, or PTY resizes.

Co-authored-by: Orca <[email protected]>
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