Skip to content

Commit b4fa501

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 17a6a01 commit b4fa501

12 files changed

Lines changed: 416 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
@@ -137,6 +137,7 @@ import { useThreadFindPositionReader } from "./useThreadFindPositionReader";
137137
import { ThreadActivityAnnouncer } from "./ThreadActivityAnnouncer";
138138
import { useStableHandoffRuns, useIncrementalTimelineRows, useStableRows } from "./useTimelineRows";
139139
import { useClientSettings } from "../../hooks/useSettings";
140+
import { useCopyOnSelect } from "../../hooks/useCopyOnSelect";
140141

141142
function timelineListStateFor(identity: string): {
142143
readonly identity: string;
@@ -742,6 +743,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
742743
const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(
743744
null,
744745
);
746+
useCopyOnSelect(timelineViewportElement);
745747
const {
746748
target: readyCitationRequest,
747749
positioning: citationPositioning,

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

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,10 @@ export function useSettingsRestore(onRestored?: () => void) {
466466
...(settings.mathRenderingEnabled !== DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled
467467
? ["Render math"]
468468
: []),
469+
...(settings.copyOnSelect !== DEFAULT_UNIFIED_SETTINGS.copyOnSelect ? ["Copy on select"] : []),
470+
...(settings.copyOnSelectToast !== DEFAULT_UNIFIED_SETTINGS.copyOnSelectToast
471+
? ["Copy on select toast"]
472+
: []),
469473
...(settings.panelAnimationDurationMs !== DEFAULT_UNIFIED_SETTINGS.panelAnimationDurationMs
470474
? ["Panel animations"]
471475
: []),
@@ -640,6 +644,8 @@ export function useSettingsRestore(onRestored?: () => void) {
640644
chatWidth: DEFAULT_UNIFIED_SETTINGS.chatWidth,
641645
effortDisplay: DEFAULT_UNIFIED_SETTINGS.effortDisplay,
642646
mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled,
647+
copyOnSelect: DEFAULT_UNIFIED_SETTINGS.copyOnSelect,
648+
copyOnSelectToast: DEFAULT_UNIFIED_SETTINGS.copyOnSelectToast,
643649
timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,
644650
notificationMode: DEFAULT_UNIFIED_SETTINGS.notificationMode,
645651
inAppNotificationsEnabled: DEFAULT_UNIFIED_SETTINGS.inAppNotificationsEnabled,
@@ -1043,6 +1049,54 @@ export function GeneralSettingsPanel() {
10431049
</Select>
10441050
}
10451051
/>
1052+
<SettingsRow
1053+
{...searchableSetting("copy-on-select")}
1054+
description="Copy text to the clipboard when you finish selecting it with the mouse in chat or the terminal."
1055+
resetAction={
1056+
settings.copyOnSelect !== DEFAULT_UNIFIED_SETTINGS.copyOnSelect ? (
1057+
<SettingResetButton
1058+
label="copy on select"
1059+
onClick={() =>
1060+
updateSettings({ copyOnSelect: DEFAULT_UNIFIED_SETTINGS.copyOnSelect })
1061+
}
1062+
/>
1063+
) : null
1064+
}
1065+
control={
1066+
<Switch
1067+
checked={settings.copyOnSelect}
1068+
onCheckedChange={(checked) => updateSettings({ copyOnSelect: Boolean(checked) })}
1069+
aria-label="Copy on select"
1070+
/>
1071+
}
1072+
/>
1073+
{settings.copyOnSelect ? (
1074+
<SettingsRow
1075+
{...searchableSetting("copy-on-select-toast")}
1076+
description="Confirm each automatic copy with a toast."
1077+
resetAction={
1078+
settings.copyOnSelectToast !== DEFAULT_UNIFIED_SETTINGS.copyOnSelectToast ? (
1079+
<SettingResetButton
1080+
label="copy on select toast"
1081+
onClick={() =>
1082+
updateSettings({
1083+
copyOnSelectToast: DEFAULT_UNIFIED_SETTINGS.copyOnSelectToast,
1084+
})
1085+
}
1086+
/>
1087+
) : null
1088+
}
1089+
control={
1090+
<Switch
1091+
checked={settings.copyOnSelectToast}
1092+
onCheckedChange={(checked) =>
1093+
updateSettings({ copyOnSelectToast: Boolean(checked) })
1094+
}
1095+
aria-label="Copy on select toast"
1096+
/>
1097+
}
1098+
/>
1099+
) : null}
10461100
</SettingsSection>
10471101
</SettingsPageContainer>
10481102
);

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -676,6 +676,19 @@ export const SETTINGS_SEARCH_ITEMS = [
676676
to: "/settings/general",
677677
searchTerms: ["timestamp clock locale system browser os 12 hour 24 hour"],
678678
},
679+
{
680+
id: "copy-on-select",
681+
title: "Copy on select",
682+
to: "/settings/general",
683+
searchTerms: ["clipboard automatic selection highlight drag mouse terminal chat herdr"],
684+
},
685+
{
686+
id: "copy-on-select-toast",
687+
title: "Copy on select toast",
688+
to: "/settings/general",
689+
targetId: "copy-on-select",
690+
searchTerms: ["clipboard copied confirmation notification"],
691+
},
679692
{
680693
id: "response-streaming",
681694
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)