Skip to content

Commit 8b9c050

Browse files
committed
fix(web): harden copy-on-select behavior
1 parent 925af56 commit 8b9c050

6 files changed

Lines changed: 214 additions & 55 deletions

File tree

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

Lines changed: 19 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,10 @@ import { Button } from "~/components/ui/button";
4343
import { PanelTabCloseButton } from "~/components/ui/panel-tab-close-button";
4444
import { readTextFromClipboard, writeTextToClipboard } from "~/hooks/useCopyToClipboard";
4545
import { getClientSettings } from "~/hooks/useSettings";
46-
import { normalizeTerminalSelectionText } from "~/lib/copyOnSelect";
46+
import {
47+
createTerminalSelectionAutoCopy,
48+
normalizeTerminalSelectionText,
49+
} from "~/lib/copyOnSelect";
4750
import { toastManager } from "~/components/ui/toast";
4851
import { cn } from "~/lib/utils";
4952
import { type TerminalContextSelection } from "~/lib/terminalContext";
@@ -463,9 +466,17 @@ export function TerminalViewport({
463466
let setupTerminal: GhosttyTerminalSurface | null = null;
464467
let setupCleanups: Array<() => void> = [];
465468
let selectionActions: ReturnType<typeof observeSelectionActions> | null = null;
466-
// Last text confirmed via copy-on-select, so repeat gestures over an
467-
// unchanged selection stay quiet instead of re-toasting.
468-
let lastAutoCopiedText: string | null = null;
469+
const autoCopyTerminalSelection = createTerminalSelectionAutoCopy({
470+
readSettings: () => {
471+
const settings = getClientSettings();
472+
return {
473+
enabled: settings.copyOnSelect,
474+
showToast: settings.copyOnSelectToast,
475+
};
476+
},
477+
writeText: (text) => writeTextToClipboard(text, "terminal selection"),
478+
onCopied: () => toastManager.add({ type: "success", title: "Copied to clipboard" }),
479+
});
469480

470481
const setup = async (): Promise<(() => void) | null> => {
471482
const setupFont = terminalFontRef.current;
@@ -551,8 +562,8 @@ export function TerminalViewport({
551562
}
552563
const selectionText = activeTerminal.getSelection();
553564
const selectionPosition = activeTerminal.getSelectionPosition();
554-
const normalizedText = selectionText.replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "");
555-
if (!selectionPosition || normalizedText.length === 0) {
565+
const normalizedText = normalizeTerminalSelectionText(selectionText);
566+
if (!selectionPosition || normalizedText === null) {
556567
return null;
557568
}
558569
const { lineStart, lineEnd } = terminalSelectionLineRange(selectionPosition);
@@ -605,7 +616,7 @@ export function TerminalViewport({
605616
// right-click started while this write was pending, so toasting
606617
// now would confirm a no-longer-active selection.
607618
if (didCopy && requestId === selectionActionRequestIdRef.current) {
608-
lastAutoCopiedText = text;
619+
autoCopyTerminalSelection.rememberCopied(text);
609620
toastManager.add({ type: "success", title: "Copied to clipboard" });
610621
}
611622
} catch (error) {
@@ -614,32 +625,6 @@ export function TerminalViewport({
614625
focusIfCurrent(requestId);
615626
};
616627

617-
// Herdr-style copy-on-select: a completed selection gesture copies on
618-
// release. Only call with a fresh, non-empty selection read for this
619-
// gesture (as `showSelectionAction` does) — never with pre-existing
620-
// text, so application clicks can't clobber the clipboard with stale
621-
// content. The toast fires only after a successful write.
622-
const autoCopyTerminalSelection = async (text: string) => {
623-
const settings = getClientSettings();
624-
if (!settings.copyOnSelect) return;
625-
if (normalizeTerminalSelectionText(text) === null) return;
626-
if (text === lastAutoCopiedText) return;
627-
// Claim before the await so a repeat gesture started while this
628-
// write is pending can't issue a second write and toast.
629-
lastAutoCopiedText = text;
630-
try {
631-
const didCopy = await writeTextToClipboard(text, "terminal selection");
632-
if (!didCopy && lastAutoCopiedText === text) lastAutoCopiedText = null;
633-
if (!didCopy) return;
634-
} catch {
635-
if (lastAutoCopiedText === text) lastAutoCopiedText = null;
636-
return;
637-
}
638-
if (getClientSettings().copyOnSelectToast) {
639-
toastManager.add({ type: "success", title: "Copied to clipboard" });
640-
}
641-
};
642-
643628
const pasteFromClipboard = async (requestId: number) => {
644629
const activeTerminal = terminalRef.current;
645630
if (!activeTerminal) return;
@@ -711,7 +696,7 @@ export function TerminalViewport({
711696
// Copy-on-select fires on release, before the popup opens; the popup
712697
// stays for Add to chat (and Copy as a fallback when auto-copy is
713698
// off or the clipboard write failed).
714-
void autoCopyTerminalSelection(nextAction.clipboardText);
699+
void autoCopyTerminalSelection.copy(nextAction.clipboardText);
715700
const requestId = ++selectionActionRequestIdRef.current;
716701
openSelectionMenuRequestIdRef.current = requestId;
717702
const clicked = await localApi.contextMenu

‎apps/web/src/hooks/useCopyOnSelect.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,7 @@ export function useCopyOnSelect(container: HTMLElement | null): void {
4242
snapshot: null,
4343
armed: false,
4444
});
45-
const settingsRef = React.useRef({ copyOnSelect, showToast });
46-
settingsRef.current = { copyOnSelect, showToast };
45+
const readSettings = React.useEffectEvent(() => ({ copyOnSelect, showToast }));
4746

4847
React.useEffect(() => {
4948
if (!container) return;
@@ -74,15 +73,15 @@ export function useCopyOnSelect(container: HTMLElement | null): void {
7473
const { snapshot: startSnapshot, armed } = gestureStartRef.current;
7574
gestureStartRef.current = { snapshot: null, armed: false };
7675
if (!armed) return;
77-
if (!settingsRef.current.copyOnSelect) return;
76+
if (!readSettings().copyOnSelect) return;
7877
if (!shouldAutoCopyOnMouseUp(event)) return;
7978
const selection = view.getSelection();
8079
if (sameDomSelectionSnapshot(startSnapshot, snapshotDomSelection(selection))) return;
8180
const text = getCopyableDomSelectionText(selection, container);
8281
if (text === null || text === lastCopiedRef.current) return;
8382
const fireCopy = () => {
8483
pendingMultiClickTimer = null;
85-
if (!settingsRef.current.copyOnSelect) return;
84+
if (!readSettings().copyOnSelect) return;
8685
if (text === lastCopiedRef.current) return;
8786
// Reserve before the await so a repeated gesture while this write is
8887
// pending can't issue a second write and toast.
@@ -93,7 +92,7 @@ export function useCopyOnSelect(container: HTMLElement | null): void {
9392
if (lastCopiedRef.current === text) lastCopiedRef.current = null;
9493
return;
9594
}
96-
if (settingsRef.current.showToast) {
95+
if (readSettings().showToast) {
9796
toastManager.add({ type: "success", title: "Copied to clipboard" });
9897
}
9998
},

‎apps/web/src/lib/copyOnSelect.test.ts‎

Lines changed: 125 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
1-
import { describe, expect, it } from "vite-plus/test";
1+
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2+
3+
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
24

35
import {
6+
createTerminalSelectionAutoCopy,
47
getCopyableDomSelectionText,
58
isCopyOnSelectEditableTarget,
69
normalizeTerminalSelectionText,
@@ -9,6 +12,93 @@ import {
912
snapshotDomSelection,
1013
} from "./copyOnSelect";
1114

15+
describe("terminal copy on select", () => {
16+
afterEach(() => {
17+
vi.unstubAllGlobals();
18+
});
19+
20+
it("preserves terminal input when the browser rejects the clipboard write", async () => {
21+
const terminalInput = {
22+
value: "にほんご",
23+
selectionStart: 4,
24+
selectionEnd: 4,
25+
select: vi.fn(),
26+
};
27+
vi.stubGlobal("window", {});
28+
vi.stubGlobal("navigator", {
29+
clipboard: { writeText: vi.fn().mockRejectedValue(new Error("denied")) },
30+
});
31+
const onCopied = vi.fn();
32+
const autoCopy = createTerminalSelectionAutoCopy({
33+
readSettings: () => ({ enabled: true, showToast: true }),
34+
writeText: (text) => writeTextToClipboard(text, "terminal selection"),
35+
onCopied,
36+
});
37+
38+
await expect(autoCopy.copy("git status")).resolves.toBe(false);
39+
expect(terminalInput.value).toBe("にほんご");
40+
expect(terminalInput.selectionStart).toBe(4);
41+
expect(terminalInput.selectionEnd).toBe(4);
42+
expect(terminalInput.select).not.toHaveBeenCalled();
43+
expect(onCopied).not.toHaveBeenCalled();
44+
});
45+
46+
it("allows the same selection to retry after a failed write", async () => {
47+
const writeText = vi
48+
.fn()
49+
.mockRejectedValueOnce(new Error("denied"))
50+
.mockResolvedValueOnce(true);
51+
const onCopied = vi.fn();
52+
const autoCopy = createTerminalSelectionAutoCopy({
53+
readSettings: () => ({ enabled: true, showToast: true }),
54+
writeText,
55+
onCopied,
56+
});
57+
58+
await expect(autoCopy.copy("git status")).resolves.toBe(false);
59+
await expect(autoCopy.copy("git status")).resolves.toBe(true);
60+
expect(onCopied).toHaveBeenCalledOnce();
61+
});
62+
63+
it("coalesces a pending write and honors the current toast setting", async () => {
64+
let finishWrite: ((didCopy: boolean) => void) | undefined;
65+
const writeText = vi.fn(
66+
() =>
67+
new Promise<boolean>((resolve) => {
68+
finishWrite = resolve;
69+
}),
70+
);
71+
const onCopied = vi.fn();
72+
const autoCopy = createTerminalSelectionAutoCopy({
73+
readSettings: () => ({ enabled: true, showToast: false }),
74+
writeText,
75+
onCopied,
76+
});
77+
78+
const firstCopy = autoCopy.copy("git status");
79+
await expect(autoCopy.copy("git status")).resolves.toBe(false);
80+
expect(writeText).toHaveBeenCalledOnce();
81+
82+
finishWrite?.(true);
83+
await expect(firstCopy).resolves.toBe(true);
84+
expect(onCopied).not.toHaveBeenCalled();
85+
});
86+
87+
it("keeps a successful explicit copy from immediately auto-copying the same selection", async () => {
88+
const writeText = vi.fn().mockResolvedValue(true);
89+
const autoCopy = createTerminalSelectionAutoCopy({
90+
readSettings: () => ({ enabled: true, showToast: true }),
91+
writeText,
92+
onCopied: vi.fn(),
93+
});
94+
95+
autoCopy.rememberCopied("git status");
96+
97+
await expect(autoCopy.copy("git status")).resolves.toBe(false);
98+
expect(writeText).not.toHaveBeenCalled();
99+
});
100+
});
101+
12102
function mouseUp(overrides: Partial<MouseEvent> = {}): MouseEvent {
13103
return { button: 0, ctrlKey: false, metaKey: false, altKey: false, ...overrides } as MouseEvent;
14104
}
@@ -67,12 +157,23 @@ class FakeElement {
67157
}
68158
}
69159

70-
function selectionOf(text: string, startContainer: unknown, endContainer: unknown) {
160+
function selectionOf(
161+
text: string,
162+
startContainer: unknown,
163+
endContainer: unknown,
164+
options: { crossesExcludedContent?: boolean } = {},
165+
) {
71166
return {
72167
isCollapsed: false,
73168
rangeCount: 1,
74169
toString: () => text,
75-
getRangeAt: () => ({ startContainer, endContainer }),
170+
getRangeAt: () => ({
171+
startContainer,
172+
endContainer,
173+
cloneContents: () => ({
174+
querySelector: () => (options.crossesExcludedContent ? new FakeElement() : null),
175+
}),
176+
}),
76177
} as unknown as Selection;
77178
}
78179

@@ -118,6 +219,10 @@ describe("normalizeTerminalSelectionText", () => {
118219
expect(normalizeTerminalSelectionText("git status")).toBe("git status");
119220
});
120221

222+
it("normalizes line endings and trims blank boundary lines", () => {
223+
expect(normalizeTerminalSelectionText("\r\n\r\ngit status\r\n\r\n")).toBe("git status");
224+
});
225+
121226
it("rejects empty and blank-line-only selections", () => {
122227
expect(normalizeTerminalSelectionText("")).toBeNull();
123228
expect(normalizeTerminalSelectionText("\n\n")).toBeNull();
@@ -128,19 +233,13 @@ describe("normalizeTerminalSelectionText", () => {
128233
describe("dom selection snapshots", () => {
129234
it("snapshots null for missing or collapsed selections", () => {
130235
expect(snapshotDomSelection(null)).toBeNull();
131-
expect(
132-
snapshotDomSelection({ isCollapsed: true } as unknown as Selection),
133-
).toBeNull();
236+
expect(snapshotDomSelection({ isCollapsed: true } as unknown as Selection)).toBeNull();
134237
});
135238

136239
it("treats an unchanged selection across a click as the same", () => {
137240
const node = textNode("hello");
138-
const before = snapshotDomSelection(
139-
selectionWithAnchors("hello", node, 0, node, 5),
140-
);
141-
const after = snapshotDomSelection(
142-
selectionWithAnchors("hello", node, 0, node, 5),
143-
);
241+
const before = snapshotDomSelection(selectionWithAnchors("hello", node, 0, node, 5));
242+
const after = snapshotDomSelection(selectionWithAnchors("hello", node, 0, node, 5));
144243
expect(sameDomSelectionSnapshot(before, after)).toBe(true);
145244
});
146245

@@ -223,6 +322,20 @@ describe("getCopyableDomSelectionText", () => {
223322
}
224323
});
225324

325+
it("rejects a range that crosses opted-out content between ordinary endpoints", () => {
326+
const container = new FakeElement();
327+
const message = new FakeElement("DIV", "plain", container);
328+
const start = textNode("before", message);
329+
const end = textNode("after", message);
330+
331+
expect(
332+
getCopyableDomSelectionText(
333+
selectionOf("before private after", start, end, { crossesExcludedContent: true }),
334+
container as unknown as HTMLElement,
335+
),
336+
).toBeNull();
337+
});
338+
226339
it("rejects collapsed, multi-range, and whitespace-only selections", () => {
227340
const container = new FakeElement();
228341
const node = textNode("hi", new FakeElement("DIV", "plain", container));

‎apps/web/src/lib/copyOnSelect.ts‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,49 @@ export function isCopyOnSelectEditableTarget(target: EventTarget | null): boolea
4747
*/
4848
export function normalizeTerminalSelectionText(text: string): string | null {
4949
const normalized = text.replace(/\r\n/g, "\n").replace(/^\n+|\n+$/g, "");
50-
return normalized.length > 0 ? text : null;
50+
return normalized.length > 0 ? normalized : null;
51+
}
52+
53+
/**
54+
* Owns terminal auto-copy state without receiving the terminal surface or its
55+
* hidden IME input, so clipboard failure cannot mutate terminal input state.
56+
*/
57+
export function createTerminalSelectionAutoCopy({
58+
readSettings,
59+
writeText,
60+
onCopied,
61+
}: {
62+
readSettings: () => { enabled: boolean; showToast: boolean };
63+
writeText: (text: string) => Promise<boolean>;
64+
onCopied: () => void;
65+
}) {
66+
let lastCopiedText: string | null = null;
67+
68+
return {
69+
copy: async (text: string): Promise<boolean> => {
70+
if (!readSettings().enabled) return false;
71+
if (normalizeTerminalSelectionText(text) === null) return false;
72+
if (text === lastCopiedText) return false;
73+
74+
lastCopiedText = text;
75+
try {
76+
const didCopy = await writeText(text);
77+
if (!didCopy) {
78+
if (lastCopiedText === text) lastCopiedText = null;
79+
return false;
80+
}
81+
} catch {
82+
if (lastCopiedText === text) lastCopiedText = null;
83+
return false;
84+
}
85+
86+
if (readSettings().showToast) onCopied();
87+
return true;
88+
},
89+
rememberCopied: (text: string): void => {
90+
lastCopiedText = text;
91+
},
92+
};
5193
}
5294

5395
function nodeInEditable(node: Node | null): boolean {
@@ -78,7 +120,11 @@ export function getCopyableDomSelectionText(
78120
if (text.trim().length === 0) return null;
79121
const range = selection.getRangeAt(0);
80122
if (nodeInEditable(range.startContainer) || nodeInEditable(range.endContainer)) return null;
81-
if (container && (!container.contains(range.startContainer) || !container.contains(range.endContainer))) {
123+
if (range.cloneContents().querySelector(COPY_ON_SELECT_EDITABLE_SELECTOR) !== null) return null;
124+
if (
125+
container &&
126+
(!container.contains(range.startContainer) || !container.contains(range.endContainer))
127+
) {
82128
return null;
83129
}
84130
return text;

‎docs/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
- [Messages and context](./user/composer.md)
77
- [Working with threads](./user/thread-sidebar.md)
88
- [Permission modes](./user/permission-modes.md)
9-
- [Terminal history](./user/terminal.md)
9+
- [Terminal](./user/terminal.md)
1010
- [Source control](./user/source-control.md)
1111
- [Project settings](./user/project-settings.md)
1212
- [Appearance and themes](./user/appearance.md)

0 commit comments

Comments
 (0)