The best way to control Claude Code, Codex and more from any computer or phone
fix(terminal): keep shared terminal grids in sync (#24352)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 27, 2026 at 20:42 UTC
49a9e80e0b30e3012412bcc564bb5e52e09d1c1d
15 files changed
+633
-72
apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt
+8
@@ -66,8 +66,16 @@ class T3TerminalModule : Module() {
66
Prop("captureRequest") { view: T3TerminalView, request: Double ->
67
view.captureRequest = request
68
}
69
+
70
+ Prop("sharedGrid") { view: T3TerminalView, sharedGrid: List<Int> ->
71
+ view.sharedGrid = sharedGrid
72
+ }
73
Events("onInput", "onResize", "onCapture")
74
75
+ OnViewDidUpdateProps { view: T3TerminalView ->
76
+ view.applyPendingBuffer()
77
+ }
78
+
79
OnViewDestroys { view: T3TerminalView ->
80
view.cleanup()
81
}
apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt
+39
-4
@@ -58,6 +58,8 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
58
private var streamedOutput: TerminalOutputBuffer? = null
59
private var cols = 0
60
private var rows = 0
61
+ private var measuredCols = 0
62
+ private var measuredRows = 0
63
private var clearingInput = false
64
private var isCleanedUp = false
65
private var backgroundColorValue = Color.parseColor("#24292E")
@@ -74,12 +76,16 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
76
recreateTerminal()
77
}
78
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.
82
var initialBuffer: String = ""
83
set(value) {
84
if (field == value) return
85
field = value
81
- feedPendingBuffer()
86
+ hasPendingBuffer = true
87
}
88
+ private var hasPendingBuffer = false
89
90
var fontSize: Float = 10f
91
set(value) {
@@ -91,6 +97,17 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
97
98
var appearanceScheme: String = "dark"
99
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
+
111
var themeConfig: String = ""
112
set(value) {
113
field = value
@@ -327,6 +344,19 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
344
val nextRows = (terminalCanvas.usableHeight() / terminalCanvas.cellHeightPx)
345
.toInt()
346
.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
360
if (nextCols == cols && nextRows == rows && terminalHandle != 0L) return
361
cols = nextCols
362
rows = nextRows
@@ -343,8 +373,7 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
373
)
374
}
375
emitResponse(response)
346
- onResize(mapOf("cols" to cols, "rows" to rows))
347
- feedPendingBuffer()
376
+ if (!hasPendingBuffer) feedPendingBuffer()
377
renderSnapshot()
378
}
379
@@ -369,7 +398,7 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
398
if (terminalHandle == 0L) return
399
destroyTerminal()
400
createTerminal()
372
- feedPendingBuffer()
401
+ if (!hasPendingBuffer) feedPendingBuffer()
402
renderSnapshot()
403
}
404
@@ -381,6 +410,12 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
410
terminalCanvas.resetSelectionState()
411
}
412
413
+ fun applyPendingBuffer() {
414
+ if (!hasPendingBuffer) return
415
+ hasPendingBuffer = false
416
+ feedPendingBuffer()
417
+ }
418
+
419
private fun feedPendingBuffer() {
420
if (streamedOutput != null || terminalHandle == 0L || initialBuffer == fedBuffer) return
421
if (!initialBuffer.startsWith(fedBuffer)) {
apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift
+8
@@ -63,7 +63,15 @@ public class T3TerminalModule: Module {
63
Prop("captureRequest") { (view: T3TerminalView, request: Double) in
64
view.captureRequest = request
65
}
66
+
67
+ Prop("sharedGrid") { (view: T3TerminalView, sharedGrid: [Int]) in
68
+ view.sharedGrid = sharedGrid
69
+ }
70
Events("onInput", "onResize", "onCapture")
71
+
72
+ OnViewDidUpdateProps { (view: T3TerminalView) in
73
+ view.applyPendingBuffer()
74
+ }
75
}
76
}
77
}
apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift
+48
-19
@@ -243,9 +243,23 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
243
}
244
}
245
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.
249
var initialBuffer: String = "" {
250
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()
263
}
264
}
265
@@ -529,7 +543,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
543
resizeSurface()
544
if let streamedOutput {
545
feedData(streamedOutput.data)
532
- } else {
546
+ } else if !hasPendingBuffer {
547
feedBuffer(initialBuffer)
548
}
549
}
@@ -559,6 +573,19 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
573
}
574
surface = nil
575
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)
589
}
590
591
private func applyRemoteBuffer(_ buffer: String) {
@@ -647,10 +674,25 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
674
terminalViewport.contentScaleFactor = scale
675
ghostty_surface_set_content_scale(surface, Double(scale), Double(scale))
676
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
+ }
691
ghostty_surface_set_occlusion(surface, window != nil)
651
- configureIOSurfaceLayers()
692
+ configureIOSurfaceLayers(
693
+ size: CGSize(width: CGFloat(surfaceWidth) / scale, height: CGFloat(surfaceHeight) / scale))
694
redrawSurface()
653
- emitGhosttyResize()
695
+ emitResize(cols: fittedCols, rows: fittedRows)
696
}
697
698
private func redrawSurface() {
@@ -658,19 +700,6 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
700
ghostty_surface_refresh(surface)
701
ghostty_surface_draw(surface)
702
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)
703
}
704
705
private func emitEstimatedResize() {
@@ -721,8 +750,8 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
750
ghostty_app_keyboard_changed(app)
751
}
752
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)
755
CATransaction.begin()
756
CATransaction.setDisableActions(true)
757
terminalViewport.layer.sublayers?.forEach { sublayer in
apps/mobile/src/features/terminal/NativeTerminalSurface.tsx
+10
-2
@@ -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";
3
import {
4
Pressable,
5
ScrollView,
@@ -47,6 +47,7 @@ interface TerminalSurfaceProps extends ViewProps {
47
readonly buffer: string | null;
48
readonly output: TerminalOutputState | null;
49
readonly fontSize?: number;
50
+ readonly grid?: TerminalGrid | null;
51
readonly isRunning: boolean;
52
readonly readOnly?: boolean;
53
readonly autoFocus?: boolean;
@@ -204,6 +205,12 @@ const ReadyTerminalSurface = memo(function ReadyTerminalSurface(props: ReadyTerm
205
const theme = props.theme ?? getMobileTerminalTheme(themeId, themeAppearance);
206
const { onInput, onResize } = props;
207
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
+ );
214
const streaming = supportsNativeTerminalOutput();
215
const nativeRef = useRef<NativeTerminalSurfaceHandle>(null);
216
const writerRef = useRef<ReturnType<typeof createTerminalOutputWriter> | null>(null);
@@ -260,6 +267,7 @@ const ReadyTerminalSurface = memo(function ReadyTerminalSurface(props: ReadyTerm
267
terminalKey={props.terminalKey}
268
initialBuffer={streaming ? "" : props.buffer}
269
fontSize={fontSize}
270
+ sharedGrid={sharedGrid}
271
style={{ flex: 1 }}
272
themeConfig={buildGhosttyThemeConfig(theme)}
273
onInput={handleNativeInput}
apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+1
@@ -939,6 +939,7 @@ function ThreadTerminal(props: {
939
buffer={terminal.version === 0 ? null : terminal.buffer}
940
output={terminal.version === 0 ? null : terminal.output}
941
fontSize={fontSize}
942
+ grid={terminal.grid}
943
isRunning={isRunning}
944
keyboardFocusRequest={keyboardFocusRequest}
945
captureRequest={captureRequest}
apps/mobile/src/features/terminal/nativeTerminalModule.ts
+2
@@ -36,6 +36,8 @@ export interface NativeTerminalSurfaceProps extends ViewProps {
36
readonly terminalKey: string;
37
readonly initialBuffer: string;
38
readonly fontSize: number;
39
+ /** `[cols, rows]` of the shared PTY, or empty before the server reports one. */
40
+ readonly sharedGrid?: ReadonlyArray<number>;
41
readonly onInput?: (event: NativeSyntheticEvent<TerminalInputEvent>) => void;
42
readonly onResize?: (event: NativeSyntheticEvent<TerminalResizeEvent>) => void;
43
}
apps/server/src/terminal/Manager.test.ts
+174
@@ -442,6 +442,133 @@ it.layer(
442
}),
443
);
444
445
+ // Which client owns the shared PTY size is left open by the issue, so this only asserts
446
+ // that every attached renderer is told the grid the PTY actually has.
447
+ it.effect("tells every attached stream the shared PTY size when attaches disagree", () =>
448
+ Effect.gen(function* () {
449
+ const { manager, ptyAdapter } = yield* createManager();
450
+ const wideEvents: TerminalAttachStreamEvent[] = [];
451
+ const narrowEvents: TerminalAttachStreamEvent[] = [];
452
+ const stopWide = yield* manager.attachStream(openInput({ cols: 130, rows: 15 }), (event) =>
453
+ Effect.sync(() => {
454
+ wideEvents.push(event);
455
+ }),
456
+ );
457
+ yield* Effect.addFinalizer(() => Effect.sync(stopWide));
458
+ const stopNarrow = yield* manager.attachStream(openInput({ cols: 54, rows: 15 }), (event) =>
459
+ Effect.sync(() => {
460
+ narrowEvents.push(event);
461
+ }),
462
+ );
463
+ yield* Effect.addFinalizer(() => Effect.sync(stopNarrow));
464
+
465
+ const spawned = ptyAdapter.spawnInputs[0]!;
466
+ const ptySize = ptyAdapter.processes[0]!.resizeCalls.at(-1) ?? {
467
+ cols: spawned.cols,
468
+ rows: spawned.rows,
469
+ };
470
+ const lastReportedSize = (events: ReadonlyArray<TerminalAttachStreamEvent>) => {
471
+ for (const event of events.toReversed()) {
472
+ const source: Record<string, unknown> =
473
+ event.type === "snapshot" ? event.snapshot : event;
474
+ if (typeof source.cols === "number" && typeof source.rows === "number") {
475
+ return { cols: source.cols, rows: source.rows };
476
+ }
477
+ }
478
+ return null;
479
+ };
480
+
481
+ expect({
482
+ wide: lastReportedSize(wideEvents),
483
+ narrow: lastReportedSize(narrowEvents),
484
+ }).toEqual({ wide: ptySize, narrow: ptySize });
485
+ }),
486
+ );
487
+
488
+ it.effect("gives the PTY back to the remaining viewer when the narrowest one detaches", () =>
489
+ Effect.gen(function* () {
490
+ const { manager, ptyAdapter } = yield* createManager();
491
+ const restored = yield* Deferred.make<void>();
492
+ const stopWide = yield* manager.attachStream(
493
+ openInput({ cols: 130, rows: 15 }),
494
+ (event) =>
495
+ event.type === "activity" && event.cols === 130 && event.rows === 15
496
+ ? Deferred.succeed(restored, undefined).pipe(Effect.asVoid)
497
+ : Effect.void,
498
+ undefined,
499
+ "wide",
500
+ );
501
+ yield* Effect.addFinalizer(() => Effect.sync(stopWide));
502
+ const stopNarrow = yield* manager.attachStream(
503
+ openInput({ cols: 54, rows: 15 }),
504
+ () => Effect.void,
505
+ undefined,
506
+ "narrow",
507
+ );
508
+ const process = ptyAdapter.processes[0]!;
509
+
510
+ yield* manager.resize(
511
+ { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 80, rows: 12 },
512
+ "narrow",
513
+ );
514
+ // A resize from a client with no attached stream cannot override attached viewers.
515
+ yield* manager.resize({
516
+ threadId: "thread-1",
517
+ terminalId: DEFAULT_TERMINAL_ID,
518
+ cols: 200,
519
+ rows: 50,
520
+ });
521
+ expect(process.resizeCalls.at(-1)).toEqual({ cols: 80, rows: 12 });
522
+
523
+ stopNarrow();
524
+ yield* Deferred.await(restored);
525
+ expect(process.resizeCalls.at(-1)).toEqual({ cols: 130, rows: 15 });
526
+ }),
527
+ );
528
+
529
+ // Client retries resend the first attach's size, which a later resize may have replaced.
530
+ it.effect("keeps a viewer's resized grid when the same viewer attaches again", () =>
531
+ Effect.gen(function* () {
532
+ const { manager, ptyAdapter } = yield* createManager();
533
+ const restored = yield* Deferred.make<void>();
534
+ const stopWide = yield* manager.attachStream(
535
+ openInput({ cols: 130, rows: 15 }),
536
+ (event) =>
537
+ event.type === "activity" && event.cols === 130 && event.rows === 15
538
+ ? Deferred.succeed(restored, undefined).pipe(Effect.asVoid)
539
+ : Effect.void,
540
+ undefined,
541
+ "wide",
542
+ );
543
+ yield* Effect.addFinalizer(() => Effect.sync(stopWide));
544
+ const stopFirst = yield* manager.attachStream(
545
+ openInput({ cols: 54, rows: 15 }),
546
+ () => Effect.void,
547
+ undefined,
548
+ "phone",
549
+ );
550
+ const process = ptyAdapter.processes[0]!;
551
+ yield* manager.resize(
552
+ { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 100, rows: 15 },
553
+ "phone",
554
+ );
555
+
556
+ const stopRetry = yield* manager.attachStream(
557
+ { ...openInput({ cols: 54, rows: 15 }), resume: true },
558
+ () => Effect.void,
559
+ undefined,
560
+ "phone",
561
+ );
562
+ expect(process.resizeCalls.at(-1)).toEqual({ cols: 100, rows: 15 });
563
+
564
+ stopRetry();
565
+ stopFirst();
566
+ yield* Deferred.await(restored);
567
+ expect(process.resizeCalls.at(-1)).toEqual({ cols: 130, rows: 15 });
568
+ expect(ptyAdapter.spawnInputs).toHaveLength(1);
569
+ }),
570
+ );
571
+
572
it.effect("resumed attaches after close never respawn until the terminal is reopened", () =>
573
Effect.gen(function* () {
574
const { manager, ptyAdapter } = yield* createManager();
@@ -1467,6 +1594,53 @@ it.layer(
1594
}).pipe(Effect.scoped),
1595
);
1596
1597
+ it.effect.each([
1598
+ { recovered: true, label: "after recovery" },
1599
+ { recovered: false, label: "when cancelled before recovery" },
1600
+ ])("keeps a stalled viewer's size until its attach stream ends ($label)", ({ recovered }) =>
1601
+ Effect.gen(function* () {
1602
+ const { manager, ptyAdapter } = yield* createManager();
1603
+ const restored = yield* Deferred.make<void>();
1604
+ const stopWide = yield* manager.attachStream(
1605
+ openInput({ cols: 130, rows: 15 }),
1606
+ (event) =>
1607
+ event.type === "activity" && event.cols === 130 && event.rows === 15
1608
+ ? Deferred.succeed(restored, undefined).pipe(Effect.asVoid)
1609
+ : Effect.void,
1610
+ undefined,
1611
+ "wide",
1612
+ );
1613
+ yield* Effect.addFinalizer(() => Effect.sync(stopWide));
1614
+ const process = ptyAdapter.processes[0]!;
1615
+
1616
+ yield* Effect.gen(function* () {
1617
+ const pull = yield* Stream.toPull(
1618
+ manager.attachOutputStream(openInput({ cols: 54, rows: 15 }), "narrow"),
1619
+ );
1620
+ expect(yield* pull).toMatchObject([{ type: "snapshot" }]);
1621
+ expect(process.resizeCalls.at(-1)).toEqual({ cols: 54, rows: 15 });
1622
+ // Overflow releases the inner subscription before any recovery pull.
1623
+ yield* publishPastOutputBudget(manager, process);
1624
+ yield* manager.resize(
1625
+ { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 50, rows: 12 },
1626
+ "narrow",
1627
+ );
1628
+ expect(process.resizeCalls.at(-1)).toEqual({ cols: 50, rows: 12 });
1629
+ if (!recovered) return;
1630
+
1631
+ expect(yield* pull).toMatchObject([{ type: "snapshot" }]);
1632
+ yield* manager.resize(
1633
+ { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID, cols: 48, rows: 12 },
1634
+ "narrow",
1635
+ );
1636
+ expect(process.resizeCalls.at(-1)).toEqual({ cols: 48, rows: 12 });
1637
+ }).pipe(Effect.scoped);
1638
+
1639
+ yield* Deferred.await(restored);
1640
+ expect(process.resizeCalls.at(-1)).toEqual({ cols: 130, rows: 15 });
1641
+ }).pipe(Effect.scoped),
1642
+ );
1643
+
1644
it.effect("does not replay in-flight output already included in an observer snapshot", () =>
1645
Effect.gen(function* () {
1646
const { manager, ptyAdapter } = yield* createManager();
apps/server/src/terminal/Manager.ts
+229
-25
@@ -57,6 +57,7 @@ import * as Option from "effect/Option";
57
import * as Path from "effect/Path";
58
import * as Schema from "effect/Schema";
59
import * as Scope from "effect/Scope";
60
+import * as Stream from "effect/Stream";
61
import * as SynchronizedRef from "effect/SynchronizedRef";
62
63
import * as ServerConfig from "../config.ts";
@@ -70,6 +71,7 @@ import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
71
import * as ProcessRunner from "../processRunner.ts";
72
import * as PortScanner from "../preview/PortScanner.ts";
73
import * as NativeTelemetryClient from "../resourceTelemetry/NativeTelemetryClient.ts";
74
+import { terminalOutputStream } from "./OutputProtocol.ts";
75
import * as PtyAdapter from "@t3tools/shared/PtyAdapter";
76
77
export {
@@ -160,12 +162,27 @@ export class TerminalManager extends Context.Service<
162
input: TerminalOpenInput,
163
) => Effect.Effect<TerminalSessionSnapshot, TerminalError>;
164
165
+ /**
166
+ * Attached viewers share one PTY sized to the smallest of them, so a narrow client
167
+ * still sees the whole TUI. Streams and resizes with the same `viewerId` (one client
168
+ * connection) count as one viewer; streams without one are each their own viewer.
169
+ */
170
readonly attachStream: (
171
input: TerminalAttachInput,
172
listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
173
registerCleanup?: (stop: () => void) => void,
174
+ viewerId?: string,
175
) => Effect.Effect<() => void, TerminalError>;
176
177
+ /**
178
+ * The `terminal.attach` RPC stream. Overflow recovery swaps the inner subscription, so
179
+ * `viewerId` and the size it reported stay attached until the whole stream ends.
180
+ */
181
+ readonly attachOutputStream: (
182
+ input: TerminalAttachInput,
183
+ viewerId: string,
184
+ ) => Stream.Stream<TerminalAttachStreamEvent, TerminalError>;
185
+
186
readonly observeStream: (
187
input: TerminalObserveInput,
188
listener: (event: TerminalAttachStreamEvent) => Effect.Effect<void>,
@@ -180,7 +197,10 @@ export class TerminalManager extends Context.Service<
197
198
readonly write: (input: TerminalWriteInput) => Effect.Effect<void, TerminalError>;
199
183
- readonly resize: (input: TerminalResizeInput) => Effect.Effect<void, TerminalError>;
200
+ readonly resize: (
201
+ input: TerminalResizeInput,
202
+ viewerId?: string,
203
+ ) => Effect.Effect<void, TerminalError>;
204
205
readonly clear: (input: TerminalClearInput) => Effect.Effect<void, TerminalError>;
206
@@ -273,6 +293,17 @@ interface TerminalSessionState {
293
runtimeEnv: Record<string, string> | null;
294
}
295
296
+interface TerminalGrid {
297
+ readonly cols: number;
298
+ readonly rows: number;
299
+}
300
+
301
+/** One client connection attached to a terminal, possibly through several streams. */
302
+interface TerminalViewer {
303
+ streams: number;
304
+ grid: TerminalGrid | null;
305
+}
306
+
307
interface PersistHistoryRequest {
308
history: BoundedTerminalHistory;
309
immediate: boolean;
@@ -354,6 +385,8 @@ function snapshot(session: TerminalSessionState): TerminalSessionSnapshot {
385
label: terminalWireLabel(session),
386
updatedAt: session.updatedAt,
387
sequence: session.eventSequence,
388
+ cols: session.cols,
389
+ rows: session.rows,
390
};
391
}
392
@@ -1631,6 +1664,104 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
1664
effect: Effect.Effect<A, E, R>,
1665
): Effect.Effect<A, E, R> => threadLocks.withLock(threadId, effect);
1666
1667
+ const terminalViewers = new Map<string, Map<string, TerminalViewer>>();
1668
+ let anonymousViewerCount = 0;
1669
+
1670
+ const retainViewer = (sessionKey: string, viewerId: string, grid: TerminalGrid | null) => {
1671
+ let viewers = terminalViewers.get(sessionKey);
1672
+ if (!viewers) {
1673
+ viewers = new Map();
1674
+ terminalViewers.set(sessionKey, viewers);
1675
+ }
1676
+ const viewer = viewers.get(viewerId);
1677
+ if (viewer) {
1678
+ viewer.streams += 1;
1679
+ // After a viewer's first size, resizes own it; attach retries resend the original size.
1680
+ viewer.grid ??= grid;
1681
+ } else {
1682
+ viewers.set(viewerId, { streams: 1, grid });
1683
+ }
1684
+ };
1685
+
1686
+ /** Returns whether the viewer left, which can grow the shared grid. */
1687
+ const releaseViewer = (sessionKey: string, viewerId: string) => {
1688
+ const viewers = terminalViewers.get(sessionKey);
1689
+ const viewer = viewers?.get(viewerId);
1690
+ if (!viewers || !viewer) return false;
1691
+ viewer.streams -= 1;
1692
+ if (viewer.streams > 0) return false;
1693
+ viewers.delete(viewerId);
1694
+ if (viewers.size === 0) terminalViewers.delete(sessionKey);
1695
+ return true;
1696
+ };
1697
+
1698
+ // The smallest attached viewer bounds each axis, so every viewer can draw the whole grid.
1699
+ const sharedViewerGrid = (sessionKey: string): TerminalGrid | null => {
1700
+ let shared: TerminalGrid | null = null;
1701
+ for (const viewer of terminalViewers.get(sessionKey)?.values() ?? []) {
1702
+ if (!viewer.grid) continue;
1703
+ shared = shared
1704
+ ? {
1705
+ cols: Math.min(shared.cols, viewer.grid.cols),
1706
+ rows: Math.min(shared.rows, viewer.grid.rows),
1707
+ }
1708
+ : viewer.grid;
1709
+ }
1710
+ return shared;
1711
+ };
1712
+
1713
+ /** Attached viewers own the size; a caller's own size only applies when none has reported one. */
1714
+ const withSharedGrid = <
1715
+ A extends { readonly cols?: number | undefined; readonly rows?: number | undefined },
1716
+ >(
1717
+ sessionKey: string,
1718
+ input: A,
1719
+ ): A => {
1720
+ const shared = sharedViewerGrid(sessionKey);
1721
+ return shared ? { ...input, cols: shared.cols, rows: shared.rows } : input;
1722
+ };
1723
+
1724
+ // Renderers draw the PTY grid, so every size change reaches them. It rides on activity
1725
+ // because older clients reject unknown event types.
1726
+ const resizeSession = Effect.fnUntraced(function* (
1727
+ session: TerminalSessionState,
1728
+ process: PtyAdapter.PtyProcess,
1729
+ cols: number,
1730
+ rows: number,
1731
+ ) {
1732
+ yield* resizePtyProcess(session, process, cols, rows);
1733
+ session.cols = cols;
1734
+ session.rows = rows;
1735
+ session.updatedAt = yield* nowIso;
1736
+ const eventStamp = advanceEventSequence(session);
1737
+ yield* publishEvent({
1738
+ type: "activity",
1739
+ threadId: session.threadId,
1740
+ terminalId: session.terminalId,
1741
+ sequence: eventStamp.sequence,
1742
+ hasRunningSubprocess: session.hasRunningSubprocess,
1743
+ label: terminalWireLabel(session),
1744
+ cols,
1745
+ rows,
1746
+ });
1747
+ });
1748
+
1749
+ const applySharedGrid = Effect.fnUntraced(function* (threadId: string, terminalId: string) {
1750
+ const session = yield* getSession(threadId, terminalId);
1751
+ if (Option.isNone(session)) return;
1752
+ const process = session.value.process;
1753
+ const shared = sharedViewerGrid(toSessionKey(threadId, terminalId));
1754
+ if (
1755
+ !process ||
1756
+ session.value.status !== "running" ||
1757
+ !shared ||
1758
+ (shared.cols === session.value.cols && shared.rows === session.value.rows)
1759
+ ) {
1760
+ return;
1761
+ }
1762
+ yield* resizeSession(session.value, process, shared.cols, shared.rows);
1763
+ });
1764
+
1765
const clearKillFiber = Effect.fn("terminal.clearKillFiber")(function* (
1766
process: PtyAdapter.PtyProcess | null,
1767
) {
@@ -2686,12 +2817,13 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2817
);
2818
2819
const openWithWorkspaceLease = Effect.fn("terminal.openLocked")(function* (
2689
- input: TerminalOpenInput,
2820
+ requestedInput: TerminalOpenInput,
2821
) {
2691
- const terminalId = input.terminalId;
2692
- yield* assertValidCwd(input.cwd);
2822
+ const terminalId = requestedInput.terminalId;
2823
+ yield* assertValidCwd(requestedInput.cwd);
2824
2694
- const sessionKey = toSessionKey(input.threadId, terminalId);
2825
+ const sessionKey = toSessionKey(requestedInput.threadId, terminalId);
2826
+ const input = withSharedGrid(sessionKey, requestedInput);
2827
const existing = yield* getSession(input.threadId, terminalId);
2828
if (Option.isNone(existing)) {
2829
yield* flushPersist(input.threadId, terminalId);
@@ -2806,10 +2938,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2938
}
2939
2940
if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) {
2809
- yield* resizePtyProcess(liveSession, liveSession.process, targetCols, targetRows);
2810
- liveSession.cols = targetCols;
2811
- liveSession.rows = targetRows;
2812
- liveSession.updatedAt = yield* nowIso;
2941
+ yield* resizeSession(liveSession, liveSession.process, targetCols, targetRows);
2942
}
2943
2944
return snapshot(liveSession);
@@ -2827,8 +2956,9 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2956
resolveLaunchInputEnvironment(input).pipe(Effect.flatMap(openLocked)),
2957
);
2958
2830
- const openOrAttachForStream = Effect.fnUntraced(function* (input: TerminalAttachInput) {
2831
- const terminalId = input.terminalId;
2959
+ const openOrAttachForStream = Effect.fnUntraced(function* (requestedInput: TerminalAttachInput) {
2960
+ const terminalId = requestedInput.terminalId;
2961
+ const input = withSharedGrid(toSessionKey(requestedInput.threadId, terminalId), requestedInput);
2962
const existing = yield* getSession(input.threadId, terminalId);
2963
2964
if (Option.isNone(existing)) {
@@ -2868,11 +2998,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
2998
session.status === "running" &&
2999
(session.cols !== targetCols || session.rows !== targetRows)
3000
) {
2871
- const process = session.process;
2872
- yield* resizePtyProcess(session, process, targetCols, targetRows);
2873
- session.cols = targetCols;
2874
- session.rows = targetRows;
2875
- session.updatedAt = yield* nowIso;
3001
+ yield* resizeSession(session, session.process, targetCols, targetRows);
3002
}
3003
3004
return snapshot(session);
@@ -2993,11 +3119,60 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
3119
);
3120
};
3121
3122
+ /** Retains `viewer` and returns its release, which runs at most once. */
3123
+ const retainViewerOnce = (
3124
+ input: TerminalObserveInput,
3125
+ viewer: string,
3126
+ grid: TerminalGrid | null,
3127
+ ) => {
3128
+ const sessionKey = toSessionKey(input.threadId, input.terminalId);
3129
+ retainViewer(sessionKey, viewer, grid);
3130
+ let retained = true;
3131
+ return () => {
3132
+ if (!retained) return;
3133
+ retained = false;
3134
+ if (releaseViewer(sessionKey, viewer)) {
3135
+ runFork(withThreadLock(input.threadId, applySharedGrid(input.threadId, input.terminalId)));
3136
+ }
3137
+ };
3138
+ };
3139
+
3140
const attachStream: TerminalManager["Service"]["attachStream"] = (
3141
input,
3142
listener,
3143
registerCleanup,
3000
- ) => streamSession(input, openOrAttachForStream(input), listener, registerCleanup);
3144
+ viewerId,
3145
+ ) => {
3146
+ const viewer = viewerId ?? `stream:${++anonymousViewerCount}`;
3147
+ let detach = () => {};
3148
+ const initial = Effect.suspend(() => {
3149
+ detach = retainViewerOnce(
3150
+ input,
3151
+ viewer,
3152
+ input.cols !== undefined && input.rows !== undefined
3153
+ ? { cols: input.cols, rows: input.rows }
3154
+ : null,
3155
+ );
3156
+ return openOrAttachForStream(input);
3157
+ });
3158
+ return streamSession(
3159
+ input,
3160
+ initial,
3161
+ listener,
3162
+ registerCleanup &&
3163
+ ((stop) =>
3164
+ registerCleanup(() => {
3165
+ stop();
3166
+ detach();
3167
+ })),
3168
+ ).pipe(
3169
+ Effect.map((stop) => () => {
3170
+ stop();
3171
+ detach();
3172
+ }),
3173
+ Effect.onError(() => Effect.sync(detach)),
3174
+ );
3175
+ };
3176
3177
const observeStream: TerminalManager["Service"]["observeStream"] = (
3178
input,
@@ -3025,6 +3200,21 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
3200
registerCleanup,
3201
);
3202
3203
+ const attachOutputStream: TerminalManager["Service"]["attachOutputStream"] = (input, viewerId) =>
3204
+ Stream.unwrap(
3205
+ Effect.acquireRelease(
3206
+ Effect.sync(() => retainViewerOnce(input, viewerId, null)),
3207
+ (release) => Effect.sync(release),
3208
+ ).pipe(
3209
+ Effect.as(
3210
+ terminalOutputStream(
3211
+ (listener, registerCleanup) => attachStream(input, listener, registerCleanup, viewerId),
3212
+ (listener, registerCleanup) => resyncStream(input, listener, registerCleanup),
3213
+ ),
3214
+ ),
3215
+ ),
3216
+ );
3217
+
3218
const metadataEventFromTerminalEvent = (
3219
event: TerminalEvent,
3220
): Effect.Effect<TerminalMetadataStreamEvent | null> => {
@@ -3131,23 +3321,36 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
3321
});
3322
});
3323
3134
- const resizeLocked = Effect.fn("terminal.resize")(function* (input: TerminalResizeInput) {
3324
+ const resizeLocked = Effect.fn("terminal.resize")(function* (
3325
+ input: TerminalResizeInput,
3326
+ viewerId: string | undefined,
3327
+ ) {
3328
+ const sessionKey = toSessionKey(input.threadId, input.terminalId);
3329
+ const viewer =
3330
+ viewerId === undefined ? undefined : terminalViewers.get(sessionKey)?.get(viewerId);
3331
+ if (viewer) {
3332
+ viewer.grid = { cols: input.cols, rows: input.rows };
3333
+ return yield* applySharedGrid(input.threadId, input.terminalId);
3334
+ }
3335
+ // A caller that is not attached cannot override the viewers that are.
3336
+ if (sharedViewerGrid(sessionKey)) return;
3337
const session = yield* getSession(input.threadId, input.terminalId);
3338
if (Option.isNone(session)) {
3339
return;
3340
}
3341
const process = session.value.process;
3140
- if (!process || session.value.status !== "running") {
3342
+ if (
3343
+ !process ||
3344
+ session.value.status !== "running" ||
3345
+ (session.value.cols === input.cols && session.value.rows === input.rows)
3346
+ ) {
3347
return;
3348
}
3143
- yield* resizePtyProcess(session.value, process, input.cols, input.rows);
3144
- session.value.cols = input.cols;
3145
- session.value.rows = input.rows;
3146
- session.value.updatedAt = yield* nowIso;
3349
+ yield* resizeSession(session.value, process, input.cols, input.rows);
3350
});
3351
3149
- const resize: TerminalManager["Service"]["resize"] = (input) =>
3150
- withThreadLock(input.threadId, resizeLocked(input));
3352
+ const resize: TerminalManager["Service"]["resize"] = (input, viewerId) =>
3353
+ withThreadLock(input.threadId, resizeLocked(input, viewerId));
3354
3355
const clear: TerminalManager["Service"]["clear"] = (input) =>
3356
withThreadLock(
@@ -3235,6 +3438,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
3438
return TerminalManager.of({
3439
open,
3440
attachStream,
3441
+ attachOutputStream,
3442
observeStream,
3443
resyncStream,
3444
write,
apps/server/src/ws.ts
+8
-8
@@ -1269,6 +1269,10 @@ export const layerWsRpc = (
1269
yield* Effect.context<Effect.Services<ReturnType<typeof remoteSshDeviceHosts>>>();
1270
const orchestrationEngine = yield* Orchestrator.OrchestratorV2;
1271
const crypto = yield* Crypto.Crypto;
1272
+ // RPC client ids are only unique within one socket; terminals share viewers across sockets.
1273
+ const terminalViewerPrefix = yield* crypto.randomUUIDv4().pipe(Effect.orDie);
1274
+ const terminalViewerId = (metadata: { readonly client: { readonly id: number } }) =>
1275
+ `${terminalViewerPrefix}:${metadata.client.id}`;
1276
const serverCommandId = (tag: string) =>
1277
crypto.randomUUIDv4().pipe(
1278
Effect.orDie,
@@ -2971,15 +2975,11 @@ export const layerWsRpc = (
2975
[WS_METHODS.reviewGetDiffPreview]: (input) => review.getDiffPreview(input),
2976
[WS_METHODS.reviewGetDiffFileContents]: (input) => review.getDiffFileContents(input),
2977
[WS_METHODS.terminalOpen]: (input) => terminalManager.open(input),
2974
- [WS_METHODS.terminalAttach]: (input) =>
2975
- terminalOutputStream(
2976
- (listener, registerCleanup) =>
2977
- terminalManager.attachStream(input, listener, registerCleanup),
2978
- (listener, registerCleanup) =>
2979
- terminalManager.resyncStream(input, listener, registerCleanup),
2980
- ),
2978
+ [WS_METHODS.terminalAttach]: (input, metadata) =>
2979
+ terminalManager.attachOutputStream(input, terminalViewerId(metadata)),
2980
[WS_METHODS.terminalWrite]: (input) => terminalManager.write(input),
2982
- [WS_METHODS.terminalResize]: (input) => terminalManager.resize(input),
2981
+ [WS_METHODS.terminalResize]: (input, metadata) =>
2982
+ terminalManager.resize(input, terminalViewerId(metadata)),
2983
[WS_METHODS.terminalClear]: (input) => terminalManager.clear(input),
2984
[WS_METHODS.terminalClose]: (input) => terminalManager.close(input),
2985
[WS_METHODS.terminalObserve]: (input) =>
apps/web/src/components/ThreadTerminalDrawer.tsx
+2
@@ -695,6 +695,7 @@ function TerminalSessionViewport({
695
void terminal.setFont(terminalFontOptions(currentFont.family, currentFont.size));
696
}
697
const latestSession = readTerminalSession();
698
+ terminal.setSharedGrid(latestSession.grid);
699
const initialOutput = readTerminalOutputUpdate(
700
latestSession.output,
701
INITIAL_TERMINAL_OUTPUT_CURSOR,
@@ -720,6 +721,7 @@ function TerminalSessionViewport({
721
}
722
const previous = previousSession;
723
previousSession = session;
724
+ terminal.setSharedGrid(session.grid);
725
synchronizeTerminalStatus(terminal, session.status, session.version);
726
outputCursorRef.current = synchronizeTerminalSession(
727
terminal,
apps/web/src/terminal/ghostty/surface.ts
+47
-12
@@ -518,10 +518,14 @@ export class GhosttyTerminalSurface {
518
readonly canvas: HTMLCanvasElement;
519
readonly input: HTMLTextAreaElement;
520
readonly scrollbar: HTMLDivElement;
521
+ /** The drawn grid: the shared PTY grid, clamped per axis to the measured one. */
522
cols = 1;
523
rows = 1;
524
525
private readonly mount: HTMLElement;
526
+ private measuredCols = 1;
527
+ private measuredRows = 1;
528
+ private sharedGrid: { readonly cols: number; readonly rows: number } | null = null;
529
private readonly context: CanvasRenderingContext2D;
530
private readonly core: GhosttyTerminalCore;
531
private readonly options: GhosttyTerminalSurfaceOptions;
@@ -866,28 +870,59 @@ export class GhosttyTerminalSurface {
870
}
871
const grid = terminalGridSize(width, height, this.metrics, CONTENT_PADDING);
872
this.mountHeight = height;
869
- // onResize is the only PTY channel; notify on first fit even when the grid matches its 1x1 sentinel.
870
- if (grid.cols !== this.cols || grid.rows !== this.rows || !this.resizeNotified) {
871
- this.cols = grid.cols;
872
- this.rows = grid.rows;
873
- this.core.resize(grid.cols, grid.rows, this.metrics.width, this.metrics.height);
873
+ // onResize is the only PTY resize channel, so the first successful fit must
874
+ // notify even when the measured grid equals the 1x1 construction sentinel.
875
+ if (
876
+ grid.cols !== this.measuredCols ||
877
+ grid.rows !== this.measuredRows ||
878
+ !this.resizeNotified
879
+ ) {
880
+ this.measuredCols = grid.cols;
881
+ this.measuredRows = grid.rows;
882
this.notifyResize();
875
- this.forceFullRender = true;
876
- this.scrollbarDirty = true;
877
- shouldRender = true;
883
}
884
+ if (this.applyGrid()) shouldRender = true;
885
// Repaint synchronously before paint so resize never stretches the old backing store.
886
if (shouldRender || this.forceFullRender) this.renderFrame();
887
return true;
888
}
889
884
- // Reflow locally during drags; debounce PTY resizes so the shell does not reprint its prompt each step.
890
+ /**
891
+ * Other clients can share this PTY, so the server owns its grid. Drawing that grid
892
+ * keeps wrapping and cursor positions in step with the PTY. Each axis is clamped to
893
+ * this surface's own fit: the server's grid lags a local resize, and read-only
894
+ * observers never constrain it.
895
+ */
896
+ setSharedGrid(grid: { readonly cols: number; readonly rows: number } | null): void {
897
+ if (this.disposed) return;
898
+ if (this.sharedGrid?.cols === grid?.cols && this.sharedGrid?.rows === grid?.rows) return;
899
+ this.sharedGrid = grid;
900
+ if (this.hasSize && this.applyGrid()) this.requestRender();
901
+ }
902
+
903
+ private applyGrid(): boolean {
904
+ const cols = Math.min(this.sharedGrid?.cols ?? this.measuredCols, this.measuredCols);
905
+ const rows = Math.min(this.sharedGrid?.rows ?? this.measuredRows, this.measuredRows);
906
+ if (cols === this.cols && rows === this.rows) return false;
907
+ this.cols = cols;
908
+ this.rows = rows;
909
+ this.core.resize(cols, rows, this.metrics.width, this.metrics.height);
910
+ this.forceFullRender = true;
911
+ this.scrollbarDirty = true;
912
+ return true;
913
+ }
914
+
915
+ /**
916
+ * The local grid reflows immediately, but the PTY only hears about settled
917
+ * dimensions: notifying on every drag step makes the shell reprint its
918
+ * prompt mid-drag, which reads as jitter.
919
+ */
920
private notifyResize(): void {
921
this.resizeNotified = true;
922
if (this.resizeNotifyTimer !== null) window.clearTimeout(this.resizeNotifyTimer);
923
this.resizeNotifyTimer = window.setTimeout(() => {
924
this.resizeNotifyTimer = null;
890
- if (!this.disposed) this.options.onResize(this.cols, this.rows);
925
+ if (!this.disposed) this.options.onResize(this.measuredCols, this.measuredRows);
926
}, 150);
927
}
928
@@ -898,7 +933,7 @@ export class GhosttyTerminalSurface {
933
if (this.resizeNotifyTimer === null) return;
934
window.clearTimeout(this.resizeNotifyTimer);
935
this.resizeNotifyTimer = null;
901
- this.options.onResize(this.cols, this.rows);
936
+ this.options.onResize(this.measuredCols, this.measuredRows);
937
};
938
939
focus(): void {
@@ -1019,7 +1054,7 @@ export class GhosttyTerminalSurface {
1054
if (this.resizeNotifyTimer !== null) {
1055
window.clearTimeout(this.resizeNotifyTimer);
1056
this.resizeNotifyTimer = null;
1022
- this.options.onResize(this.cols, this.rows);
1057
+ this.options.onResize(this.measuredCols, this.measuredRows);
1058
}
1059
this.cancelRender();
1060
if (this.compositionSuppressionTimer !== null) {
packages/client-runtime/src/state/terminalSession.test.ts
+24
@@ -67,6 +67,30 @@ describe("terminal session reducers", () => {
67
});
68
});
69
70
+ it("follows the shared PTY grid from snapshots and activity without disturbing output", () => {
71
+ const attached = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
72
+ type: "snapshot",
73
+ snapshot: { ...BASE_SNAPSHOT, cols: 130, rows: 15 },
74
+ });
75
+ const activity = {
76
+ type: "activity",
77
+ threadId: TARGET.threadId,
78
+ terminalId: TARGET.terminalId,
79
+ hasRunningSubprocess: false,
80
+ label: "Terminal 1",
81
+ } as const;
82
+ const narrowed = applyTerminalAttachStreamEvent(attached, { ...activity, cols: 54, rows: 15 });
83
+ // Activity from a server without geometry, or a repeat, must not reset the renderer.
84
+ const unchanged = applyTerminalAttachStreamEvent(
85
+ applyTerminalAttachStreamEvent(narrowed, activity),
86
+ { ...activity, cols: 54, rows: 15 },
87
+ );
88
+
89
+ expect(attached.grid).toEqual({ cols: 130, rows: 15 });
90
+ expect(narrowed).toEqual({ ...attached, grid: { cols: 54, rows: 15 } });
91
+ expect(unchanged).toBe(narrowed);
92
+ });
93
+
94
it("preserves a BOM code point at a new output chunk boundary", () => {
95
const initial = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
96
type: "snapshot",
packages/client-runtime/src/state/terminalSession.ts
+27
-2
@@ -24,9 +24,17 @@ export {
24
} from "./terminalOutput.ts";
25
export { DEFAULT_MAX_TERMINAL_BUFFER_BYTES } from "@t3tools/contracts";
26
27
+/** The PTY grid every renderer of a shared terminal draws. */
28
+export interface TerminalGrid {
29
+ readonly cols: number;
30
+ readonly rows: number;
31
+}
32
+
33
export interface TerminalSessionState {
34
readonly summary: TerminalSummary | null;
35
readonly output: TerminalOutputState;
36
+ /** Null when the server predates shared terminal geometry. */
37
+ readonly grid: TerminalGrid | null;
38
readonly status: TerminalSessionSnapshot["status"] | "closed";
39
readonly error: string | null;
40
readonly hasRunningSubprocess: boolean;
@@ -37,6 +45,7 @@ export interface TerminalSessionState {
45
46
export interface TerminalBufferState {
47
readonly output: TerminalOutputState;
48
+ readonly grid: TerminalGrid | null;
49
readonly status: TerminalSessionSnapshot["status"] | "closed";
50
readonly error: string | null;
51
readonly updatedAt: string | null;
@@ -65,6 +74,7 @@ export function selectRunningSubprocessTerminalIds(
74
75
export const EMPTY_TERMINAL_BUFFER_STATE = Object.freeze<TerminalBufferState>({
76
output: EMPTY_TERMINAL_OUTPUT_STATE,
77
+ grid: null,
78
status: "closed",
79
error: null,
80
updatedAt: null,
@@ -75,6 +85,7 @@ export const EMPTY_TERMINAL_BUFFER_STATE = Object.freeze<TerminalBufferState>({
85
export const EMPTY_TERMINAL_SESSION_STATE = Object.freeze<TerminalSessionState>({
86
summary: null,
87
output: EMPTY_TERMINAL_OUTPUT_STATE,
88
+ grid: null,
89
status: "closed",
90
error: null,
91
hasRunningSubprocess: false,
@@ -103,6 +114,7 @@ function terminalBufferStateFromSnapshot(
114
): TerminalBufferState {
115
return {
116
output: resetOutput(current.output, snapshot.history, maxBufferBytes),
117
+ grid: nextGrid(current.grid, snapshot),
118
status: snapshot.status,
119
error: null,
120
updatedAt: snapshot.updatedAt,
@@ -111,6 +123,16 @@ function terminalBufferStateFromSnapshot(
123
};
124
}
125
126
+function nextGrid(
127
+ current: TerminalGrid | null,
128
+ source: { readonly cols?: number | undefined; readonly rows?: number | undefined },
129
+): TerminalGrid | null {
130
+ if (source.cols === undefined || source.rows === undefined) return current;
131
+ return current?.cols === source.cols && current.rows === source.rows
132
+ ? current
133
+ : { cols: source.cols, rows: source.rows };
134
+}
135
+
136
function latestTimestamp(left: string | null, right: string | null): string | null {
137
if (left === null) return right;
138
if (right === null) return left;
@@ -124,6 +146,7 @@ export function combineTerminalSessionState(
146
return {
147
summary,
148
output: buffer.output,
149
+ grid: buffer.grid,
150
status: buffer.version > 0 ? buffer.status : (summary?.status ?? buffer.status),
151
error: buffer.error,
152
hasRunningSubprocess: summary?.hasRunningSubprocess ?? false,
@@ -186,8 +209,10 @@ export function applyTerminalAttachStreamEvent(
209
error: event.message,
210
version: current.version + 1,
211
};
189
- case "activity":
190
- return current;
212
+ case "activity": {
213
+ const grid = nextGrid(current.grid, event);
214
+ return grid === current.grid ? current : { ...current, grid };
215
+ }
216
}
217
}
218
packages/contracts/src/terminal.ts
+6
@@ -100,6 +100,9 @@ export const TerminalSessionSnapshot = Schema.Struct({
100
label: Schema.String.check(Schema.isMaxLength(128)),
101
updatedAt: Schema.String,
102
sequence: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
103
+ // The PTY grid every renderer of this terminal should draw; absent from older servers.
104
+ cols: Schema.optional(TerminalColsSchema),
105
+ rows: Schema.optional(TerminalRowsSchema),
106
});
107
export type TerminalSessionSnapshot = typeof TerminalSessionSnapshot.Type;
108
@@ -193,6 +196,9 @@ const TerminalActivityEvent = Schema.Struct({
196
type: Schema.Literal("activity"),
197
hasRunningSubprocess: Schema.Boolean,
198
label: Schema.String.check(Schema.isMaxLength(128)),
199
+ // Shared PTY grid changes ride on activity because older clients reject unknown event types.
200
+ cols: Schema.optional(TerminalColsSchema),
201
+ rows: Schema.optional(TerminalRowsSchema),
202
});
203
204
export const TerminalEvent = Schema.Union([