Skip to content

Commit 97dbfd7

Browse files
fix(web): preserve terminal selections across unchanged redraws (#25030)
Co-authored-by: Dara Adedeji <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent 49f51e1 commit 97dbfd7

5 files changed

Lines changed: 169 additions & 26 deletions

File tree

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

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,13 @@ describe("terminal selection actions", () => {
4040
});
4141

4242
it("retains visible output and selection until a replacement subscription receives its snapshot", () => {
43-
const terminal = { resetAndWrite: vi.fn(), write: vi.fn(), clearSelection: vi.fn() };
43+
const terminal = {
44+
resetAndWrite: vi.fn(),
45+
write: vi.fn(),
46+
getSelection: vi.fn(() => "selected"),
47+
getSelectionCellCount: vi.fn(() => 8),
48+
clearSelection: vi.fn(),
49+
};
4450
const snapshot = {
4551
threadId: "thread",
4652
terminalId: "term-1",
@@ -90,7 +96,13 @@ it("retains visible output and selection until a replacement subscription receiv
9096
});
9197

9298
it("reports an attach failure that leaves the output unchanged", () => {
93-
const terminal = { resetAndWrite: vi.fn(), write: vi.fn(), clearSelection: vi.fn() };
99+
const terminal = {
100+
resetAndWrite: vi.fn(),
101+
write: vi.fn(),
102+
getSelection: vi.fn(() => "selected"),
103+
getSelectionCellCount: vi.fn(() => 8),
104+
clearSelection: vi.fn(),
105+
};
94106
const previous = { ...EMPTY_TERMINAL_BUFFER_STATE, error: null };
95107
const failed = { ...previous, error: "Terminal attach failed" };
96108

@@ -99,5 +111,7 @@ it("reports an attach failure that leaves the output unchanged", () => {
99111
).toBe(INITIAL_TERMINAL_OUTPUT_CURSOR);
100112
expect(terminal.write).toHaveBeenCalledWith("\r\n[terminal] Terminal attach failed\r\n");
101113
expect(terminal.resetAndWrite).not.toHaveBeenCalled();
114+
expect(terminal.getSelection).not.toHaveBeenCalled();
115+
expect(terminal.getSelectionCellCount).not.toHaveBeenCalled();
102116
expect(terminal.clearSelection).not.toHaveBeenCalled();
103117
});

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

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -165,21 +165,33 @@ export function writeTerminalOutputUpdate(
165165
}
166166
}
167167

168+
// Avoid formatting unbounded scrollback selections on every output update.
169+
const MAX_COMPARED_SELECTION_CELLS = 3_000;
170+
168171
export function synchronizeTerminalOutput(
169-
terminal: Pick<GhosttyTerminalSurface, "resetAndWrite" | "write" | "clearSelection">,
172+
terminal: Pick<
173+
GhosttyTerminalSurface,
174+
"resetAndWrite" | "write" | "getSelection" | "getSelectionCellCount" | "clearSelection"
175+
>,
170176
session: Pick<TerminalSessionState, "output" | "version">,
171177
cursor: TerminalOutputCursor,
172178
): TerminalOutputCursor {
173179
if (session.version === 0) return cursor;
174180
const update = readTerminalOutputUpdate(session.output, cursor);
181+
if (update.type === "none") return update.cursor;
182+
const cells = terminal.getSelectionCellCount();
183+
const compared = cells <= MAX_COMPARED_SELECTION_CELLS;
184+
const selection = cells > 0 && compared ? terminal.getSelection() : "";
175185
writeTerminalOutputUpdate(terminal, update);
176-
terminal.clearSelection();
186+
if (!compared || (cells > 0 && terminal.getSelection() !== selection)) {
187+
terminal.clearSelection();
188+
}
177189
return update.cursor;
178190
}
179191

180192
/** Writes what changed between two session notifications: new output, then a new error. */
181193
export function synchronizeTerminalSession(
182-
terminal: Pick<GhosttyTerminalSurface, "resetAndWrite" | "write" | "clearSelection">,
194+
terminal: Parameters<typeof synchronizeTerminalOutput>[0],
183195
previous: Pick<TerminalSessionState, "output" | "version" | "error">,
184196
session: Pick<TerminalSessionState, "output" | "version" | "error">,
185197
cursor: TerminalOutputCursor,
@@ -790,8 +802,12 @@ function TerminalSessionViewport({
790802
};
791803
};
792804

793-
const addSelectionToChat = (selection: TerminalContextSelection) => {
794-
handleAddTerminalContext(selection);
805+
const addSelectionToChat = (clipboardText: string) => {
806+
// Output keeps moving the selected rows while a menu is open, so take
807+
// the line numbers now, and only if the same text is still selected.
808+
const current = readSelectionAction();
809+
if (current?.clipboardText !== clipboardText) return;
810+
handleAddTerminalContext(current.selection);
795811
terminalRef.current?.clearSelection();
796812
terminalRef.current?.focus();
797813
};
@@ -864,7 +880,7 @@ function TerminalSessionViewport({
864880
switch (clicked) {
865881
case "add-to-chat":
866882
if (selectionAction && canAddSelectionToChat()) {
867-
addSelectionToChat(selectionAction.selection);
883+
addSelectionToChat(selectionAction.clipboardText);
868884
}
869885
return;
870886
case "copy":
@@ -914,7 +930,7 @@ function TerminalSessionViewport({
914930
}
915931
switch (clicked) {
916932
case "add-to-chat":
917-
if (canAddSelectionToChat()) addSelectionToChat(nextAction.selection);
933+
if (canAddSelectionToChat()) addSelectionToChat(nextAction.clipboardText);
918934
return;
919935
case "copy":
920936
await copySelection(nextAction.clipboardText, requestId);

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -736,6 +736,25 @@ export class GhosttyTerminalCore {
736736
}
737737
}
738738

739+
selectionRange(): GhosttySelectionRange["screen"] | null {
740+
this.ensureActive();
741+
const layout = this.runtime.layout("GhosttySelection");
742+
const selection = this.runtime.alloc(layout.size);
743+
try {
744+
this.runtime.setField(selection, "GhosttySelection", "size", layout.size);
745+
if (
746+
this.runtime.call("ghostty_terminal_get", this.terminal, 31, selection) !== GHOSTTY_SUCCESS
747+
) {
748+
return null;
749+
}
750+
const start = this.pointFromGridRef(selection + layout.fields.start!.offset, 2);
751+
const end = this.pointFromGridRef(selection + layout.fields.end!.offset, 2);
752+
return start && end ? { start, end } : null;
753+
} finally {
754+
this.runtime.free(selection, layout.size);
755+
}
756+
}
757+
739758
selectWord(col: number, row: number): GhosttySelectionRange | null {
740759
return this.selectAt(
741760
"GhosttyTerminalSelectWordOptions",

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

Lines changed: 86 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 { synchronizeTerminalSession } from "../../components/ThreadTerminalDrawer";
28

39
import { GhosttyTerminalCore, type GhosttyCell, type GhosttyRow } from "./core";
410
import {
@@ -436,6 +442,86 @@ describe("GhosttyTerminalSurface visibility", () => {
436442
},
437443
);
438444

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

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

Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -573,7 +573,6 @@ export class GhosttyTerminalSurface {
573573
private mountHeight = 0;
574574
private selectionEnd: { x: number; y: number } | null = null;
575575
private selectionAnchorScreen: { x: number; y: number } | null = null;
576-
private selectionEndScreen: { x: number; y: number } | null = null;
577576
private selectionMode: "cell" | "word" | "line" = "cell";
578577
private selectionBase: {
579578
start: { x: number; y: number };
@@ -985,11 +984,16 @@ export class GhosttyTerminalSurface {
985984
return this.core.selectionText();
986985
}
987986

987+
/** An upper bound on the selection's size, read without formatting its text. */
988+
getSelectionCellCount(): number {
989+
const range = this.core.selectionRange();
990+
return range ? (Math.abs(range.end.y - range.start.y) + 1) * this.cols : 0;
991+
}
992+
988993
selectAll(): void {
989994
this.clearPrimedCopy();
990995
const range = this.core.selectAll();
991996
this.selectionAnchorScreen = range?.start ?? null;
992-
this.selectionEndScreen = range?.end ?? null;
993997
this.selectionEnd = range ? this.core.screenPointToViewport(range.end.x, range.end.y) : null;
994998
this.selectionMode = "cell";
995999
this.selectionBase = null;
@@ -1000,15 +1004,13 @@ export class GhosttyTerminalSurface {
10001004
}
10011005

10021006
getSelectionPosition(): GhosttySelectionPosition | null {
1003-
if (!this.selectionAnchorScreen || !this.selectionEndScreen || !this.hasSelection())
1004-
return null;
1005-
const before =
1006-
this.selectionAnchorScreen.y < this.selectionEndScreen.y ||
1007-
(this.selectionAnchorScreen.y === this.selectionEndScreen.y &&
1008-
this.selectionAnchorScreen.x <= this.selectionEndScreen.x);
1009-
return before
1010-
? { start: this.selectionAnchorScreen, end: this.selectionEndScreen }
1011-
: { start: this.selectionEndScreen, end: this.selectionAnchorScreen };
1007+
// Ask Ghostty rather than the gesture's coordinates, which go stale once
1008+
// output scrolls the selected rows (alternate screen, scrollback pruning).
1009+
const range = this.hasSelection() ? this.core.selectionRange() : null;
1010+
if (!range) return null;
1011+
const { start, end } = range;
1012+
const before = start.y < end.y || (start.y === end.y && start.x <= end.x);
1013+
return before ? { start, end } : { start: end, end: start };
10121014
}
10131015

10141016
getSelectionEndClientRect(): { readonly right: number; readonly bottom: number } | null {
@@ -1036,7 +1038,6 @@ export class GhosttyTerminalSurface {
10361038
this.core.clearSelection();
10371039
this.selectionEnd = null;
10381040
this.selectionAnchorScreen = null;
1039-
this.selectionEndScreen = null;
10401041
this.selectionMode = "cell";
10411042
this.selectionBase = null;
10421043
this.setSelectionAutoscroll(0);
@@ -1421,15 +1422,13 @@ export class GhosttyTerminalSurface {
14211422
this.selectionBase = range.screen;
14221423
this.selectionEnd = range.viewport.end;
14231424
this.selectionAnchorScreen = range.screen.start;
1424-
this.selectionEndScreen = range.screen.end;
14251425
this.options.onSelectionChange();
14261426
} else {
14271427
this.selectionMode = "cell";
14281428
this.selectionBase = null;
14291429
this.selectionEnd = cell;
14301430
const screen = this.core.viewportPointToScreen(cell.x, cell.y);
14311431
this.selectionAnchorScreen = screen;
1432-
this.selectionEndScreen = screen;
14331432
if (screen) {
14341433
this.core.setSelection({ ...screen, tag: 2 }, { ...screen, tag: 2 });
14351434
} else {
@@ -1511,8 +1510,18 @@ export class GhosttyTerminalSurface {
15111510
};
15121511

15131512
private extendSelectionTo(clientX: number, clientY: number): void {
1514-
const anchorScreen = this.selectionAnchorScreen;
1515-
if (anchorScreen === null) return;
1513+
if (this.selectionAnchorScreen === null) return;
1514+
// Ghostty moves its selection with output; keep the drag on those rows too.
1515+
const anchorScreen = this.core.selectionRange()?.start;
1516+
if (!anchorScreen) return;
1517+
const rowDelta = anchorScreen.y - this.selectionAnchorScreen.y;
1518+
if (this.selectionBase && rowDelta !== 0) {
1519+
const { start, end } = this.selectionBase;
1520+
this.selectionBase = {
1521+
start: { x: start.x, y: start.y + rowDelta },
1522+
end: { x: end.x, y: end.y + rowDelta },
1523+
};
1524+
}
15161525
const cell = this.cellAt(clientX, clientY);
15171526
this.selectionMoved = true;
15181527
this.selectionEnd = cell;
@@ -1532,7 +1541,6 @@ export class GhosttyTerminalSurface {
15321541
const anchor = base === null ? anchorScreen : beforeBase ? base.end : base.start;
15331542
const end = range === null ? cellScreen : beforeBase ? range.screen.start : range.screen.end;
15341543
this.selectionAnchorScreen = anchor;
1535-
this.selectionEndScreen = end;
15361544
this.core.setSelection({ ...anchor, tag: 2 }, { ...end, tag: 2 });
15371545
this.options.onSelectionChange();
15381546
this.forceFullRender = true;

0 commit comments

Comments
 (0)