Skip to content

Commit 49a9e80

Browse files
fix(terminal): keep shared terminal grids in sync (pingdotgg#24352)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent fe55faf commit 49a9e80

15 files changed

Lines changed: 633 additions & 72 deletions

File tree

‎apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,16 @@ class T3TerminalModule : Module() {
6666
Prop("captureRequest") { view: T3TerminalView, request: Double ->
6767
view.captureRequest = request
6868
}
69+
70+
Prop("sharedGrid") { view: T3TerminalView, sharedGrid: List<Int> ->
71+
view.sharedGrid = sharedGrid
72+
}
6973
Events("onInput", "onResize", "onCapture")
7074

75+
OnViewDidUpdateProps { view: T3TerminalView ->
76+
view.applyPendingBuffer()
77+
}
78+
7179
OnViewDestroys { view: T3TerminalView ->
7280
view.cleanup()
7381
}

‎apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt‎

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
5858
private var streamedOutput: TerminalOutputBuffer? = null
5959
private var cols = 0
6060
private var rows = 0
61+
private var measuredCols = 0
62+
private var measuredRows = 0
6163
private var clearingInput = false
6264
private var isCleanedUp = false
6365
private var backgroundColorValue = Color.parseColor("#24292E")
@@ -74,12 +76,16 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
7476
recreateTerminal()
7577
}
7678

79+
// Expo sets a batch's props in no fixed order, so the buffer waits for the whole batch:
80+
// output fed before the same batch's sharedGrid lands would be drawn, and clipped, at the
81+
// previous grid.
7782
var initialBuffer: String = ""
7883
set(value) {
7984
if (field == value) return
8085
field = value
81-
feedPendingBuffer()
86+
hasPendingBuffer = true
8287
}
88+
private var hasPendingBuffer = false
8389

8490
var fontSize: Float = 10f
8591
set(value) {
@@ -91,6 +97,17 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
9197

9298
var appearanceScheme: String = "dark"
9399

100+
// The PTY grid shared by every attached client, or empty before the server reports one.
101+
// The terminal draws this grid, clamped to the view's own fit (the server's grid lags a
102+
// local resize, and read-only observers never constrain it), so its wrapping and cursor
103+
// match the PTY; the view's own fit still goes out through onResize.
104+
var sharedGrid: List<Int> = emptyList()
105+
set(value) {
106+
if (field == value) return
107+
field = value
108+
applyGrid()
109+
}
110+
94111
var themeConfig: String = ""
95112
set(value) {
96113
field = value
@@ -327,6 +344,19 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
327344
val nextRows = (terminalCanvas.usableHeight() / terminalCanvas.cellHeightPx)
328345
.toInt()
329346
.coerceIn(2, 200)
347+
if (nextCols != measuredCols || nextRows != measuredRows) {
348+
measuredCols = nextCols
349+
measuredRows = nextRows
350+
onResize(mapOf("cols" to measuredCols, "rows" to measuredRows))
351+
}
352+
applyGrid()
353+
}
354+
355+
private fun applyGrid() {
356+
if (measuredCols <= 0 || measuredRows <= 0 || isCleanedUp) return
357+
val shared = sharedGrid.takeIf { it.size == 2 && it[0] > 0 && it[1] > 0 }
358+
val nextCols = shared?.get(0)?.coerceAtMost(measuredCols) ?: measuredCols
359+
val nextRows = shared?.get(1)?.coerceAtMost(measuredRows) ?: measuredRows
330360
if (nextCols == cols && nextRows == rows && terminalHandle != 0L) return
331361
cols = nextCols
332362
rows = nextRows
@@ -343,8 +373,7 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
343373
)
344374
}
345375
emitResponse(response)
346-
onResize(mapOf("cols" to cols, "rows" to rows))
347-
feedPendingBuffer()
376+
if (!hasPendingBuffer) feedPendingBuffer()
348377
renderSnapshot()
349378
}
350379

@@ -369,7 +398,7 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
369398
if (terminalHandle == 0L) return
370399
destroyTerminal()
371400
createTerminal()
372-
feedPendingBuffer()
401+
if (!hasPendingBuffer) feedPendingBuffer()
373402
renderSnapshot()
374403
}
375404

@@ -381,6 +410,12 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
381410
terminalCanvas.resetSelectionState()
382411
}
383412

413+
fun applyPendingBuffer() {
414+
if (!hasPendingBuffer) return
415+
hasPendingBuffer = false
416+
feedPendingBuffer()
417+
}
418+
384419
private fun feedPendingBuffer() {
385420
if (streamedOutput != null || terminalHandle == 0L || initialBuffer == fedBuffer) return
386421
if (!initialBuffer.startsWith(fedBuffer)) {

‎apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,15 @@ public class T3TerminalModule: Module {
6363
Prop("captureRequest") { (view: T3TerminalView, request: Double) in
6464
view.captureRequest = request
6565
}
66+
67+
Prop("sharedGrid") { (view: T3TerminalView, sharedGrid: [Int]) in
68+
view.sharedGrid = sharedGrid
69+
}
6670
Events("onInput", "onResize", "onCapture")
71+
72+
OnViewDidUpdateProps { (view: T3TerminalView) in
73+
view.applyPendingBuffer()
74+
}
6775
}
6876
}
6977
}

‎apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift‎

Lines changed: 48 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -243,9 +243,23 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
243243
}
244244
}
245245

246+
// Expo sets a batch's props in no fixed order, so the buffer waits for the whole batch:
247+
// output fed before the same batch's sharedGrid lands would be drawn, and clipped, at the
248+
// previous grid.
246249
var initialBuffer: String = "" {
247250
didSet {
248-
applyRemoteBuffer(initialBuffer)
251+
hasPendingBuffer = true
252+
}
253+
}
254+
private var hasPendingBuffer = false
255+
256+
// The PTY grid shared by every attached client, or empty before the server reports one.
257+
// The surface draws this grid so its wrapping and cursor match the PTY; the view's own
258+
// fit still goes out through onResize.
259+
var sharedGrid: [Int] = [] {
260+
didSet {
261+
guard oldValue != sharedGrid else { return }
262+
resizeSurface()
249263
}
250264
}
251265

@@ -529,7 +543,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
529543
resizeSurface()
530544
if let streamedOutput {
531545
feedData(streamedOutput.data)
532-
} else {
546+
} else if !hasPendingBuffer {
533547
feedBuffer(initialBuffer)
534548
}
535549
}
@@ -559,6 +573,19 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
559573
}
560574
surface = nil
561575
app = nil
576+
// Ghostty adds its IOSurface layer to the viewport on iOS but never removes it on
577+
// free, leaving the last frame on screen under the next surface's layer. The
578+
// viewport has no subviews, so every sublayer belongs to a freed surface.
579+
CATransaction.begin()
580+
CATransaction.setDisableActions(true)
581+
terminalViewport.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
582+
CATransaction.commit()
583+
}
584+
585+
func applyPendingBuffer() {
586+
guard hasPendingBuffer else { return }
587+
hasPendingBuffer = false
588+
applyRemoteBuffer(initialBuffer)
562589
}
563590

564591
private func applyRemoteBuffer(_ buffer: String) {
@@ -647,30 +674,32 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
647674
terminalViewport.contentScaleFactor = scale
648675
ghostty_surface_set_content_scale(surface, Double(scale), Double(scale))
649676
ghostty_surface_set_size(surface, width, height)
677+
let fitted = ghostty_surface_size(surface)
678+
let fittedCols = max(1, Int(fitted.columns))
679+
let fittedRows = max(1, Int(fitted.rows))
680+
// Trimming whole cells keeps ghostty's padding, and the surface can only shrink
681+
// within the view, so a stale larger grid falls back to the fitted one.
682+
var surfaceWidth = width
683+
var surfaceHeight = height
684+
if sharedGrid.count == 2, sharedGrid[0] > 0, sharedGrid[1] > 0 {
685+
surfaceWidth -= UInt32(max(fittedCols - sharedGrid[0], 0)) * fitted.cell_width_px
686+
surfaceHeight -= UInt32(max(fittedRows - sharedGrid[1], 0)) * fitted.cell_height_px
687+
if surfaceWidth != width || surfaceHeight != height {
688+
ghostty_surface_set_size(surface, surfaceWidth, surfaceHeight)
689+
}
690+
}
650691
ghostty_surface_set_occlusion(surface, window != nil)
651-
configureIOSurfaceLayers()
692+
configureIOSurfaceLayers(
693+
size: CGSize(width: CGFloat(surfaceWidth) / scale, height: CGFloat(surfaceHeight) / scale))
652694
redrawSurface()
653-
emitGhosttyResize()
695+
emitResize(cols: fittedCols, rows: fittedRows)
654696
}
655697

656698
private func redrawSurface() {
657699
guard let surface else { return }
658700
ghostty_surface_refresh(surface)
659701
ghostty_surface_draw(surface)
660702
markIOSurfaceLayersForDisplay()
661-
emitGhosttyResize()
662-
}
663-
664-
private func emitGhosttyResize() {
665-
guard let surface else {
666-
emitEstimatedResize()
667-
return
668-
}
669-
670-
let size = ghostty_surface_size(surface)
671-
let cols = max(1, Int(size.columns))
672-
let rows = max(1, Int(size.rows))
673-
emitResize(cols: cols, rows: rows)
674703
}
675704

676705
private func emitEstimatedResize() {
@@ -721,8 +750,8 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
721750
ghostty_app_keyboard_changed(app)
722751
}
723752

724-
private func configureIOSurfaceLayers() {
725-
let targetBounds = CGRect(origin: .zero, size: terminalViewport.bounds.size)
753+
private func configureIOSurfaceLayers(size: CGSize) {
754+
let targetBounds = CGRect(origin: .zero, size: size)
726755
CATransaction.begin()
727756
CATransaction.setDisableActions(true)
728757
terminalViewport.layer.sublayers?.forEach { sublayer in

‎apps/mobile/src/features/terminal/NativeTerminalSurface.tsx‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import type { TerminalOutputState } from "@t3tools/client-runtime/state/terminal";
2-
import { memo, useEffect, useImperativeHandle, useRef, useState, type Ref } from "react";
1+
import type { TerminalGrid, TerminalOutputState } from "@t3tools/client-runtime/state/terminal";
2+
import { memo, useEffect, useImperativeHandle, useMemo, useRef, useState, type Ref } from "react";
33
import {
44
Pressable,
55
ScrollView,
@@ -47,6 +47,7 @@ interface TerminalSurfaceProps extends ViewProps {
4747
readonly buffer: string | null;
4848
readonly output: TerminalOutputState | null;
4949
readonly fontSize?: number;
50+
readonly grid?: TerminalGrid | null;
5051
readonly isRunning: boolean;
5152
readonly readOnly?: boolean;
5253
readonly autoFocus?: boolean;
@@ -204,6 +205,12 @@ const ReadyTerminalSurface = memo(function ReadyTerminalSurface(props: ReadyTerm
204205
const theme = props.theme ?? getMobileTerminalTheme(themeId, themeAppearance);
205206
const { onInput, onResize } = props;
206207
const NativeTerminalSurfaceView = resolveNativeTerminalSurfaceView();
208+
const gridCols = props.grid?.cols;
209+
const gridRows = props.grid?.rows;
210+
const sharedGrid = useMemo(
211+
() => (gridCols !== undefined && gridRows !== undefined ? [gridCols, gridRows] : []),
212+
[gridCols, gridRows],
213+
);
207214
const streaming = supportsNativeTerminalOutput();
208215
const nativeRef = useRef<NativeTerminalSurfaceHandle>(null);
209216
const writerRef = useRef<ReturnType<typeof createTerminalOutputWriter> | null>(null);
@@ -260,6 +267,7 @@ const ReadyTerminalSurface = memo(function ReadyTerminalSurface(props: ReadyTerm
260267
terminalKey={props.terminalKey}
261268
initialBuffer={streaming ? "" : props.buffer}
262269
fontSize={fontSize}
270+
sharedGrid={sharedGrid}
263271
style={{ flex: 1 }}
264272
themeConfig={buildGhosttyThemeConfig(theme)}
265273
onInput={handleNativeInput}

‎apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -939,6 +939,7 @@ function ThreadTerminal(props: {
939939
buffer={terminal.version === 0 ? null : terminal.buffer}
940940
output={terminal.version === 0 ? null : terminal.output}
941941
fontSize={fontSize}
942+
grid={terminal.grid}
942943
isRunning={isRunning}
943944
keyboardFocusRequest={keyboardFocusRequest}
944945
captureRequest={captureRequest}

‎apps/mobile/src/features/terminal/nativeTerminalModule.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ export interface NativeTerminalSurfaceProps extends ViewProps {
3636
readonly terminalKey: string;
3737
readonly initialBuffer: string;
3838
readonly fontSize: number;
39+
/** `[cols, rows]` of the shared PTY, or empty before the server reports one. */
40+
readonly sharedGrid?: ReadonlyArray<number>;
3941
readonly onInput?: (event: NativeSyntheticEvent<TerminalInputEvent>) => void;
4042
readonly onResize?: (event: NativeSyntheticEvent<TerminalResizeEvent>) => void;
4143
}

0 commit comments

Comments
 (0)