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.

fix(bridge): clipboard fallback never leaks its scratch textarea or steals focus

enes68b4696fbf02
diff --git a/src/renderer/bridge/stubs.test.ts b/src/renderer/bridge/stubs.test.ts
index 91c525a38..cd63bb6d7 100644
--- a/src/renderer/bridge/stubs.test.ts
+++ b/src/renderer/bridge/stubs.test.ts
@@ -62,20 +62,31 @@ describe('bridge stubs', () => {
})
/** A minimal `document` for the hidden-textarea copy fallback: vitest runs in the node
- * environment, so there is no DOM to lean on. `execCommand` is the knob each test turns. */
+ * environment, so there is no DOM to lean on. `execCommand` is the knob each test turns.
+ * It models the two things reality has and a naive fake does not: `select()` MOVES FOCUS
+ * (activeElement becomes the scratch textarea), and `execCommand` may THROW (Firefox has
+ * historically thrown NS_ERROR_FAILURE) — the two gaps that hid the leak/focus bugs. */
function fakeDocument(execCommand: () => boolean) {
- const textarea = {
- value: '',
- style: {} as Record<string, string>,
- setAttribute: vi.fn(),
- select: vi.fn()
- }
+ // The element that had focus before the copy — xterm's helper textarea, in reality.
+ const previouslyFocused = { focus: vi.fn() }
const doc = {
+ activeElement: previouslyFocused as unknown as { focus: () => void },
createElement: vi.fn(() => textarea),
body: { appendChild: vi.fn(), removeChild: vi.fn() },
execCommand: vi.fn(execCommand)
}
- return { doc, textarea }
+ const textarea = {
+ value: '',
+ style: {} as Record<string, string>,
+ setAttribute: vi.fn(),
+ // select() focuses the scratch textarea, exactly as in a real browser
+ select: vi.fn(() => {
+ doc.activeElement = textarea as unknown as { focus: () => void }
+ }),
+ focus: vi.fn(),
+ remove: vi.fn()
+ }
+ return { doc, textarea, previouslyFocused }
}
describe('bridge clipboard', () => {
@@ -96,7 +107,39 @@ describe('bridge clipboard', () => {
expect(doc.execCommand).toHaveBeenCalledWith('copy')
expect(textarea.value).toBe('hi')
// the scratch textarea must not be left behind in the DOM
- expect(doc.body.removeChild).toHaveBeenCalledWith(textarea)
+ expect(textarea.remove).toHaveBeenCalled()
+ })
+
+ it('removes the scratch textarea even when execCommand THROWS (no leaked node)', () => {
+ const { doc, textarea } = fakeDocument(() => {
+ throw new Error('NS_ERROR_FAILURE')
+ })
+ vi.stubGlobal('navigator', {})
+ vi.stubGlobal('document', doc)
+ vi.stubGlobal('window', { dispatchEvent: vi.fn(), isSecureContext: false })
+ expect(() => buildStubApi().clipboard.writeText('hi')).not.toThrow()
+ // an invisible, focused, position:fixed textarea left in <body> would eat every keystroke
+ expect(textarea.remove).toHaveBeenCalled()
+ })
+
+ it('restores focus to the previously-focused element after a successful fallback copy', () => {
+ const { doc, previouslyFocused } = fakeDocument(() => true)
+ vi.stubGlobal('navigator', {})
+ vi.stubGlobal('document', doc)
+ buildStubApi().clipboard.writeText('hi')
+ // without this the terminal goes deaf: activeElement falls back to <body>
+ expect(previouslyFocused.focus).toHaveBeenCalledTimes(1)
+ })
+
+ it('restores focus even when the copy fails', () => {
+ const { doc, previouslyFocused } = fakeDocument(() => {
+ throw new Error('NS_ERROR_FAILURE')
+ })
+ vi.stubGlobal('navigator', {})
+ vi.stubGlobal('document', doc)
+ vi.stubGlobal('window', { dispatchEvent: vi.fn(), isSecureContext: false })
+ buildStubApi().clipboard.writeText('hi')
+ expect(previouslyFocused.focus).toHaveBeenCalledTimes(1)
})
it('surfaces a toast when even execCommand cannot copy (never silent)', () => {
@@ -104,7 +147,7 @@ describe('bridge clipboard', () => {
const dispatchEvent = vi.fn()
vi.stubGlobal('navigator', {})
vi.stubGlobal('document', doc)
- vi.stubGlobal('window', { dispatchEvent })
+ vi.stubGlobal('window', { dispatchEvent, isSecureContext: false })
buildStubApi().clipboard.writeText('hi')
expect(dispatchEvent).toHaveBeenCalledTimes(1)
const ev = dispatchEvent.mock.calls[0][0] as CustomEvent<{ kind: string; message: string }>
@@ -112,4 +155,16 @@ describe('bridge clipboard', () => {
expect(ev.detail.kind).toBe('error')
expect(ev.detail.message).toMatch(/http/i)
})
+
+ it('does not blame plain http when the failure happens in a secure context', () => {
+ const { doc } = fakeDocument(() => false)
+ const dispatchEvent = vi.fn()
+ vi.stubGlobal('navigator', {})
+ vi.stubGlobal('document', doc)
+ vi.stubGlobal('window', { dispatchEvent, isSecureContext: true })
+ buildStubApi().clipboard.writeText('hi')
+ const ev = dispatchEvent.mock.calls[0][0] as CustomEvent<{ message: string }>
+ expect(ev.detail.message).not.toMatch(/plain http/i)
+ expect(ev.detail.message).toMatch(/copy/i)
+ })
})
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 49af552f2..6e4267877 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -38,34 +38,50 @@ const noop = (): void => {}
const pnoop = (): Promise<void> => Promise.resolve()
/** Copy without the Clipboard API (non-secure context): a hidden textarea + execCommand('copy').
- * Only works inside a user gesture — which is exactly where copy is triggered from (keydown).
- * Returns false when even that fails, so the caller can surface it rather than swallow it. */
+ * Browsers only honor it inside a user gesture. That holds for the copy shortcut and the click-
+ * driven copy buttons, but NOT for the OSC 52 path (`TerminalNode.tsx` — driven by terminal
+ * OUTPUT, e.g. `vim "+y`, with no user activation): over plain http that one always fails and
+ * lands in the error banner below. Returns false when the copy fails, so the caller surfaces it
+ * rather than swallowing it — never silent.
+ *
+ * Cleanup is in a `finally` on purpose: `select()`/`execCommand()` CAN throw (Firefox has thrown
+ * NS_ERROR_FAILURE on execCommand('copy')), and a leaked scratch textarea would be invisible,
+ * 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 {
+ const prev = document.activeElement as HTMLElement | null
+ let ta: HTMLTextAreaElement | undefined
try {
- const ta = document.createElement('textarea')
+ ta = document.createElement('textarea')
ta.value = text
ta.setAttribute('readonly', '')
ta.style.position = 'fixed'
ta.style.opacity = '0'
document.body.appendChild(ta)
ta.select()
- const ok = document.execCommand('copy')
- document.body.removeChild(ta)
- if (!ok) throw new Error('execCommand returned false')
+ if (!document.execCommand('copy')) throw new Error('execCommand returned false')
return true
} catch {
- // Surfacing beats silence: over plain http there is no way to copy, and the user needs to know
- // why nothing landed in their clipboard. Canvas listens for this event and shows a banner.
+ // 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
+ // failed too. Canvas listens for this event and shows a banner.
+ const secure = typeof window !== 'undefined' && window.isSecureContext
window.dispatchEvent(
new CustomEvent('nodeterm:toast', {
detail: {
kind: 'error',
- message:
- 'Copy failed — the browser blocks clipboard access over plain http. Use https or localhost.'
+ message: secure
+ ? 'Copy failed — the browser denied clipboard access. Click the page and try again.'
+ : 'Copy failed — the browser blocks clipboard access over plain http. Use https or localhost.'
}
})
)
return false
+ } finally {
+ ta?.remove()
+ prev?.focus?.()
}
}