Skip to content

Commit 61058c2

Browse files
farmerpaulclaude
andcommitted
feat(web): copy chat and terminal selections automatically
Add opt-in Settings > General > Copy on select. When on, finishing a fresh mouse selection in the chat timeline or the integrated terminal writes it to the clipboard; Copy on select toast controls the confirmation. Chat skips unchanged, modifier-key and editable-target gestures, and rejects any range that touches form fields, editable content or a data-no-copy-on-select subtree. Double and triple clicks copy once. Both surfaces write through the async Clipboard API only, so a failed write is silent, retryable and never touches the terminal's hidden input. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2482b03 commit 61058c2

12 files changed

Lines changed: 421 additions & 2 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ vi.mock("../hooks/useSettings", async () => {
103103
return {
104104
useClientSettings: <T,>(select: (settings: typeof DEFAULT_CLIENT_SETTINGS) => T) =>
105105
select(DEFAULT_CLIENT_SETTINGS),
106+
getClientSettings: () => DEFAULT_CLIENT_SETTINGS,
106107
};
107108
});
108109

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ import {
8282
import { readLocalApi } from "~/localApi";
8383
import { confirmTerminalClose } from "~/lib/terminalCloseConfirm";
8484
import { useClientSettings } from "../hooks/useSettings";
85+
import { copySelectionIfEnabled } from "../hooks/useCopyOnSelect";
8586
import { getFileMetadataQueryAtom } from "../hooks/useFileMetadata";
8687
import { FileMetadataThreadContext } from "../hooks/FileMetadataThreadProvider";
8788
import { useLocalStorage } from "../hooks/useLocalStorage";
@@ -960,6 +961,8 @@ function TerminalSessionViewport({
960961
clearSelectionAction();
961962
return;
962963
}
964+
// Writes through the Clipboard API, never Ghostty's hidden input, so a failure can't touch IME text.
965+
copySelectionIfEnabled(nextAction.clipboardText);
963966
const requestId = ++selectionActionRequestIdRef.current;
964967
openSelectionMenuRequestIdRef.current = requestId;
965968
const clicked = await localApi.contextMenu

‎apps/web/src/components/chat/MessagesTimeline.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ import { useThreadFindPositionReader } from "./useThreadFindPositionReader";
139139
import { ThreadActivityAnnouncer } from "./ThreadActivityAnnouncer";
140140
import { useStableHandoffRuns, useIncrementalTimelineRows, useStableRows } from "./useTimelineRows";
141141
import { useClientSettings } from "../../hooks/useSettings";
142+
import { useCopyOnSelect } from "../../hooks/useCopyOnSelect";
142143

143144
function timelineListStateFor(identity: string): {
144145
readonly identity: string;
@@ -825,6 +826,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
825826
const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(
826827
null,
827828
);
829+
useCopyOnSelect(timelineViewportElement);
828830
const {
829831
target: readyCitationRequest,
830832
positioning: citationPositioning,

‎apps/web/src/components/settings/SettingsPanels.tsx‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,10 @@ export function useSettingsRestore(onRestored?: () => void) {
464464
...(settings.mathRenderingEnabled !== DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled
465465
? ["Render math"]
466466
: []),
467+
...(settings.copyOnSelect !== DEFAULT_UNIFIED_SETTINGS.copyOnSelect ? ["Copy on select"] : []),
468+
...(settings.copyOnSelectToast !== DEFAULT_UNIFIED_SETTINGS.copyOnSelectToast
469+
? ["Copy on select toast"]
470+
: []),
467471
...(settings.panelAnimationDurationMs !== DEFAULT_UNIFIED_SETTINGS.panelAnimationDurationMs
468472
? ["Panel animations"]
469473
: []),
@@ -646,6 +650,8 @@ export function useSettingsRestore(onRestored?: () => void) {
646650
effortDisplay: DEFAULT_UNIFIED_SETTINGS.effortDisplay,
647651
mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled,
648652
language: DEFAULT_UNIFIED_SETTINGS.language,
653+
copyOnSelect: DEFAULT_UNIFIED_SETTINGS.copyOnSelect,
654+
copyOnSelectToast: DEFAULT_UNIFIED_SETTINGS.copyOnSelectToast,
649655
timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
650656
notificationMode: DEFAULT_UNIFIED_SETTINGS.notificationMode,
651657
inAppNotificationsEnabled: DEFAULT_UNIFIED_SETTINGS.inAppNotificationsEnabled,
@@ -1128,6 +1134,59 @@ export function GeneralSettingsPanel() {
11281134
</Select>
11291135
}
11301136
/>
1137+
<SettingsRow
1138+
{...setting("copy-on-select")}
1139+
description={
1140+
<T>
1141+
Copy text to the clipboard when you finish selecting it with the mouse in chat or the
1142+
terminal.
1143+
</T>
1144+
}
1145+
resetAction={
1146+
settings.copyOnSelect !== DEFAULT_UNIFIED_SETTINGS.copyOnSelect ? (
1147+
<SettingResetButton
1148+
label="copy on select"
1149+
onClick={() =>
1150+
updateSettings({ copyOnSelect: DEFAULT_UNIFIED_SETTINGS.copyOnSelect })
1151+
}
1152+
/>
1153+
) : null
1154+
}
1155+
control={
1156+
<Switch
1157+
checked={settings.copyOnSelect}
1158+
onCheckedChange={(checked) => updateSettings({ copyOnSelect: Boolean(checked) })}
1159+
aria-label={gt("Copy on select")}
1160+
/>
1161+
}
1162+
/>
1163+
{settings.copyOnSelect ? (
1164+
<SettingsRow
1165+
{...setting("copy-on-select-toast")}
1166+
description={<T>Confirm each automatic copy with a toast.</T>}
1167+
resetAction={
1168+
settings.copyOnSelectToast !== DEFAULT_UNIFIED_SETTINGS.copyOnSelectToast ? (
1169+
<SettingResetButton
1170+
label="copy on select toast"
1171+
onClick={() =>
1172+
updateSettings({
1173+
copyOnSelectToast: DEFAULT_UNIFIED_SETTINGS.copyOnSelectToast,
1174+
})
1175+
}
1176+
/>
1177+
) : null
1178+
}
1179+
control={
1180+
<Switch
1181+
checked={settings.copyOnSelectToast}
1182+
onCheckedChange={(checked) =>
1183+
updateSettings({ copyOnSelectToast: Boolean(checked) })
1184+
}
1185+
aria-label={gt("Copy on select toast")}
1186+
/>
1187+
}
1188+
/>
1189+
) : null}
11311190
</SettingsSection>
11321191
</SettingsPageContainer>
11331192
);

‎apps/web/src/components/settings/settingsSearch.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,19 @@ export const SETTINGS_SEARCH_ITEMS = [
704704
to: "/settings/general",
705705
searchTerms: ["timestamp clock locale system browser os 12 hour 24 hour"],
706706
},
707+
{
708+
id: "copy-on-select",
709+
title: msg("Copy on select"),
710+
to: "/settings/general",
711+
searchTerms: ["clipboard automatic selection highlight drag mouse terminal chat herdr"],
712+
},
713+
{
714+
id: "copy-on-select-toast",
715+
title: msg("Copy on select toast"),
716+
to: "/settings/general",
717+
targetId: "copy-on-select",
718+
searchTerms: ["clipboard copied confirmation notification"],
719+
},
707720
{
708721
id: "response-streaming",
709722
title: "Response streaming",
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { useEffect } from "react";
2+
3+
import { toastManager } from "~/components/ui/toast";
4+
import { createSelectionCopier, observeCopyOnSelect } from "~/lib/copyOnSelect";
5+
import { getClientSettings, useClientSettings } from "./useSettings";
6+
7+
const copySelection = createSelectionCopier(() => {
8+
if (getClientSettings().copyOnSelectToast) {
9+
toastManager.add({ type: "success", title: "Copied to clipboard" });
10+
}
11+
});
12+
13+
/** Copies a finished mouse selection when Copy on select is on. Shared by chat and the terminal. */
14+
export function copySelectionIfEnabled(text: string): void {
15+
if (getClientSettings().copyOnSelect) void copySelection(text);
16+
}
17+
18+
export function useCopyOnSelect(container: HTMLElement | null): void {
19+
const enabled = useClientSettings((settings) => settings.copyOnSelect);
20+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to window mouse events for the container
21+
useEffect(() => {
22+
if (!container || !enabled) return;
23+
return observeCopyOnSelect(container, copySelectionIfEnabled);
24+
}, [container, enabled]);
25+
}
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
import { describe, expect, it, vi } from "vite-plus/test";
2+
3+
import { fakeTimers } from "../../test/render";
4+
import { createSelectionCopier, observeCopyOnSelect, readCopyableSelection } from "./copyOnSelect";
5+
import { SELECTION_MULTI_CLICK_INTERVAL_MS } from "./selectionActions";
6+
7+
function mount(html: string) {
8+
const container = document.createElement("div");
9+
container.innerHTML = html;
10+
document.body.append(container);
11+
return Object.assign(container, {
12+
[Symbol.dispose]: () => {
13+
document.getSelection()?.removeAllRanges();
14+
container.remove();
15+
},
16+
});
17+
}
18+
19+
function textOf(root: ParentNode, selector: string): Text {
20+
return root.querySelector(selector)!.firstChild as Text;
21+
}
22+
23+
function select(start: Text, startOffset: number, end: Text, endOffset: number) {
24+
document.getSelection()!.setBaseAndExtent(start, startOffset, end, endOffset);
25+
}
26+
27+
function mouse(type: "mousedown" | "mouseup", target: EventTarget, init: MouseEventInit = {}) {
28+
target.dispatchEvent(new MouseEvent(type, { bubbles: true, button: 0, detail: 1, ...init }));
29+
}
30+
31+
describe("readCopyableSelection", () => {
32+
it.each([
33+
["plain text", '<p id="a">alpha</p><p id="b">bravo</p>', "alpha\n\nbravo"],
34+
["a link", '<p id="a">see <a href="#">docs</a></p><p id="b">bravo</p>', "see docs\n\nbravo"],
35+
["a button", '<p id="a">run <button>go</button></p><p id="b">bravo</p>', "run go\n\nbravo"],
36+
[
37+
"a citation chip",
38+
'<p id="a">cite <span contenteditable="false">[1]</span></p><p id="b">bravo</p>',
39+
"cite [1]\n\nbravo",
40+
],
41+
])("copies a range across %s", (_name, html, expected) => {
42+
using container = mount(html);
43+
select(textOf(container, "#a"), 0, textOf(container, "#b"), 5);
44+
expect(readCopyableSelection(document.getSelection(), container)).toBe(expected);
45+
});
46+
47+
it.each([
48+
["an input", '<input value="secret" />'],
49+
["a textarea", "<textarea>secret</textarea>"],
50+
["a select", "<select><option>secret</option></select>"],
51+
["editable content", '<div contenteditable="true">secret</div>'],
52+
["bare contenteditable", "<div contenteditable>secret</div>"],
53+
["plaintext-only content", '<div contenteditable="plaintext-only">secret</div>'],
54+
["an opted-out subtree", "<div data-no-copy-on-select>secret</div>"],
55+
])("rejects a range whose ordinary endpoints cross %s", (_name, excluded) => {
56+
using container = mount(`<p id="a">alpha</p>${excluded}<p id="b">bravo</p>`);
57+
select(textOf(container, "#a"), 0, textOf(container, "#b"), 5);
58+
expect(readCopyableSelection(document.getSelection(), container)).toBeNull();
59+
});
60+
61+
it("rejects selections that end in editable content, leave the container, or hold no text", () => {
62+
using container = mount('<p id="a">alpha</p><div id="e" contenteditable>edit</div>');
63+
using outside = mount('<p id="o">outside</p>');
64+
const alpha = textOf(container, "#a");
65+
66+
select(alpha, 0, textOf(container, "#e"), 2);
67+
expect(readCopyableSelection(document.getSelection(), container)).toBeNull();
68+
select(alpha, 0, textOf(outside, "#o"), 3);
69+
expect(readCopyableSelection(document.getSelection(), container)).toBeNull();
70+
select(alpha, 2, alpha, 2);
71+
expect(readCopyableSelection(document.getSelection(), container)).toBeNull();
72+
container.querySelector("#a")!.textContent = " ";
73+
select(textOf(container, "#a"), 0, textOf(container, "#a"), 3);
74+
expect(readCopyableSelection(document.getSelection(), container)).toBeNull();
75+
});
76+
});
77+
78+
describe("observeCopyOnSelect", () => {
79+
function setup() {
80+
const container = mount('<p id="a">alpha bravo</p><textarea id="t">draft</textarea>');
81+
const copy = vi.fn();
82+
const stop = observeCopyOnSelect(container, copy);
83+
const unmount = container[Symbol.dispose];
84+
return Object.assign(container, {
85+
copy,
86+
text: textOf(container, "#a"),
87+
paragraph: container.querySelector("#a")!,
88+
[Symbol.dispose]: () => {
89+
stop();
90+
unmount();
91+
},
92+
});
93+
}
94+
95+
it("copies a fresh drag, including one released outside the container", () => {
96+
using view = setup();
97+
mouse("mousedown", view.paragraph);
98+
select(view.text, 0, view.text, 5);
99+
mouse("mouseup", document.body);
100+
expect(view.copy).toHaveBeenCalledExactlyOnceWith("alpha");
101+
});
102+
103+
it("ignores clicks that leave the selection unchanged, modifier clicks, and editable targets", () => {
104+
using view = setup();
105+
select(view.text, 0, view.text, 5);
106+
mouse("mousedown", view.paragraph);
107+
mouse("mouseup", view.paragraph);
108+
109+
mouse("mousedown", view.paragraph, { metaKey: true });
110+
select(view.text, 6, view.text, 11);
111+
mouse("mouseup", view.paragraph, { metaKey: true });
112+
113+
mouse("mousedown", view.querySelector("#t")!);
114+
select(view.text, 0, view.text, 11);
115+
mouse("mouseup", view.paragraph);
116+
117+
expect(view.copy).not.toHaveBeenCalled();
118+
});
119+
120+
it("copies a double then triple click once, after the sequence settles", () => {
121+
using _timers = fakeTimers();
122+
using view = setup();
123+
mouse("mousedown", view.paragraph);
124+
mouse("mouseup", view.paragraph);
125+
mouse("mousedown", view.paragraph, { detail: 2 });
126+
select(view.text, 0, view.text, 5);
127+
mouse("mouseup", view.paragraph, { detail: 2 });
128+
mouse("mousedown", view.paragraph, { detail: 3 });
129+
select(view.text, 0, view.text, 11);
130+
mouse("mouseup", view.paragraph, { detail: 3 });
131+
expect(view.copy).not.toHaveBeenCalled();
132+
133+
vi.advanceTimersByTime(SELECTION_MULTI_CLICK_INTERVAL_MS);
134+
expect(view.copy).toHaveBeenCalledExactlyOnceWith("alpha bravo");
135+
});
136+
});
137+
138+
describe("createSelectionCopier", () => {
139+
it("fails silently without touching focused input, then retries the same text", async () => {
140+
using input = mount('<textarea id="t">にほんご</textarea>');
141+
const terminalInput = input.querySelector("textarea")!;
142+
terminalInput.focus();
143+
terminalInput.setSelectionRange(4, 4);
144+
using execCommand = vi.spyOn(document, "execCommand");
145+
using writeText = vi
146+
.spyOn(navigator.clipboard, "writeText")
147+
.mockRejectedValueOnce(new Error("denied"))
148+
.mockResolvedValueOnce(undefined);
149+
const onCopied = vi.fn();
150+
const copy = createSelectionCopier(onCopied);
151+
152+
await expect(copy("git status")).resolves.toBe(false);
153+
expect(onCopied).not.toHaveBeenCalled();
154+
expect(document.activeElement).toBe(terminalInput);
155+
expect(terminalInput.value).toBe("にほんご");
156+
expect([terminalInput.selectionStart, terminalInput.selectionEnd]).toEqual([4, 4]);
157+
expect(execCommand).not.toHaveBeenCalled();
158+
159+
await expect(copy("git status")).resolves.toBe(true);
160+
expect(onCopied).toHaveBeenCalledOnce();
161+
expect(writeText).toHaveBeenCalledTimes(2);
162+
});
163+
164+
it("does not repeat a write of the same text while it is in flight", async () => {
165+
let resolve = () => {};
166+
const promise = new Promise<void>((done) => (resolve = done));
167+
using writeText = vi.spyOn(navigator.clipboard, "writeText").mockReturnValue(promise);
168+
const onCopied = vi.fn();
169+
const copy = createSelectionCopier(onCopied);
170+
171+
const first = copy("git status");
172+
await expect(copy("git status")).resolves.toBe(false);
173+
resolve();
174+
await expect(first).resolves.toBe(true);
175+
expect(writeText).toHaveBeenCalledOnce();
176+
expect(onCopied).toHaveBeenCalledOnce();
177+
});
178+
});

0 commit comments

Comments
 (0)