Skip to content

Fix iOS terminal scrolling at history ends - #8399

Closed
azooz2003-bit wants to merge 5 commits into
mainfrom
task-ios-end-scroll-bounce
Closed

azooz2003-bit wants to merge 5 commits into
mainfrom
task-ios-end-scroll-bounce

Conversation

@azooz2003-bit

@azooz2003-bit azooz2003-bit commented Jul 18, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Make the iPhone the sole owner of primary terminal viewport scrolling.
  • Stop outward momentum at Ghostty authoritative top and bottom boundaries.
  • Preserve distance from the bottom when a full history replay replaces the render grid.
  • Restrict history prefetch to the older-history direction and expand it incrementally to 4,800 rows.

Verification

  • FullReplacementScrollPositionTests and TerminalScrollBoundaryTests pass on the dedicated iOS 26.5 simulator.
  • CmuxMobileShell TerminalScroll and TerminalOutput tests pass, 38 tests total.
  • The regression test fails on commit c6d8617 before the fix and passes on commit 9c8be0e after the fix.
  • The paired isend simulator remained pinned to line 0800 through three outward bottom swipes.
  • macOS and iOS tagged builds succeeded with the same isend tag.

Notes

The iOS package convention check reports two pre-existing violations in CmxIrohTCPFirstActivation.swift and CmuxPopoverMutation.swift. Neither file changed in this branch.


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.


Summary by cubic

Fixes iOS terminal scroll bounce at history ends and makes primary‑screen scrolling phone‑local. Preserves the viewport across full render‑grid replays with compare‑and‑swap restoration that waits for a row‑space rebuild, and fetches deeper history in pages up to 4,800 rows.

  • Bug Fixes
    • Primary screen: phone owns the viewport; Mac serves paged snapshots via zero‑line scroll RPCs.
    • Suppress outward momentum at top/bottom with TerminalScrollBoundary (fails open without scrollback).
    • Full replacements: mark only full render‑grid as replacements; preserve distance‑from‑bottom using row‑space revision CAS; buffer gesture deltas and flush after; skip initial auto‑scroll when preserving offset.
    • Alternate screen: keep forwarding wheel input to the real PTY so TUIs scroll as before.
    • History prefetch: only when scrolling up; window grows 600 → 4,800 rows; stop after short or capped responses.
    • Tests: added unit/UI coverage for boundary suppression, gesture routing, prefetch paging, full‑replay viewport preservation and row‑space rebuild, and endpoint gestures (pinned at bottom, clean reversal, no snap‑back).

Written for commit c71a77f. Summary will update on new commits.

Review in cubic

Summary by CodeRabbit

  • New Features
    • Increased mobile scrollback prefetch budget (600 → 4800) for faster, smoother history loading.
    • Added full terminal replacement output handling that preserves the user’s current scrollback viewport.
    • Improved scroll gesture routing across primary/alternate screen modes, including wheel behavior.
  • Bug Fixes
    • Correctly distinguishes full replacement vs incremental output to prevent unwanted scroll/viewport drift.
    • Ensures scroll requests with zero lines still honor configured max scrollback; refines prefetch/flush behavior during replacements.
  • Tests
    • Expanded unit and UI coverage for replacement detection, scroll prefetching, scroll boundary behavior, and rapid-swipe pinning.

@cursor

cursor Bot commented Jul 18, 2026

Copy link
Copy Markdown

Bugbot is paused — on-demand spend limit reached

Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.

A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.

@coderabbitai

coderabbitai Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Full render-grid replacements now preserve local scroll position, while output chunks carry replacement metadata to Ghostty. Mobile scroll gestures route by active screen, use bounded prefetch windows, and record server response limits.

Changes

Mobile terminal behavior

Layer / File(s) Summary
Full replacement delivery
Packages/iOS/CmuxMobileShell/..., Packages/iOS/CmuxMobileShellUI/..., Packages/iOS/CmuxMobileShellModel/...
Full render-grid payloads propagate isFullReplacement through output chunks and use the dedicated replacement processing path.
Replacement scroll preservation
Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/..., Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/..., ios/cmuxUITests/...
Full replacement processing defers pending scroll deltas, restores distance from bottom, and adds boundary, replay-preservation, and endpoint gesture tests.
Scroll routing and prefetch
Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/..., Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/..., Sources/TerminalController*
Scroll gestures route by active screen, primary-screen prefetch state grows to a cap and stops after limited responses, and the mobile prefetch budget increases to 4800 rows.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant MobileShellComposite
  participant MobileTerminalOutputChunk
  participant GhosttySurfaceRepresentable
  participant GhosttySurfaceView
  MobileShellComposite->>MobileTerminalOutputChunk: propagate isFullReplacement
  GhosttySurfaceRepresentable->>GhosttySurfaceView: process full replacement
  GhosttySurfaceView->>GhosttySurfaceView: preserve scroll distance
  GhosttySurfaceView-->>GhosttySurfaceRepresentable: return processing result
Loading

Possibly related PRs

  • manaflow-ai/cmux#7098: Modifies the same terminal-output delivery paths with replay-barrier and reset handling.
  • manaflow-ai/cmux#7171: Updates iOS full-replacement output and replay tracking in the same delivery path.
  • manaflow-ai/cmux#7675: Changes the same terminal-output delivery flow with replay-barrier handling.

Suggested reviewers: lawrencecchen

🚥 Pre-merge checks | ✅ 24 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.05% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (24 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.
Cmux Swift Actor Isolation ✅ Passed PASS: The changed value models stay nonisolated/Sendable, MobileShellComposite is @MainActor, and the new scroll helper explicitly opts out; UI calls remain on MainActor.
Cmux Swift Blocking Runtime ✅ Passed PASS: the HEAD diff only adds an iOS test file; its only timing loop is a deterministic waitUntil helper using Task.sleep, which the rule allows in tests.
Cmux Browser Automation Off-Main ✅ Passed The PR only changes iOS terminal scroll/replay code and tests; no browser.*, processV2Command, or socketWorkerMethods routing changed.
Cmux Expensive Synchronous Load ✅ Passed Touched files only change terminal scroll/output behavior; no new RestorableAgentSessionIndex.load() or agent-store call sites were added in the diff.
Cmux Cache Substitution Correctness ✅ Passed No authoritative read was swapped for a stale cache; full-replacement replay uses live Ghostty scrollbar reads/CAS restore, and scroll prefetch has a cold fallback plus response-driven expiry.
Cmux No Hacky Sleeps ✅ Passed PR changes only Swift sources/tests; no TS/JS/shell/build/runtime diffs with fixed sleeps, polling, or delayed dispatch.
Cmux Algorithmic Complexity ✅ Passed Changed paths are O(1) flag/state checks and bounded queue/prefetch logic; no new scalable collection rescans or repeated sorts were introduced.
Cmux Swift Concurrency ✅ Passed HEAD only changes an XCTest file, and its async usage is test-only; no new cmux runtime legacy async pattern is introduced.
Cmux Swift @Concurrent ✅ Passed Changed async methods are UI-bound @MainActor continuations or existing RPC helpers; no new nonisolated async lacks @concurrent, and no invalid @concurrent appears.
Cmux Swift Package Boundaries ✅ Passed Reusable scroll-boundary and prefetch logic moved into CmuxMobileTerminal/CmuxMobileShell; app-target changes are RPC/Ghostty glue using app singletons.
Cmux Swiftpm Lockfiles ✅ Passed HEAD only changes a test file; no Package.swift, Package.resolved, .gitignore, workflow, or Xcode package-reference files were touched.
Cmux Swift Logging ✅ Passed Only changed file is an XCTest; no added/changed print/debugPrint/dump/NSLog/Logger in production Swift, and existing Logger declarations were unchanged.
Cmux User-Facing Error Privacy ✅ Passed Changed files only add scroll/output flags and comments/tests; no user-facing errors, alerts, API error bodies, or raw upstream details were introduced.
Cmux Full Internationalization ✅ Passed The diff only adds logic/tests/comments; no user-facing Swift text, xcstrings, or locale-specific web assets changed, and no localization APIs were introduced.
Cmux Swiftui State Layout ✅ Passed Touched UI code is a UIKit bridge (UIViewRepresentable/UIView subclasses); no new ObservableObject/@published, GeometryReader, lazy row subtrees, or render-time state mutation found.
Cmux Architecture Rethink ✅ Passed The patch adds localized state/invariants for scroll ownership and full-replacement replay, with no new timing hacks or split lifecycle owners in production code.
Cmux Swift Auxiliary Window Close Shortcuts ✅ Passed No changed production Swift adds user-visible standalone windows; only a test-only UIWindow harness appears, which is exempt from the cmux auxiliary-window close-shortcut rule.
Cmux Source Artifacts ✅ Passed All changed paths are intentional Swift source/test files; none match artifact, cache, temp, or generated-output paths in the policy.
Cmux No Test Or Debug Seam In Production Source ✅ Passed PASS: The new code adds product scroll/output logic only; no new #if DEBUG, ForTesting, debug, or test-only accessors were introduced in production Sources.
Cmux No Ambient Global State ✅ Passed No new file-scope funcs/vars or singleton namespaces were added; the new APIs are type/extension methods and the new structs carry instance state.
Title check ✅ Passed The title concisely matches the main change: fixing iOS terminal scrolling at history boundaries.
Description check ✅ Passed The description covers summary and verification well, but it omits the demo video, review trigger, and checklist sections from the template.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch task-ios-end-scroll-bounce

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift`:
- Around line 2132-2137: Separate scroll restoration status from output
application success in the processOutput flow around scrollPositionPreserved and
GhosttySurfaceScrollPosition.restore. Keep restoration results for scroll
behavior only, and update the completion call to return true whenever the output
is applied to the current surface generation, even if the exact scroll offset
cannot be restored.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 198ad846-63bf-4086-a8f2-5487da562010

📥 Commits

Reviewing files that changed from the base of the PR and between 9687274 and 9c8be0e.

📒 Files selected for processing (17)
  • Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+TerminalOutputDelivery.swift
  • Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+TerminalScrollDelivery.swift
  • Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TerminalOutputDelivery.swift
  • Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TerminalScrollDelivery.swift
  • Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TerminalOutputDeliveryQueueTests.swift
  • Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TerminalScrollDeliveryQueueTests.swift
  • Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileTerminalOutputSinking.swift
  • Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/GhosttySurfaceRepresentable.swift
  • Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttyRuntime.swift
  • Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+LocalScrollbackScroll.swift
  • Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+ThemeOutput.swift
  • Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift
  • Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/TerminalScrollBoundary.swift
  • Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/FullReplacementScrollPositionTests.swift
  • Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/TerminalScrollBoundaryTests.swift
  • Sources/TerminalController+MobileScrollPrefetch.swift
  • Sources/TerminalController.swift

@greptile-apps

greptile-apps Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR rearchitects iOS terminal scrolling so the phone owns its primary-screen viewport locally, asking the Mac only for deeper history snapshots, while preserving the user's scroll offset across full render-grid replacements and suppressing outward momentum at the loaded top and bottom boundaries.

  • Primary-screen viewport ownership: TerminalScrollDelivery.forScrollGesture now routes scroll gestures by active screen; primary-screen gestures apply locally with lines: 0 and only trigger a prefetch RPC when the paging threshold is crossed, while alternate-screen wheel input still reaches the Mac PTY.
  • Full-replacement offset preservation: processFullReplacementOutputAndWait captures distanceFromBottom before applying VT output on the serial output queue and uses a compare-and-swap (ghostty_surface_scroll_to_row_if_revision) to restore it after, with the restoration failure deliberately decoupled from the applied return value so it cannot trigger a spurious stream reset.
  • Boundary suppression and prefetch paging: TerminalScrollBoundary.suppresses blocks outward momentum at the loaded endpoints; the history prefetch window grows incrementally from 600 to 4 800 rows, stopping once the server returns a short or capped response; the server-side mobileScrollPrefetchScrollbackLineBudget is raised to match so the cap never falsely marks history as fully loaded.

Confidence Score: 5/5

Safe to merge. The changes are well-scoped to the iOS scroll pipeline with no cross-cutting mutations to shared Mac-side state.

The viewport-preservation path correctly decouples scroll-restoration failure from output-application result. The fullReplacementOutputInFlight flag is set and cleared exclusively on the main actor, preventing gesture flushes from racing the background output queue. Server-side budget and client-side maxWindowRows are raised together to 4 800 rows so the short-response heuristic cannot fire a false positive on intermediate pages. All three new invariants are covered by focused unit and integration tests.

No files require special attention.

Important Files Changed

Filename Overview
Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/TerminalScrollBoundary.swift New file. Clean nonisolated value types; suppresses fails open for no-scrollback surfaces (correct for alt-screen TUIs); CAS restoration re-reads revision after output to avoid stale row-space revision.
Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift Core scroll coordination changes: fullReplacementOutputInFlight flag is set/cleared only on the main actor; flushPendingScrollIfNeeded widened to internal for production use by GhosttySurfaceView+ThemeOutput.swift; preservingScrollbackOffset path skips initial auto-scroll-to-bottom correctly.
Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+ThemeOutput.swift New processFullReplacementOutputAndWait correctly wraps beginFullReplacementOutput/finishFullReplacementOutput around the async output operation; scroll restoration failure is explicitly discarded so it cannot contaminate the applied return value.
Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TerminalScrollDelivery.swift Prefetch state now only accumulates on positive (older-history) scrolls and resets on direction reversal; window grows 600 rows per trigger up to 4 800; recordResponse correctly stops further fetches after a short or capped server response.
Sources/TerminalController+MobileScrollPrefetch.swift Server-side budget raised from 600 to 4 800 rows, correctly aligned with the client's new maxWindowRows; without this the server cap would falsely trigger historyFullyLoaded on every second prefetch page.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant DL as Display Link
    participant GSV as GhosttySurfaceView (Main)
    participant OQ as outputQueue (Background)
    participant GK as GhosttyKit C API
    participant MSC as MobileShellComposite
    participant Mac as Mac RPC

    Note over DL,GSV: Normal primary-screen gesture
    DL->>GSV: flushPendingScrollIfNeeded()
    GSV->>GK: ghostty_surface_scrollbar() boundary
    alt boundary suppresses at top or bottom
        GK-->>GSV: suppressed
    else within range
        GK-->>GSV: boundary ok
        GSV->>GK: ghostty_surface_mouse_scroll()
        GSV->>MSC: didScrollLines prefetch check
        MSC->>Mac: "scroll RPC lines=0 maxScrollbackRows=N"
        Mac-->>MSC: renderGrid snapshot
        MSC->>MSC: recordResponse grow or stop window
        MSC->>GSV: deliverAuthoritativeTerminalRenderGrid()
    end

    Note over DL,GSV: Full replacement output arrives
    GSV->>GSV: beginFullReplacementOutput
    DL->>GSV: flushPendingScrollIfNeeded BLOCKED
    GSV->>OQ: "processOutput preserving=true async"
    OQ->>GK: ghostty_surface_scrollbar distanceFromBottom
    OQ->>GK: ghostty_surface_process_output full VT replay
    OQ->>GK: ghostty_surface_scroll_to_row_if_revision CAS
    GK-->>OQ: positioned
    OQ-->>GSV: "completion applied=true via main.async"
    GSV->>GSV: "finishFullReplacementOutput applied=true"
    GSV->>GSV: flushPendingScrollIfNeeded buffered deltas applied
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant DL as Display Link
    participant GSV as GhosttySurfaceView (Main)
    participant OQ as outputQueue (Background)
    participant GK as GhosttyKit C API
    participant MSC as MobileShellComposite
    participant Mac as Mac RPC

    Note over DL,GSV: Normal primary-screen gesture
    DL->>GSV: flushPendingScrollIfNeeded()
    GSV->>GK: ghostty_surface_scrollbar() boundary
    alt boundary suppresses at top or bottom
        GK-->>GSV: suppressed
    else within range
        GK-->>GSV: boundary ok
        GSV->>GK: ghostty_surface_mouse_scroll()
        GSV->>MSC: didScrollLines prefetch check
        MSC->>Mac: "scroll RPC lines=0 maxScrollbackRows=N"
        Mac-->>MSC: renderGrid snapshot
        MSC->>MSC: recordResponse grow or stop window
        MSC->>GSV: deliverAuthoritativeTerminalRenderGrid()
    end

    Note over DL,GSV: Full replacement output arrives
    GSV->>GSV: beginFullReplacementOutput
    DL->>GSV: flushPendingScrollIfNeeded BLOCKED
    GSV->>OQ: "processOutput preserving=true async"
    OQ->>GK: ghostty_surface_scrollbar distanceFromBottom
    OQ->>GK: ghostty_surface_process_output full VT replay
    OQ->>GK: ghostty_surface_scroll_to_row_if_revision CAS
    GK-->>OQ: positioned
    OQ-->>GSV: "completion applied=true via main.async"
    GSV->>GSV: "finishFullReplacementOutput applied=true"
    GSV->>GSV: flushPendingScrollIfNeeded buffered deltas applied
Loading

Reviews (3): Last reviewed commit: "Verify full replay row-space replacement" | Re-trigger Greptile

@cursor

cursor Bot commented Jul 18, 2026

Copy link
Copy Markdown

Bugbot is paused — on-demand spend limit reached

Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.

A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.

@azooz2003-bit

Copy link
Copy Markdown
Collaborator Author

Superseded by #8451, which fixes the reported workspace-list scroll path. This PR targeted terminal-detail scrolling and does not match the corrected scope.

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