The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 10:45 UTC
fix(web): preserve terminal selections across unchanged redraws (#25030)
Co-authored-by: Dara Adedeji <76637177+SunkenInTime@users.noreply.github.com> Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com>
maria committed
Oct 30, 2026 at 21:10 UTC
97dbfd72d4444317f976d9d60b56eca0aec38530
5 files changed
+169
-26
apps/web/src/components/ThreadTerminalDrawer.test.ts
+16
-2
@@ -40,7 +40,13 @@ describe("terminal selection actions", () => {
40
});
41
42
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
+ };
50
const snapshot = {
51
threadId: "thread",
52
terminalId: "term-1",
@@ -90,7 +96,13 @@ it("retains visible output and selection until a replacement subscription receiv
96
});
97
98
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
+ };
106
const previous = { ...EMPTY_TERMINAL_BUFFER_STATE, error: null };
107
const failed = { ...previous, error: "Terminal attach failed" };
108
@@ -99,5 +111,7 @@ it("reports an attach failure that leaves the output unchanged", () => {
111
).toBe(INITIAL_TERMINAL_OUTPUT_CURSOR);
112
expect(terminal.write).toHaveBeenCalledWith("\r\n[terminal] Terminal attach failed\r\n");
113
expect(terminal.resetAndWrite).not.toHaveBeenCalled();
114
+ expect(terminal.getSelection).not.toHaveBeenCalled();
115
+ expect(terminal.getSelectionCellCount).not.toHaveBeenCalled();
116
expect(terminal.clearSelection).not.toHaveBeenCalled();
117
});
apps/web/src/components/ThreadTerminalDrawer.tsx
+23
-7
@@ -165,21 +165,33 @@ export function writeTerminalOutputUpdate(
165
}
166
}
167
168
+// Avoid formatting unbounded scrollback selections on every output update.
169
+const MAX_COMPARED_SELECTION_CELLS = 3_000;
170
+
171
export function synchronizeTerminalOutput(
169
- terminal: Pick<GhosttyTerminalSurface, "resetAndWrite" | "write" | "clearSelection">,
172
+ terminal: Pick<
173
+ GhosttyTerminalSurface,
174
+ "resetAndWrite" | "write" | "getSelection" | "getSelectionCellCount" | "clearSelection"
175
+ >,
176
session: Pick<TerminalSessionState, "output" | "version">,
177
cursor: TerminalOutputCursor,
178
): TerminalOutputCursor {
179
if (session.version === 0) return cursor;
180
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() : "";
185
writeTerminalOutputUpdate(terminal, update);
176
- terminal.clearSelection();
186
+ if (!compared || (cells > 0 && terminal.getSelection() !== selection)) {
187
+ terminal.clearSelection();
188
+ }
189
return update.cursor;
190
}
191
192
/** Writes what changed between two session notifications: new output, then a new error. */
193
export function synchronizeTerminalSession(
182
- terminal: Pick<GhosttyTerminalSurface, "resetAndWrite" | "write" | "clearSelection">,
194
+ terminal: Parameters<typeof synchronizeTerminalOutput>[0],
195
previous: Pick<TerminalSessionState, "output" | "version" | "error">,
196
session: Pick<TerminalSessionState, "output" | "version" | "error">,
197
cursor: TerminalOutputCursor,
@@ -790,8 +802,12 @@ function TerminalSessionViewport({
802
};
803
};
804
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);
811
terminalRef.current?.clearSelection();
812
terminalRef.current?.focus();
813
};
@@ -864,7 +880,7 @@ function TerminalSessionViewport({
880
switch (clicked) {
881
case "add-to-chat":
882
if (selectionAction && canAddSelectionToChat()) {
867
- addSelectionToChat(selectionAction.selection);
883
+ addSelectionToChat(selectionAction.clipboardText);
884
}
885
return;
886
case "copy":
@@ -914,7 +930,7 @@ function TerminalSessionViewport({
930
}
931
switch (clicked) {
932
case "add-to-chat":
917
- if (canAddSelectionToChat()) addSelectionToChat(nextAction.selection);
933
+ if (canAddSelectionToChat()) addSelectionToChat(nextAction.clipboardText);
934
return;
935
case "copy":
936
await copySelection(nextAction.clipboardText, requestId);
apps/web/src/terminal/ghostty/core.ts
+19
@@ -736,6 +736,25 @@ export class GhosttyTerminalCore {
736
}
737
}
738
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
+
758
selectWord(col: number, row: number): GhosttySelectionRange | null {
759
return this.selectAt(
760
"GhosttyTerminalSelectWordOptions",
apps/web/src/terminal/ghostty/surface.test.ts
+86
@@ -1,4 +1,10 @@
1
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";
8
9
import { GhosttyTerminalCore, type GhosttyCell, type GhosttyRow } from "./core";
10
import {
@@ -436,6 +442,86 @@ describe("GhosttyTerminalSurface visibility", () => {
442
},
443
);
444
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
+
525
it("does not activate a link replaced before pointer release", async () => {
526
const harness = createHarness();
527
const onLinkActivate = vi.fn();
apps/web/src/terminal/ghostty/surface.ts
+25
-17
@@ -573,7 +573,6 @@ export class GhosttyTerminalSurface {
573
private mountHeight = 0;
574
private selectionEnd: { x: number; y: number } | null = null;
575
private selectionAnchorScreen: { x: number; y: number } | null = null;
576
- private selectionEndScreen: { x: number; y: number } | null = null;
576
private selectionMode: "cell" | "word" | "line" = "cell";
577
private selectionBase: {
578
start: { x: number; y: number };
@@ -985,11 +984,16 @@ export class GhosttyTerminalSurface {
984
return this.core.selectionText();
985
}
986
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
+
993
selectAll(): void {
994
this.clearPrimedCopy();
995
const range = this.core.selectAll();
996
this.selectionAnchorScreen = range?.start ?? null;
992
- this.selectionEndScreen = range?.end ?? null;
997
this.selectionEnd = range ? this.core.screenPointToViewport(range.end.x, range.end.y) : null;
998
this.selectionMode = "cell";
999
this.selectionBase = null;
@@ -1000,15 +1004,13 @@ export class GhosttyTerminalSurface {
1004
}
1005
1006
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 };
1014
}
1015
1016
getSelectionEndClientRect(): { readonly right: number; readonly bottom: number } | null {
@@ -1036,7 +1038,6 @@ export class GhosttyTerminalSurface {
1038
this.core.clearSelection();
1039
this.selectionEnd = null;
1040
this.selectionAnchorScreen = null;
1039
- this.selectionEndScreen = null;
1041
this.selectionMode = "cell";
1042
this.selectionBase = null;
1043
this.setSelectionAutoscroll(0);
@@ -1421,7 +1422,6 @@ export class GhosttyTerminalSurface {
1422
this.selectionBase = range.screen;
1423
this.selectionEnd = range.viewport.end;
1424
this.selectionAnchorScreen = range.screen.start;
1424
- this.selectionEndScreen = range.screen.end;
1425
this.options.onSelectionChange();
1426
} else {
1427
this.selectionMode = "cell";
@@ -1429,7 +1429,6 @@ export class GhosttyTerminalSurface {
1429
this.selectionEnd = cell;
1430
const screen = this.core.viewportPointToScreen(cell.x, cell.y);
1431
this.selectionAnchorScreen = screen;
1432
- this.selectionEndScreen = screen;
1432
if (screen) {
1433
this.core.setSelection({ ...screen, tag: 2 }, { ...screen, tag: 2 });
1434
} else {
@@ -1511,8 +1510,18 @@ export class GhosttyTerminalSurface {
1510
};
1511
1512
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
+ }
1525
const cell = this.cellAt(clientX, clientY);
1526
this.selectionMoved = true;
1527
this.selectionEnd = cell;
@@ -1532,7 +1541,6 @@ export class GhosttyTerminalSurface {
1541
const anchor = base === null ? anchorScreen : beforeBase ? base.end : base.start;
1542
const end = range === null ? cellScreen : beforeBase ? range.screen.start : range.screen.end;
1543
this.selectionAnchorScreen = anchor;
1535
- this.selectionEndScreen = end;
1544
this.core.setSelection({ ...anchor, tag: 2 }, { ...end, tag: 2 });
1545
this.options.onSelectionChange();
1546
this.forceFullRender = true;