Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ extension MobileShellComposite {
data: immediate.bytes,
streamToken: streamToken,
viewportPolicy: immediate.viewportPolicy,
isFullReplacement: immediate.isFullReplacement,
terminalConfigTheme: immediate.terminalConfigTheme
)
)
Expand Down Expand Up @@ -418,6 +419,7 @@ extension MobileShellComposite {
data: next.bytes,
streamToken: streamToken,
viewportPolicy: next.viewportPolicy,
isFullReplacement: next.isFullReplacement,
terminalConfigTheme: next.terminalConfigTheme
))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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()
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import CMUXMobileCore
import Foundation

struct TerminalScrollDelivery: Equatable, Sendable {
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import CMUXMobileCore
import Foundation
import Testing
@testable import CmuxMobileShell
Expand Down Expand Up @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,22 @@ 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?

public init(
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
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading