Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
2138a8c
Add iOS terminal typing replay regressions
austinywang Jul 2, 2026
1d2b505
Stabilize iOS typing render-grid catch-up
austinywang Jul 2, 2026
5003f14
Fix iOS render-grid replay guard fallout
austinywang Jul 2, 2026
8246cd1
Retry render-grid replay dropped during input catch-up
austinywang Jul 2, 2026
2842814
Harden render-grid input catch-up recovery
austinywang Jul 2, 2026
1cad377
Complete synchronized render-grid replay reset
austinywang Jul 2, 2026
400ae09
Coalesce render-grid input catch-up refreshes
austinywang Jul 2, 2026
91c39dd
Clear replay barrier after pending input retry exhaustion
austinywang Jul 2, 2026
ff26df7
Reset dynamic OSC colors during render-grid replay
austinywang Jul 2, 2026
ec0af10
Require replay after dropped render-grid deltas
austinywang Jul 2, 2026
53caec9
Keep dropped render-grid marker until replay delivery
austinywang Jul 2, 2026
7cd3b15
Fix render-grid stale recovery reset edges
austinywang Jul 2, 2026
ff7b0c1
Reset render-grid replay style before clears
austinywang Jul 2, 2026
dedd37a
Update render-grid replay byte expectation
austinywang Jul 2, 2026
28b3961
Fix render-grid replay test helpers
austinywang Jul 2, 2026
6245bda
Retry stale non-barrier render-grid replays
austinywang Jul 2, 2026
82325a6
Reset render-grid replay modes before restore
austinywang Jul 2, 2026
e244980
Reset render-grid report modes
austinywang Jul 2, 2026
661fee5
Import diagnostics for replay retry logging
austinywang Jul 2, 2026
009ecb2
Restore grapheme mode before render-grid paint
austinywang Jul 2, 2026
43d5d83
Bound dropped render-grid replay requests
austinywang Jul 2, 2026
434d7e3
Merge remote-tracking branch 'origin/main' into issue-7164-ios-typing…
austinywang Jul 2, 2026
e5128a0
Treat CRLF as one grapheme in replay presentation probe
austinywang Jul 2, 2026
0240e2c
Widen render-grid test frames for descriptive marker texts
austinywang Jul 2, 2026
a13b144
Reset OSC 133 semantic prompt state in full render-grid replay
austinywang Jul 2, 2026
ebacf70
Count no-progress replay responses against the retry budget
austinywang Jul 2, 2026
b4492ef
Overwrite Ghostty's saved-mode bank during full render-grid replay
austinywang Jul 2, 2026
00e3868
Reset primary cursor shape before alternate-screen replay entry
austinywang Jul 2, 2026
38d370c
Merge remote-tracking branch 'origin/main' into issue-7164-ios-typing…
austinywang Jul 2, 2026
fb09b5b
Reset replay retry budget at new input catch-up episodes
austinywang Jul 2, 2026
5d6298c
Arm bounded replay for dropped hybrid alternate-exit frames
austinywang Jul 2, 2026
059e42d
Include cursor modes in the replay saved-mode bank reset
austinywang Jul 2, 2026
c819347
Clarify fresh-budget test comment and use the retry constant
austinywang Jul 2, 2026
5d8639a
Track fresh-budget test comment growth in the length budget
austinywang Jul 2, 2026
2820189
Reset saved cursors to the RIS baseline during full replay
austinywang Jul 2, 2026
01fc8b1
Clear stale DECCOLM state during full render-grid replay
austinywang Jul 2, 2026
00fea82
Merge remote-tracking branch 'origin/main' into issue-7164-ios-typing…
austinywang Jul 2, 2026
98101ba
Reset ?1048 save-cursor mode state in the replay baseline
austinywang Jul 2, 2026
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 @@ -89,10 +89,12 @@ public struct MobileTerminalRenderGridReplay: Sendable {
let stylesByID = styleMapByID(frame.styles)
let defaultStyle = stylesByID[0] ?? .default

// Reset to a known state, then apply everything inside a synchronized
// update so the client never shows a partially-restored screen.
bytes.append(Data("\u{1B}c".utf8))
// Apply the whole restore inside a synchronized update so the client
// never presents the empty reset/clear frame before the snapshot lands.
// `ESC c` clears immediately before synchronized output can be enabled,
// so use a soft reset plus explicit primary-screen clear instead.
bytes.append(Data("\u{1B}[?2026h".utf8))
bytes.append(Data("\u{1B}[!p\u{1B}[?2026h\u{1B}[?1049l\u{1B}[H\u{1B}[2J\u{1B}[3J".utf8))
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved

// Dynamic default colors (OSC 10/11/12). Cells already carry explicit
// RGB, so these mainly fix the cursor color and color queries.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ import Testing
let decoded = try MobileTerminalRenderGridFrame.decodeJSONObject(frame.jsonObject())
#expect(decoded == frame)
// A full snapshot is restored as a synchronized, autowrap-off scrolling
// flow: reset, paint each viewport row (CHA-positioned spans), then restore
// the cursor.
// flow: soft-reset and clear, paint each viewport row (CHA-positioned
// spans), then restore the cursor.
#expect(String(data: frame.vtReplacementBytes(), encoding: .utf8) ==
"\u{1B}c\u{1B}[?2026h" +
"\u{1B}[?2026h\u{1B}[!p\u{1B}[?2026h\u{1B}[?1049l\u{1B}[H\u{1B}[2J\u{1B}[3J" +
"\u{1B}[?7l\u{1B}[?25l\u{1B}[0m" +
"\u{1B}[0m\u{1B}[1Galpha" +
"\r\n\u{1B}[0m" +
Expand All @@ -34,6 +34,31 @@ import Testing
)
}

@Test func renderGridFullSnapshotDoesNotPresentBlankFrameBeforeContent() throws {
let frame = try MobileTerminalRenderGridFrame.fromPlainRows(
surfaceID: "terminal-a",
stateSeq: 42,
columns: 8,
rows: 2,
text: "visible\nrow",
cursor: .init(row: 1, column: 3)
)

let presentedFrames = try ReplayPresentationProbe.presentedRows(
from: frame.vtReplacementBytes(),
rows: frame.rows,
columns: frame.columns
)

#expect(presentedFrames.last?.contains { $0.contains("visible") } == true)
#expect(
!presentedFrames.contains(where: { frameRows in
frameRows.allSatisfy { $0.trimmingCharacters(in: .whitespaces).isEmpty }
}),
"full replay must not present the empty reset frame before synchronized snapshot content lands"
)
}

@Test func renderGridDeltaClearsOnlyChangedRows() throws {
let frame = try MobileTerminalRenderGridFrame.fromPlainRows(
surfaceID: "terminal-a",
Expand Down Expand Up @@ -207,6 +232,140 @@ import Testing
}
}

private struct ReplayPresentationProbe {
static func presentedRows(from data: Data, rows: Int, columns: Int) throws -> [[String]] {
let text = try #require(String(data: data, encoding: .utf8))
var probe = ReplayPresentationProbe(rows: rows, columns: columns)
probe.consume(text)
return probe.presentedFrames
}

private let rows: Int
private let columns: Int
private var cells: [[Character]]
private var row = 0
private var column = 0
private var synchronized = false
private(set) var presentedFrames: [[String]] = []

private init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
cells = Array(
repeating: Array(repeating: Character(" "), count: columns),
count: rows
)
}

private mutating func consume(_ text: String) {
var index = text.startIndex
while index < text.endIndex {
switch text[index] {
case "\u{1B}":
index = consumeEscape(in: text, from: index)
case "\r":
column = 0
index = text.index(after: index)
case "\n":
row = min(row + 1, max(rows - 1, 0))
index = text.index(after: index)
default:
if cells.indices.contains(row), cells[row].indices.contains(column) {
cells[row][column] = text[index]
}
column = min(column + 1, max(columns - 1, 0))
index = text.index(after: index)
}
}
}

private mutating func consumeEscape(in text: String, from escapeIndex: String.Index) -> String.Index {
var index = text.index(after: escapeIndex)
guard index < text.endIndex else { return index }
if text[index] == "c" {
clearScreen()
presentIfUnsynchronized()
return text.index(after: index)
}
guard text[index] == "[" else {
return text.index(after: index)
}
index = text.index(after: index)
let parametersStart = index
while index < text.endIndex, !isCSIFinalByte(text[index]) {
index = text.index(after: index)
}
guard index < text.endIndex else { return index }
let parameters = String(text[parametersStart..<index])
consumeCSI(parameters: parameters, final: text[index])
return text.index(after: index)
}

private mutating func consumeCSI(parameters: String, final: Character) {
switch final {
case "h" where parameters == "?2026":
synchronized = true
case "l" where parameters == "?2026":
synchronized = false
recordFrame()
case "H", "f":
let values = csiIntegerParameters(parameters)
row = min(max((values.first ?? 1) - 1, 0), max(rows - 1, 0))
column = min(max((values.dropFirst().first ?? 1) - 1, 0), max(columns - 1, 0))
case "G":
column = min(max((csiIntegerParameters(parameters).first ?? 1) - 1, 0), max(columns - 1, 0))
case "J":
if parameters.contains("2") {
clearScreen()
presentIfUnsynchronized()
}
case "K":
if parameters.contains("2"), cells.indices.contains(row) {
cells[row] = Array(repeating: Character(" "), count: columns)
presentIfUnsynchronized()
}
default:
break
}
}

private mutating func clearScreen() {
cells = Array(
repeating: Array(repeating: Character(" "), count: columns),
count: rows
)
row = 0
column = 0
}

private mutating func presentIfUnsynchronized() {
if !synchronized {
recordFrame()
}
}

private mutating func recordFrame() {
presentedFrames.append(cells.map { String($0) })
}

private func isCSIFinalByte(_ character: Character) -> Bool {
guard let scalar = character.unicodeScalars.first,
character.unicodeScalars.count == 1 else {
return false
}
return (0x40...0x7E).contains(scalar.value)
}

private func csiIntegerParameters(_ parameters: String) -> [Int] {
parameters
.split(separator: ";")
.map { component in
let digits = component.drop { !$0.isNumber }
return Int(digits) ?? 1
}
}
}

@Test func renderGridPreviousShapeKeepsWidthOneSymbolsNarrow() throws {
let object: [String: Any] = [
"format": MobileTerminalRenderGridFrame.currentFormat,
Expand Down Expand Up @@ -319,7 +478,7 @@ import Testing
)

let vt = try #require(String(data: frame.vtPatchBytes(), encoding: .utf8))
#expect(vt.hasPrefix("\u{1B}c\u{1B}[?2026h"))
#expect(vt.hasPrefix("\u{1B}[?2026h\u{1B}[!p\u{1B}[?2026h"))
#expect(vt.hasSuffix("\u{1B}[?2026l"))
#expect(vt.contains("\u{1B}[?1049h")) // entered the alternate screen
#expect(vt.contains("\u{1B}[?1000h")) // mouse mode restored
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6629,26 +6629,12 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
|| (terminalOutputTransport == .hybrid && terminalActiveScreenBySurfaceID[surfaceID] == .alternate)
if canRenderGridAdvancePendingSeq, terminalEventListenerTask != nil {
let pendingSeq = pendingTerminalByteEndSeqBySurfaceID[surfaceID]
pendingTerminalByteEndSeqBySurfaceID[surfaceID] = max(remoteSeq, pendingSeq ?? 0)
if let pendingSeq, localSeq < pendingSeq {
MobileDebugLog.anchormux("sync.input_seq_still_behind surface=\(surfaceID) local=\(localSeq) pending=\(pendingSeq) remote=\(remoteSeq)")
diagnosticLog?.record(DiagnosticEvent(
.inputSeqBehind,
surface: Self.diagnosticSurfaceHandle(surfaceID),
a: Int(clamping: localSeq),
b: Int(clamping: remoteSeq),
c: Int(clamping: pendingSeq)
))
mobileShellLog.info("terminal render-grid still behind after input surface=\(surfaceID, privacy: .public) localSeq=\(localSeq, privacy: .public) pendingSeq=\(pendingSeq, privacy: .public) remoteSeq=\(remoteSeq, privacy: .public)")
resyncTerminalOutput(
reason: "input_seq_still_behind",
restartEventStream: true,
surfaceIDs: [surfaceID]
)
} else {
MobileDebugLog.anchormux("sync.input_seq_wait surface=\(surfaceID) local=\(localSeq) remote=\(remoteSeq)")
refreshTerminalEventSubscription(reason: "input_seq_wait")
}
let targetSeq = max(remoteSeq, pendingSeq ?? 0)
pendingTerminalByteEndSeqBySurfaceID[surfaceID] = targetSeq
MobileDebugLog.anchormux(
"sync.input_seq_wait surface=\(surfaceID) local=\(localSeq) pending=\(targetSeq) remote=\(remoteSeq)"
)
refreshTerminalEventSubscription(reason: "input_seq_wait")
return
}
MobileDebugLog.anchormux("sync.input_seq_behind surface=\(surfaceID) local=\(localSeq) remote=\(remoteSeq)")
Expand Down Expand Up @@ -6873,6 +6859,9 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
hasTerminalOutputSink(surfaceID: renderGrid.surfaceID) else {
return
}
guard !shouldDropRenderGridBehindPendingInput(renderGrid, source: source) else {
return
}
if let deliveredSeq = deliveredTerminalByteEndSeqBySurfaceID[renderGrid.surfaceID],
deliveredSeq > renderGrid.stateSeq {
MobileDebugLog.anchormux(
Expand Down Expand Up @@ -6974,6 +6963,20 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
}
}

private func shouldDropRenderGridBehindPendingInput(
_ renderGrid: MobileTerminalRenderGridFrame,
source: String
) -> Bool {
guard let pendingSeq = pendingTerminalByteEndSeqBySurfaceID[renderGrid.surfaceID],
renderGrid.stateSeq < pendingSeq else {
return false
}
MobileDebugLog.anchormux(
"sync.render_grid_wait_input source=\(source) surface=\(renderGrid.surfaceID) frame=\(renderGrid.stateSeq) pending=\(pendingSeq)"
)
return true
}

/// The Mac-pushed live font-size stream for a terminal surface.
///
/// A mounted surface obtains this alongside ``terminalOutputStream(surfaceID:)``
Expand Down Expand Up @@ -7218,6 +7221,15 @@ public final class MobileShellComposite: MobileTerminalOutputSinking {
MobileDebugLog.anchormux("CMUX_REPLAY raw_tail surface=\(surfaceID) bytes=\(bytes?.count ?? -1) seq=\(replaySeq ?? 0)")
}
if let renderGrid {
guard !self.shouldDropRenderGridBehindPendingInput(renderGrid, source: "replay") else {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
self.clearTerminalReplayBarrierIfCurrent(
surfaceID: surfaceID,
token: replayBarrierTokenForRequest,
reason: "pending_input",
preserveDroppedOutput: true
)
return
Comment thread
austinywang marked this conversation as resolved.
Resolved
}
let accepted = self.deliverTerminalRenderGrid(
renderGrid,
surfaceID: surfaceID,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ actor LivenessHostRouter {
private var replayTexts: [String] = []
private var replayFailuresRemaining = 0
private var emptyReplayResponsesRemaining = 0
private var terminalInputSeqs: [UInt64] = []

func record(method: String?, topics: [String]?) {
recorded.append(RecordedRequest(method: method, topics: topics))
Expand Down Expand Up @@ -186,6 +187,10 @@ actor LivenessHostRouter {
emptyReplayResponsesRemaining += count
}

func enqueueTerminalInputSeqs(_ seqs: [UInt64]) {
terminalInputSeqs.append(contentsOf: seqs)
}

/// Hold every `mobile.events.subscribe` response until released.
func setHoldSubscribe(_ hold: Bool) {
holdSubscribe = hold
Expand Down Expand Up @@ -308,8 +313,9 @@ actor LivenessHostRouter {
case "mobile.events.unsubscribe", "mobile.terminal.viewport":
return try? Self.resultFrame(id: id, result: [:])
case "terminal.input":
let terminalSeq = terminalInputSeqs.isEmpty ? 100 : terminalInputSeqs.removeFirst()
return try? Self.resultFrame(id: id, result: [
"terminal_seq": 100,
"terminal_seq": terminalSeq,
])
default:
return try? Self.errorFrame(id: id, message: "Unexpected method \(method ?? "nil")")
Expand Down
Loading
Loading