Skip to content

Commit 1721f18

Browse files
fix(web): clearing a running terminal keeps its screen and input modes (#36380)
1 parent cfc71e1 commit 1721f18

8 files changed

Lines changed: 126 additions & 16 deletions

File tree

‎apps/mobile/src/features/terminal/NativeTerminalSurface.test.tsx‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import {
22
applyTerminalAttachStreamEvent,
33
EMPTY_TERMINAL_BUFFER_STATE,
4-
terminalOutputText,
4+
terminalOutputReplay,
55
} from "@t3tools/client-runtime/state/terminal";
66
import { act, useImperativeHandle, useLayoutEffect, type ReactNode } from "react";
77
import { createRoot } from "react-dom/client";
@@ -106,7 +106,7 @@ function setup(revision: number | null) {
106106
? null
107107
: (revision ?? 0) >= 1
108108
? ""
109-
: terminalOutputText(state.output)
109+
: terminalOutputReplay(state.output)
110110
}
111111
isRunning
112112
onInput={() => {}}
@@ -163,6 +163,24 @@ it.each([null, 1])(
163163
} else {
164164
expect(mocks.write).not.toHaveBeenCalled();
165165
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+
]);
166184
}
167185
},
168186
);

‎apps/mobile/src/features/terminal/NativeTerminalSurface.tsx‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -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";
26
import { memo, useEffect, useImperativeHandle, useMemo, useRef, useState, type Ref } from "react";
37
import {
48
Pressable,
@@ -199,7 +203,12 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface({
199203
});
200204

201205
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+
);
203212
return <ReadyTerminalSurface key={props.terminalKey} {...props} buffer={buffer} />;
204213
});
205214

‎apps/mobile/src/state/use-terminal-session.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import {
22
combineTerminalSessionState,
33
EMPTY_TERMINAL_BUFFER_STATE,
44
EMPTY_TERMINAL_SESSION_STATE,
5-
terminalOutputText,
5+
terminalOutputReplay,
66
type KnownTerminalSession,
77
type TerminalSessionState,
88
} from "@t3tools/client-runtime/state/terminal";
@@ -57,8 +57,8 @@ export function useAttachedTerminalSession(input: {
5757
);
5858
const output = attach.data?.output ?? EMPTY_TERMINAL_BUFFER_STATE.output;
5959
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) : "";
6262

6363
return useMemo(() => {
6464
if (input.environmentId === null || input.terminal === null) {

‎apps/web/src/components/ThreadTerminalDrawer.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,10 @@ it("retains visible output and selection until a replacement subscription receiv
7373
threadId: "thread",
7474
terminalId: "term-1",
7575
});
76+
terminal.resetAndWrite.mockClear();
7677
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");
7880
});
7981

8082
it("reports an attach failure that leaves the output unchanged", () => {

‎apps/web/src/terminal/ghostty/core.test.ts‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,7 @@ describe("GhosttyTerminalCore snapshots", () => {
369369
expect(core.snapshot()).toEqual(reference.snapshot());
370370
});
371371

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 () => {
373373
const [core, reference] = await Promise.all([createCore(), createCore()]);
374374
let state = createSession("hello");
375375
const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
@@ -398,7 +398,7 @@ describe("GhosttyTerminalCore snapshots", () => {
398398
core.write("\r\nstale local text");
399399
state = applyTerminalAttachStreamEvent(state, event);
400400
const update = readTerminalOutputUpdate(state.output, cursor);
401-
expect(update.type).toBe("reset");
401+
expect(update.type).toBe(event.type === "cleared" ? "append" : "reset");
402402
writeTerminalOutputUpdate(core, update);
403403
cursor = update.cursor;
404404
reference.resetAndWrite(event.type === "cleared" ? "" : "hello");
@@ -413,6 +413,40 @@ describe("GhosttyTerminalCore snapshots", () => {
413413
reference.resetAndWrite("hello");
414414
expect(core.snapshot()).toEqual(reference.snapshot());
415415
});
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+
});
416450
});
417451

418452
describe("GhosttyTerminalCore scrollback", () => {

‎packages/client-runtime/src/state/terminalOutput.ts‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ export interface TerminalOutputState {
1212
readonly retainedBytes: number;
1313
readonly resetVersion: number;
1414
readonly nextOffset: number;
15+
/** Chunks before this offset are replayed to emulators but are no longer displayed text. */
16+
readonly textStartOffset: number;
1517
}
1618

1719
export interface TerminalOutputCursor {
@@ -54,6 +56,7 @@ export const EMPTY_TERMINAL_OUTPUT_STATE = Object.freeze<TerminalOutputState>({
5456
retainedBytes: 0,
5557
resetVersion: 0,
5658
nextOffset: 0,
59+
textStartOffset: 0,
5760
});
5861

5962
interface Utf8Chunk {
@@ -175,6 +178,7 @@ function appendOutput(
175178
retainedBytes: 0,
176179
resetVersion: current.resetVersion + 1,
177180
nextOffset: current.nextOffset + data.length,
181+
textStartOffset: current.textStartOffset,
178182
};
179183
}
180184
const appended = splitOutputChunks(
@@ -221,6 +225,7 @@ function appendOutput(
221225
retainedBytes,
222226
resetVersion: current.resetVersion,
223227
nextOffset: appended.nextOffset,
228+
textStartOffset: current.textStartOffset,
224229
};
225230
}
226231

@@ -241,13 +246,39 @@ function resetOutput(
241246
retainedBytes: reset.byteLength,
242247
resetVersion: current.resetVersion + 1,
243248
nextOffset: reset.nextOffset,
249+
textStartOffset: 0,
244250
};
245251
}
246252

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 {
248272
return output.chunks.map((chunk) => chunk.data).join("");
249273
}
250274

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+
251282
export function readTerminalOutputUpdate(
252283
output: TerminalOutputState,
253284
cursor: TerminalOutputCursor,
@@ -263,7 +294,7 @@ export function readTerminalOutputUpdate(
263294
cursor.resetVersion !== output.resetVersion ||
264295
cursor.offset < (firstChunk?.startOffset ?? output.nextOffset)
265296
) {
266-
return { type: "reset", data: terminalOutputText(output), cursor: nextCursor };
297+
return { type: "reset", data: terminalOutputReplay(output), cursor: nextCursor };
267298
}
268299

269300
// Appends and compaction preserve offset order, so unread chunks form a suffix.
@@ -286,4 +317,4 @@ export function readTerminalOutputUpdate(
286317
};
287318
}
288319

289-
export { appendOutput, resetOutput };
320+
export { appendOutput, clearOutput, resetOutput };

‎packages/client-runtime/src/state/terminalSession.test.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ describe("terminal session reducers", () => {
252252
expect(state.output.retainedBytes).toBe(8);
253253
});
254254

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", () => {
256256
let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
257257
type: "snapshot",
258258
snapshot: BASE_SNAPSHOT,
@@ -273,8 +273,22 @@ describe("terminal session reducers", () => {
273273
threadId: TARGET.threadId,
274274
terminalId: TARGET.terminalId,
275275
});
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";
276278
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");
278292
state = applyTerminalAttachStreamEvent(state, {
279293
type: "restarted",
280294
threadId: TARGET.threadId,

‎packages/client-runtime/src/state/terminalSession.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import type {
99
import { DEFAULT_MAX_TERMINAL_BUFFER_BYTES } from "@t3tools/contracts";
1010
import {
1111
appendOutput,
12+
clearOutput,
1213
EMPTY_TERMINAL_OUTPUT_STATE,
1314
resetOutput,
1415
type TerminalOutputState,
@@ -17,6 +18,7 @@ import {
1718
export {
1819
INITIAL_TERMINAL_OUTPUT_CURSOR,
1920
readTerminalOutputUpdate,
21+
terminalOutputReplay,
2022
terminalOutputText,
2123
type TerminalOutputCursor,
2224
type TerminalOutputState,
@@ -193,7 +195,7 @@ export function applyTerminalAttachStreamEvent(
193195
case "cleared":
194196
return {
195197
...current,
196-
output: resetOutput(current.output, "", maxBufferBytes),
198+
output: clearOutput(current.output, maxBufferBytes),
197199
error: null,
198200
version: current.version + 1,
199201
};

0 commit comments

Comments
 (0)