perf(web): stop replaying terminal buffers on rollover (#9707)

Keep bounded, byte-counted terminal chunks and append only unread output. Use UTF-16 cursors so compaction preserves live terminal replies. Reset on lifecycle changes or a real retained-data gap.

Keep the existing wire protocol, native buffer interface, and client retention limit. Native streaming and strict server replay byte bounds remain separate.

Continue the client helpers from https://github.com/pingdotgg/t3code/pull/9027 at source head 9391da2b48439d1d7a2b01d169e785682bf8abb8.

Created with GPT-6 Astra (preview) in Codex.

Co-Authored-By: Wout Stiens <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-09-04 09:27:24 -07:00
1 parent 7839140e5e
commit da7e46d08e
8 files changed
+928 -67

No files matched your search

@@ -1,6 +1,9 @@
import { describe, expect, it } from "vite-plus/test";
import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal";
import {
EMPTY_TERMINAL_BUFFER_STATE,
type KnownTerminalSession,
} from "@t3tools/client-runtime/state/terminal";
import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
@@ -55,7 +58,7 @@ function makeKnownSession(input: {
updatedAt: input.updatedAt ?? "2026-04-15T20:00:00.000Z",
}
: null,
buffer: "",
output: EMPTY_TERMINAL_BUFFER_STATE.output,
status: input.status,
error: null,
hasRunningSubprocess: false,
+18 -4
View File
@@ -2,6 +2,7 @@ import {
combineTerminalSessionState,
EMPTY_TERMINAL_BUFFER_STATE,
EMPTY_TERMINAL_SESSION_STATE,
terminalOutputText,
type KnownTerminalSession,
type TerminalSessionState,
} from "@t3tools/client-runtime/state/terminal";
@@ -11,10 +12,16 @@ import { useMemo } from "react";
import { useEnvironmentQuery } from "./query";
import { terminalEnvironment } from "./terminal";
type LegacyTerminalSessionState = TerminalSessionState & { readonly buffer: string };
const EMPTY_LEGACY_TERMINAL_SESSION_STATE: LegacyTerminalSessionState = {
...EMPTY_TERMINAL_SESSION_STATE,
buffer: "",
};
export function useAttachedTerminalSession(input: {
readonly environmentId: EnvironmentId | null;
readonly terminal: TerminalAttachInput | null;
}): TerminalSessionState {
}): LegacyTerminalSessionState {
const attach = useEnvironmentQuery(
input.environmentId !== null && input.terminal !== null
? terminalEnvironment.attach({
@@ -31,10 +38,14 @@ export function useAttachedTerminalSession(input: {
input: null,
}),
);
const output = attach.data?.output ?? EMPTY_TERMINAL_BUFFER_STATE.output;
// Installed native binaries still accept initialBuffer. Keep materialization
// at this mobile boundary until the native streaming API is released.
const buffer = useMemo(() => terminalOutputText(output), [output]);
return useMemo(() => {
if (input.environmentId === null || input.terminal === null) {
return EMPTY_TERMINAL_SESSION_STATE;
return EMPTY_LEGACY_TERMINAL_SESSION_STATE;
}
const summary =
metadata.data?.find(
@@ -42,9 +53,12 @@ export function useAttachedTerminalSession(input: {
terminal.threadId === input.terminal?.threadId &&
terminal.terminalId === input.terminal?.terminalId,
) ?? null;
const state = combineTerminalSessionState(summary, attach.data ?? EMPTY_TERMINAL_BUFFER_STATE);
const state = {
...combineTerminalSessionState(summary, attach.data ?? EMPTY_TERMINAL_BUFFER_STATE),
buffer,
};
return attach.error === null ? state : { ...state, error: attach.error, status: "error" };
}, [attach.data, attach.error, input.environmentId, input.terminal, metadata.data]);
}, [attach.data, attach.error, buffer, input.environmentId, input.terminal, metadata.data]);
}
export function useKnownTerminalSessions(input: {
@@ -3,7 +3,13 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { type TerminalSessionState } from "@t3tools/client-runtime/state/terminal";
import {
INITIAL_TERMINAL_OUTPUT_CURSOR,
readTerminalOutputUpdate,
type TerminalOutputCursor,
type TerminalOutputUpdate,
type TerminalSessionState,
} from "@t3tools/client-runtime/state/terminal";
import {
Plus,
Square,
@@ -99,8 +105,15 @@ function writeSystemMessage(terminal: GhosttyTerminalSurface, message: string):
terminal.write(`\r\n[terminal] ${message}\r\n`);
}
function writeTerminalBuffer(terminal: GhosttyTerminalSurface, buffer: string): void {
terminal.resetAndWrite(buffer);
export function writeTerminalOutputUpdate(
terminal: Pick<GhosttyTerminalSurface, "resetAndWrite" | "write">,
update: TerminalOutputUpdate,
): void {
if (update.type === "reset") {
terminal.resetAndWrite(update.data);
} else if (update.type === "append") {
terminal.write(update.data);
}
}
function parseTerminalColor(value: string, fallback: GhosttyColor): GhosttyColor {
@@ -380,9 +393,10 @@ export function TerminalViewport({
input: { threadId, terminalId, cols, rows },
}),
);
const terminalBuffer = terminalSession.buffer;
const terminalOutput = terminalSession.output;
const terminalError = terminalSession.error;
const terminalStatus = terminalSession.status;
const outputCursorRef = useRef<TerminalOutputCursor>(INITIAL_TERMINAL_OUTPUT_CURSOR);
const synchronizedStatusRef = useRef<TerminalSessionState["status"]>("closed");
const synchronizeTerminalStatus = useEffectEvent(
(terminal: GhosttyTerminalSurface, status: TerminalSessionState["status"]) => {
@@ -403,14 +417,14 @@ export function TerminalViewport({
);
const terminalVersion = terminalSession.version;
const previousSessionRef = useRef({
buffer: terminalBuffer,
output: terminalOutput,
error: terminalError,
status: terminalStatus,
version: terminalVersion,
});
const latestSessionRef = useRef(previousSessionRef.current);
latestSessionRef.current = {
buffer: terminalBuffer,
output: terminalOutput,
error: terminalError,
status: terminalStatus,
version: terminalVersion,
@@ -474,7 +488,14 @@ export function TerminalViewport({
}
const latestSession = latestSessionRef.current;
previousSessionRef.current = latestSession;
if (latestSession.buffer.length > 0) terminal.resetAndWrite(latestSession.buffer);
const initialOutput = readTerminalOutputUpdate(
latestSession.output,
INITIAL_TERMINAL_OUTPUT_CURSOR,
);
if (initialOutput.type === "reset" && initialOutput.data.length > 0) {
writeTerminalOutputUpdate(terminal, initialOutput);
}
outputCursorRef.current = initialOutput.cursor;
if (latestSession.error !== null) writeSystemMessage(terminal, latestSession.error);
// Attaching to a session that already exited must still run exit handling
// once, so mount synchronization starts from the empty "closed" state.
@@ -845,7 +866,7 @@ export function TerminalViewport({
useEffect(() => {
const terminal = terminalRef.current;
const current = {
buffer: terminalBuffer,
output: terminalOutput,
error: terminalError,
status: terminalStatus,
version: terminalVersion,
@@ -857,18 +878,13 @@ export function TerminalViewport({
const previous = previousSessionRef.current;
synchronizeTerminalStatus(terminal, current.status);
if (current.version === previous.version) {
if (current.version === previous.version && current.output === previous.output) {
return;
}
if (
current.buffer.length >= previous.buffer.length &&
current.buffer.startsWith(previous.buffer)
) {
terminal.write(current.buffer.slice(previous.buffer.length));
} else {
writeTerminalBuffer(terminal, current.buffer);
}
const outputUpdate = readTerminalOutputUpdate(current.output, outputCursorRef.current);
writeTerminalOutputUpdate(terminal, outputUpdate);
outputCursorRef.current = outputUpdate.cursor;
terminal.clearSelection();
if (current.error !== null && current.error !== previous.error) {
@@ -881,7 +897,7 @@ export function TerminalViewport({
});
}
previousSessionRef.current = current;
}, [autoFocus, terminalBuffer, terminalError, terminalStatus, terminalVersion]);
}, [autoFocus, terminalOutput, terminalError, terminalStatus, terminalVersion]);
useEffect(() => {
if (!autoFocus) return;
+234 -2
View File
@@ -1,5 +1,15 @@
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import {
applyTerminalAttachStreamEvent,
DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
INITIAL_TERMINAL_OUTPUT_CURSOR,
nextTerminalAttachSeedState,
readTerminalOutputUpdate,
terminalOutputText,
type TerminalBufferState,
} from "@t3tools/client-runtime/state/terminal";
import { writeTerminalOutputUpdate } from "../../components/ThreadTerminalDrawer";
import { GHOSTTY_CELL_WIDE, GhosttyTerminalCore, ghosttyCellText } from "./core";
import { loadGhosttyRuntime } from "./runtime";
@@ -50,7 +60,7 @@ describe("ghosttyCellText", () => {
describe("GhosttyTerminalCore snapshots", () => {
const cores = new Set<GhosttyTerminalCore>();
async function createCore() {
async function createCore(onData: (data: string) => void = () => {}) {
const core = await GhosttyTerminalCore.create(
12,
3,
@@ -61,12 +71,40 @@ describe("GhosttyTerminalCore snapshots", () => {
background: { r: 0, g: 0, b: 0 },
cursor: { r: 255, g: 255, b: 255 },
},
() => {},
onData,
);
cores.add(core);
return core;
}
function createSession(history: string) {
return applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
type: "snapshot",
snapshot: {
threadId: "terminal-stream-test",
terminalId: "term-1",
cwd: "/repo",
worktreePath: null,
status: "running",
pid: 123,
history,
exitCode: null,
exitSignal: null,
label: "Terminal",
updatedAt: "2026-09-04T00:00:00.000Z",
},
});
}
function append(state: TerminalBufferState, data: string) {
return applyTerminalAttachStreamEvent(state, {
type: "output",
threadId: "terminal-stream-test",
terminalId: "term-1",
data,
});
}
afterEach(() => {
for (const core of cores) core.dispose();
cores.clear();
@@ -145,4 +183,198 @@ describe("GhosttyTerminalCore snapshots", () => {
core.dispose();
expect(free).toHaveBeenCalledWith(buffer, capacity);
});
it.each(["varied", "identical"] as const)(
"preserves Ghostty state through a full MiB of %s output without rollover resets",
async (kind) => {
const [core, reference] = await Promise.all([createCore(), createCore()]);
const initial = "\x1b[31m";
let state = createSession(initial);
const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
writeTerminalOutputUpdate(core, first);
reference.resetAndWrite(initial);
let cursor = first.cursor;
const reset = vi.spyOn(core, "resetAndWrite");
const inputs: string[] = [];
let receivedCharacters = 0;
for (let index = 0; index < 128; index += 1) {
const data =
kind === "identical"
? "x".repeat(8192)
: `${index.toString().padStart(4, "0")}\r\n${"x".repeat(8186)}`;
inputs.push(data);
state = append(state, data);
const update = readTerminalOutputUpdate(state.output, cursor);
if (update.type !== "append") throw new Error(`Expected append, received ${update.type}`);
receivedCharacters += update.data.length;
writeTerminalOutputUpdate(core, update);
cursor = update.cursor;
}
reference.write(inputs.join(""));
expect(receivedCharacters).toBe(1024 * 1024);
expect(state.output.retainedBytes).toBe(DEFAULT_MAX_TERMINAL_BUFFER_BYTES);
expect(reset).not.toHaveBeenCalled();
expect(core.snapshot()).toEqual(reference.snapshot());
},
);
it("preserves Unicode and split ANSI parser state across batched renderer reads", async () => {
const [core, reference] = await Promise.all([createCore(), createCore()]);
let state = createSession("");
const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
writeTerminalOutputUpdate(core, first);
let cursor = first.cursor;
const reset = vi.spyOn(core, "resetAndWrite");
const inputs = [
`${"a".repeat(16_383)}🙂`,
"\x1b[3",
"1m",
"e",
"\u0301界🙂",
"\x1b[0",
"m\r\n",
"\x1b]8;;https://t3.codes\x1b",
"\\link",
"\x1b]8;;\x1b",
"\\\x1b[?1049h",
"alternate",
"\x1b[?1049l",
"\r\nend",
];
let received = "";
for (const [index, data] of inputs.entries()) {
state = append(state, data);
if (index % 3 !== 0 && index !== inputs.length - 1) continue;
const update = readTerminalOutputUpdate(state.output, cursor);
if (update.type !== "append") throw new Error(`Expected append, received ${update.type}`);
received += update.data;
writeTerminalOutputUpdate(core, update);
cursor = update.cursor;
}
reference.write(inputs.join(""));
expect(received).toBe(inputs.join(""));
expect(reset).not.toHaveBeenCalled();
expect(core.snapshot()).toEqual(reference.snapshot());
});
it("answers a live VT query when batched reads cross a chunk compaction", async () => {
const replies: string[] = [];
const core = await createCore((data) => replies.push(data));
core.write("\x1b[5n");
expect(replies).toEqual(["\x1b[0n"]);
replies.length = 0;
let state = createSession("");
const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
writeTerminalOutputUpdate(core, initial);
let cursor = initial.cursor;
for (let index = 0; index < 1000; index += 1) {
state = append(state, "x");
const update = readTerminalOutputUpdate(state.output, cursor);
writeTerminalOutputUpdate(core, update);
cursor = update.cursor;
}
for (let index = 0; index < 24; index += 1) state = append(state, "x");
state = append(state, "\x1b[5n");
const update = readTerminalOutputUpdate(state.output, cursor);
writeTerminalOutputUpdate(core, update);
expect({ type: update.type, replies }).toEqual({ type: "append", replies: ["\x1b[0n"] });
});
it("recovers a lagging renderer once from bounded output and resumes appending", async () => {
const [core, reference] = await Promise.all([createCore(), createCore()]);
let state = createSession("\x1b[31mold");
const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
writeTerminalOutputUpdate(core, initial);
const reset = vi.spyOn(core, "resetAndWrite");
const data = "line\r\n".repeat(8192);
for (let index = 0; index < 16; index += 1) state = append(state, data);
const recovery = readTerminalOutputUpdate(state.output, initial.cursor);
if (recovery.type !== "reset") throw new Error(`Expected reset, received ${recovery.type}`);
expect(new TextEncoder().encode(recovery.data).byteLength).toBe(
DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
);
writeTerminalOutputUpdate(core, recovery);
reference.resetAndWrite(recovery.data);
expect(core.snapshot()).toEqual(reference.snapshot());
state = append(state, "\r\nlatest");
const next = readTerminalOutputUpdate(state.output, recovery.cursor);
expect(next.type).toBe("append");
writeTerminalOutputUpdate(core, next);
reference.write("\r\nlatest");
expect(reset).toHaveBeenCalledTimes(1);
expect(core.snapshot()).toEqual(reference.snapshot());
});
it("replays the latest retained output when WASM arrives after several events", async () => {
const pendingCore = createCore();
let state = createSession("before");
state = append(state, "\r\nduring ");
state = append(state, "🙂 load");
const core = await pendingCore;
const first = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
writeTerminalOutputUpdate(core, first);
const reference = await createCore();
reference.resetAndWrite(terminalOutputText(state.output));
const reset = vi.spyOn(core, "resetAndWrite");
state = append(state, "\r\nafter");
const next = readTerminalOutputUpdate(state.output, first.cursor);
expect(next).toMatchObject({ type: "append", data: "\r\nafter" });
writeTerminalOutputUpdate(core, next);
reference.write("\r\nafter");
expect(reset).not.toHaveBeenCalled();
expect(core.snapshot()).toEqual(reference.snapshot());
});
it("resets real Ghostty for a repeated snapshot, clear, restart, and a fresh attach", async () => {
const [core, reference] = await Promise.all([createCore(), createCore()]);
let state = createSession("hello");
const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
writeTerminalOutputUpdate(core, initial);
let cursor = initial.cursor;
const snapshot = {
threadId: "terminal-stream-test",
terminalId: "term-1",
cwd: "/repo",
worktreePath: null,
status: "running" as const,
pid: 456,
history: "hello",
exitCode: null,
exitSignal: null,
label: "Terminal",
updatedAt: "2026-09-04T00:00:01.000Z",
};
const events = [
{ type: "snapshot", snapshot },
{ type: "cleared", threadId: snapshot.threadId, terminalId: snapshot.terminalId },
{ type: "restarted", threadId: snapshot.threadId, terminalId: snapshot.terminalId, snapshot },
] as const;
for (const event of events) {
core.write("\r\nstale local text");
state = applyTerminalAttachStreamEvent(state, event);
const update = readTerminalOutputUpdate(state.output, cursor);
expect(update.type).toBe("reset");
writeTerminalOutputUpdate(core, update);
cursor = update.cursor;
reference.resetAndWrite(event.type === "cleared" ? "" : "hello");
expect(core.snapshot()).toEqual(reference.snapshot());
}
core.write("\r\nstale local text");
state = createSession("hello");
const reattached = readTerminalOutputUpdate(state.output, cursor);
expect(reattached.type).toBe("reset");
writeTerminalOutputUpdate(core, reattached);
reference.resetAndWrite("hello");
expect(core.snapshot()).toEqual(reference.snapshot());
});
});