Skip to content

fix(attach): restore full terminal state on reattach - #29

Merged
serabi merged 8 commits into
mainfrom
fix/attach-terminal-state
Nov 7, 2026
Merged

serabi merged 8 commits into
mainfrom
fix/attach-terminal-state

Conversation

@serabi

@serabi serabi commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Why

Restore terminal contents and settings when a client reattaches. Keep scrollback complete and restore the primary screen after a full-screen app exits.

What's Included

  • Replay logical history lines and preserve the last screenful for the attaching client's height.
  • Restore the primary screen before the alternate screen, including saved origin state.
  • Reset retained margins, origin mode, and attributes before replay. Restore wrap mode, cursor shape, palette colors, and custom tab stops.
  • Restore synchronized output after a failed replay.
  • Add terminal replay tests and the real-daemon attach regression. Use portable Python cleanup for its owned fixture directory, reporting cleanup errors without replacing an original failure.
  • List the replay repairs in the README fork note. Stacked on fix(session): preserve unresponsive session sockets #28.

UI / UX

Not applicable. This changes terminal replay in the backend. Earlier awesoMux and synthetic phone-watch results were from the pre-rebase revision; no new app or physical-phone proof is claimed here.

Notes

Models: Claude Opus 5.5, GPT-6.1 Sol

Merge risk: medium. Replay changes screen contents and terminal modes. The real-daemon regression covers Ghostty, but other terminals and the rebased revision in awesoMux remain unchecked. Recovery: revert for future snapshots; already connected terminals and running daemons can keep their state.

Current macOS checks with Zig 0.16: formatting, unit tests, build, and terminal replay tests pass. git diff --check passes. With trash unavailable on PATH, all 96 attach cases pass. A separate forced-failure run injects both an attach assertion and a cleanup error: cleanup removes the owned fixture, reports its error separately, and the final traceback keeps the original assertion. The cleanup review thread remains open and unanswered for Sarah. The earlier 3 reattach cases passed at 9a9aea6; they were not rerun for this harness/docs change. Hosted CI for the new head is reported separately. Remaining limits: very large snapshots grow with scrollback; clients must enforce their own size limits. Long viewport lines do not reflow. Tab stops past the source width are not restored. A real iPhone and tab stops in awesoMux itself remain untested.

After this lands, adding the attach regression to zmx CI and updating awesoMux's submodule pin need separate approval. Keep awesomux-pin-cc24771 and awesomux-pin-ffa16fa. Merge with a merge commit and keep the branch.


Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

fix(attach): restore full terminal state on reattach

Summary

Reattaching to a session previously restored only the visible screen plus a narrow set of extras. This PR makes the serialized snapshot a faithful reproducer: scrollback, primary and alternate screens, cursor shape, palette overrides, tab stops, wrap mode, origin mode, and retained margins all survive a detach/attach cycle, and the snapshot is now laid out for the attaching client's row count rather than the daemon's.

What changed

  • serializeTerminalState(alloc, term, client_rows) — new client_rows parameter; both daemon call sites (loop.zig) pass client.requested.rows. Snapshot geometry now matches the receiver, so Watch/follower clients and resized viewers no longer get a layout sized for someone else.
  • Scrollback reflow — history is emitted through ScreenFormatter with unwrap enabled (only when the source has DECAWM on), instead of a hard-wrapped TerminalFormatter. Long logical lines re-render correctly on a wider receiver; sessions with DECAWM off stay hard-wrapped because a receiver without RIS is still in that mode.
  • Receiver state reset before replay — 1047l, 6l, r, 2J, H clear any leftover alt buffer, origin mode, and margins; a client that died on alt no longer shows its stale primary through the reattached session. Replayed rows are pushed into history with client_rows CRLFs before the screen is cleared.
  • Alt-screen reconstruction — when alt is active, the full primary screen (with its cursor and saved origin via DECOM for 1049) is replayed first, then the correct entry mode (1049/1047/47, preferring 1049) is issued once, with SGR, charset, and DECSCA protection reset in between so primary styling cannot bleed into alt.
  • New restorations: OSC 4 palette entries (only set mask bits), DECSCUSR cursor style (only when not default, so a client keeps its configured shape), tab stops (only via hasCustomTabstops, avoiding the cursor-corruption that forced tabstops = false), and DECAWM.
  • Testing: new terminal-replay binary (zig build test-replay) and test/attach_scrollback.py, an end-to-end harness driving the real daemon over its socket and comparing ordered rows against a fresh reference terminal.

Security-relevant changes

  • DECSET 2026 restoration moved to defer (with a regression test using a FailingAllocator). Previously an allocation failure inside serialization left the live terminal with synchronized output disabled — a resource-exhaustion path that silently changed a running session's rendering mode. It is now restored on every exit.
  • No stale-screen bleed on reattach: the pre-replay 2J/H and 1047l drop content from a prior client that terminated while on the alternate screen, preventing leftovers from a previous viewer appearing in a new one.
  • Pen/charset/protection are re-armed between screens, closing the path where primary-screen escape state (e.g. ESC(0 line-drawing) restyled alternate-screen output.

Performance impact

Attach is now measurably more expensive: the snapshot can carry the full primary screen in addition to the active viewport (when alt is active), the whole palette mask is walked per serialize, and up to 10 000 history lines are expanded. The test records snapshot size for a 10 000-line primary plus alt and asserts it stays under the protocol's 8 MiB ceiling. Cost scales with scrollback depth × client rows, so this is attach-path only, not per-frame.

Review finding (medium, unresolved)

  • src/util.zig:948 — serializeTerminalState mutates live terminal alt-screen modes. The format_term = term.* copy deliberately clears the alt-screen mode bits for the viewport formatter; the reviewer flags that this does not reliably isolate the live terminal. Needs confirmation whether these fields are by-value before merging.

Code quality notes

  • The 386-line Python harness is large for a regression test; the boundary/narrow cases only print('OBSERVE ...') and never assert, so they can't fail — either assert them or drop them to keep the suite honest.
  • writeCursorStyle is called twice per serialize (primary and active screen) and the selection/pin construction is duplicated between the primary formatter and the viewport formatter — a small helper would keep these in sync.
  • hasCustomTabstops and the palette loop re-scan every serialize; caching on the terminal would avoid repeat work at negligible complexity.

@kody-ai

This comment has been minimized.

Comment thread src/util.zig Resolved
@kody-ai

This comment has been minimized.

@kody-ai

This comment has been minimized.

serabi added a commit that referenced this pull request Nov 7, 2026
Port PR metadata and size checks from awesoMux and add Zig 0.16
unit and automation checks. Preserve human comments and checklist
confirmations when workflows reconcile their own comments.

Add the approved fork-specific merge-risk skill. Defer attach CI
until the regression harness lands through PR #29.
serabi added a commit that referenced this pull request Nov 7, 2026
Add Zig 0.16 CI, PR metadata and size checks, and fork-specific merge-risk guidance. Attach regression CI follows PR #29.
@serabi
serabi force-pushed the fix/preserve-unresponsive-sessions branch from ffa16fa to 6c6ab41 Compare November 7, 2026 04:48
@serabi
serabi force-pushed the fix/attach-terminal-state branch from cc24771 to 9a9aea6 Compare November 7, 2026 04:50
@kody-ai

This comment has been minimized.

@github-actions

github-actions Bot commented Nov 7, 2026

Copy link
Copy Markdown

External contributor checklist

Thanks for contributing. A maintainer will handle the trusted checks and final merge.

  • A maintainer has reviewed the change.
  • The PR description follows the template.
  • Visible changes include screenshots or a clear not-applicable explanation.
  • A maintainer confirmed no untrusted fork code was run with repository secrets.

@github-actions github-actions Bot added the size:L 100-499 effective changed lines. label Nov 7, 2026
Comment thread test/attach_scrollback.py Resolved
Reattach cleared the receiver's screen right after replaying history, so
the last screenful never reached its scrollback. Push those rows out
first, counting the attaching client's rows because a Watch or follower
can be taller than the daemon's grid.

Replay history as logical lines so it reflows after a resize. The
viewport stays hard-wrapped because the restored cursor assumes the
source row layout. Sessions with DECAWM off stay hard-wrapped throughout
so a receiver still in that mode cannot truncate a line.
Restore primary history, viewport, and cursor before entering alt.
Normalize receivers onto primary and emit one alt transition so mode
aliases cannot overwrite the saved cursor.

Exercise real-daemon snapshots with fresh and already-alt receivers,
taller clients, mode aliases, and a 10,000-line primary buffer.
A receiver reattached without RIS could keep DECAWM off and truncate
unwrapped history, so turn wrapping on first when the source uses it.

Entering 1049 saved the receiver's origin mode instead of the primary
screen's saved one. Set that mode before entering, then clear it so the
viewport replay applies the alternate screen's own mode.
@serabi
serabi force-pushed the fix/preserve-unresponsive-sessions branch from 6c6ab41 to 3f06807 Compare November 7, 2026 05:15
@serabi
serabi force-pushed the fix/attach-terminal-state branch from 9a9aea6 to 2c8f9f3 Compare November 7, 2026 05:15
@kody-ai

kody-ai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the @kody start-review command at the root of your PR.

  • Validate Business Logic: Ask Kody to validate your code against business rules by adding a comment with the @kody -v business-logic command.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Access your configuration settings here.

​

Comment thread src/util.zig Resolved
@serabi
serabi changed the base branch from fix/preserve-unresponsive-sessions to main November 7, 2026 05:24
@serabi
serabi merged commit b8eb0f6 into main Nov 7, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L 100-499 effective changed lines.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant