The best way to control Claude Code, Codex and more from any computer or phone
perf(mobile): append terminal output without replaying history (#24261)
Julius Marminge committed
Oct 25, 2026 at 11:42 UTC
1eb4071a497cf1388a41040283a4065245dbe977
13 files changed
+499
-9
apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalModule.kt
+5
@@ -11,9 +11,14 @@ class T3TerminalModule : Module() {
11
// logs so a stale native binary is distinguishable from a broken key pipeline.
12
Constants(
13
"hardwareKeyRevision" to 2,
14
+ "outputRevision" to 1,
15
)
16
17
View(T3TerminalView::class) {
18
+ AsyncFunction("writeOutput") { view: T3TerminalView, data: String, reset: Boolean ->
19
+ view.writeOutput(data, reset)
20
+ }
21
+
22
Prop("terminalKey") { view: T3TerminalView, terminalKey: String ->
23
view.terminalKey = terminalKey
24
}
apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/T3TerminalView.kt
+26
-1
@@ -55,6 +55,7 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
55
}
56
private var terminalHandle = 0L
57
private var fedBuffer = ""
58
+ private var streamedOutput: TerminalOutputBuffer? = null
59
private var cols = 0
60
private var rows = 0
61
private var clearingInput = false
@@ -361,6 +362,7 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
362
paletteColors,
363
)
364
fedBuffer = ""
365
+ streamedOutput?.let { output -> feedOutput(output.data) }
366
}
367
368
private fun recreateTerminal() {
@@ -380,7 +382,7 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
382
}
383
384
private fun feedPendingBuffer() {
383
- if (terminalHandle == 0L || initialBuffer == fedBuffer) return
385
+ if (streamedOutput != null || terminalHandle == 0L || initialBuffer == fedBuffer) return
386
if (!initialBuffer.startsWith(fedBuffer)) {
387
recreateTerminal()
388
if (terminalHandle == 0L) return
@@ -399,6 +401,29 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
401
renderSnapshot()
402
}
403
404
+ fun writeOutput(data: String, reset: Boolean) {
405
+ if (isCleanedUp) return
406
+ val output = streamedOutput ?: TerminalOutputBuffer()
407
+ val bytes = data.toByteArray(Charsets.UTF_8)
408
+ output.write(bytes, reset)
409
+ streamedOutput = output
410
+ if (reset) {
411
+ recreateTerminal()
412
+ } else if (terminalHandle != 0L) {
413
+ feedOutput(bytes)
414
+ renderSnapshot()
415
+ }
416
+ }
417
+
418
+ private fun feedOutput(data: ByteArray) {
419
+ if (terminalHandle == 0L || data.isEmpty()) return
420
+ emitResponse(GhosttyBridge.nativeFeed(terminalHandle, data))
421
+ if (terminalCanvas.hasActiveSelection()) {
422
+ GhosttyBridge.nativeClearSelection(terminalHandle)
423
+ terminalCanvas.resetSelectionState()
424
+ }
425
+ }
426
+
427
private fun renderSnapshot() {
428
if (terminalHandle == 0L) return
429
TerminalFrame.decode(
apps/mobile/modules/t3-terminal/android/src/main/java/expo/modules/t3terminal/TerminalOutputBuffer.kt
new
+71
@@ -0,0 +1,71 @@
1
+package expo.modules.t3terminal
2
+
3
+import java.util.ArrayDeque
4
+
5
+private const val REPLAY_LIMIT = 512 * 1024
6
+private const val REPLAY_CHUNK_SIZE = 16 * 1024
7
+
8
+// Keep only replay history for intentional terminal recreation.
9
+internal class TerminalOutputBuffer {
10
+ private val chunks = ArrayDeque<ByteArray>()
11
+ private var firstOffset = 0
12
+ private var tailSize = 0
13
+ private var size = 0
14
+
15
+ // Only terminal recreation needs contiguous history; appends reuse the retained chunks.
16
+ val data: ByteArray
17
+ get() {
18
+ val result = ByteArray(size)
19
+ var destination = 0
20
+ var start = firstOffset
21
+ for (chunk in chunks) {
22
+ val end = if (chunk === chunks.last) tailSize else chunk.size
23
+ chunk.copyInto(result, destination, start, end)
24
+ destination += end - start
25
+ start = 0
26
+ }
27
+ return result
28
+ }
29
+
30
+ fun write(incoming: ByteArray, reset: Boolean) {
31
+ if (reset || incoming.size >= REPLAY_LIMIT) clear()
32
+ var start = maxOf(0, incoming.size - REPLAY_LIMIT)
33
+ while (start < incoming.size && incoming[start].toInt() and 0xC0 == 0x80) start += 1
34
+ while (start < incoming.size) {
35
+ if (chunks.isEmpty() || tailSize == REPLAY_CHUNK_SIZE) {
36
+ chunks.addLast(ByteArray(REPLAY_CHUNK_SIZE))
37
+ tailSize = 0
38
+ }
39
+ val count = minOf(incoming.size - start, REPLAY_CHUNK_SIZE - tailSize)
40
+ incoming.copyInto(chunks.last, tailSize, start, start + count)
41
+ start += count
42
+ tailSize += count
43
+ size += count
44
+ }
45
+ discardPrefix(maxOf(0, size - REPLAY_LIMIT))
46
+ while (size > 0 && chunks.first[firstOffset].toInt() and 0xC0 == 0x80) discardPrefix(1)
47
+ }
48
+
49
+ private fun discardPrefix(count: Int) {
50
+ var remaining = count
51
+ while (remaining > 0) {
52
+ val end = if (chunks.size == 1) tailSize else chunks.first.size
53
+ val discarded = minOf(remaining, end - firstOffset)
54
+ firstOffset += discarded
55
+ remaining -= discarded
56
+ size -= discarded
57
+ if (firstOffset == end) {
58
+ chunks.removeFirst()
59
+ firstOffset = 0
60
+ if (chunks.isEmpty()) tailSize = 0
61
+ }
62
+ }
63
+ }
64
+
65
+ private fun clear() {
66
+ chunks.clear()
67
+ firstOffset = 0
68
+ tailSize = 0
69
+ size = 0
70
+ }
71
+}
apps/mobile/modules/t3-terminal/ios/T3TerminalModule.swift
+5
@@ -8,9 +8,14 @@ public class T3TerminalModule: Module {
8
// logs so a stale native binary is distinguishable from a broken key pipeline.
9
Constants([
10
"hardwareKeyRevision": 3,
11
+ "outputRevision": 1,
12
])
13
14
View(T3TerminalView.self) {
15
+ AsyncFunction("writeOutput") { (view: T3TerminalView, data: String, reset: Bool) in
16
+ view.writeOutput(data, reset: reset)
17
+ }
18
+
19
Prop("terminalKey") { (view: T3TerminalView, terminalKey: String) in
20
view.terminalKey = terminalKey
21
}
apps/mobile/modules/t3-terminal/ios/T3TerminalView.swift
+21
-1
@@ -196,6 +196,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
196
private var lastContentScale: CGFloat = 0
197
private var lastReportedGrid: (cols: Int, rows: Int)?
198
private var lastAppliedBuffer = ""
199
+ private var streamedOutput: TerminalOutputBuffer?
200
private var pendingVerticalScrollPoints: CGFloat = 0
201
private var app: ghostty_app_t?
202
private var surface: ghostty_surface_t?
@@ -526,7 +527,11 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
527
ghostty_surface_set_color_scheme(createdSurface, appearance.ghosttyColorScheme)
528
setupWriteCallback()
529
resizeSurface()
529
- feedBuffer(initialBuffer)
530
+ if let streamedOutput {
531
+ feedData(streamedOutput.data)
532
+ } else {
533
+ feedBuffer(initialBuffer)
534
+ }
535
}
536
537
private func resetSurface() {
@@ -557,6 +562,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
562
}
563
564
private func applyRemoteBuffer(_ buffer: String) {
565
+ guard streamedOutput == nil else { return }
566
guard surface != nil else {
567
createSurfaceIfPossible()
568
return
@@ -579,6 +585,20 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
585
createSurfaceIfPossible()
586
}
587
588
+ func writeOutput(_ data: String, reset: Bool) {
589
+ let output = streamedOutput ?? TerminalOutputBuffer()
590
+ let bytes = Data(data.utf8)
591
+ output.write(bytes, reset: reset)
592
+ streamedOutput = output
593
+ if reset {
594
+ refreshSurface()
595
+ } else if surface == nil {
596
+ createSurfaceIfPossible()
597
+ } else {
598
+ feedData(bytes)
599
+ }
600
+ }
601
+
602
private func feedBuffer(_ buffer: String) {
603
guard !buffer.isEmpty else { return }
604
feedData(Data(buffer.utf8))
apps/mobile/modules/t3-terminal/ios/TerminalOutputBuffer.swift
new
+28
@@ -0,0 +1,28 @@
1
+import Foundation
2
+
3
+// Keep only replay history for intentional surface recreation (font/theme changes).
4
+final class TerminalOutputBuffer {
5
+ private var storage = Data()
6
+ private var retainedStart = 0
7
+ private let limit = 512 * 1024
8
+
9
+ var data: Data { storage.subdata(in: retainedStart..<storage.count) }
10
+
11
+ func write(_ incoming: Data, reset: Bool) {
12
+ if reset || incoming.count >= limit {
13
+ storage = incoming.subdata(in: max(0, incoming.count - limit)..<incoming.count)
14
+ retainedStart = 0
15
+ } else {
16
+ storage.append(incoming)
17
+ retainedStart = max(retainedStart, storage.count - limit)
18
+ }
19
+ while retainedStart < storage.count && storage[retainedStart] & 0xC0 == 0x80 {
20
+ retainedStart += 1
21
+ }
22
+ // Compact once per history window, rather than copying 512 KiB on every append.
23
+ if retainedStart >= limit {
24
+ storage = storage.subdata(in: retainedStart..<storage.count)
25
+ retainedStart = 0
26
+ }
27
+ }
28
+}
apps/mobile/src/features/terminal/NativeTerminalSurface.test.tsx
new
+153
@@ -0,0 +1,153 @@
1
+import {
2
+ applyTerminalAttachStreamEvent,
3
+ EMPTY_TERMINAL_BUFFER_STATE,
4
+ terminalOutputText,
5
+} from "@t3tools/client-runtime/state/terminal";
6
+import { act, useImperativeHandle, useLayoutEffect, type ReactNode } from "react";
7
+import { createRoot } from "react-dom/client";
8
+import type { NativeSyntheticEvent } from "react-native";
9
+import { expect, it, vi } from "vite-plus/test";
10
+
11
+import type { NativeTerminalSurfaceProps } from "./nativeTerminalModule";
12
+
13
+const mocks = vi.hoisted(() => ({
14
+ revision: null as number | null,
15
+ initialBuffers: [] as string[],
16
+ mounts: vi.fn(),
17
+ unmounts: vi.fn(),
18
+ write: vi.fn(async (_data: string, _reset: boolean) => {}),
19
+}));
20
+
21
+function RawView({ ref: nativeRef, initialBuffer, onResize }: NativeTerminalSurfaceProps) {
22
+ useImperativeHandle(nativeRef, () => ({ writeOutput: mocks.write }));
23
+ useLayoutEffect(() => {
24
+ mocks.mounts();
25
+ return () => {
26
+ mocks.unmounts();
27
+ };
28
+ }, []);
29
+ useLayoutEffect(() => {
30
+ mocks.initialBuffers.push(initialBuffer);
31
+ }, [initialBuffer]);
32
+ useLayoutEffect(() => {
33
+ onResize?.({ nativeEvent: { cols: 80, rows: 24 } } as NativeSyntheticEvent<{
34
+ cols: number;
35
+ rows: number;
36
+ }>);
37
+ }, [onResize]);
38
+ return null;
39
+}
40
+
41
+vi.mock("expo", () => ({
42
+ requireNativeView: () => RawView,
43
+ requireOptionalNativeModule: () =>
44
+ mocks.revision === null ? {} : { outputRevision: mocks.revision },
45
+}));
46
+vi.mock("react-native", () => ({ View: ({ children }: { children: ReactNode }) => children }));
47
+vi.mock("../../components/ui/AppText", () => ({ AppText: () => null }));
48
+vi.mock("../../lib/typography", () => ({ MOBILE_TYPOGRAPHY: { label: { fontSize: 10 } } }));
49
+vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({
50
+ useAppearancePreferences: () => ({ themeAppearance: "dark", themeId: "default" }),
51
+}));
52
+vi.mock("./terminalTheme", () => ({
53
+ buildGhosttyThemeConfig: () => "theme",
54
+ getMobileTerminalTheme: () => ({}),
55
+}));
56
+
57
+import { TerminalSurface } from "./NativeTerminalSurface";
58
+
59
+function setup(revision: number | null) {
60
+ mocks.revision = revision;
61
+ mocks.initialBuffers = [];
62
+ mocks.write.mockReset();
63
+ mocks.write.mockResolvedValue(undefined);
64
+ mocks.mounts.mockClear();
65
+ mocks.unmounts.mockClear();
66
+ const document = { nodeType: 9, addEventListener() {}, removeEventListener() {} };
67
+ const container = {
68
+ nodeType: 1,
69
+ tagName: "DIV",
70
+ namespaceURI: "http://www.w3.org/1999/xhtml",
71
+ ownerDocument: document,
72
+ addEventListener() {},
73
+ removeEventListener() {},
74
+ };
75
+ vi.stubGlobal("document", document);
76
+ vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
77
+ vi.stubGlobal("expo", { getViewConfig: () => ({}) });
78
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
79
+ const root = createRoot(container as unknown as HTMLElement);
80
+ return {
81
+ async render(
82
+ state: typeof EMPTY_TERMINAL_BUFFER_STATE,
83
+ terminalKey = "environment:thread:term-1",
84
+ ) {
85
+ await act(async () => {
86
+ root.render(
87
+ <TerminalSurface
88
+ terminalKey={terminalKey}
89
+ output={state.version === 0 ? null : state.output}
90
+ buffer={
91
+ state.version === 0
92
+ ? null
93
+ : (revision ?? 0) >= 1
94
+ ? ""
95
+ : terminalOutputText(state.output)
96
+ }
97
+ isRunning
98
+ onInput={() => {}}
99
+ onResize={() => {}}
100
+ />,
101
+ );
102
+ });
103
+ },
104
+ async [Symbol.asyncDispose]() {
105
+ await act(async () => root.unmount());
106
+ vi.unstubAllGlobals();
107
+ },
108
+ };
109
+}
110
+
111
+it.each([null, 1])(
112
+ "preserves the native view across rollover and uses legacy history on older binaries (revision %s)",
113
+ async (revision) => {
114
+ await using harness = setup(revision);
115
+ let state = applyTerminalAttachStreamEvent(
116
+ EMPTY_TERMINAL_BUFFER_STATE,
117
+ {
118
+ type: "output",
119
+ threadId: "thread",
120
+ terminalId: "term-1",
121
+ data: "retained",
122
+ },
123
+ 8,
124
+ );
125
+ await harness.render(state);
126
+ state = applyTerminalAttachStreamEvent(
127
+ state,
128
+ {
129
+ type: "output",
130
+ threadId: "thread",
131
+ terminalId: "term-1",
132
+ data: "-new",
133
+ },
134
+ 8,
135
+ );
136
+ await harness.render(state);
137
+ await harness.render(EMPTY_TERMINAL_BUFFER_STATE);
138
+ expect(mocks.mounts).toHaveBeenCalledTimes(1);
139
+ expect(mocks.unmounts).not.toHaveBeenCalled();
140
+ if (revision === 1) {
141
+ expect(mocks.initialBuffers).toEqual([""]);
142
+ expect(mocks.write.mock.calls).toEqual([
143
+ ["retained", true],
144
+ ["-new", false],
145
+ ]);
146
+ await harness.render(state, "another-environment:thread:term-1");
147
+ expect(mocks.write).toHaveBeenLastCalledWith("ined-new", true);
148
+ } else {
149
+ expect(mocks.write).not.toHaveBeenCalled();
150
+ expect(mocks.initialBuffers).toEqual(["retained", "ined-new"]);
151
+ }
152
+ },
153
+);
apps/mobile/src/features/terminal/NativeTerminalSurface.tsx
+33
-3
@@ -1,4 +1,5 @@
1
-import { memo, useCallback, useEffect, useRef } from "react";
1
+import type { TerminalOutputState } from "@t3tools/client-runtime/state/terminal";
2
+import { memo, useCallback, useEffect, useRef, useState } from "react";
3
import {
4
Pressable,
5
ScrollView,
@@ -16,6 +17,8 @@ import { useAppearancePreferences } from "../settings/appearance/AppearancePrefe
17
import {
18
getNativeTerminalHardwareKeyRevision,
19
resolveNativeTerminalSurfaceView,
20
+ supportsNativeTerminalOutput,
21
+ type NativeTerminalSurfaceHandle,
22
} from "./nativeTerminalModule";
23
import {
24
buildGhosttyThemeConfig,
@@ -24,6 +27,7 @@ import {
27
} from "./terminalTheme";
28
import { terminalDebugLog } from "./terminalDebugLog";
29
import { useTerminalSurfaceBuffer } from "./useTerminalSurfaceBuffer";
30
+import { createTerminalOutputWriter } from "./terminalOutputWriter";
31
32
interface TerminalInputEvent {
33
readonly data: string;
@@ -37,6 +41,7 @@ interface TerminalResizeEvent {
41
interface TerminalSurfaceProps extends ViewProps {
42
readonly terminalKey: string;
43
readonly buffer: string | null;
44
+ readonly output: TerminalOutputState | null;
45
readonly fontSize?: number;
46
readonly isRunning: boolean;
47
readonly readOnly?: boolean;
@@ -186,7 +191,7 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(
191
192
export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) {
193
const buffer = useTerminalSurfaceBuffer(props);
189
- return <ReadyTerminalSurface {...props} buffer={buffer} />;
194
+ return <ReadyTerminalSurface key={props.terminalKey} {...props} buffer={buffer} />;
195
});
196
197
const ReadyTerminalSurface = memo(function ReadyTerminalSurface(props: ReadyTerminalSurfaceProps) {
@@ -196,6 +201,28 @@ const ReadyTerminalSurface = memo(function ReadyTerminalSurface(props: ReadyTerm
201
const { onInput, onResize } = props;
202
const NativeTerminalSurfaceView = resolveNativeTerminalSurfaceView();
203
const hasNativeSurface = Boolean(NativeTerminalSurfaceView);
204
+ const streaming = supportsNativeTerminalOutput();
205
+ const nativeRef = useRef<NativeTerminalSurfaceHandle>(null);
206
+ const writerRef = useRef<ReturnType<typeof createTerminalOutputWriter> | null>(null);
207
+ const [nativeReady, setNativeReady] = useState(false);
208
+
209
+ useEffect(() => {
210
+ const view = nativeRef.current;
211
+ if (!streaming || !nativeReady || view === null) return;
212
+ const writer = createTerminalOutputWriter((data, reset) => view.writeOutput(data, reset));
213
+ writerRef.current = writer;
214
+ return () => {
215
+ writerRef.current = null;
216
+ writer.dispose();
217
+ };
218
+ }, [nativeReady, streaming]);
219
+
220
+ useEffect(() => {
221
+ if (!streaming || !nativeReady || props.output === null) return;
222
+ void writerRef.current?.write(props.output).catch((error: unknown) => {
223
+ console.error("Terminal output delivery failed", error);
224
+ });
225
+ }, [nativeReady, props.output, streaming]);
226
227
useEffect(() => {
228
terminalDebugLog("native:surface", {
@@ -220,6 +247,8 @@ const ReadyTerminalSurface = memo(function ReadyTerminalSurface(props: ReadyTerm
247
);
248
const handleNativeResize = useCallback(
249
(event: NativeSyntheticEvent<TerminalResizeEvent>) => {
250
+ // The first grid event comes from the mounted native surface, after registration.
251
+ setNativeReady(true);
252
onResize({
253
cols: event.nativeEvent.cols,
254
rows: event.nativeEvent.rows,
@@ -232,6 +261,7 @@ const ReadyTerminalSurface = memo(function ReadyTerminalSurface(props: ReadyTerm
261
return (
262
<View style={props.style}>
263
<NativeTerminalSurfaceView
264
+ ref={nativeRef}
265
appearanceScheme={themeAppearance}
266
autoFocus={!props.readOnly && (props.autoFocus ?? true)}
267
readOnly={props.readOnly ?? false}
@@ -240,7 +270,7 @@ const ReadyTerminalSurface = memo(function ReadyTerminalSurface(props: ReadyTerm
270
foregroundColor={theme.foreground}
271
mutedForegroundColor={theme.mutedForeground}
272
terminalKey={props.terminalKey}
243
- initialBuffer={props.buffer}
273
+ initialBuffer={streaming ? "" : props.buffer}
274
fontSize={fontSize}
275
style={{ flex: 1 }}
276
themeConfig={buildGhosttyThemeConfig(theme)}
apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+4
-1
@@ -17,7 +17,7 @@ import { Platform, Pressable, View } from "react-native";
17
import { useSafeAreaInsets } from "react-native-safe-area-context";
18
import { AppText as Text } from "../../components/ui/AppText";
19
import { TerminalContextSheet } from "./TerminalContextSheet";
20
-import { hasNativeTerminalSurface } from "./nativeTerminalModule";
20
+import { hasNativeTerminalSurface, supportsNativeTerminalOutput } from "./nativeTerminalModule";
21
import * as Clipboard from "expo-clipboard";
22
import * as Schema from "effect/Schema";
23
import {
@@ -449,7 +449,9 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
449
);
450
const observingTerminal =
451
!canOperateTerminal && canReadTerminal && selectedThread !== null && hasTerminalTarget;
452
+ const streamingOutput = supportsNativeTerminalOutput();
453
const terminal = useAttachedTerminalSession({
454
+ materializeBuffer: !streamingOutput,
455
environmentId: selectedThread?.environmentId ?? null,
456
terminal: canOperateTerminal
457
? terminalAttachInput
@@ -1245,6 +1247,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
1247
autoFocus={canOperateTerminal && terminalAutoFocus}
1248
readOnly={!canOperateTerminal}
1249
buffer={terminal.version === 0 ? null : terminalSurfaceBuffer}
1250
+ output={terminal.version === 0 ? null : terminal.output}
1251
fontSize={fontSize}
1252
isRunning={isRunning}
1253
keyboardFocusRequest={keyboardFocusRequest}
apps/mobile/src/features/terminal/nativeTerminalModule.ts
+17
-1
@@ -1,4 +1,4 @@
1
-import type { ComponentType } from "react";
1
+import type { ComponentType, Ref } from "react";
2
import type { NativeSyntheticEvent, ViewProps } from "react-native";
3
import { requireNativeView, requireOptionalNativeModule } from "expo";
4
@@ -22,6 +22,7 @@ interface TerminalResizeEvent {
22
}
23
24
export interface NativeTerminalSurfaceProps extends ViewProps {
25
+ readonly ref?: Ref<NativeTerminalSurfaceHandle>;
26
readonly appearanceScheme?: "light" | "dark";
27
readonly autoFocus?: boolean;
28
readonly readOnly?: boolean;
@@ -39,6 +40,10 @@ export interface NativeTerminalSurfaceProps extends ViewProps {
40
readonly onResize?: (event: NativeSyntheticEvent<TerminalResizeEvent>) => void;
41
}
42
43
+export interface NativeTerminalSurfaceHandle {
44
+ readonly writeOutput: (data: string, reset: boolean) => Promise<void>;
45
+}
46
+
47
let cachedNativeTerminalSurfaceView: ComponentType<NativeTerminalSurfaceProps> | undefined;
48
let nativeTerminalSurfaceViewResolutionFailed = false;
49
@@ -96,3 +101,14 @@ export function getNativeTerminalHardwareKeyRevision(): number | null {
101
export function hasNativeTerminalSurface() {
102
return resolveNativeTerminalSurfaceView() !== null;
103
}
104
+
105
+export function supportsNativeTerminalOutput(): boolean {
106
+ try {
107
+ const module = requireOptionalNativeModule<{ readonly outputRevision?: number }>(
108
+ NATIVE_TERMINAL_MODULE_NAME,
109
+ );
110
+ return (module?.outputRevision ?? 0) >= 1 && hasNativeTerminalSurface();
111
+ } catch {
112
+ return false;
113
+ }
114
+}
apps/mobile/src/features/terminal/terminalOutputWriter.test.ts
new
+73
@@ -0,0 +1,73 @@
1
+import {
2
+ applyTerminalAttachStreamEvent,
3
+ DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
4
+ EMPTY_TERMINAL_BUFFER_STATE,
5
+ terminalOutputText,
6
+} from "@t3tools/client-runtime/state/terminal";
7
+import { expect, it, vi } from "vite-plus/test";
8
+
9
+import { createTerminalOutputWriter } from "./terminalOutputWriter";
10
+
11
+function append(
12
+ state: typeof EMPTY_TERMINAL_BUFFER_STATE,
13
+ data: string,
14
+ limit = DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
15
+) {
16
+ return applyTerminalAttachStreamEvent(
17
+ state,
18
+ { type: "output", data, threadId: "thread", terminalId: "term-1" },
19
+ limit,
20
+ );
21
+}
22
+
23
+it("appends across rollover without replay and seeds fresh writers with only bounded history", async () => {
24
+ const write = vi.fn(async (_data: string, _reset: boolean) => {});
25
+ const writer = createTerminalOutputWriter(write);
26
+ let state = EMPTY_TERMINAL_BUFFER_STATE;
27
+ const chunks: string[] = [];
28
+ await writer.write(state.output);
29
+ for (let index = 0; index < 128; index += 1) {
30
+ const chunk = `${index}\r\n`.padEnd(16 * 1024, "x");
31
+ chunks.push(chunk);
32
+ state = append(state, chunk);
33
+ await writer.write(state.output);
34
+ expect(write).toHaveBeenLastCalledWith(chunk, false);
35
+ }
36
+ expect(state.output.retainedBytes).toBe(DEFAULT_MAX_TERMINAL_BUFFER_BYTES);
37
+ const retained = chunks.slice(-32).join("");
38
+ expect(terminalOutputText(state.output)).toBe(retained);
39
+ expect(write.mock.calls.filter(([, reset]) => reset)).toEqual([["", true]]);
40
+ expect(write.mock.calls.reduce((total, [data]) => total + data.length, 0)).toBe(2 * 1024 * 1024);
41
+
42
+ const remountedWrite = vi.fn(async () => {});
43
+ await createTerminalOutputWriter(remountedWrite).write(state.output);
44
+ expect(remountedWrite.mock.calls).toEqual([[retained, true]]);
45
+});
46
+
47
+it("recovers the newer snapshot queued during a rejected append without a third write", async () => {
48
+ const started = Promise.withResolvers<void>();
49
+ const release = Promise.withResolvers<void>();
50
+ const write = vi.fn(async () => {});
51
+ const writer = createTerminalOutputWriter(write);
52
+ const initial = append(EMPTY_TERMINAL_BUFFER_STATE, "initial");
53
+ await writer.write(initial.output);
54
+ write.mockImplementationOnce(async () => {
55
+ started.resolve();
56
+ await release.promise;
57
+ throw new Error("partially applied append");
58
+ });
59
+ const first = append(initial, "-first");
60
+ const draining = writer.write(first.output);
61
+ await started.promise;
62
+ const latest = append(first, "-latest");
63
+ void writer.write(latest.output);
64
+ release.resolve();
65
+ await draining;
66
+ expect(write.mock.calls).toEqual([
67
+ ["initial", true],
68
+ ["-first", false],
69
+ ["initial-first-latest", true],
70
+ ]);
71
+ await writer.write(append(latest, "-next").output);
72
+ expect(write).toHaveBeenLastCalledWith("-next", false);
73
+});
apps/mobile/src/features/terminal/terminalOutputWriter.ts
new
+56
@@ -0,0 +1,56 @@
1
+import {
2
+ INITIAL_TERMINAL_OUTPUT_CURSOR,
3
+ readTerminalOutputUpdate,
4
+ type TerminalOutputState,
5
+} from "@t3tools/client-runtime/state/terminal";
6
+
7
+/** One writer per mounted native view; intermediate snapshots can be coalesced safely. */
8
+export function createTerminalOutputWriter(
9
+ writeOutput: (data: string, reset: boolean) => Promise<void>,
10
+) {
11
+ let cursor = INITIAL_TERMINAL_OUTPUT_CURSOR;
12
+ let pending: TerminalOutputState | null = null;
13
+ let draining: Promise<void> | null = null;
14
+ let disposed = false;
15
+
16
+ async function drain() {
17
+ let recovering = false;
18
+ try {
19
+ while (pending !== null) {
20
+ if (disposed) return;
21
+ const output = pending;
22
+ pending = null;
23
+ const update = readTerminalOutputUpdate(output, cursor);
24
+ if (update.type === "none") continue;
25
+ try {
26
+ await writeOutput(update.data, update.type === "reset");
27
+ } catch (error) {
28
+ if (disposed) return;
29
+ // A rejected command may have partially applied. Replay the latest retained history
30
+ // once per drain; a persistent native failure must settle instead of spinning.
31
+ cursor = INITIAL_TERMINAL_OUTPUT_CURSOR;
32
+ pending ??= output;
33
+ if (recovering) throw error;
34
+ recovering = true;
35
+ continue;
36
+ }
37
+ cursor = update.cursor;
38
+ }
39
+ } finally {
40
+ draining = null;
41
+ }
42
+ }
43
+
44
+ return {
45
+ write(output: TerminalOutputState): Promise<void> {
46
+ if (disposed) return Promise.resolve();
47
+ pending = output;
48
+ draining ??= Promise.resolve().then(drain);
49
+ return draining;
50
+ },
51
+ dispose() {
52
+ disposed = true;
53
+ pending = null;
54
+ },
55
+ };
56
+}
apps/mobile/src/state/use-terminal-session.ts
+7
-2
@@ -28,6 +28,7 @@ const EMPTY_LEGACY_TERMINAL_SESSION_STATE: LegacyTerminalSessionState = {
28
export function useAttachedTerminalSession(input: {
29
readonly environmentId: EnvironmentId | null;
30
readonly terminal: TerminalAttachInput | null;
31
+ readonly materializeBuffer?: boolean;
32
}): LegacyTerminalSessionState {
33
const canRead = useEnvironmentScope(input.environmentId, AuthTerminalReadScope);
34
const canOperate = useEnvironmentScope(input.environmentId, AuthTerminalOperateScope);
@@ -55,8 +56,12 @@ export function useAttachedTerminalSession(input: {
56
}),
57
);
58
const output = attach.data?.output ?? EMPTY_TERMINAL_BUFFER_STATE.output;
58
- // Keep initialBuffer materialization at the mobile boundary until native streaming ships.
59
- const buffer = useMemo(() => terminalOutputText(output), [output]);
59
+ const materializeBuffer = input.materializeBuffer ?? true;
60
+ // Older installed binaries and the text fallback still need initialBuffer.
61
+ const buffer = useMemo(
62
+ () => (materializeBuffer ? terminalOutputText(output) : ""),
63
+ [materializeBuffer, output],
64
+ );
65
66
return useMemo(() => {
67
if (input.environmentId === null || input.terminal === null) {