From c6d8617311ee15d27fc7bb40bd1fa2802d0ee363 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Fri, 17 Jul 2026 19:22:07 -0700 Subject: [PATCH 1/5] Add failing iOS full-replay scroll position test --- ...hellComposite+TerminalOutputDelivery.swift | 2 + .../TerminalOutputDelivery.swift | 12 ++ .../MobileTerminalOutputSinking.swift | 4 + .../GhosttySurfaceRepresentable.swift | 15 ++- .../GhosttySurfaceView+ThemeOutput.swift | 11 ++ .../FullReplacementScrollPositionTests.swift | 109 ++++++++++++++++++ 6 files changed, 149 insertions(+), 4 deletions(-) create mode 100644 Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/FullReplacementScrollPositionTests.swift diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+TerminalOutputDelivery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+TerminalOutputDelivery.swift index 09fdc22e47e0..697d7a2eaed9 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+TerminalOutputDelivery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+TerminalOutputDelivery.swift @@ -333,6 +333,7 @@ extension MobileShellComposite { data: immediate.bytes, streamToken: streamToken, viewportPolicy: immediate.viewportPolicy, + isFullReplacement: immediate.isFullReplacement, terminalConfigTheme: immediate.terminalConfigTheme ) ) @@ -418,6 +419,7 @@ extension MobileShellComposite { data: next.bytes, streamToken: streamToken, viewportPolicy: next.viewportPolicy, + isFullReplacement: next.isFullReplacement, terminalConfigTheme: next.terminalConfigTheme )) } diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TerminalOutputDelivery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TerminalOutputDelivery.swift index 09073b5a3d67..9f8fd8549508 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TerminalOutputDelivery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TerminalOutputDelivery.swift @@ -72,6 +72,18 @@ struct TerminalOutputDelivery: Equatable, Sendable { nil } } + + /// Whether this payload rebuilds the complete terminal from an authoritative + /// render-grid snapshot. Full snapshots begin with a terminal reset, so the + /// apply side must preserve any phone-local scrollback position around them. + var isFullReplacement: Bool { + switch payload { + case .renderGrid(let frame): + frame.full + case .bytes, .theme: + false + } + } } /// Backpressure queue for one mounted mobile terminal output stream. diff --git a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileTerminalOutputSinking.swift b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileTerminalOutputSinking.swift index 87ae9da0201d..871c582be567 100644 --- a/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileTerminalOutputSinking.swift +++ b/Packages/iOS/CmuxMobileShellModel/Sources/CmuxMobileShellModel/MobileTerminalOutputSinking.swift @@ -25,6 +25,8 @@ public struct MobileTerminalOutputChunk: Sendable { public let data: Data public let streamToken: UUID public let viewportPolicy: MobileTerminalOutputViewportPolicy? + /// Whether `data` rebuilds the complete terminal from a render-grid snapshot. + public let isFullReplacement: Bool /// Raw Ghostty defaults that must be installed before this chunk's VT replay. public let terminalConfigTheme: TerminalTheme? @@ -32,11 +34,13 @@ public struct MobileTerminalOutputChunk: Sendable { data: Data, streamToken: UUID, viewportPolicy: MobileTerminalOutputViewportPolicy? = nil, + isFullReplacement: Bool = false, terminalConfigTheme: TerminalTheme? = nil ) { self.data = data self.streamToken = streamToken self.viewportPolicy = viewportPolicy + self.isFullReplacement = isFullReplacement self.terminalConfigTheme = terminalConfigTheme } } diff --git a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/GhosttySurfaceRepresentable.swift b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/GhosttySurfaceRepresentable.swift index b8b65535a10c..4186235f0488 100644 --- a/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/GhosttySurfaceRepresentable.swift +++ b/Packages/iOS/CmuxMobileShellUI/Sources/CmuxMobileShellUI/GhosttySurfaceRepresentable.swift @@ -324,10 +324,17 @@ struct GhosttySurfaceRepresentable: UIViewRepresentable { continue } if !chunk.data.isEmpty || chunk.terminalConfigTheme != nil { - let applied = await surfaceView.processOutputAndWait( - chunk.data, - terminalConfigTheme: chunk.terminalConfigTheme - ) + let applied = if chunk.isFullReplacement { + await surfaceView.processFullReplacementOutputAndWait( + chunk.data, + terminalConfigTheme: chunk.terminalConfigTheme + ) + } else { + await surfaceView.processOutputAndWait( + chunk.data, + terminalConfigTheme: chunk.terminalConfigTheme + ) + } guard applied else { store.terminalOutputDidReset( surfaceID: surfaceID, diff --git a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+ThemeOutput.swift b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+ThemeOutput.swift index 90f0f0c998a3..daf9131a9b4a 100644 --- a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+ThemeOutput.swift +++ b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+ThemeOutput.swift @@ -43,6 +43,17 @@ extension GhosttySurfaceView { } } + /// Dedicated seam for complete render-grid replacements. The regression + /// test intentionally starts with a plain forward so the first commit + /// demonstrates the reset-induced scroll jump. + @discardableResult + public func processFullReplacementOutputAndWait( + _ data: Data, + terminalConfigTheme: TerminalTheme? = nil + ) async -> Bool { + await processOutputAndWait(data, terminalConfigTheme: terminalConfigTheme) + } + /// Enqueues the current raw config defaults on this surface's serial Ghostty queue. public func applyTerminalConfigTheme() { applyTerminalConfigTheme(terminalConfigTheme, force: false) diff --git a/Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/FullReplacementScrollPositionTests.swift b/Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/FullReplacementScrollPositionTests.swift new file mode 100644 index 000000000000..184bb6de71e7 --- /dev/null +++ b/Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/FullReplacementScrollPositionTests.swift @@ -0,0 +1,109 @@ +#if canImport(UIKit) +import CMUXMobileCore +import Foundation +import GhosttyKit +import Testing +import UIKit + +@testable import CmuxMobileTerminal + +@MainActor +@Suite("Full replacement scroll position", .serialized) +struct FullReplacementScrollPositionTests { + private final class Delegate: NSObject, GhosttySurfaceViewDelegate { + func ghosttySurfaceView(_ surfaceView: GhosttySurfaceView, didProduceInput data: Data) {} + func ghosttySurfaceView( + _ surfaceView: GhosttySurfaceView, + didResize size: TerminalGridSize, + reportID: UInt64 + ) {} + } + + private struct Harness { + let window: UIWindow + let view: GhosttySurfaceView + let delegate: Delegate + } + + private func makeHarness() throws -> Harness { + let runtime = try GhosttyRuntime.shared() + let delegate = Delegate() + let view = GhosttySurfaceView(runtime: runtime, delegate: delegate, fontSize: 10) + view.isRenderDispatchSuppressed = true + let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 700)) + window.addSubview(view) + view.frame = window.bounds + window.isHidden = false + view.layoutIfNeeded() + return Harness(window: window, view: view, delegate: delegate) + } + + private func waitUntil( + timeout: Duration = .seconds(10), + _ predicate: @MainActor () -> Bool + ) async -> Bool { + let clock = ContinuousClock() + let deadline = clock.now + timeout + while clock.now < deadline { + if predicate() { return true } + try? await Task.sleep(for: .milliseconds(25)) + } + return predicate() + } + + private func scrollbarDistanceFromBottom(_ view: GhosttySurfaceView) -> UInt64? { + guard let surface = view.surface else { return nil } + var snapshot = ghostty_surface_scrollbar_s() + guard ghostty_surface_scrollbar(surface, &snapshot) else { return nil } + let maximumOffset = snapshot.total > snapshot.len ? snapshot.total - snapshot.len : 0 + return maximumOffset - min(snapshot.offset, maximumOffset) + } + + private func fullFrame(from view: GhosttySurfaceView) throws -> MobileTerminalRenderGridFrame { + let surface = try #require(view.surface) + let surfaceID = "full-replacement-scroll-position" + let exported = surfaceID.withCString { pointer in + ghostty_surface_render_grid_json_with_theme( + surface, + pointer, + UInt(surfaceID.utf8.count), + 1, + 500, + true + ) + } + defer { ghostty_string_free(exported) } + let pointer = try #require(exported.ptr) + let data = Data(bytes: pointer, count: Int(exported.len)) + return try JSONDecoder().decode(MobileTerminalRenderGridFrame.self, from: data) + } + + @Test("authoritative full replay keeps the phone-local viewport in history") + func fullReplayPreservesDistanceFromBottom() async throws { + let harness = try makeHarness() + defer { harness.view.prepareForDismantle() } + + let seed = (1...300) + .map { String(format: "full-replay line %03d\r\n", $0) } + .joined() + #expect(await harness.view.processOutputAndWait(Data(seed.utf8))) + let frame = try fullFrame(from: harness.view) + + harness.view.applyLocalScrollbackScroll(lines: 60, col: 2, row: 2) + #expect(await waitUntil { + (scrollbarDistanceFromBottom(harness.view) ?? 0) >= 40 + }) + let before = try #require(scrollbarDistanceFromBottom(harness.view)) + + #expect( + await harness.view.processFullReplacementOutputAndWait( + frame.vtPatchBytes(), + terminalConfigTheme: frame.terminalConfigTheme + ) + ) + let after = try #require(scrollbarDistanceFromBottom(harness.view)) + + #expect(after == before, "full replay moved the viewport from \(before) rows above bottom to \(after)") + } +} +#endif From 9c8be0e8cbca25f734628e1df33803f41fefff66 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Fri, 17 Jul 2026 19:32:38 -0700 Subject: [PATCH 2/5] Fix iOS terminal scrolling at history ends --- ...hellComposite+TerminalScrollDelivery.swift | 29 ++++--- .../TerminalScrollDelivery.swift | 68 ++++++++++++++- .../TerminalOutputDeliveryQueueTests.swift | 24 ++++++ .../TerminalScrollDeliveryQueueTests.swift | 86 ++++++++++++++++++- .../CmuxMobileTerminal/GhosttyRuntime.swift | 4 +- ...ttySurfaceView+LocalScrollbackScroll.swift | 10 ++- .../GhosttySurfaceView+ThemeOutput.swift | 33 +++++-- .../GhosttySurfaceView.swift | 48 +++++++++-- .../TerminalScrollBoundary.swift | 63 ++++++++++++++ .../TerminalScrollBoundaryTests.swift | 25 ++++++ ...minalController+MobileScrollPrefetch.swift | 2 +- Sources/TerminalController.swift | 9 +- 12 files changed, 363 insertions(+), 38 deletions(-) create mode 100644 Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/TerminalScrollBoundary.swift create mode 100644 Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/TerminalScrollBoundaryTests.swift diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+TerminalScrollDelivery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+TerminalScrollDelivery.swift index 0b4eb05ca6bb..87c9929ef46b 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+TerminalScrollDelivery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/MobileShellComposite+TerminalScrollDelivery.swift @@ -8,11 +8,9 @@ private let terminalScrollDeliveryLog = Logger( ) extension MobileShellComposite { - /// Forward a scroll gesture to the Mac's real surface. libghostty does the - /// mode-correct thing: normal screen moves the viewport into scrollback; - /// alt screen + mouse reporting encodes mouse-wheel to the PTY for the - /// program. The render-grid mirrors the result (it exports the live - /// `vp_top`). + /// Route a scroll gesture by active screen. The phone owns its primary + /// viewport and asks the Mac only for deeper history; alternate-screen wheel + /// input still reaches the real PTY so full-screen programs keep scrolling. /// /// Fire-and-forget and single-flight per surface. Native iOS scrolling can /// continue through deceleration after the finger lifts; while one RPC is @@ -21,19 +19,21 @@ extension MobileShellComposite { public func scrollTerminal(surfaceID: String, lines: Double, col: Int, row: Int) async { var prefetchState = terminalScrollbackPrefetchStatesBySurfaceID[surfaceID] ?? TerminalScrollbackPrefetchState() - let maxScrollbackRows = prefetchState.rowsToPrefetch(forScrollLines: lines) - terminalScrollbackPrefetchStatesBySurfaceID[surfaceID] = prefetchState - enqueueTerminalScroll(TerminalScrollDelivery( + let delivery = TerminalScrollDelivery.forScrollGesture( surfaceID: surfaceID, + activeScreen: terminalActiveScreenBySurfaceID[surfaceID], lines: lines, col: col, row: row, - maxScrollbackRows: maxScrollbackRows - )) + prefetchState: &prefetchState + ) + terminalScrollbackPrefetchStatesBySurfaceID[surfaceID] = prefetchState + guard let delivery else { return } + enqueueTerminalScroll(delivery) } private func enqueueTerminalScroll(_ delivery: TerminalScrollDelivery) { - guard delivery.lines != 0 else { return } + guard delivery.lines != 0 || delivery.maxScrollbackRows != nil else { return } let queueToken = terminalScrollQueueTokensBySurfaceID[delivery.surfaceID] ?? UUID() terminalScrollQueueTokensBySurfaceID[delivery.surfaceID] = queueToken var queue = terminalScrollQueuesBySurfaceID[delivery.surfaceID] ?? TerminalScrollDeliveryQueue() @@ -95,6 +95,13 @@ extension MobileShellComposite { renderGrid.surfaceID == delivery.surfaceID else { return } + var prefetchState = terminalScrollbackPrefetchStatesBySurfaceID[delivery.surfaceID] + ?? TerminalScrollbackPrefetchState() + prefetchState.recordResponse( + requestedRows: maxScrollbackRows, + availableRows: renderGrid.scrollbackRows + ) + terminalScrollbackPrefetchStatesBySurfaceID[delivery.surfaceID] = prefetchState deliverAuthoritativeTerminalRenderGrid( renderGrid, expectedSurfaceID: delivery.surfaceID, diff --git a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TerminalScrollDelivery.swift b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TerminalScrollDelivery.swift index f96d23606927..b70b2b23ae69 100644 --- a/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TerminalScrollDelivery.swift +++ b/Packages/iOS/CmuxMobileShell/Sources/CmuxMobileShell/TerminalScrollDelivery.swift @@ -1,3 +1,4 @@ +import CMUXMobileCore import Foundation struct TerminalScrollDelivery: Equatable, Sendable { @@ -25,30 +26,91 @@ struct TerminalScrollDelivery: Equatable, Sendable { struct TerminalScrollbackPrefetchState: Equatable, Sendable { static let defaultWindowRows = 600 static let defaultRefreshDistanceRows = 120.0 + static let defaultMaxWindowRows = 4800 var windowRows: Int var refreshDistanceRows: Double + var maxWindowRows: Int private var hasPrimedWindow = false private var accumulatedRowsSincePrefetch = 0.0 + private var historyFullyLoaded = false init( windowRows: Int = Self.defaultWindowRows, - refreshDistanceRows: Double = Self.defaultRefreshDistanceRows + refreshDistanceRows: Double = Self.defaultRefreshDistanceRows, + maxWindowRows: Int = Self.defaultMaxWindowRows ) { self.windowRows = max(0, windowRows) self.refreshDistanceRows = max(1, refreshDistanceRows) + self.maxWindowRows = max(self.windowRows, maxWindowRows) } mutating func rowsToPrefetch(forScrollLines lines: Double) -> Int? { - guard lines != 0, windowRows > 0 else { return nil } - accumulatedRowsSincePrefetch += abs(lines) + guard lines > 0, windowRows > 0 else { + accumulatedRowsSincePrefetch = 0 + return nil + } + guard !historyFullyLoaded else { return nil } + accumulatedRowsSincePrefetch += lines guard !hasPrimedWindow || accumulatedRowsSincePrefetch >= refreshDistanceRows else { return nil } + if hasPrimedWindow { + windowRows = min(windowRows + Self.defaultWindowRows, maxWindowRows) + } hasPrimedWindow = true accumulatedRowsSincePrefetch = 0 return windowRows } + + /// Stops deeper fetches after the host returns less history than requested, + /// or after the configured client cap has been served. + mutating func recordResponse(requestedRows: Int, availableRows: Int) { + guard requestedRows > 0 else { return } + if availableRows < requestedRows || requestedRows >= maxWindowRows { + historyFullyLoaded = true + } + } +} + +extension TerminalScrollDelivery { + /// Routes phone gestures without giving the primary-screen viewport two + /// owners. The local mirror scrolls primary history; the Mac only serves + /// periodic history snapshots. Alternate-screen wheel input still reaches + /// the real PTY, and an unknown screen keeps legacy forwarding until the + /// first render-grid frame reports its mode. + static func forScrollGesture( + surfaceID: String, + activeScreen: MobileTerminalRenderGridFrame.Screen?, + lines: Double, + col: Int, + row: Int, + prefetchState: inout TerminalScrollbackPrefetchState + ) -> TerminalScrollDelivery? { + switch activeScreen { + case .primary: + guard let maxScrollbackRows = prefetchState.rowsToPrefetch(forScrollLines: lines) else { + return nil + } + return TerminalScrollDelivery( + surfaceID: surfaceID, + lines: 0, + col: col, + row: row, + maxScrollbackRows: maxScrollbackRows + ) + case .alternate: + return TerminalScrollDelivery(surfaceID: surfaceID, lines: lines, col: col, row: row) + case nil: + return TerminalScrollDelivery( + surfaceID: surfaceID, + lines: lines, + col: col, + row: row, + maxScrollbackRows: prefetchState.rowsToPrefetch(forScrollLines: lines) + ) + } + } } struct TerminalScrollDeliveryQueue: Sendable { diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TerminalOutputDeliveryQueueTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TerminalOutputDeliveryQueueTests.swift index c96df9c1a63e..1bdbcf3bcff3 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TerminalOutputDeliveryQueueTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TerminalOutputDeliveryQueueTests.swift @@ -11,6 +11,30 @@ import Testing #expect(queue.pendingCount == 0) } +@Test func terminalOutputDeliveryMarksOnlyFullRenderGridAsReplacement() throws { + let full = try MobileTerminalRenderGridFrame.fromPlainRows( + surfaceID: "terminal", + stateSeq: 1, + columns: 12, + rows: 1, + text: "full" + ) + let delta = try MobileTerminalRenderGridFrame.fromPlainRows( + surfaceID: "terminal", + stateSeq: 2, + columns: 12, + rows: 1, + text: "delta", + full: false, + changedRows: [0] + ) + + #expect(TerminalOutputDelivery(renderGrid: full, replaceable: true).isFullReplacement) + #expect(!TerminalOutputDelivery(renderGrid: delta, replaceable: true).isFullReplacement) + #expect(!TerminalOutputDelivery(theme: full).isFullReplacement) + #expect(!TerminalOutputDelivery(bytes: Data(), replaceable: false).isFullReplacement) +} + @Test func terminalOutputQueueIgnoresCompletionWhenNothingIsInFlight() { var queue = TerminalOutputDeliveryQueue() diff --git a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TerminalScrollDeliveryQueueTests.swift b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TerminalScrollDeliveryQueueTests.swift index 1a7eecf24c73..b91729353747 100644 --- a/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TerminalScrollDeliveryQueueTests.swift +++ b/Packages/iOS/CmuxMobileShell/Tests/CmuxMobileShellTests/TerminalScrollDeliveryQueueTests.swift @@ -1,3 +1,4 @@ +import CMUXMobileCore import Foundation import Testing @testable import CmuxMobileShell @@ -67,14 +68,95 @@ import Testing #expect(coalesced.maxScrollbackRows == 600) } -@Test func terminalScrollbackPrefetchStatePrimesThenRefreshesByDistance() { +@Test func terminalScrollbackPrefetchStateOnlyCountsContinuousHistoryMovement() { var state = TerminalScrollbackPrefetchState(windowRows: 600, refreshDistanceRows: 10) #expect(state.rowsToPrefetch(forScrollLines: 0) == nil) + #expect(state.rowsToPrefetch(forScrollLines: -1) == nil) #expect(state.rowsToPrefetch(forScrollLines: 1) == 600) #expect(state.rowsToPrefetch(forScrollLines: 4) == nil) #expect(state.rowsToPrefetch(forScrollLines: -5.5) == nil) - #expect(state.rowsToPrefetch(forScrollLines: 0.5) == 600) + #expect(state.rowsToPrefetch(forScrollLines: 6) == nil) + #expect(state.rowsToPrefetch(forScrollLines: 4) == 1200) +} + +@Test func terminalScrollbackPrefetchStatePagesToCapThenStops() { + var state = TerminalScrollbackPrefetchState( + windowRows: 600, + refreshDistanceRows: 10, + maxWindowRows: 1800 + ) + + #expect(state.rowsToPrefetch(forScrollLines: 1) == 600) + #expect(state.rowsToPrefetch(forScrollLines: 10) == 1200) + #expect(state.rowsToPrefetch(forScrollLines: 10) == 1800) + state.recordResponse(requestedRows: 1800, availableRows: 1800) + #expect(state.rowsToPrefetch(forScrollLines: 100) == nil) +} + +@Test func terminalScrollbackPrefetchStateStopsAfterShortResponse() { + var state = TerminalScrollbackPrefetchState(windowRows: 600, refreshDistanceRows: 10) + + #expect(state.rowsToPrefetch(forScrollLines: 1) == 600) + state.recordResponse(requestedRows: 600, availableRows: 420) + #expect(state.rowsToPrefetch(forScrollLines: 100) == nil) +} + +@Test func terminalScrollGestureRoutingKeepsPrimaryViewportPhoneLocal() { + var state = TerminalScrollbackPrefetchState(windowRows: 600, refreshDistanceRows: 10) + + let priming = TerminalScrollDelivery.forScrollGesture( + surfaceID: "surface", + activeScreen: .primary, + lines: 2, + col: 3, + row: 4, + prefetchState: &state + ) + #expect(priming?.lines == 0) + #expect(priming?.maxScrollbackRows == 600) + + let localOnly = TerminalScrollDelivery.forScrollGesture( + surfaceID: "surface", + activeScreen: .primary, + lines: 3, + col: 3, + row: 4, + prefetchState: &state + ) + #expect(localOnly == nil) +} + +@Test func terminalScrollGestureRoutingForwardsAlternateScreenWheel() { + var state = TerminalScrollbackPrefetchState(windowRows: 600, refreshDistanceRows: 10) + + let delivery = TerminalScrollDelivery.forScrollGesture( + surfaceID: "surface", + activeScreen: .alternate, + lines: -3.5, + col: 7, + row: 9, + prefetchState: &state + ) + + #expect(delivery == TerminalScrollDelivery(surfaceID: "surface", lines: -3.5, col: 7, row: 9)) + #expect(state.rowsToPrefetch(forScrollLines: 1) == 600) +} + +@Test func terminalScrollGestureRoutingPreservesLegacyForwardingWhileScreenUnknown() { + var state = TerminalScrollbackPrefetchState(windowRows: 600, refreshDistanceRows: 10) + + let delivery = TerminalScrollDelivery.forScrollGesture( + surfaceID: "surface", + activeScreen: nil, + lines: 2, + col: 1, + row: 1, + prefetchState: &state + ) + + #expect(delivery?.lines == 2) + #expect(delivery?.maxScrollbackRows == 600) } @Test func terminalScrollQueueResetDropsPendingWork() { diff --git a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttyRuntime.swift b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttyRuntime.swift index f072852e6dbc..bc25b56a67b4 100644 --- a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttyRuntime.swift +++ b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttyRuntime.swift @@ -446,8 +446,8 @@ private extension GhosttyRuntime { } func applyGhosttyiOSDefaults(_ config: ghostty_config_t, theme: TerminalTheme) { - // The phone scrolls the authoritative Mac surface. Local scrollback exists - // only for bounded local text reads, so cap it below Ghostty's 10MB default. + // The phone owns its primary-screen viewport and pages bounded history + // snapshots from the Mac. Keep that local history below Ghostty's 10MB default. let defaults = """ scrollback-limit = 2000000 font-family = Menlo diff --git a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+LocalScrollbackScroll.swift b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+LocalScrollbackScroll.swift index 707240e2f734..f807ba188d40 100644 --- a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+LocalScrollbackScroll.swift +++ b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+LocalScrollbackScroll.swift @@ -9,8 +9,13 @@ extension GhosttySurfaceView { /// screens libghostty turns this into mouse-wheel bytes; the mirror is /// display-only and drops those bytes, so the authoritative Mac response /// remains the visible update for TUIs. - func applyLocalScrollbackScroll(lines: Double, col: Int, row: Int) { - guard lines != 0, let surface else { return } + @discardableResult + func applyLocalScrollbackScroll(lines: Double, col: Int, row: Int) -> Bool { + guard lines != 0, let surface else { return false } + let scrollPosition = GhosttySurfaceScrollPosition(surface: surface) + if scrollPosition.boundary()?.suppresses(lines: lines) == true { + return false + } let displayScale = window?.windowScene?.screen.scale ?? traitCollection.displayScale let scale = max(Double(displayScale), 1) let size = ghostty_surface_size(surface) @@ -22,6 +27,7 @@ extension GhosttySurfaceView { ghostty_surface_mouse_scroll(surface, 0, lines, 0) drawForWakeup() scheduleVisibleArtifactCountUpdate() + return true } } #endif diff --git a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+ThemeOutput.swift b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+ThemeOutput.swift index daf9131a9b4a..836718800217 100644 --- a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+ThemeOutput.swift +++ b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView+ThemeOutput.swift @@ -31,27 +31,50 @@ extension GhosttySurfaceView { public func processOutputAndWait( _ data: Data, terminalConfigTheme: TerminalTheme? + ) async -> Bool { + await processOutputAndWait( + data, + terminalConfigTheme: terminalConfigTheme, + preservingScrollbackOffset: false + ) + } + + private func processOutputAndWait( + _ data: Data, + terminalConfigTheme: TerminalTheme?, + preservingScrollbackOffset: Bool ) async -> Bool { await withCheckedContinuation { continuation in let operationID = registerPendingOutputApply( byteCount: data.count, continuation: continuation ) - processOutput(data, terminalConfigTheme: terminalConfigTheme) { [weak self] applied in + processOutput( + data, + terminalConfigTheme: terminalConfigTheme, + preservingScrollbackOffset: preservingScrollbackOffset + ) { [weak self] applied in self?.completePendingOutputApply(id: operationID, returning: applied) } } } - /// Dedicated seam for complete render-grid replacements. The regression - /// test intentionally starts with a plain forward so the first commit - /// demonstrates the reset-induced scroll jump. + /// Applies a complete render-grid replacement without moving the phone's + /// local viewport. Scroll geometry is captured and restored inside the + /// same serial Ghostty operation as the terminal rebuild. @discardableResult public func processFullReplacementOutputAndWait( _ data: Data, terminalConfigTheme: TerminalTheme? = nil ) async -> Bool { - await processOutputAndWait(data, terminalConfigTheme: terminalConfigTheme) + beginFullReplacementOutput() + let applied = await processOutputAndWait( + data, + terminalConfigTheme: terminalConfigTheme, + preservingScrollbackOffset: true + ) + finishFullReplacementOutput(applied: applied) + return applied } /// Enqueues the current raw config defaults on this surface's serial Ghostty queue. diff --git a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift index ec1e6ea5839f..8d3f09e7c9e9 100644 --- a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift +++ b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift @@ -1540,8 +1540,8 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { private func enqueueScrollMechanicsDelta(_ deltaY: CGFloat, touchPoint: CGPoint) { // The transparent UIScrollView supplies native iOS tracking, - // deceleration, and momentum. The Mac still owns terminal semantics: - // normal-screen scrollback and alt-screen mouse-wheel delivery. + // deceleration, and momentum. The local Ghostty mirror owns primary- + // screen scrollback; alternate-screen wheel input still reaches the Mac. guard deltaY != 0 else { return } let cellHeightPt = cellPixelSize.height / max(preferredScreenScale, 1) let divisor = cellHeightPt > 1 ? Double(cellHeightPt) * 3 : 42 @@ -1552,6 +1552,10 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { /// Coalesced native scroll forwarded to the Mac once per display-link frame. private var pendingScrollLines: Double = 0 private var pendingScrollCell: (col: Int, row: Int) = (0, 0) + /// A complete render-grid rebuild owns the local row space until its + /// compare-and-swap restoration finishes. Gesture deltas stay coalesced + /// during that window and are applied afterward. + private var fullReplacementOutputInFlight = false /// Map a touch point to a grid cell (shared effective grid with the Mac), so /// alt-screen mouse-wheel reports at the cell under the finger. @@ -1564,15 +1568,31 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { return (col, row) } - private func flushPendingScrollIfNeeded() { - guard pendingScrollLines != 0 else { return } + func flushPendingScrollIfNeeded() { + guard !fullReplacementOutputInFlight, pendingScrollLines != 0 else { return } let lines = pendingScrollLines let cell = pendingScrollCell pendingScrollLines = 0 - applyLocalScrollbackScroll(lines: lines, col: cell.col, row: cell.row) + let appliedLocally = applyLocalScrollbackScroll(lines: lines, col: cell.col, row: cell.row) + // Positive lines move toward older history. Keep delivering them at the + // loaded top so the shell can fetch a deeper phone-local window. + guard appliedLocally || lines > 0 else { return } delegate?.ghosttySurfaceView(self, didScrollLines: lines, atCol: cell.col, row: cell.row) } + func beginFullReplacementOutput() { + fullReplacementOutputInFlight = true + } + + func finishFullReplacementOutput(applied: Bool) { + fullReplacementOutputInFlight = false + if applied { + flushPendingScrollIfNeeded() + } else { + pendingScrollLines = 0 + } + } + /// A tap both raises the software keyboard (so the user can type) and /// forwards a left click at the tapped cell to the Mac. The Mac's libghostty /// self-gates: TUIs with mouse reporting get the click; a normal screen @@ -2044,6 +2064,7 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { func processOutput( _ data: Data, terminalConfigTheme outputConfigTheme: TerminalTheme? = nil, + preservingScrollbackOffset: Bool = false, completion: (@MainActor @Sendable (Bool) -> Void)? ) { guard !renderPipelineRecoveryPaused else { @@ -2095,6 +2116,9 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { // preserved) and hop back to main only for the Swift-side UI state. let workQueue = outputQueue workQueue.async { [weak self] in + let distanceFromBottom = preservingScrollbackOffset + ? GhosttySurfaceScrollPosition(surface: surface).distanceFromBottom() + : nil if let preparedConfigBits, let preparedConfig = ghostty_config_t(bitPattern: preparedConfigBits) { ghostty_surface_update_theme_config(surface, preparedConfig) @@ -2105,6 +2129,12 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { let pointer = baseAddress.assumingMemoryBound(to: CChar.self) ghostty_surface_process_output(surface, pointer, UInt(buffer.count)) } + let scrollPositionPreserved = if preservingScrollbackOffset, + let distanceFromBottom { + GhosttySurfaceScrollPosition(surface: surface).restore(distanceFromBottom) + } else { + !preservingScrollbackOffset + } #if DEBUG // `ghostty_surface_read_text` takes the same internal surface lock as // `process_output`. Reading it on the MAIN thread per-output (to feed @@ -2144,7 +2174,11 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { if !self.surfaceHasReceivedOutput { self.surfaceHasReceivedOutput = true self.snapshotFallbackView.isHidden = true - self.scrollInitialOutputToBottomIfNeeded() + if preservingScrollbackOffset { + self.shouldScrollInitialOutputToBottom = false + } else { + self.scrollInitialOutputToBottomIfNeeded() + } } let now = CACurrentMediaTime() if now - self.lastProcessOutputLogTime > 1.0 { @@ -2159,7 +2193,7 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { } self.onOutputProcessedForTesting?() #endif - completion?(true) + completion?(scrollPositionPreserved) } } } diff --git a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/TerminalScrollBoundary.swift b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/TerminalScrollBoundary.swift new file mode 100644 index 000000000000..7dc5197d2d6c --- /dev/null +++ b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/TerminalScrollBoundary.swift @@ -0,0 +1,63 @@ +#if canImport(UIKit) +import GhosttyKit + +/// Ghostty's authoritative primary-screen viewport range. +struct TerminalScrollBoundary: Equatable, Sendable { + let total: UInt64 + let offset: UInt64 + let len: UInt64 + + private var maximumOffset: UInt64 { + total > len ? total - len : 0 + } + + /// Whether a wheel delta points outward from a loaded history boundary. + /// A screen without scrollback fails open so alternate-screen TUIs keep + /// receiving their wheel input. + func suppresses(lines: Double) -> Bool { + guard lines != 0, total > len else { return false } + if lines > 0 { + return offset == 0 + } + return offset >= maximumOffset + } +} + +/// Thread-safe direct reads and compare-and-swap restoration for one Ghostty +/// surface. The C API owns the terminal lock, so callers never restore from an +/// asynchronously cached scrollbar callback. +nonisolated struct GhosttySurfaceScrollPosition { + let surface: ghostty_surface_t + + func boundary() -> TerminalScrollBoundary? { + var snapshot = ghostty_surface_scrollbar_s() + guard ghostty_surface_scrollbar(surface, &snapshot) else { return nil } + return TerminalScrollBoundary( + total: snapshot.total, + offset: snapshot.offset, + len: snapshot.len + ) + } + + func distanceFromBottom() -> UInt64? { + var snapshot = ghostty_surface_scrollbar_s() + guard ghostty_surface_scrollbar(surface, &snapshot) else { return nil } + let maximumOffset = snapshot.total > snapshot.len ? snapshot.total - snapshot.len : 0 + return maximumOffset - min(snapshot.offset, maximumOffset) + } + + func restore(_ distanceFromBottom: UInt64) -> Bool { + var current = ghostty_surface_scrollbar_s() + guard ghostty_surface_scrollbar(surface, ¤t) else { return false } + let maximumOffset = current.total > current.len ? current.total - current.len : 0 + let target = maximumOffset - min(distanceFromBottom, maximumOffset) + var positioned = ghostty_surface_scrollbar_s() + return ghostty_surface_scroll_to_row_if_revision( + surface, + target, + current.row_space_revision, + &positioned + ) && positioned.offset == target + } +} +#endif diff --git a/Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/TerminalScrollBoundaryTests.swift b/Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/TerminalScrollBoundaryTests.swift new file mode 100644 index 000000000000..97f872bb8794 --- /dev/null +++ b/Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/TerminalScrollBoundaryTests.swift @@ -0,0 +1,25 @@ +#if canImport(UIKit) +import Testing + +@testable import CmuxMobileTerminal + +@Test func terminalScrollBoundarySuppressesOutwardMovementAtLoadedEnds() { + let top = TerminalScrollBoundary(total: 100, offset: 0, len: 20) + let middle = TerminalScrollBoundary(total: 100, offset: 40, len: 20) + let bottom = TerminalScrollBoundary(total: 100, offset: 80, len: 20) + + #expect(top.suppresses(lines: 1)) + #expect(!top.suppresses(lines: -1)) + #expect(!middle.suppresses(lines: 1)) + #expect(!middle.suppresses(lines: -1)) + #expect(!bottom.suppresses(lines: 1)) + #expect(bottom.suppresses(lines: -1)) +} + +@Test func terminalScrollBoundaryFailsOpenWithoutScrollback() { + let boundary = TerminalScrollBoundary(total: 20, offset: 0, len: 20) + + #expect(!boundary.suppresses(lines: 1)) + #expect(!boundary.suppresses(lines: -1)) +} +#endif diff --git a/Sources/TerminalController+MobileScrollPrefetch.swift b/Sources/TerminalController+MobileScrollPrefetch.swift index 9b1f7b501f30..f806c31d5edd 100644 --- a/Sources/TerminalController+MobileScrollPrefetch.swift +++ b/Sources/TerminalController+MobileScrollPrefetch.swift @@ -10,7 +10,7 @@ extension TerminalController { /// Larger history window returned only on explicit mobile scroll prefetch /// requests, keeping ordinary scroll RPCs small. - nonisolated static let mobileScrollPrefetchScrollbackLineBudget = 600 + nonisolated static let mobileScrollPrefetchScrollbackLineBudget = 4800 func mobileTerminalRenderGridFrame( terminalPanel: TerminalPanel, diff --git a/Sources/TerminalController.swift b/Sources/TerminalController.swift index f98d098b82e2..3513625e363b 100644 --- a/Sources/TerminalController.swift +++ b/Sources/TerminalController.swift @@ -14279,11 +14279,10 @@ class TerminalController { return .ok(payload) } - /// Forward a phone scroll gesture to the real surface so libghostty handles - /// it per-mode (scrollback in the normal screen, mouse-wheel to the program - /// in the alt screen). The producer already exports the live `vp_top`, so - /// the resulting viewport mirrors back to the phone; nudge an emit since a - /// pure scroll with no PTY output may not fire a render/tick on its own. + /// Handle phone scroll RPCs. Primary-screen history stays phone-local and + /// uses zero-delta requests only to fetch deeper snapshots. Alternate- + /// screen wheel input reaches the real surface so TUIs receive it; nudge an + /// emit because wheel input without PTY output may not trigger one itself. func v2MobileTerminalScroll(params: [String: Any]) -> V2CallResult { if let error = mobileWorkspaceIDValidationError(params: params) { return error From bf9145b342c5f393606297542a3826c52574f019 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Fri, 17 Jul 2026 20:53:17 -0700 Subject: [PATCH 3/5] Fix full-replay completion semantics --- .../GhosttySurfaceView.swift | 12 +++---- .../TerminalScrollBoundary.swift | 34 +++++++++++++------ .../TerminalScrollBoundaryTests.swift | 12 +++++++ 3 files changed, 41 insertions(+), 17 deletions(-) diff --git a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift index 8d3f09e7c9e9..3e15fb49d1b4 100644 --- a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift +++ b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/GhosttySurfaceView.swift @@ -2129,11 +2129,11 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { let pointer = baseAddress.assumingMemoryBound(to: CChar.self) ghostty_surface_process_output(surface, pointer, UInt(buffer.count)) } - let scrollPositionPreserved = if preservingScrollbackOffset, - let distanceFromBottom { - GhosttySurfaceScrollPosition(surface: surface).restore(distanceFromBottom) - } else { - !preservingScrollbackOffset + if preservingScrollbackOffset, let distanceFromBottom { + // Output application and best-effort viewport restoration have + // separate contracts. A failed compare-and-swap must not report + // already-applied bytes as dropped and start replay recovery. + _ = GhosttySurfaceScrollPosition(surface: surface).restore(distanceFromBottom) } #if DEBUG // `ghostty_surface_read_text` takes the same internal surface lock as @@ -2193,7 +2193,7 @@ public final class GhosttySurfaceView: UIView, TerminalSurfaceHosting { } self.onOutputProcessedForTesting?() #endif - completion?(scrollPositionPreserved) + completion?(true) } } } diff --git a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/TerminalScrollBoundary.swift b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/TerminalScrollBoundary.swift index 7dc5197d2d6c..a2e464a5778e 100644 --- a/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/TerminalScrollBoundary.swift +++ b/Packages/iOS/CmuxMobileTerminal/Sources/CmuxMobileTerminal/TerminalScrollBoundary.swift @@ -11,6 +11,14 @@ struct TerminalScrollBoundary: Equatable, Sendable { total > len ? total - len : 0 } + var distanceFromBottom: UInt64 { + maximumOffset - min(offset, maximumOffset) + } + + func targetOffset(distanceFromBottom: UInt64) -> UInt64 { + maximumOffset - min(distanceFromBottom, maximumOffset) + } + /// Whether a wheel delta points outward from a loaded history boundary. /// A screen without scrollback fails open so alternate-screen TUIs keep /// receiving their wheel input. @@ -32,25 +40,19 @@ nonisolated struct GhosttySurfaceScrollPosition { func boundary() -> TerminalScrollBoundary? { var snapshot = ghostty_surface_scrollbar_s() guard ghostty_surface_scrollbar(surface, &snapshot) else { return nil } - return TerminalScrollBoundary( - total: snapshot.total, - offset: snapshot.offset, - len: snapshot.len - ) + return Self.boundary(from: snapshot) } func distanceFromBottom() -> UInt64? { - var snapshot = ghostty_surface_scrollbar_s() - guard ghostty_surface_scrollbar(surface, &snapshot) else { return nil } - let maximumOffset = snapshot.total > snapshot.len ? snapshot.total - snapshot.len : 0 - return maximumOffset - min(snapshot.offset, maximumOffset) + boundary()?.distanceFromBottom } func restore(_ distanceFromBottom: UInt64) -> Bool { var current = ghostty_surface_scrollbar_s() guard ghostty_surface_scrollbar(surface, ¤t) else { return false } - let maximumOffset = current.total > current.len ? current.total - current.len : 0 - let target = maximumOffset - min(distanceFromBottom, maximumOffset) + let target = Self.boundary(from: current).targetOffset( + distanceFromBottom: distanceFromBottom + ) var positioned = ghostty_surface_scrollbar_s() return ghostty_surface_scroll_to_row_if_revision( surface, @@ -59,5 +61,15 @@ nonisolated struct GhosttySurfaceScrollPosition { &positioned ) && positioned.offset == target } + + private static func boundary( + from snapshot: ghostty_surface_scrollbar_s + ) -> TerminalScrollBoundary { + TerminalScrollBoundary( + total: snapshot.total, + offset: snapshot.offset, + len: snapshot.len + ) + } } #endif diff --git a/Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/TerminalScrollBoundaryTests.swift b/Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/TerminalScrollBoundaryTests.swift index 97f872bb8794..d66ece30ba2d 100644 --- a/Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/TerminalScrollBoundaryTests.swift +++ b/Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/TerminalScrollBoundaryTests.swift @@ -22,4 +22,16 @@ import Testing #expect(!boundary.suppresses(lines: 1)) #expect(!boundary.suppresses(lines: -1)) } + +@Test func terminalScrollBoundaryMapsOffsetsFromTheBottom() { + let top = TerminalScrollBoundary(total: 100, offset: 0, len: 20) + let middle = TerminalScrollBoundary(total: 100, offset: 40, len: 20) + let bottom = TerminalScrollBoundary(total: 100, offset: 80, len: 20) + + #expect(top.distanceFromBottom == 80) + #expect(middle.distanceFromBottom == 40) + #expect(bottom.distanceFromBottom == 0) + #expect(bottom.targetOffset(distanceFromBottom: 40) == 40) + #expect(bottom.targetOffset(distanceFromBottom: 100) == 0) +} #endif From d14c1d3ee8f4cdc08b821ba68d1654dd7612c181 Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Fri, 17 Jul 2026 22:48:02 -0700 Subject: [PATCH 4/5] Add iOS endpoint gesture UI coverage --- ios/cmuxUITests/cmuxUITests.swift | 142 ++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) diff --git a/ios/cmuxUITests/cmuxUITests.swift b/ios/cmuxUITests/cmuxUITests.swift index 16bb31d40633..c2376f678017 100644 --- a/ios/cmuxUITests/cmuxUITests.swift +++ b/ios/cmuxUITests/cmuxUITests.swift @@ -323,6 +323,148 @@ final class cmuxUITests: XCTestCase { ) } + @MainActor + func testTerminalEndpointRapidSwipesStayPinnedAndReverseCleanly() throws { + let app = launchApp(mockData: false, environment: [ + "CMUX_BOTTOM_SCROLL_STRESS": "1", + ]) + defer { app.terminate() } + let surface = app.otherElements["MobileTerminalSurface"] + XCTAssertTrue(surface.waitForExistence(timeout: 8)) + + func scrollbar(_ dock: [String: String]) -> (total: Int, offset: Int, len: Int)? { + guard let total = dock["scrollTotal"].flatMap(Int.init), + let offset = dock["scrollOffset"].flatMap(Int.init), + let len = dock["scrollLen"].flatMap(Int.init) else { + return nil + } + return (total, offset, len) + } + + func maximumOffset(_ snapshot: (total: Int, offset: Int, len: Int)) -> Int { + max(0, snapshot.total - snapshot.len) + } + + let initialDock = waitForDock(in: app, timeout: 8, describe: "endpoint stress fixture at bottom") { + guard $0["bottomStressPhase"] == "done", let snapshot = scrollbar($0) else { return false } + return $0["scrollAtBottom"] == "1" + && snapshot.total > snapshot.len + && snapshot.offset >= maximumOffset(snapshot) - 1 + } + guard let initial = scrollbar(initialDock) else { + XCTFail("Endpoint stress fixture did not expose Ghostty scrollbar state. dock=\(initialDock)") + return + } + + guard let renderMinY = initialDock["renderMinY"].flatMap(Double.init), + let renderMaxY = initialDock["renderMaxY"].flatMap(Double.init) else { + XCTFail("Endpoint stress fixture did not expose its render bounds. dock=\(initialDock)") + return + } + let surfaceFrame = surface.frame + let renderHeight = CGFloat(renderMaxY - renderMinY) + let topGestureInset = min(72, max(12, renderHeight / 3)) + let upperY = surfaceFrame.minY + CGFloat(renderMinY) + topGestureInset + let lowerY = surfaceFrame.minY + CGFloat(renderMaxY) - 12 + guard lowerY - upperY >= 40 else { + XCTFail("Terminal render region is too short for endpoint gestures. surface=\(surfaceFrame) dock=\(initialDock)") + return + } + let screenOrigin = app.coordinate(withNormalizedOffset: .zero) + let upperRenderCoordinate = screenOrigin.withOffset(CGVector(dx: surfaceFrame.midX, dy: upperY)) + let lowerRenderCoordinate = screenOrigin.withOffset(CGVector(dx: surfaceFrame.midX, dy: lowerY)) + + func swipeUpInsideRenderRegion() { + lowerRenderCoordinate.press( + forDuration: 0.01, + thenDragTo: upperRenderCoordinate, + withVelocity: .fast, + thenHoldForDuration: 0 + ) + } + + func swipeDownInsideRenderRegion() { + upperRenderCoordinate.press( + forDuration: 0.01, + thenDragTo: lowerRenderCoordinate, + withVelocity: .fast, + thenHoldForDuration: 0 + ) + } + + for _ in 0..<5 { + swipeUpInsideRenderRegion() + } + RunLoop.current.run(until: Date().addingTimeInterval(0.6)) + let afterOutwardSwipes = waitForDock(in: app, describe: "rapid outward swipes remain at bottom") { + guard let snapshot = scrollbar($0) else { return false } + return $0["scrollAtBottom"] == "1" + && snapshot.offset >= maximumOffset(snapshot) - 1 + } + guard let outward = scrollbar(afterOutwardSwipes) else { + XCTFail("Scrollbar state disappeared after rapid outward swipes. dock=\(afterOutwardSwipes)") + return + } + XCTAssertLessThanOrEqual( + abs(outward.offset - initial.offset), + 1, + "Rapid outward swipes at the loaded bottom must not move or rebound the terminal viewport. before=\(initial) after=\(outward)" + ) + + swipeDownInsideRenderRegion() + let olderDock = waitForDock(in: app, describe: "reversal reaches older terminal rows") { + guard let snapshot = scrollbar($0) else { return false } + return $0["scrollAtBottom"] == "0" + && snapshot.offset <= maximumOffset(snapshot) - 2 + } + guard let older = scrollbar(olderDock) else { + XCTFail("Scrollbar state disappeared after reversing toward older rows. dock=\(olderDock)") + return + } + XCTAssertLessThan( + older.offset, + maximumOffset(older), + "Reversing from the bottom must move into older terminal rows. snapshot=\(older)" + ) + + for _ in 0..<16 { + swipeUpInsideRenderRegion() + if surfaceDock(in: app)["scrollAtBottom"] == "1" { + break + } + } + let restoredDock = waitForDock(in: app, describe: "reversal returns to bottom without snap-back") { + guard let snapshot = scrollbar($0) else { return false } + return $0["scrollAtBottom"] == "1" + && snapshot.offset >= maximumOffset(snapshot) - 1 + } + guard let restored = scrollbar(restoredDock) else { + XCTFail("Scrollbar state disappeared after returning to bottom. dock=\(restoredDock)") + return + } + XCTAssertEqual(restoredDock["scrollAtBottom"], "1", "Ghostty must confirm the restored bottom. dock=\(restoredDock)") + + for _ in 0..<3 { + swipeUpInsideRenderRegion() + } + RunLoop.current.run(until: Date().addingTimeInterval(0.6)) + let finalDock = waitForDock(in: app, describe: "second outward burst remains pinned") { + guard let snapshot = scrollbar($0) else { return false } + return $0["scrollAtBottom"] == "1" + && snapshot.offset >= maximumOffset(snapshot) - 1 + } + guard let final = scrollbar(finalDock) else { + XCTFail("Scrollbar state disappeared after the second outward burst. dock=\(finalDock)") + return + } + XCTAssertLessThanOrEqual( + abs(final.offset - restored.offset), + 1, + "A second outward burst after reversal must remain pinned at the loaded bottom. before=\(restored) after=\(final)" + ) + XCTAssertEqual(finalDock["staleViewportObserved"], "0", "Endpoint gestures must not expose a stale viewport. dock=\(finalDock)") + } + @MainActor func testWorkspaceToolbarCreatesWorkspaceAndTerminal() async throws { let server = try MobileSyncMockHostServer(createdWorkspaceTerminalDelay: 1.5) From c71a77ff5860342cc3871b82062a5b89a000eb7e Mon Sep 17 00:00:00 2001 From: cmux reload-cloud Date: Fri, 17 Jul 2026 22:53:35 -0700 Subject: [PATCH 5/5] Verify full replay row-space replacement --- .../FullReplacementScrollPositionTests.swift | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/FullReplacementScrollPositionTests.swift b/Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/FullReplacementScrollPositionTests.swift index 184bb6de71e7..7ff24754c365 100644 --- a/Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/FullReplacementScrollPositionTests.swift +++ b/Packages/iOS/CmuxMobileTerminal/Tests/CmuxMobileTerminalTests/FullReplacementScrollPositionTests.swift @@ -51,10 +51,19 @@ struct FullReplacementScrollPositionTests { return predicate() } - private func scrollbarDistanceFromBottom(_ view: GhosttySurfaceView) -> UInt64? { + private func scrollbarSnapshot(_ view: GhosttySurfaceView) -> ghostty_surface_scrollbar_s? { guard let surface = view.surface else { return nil } var snapshot = ghostty_surface_scrollbar_s() guard ghostty_surface_scrollbar(surface, &snapshot) else { return nil } + return snapshot + } + + private func scrollbarDistanceFromBottom(_ view: GhosttySurfaceView) -> UInt64? { + guard let snapshot = scrollbarSnapshot(view) else { return nil } + return scrollbarDistanceFromBottom(snapshot) + } + + private func scrollbarDistanceFromBottom(_ snapshot: ghostty_surface_scrollbar_s) -> UInt64 { let maximumOffset = snapshot.total > snapshot.len ? snapshot.total - snapshot.len : 0 return maximumOffset - min(snapshot.offset, maximumOffset) } @@ -93,7 +102,8 @@ struct FullReplacementScrollPositionTests { #expect(await waitUntil { (scrollbarDistanceFromBottom(harness.view) ?? 0) >= 40 }) - let before = try #require(scrollbarDistanceFromBottom(harness.view)) + let beforeSnapshot = try #require(scrollbarSnapshot(harness.view)) + let before = scrollbarDistanceFromBottom(beforeSnapshot) #expect( await harness.view.processFullReplacementOutputAndWait( @@ -101,8 +111,13 @@ struct FullReplacementScrollPositionTests { terminalConfigTheme: frame.terminalConfigTheme ) ) - let after = try #require(scrollbarDistanceFromBottom(harness.view)) + let afterSnapshot = try #require(scrollbarSnapshot(harness.view)) + let after = scrollbarDistanceFromBottom(afterSnapshot) + #expect( + afterSnapshot.row_space_revision != beforeSnapshot.row_space_revision, + "full replay must rebuild the row space before scroll restoration is judged" + ) #expect(after == before, "full replay moved the viewport from \(before) rows above bottom to \(after)") } }