Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat: copyOnSelect setting for xterm-owned mouse selections (#759) (#963)

ezwepaea0faca43e1
diff --git a/CLAUDE.md b/CLAUDE.md
index 4bfe5ca7e..1afe0b497 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -596,6 +596,14 @@ tmux 3.4:
to `pbcopy` was macOS-only, and over SSH it would have copied on the *remote* host anyway. OSC 52
is cross-platform and works over SSH.
+**Copy-on-select (opt-in, `copyOnSelect`, default off — #759)** is the route for a selection
+**xterm** owns, which OSC 52 never sees: a plain drag on Windows (no tmux), a forced Option/Shift
+drag inside a mouse-tracking app. `terminal/copy-on-select.ts` triggers on the GESTURE (a press
+xterm's SelectionService takes, then a release anywhere), not on `onSelectionChange` — the search
+addon's `select()` must never touch the clipboard. Canvas node and kanban modal only, never the
+settings preview; attached once per xterm (it survives park/adopt) and written via the bridge's
+`{ quiet: true }` path so a failed write raises no toast per drag.
+
**A tmux client is not necessarily a watcher.** `SessionInfo.clients` is a COUNT
(`#{session_attached}`), never a boolean, because one session can hold several: the app's painter,
the user's own `tmux -L node-terminal attach`, a second nodeterm on the same socket, and our own
diff --git a/src/preload/index.ts b/src/preload/index.ts
index ef7a94f00..b0eddc084 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -378,6 +378,8 @@ const api: NodeTerminalApi = {
},
clipboard: {
// Route to the MAIN process: renderer-side `clipboard` access is deprecated in Electron.
+ // Fire-and-forget with no failure surface, so `ClipboardWriteOptions.quiet` has nothing to
+ // silence here and is ignored.
writeText: (text: string) => ipcRenderer.send(IPC.clipboardWrite, text),
writeFiles: (paths: string[]) => ipcRenderer.invoke(IPC.clipboardWriteFiles, paths)
},
diff --git a/src/renderer/bridge/stubs.test.ts b/src/renderer/bridge/stubs.test.ts
index 6ea78d9c3..dd6cfa8b8 100644
--- a/src/renderer/bridge/stubs.test.ts
+++ b/src/renderer/bridge/stubs.test.ts
@@ -223,6 +223,31 @@ describe('bridge clipboard', () => {
expect(ev.detail.message).not.toMatch(/plain http/i)
expect(ev.detail.message).toMatch(/copy/i)
})
+
+ // Issue #759: copy-on-select writes on EVERY completed drag, so a failure toast per drag would
+ // be unusable. The quiet path still tries both routes — it only withholds the banner.
+ it('quiet: still falls back to execCommand, but raises no toast when that fails', () => {
+ const { doc } = fakeDocument(() => false)
+ const dispatchEvent = vi.fn()
+ vi.stubGlobal('navigator', {})
+ vi.stubGlobal('document', doc)
+ vi.stubGlobal('window', { dispatchEvent, isSecureContext: false })
+ buildStubApi().clipboard.writeText('hi', { quiet: true })
+ expect(doc.execCommand).toHaveBeenCalledWith('copy')
+ expect(dispatchEvent).not.toHaveBeenCalled()
+ })
+
+ it('quiet: a rejected Clipboard API falls back without a toast either', async () => {
+ const { doc } = fakeDocument(() => false)
+ const dispatchEvent = vi.fn()
+ const writeText = vi.fn().mockRejectedValue(new Error('NotAllowedError'))
+ vi.stubGlobal('navigator', { clipboard: { writeText } })
+ vi.stubGlobal('document', doc)
+ vi.stubGlobal('window', { dispatchEvent, isSecureContext: true })
+ buildStubApi().clipboard.writeText('hi', { quiet: true })
+ await vi.waitFor(() => expect(doc.execCommand).toHaveBeenCalledWith('copy'))
+ expect(dispatchEvent).not.toHaveBeenCalled()
+ })
})
describe('bridge stubs: canvasAuthority', () => {
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 836e2db08..26f72c94b 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -20,6 +20,7 @@ import {
UNKNOWN_CODEX_IDENTITY_CAPS,
UNKNOWN_CODEX_CLI_CAPS,
type ClaudeUsage,
+ type ClipboardWriteOptions,
type NodeTerminalApi,
type NotifyPayload,
type UpdatePolicy
@@ -63,7 +64,7 @@ const pnoop = (): Promise<void> => Promise.resolve()
* focused and `position:fixed` — i.e. it would swallow every subsequent keystroke. `select()` also
* steals focus from xterm's helper textarea, so the previously-focused element is restored too
* (the terminal's *selection* survives on its own — xterm paints it, it is not a DOM Selection). */
-function copyViaExecCommand(text: string): boolean {
+function copyViaExecCommand(text: string, quiet = false): boolean {
const prev = document.activeElement as HTMLElement | null
let ta: HTMLTextAreaElement | undefined
try {
@@ -77,6 +78,10 @@ function copyViaExecCommand(text: string): boolean {
if (!document.execCommand('copy')) throw new Error('execCommand returned false')
return true
} catch {
+ // A QUIET write (copy-on-select, issue #759) ends here: it fires on every drag, and a banner
+ // per drag would be unusable. The explicit copy chord still toasts, so a user on plain http
+ // learns the clipboard is blocked the first time they copy deliberately.
+ if (quiet) return false
// Surfacing beats silence: the user needs to know why nothing landed in their clipboard. The
// diagnosis differs — plain http has no Clipboard API at all, while in a secure context we got
// here because the API rejected (permission denied / document not focused) AND the fallback
@@ -174,12 +179,13 @@ export function buildStubApi(): Omit<
// context (https or localhost); over plain http on a LAN it is undefined, and the old
// optional-chained call copied nothing and told nobody. execCommand('copy') is deprecated but
// is the only thing that works there.
- writeText: (text: string): void => {
+ writeText: (text: string, opts?: ClipboardWriteOptions): void => {
+ const quiet = opts?.quiet === true
if (typeof navigator !== 'undefined' && navigator.clipboard) {
- void navigator.clipboard.writeText(text).catch(() => copyViaExecCommand(text))
+ void navigator.clipboard.writeText(text).catch(() => copyViaExecCommand(text, quiet))
return
}
- copyViaExecCommand(text)
+ copyViaExecCommand(text, quiet)
},
// A browser cannot place host-local file references on the viewer's OS clipboard.
writeFiles: async (): Promise<boolean> => false
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index 13fe7a2c0..e4d56a036 100644
--- a/src/renderer/components/kanban/ModalTerminal.tsx
+++ b/src/renderer/components/kanban/ModalTerminal.tsx
@@ -26,6 +26,7 @@ import { useTerminalGlass } from '../../lib/useTerminalGlass'
import { LocalTransport } from '../../terminal/local-transport'
import { clipboardImages, droppedPaths, pasteHasText, pastedFiles } from '../../terminal/file-drop'
import { guardMiddleClickPaste } from '../../terminal/middle-click'
+import { attachCopyOnSelect } from '../../terminal/copy-on-select'
import {
createOsc8LinkHandler,
createUrlLinkProvider,
@@ -272,6 +273,16 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch, covere
)
}
+ // MIRROR TerminalNode's copy-on-select (issue #759): same helper, same live setting read, same
+ // quiet clipboard path. This xterm is created and disposed by this one effect (no park), so the
+ // per-mount `cleanups` is its whole lifetime.
+ cleanups.push(
+ attachCopyOnSelect(term, {
+ enabled: () => useSettings.getState().settings.copyOnSelect,
+ write: (text) => window.nodeTerminal.clipboard.writeText(text, { quiet: true })
+ })
+ )
+
// MIRROR TerminalNode "WRITE-ONLY — `parseOsc52` returns null" — the OSC 52 clipboard-write path.
// tmux's mouse is ON, so a drag-select in copy-mode emits OSC 52 to this client; this handler
// writes the system clipboard. `parseOsc52` returns null for a `?` read query so a remote program
diff --git a/src/renderer/components/settings/sections/TerminalSection.tsx b/src/renderer/components/settings/sections/TerminalSection.tsx
index 5215fce55..972ca7178 100644
--- a/src/renderer/components/settings/sections/TerminalSection.tsx
+++ b/src/renderer/components/settings/sections/TerminalSection.tsx
@@ -63,6 +63,12 @@ const ROWS = {
title: 'Middle-click paste',
keywords: ['middle', 'click', 'mouse', 'paste', 'primary', 'selection', 'x11', 'linux', 'wheel']
},
+ copyOnSelect: {
+ title: 'Copy on select',
+ keywords: [
+ 'copy', 'select', 'selection', 'clipboard', 'drag', 'mouse', 'highlight', 'auto', 'windows'
+ ]
+ },
wordSeparator: {
title: 'Word selection',
keywords: ['word', 'separator', 'selection', 'double click', 'identifier', 'hyphen']
@@ -323,6 +329,20 @@ export function TerminalSection({ isActive }: { isActive: boolean }): React.JSX.
</div>
</SearchableRow>
+ <SearchableRow {...ROWS.copyOnSelect}>
+ <FieldRow
+ label="Copy on select"
+ description="Off by default. On, finishing a mouse selection in the terminal itself — a drag, a double or triple click, or inside an app that grabs the mouse an Option-drag (macOS) or Shift-drag (Windows, Linux) — copies it to the clipboard. It cannot copy a selection an app draws itself. Copies a program sends on its own (tmux copy mode, vim) reach the clipboard whether this is on or off."
+ control={
+ <Switch
+ checked={settings.copyOnSelect}
+ onChange={(v) => update({ copyOnSelect: v })}
+ ariaLabel="Copy on select"
+ />
+ }
+ />
+ </SearchableRow>
+
<SearchableRow {...ROWS.wordSeparator}>
<FieldRow
label="Word separators"
diff --git a/src/renderer/lib/settingsReset.test.ts b/src/renderer/lib/settingsReset.test.ts
index 26ac5d2a6..d2a2c3ffc 100644
--- a/src/renderer/lib/settingsReset.test.ts
+++ b/src/renderer/lib/settingsReset.test.ts
@@ -35,6 +35,13 @@ describe('reset key lists', () => {
expect(TERMINAL_RESET_KEYS).not.toContain('tmuxScrollback')
})
+ // Issue #759: the toggle lives in the Terminal section beside word selection, so its reset
+ // button owns it too — resetting puts the clipboard back to explicit-copy only.
+ it('claims copyOnSelect, whose default is off', () => {
+ expect(TERMINAL_RESET_KEYS).toContain('copyOnSelect')
+ expect(resetPatch(['copyOnSelect'] as const)).toEqual({ copyOnSelect: false })
+ })
+
// A global "reset everything" would empty these; per-section lists must never reach them.
it.each(['claudeAccounts', 'customAgents', 'seenOnboarding', 'phoneAccessEnabled'])(
'never resets %s',
diff --git a/src/renderer/lib/settingsReset.ts b/src/renderer/lib/settingsReset.ts
index 9fea05a57..1c0f4a384 100644
--- a/src/renderer/lib/settingsReset.ts
+++ b/src/renderer/lib/settingsReset.ts
@@ -15,6 +15,7 @@ export const TERMINAL_RESET_KEYS = [
'fontFamily',
'fontSize',
'terminalWordSeparator',
+ 'copyOnSelect',
'fontWeight',
'fontWeightBold',
'drawBoldTextInBrightColors',
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 0784f3249..0d2cc9590 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -38,6 +38,7 @@ import { LocalTransport } from '../terminal/local-transport'
import { clipboardImages, droppedPaths, pasteHasText, pastedFiles } from '../terminal/file-drop'
import type { TerminalTransport } from '../terminal/transport'
import { guardMiddleClickPaste } from '../terminal/middle-click'
+import { attachCopyOnSelect } from '../terminal/copy-on-select'
import { patchTerminalScale } from '../terminal/scale-fix'
import { focusedNodeId, subscribeFocusedNode, focusSurfaceEl } from '../state/focusNode'
import { parseOsc52 } from '../terminal/osc52'
@@ -3388,6 +3389,26 @@ export function TerminalNode({
// `!parked` so nothing is wired twice.
const cleanups: Array<() => void> = parked ? parked.cleanups : []
+ // Copy-on-select (issue #759). REGISTERED ONCE, at construction, and disposed WITH THE TERMINAL
+ // — the OSC 52 handler's lifecycle, not a per-mount one: its only persistent listener lives on
+ // `term.element`, which travels with the xterm across a park/adopt, so re-attaching on adopt
+ // would stack a second copy per remount. `cleanups` is exactly the right owner — carried over
+ // by a park, run only on the final teardown (both `disposeParked` and the real-teardown branch
+ // below). Both deps are read at EVENT time, never captured: the setting via the store (a
+ // toggle applies to every open terminal on its next drag, parked ones included), and the
+ // clipboard via the QUIET path (a failure toast per drag would be unusable). No `Copied` pill:
+ // that pill exists because tmux copy-mode CLEARS the highlight as it copies; an xterm
+ // selection stays highlighted, so there is no "did it copy?" doubt to answer, and on the
+ // quiet path the pill would claim success for a write that may have failed.
+ if (!parked) {
+ cleanups.push(
+ attachCopyOnSelect(term, {
+ enabled: () => useSettings.getState().settings.copyOnSelect,
+ write: (text) => window.nodeTerminal.clipboard.writeText(text, { quiet: true })
+ })
+ )
+ }
+
// Agent state (busy/idle/attention) comes from the agent's own hooks via the
// agent:status IPC (handled centrally in Canvas) — not from parsing the output here.
// We only surface the conversation topic from the terminal title, when the agent sets one.
diff --git a/src/renderer/terminal/copy-on-select.test.ts b/src/renderer/terminal/copy-on-select.test.ts
new file mode 100644
index 000000000..fbfc89f6b
--- /dev/null
+++ b/src/renderer/terminal/copy-on-select.test.ts
@@ -0,0 +1,317 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ attachCopyOnSelect,
+ xtermOwnsMouseDown,
+ type CopyOnSelectTerminal
+} from './copy-on-select'
+
+/**
+ * Issue #759: a `copyOnSelect` setting. The rule is "a COMPLETED MOUSE selection that xterm owns
+ * lands on the clipboard" — not "every selection change": the search addon calls
+ * `Terminal.select()` while the user steps through hits, and that must never touch the clipboard.
+ */
+describe('xtermOwnsMouseDown', () => {
+ const down = (init: MouseEventInit): MouseEvent => new MouseEvent('mousedown', init)
+
+ it('owns a plain left press when no app is tracking the mouse', () => {
+ expect(xtermOwnsMouseDown(down({ button: 0 }), 'none', { isMac: true, optionForces: true })).toBe(true)
+ expect(xtermOwnsMouseDown(down({ button: 0 }), 'none', { isMac: false, optionForces: true })).toBe(true)
+ })
+
+ it('never owns another button (right-click-selects-word is a context-menu gesture)', () => {
+ for (const button of [1, 2]) {
+ expect(xtermOwnsMouseDown(down({ button }), 'none', { isMac: true, optionForces: true })).toBe(false)
+ }
+ })
+
+ it('does not own a plain press while an app tracks the mouse — the report goes to the pty', () => {
+ expect(xtermOwnsMouseDown(down({ button: 0 }), 'vt200', { isMac: true, optionForces: true })).toBe(false)
+ expect(xtermOwnsMouseDown(down({ button: 0 }), 'any', { isMac: false, optionForces: true })).toBe(false)
+ })
+
+ it('owns a FORCED selection inside a mouse-tracking app: Option on macOS, Shift elsewhere', () => {
+ expect(
+ xtermOwnsMouseDown(down({ button: 0, altKey: true }), 'vt200', { isMac: true, optionForces: true })
+ ).toBe(true)
+ expect(
+ xtermOwnsMouseDown(down({ button: 0, shiftKey: true }), 'vt200', { isMac: false, optionForces: true })
+ ).toBe(true)
+ // xterm 5.5 `shouldForceSelection`: Shift does not force on macOS, Option only when the option is set.
+ expect(
+ xtermOwnsMouseDown(down({ button: 0, shiftKey: true }), 'vt200', { isMac: true, optionForces: true })
+ ).toBe(false)
+ expect(
+ xtermOwnsMouseDown(down({ button: 0, altKey: true }), 'vt200', { isMac: true, optionForces: false })
+ ).toBe(false)
+ })
+})
+
+describe('attachCopyOnSelect', () => {
+ interface Fake {
+ term: CopyOnSelectTerminal & { selection: string; tracking: CopyOnSelectTerminal['modes']['mouseTrackingMode'] }
+ element: HTMLElement
+ screen: HTMLElement
+ write: ReturnType<typeof vi.fn>
+ setEnabled: (v: boolean) => void
+ dispose: () => void
+ }
+ const disposers: Array<() => void> = []
+
+ beforeEach(() => {
+ vi.useFakeTimers()
+ })
+ afterEach(() => {
+ while (disposers.length > 0) disposers.pop()?.()
+ document.body.innerHTML = ''
+ vi.useRealTimers()
+ })
+
+ function mount(opts: { enabled?: boolean; isMac?: boolean } = {}): Fake {
+ const element = document.createElement('div')
+ // Stands in for xterm's screen, the usual event target inside `term.element`.
+ const screen = document.createElement('div')
+ element.appendChild(screen)
+ document.body.appendChild(element)
+ let enabled = opts.enabled ?? true
+ const term = {
+ selection: '',
+ tracking: 'none' as CopyOnSelectTerminal['modes']['mouseTrackingMode'],
+ element,
+ get modes() {
+ return { mouseTrackingMode: term.tracking }
+ },
+ options: { macOptionClickForcesSelection: true },
+ hasSelection: () => term.selection.length > 0,
+ getSelection: () => term.selection
+ }
+ const write = vi.fn()
+ const dispose = attachCopyOnSelect(term, {
+ enabled: () => enabled,
+ write,
+ isMac: opts.isMac ?? true
+ })
+ disposers.push(dispose)
+ return { term, element, screen, write, setEnabled: (v) => (enabled = v), dispose }
+ }
+
+ function mouse(target: EventTarget, type: 'mousedown' | 'mouseup', init: MouseEventInit = {}): void {
+ target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, button: 0, ...init }))
+ }
+
+ /** A drag: press inside, xterm builds the selection, release at `upTarget`, timers flush. */
+ function drag(f: Fake, text: string, upTarget: EventTarget = f.screen, init: MouseEventInit = {}): void {
+ mouse(f.screen, 'mousedown', init)
+ f.term.selection = text
+ mouse(upTarget, 'mouseup', init)
+ vi.runAllTimers()
+ }
+
+ it('copies a completed mouse selection', () => {
+ const f = mount()
+ drag(f, 'hello world')
+ expect(f.write).toHaveBeenCalledTimes(1)
+ expect(f.write).toHaveBeenCalledWith('hello world')
+ })
+
+ it('reads the selection AFTER xterm finalised it on the same mouseup', () => {
+ // xterm's SelectionService finalises on a DOCUMENT bubble-phase mouseup listener it adds on
+ // mousedown. The helper listens on the window in the CAPTURE phase — i.e. before xterm — so it
+ // must defer its read, or it would see the selection as it was before the release.
+ const f = mount()
+ const xtermMouseUp = (): void => {
+ f.term.selection = 'finalised on mouseup'
+ }
+ document.addEventListener('mouseup', xtermMouseUp)
+ try {
+ mouse(f.screen, 'mousedown')
+ mouse(f.screen, 'mouseup')
+ expect(f.write).not.toHaveBeenCalled()
+ vi.runAllTimers()
+ expect(f.write).toHaveBeenCalledWith('finalised on mouseup')
+ } finally {
+ document.removeEventListener('mouseup', xtermMouseUp)
+ }
+ })
+
+ it('does nothing while the setting is off', () => {
+ const f = mount({ enabled: false })
+ drag(f, 'hello')
+ expect(f.write).not.toHaveBeenCalled()
+ })
+
+ it('never writes an empty selection (a plain click clears it)', () => {
+ const f = mount()
+ drag(f, '')
+ expect(f.write).not.toHaveBeenCalled()
+ })
+
+ it('ignores a programmatic selection — no mousedown in the terminal, no copy', () => {
+ // The search addon's `Terminal.select()` sets a selection with no gesture at all; a later
+ // release anywhere in the window must not sweep it onto the clipboard.
+ const f = mount()
+ f.term.selection = 'search hit'
+ mouse(document.body, 'mouseup')
+ vi.runAllTimers()
+ expect(f.write).not.toHaveBeenCalled()
+ })
+
+ it('copies when the drag is released OUTSIDE the terminal', () => {
+ const f = mount()
+ const elsewhere = document.createElement('div')
+ document.body.appendChild(elsewhere)
+ drag(f, 'overshot the node', elsewhere)
+ expect(f.write).toHaveBeenCalledWith('overshot the node')
+ })
+
+ it('ignores a gesture that STARTED outside the terminal', () => {
+ const f = mount()
+ const elsewhere = document.createElement('div')
+ document.body.appendChild(elsewhere)
+ mouse(elsewhere, 'mousedown')
+ f.term.selection = 'left over'
+ mouse(f.screen, 'mouseup')
+ vi.runAllTimers()
+ expect(f.write).not.toHaveBeenCalled()
+ })
+
+ it('copies each completed gesture once, and a stray later mouseup copies nothing', () => {
+ const f = mount()
+ drag(f, 'one')
+ // The pending release listener was one-shot: a release with no new press is not a gesture.
+ mouse(document.body, 'mouseup')
+ vi.runAllTimers()
+ expect(f.write).toHaveBeenCalledTimes(1)
+ })
+
+ it('cancels a gesture abandoned by leaving the window — a later unrelated release copies nothing', () => {
+ // Press in the terminal, switch windows with the button held, release in the other app: this
+ // window never sees that mouseup. Without a cancel on blur the armed listener survives, and the
+ // next click anywhere back here would copy whatever is selected THEN — a search hit included.
+ const f = mount()
+ mouse(f.screen, 'mousedown')
+ window.dispatchEvent(new Event('blur'))
+ f.term.selection = 'search hit'
+ mouse(document.body, 'mouseup')
+ vi.runAllTimers()
+ expect(f.write).not.toHaveBeenCalled()
+ })
+
+ it('cancels a gesture whose release was lost when the NEXT press comes — anywhere', () => {
+ // The release of the first gesture never arrived (outside the window, focus kept). A later press
+ // that is not a new owned press here — a toolbar click, a plain click in a mouse-tracking
+ // terminal — must disarm it, or its own release would copy the stale selection.
+ const f = mount()
+ mouse(f.screen, 'mousedown')
+ f.term.selection = 'stale highlight'
+ const toolbar = document.createElement('button')
+ document.body.appendChild(toolbar)
+ mouse(toolbar, 'mousedown')
+ mouse(toolbar, 'mouseup')
+ vi.runAllTimers()
+ expect(f.write).not.toHaveBeenCalled()
+ })
+
+ it('a new owned press re-arms cleanly after a lost release, and copies once', () => {
+ const f = mount()
+ mouse(f.screen, 'mousedown')
+ drag(f, 'second drag')
+ expect(f.write).toHaveBeenCalledTimes(1)
+ expect(f.write).toHaveBeenCalledWith('second drag')
+ })
+
+ it('a right or middle button release during a left drag does not complete it', () => {
+ const f = mount()
+ mouse(f.screen, 'mousedown')
+ f.term.selection = 'partial'
+ mouse(f.screen, 'mouseup', { button: 2 })
+ vi.runAllTimers()
+ expect(f.write).not.toHaveBeenCalled()
+ f.term.selection = 'whole drag'
+ mouse(f.screen, 'mouseup')
+ vi.runAllTimers()
+ expect(f.write).toHaveBeenCalledTimes(1)
+ expect(f.write).toHaveBeenCalledWith('whole drag')
+ })
+
+ it('does not re-copy a stale selection when an app owns the mouse (tmux copy-mode drag)', () => {
+ // Under tmux with mouse ON a plain drag is tmux's, which copies via OSC 52 on release. An older
+ // xterm selection still on screen must not overwrite that copy a tick later.
+ const f = mount()
+ f.term.selection = 'stale forced selection'
+ f.term.tracking = 'vt200'
+ mouse(f.screen, 'mousedown')
+ mouse(f.screen, 'mouseup')
+ vi.runAllTimers()
+ expect(f.write).not.toHaveBeenCalled()
+ })
+
+ it('copies a forced (Option) selection inside a mouse-tracking app — deliberate', () => {
+ const f = mount({ isMac: true })
+ f.term.tracking = 'vt200'
+ drag(f, 'forced', f.screen, { altKey: true })
+ expect(f.write).toHaveBeenCalledWith('forced')
+ })
+
+ it('reads the setting LIVE, so a toggle applies to the next gesture', () => {
+ const f = mount({ enabled: false })
+ drag(f, 'before')
+ expect(f.write).not.toHaveBeenCalled()
+ f.setEnabled(true)
+ drag(f, 'after')
+ expect(f.write).toHaveBeenCalledWith('after')
+ f.setEnabled(false)
+ drag(f, 'off again')
+ expect(f.write).toHaveBeenCalledTimes(1)
+ })
+
+ it('honours a toggle-off that lands mid-gesture', () => {
+ const f = mount()
+ mouse(f.screen, 'mousedown')
+ f.term.selection = 'text'
+ f.setEnabled(false)
+ mouse(f.screen, 'mouseup')
+ vi.runAllTimers()
+ expect(f.write).not.toHaveBeenCalled()
+ })
+
+ it('dispose removes every listener, including a gesture in flight', () => {
+ const f = mount()
+ const removeSpy = vi.spyOn(window, 'removeEventListener')
+ mouse(f.screen, 'mousedown')
+ f.term.selection = 'text'
+ f.dispose()
+ expect(removeSpy).toHaveBeenCalledWith('mouseup', expect.any(Function), true)
+ removeSpy.mockRestore()
+ mouse(f.screen, 'mouseup')
+ vi.runAllTimers()
+ drag(f, 'after dispose')
+ expect(f.write).not.toHaveBeenCalled()
+ })
+
+ it('dispose cancels a read already scheduled for the release', () => {
+ const f = mount()
+ mouse(f.screen, 'mousedown')
+ f.term.selection = 'text'
+ mouse(f.screen, 'mouseup')
+ f.dispose()
+ vi.runAllTimers()
+ expect(f.write).not.toHaveBeenCalled()
+ })
+
+ it('a terminal with no element (never opened) attaches nothing and disposes cleanly', () => {
+ const write = vi.fn()
+ const dispose = attachCopyOnSelect(
+ {
+ element: undefined,
+ modes: { mouseTrackingMode: 'none' },
+ options: {},
+ hasSelection: () => true,
+ getSelection: () => 'x'
+ },
+ { enabled: () => true, write, isMac: true }
+ )
+ expect(() => dispose()).not.toThrow()
+ expect(write).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/renderer/terminal/copy-on-select.ts b/src/renderer/terminal/copy-on-select.ts
new file mode 100644
index 000000000..9c7c28f7c
--- /dev/null
+++ b/src/renderer/terminal/copy-on-select.ts
@@ -0,0 +1,159 @@
+import type { Terminal } from '@xterm/xterm'
+import { isMacPlatform } from '@shared/platform-utils'
+
+/**
+ * Copy-on-select (issue #759): when the `copyOnSelect` setting is on, a COMPLETED MOUSE selection
+ * that xterm owns lands on the system clipboard.
+ *
+ * A sibling of `terminal-config.ts`, not part of it: that module is pure appearance decisions that
+ * flow into xterm OPTIONS, and this is behaviour attached to a live `Terminal` with the clipboard
+ * bridge injected. It exists as one helper so the canvas node (`TerminalNode`) and the kanban modal
+ * (`ModalTerminal`) cannot drift apart; the settings preview (`TerminalPreview`) deliberately does
+ * NOT call it — it is a sample, not a session, and `disableStdin` does not stop a mouse selection.
+ *
+ * WHERE THIS ACTUALLY APPLIES. On macOS/Linux every session runs under tmux with its mouse ON, so a
+ * plain drag is tmux copy-mode, which already reaches the clipboard through OSC 52 (the handler in
+ * TerminalNode) — xterm owns the selection there only for a FORCED selection (Option-drag on macOS,
+ * see below). On Windows there is no tmux (the session-host backend, `pty-manager.ts`), so a plain
+ * drag IS an xterm selection unless the running app enabled mouse tracking — that is the case the
+ * issue was filed for. Either way this cannot copy a selection an app draws itself (a TUI that
+ * captures the mouse and highlights its own text), and it does not touch OSC 52 copies, which
+ * arrive independently of this setting.
+ *
+ * WHICH SELECTIONS COUNT — and why this is not an `onSelectionChange` subscription. That event
+ * also fires for PROGRAMMATIC selections (the search addon calls `Terminal.select()` for every hit
+ * the user steps through) and on a clear. So the trigger is the gesture instead: a primary-button
+ * press inside `term.element` that xterm's own SelectionService takes (`xtermOwnsMouseDown`),
+ * followed by a release ANYWHERE in the window — a drag very often overshoots the node, and xterm
+ * itself listens for that release on the document. Double/triple-click word/line selection is the
+ * same gesture with `detail` 2/3 and is covered for free. xterm 5.5.0 has no public
+ * "selection finished" event and no `copyOnSelect` option, hence the DOM listeners.
+ *
+ * ORDERING, verified against xterm 5.5.0 `SelectionService`: on mousedown it adds a DOCUMENT
+ * bubble-phase `mouseup` listener and finalises the selection there (`_handleMouseUp` →
+ * `_fireEventIfSelectionChanged`). Our release listener is on the WINDOW in the CAPTURE phase (so
+ * nothing below can stop it), i.e. it runs BEFORE xterm's. The read is therefore deferred with a
+ * macrotask (`setTimeout 0`) — NOT `queueMicrotask`: for a real user event the microtask
+ * checkpoint runs between listener callbacks, which would still be before xterm's document
+ * listener.
+ *
+ * FORCED SELECTIONS COPY — intentionally. Inside an app that tracks the mouse, xterm still selects
+ * when the gesture is forced (`macOptionClickForcesSelection` + Option on macOS, Shift elsewhere);
+ * that selection is exactly as deliberate as a plain drag in a shell, so it copies too. The
+ * flip side is equally deliberate: a plain press while an app tracks the mouse is NOT ours, so a
+ * stale xterm selection still on screen is never re-copied over the top of what tmux just put on
+ * the clipboard through OSC 52.
+ *
+ * NEVER AN EMPTY WRITE: a plain click clears the selection; writing `''` would wipe the clipboard.
+ *
+ * `enabled` is read LIVE at press AND at read time, so toggling the setting applies to the next
+ * gesture on every open terminal without recreating any of them.
+ */
+
+/** The slice of an xterm `Terminal` this helper reads — narrow, so tests need no real xterm. */
+export interface CopyOnSelectTerminal {
+ readonly element: HTMLElement | undefined
+ readonly modes: { readonly mouseTrackingMode: Terminal['modes']['mouseTrackingMode'] }
+ readonly options: { readonly macOptionClickForcesSelection?: boolean }
+ hasSelection(): boolean
+ getSelection(): string
+}
+
+export interface CopyOnSelectDeps {
+ /** The live setting. Read at event time, never captured. */
+ enabled: () => boolean
+ /** Writes the system clipboard. Callers pass the bridge's QUIET path (no failure toast per drag). */
+ write: (text: string) => void
+ /** Defaults to `isMacPlatform()` — the same navigator test xterm's own `Browser.isMac` makes. */
+ isMac?: boolean
+}
+
+/**
+ * Does xterm's SelectionService take this mousedown? Mirrors xterm 5.5.0 `handleMouseDown` +
+ * `shouldForceSelection`: primary button only; always when no app tracks the mouse (the service is
+ * enabled); otherwise only when forced — Option (with `macOptionClickForcesSelection`) on macOS,
+ * Shift everywhere else.
+ */
+export function xtermOwnsMouseDown(
+ e: MouseEvent,
+ mouseTrackingMode: CopyOnSelectTerminal['modes']['mouseTrackingMode'],
+ platform: { isMac: boolean; optionForces: boolean }
+): boolean {
+ if (e.button !== 0) return false
+ if (mouseTrackingMode === 'none') return true
+ return platform.isMac ? e.altKey && platform.optionForces : e.shiftKey
+}
+
+/**
+ * Attach copy-on-select to an OPENED terminal. Returns the disposer.
+ *
+ * Only ONE listener persists — the capture-phase `mousedown` on `term.element`, which travels with
+ * the xterm instance across a park/adopt exactly like `installLinkClickFallback`. Capture phase
+ * because xterm calls `stopPropagation` on a forced mousedown (so the press never reaches the pty)
+ * from its bubble listener on that same element. The window `mouseup` listener exists only while
+ * a gesture is in flight (one-shot, together with the `blur` / `mousedown` listeners that cancel a
+ * gesture whose release was lost — see `disarm`), so nothing window-level outlives its gesture.
+ */
+export function attachCopyOnSelect(term: CopyOnSelectTerminal, deps: CopyOnSelectDeps): () => void {
+ const element = term.element
+ if (!element) return () => {}
+ const win = element.ownerDocument.defaultView ?? window
+ const isMac = deps.isMac ?? isMacPlatform()
+ let pendingUp: ((e: MouseEvent) => void) | null = null
+ let readTimer: ReturnType<typeof setTimeout> | null = null
+
+ // Ends an armed gesture WITHOUT a write. Three ways a gesture can lose its release, and each is a
+ // trigger here, because an armed listener that outlives its gesture would copy whatever is
+ // selected when some LATER release arrives — a stale highlight or a search hit:
+ // - `blur`: button held, released in another app;
+ // - any later `mousedown` in the window: the previous release was lost somewhere else (a new
+ // owned press here re-arms right after, since the window capture listener runs before the
+ // element's);
+ // - dispose.
+ const disarm = (): void => {
+ if (pendingUp) win.removeEventListener('mouseup', pendingUp, true)
+ pendingUp = null
+ win.removeEventListener('blur', disarm)
+ win.removeEventListener('mousedown', disarm, true)
+ }
+
+ const clearPending = (): void => {
+ disarm()
+ if (readTimer !== null) clearTimeout(readTimer)
+ readTimer = null
+ }
+
+ const onDown = (e: MouseEvent): void => {
+ if (!deps.enabled()) return
+ const owned = xtermOwnsMouseDown(e, term.modes.mouseTrackingMode, {
+ isMac,
+ optionForces: term.options.macOptionClickForcesSelection === true
+ })
+ if (!owned) return
+ clearPending()
+ const onUp = (up: MouseEvent): void => {
+ // Only the PRIMARY release completes the gesture: a right/middle release mid-drag would copy
+ // the partial selection and drop the real one.
+ if (up.button !== 0) return
+ disarm()
+ readTimer = setTimeout(() => {
+ readTimer = null
+ if (!deps.enabled() || !term.hasSelection()) return
+ const text = term.getSelection()
+ if (text) deps.write(text)
+ }, 0)
+ }
+ pendingUp = onUp
+ win.addEventListener('mouseup', onUp, true)
+ win.addEventListener('blur', disarm)
+ // Added during THIS press's element-capture phase, so it cannot fire for this press: the
+ // window's capture phase has already passed.
+ win.addEventListener('mousedown', disarm, true)
+ }
+
+ element.addEventListener('mousedown', onDown, true)
+ return () => {
+ element.removeEventListener('mousedown', onDown, true)
+ clearPending()
+ }
+}
diff --git a/src/shared/default-settings.test.ts b/src/shared/default-settings.test.ts
index e57058475..2c34c6f86 100644
--- a/src/shared/default-settings.test.ts
+++ b/src/shared/default-settings.test.ts
@@ -31,6 +31,11 @@ describe('DEFAULT_SETTINGS', () => {
expect(DEFAULT_SETTINGS.autoHideFinishedSubagentCards).toBe(false)
})
+ it('ships copy-on-select OFF, so an update never starts rewriting the clipboard', () => {
+ // Issue #759: opt-in on purpose — silently changing what is on the clipboard is a surprise.
+ expect(DEFAULT_SETTINGS.copyOnSelect).toBe(false)
+ })
+
it('keeps common identifier and path characters inside terminal word selections', () => {
expect(DEFAULT_SETTINGS.terminalWordSeparator).not.toMatch(/[-_/.]/)
})
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 8abc7457b..e27de074e 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1467,8 +1467,18 @@ export interface DialogApi {
selectFile(): Promise<string | null>
}
+export interface ClipboardWriteOptions {
+ /**
+ * Never raise a failure toast. For writes the user did not explicitly ask for as a copy — today
+ * only copy-on-select (issue #759), which writes on every completed drag, where a toast per drag
+ * would be unusable. The write still tries every route; only the banner is withheld. The desktop
+ * preload's write is fire-and-forget IPC with no failure surface at all, so it ignores this.
+ */
+ quiet?: boolean
+}
+
export interface ClipboardApi {
- writeText(text: string): void
+ writeText(text: string, opts?: ClipboardWriteOptions): void
/** Copy local files so Finder and other file-aware macOS apps can paste them. */
writeFiles(paths: string[]): Promise<boolean>
}
@@ -1851,6 +1861,19 @@ export interface Settings {
* click drops whatever was last selected anywhere on the machine into a live agent prompt.
*/
terminalMiddleClickPaste: boolean
+ /**
+ * Copy a completed MOUSE selection that the terminal emulator (xterm) owns to the system
+ * clipboard (issue #759). OFF by default: it preserves the explicit-copy behaviour, and silently
+ * changing what is on the clipboard is a surprise worth opting into.
+ *
+ * Scope, stated honestly: it covers only selections xterm makes itself — a drag, double/triple
+ * click, or a FORCED selection (Option-drag on macOS, Shift-drag elsewhere) inside an app that
+ * tracks the mouse. It cannot copy a selection an app draws itself, and OSC 52 copies (tmux
+ * copy-mode, vim `"+y`) reach the clipboard whether this is on or off. Programmatic selections
+ * (find-bar hits) never copy. Read live, so a toggle applies to the next drag on every open
+ * terminal. Logic: `renderer/terminal/copy-on-select.ts`.
+ */
+ copyOnSelect: boolean
/** Plain mouse wheel zooms the canvas (no Cmd/Ctrl needed). On macOS a two-finger trackpad
* scroll keeps panning independently (see canvas/wheel-gesture.ts), so mouse and trackpad
* coexist; elsewhere this still trades away scroll-to-pan, so it stays opt-in. */
@@ -2221,6 +2244,7 @@ export const DEFAULT_SETTINGS: Settings = {
openMarkdownPreview: true,
openMarkdownPreviewMigrated: true,
terminalMiddleClickPaste: false,
+ copyOnSelect: false,
wheelZoom: false,
wheelZoomSpeed: 1,
trackpadPan: true,