Skip to content

Commit 5bf240c

Browse files
committed
fix(web): terminal selection survives full-screen redraws
1 parent 680152e commit 5bf240c

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
@@ -39,7 +39,13 @@ describe("terminal selection actions", () => {
3939
});
4040

4141
it("retains visible output and selection until a replacement subscription receives its snapshot", () => {
42-
const terminal = { resetAndWrite: vi.fn(), write: vi.fn(), clearSelection: vi.fn() };
42+
const terminal = {
43+
resetAndWrite: vi.fn(),
44+
write: vi.fn(),
45+
getSelection: vi.fn(() => "selected"),
46+
getSelectionCellCount: vi.fn(() => 8),
47+
clearSelection: vi.fn(),
48+
};
4349
const snapshot = {
4450
threadId: "thread",
4551
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,4 +1,10 @@
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";
7+
import { synchronizeTerminalOutput } from "../../components/ThreadTerminalDrawer";
28

39
import { GhosttyTerminalCore, type GhosttyCell, type GhosttyRow } from "./core";
410
import {
@@ -435,6 +441,84 @@ describe("GhosttyTerminalSurface visibility", () => {
435441
},
436442
);
437443

444+
it("keeps a selection through redraws until the selected text changes", async () => {
445+
const harness = createHarness();
446+
const surface = await harness.create();
447+
let state = applyTerminalAttachStreamEvent(nextTerminalAttachSeedState(), {
448+
type: "snapshot",
449+
snapshot: {
450+
threadId: "thread",
451+
terminalId: "term-1",
452+
cwd: "/repo",
453+
worktreePath: null,
454+
status: "running",
455+
pid: 123,
456+
history: "* Working |",
457+
exitCode: null,
458+
exitSignal: null,
459+
label: "Terminal",
460+
updatedAt: "2026-10-20T00:00:00.000Z",
461+
},
462+
});
463+
let cursor = synchronizeTerminalOutput(surface, state, INITIAL_TERMINAL_OUTPUT_CURSOR);
464+
harness.flushFrame();
465+
harness.pointer("pointerdown", 5, 1);
466+
harness.pointer("pointermove", 85, 1);
467+
harness.pointer("pointerup", 85, 0);
468+
expect(surface.getSelection()).toBe("* Working |");
469+
470+
// A TUI repaints its spinner line in place, the way Claude Code redraws.
471+
const redraw = (data: string) => {
472+
state = applyTerminalAttachStreamEvent(state, {
473+
type: "output",
474+
threadId: "thread",
475+
terminalId: "term-1",
476+
data,
477+
});
478+
cursor = synchronizeTerminalOutput(surface, state, cursor);
479+
};
480+
redraw("\r\x1b[2K* Working |");
481+
expect(surface.getSelection()).toBe("* Working |");
482+
483+
redraw("\r\x1b[2K* Working /");
484+
expect(surface.getSelection()).toBe("");
485+
expect(surface.getSelectionPosition()).toBeNull();
486+
});
487+
488+
it("reports where a selection sits after output scrolls it", async () => {
489+
const harness = createHarness();
490+
const surface = await harness.create();
491+
const rows = Array.from({ length: 10 }, (_, index) => `row ${index}`);
492+
surface.write(`\x1b[?1049h\x1b[H${rows.join("\r\n")}`);
493+
harness.flushFrame();
494+
harness.pointer("pointerdown", 5, 1, {}, 0, 50);
495+
harness.pointer("pointermove", 45, 1, {}, 0, 50);
496+
harness.pointer("pointerup", 45, 0, {}, 0, 50);
497+
const text = surface.getSelection();
498+
const before = surface.getSelectionPosition();
499+
expect(text).toMatch(/^row \d$/);
500+
501+
surface.write("\r\nrow 10\r\nrow 11");
502+
expect(surface.getSelection()).toBe(text);
503+
expect(surface.getSelectionPosition()?.start.y).toBe(before!.start.y - 2);
504+
});
505+
506+
it("keeps a drag anchored to its text when output scrolls it mid-drag", async () => {
507+
const harness = createHarness();
508+
const surface = await harness.create();
509+
const rows = Array.from({ length: 10 }, (_, index) => `row ${index}`);
510+
surface.write(`\x1b[?1049h\x1b[H${rows.join("\r\n")}`);
511+
harness.flushFrame();
512+
harness.pointer("pointerdown", 5, 1, {}, 0, 50);
513+
harness.pointer("pointermove", 45, 1, {}, 0, 50);
514+
expect(surface.getSelection()).toBe("row 6");
515+
516+
// The pointer stays over the row that output scrolls "row 8" into.
517+
surface.write("\r\nrow 10\r\nrow 11");
518+
harness.pointer("pointermove", 53, 1, {}, 0, 50);
519+
expect(surface.getSelection()).toBe("row 6\nrow 7\nrow 8");
520+
});
521+
438522
it("does not activate a link replaced before pointer release", async () => {
439523
const harness = createHarness();
440524
const onLinkActivate = vi.fn();

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

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -552,7 +552,6 @@ export class GhosttyTerminalSurface {
552552
private mountHeight = 0;
553553
private selectionEnd: { x: number; y: number } | null = null;
554554
private selectionAnchorScreen: { x: number; y: number } | null = null;
555-
private selectionEndScreen: { x: number; y: number } | null = null;
556555
private selectionMode: "cell" | "word" | "line" = "cell";
557556
private selectionBase: {
558557
start: { x: number; y: number };
@@ -953,11 +952,16 @@ export class GhosttyTerminalSurface {
953952
return this.core.selectionText();
954953
}
955954

955+
/** An upper bound on the selection's size, read without formatting its text. */
956+
getSelectionCellCount(): number {
957+
const range = this.core.selectionRange();
958+
return range ? (Math.abs(range.end.y - range.start.y) + 1) * this.cols : 0;
959+
}
960+
956961
selectAll(): void {
957962
this.clearPrimedCopy();
958963
const range = this.core.selectAll();
959964
this.selectionAnchorScreen = range?.start ?? null;
960-
this.selectionEndScreen = range?.end ?? null;
961965
this.selectionEnd = range ? this.core.screenPointToViewport(range.end.x, range.end.y) : null;
962966
this.selectionMode = "cell";
963967
this.selectionBase = null;
@@ -968,15 +972,13 @@ export class GhosttyTerminalSurface {
968972
}
969973

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

982984
getSelectionEndClientRect(): { readonly right: number; readonly bottom: number } | null {
@@ -1004,7 +1006,6 @@ export class GhosttyTerminalSurface {
10041006
this.core.clearSelection();
10051007
this.selectionEnd = null;
10061008
this.selectionAnchorScreen = null;
1007-
this.selectionEndScreen = null;
10081009
this.selectionMode = "cell";
10091010
this.selectionBase = null;
10101011
this.setSelectionAutoscroll(0);
@@ -1404,15 +1405,13 @@ export class GhosttyTerminalSurface {
14041405
this.selectionBase = range.screen;
14051406
this.selectionEnd = range.viewport.end;
14061407
this.selectionAnchorScreen = range.screen.start;
1407-
this.selectionEndScreen = range.screen.end;
14081408
this.options.onSelectionChange();
14091409
} else {
14101410
this.selectionMode = "cell";
14111411
this.selectionBase = null;
14121412
this.selectionEnd = cell;
14131413
const screen = this.core.viewportPointToScreen(cell.x, cell.y);
14141414
this.selectionAnchorScreen = screen;
1415-
this.selectionEndScreen = screen;
14161415
if (screen) {
14171416
this.core.setSelection({ ...screen, tag: 2 }, { ...screen, tag: 2 });
14181417
} else {
@@ -1495,8 +1494,20 @@ export class GhosttyTerminalSurface {
14951494
};
14961495

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

0 commit comments

Comments
 (0)