Skip to content

Commit 799ef0c

Browse files
committed
fix(web): terminal selection survives full-screen redraws
1 parent 7e289ae commit 799ef0c

5 files changed

Lines changed: 190 additions & 44 deletions

File tree

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,13 @@ describe("terminal selection actions", () => {
209209
});
210210

211211
it("retains visible output and selection until a replacement subscription receives its snapshot", () => {
212-
const terminal = { resetAndWrite: vi.fn(), write: vi.fn(), clearSelection: vi.fn() };
212+
const terminal = {
213+
resetAndWrite: vi.fn(),
214+
write: vi.fn(),
215+
getSelection: vi.fn(() => "selected"),
216+
getSelectionCellCount: vi.fn(() => 8),
217+
clearSelection: vi.fn(),
218+
};
213219
const snapshot = {
214220
threadId: "thread",
215221
terminalId: "term-1",

‎apps/web/src/components/ThreadTerminalDrawer.tsx‎

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -153,15 +153,33 @@ export function writeTerminalOutputUpdate(
153153
}
154154
}
155155

156+
// Comparing the selected text costs about 100 ns per character on every output
157+
// update. 3,000 cells, about 25 rows of a 120-column terminal, keeps a densely
158+
// filled selection near 0.3 ms.
159+
const MAX_COMPARED_SELECTION_CELLS = 3_000;
160+
156161
export function synchronizeTerminalOutput(
157-
terminal: Pick<GhosttyTerminalSurface, "resetAndWrite" | "write" | "clearSelection">,
162+
terminal: Pick<
163+
GhosttyTerminalSurface,
164+
"resetAndWrite" | "write" | "getSelection" | "getSelectionCellCount" | "clearSelection"
165+
>,
158166
session: Pick<TerminalSessionState, "output" | "version">,
159167
cursor: TerminalOutputCursor,
160168
): TerminalOutputCursor {
161169
if (session.version === 0) return cursor;
162170
const update = readTerminalOutputUpdate(session.output, cursor);
171+
if (update.type === "none") return update.cursor;
172+
// Full-screen TUIs redraw unchanged cells many times a second, so a selection
173+
// only goes once the text under it changes: overwritten cells, a clear, a
174+
// reset, or rows pruned from scrollback. Ghostty's selection follows rows as
175+
// they scroll. A selection too large to compare goes on any output.
176+
const cells = terminal.getSelectionCellCount();
177+
const compared = cells <= MAX_COMPARED_SELECTION_CELLS;
178+
const selection = cells > 0 && compared ? terminal.getSelection() : "";
163179
writeTerminalOutputUpdate(terminal, update);
164-
terminal.clearSelection();
180+
if (!compared || (cells > 0 && terminal.getSelection() !== selection)) {
181+
terminal.clearSelection();
182+
}
165183
return update.cursor;
166184
}
167185

@@ -747,8 +765,12 @@ function TerminalSessionViewport({
747765
};
748766
};
749767

750-
const addSelectionToChat = (selection: TerminalContextSelection) => {
751-
handleAddTerminalContext(selection);
768+
const addSelectionToChat = (clipboardText: string) => {
769+
// Output keeps moving the selected rows while a menu is open, so take
770+
// the line numbers now, and only if the same text is still selected.
771+
const current = readSelectionAction();
772+
if (current?.clipboardText !== clipboardText) return;
773+
handleAddTerminalContext(current.selection);
752774
terminalRef.current?.clearSelection();
753775
terminalRef.current?.focus();
754776
};
@@ -825,7 +847,7 @@ function TerminalSessionViewport({
825847
switch (clicked) {
826848
case "add-to-chat":
827849
if (selectionAction && canAddSelectionToChat()) {
828-
addSelectionToChat(selectionAction.selection);
850+
addSelectionToChat(selectionAction.clipboardText);
829851
}
830852
return;
831853
case "copy":
@@ -875,7 +897,7 @@ function TerminalSessionViewport({
875897
}
876898
switch (clicked) {
877899
case "add-to-chat":
878-
if (canAddSelectionToChat()) addSelectionToChat(nextAction.selection);
900+
if (canAddSelectionToChat()) addSelectionToChat(nextAction.clipboardText);
879901
return;
880902
case "copy":
881903
await copySelection(nextAction.clipboardText, requestId);

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

Lines changed: 44 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,8 @@ export class GhosttyTerminalCore {
221221
private scratch = 0;
222222
private graphemes = 0;
223223
private graphemeCapacity = 0;
224+
private selectionBuffer = 0;
225+
private selectionCapacity = 0;
224226
private style = 0;
225227
private cellQuery = 0;
226228
private scrollbar = 0;
@@ -749,6 +751,26 @@ export class GhosttyTerminalCore {
749751
}
750752
}
751753

754+
/** Screen coordinates of Ghostty's selection, which follows its rows as output scrolls them. */
755+
selectionRange(): GhosttySelectionRange["screen"] | null {
756+
this.ensureActive();
757+
const layout = this.runtime.layout("GhosttySelection");
758+
const selection = this.runtime.alloc(layout.size);
759+
try {
760+
this.runtime.setField(selection, "GhosttySelection", "size", layout.size);
761+
if (
762+
this.runtime.call("ghostty_terminal_get", this.terminal, 31, selection) !== GHOSTTY_SUCCESS
763+
) {
764+
return null;
765+
}
766+
const start = this.pointFromGridRef(selection + layout.fields.start!.offset, 2);
767+
const end = this.pointFromGridRef(selection + layout.fields.end!.offset, 2);
768+
return start && end ? { start, end } : null;
769+
} finally {
770+
this.runtime.free(selection, layout.size);
771+
}
772+
}
773+
752774
selectWord(col: number, row: number): GhosttySelectionRange | null {
753775
return this.selectAt(
754776
"GhosttyTerminalSelectWordOptions",
@@ -882,32 +904,33 @@ export class GhosttyTerminalCore {
882904
optionsView.setUint8(9, 1);
883905
optionsView.setUint32(12, 0, true);
884906
const written = this.runtime.call("ghostty_wasm_alloc_usize");
885-
const sizeResult = this.runtime.call(
886-
"ghostty_terminal_selection_format_buf",
887-
this.terminal,
888-
options,
889-
0,
890-
0,
891-
written,
892-
);
893-
const outputSize = this.runtime.view(written, 4).getUint32(0, true);
894-
let text = "";
895-
if (sizeResult === GHOSTTY_OUT_OF_SPACE && outputSize > 0) {
896-
const output = this.runtime.alloc(outputSize);
897-
const result = this.runtime.call(
907+
// Terminal output reads the selection on every update, so format straight
908+
// into a kept buffer; a size query first would format the text twice.
909+
const format = () =>
910+
this.runtime.call(
898911
"ghostty_terminal_selection_format_buf",
899912
this.terminal,
900913
options,
901-
output,
902-
outputSize,
914+
this.selectionBuffer,
915+
this.selectionCapacity,
903916
written,
904917
);
905-
const outputLength = this.runtime.view(written, 4).getUint32(0, true);
906-
if (result === GHOSTTY_SUCCESS) {
907-
text = decoder.decode(this.runtime.bytes(output, outputLength));
908-
}
909-
this.runtime.free(output, outputSize);
918+
let result = format();
919+
const required = this.runtime.view(written, 4).getUint32(0, true);
920+
if (result === GHOSTTY_OUT_OF_SPACE && required > 0) {
921+
const capacity = Math.max(required, this.selectionCapacity * 2);
922+
// Allocate first: if it throws, the core must not keep a freed pointer.
923+
const buffer = this.runtime.alloc(capacity);
924+
if (this.selectionBuffer) this.runtime.free(this.selectionBuffer, this.selectionCapacity);
925+
this.selectionBuffer = buffer;
926+
this.selectionCapacity = capacity;
927+
result = format();
910928
}
929+
const length = this.runtime.view(written, 4).getUint32(0, true);
930+
const text =
931+
result === GHOSTTY_SUCCESS && length > 0
932+
? decoder.decode(this.runtime.bytes(this.selectionBuffer, length))
933+
: "";
911934
this.runtime.call("ghostty_wasm_free_usize", written);
912935
this.runtime.free(options, SELECTION_FORMAT_OPTIONS_SIZE);
913936
return text;
@@ -961,6 +984,7 @@ export class GhosttyTerminalCore {
961984
}
962985
if (this.scratch) this.runtime.free(this.scratch, 16);
963986
if (this.graphemes) this.runtime.free(this.graphemes, this.graphemeCapacity);
987+
if (this.selectionBuffer) this.runtime.free(this.selectionBuffer, this.selectionCapacity);
964988
for (const slot of [
965989
this.mouseEventSlot,
966990
this.mouseEncoderSlot,

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

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2+
import {
3+
applyTerminalAttachStreamEvent,
4+
INITIAL_TERMINAL_OUTPUT_CURSOR,
5+
nextTerminalAttachSeedState,
6+
} from "@t3tools/client-runtime/state/terminal";
27
import * as appearanceFonts from "../../appearanceFonts";
8+
import { synchronizeTerminalOutput } from "../../components/ThreadTerminalDrawer";
39

410
import { GhosttyTerminalCore, type GhosttyCell, type GhosttyRow } from "./core";
511
import {
@@ -902,6 +908,84 @@ describe("GhosttyTerminalSurface visibility", () => {
902908
expect(harness.renderedSnapshot.rowData[0]?.text).not.toBe(bottom);
903909
});
904910

911+
it("keeps a selection through redraws until the selected text changes", async () => {
912+
const harness = createHarness();
913+
const surface = await harness.create();
914+
let state = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
915+
type: "snapshot",
916+
snapshot: {
917+
threadId: "thread",
918+
terminalId: "term-1",
919+
cwd: "/repo",
920+
worktreePath: null,
921+
status: "running",
922+
pid: 123,
923+
history: "* Working |",
924+
exitCode: null,
925+
exitSignal: null,
926+
label: "Terminal",
927+
updatedAt: "2026-10-20T00:00:00.000Z",
928+
},
929+
});
930+
let cursor = synchronizeTerminalOutput(surface, state, INITIAL_TERMINAL_OUTPUT_CURSOR);
931+
harness.flushFrame();
932+
harness.pointer("pointerdown", 5, 1);
933+
harness.pointer("pointermove", 85, 1);
934+
harness.pointer("pointerup", 85, 0);
935+
expect(surface.getSelection()).toBe("* Working |");
936+
937+
// A TUI repaints its spinner line in place, the way Claude Code redraws.
938+
const redraw = (data: string) => {
939+
state = applyTerminalAttachStreamEvent(state, {
940+
type: "output",
941+
threadId: "thread",
942+
terminalId: "term-1",
943+
data,
944+
});
945+
cursor = synchronizeTerminalOutput(surface, state, cursor);
946+
};
947+
redraw("\r\x1b[2K* Working |");
948+
expect(surface.getSelection()).toBe("* Working |");
949+
950+
redraw("\r\x1b[2K* Working /");
951+
expect(surface.getSelection()).toBe("");
952+
expect(surface.getSelectionPosition()).toBeNull();
953+
});
954+
955+
it("reports where a selection sits after output scrolls it", async () => {
956+
const harness = createHarness();
957+
const surface = await harness.create();
958+
const rows = Array.from({ length: 10 }, (_, index) => `row ${index}`);
959+
surface.write(`\x1b[?1049h\x1b[H${rows.join("\r\n")}`);
960+
harness.flushFrame();
961+
harness.pointer("pointerdown", 5, 1, {}, 0, 50);
962+
harness.pointer("pointermove", 45, 1, {}, 0, 50);
963+
harness.pointer("pointerup", 45, 0, {}, 0, 50);
964+
const text = surface.getSelection();
965+
const before = surface.getSelectionPosition();
966+
expect(text).toMatch(/^row \d$/);
967+
968+
surface.write("\r\nrow 10\r\nrow 11");
969+
expect(surface.getSelection()).toBe(text);
970+
expect(surface.getSelectionPosition()?.start.y).toBe(before!.start.y - 2);
971+
});
972+
973+
it("keeps a drag anchored to its text when output scrolls it mid-drag", async () => {
974+
const harness = createHarness();
975+
const surface = await harness.create();
976+
const rows = Array.from({ length: 10 }, (_, index) => `row ${index}`);
977+
surface.write(`\x1b[?1049h\x1b[H${rows.join("\r\n")}`);
978+
harness.flushFrame();
979+
harness.pointer("pointerdown", 5, 1, {}, 0, 50);
980+
harness.pointer("pointermove", 45, 1, {}, 0, 50);
981+
expect(surface.getSelection()).toBe("row 6");
982+
983+
// The pointer stays over the row that output scrolls "row 8" into.
984+
surface.write("\r\nrow 10\r\nrow 11");
985+
harness.pointer("pointermove", 53, 1, {}, 0, 50);
986+
expect(surface.getSelection()).toBe("row 6\nrow 7\nrow 8");
987+
});
988+
905989
it("keeps the selection on reveal and applies a hidden selection clear", async () => {
906990
const harness = createHarness();
907991
const surface = await harness.create();

‎apps/web/src/terminal/ghostty/surface.ts‎

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -554,7 +554,6 @@ export class GhosttyTerminalSurface {
554554
private mountHeight = 0;
555555
private selectionEnd: { x: number; y: number } | null = null;
556556
private selectionAnchorScreen: { x: number; y: number } | null = null;
557-
private selectionEndScreen: { x: number; y: number } | null = null;
558557
private selectionMode: "cell" | "word" | "line" = "cell";
559558
private selectionBase: {
560559
start: { x: number; y: number };
@@ -955,11 +954,16 @@ export class GhosttyTerminalSurface {
955954
return this.core.selectionText();
956955
}
957956

957+
/** An upper bound on the selection's size, read without formatting its text. */
958+
getSelectionCellCount(): number {
959+
const range = this.core.selectionRange();
960+
return range ? (Math.abs(range.end.y - range.start.y) + 1) * this.cols : 0;
961+
}
962+
958963
selectAll(): void {
959964
this.clearPrimedCopy();
960965
const range = this.core.selectAll();
961966
this.selectionAnchorScreen = range?.start ?? null;
962-
this.selectionEndScreen = range?.end ?? null;
963967
this.selectionEnd = range ? this.core.screenPointToViewport(range.end.x, range.end.y) : null;
964968
this.selectionMode = "cell";
965969
this.selectionBase = null;
@@ -970,15 +974,13 @@ export class GhosttyTerminalSurface {
970974
}
971975

972976
getSelectionPosition(): GhosttySelectionPosition | null {
973-
if (!this.selectionAnchorScreen || !this.selectionEndScreen || !this.hasSelection())
974-
return null;
975-
const before =
976-
this.selectionAnchorScreen.y < this.selectionEndScreen.y ||
977-
(this.selectionAnchorScreen.y === this.selectionEndScreen.y &&
978-
this.selectionAnchorScreen.x <= this.selectionEndScreen.x);
979-
return before
980-
? { start: this.selectionAnchorScreen, end: this.selectionEndScreen }
981-
: { start: this.selectionEndScreen, end: this.selectionAnchorScreen };
977+
// Ask Ghostty rather than the gesture's coordinates, which go stale once
978+
// output scrolls the selected rows (alternate screen, scrollback pruning).
979+
const range = this.hasSelection() ? this.core.selectionRange() : null;
980+
if (!range) return null;
981+
const { start, end } = range;
982+
const before = start.y < end.y || (start.y === end.y && start.x <= end.x);
983+
return before ? { start, end } : { start: end, end: start };
982984
}
983985

984986
getSelectionEndClientRect(): { readonly right: number; readonly bottom: number } | null {
@@ -1006,7 +1008,6 @@ export class GhosttyTerminalSurface {
10061008
this.core.clearSelection();
10071009
this.selectionEnd = null;
10081010
this.selectionAnchorScreen = null;
1009-
this.selectionEndScreen = null;
10101011
this.selectionMode = "cell";
10111012
this.selectionBase = null;
10121013
this.setSelectionAutoscroll(0);
@@ -1406,15 +1407,13 @@ export class GhosttyTerminalSurface {
14061407
this.selectionBase = range.screen;
14071408
this.selectionEnd = range.viewport.end;
14081409
this.selectionAnchorScreen = range.screen.start;
1409-
this.selectionEndScreen = range.screen.end;
14101410
this.options.onSelectionChange();
14111411
} else {
14121412
this.selectionMode = "cell";
14131413
this.selectionBase = null;
14141414
this.selectionEnd = cell;
14151415
const screen = this.core.viewportPointToScreen(cell.x, cell.y);
14161416
this.selectionAnchorScreen = screen;
1417-
this.selectionEndScreen = screen;
14181417
if (screen) {
14191418
this.core.setSelection({ ...screen, tag: 2 }, { ...screen, tag: 2 });
14201419
} else {
@@ -1497,8 +1496,20 @@ export class GhosttyTerminalSurface {
14971496
};
14981497

14991498
private extendSelectionTo(clientX: number, clientY: number): void {
1500-
const anchorScreen = this.selectionAnchorScreen;
1501-
if (anchorScreen === null) return;
1499+
if (this.selectionAnchorScreen === null) return;
1500+
// Output can scroll the selected rows mid-drag. Ghostty keeps the selection,
1501+
// anchor first, on its rows, so the gesture's anchor and word/line base
1502+
// move with it instead of reselecting from where the rows used to be.
1503+
const anchorScreen = this.core.selectionRange()?.start;
1504+
if (!anchorScreen) return;
1505+
const rowDelta = anchorScreen.y - this.selectionAnchorScreen.y;
1506+
if (this.selectionBase && rowDelta !== 0) {
1507+
const { start, end } = this.selectionBase;
1508+
this.selectionBase = {
1509+
start: { x: start.x, y: start.y + rowDelta },
1510+
end: { x: end.x, y: end.y + rowDelta },
1511+
};
1512+
}
15021513
const cell = this.cellAt(clientX, clientY);
15031514
this.selectionMoved = true;
15041515
this.selectionEnd = cell;
@@ -1518,7 +1529,6 @@ export class GhosttyTerminalSurface {
15181529
const anchor = base === null ? anchorScreen : beforeBase ? base.end : base.start;
15191530
const end = range === null ? cellScreen : beforeBase ? range.screen.start : range.screen.end;
15201531
this.selectionAnchorScreen = anchor;
1521-
this.selectionEndScreen = end;
15221532
this.core.setSelection({ ...anchor, tag: 2 }, { ...end, tag: 2 });
15231533
this.options.onSelectionChange();
15241534
this.forceFullRender = true;

0 commit comments

Comments
 (0)