Skip to content

Commit 5214f0e

Browse files
perf(mobile): append terminal output without replaying history
1 parent 22dc1da commit 5214f0e

15 files changed

Lines changed: 779 additions & 10 deletions

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,14 @@ class T3TerminalModule : Module() {
1111
// logs so a stale native binary is distinguishable from a broken key pipeline.
1212
Constants(
1313
"hardwareKeyRevision" to 2,
14+
"outputRevision" to 1,
1415
)
1516

1617
View(T3TerminalView::class) {
18+
AsyncFunction("writeOutput") { view: T3TerminalView, data: String, reset: Boolean ->
19+
view.writeOutput(data, reset)
20+
}
21+
1722
Prop("terminalKey") { view: T3TerminalView, terminalKey: String ->
1823
view.terminalKey = terminalKey
1924
}

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

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
5555
}
5656
private var terminalHandle = 0L
5757
private var fedBuffer = ""
58+
private var streamedOutput: TerminalOutputBuffer? = null
5859
private var cols = 0
5960
private var rows = 0
6061
private var clearingInput = false
@@ -362,6 +363,7 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
362363
paletteColors,
363364
)
364365
fedBuffer = ""
366+
streamedOutput?.let { output -> feedOutput(output.data) }
365367
}
366368

367369
private fun recreateTerminal() {
@@ -381,7 +383,7 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
381383
}
382384

383385
private fun feedPendingBuffer() {
384-
if (terminalHandle == 0L || initialBuffer == fedBuffer) return
386+
if (streamedOutput != null || terminalHandle == 0L || initialBuffer == fedBuffer) return
385387
if (!initialBuffer.startsWith(fedBuffer)) {
386388
recreateTerminal()
387389
if (terminalHandle == 0L) return
@@ -400,6 +402,28 @@ class T3TerminalView(context: Context, appContext: AppContext) : ExpoView(contex
400402
renderSnapshot()
401403
}
402404

405+
fun writeOutput(data: String, reset: Boolean) {
406+
if (isCleanedUp) return
407+
val output = streamedOutput ?: TerminalOutputBuffer()
408+
output.write(data, reset)
409+
streamedOutput = output
410+
if (reset) {
411+
recreateTerminal()
412+
} else if (terminalHandle != 0L) {
413+
feedOutput(data.toByteArray(Charsets.UTF_8))
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+
403427
private fun renderSnapshot() {
404428
if (terminalHandle == 0L) return
405429
TerminalFrame.decode(
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
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(text: String, reset: Boolean) {
31+
val incoming = text.toByteArray(Charsets.UTF_8)
32+
if (reset || incoming.size >= REPLAY_LIMIT) clear()
33+
var start = maxOf(0, incoming.size - REPLAY_LIMIT)
34+
while (start < incoming.size && incoming[start].toInt() and 0xC0 == 0x80) start += 1
35+
while (start < incoming.size) {
36+
if (chunks.isEmpty() || tailSize == REPLAY_CHUNK_SIZE) {
37+
chunks.addLast(ByteArray(REPLAY_CHUNK_SIZE))
38+
tailSize = 0
39+
}
40+
val count = minOf(incoming.size - start, REPLAY_CHUNK_SIZE - tailSize)
41+
incoming.copyInto(chunks.last, tailSize, start, start + count)
42+
start += count
43+
tailSize += count
44+
size += count
45+
}
46+
discardPrefix(maxOf(0, size - REPLAY_LIMIT))
47+
while (size > 0 && chunks.first[firstOffset].toInt() and 0xC0 == 0x80) discardPrefix(1)
48+
}
49+
50+
private fun discardPrefix(count: Int) {
51+
var remaining = count
52+
while (remaining > 0) {
53+
val end = if (chunks.size == 1) tailSize else chunks.first.size
54+
val discarded = minOf(remaining, end - firstOffset)
55+
firstOffset += discarded
56+
remaining -= discarded
57+
size -= discarded
58+
if (firstOffset == end) {
59+
chunks.removeFirst()
60+
firstOffset = 0
61+
if (chunks.isEmpty()) tailSize = 0
62+
}
63+
}
64+
}
65+
66+
private fun clear() {
67+
chunks.clear()
68+
firstOffset = 0
69+
tailSize = 0
70+
size = 0
71+
}
72+
}

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,14 @@ public class T3TerminalModule: Module {
88
// logs so a stale native binary is distinguishable from a broken key pipeline.
99
Constants([
1010
"hardwareKeyRevision": 3,
11+
"outputRevision": 1,
1112
])
1213

1314
View(T3TerminalView.self) {
15+
AsyncFunction("writeOutput") { (view: T3TerminalView, data: String, reset: Bool) in
16+
view.writeOutput(data, reset: reset)
17+
}
18+
1419
Prop("terminalKey") { (view: T3TerminalView, terminalKey: String) in
1520
view.terminalKey = terminalKey
1621
}

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

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
205205
private var lastContentScale: CGFloat = 0
206206
private var lastReportedGrid: (cols: Int, rows: Int)?
207207
private var lastAppliedBuffer = ""
208+
private var streamedOutput: TerminalOutputBuffer?
208209
private var pendingVerticalScrollPoints: CGFloat = 0
209210
private var app: ghostty_app_t?
210211
private var surface: ghostty_surface_t?
@@ -535,7 +536,11 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
535536
ghostty_surface_set_color_scheme(createdSurface, appearance.ghosttyColorScheme)
536537
setupWriteCallback()
537538
resizeSurface()
538-
feedBuffer(initialBuffer)
539+
if let streamedOutput {
540+
feedData(streamedOutput.data)
541+
} else {
542+
feedBuffer(initialBuffer)
543+
}
539544
}
540545

541546
private func resetSurface() {
@@ -566,6 +571,7 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
566571
}
567572

568573
private func applyRemoteBuffer(_ buffer: String) {
574+
guard streamedOutput == nil else { return }
569575
guard surface != nil else {
570576
createSurfaceIfPossible()
571577
return
@@ -588,6 +594,19 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
588594
createSurfaceIfPossible()
589595
}
590596

597+
func writeOutput(_ data: String, reset: Bool) {
598+
let output = streamedOutput ?? TerminalOutputBuffer()
599+
output.write(data, reset: reset)
600+
streamedOutput = output
601+
if reset {
602+
refreshSurface()
603+
} else if surface == nil {
604+
createSurfaceIfPossible()
605+
} else {
606+
feedData(Data(data.utf8))
607+
}
608+
}
609+
591610
private func feedBuffer(_ buffer: String) {
592611
guard !buffer.isEmpty else { return }
593612
feedData(Data(buffer.utf8))
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import Foundation
2+
3+
// Keep only replay history for intentional surface recreation (font/theme changes).
4+
final class TerminalOutputBuffer {
5+
private(set) var data = Data()
6+
private let limit = 512 * 1024
7+
8+
func write(_ text: String, reset: Bool) {
9+
if reset {
10+
data = Data(text.utf8)
11+
} else {
12+
data.append(contentsOf: text.utf8)
13+
}
14+
guard data.count > limit else { return }
15+
var start = data.count - limit
16+
while start < data.count && data[data.startIndex + start] & 0xC0 == 0x80 {
17+
start += 1
18+
}
19+
data = Data(data.dropFirst(start))
20+
}
21+
}
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
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: 0,
15+
initialBuffers: [] as string[],
16+
write: vi.fn(async (_data: string, _reset: boolean) => {}),
17+
}));
18+
19+
function RawView({ ref: nativeRef, initialBuffer, onResize }: NativeTerminalSurfaceProps) {
20+
useImperativeHandle(nativeRef, () => ({ writeOutput: mocks.write }));
21+
useLayoutEffect(() => {
22+
mocks.initialBuffers.push(initialBuffer);
23+
}, [initialBuffer]);
24+
useLayoutEffect(() => {
25+
onResize?.({ nativeEvent: { cols: 80, rows: 24 } } as NativeSyntheticEvent<{
26+
cols: number;
27+
rows: number;
28+
}>);
29+
}, [onResize]);
30+
return null;
31+
}
32+
33+
vi.mock("expo", () => ({
34+
requireNativeView: () => RawView,
35+
requireOptionalNativeModule: () => ({ outputRevision: mocks.revision }),
36+
}));
37+
vi.mock("react-native", () => ({ View: ({ children }: { children: ReactNode }) => children }));
38+
vi.mock("../../components/ui/AppText", () => ({ AppText: () => null }));
39+
vi.mock("../../lib/typography", () => ({ MOBILE_TYPOGRAPHY: { label: { fontSize: 10 } } }));
40+
vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({
41+
useAppearancePreferences: () => ({ themeAppearance: "dark", themeId: "default" }),
42+
}));
43+
vi.mock("./terminalTheme", () => ({
44+
buildGhosttyThemeConfig: () => "theme",
45+
getMobileTerminalTheme: () => ({}),
46+
}));
47+
48+
import { TerminalSurface } from "./NativeTerminalSurface";
49+
50+
function setup(revision: number) {
51+
mocks.revision = revision;
52+
mocks.initialBuffers = [];
53+
mocks.write.mockClear();
54+
const document = { nodeType: 9, addEventListener() {}, removeEventListener() {} };
55+
const container = {
56+
nodeType: 1,
57+
tagName: "DIV",
58+
namespaceURI: "http://www.w3.org/1999/xhtml",
59+
ownerDocument: document,
60+
addEventListener() {},
61+
removeEventListener() {},
62+
};
63+
vi.stubGlobal("document", document);
64+
vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
65+
vi.stubGlobal("expo", { getViewConfig: () => ({}) });
66+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
67+
const root = createRoot(container as unknown as HTMLElement);
68+
return {
69+
async render(
70+
state: typeof EMPTY_TERMINAL_BUFFER_STATE,
71+
terminalKey = "environment:thread:term-1",
72+
) {
73+
await act(async () => {
74+
root.render(
75+
<TerminalSurface
76+
terminalKey={terminalKey}
77+
output={state.version === 0 ? null : state.output}
78+
buffer={
79+
state.version === 0 ? null : revision >= 1 ? "" : terminalOutputText(state.output)
80+
}
81+
isRunning
82+
onInput={() => {}}
83+
onResize={() => {}}
84+
/>,
85+
);
86+
});
87+
},
88+
async [Symbol.asyncDispose]() {
89+
await act(async () => root.unmount());
90+
vi.unstubAllGlobals();
91+
},
92+
};
93+
}
94+
95+
it.each([0, 1])(
96+
"uses append/reset only on capable installed binaries (revision %s)",
97+
async (revision) => {
98+
await using harness = setup(revision);
99+
let state = applyTerminalAttachStreamEvent(
100+
EMPTY_TERMINAL_BUFFER_STATE,
101+
{
102+
type: "output",
103+
threadId: "thread",
104+
terminalId: "term-1",
105+
data: "retained",
106+
},
107+
8,
108+
);
109+
await harness.render(state);
110+
state = applyTerminalAttachStreamEvent(
111+
state,
112+
{
113+
type: "output",
114+
threadId: "thread",
115+
terminalId: "term-1",
116+
data: "-new",
117+
},
118+
8,
119+
);
120+
await harness.render(state);
121+
await harness.render(EMPTY_TERMINAL_BUFFER_STATE);
122+
if (revision === 1) {
123+
expect(mocks.initialBuffers).toEqual([""]);
124+
expect(mocks.write.mock.calls).toEqual([
125+
["retained", true],
126+
["-new", false],
127+
]);
128+
await harness.render(state, "another-environment:thread:term-1");
129+
expect(mocks.write).toHaveBeenLastCalledWith("ined-new", true);
130+
} else {
131+
expect(mocks.write).not.toHaveBeenCalled();
132+
expect(mocks.initialBuffers).toEqual(["retained", "ined-new"]);
133+
}
134+
},
135+
);

0 commit comments

Comments
 (0)