@devries-cameron20 / t3code-1 / commits / 1721f187c6
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): clearing a running terminal keeps its screen and input modes (#36380)

Julius Marminge committed Nov 13, 2026 at 12:49 UTC 1721f187c6668e5305ee1b583201edf7171db594
8 files changed +126 -16
apps/mobile/src/features/terminal/NativeTerminalSurface.test.tsx
+20 -2
@@ -1,7 +1,7 @@
1 import {
2 applyTerminalAttachStreamEvent,
3 EMPTY_TERMINAL_BUFFER_STATE,
4 - terminalOutputText,
4 + terminalOutputReplay,
5 } from "@t3tools/client-runtime/state/terminal";
6 import { act, useImperativeHandle, useLayoutEffect, type ReactNode } from "react";
7 import { createRoot } from "react-dom/client";
@@ -106,7 +106,7 @@ function setup(revision: number | null) {
106 ? null
107 : (revision ?? 0) >= 1
108 ? ""
109 - : terminalOutputText(state.output)
109 + : terminalOutputReplay(state.output)
110 }
111 isRunning
112 onInput={() => {}}
@@ -163,6 +163,24 @@ it.each([null, 1])(
163 } else {
164 expect(mocks.write).not.toHaveBeenCalled();
165 expect(mocks.initialBuffers).toEqual(["retained", "ined-new"]);
166 + // An older binary recreates its emulator unless the next buffer extends the last one.
167 + // The buffer is full here, so the erase must not push the earlier output out.
168 + let cleared = applyTerminalAttachStreamEvent(
169 + state,
170 + { type: "output", threadId: "thread", terminalId: "term-1", data: "\u001b[?1049h" },
171 + 16,
172 + );
173 + await harness.render(cleared);
174 + cleared = applyTerminalAttachStreamEvent(
175 + cleared,
176 + { type: "cleared", threadId: "thread", terminalId: "term-1" },
177 + 16,
178 + );
179 + await harness.render(cleared);
180 + expect(mocks.initialBuffers.slice(2)).toEqual([
181 + "ined-new\u001b[?1049h",
182 + "ined-new\u001b[?1049h\u001b[H\u001b[2J\u001b[3J",
183 + ]);
184 }
185 },
186 );
apps/mobile/src/features/terminal/NativeTerminalSurface.tsx
+11 -2
@@ -1,4 +1,8 @@
1 -import type { TerminalGrid, TerminalOutputState } from "@t3tools/client-runtime/state/terminal";
1 +import {
2 + terminalOutputText,
3 + type TerminalGrid,
4 + type TerminalOutputState,
5 +} from "@t3tools/client-runtime/state/terminal";
6 import { memo, useEffect, useImperativeHandle, useMemo, useRef, useState, type Ref } from "react";
7 import {
8 Pressable,
@@ -199,7 +203,12 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface({
203 });
204
205 export const TerminalSurface = memo(function TerminalSurface(props: TerminalSurfaceProps) {
202 - const buffer = useTerminalSurfaceBuffer(props);
206 + // The text fallback draws escape sequences literally, so it gets displayed text, not the replay.
207 + const buffer = useTerminalSurfaceBuffer(
208 + resolveNativeTerminalSurfaceView() || props.output === null
209 + ? props
210 + : { terminalKey: props.terminalKey, buffer: terminalOutputText(props.output) },
211 + );
212 return <ReadyTerminalSurface key={props.terminalKey} {...props} buffer={buffer} />;
213 });
214
apps/mobile/src/state/use-terminal-session.ts
+3 -3
@@ -2,7 +2,7 @@ import {
2 combineTerminalSessionState,
3 EMPTY_TERMINAL_BUFFER_STATE,
4 EMPTY_TERMINAL_SESSION_STATE,
5 - terminalOutputText,
5 + terminalOutputReplay,
6 type KnownTerminalSession,
7 type TerminalSessionState,
8 } from "@t3tools/client-runtime/state/terminal";
@@ -57,8 +57,8 @@ export function useAttachedTerminalSession(input: {
57 );
58 const output = attach.data?.output ?? EMPTY_TERMINAL_BUFFER_STATE.output;
59 const materializeBuffer = input.materializeBuffer ?? true;
60 - // Older installed binaries and the text fallback still need initialBuffer.
61 - const buffer = materializeBuffer ? terminalOutputText(output) : "";
60 + // Older installed binaries are fed this as initialBuffer; clearing it would recreate their emulator.
61 + const buffer = materializeBuffer ? terminalOutputReplay(output) : "";
62
63 return useMemo(() => {
64 if (input.environmentId === null || input.terminal === null) {
apps/web/src/components/ThreadTerminalDrawer.test.ts
+3 -1
@@ -73,8 +73,10 @@ it("retains visible output and selection until a replacement subscription receiv
73 threadId: "thread",
74 terminalId: "term-1",
75 });
76 + terminal.resetAndWrite.mockClear();
77 synchronizeTerminalOutput(terminal, cleared, observedCursor);
77 - expect(terminal.resetAndWrite).toHaveBeenLastCalledWith("");
78 + expect(terminal.resetAndWrite).not.toHaveBeenCalled();
79 + expect(terminal.write).toHaveBeenLastCalledWith("\u001b[H\u001b[2J\u001b[3J");
80 });
81
82 it("reports an attach failure that leaves the output unchanged", () => {
apps/web/src/terminal/ghostty/core.test.ts
+36 -2
@@ -369,7 +369,7 @@ describe("GhosttyTerminalCore snapshots", () => {
369 expect(core.snapshot()).toEqual(reference.snapshot());
370 });
371
372 - it("resets real Ghostty for a repeated snapshot, clear, restart, and a fresh attach", async () => {
372 + it("drops stale text in real Ghostty for a repeated snapshot, clear, restart, and a fresh attach", async () => {
373 const [core, reference] = await Promise.all([createCore(), createCore()]);
374 let state = createSession("hello");
375 const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
@@ -398,7 +398,7 @@ describe("GhosttyTerminalCore snapshots", () => {
398 core.write("\r\nstale local text");
399 state = applyTerminalAttachStreamEvent(state, event);
400 const update = readTerminalOutputUpdate(state.output, cursor);
401 - expect(update.type).toBe("reset");
401 + expect(update.type).toBe(event.type === "cleared" ? "append" : "reset");
402 writeTerminalOutputUpdate(core, update);
403 cursor = update.cursor;
404 reference.resetAndWrite(event.type === "cleared" ? "" : "hello");
@@ -413,6 +413,40 @@ describe("GhosttyTerminalCore snapshots", () => {
413 reference.resetAndWrite("hello");
414 expect(core.snapshot()).toEqual(reference.snapshot());
415 });
416 +
417 + it("keeps a running program's screen and input modes when its history is cleared", async () => {
418 + const replies: string[] = [];
419 + const core = await createCore((data) => replies.push(data));
420 + const modes = () => {
421 + replies.length = 0;
422 + core.write("\x1b[?u");
423 + return {
424 + alternateScreen: core.isAlternateScreen(),
425 + applicationCursorKeys: core.isApplicationCursorKeys(),
426 + mouseTracking: core.isMouseTracking(),
427 + kittyFlags: replies.join(""),
428 + };
429 + };
430 + let state = createSession("\x1b[?1049h\x1b[>7u\x1b[?1;1000;1006h");
431 + const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
432 + writeTerminalOutputUpdate(core, initial);
433 + const live = modes();
434 + expect(live).toEqual({
435 + alternateScreen: true,
436 + applicationCursorKeys: true,
437 + mouseTracking: true,
438 + kittyFlags: "\x1b[?7u",
439 + });
440 +
441 + state = applyTerminalAttachStreamEvent(state, {
442 + type: "cleared",
443 + threadId: "terminal-stream-test",
444 + terminalId: "term-1",
445 + });
446 + writeTerminalOutputUpdate(core, readTerminalOutputUpdate(state.output, initial.cursor));
447 +
448 + expect(modes()).toEqual(live);
449 + });
450 });
451
452 describe("GhosttyTerminalCore scrollback", () => {
packages/client-runtime/src/state/terminalOutput.ts
+34 -3
@@ -12,6 +12,8 @@ export interface TerminalOutputState {
12 readonly retainedBytes: number;
13 readonly resetVersion: number;
14 readonly nextOffset: number;
15 + /** Chunks before this offset are replayed to emulators but are no longer displayed text. */
16 + readonly textStartOffset: number;
17 }
18
19 export interface TerminalOutputCursor {
@@ -54,6 +56,7 @@ export const EMPTY_TERMINAL_OUTPUT_STATE = Object.freeze<TerminalOutputState>({
56 retainedBytes: 0,
57 resetVersion: 0,
58 nextOffset: 0,
59 + textStartOffset: 0,
60 });
61
62 interface Utf8Chunk {
@@ -175,6 +178,7 @@ function appendOutput(
178 retainedBytes: 0,
179 resetVersion: current.resetVersion + 1,
180 nextOffset: current.nextOffset + data.length,
181 + textStartOffset: current.textStartOffset,
182 };
183 }
184 const appended = splitOutputChunks(
@@ -221,6 +225,7 @@ function appendOutput(
225 retainedBytes,
226 resetVersion: current.resetVersion,
227 nextOffset: appended.nextOffset,
228 + textStartOffset: current.textStartOffset,
229 };
230 }
231
@@ -241,13 +246,39 @@ function resetOutput(
246 retainedBytes: reset.byteLength,
247 resetVersion: current.resetVersion + 1,
248 nextOffset: reset.nextOffset,
249 + textStartOffset: 0,
250 };
251 }
252
247 -export function terminalOutputText(output: TerminalOutputState): string {
253 +// Erases the screen and scrollback only. A full emulator reset would drop the
254 +// screen and input modes the still-running program negotiated.
255 +const CLEAR_TERMINAL_TEXT = "\u001b[H\u001b[2J\u001b[3J";
256 +
257 +/** Earlier output stays retained so a replay from the start restores those modes. */
258 +function clearOutput(current: TerminalOutputState, maxBufferBytes: number): TerminalOutputState {
259 + // The erase rides over the budget: trimming here would evict the output that set those modes.
260 + const cleared = appendOutput(
261 + current,
262 + CLEAR_TERMINAL_TEXT,
263 + maxBufferBytes <= 0
264 + ? maxBufferBytes
265 + : Math.max(maxBufferBytes, current.retainedBytes + CLEAR_TERMINAL_TEXT.length),
266 + );
267 + return { ...cleared, textStartOffset: cleared.nextOffset };
268 +}
269 +
270 +/** Everything retained, for an emulator that is fed the whole history. */
271 +export function terminalOutputReplay(output: TerminalOutputState): string {
272 return output.chunks.map((chunk) => chunk.data).join("");
273 }
274
275 +/** The output as plain text, for surfaces that do not interpret escape sequences. */
276 +export function terminalOutputText(output: TerminalOutputState): string {
277 + return output.chunks
278 + .map((chunk) => chunk.data.slice(Math.max(0, output.textStartOffset - chunk.startOffset)))
279 + .join("");
280 +}
281 +
282 export function readTerminalOutputUpdate(
283 output: TerminalOutputState,
284 cursor: TerminalOutputCursor,
@@ -263,7 +294,7 @@ export function readTerminalOutputUpdate(
294 cursor.resetVersion !== output.resetVersion ||
295 cursor.offset < (firstChunk?.startOffset ?? output.nextOffset)
296 ) {
266 - return { type: "reset", data: terminalOutputText(output), cursor: nextCursor };
297 + return { type: "reset", data: terminalOutputReplay(output), cursor: nextCursor };
298 }
299
300 // Appends and compaction preserve offset order, so unread chunks form a suffix.
@@ -286,4 +317,4 @@ export function readTerminalOutputUpdate(
317 };
318 }
319
289 -export { appendOutput, resetOutput };
320 +export { appendOutput, clearOutput, resetOutput };
packages/client-runtime/src/state/terminalSession.test.ts
+16 -2
@@ -252,7 +252,7 @@ describe("terminal session reducers", () => {
252 expect(state.output.retainedBytes).toBe(8);
253 });
254
255 - it("resets for repeated snapshots, clear, and restart even when output text repeats", () => {
255 + it("resets for repeated snapshots and restart even when output text repeats, and erases on clear", () => {
256 let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
257 type: "snapshot",
258 snapshot: BASE_SNAPSHOT,
@@ -273,8 +273,22 @@ describe("terminal session reducers", () => {
273 threadId: TARGET.threadId,
274 terminalId: TARGET.terminalId,
275 });
276 + // Clear erases text in place: a full reset would drop the running program's modes.
277 + const erase = "\u001b[H\u001b[2J\u001b[3J";
278 const cleared = readTerminalOutputUpdate(state.output, cursor);
277 - expect(cleared).toMatchObject({ type: "reset", data: "" });
279 + expect(cleared).toMatchObject({ type: "append", data: erase });
280 + expect(readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR)).toMatchObject({
281 + type: "reset",
282 + data: `hello${erase}`,
283 + });
284 + expect(terminalOutputText(state.output)).toBe("");
285 + const afterClear = applyTerminalAttachStreamEvent(state, {
286 + type: "output",
287 + threadId: TARGET.threadId,
288 + terminalId: TARGET.terminalId,
289 + data: "next",
290 + });
291 + expect(terminalOutputText(afterClear.output)).toBe("next");
292 state = applyTerminalAttachStreamEvent(state, {
293 type: "restarted",
294 threadId: TARGET.threadId,
packages/client-runtime/src/state/terminalSession.ts
+3 -1
@@ -9,6 +9,7 @@ import type {
9 import { DEFAULT_MAX_TERMINAL_BUFFER_BYTES } from "@t3tools/contracts";
10 import {
11 appendOutput,
12 + clearOutput,
13 EMPTY_TERMINAL_OUTPUT_STATE,
14 resetOutput,
15 type TerminalOutputState,
@@ -17,6 +18,7 @@ import {
18 export {
19 INITIAL_TERMINAL_OUTPUT_CURSOR,
20 readTerminalOutputUpdate,
21 + terminalOutputReplay,
22 terminalOutputText,
23 type TerminalOutputCursor,
24 type TerminalOutputState,
@@ -193,7 +195,7 @@ export function applyTerminalAttachStreamEvent(
195 case "cleared":
196 return {
197 ...current,
196 - output: resetOutput(current.output, "", maxBufferBytes),
198 + output: clearOutput(current.output, maxBufferBytes),
199 error: null,
200 version: current.version + 1,
201 };