Skip to content

The agent that grows with you

fix(webapp): copy without the Clipboard API on plain-HTTP origins

dokterdokff414fec246d
diff --git a/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsx b/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsx
index e7b9aebc9fd..e64aaff8b8d 100644
--- a/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsx
+++ b/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsx
@@ -33,6 +33,7 @@ import {
} from '@/components/ui/dropdown-menu'
import { Tip } from '@/components/ui/tooltip'
import { useI18n } from '@/i18n'
+import { writeClipboardText } from '@/lib/clipboard'
import {
runSessionControlAction,
type SessionControlAction,
@@ -136,7 +137,7 @@ export const SessionControlGoalSection = memo(function SessionControlGoalSection
const copyCriterionText = useCallback(
async (text: string) => {
try {
- await navigator.clipboard.writeText(text)
+ await writeClipboardText(text)
onFeedback(null, ctrl.copySuccess)
} catch {
onFeedback(ctrl.copyFailure, null)
diff --git a/apps/desktop/src/components/desktop-install-overlay.tsx b/apps/desktop/src/components/desktop-install-overlay.tsx
index 0cc4d279faa..c6f77da58b2 100644
--- a/apps/desktop/src/components/desktop-install-overlay.tsx
+++ b/apps/desktop/src/components/desktop-install-overlay.tsx
@@ -15,6 +15,7 @@ import type {
DesktopBootstrapState
} from '@/global'
import { useI18n } from '@/i18n'
+import { writeClipboardText } from '@/lib/clipboard'
import { AlertCircle, ChevronDown, ChevronRight, Globe, iconSize, Loader2, Monitor } from '@/lib/icons'
import { capitalize } from '@/lib/text'
import { cn } from '@/lib/utils'
@@ -542,7 +543,7 @@ export function DesktopInstallOverlay({ enabled = true }: DesktopInstallOverlayP
<div className="mt-2 flex items-center gap-2">
<Button
onClick={() => {
- void navigator.clipboard?.writeText(ups.installCommand).catch(() => {})
+ void writeClipboardText(ups.installCommand).catch(() => {})
}}
size="sm"
variant="secondary"
@@ -751,7 +752,7 @@ export function DesktopInstallOverlay({ enabled = true }: DesktopInstallOverlayP
const fullText = state.error ? `Error: ${state.error}\n\n${text}` : text
try {
- await navigator.clipboard.writeText(fullText)
+ await writeClipboardText(fullText)
setCopied(true)
window.setTimeout(() => setCopied(false), 1500)
} catch {
diff --git a/apps/desktop/src/lib/browser-clipboard.ts b/apps/desktop/src/lib/browser-clipboard.ts
index 854e04f2fbd..f2f65ca91cb 100644
--- a/apps/desktop/src/lib/browser-clipboard.ts
+++ b/apps/desktop/src/lib/browser-clipboard.ts
@@ -1,4 +1,5 @@
import { IMAGE_EXTENSION_BY_MIME } from '@/lib/browser-uploads'
+import { copyTextThroughSelection } from '@/lib/clipboard'
interface BrowserClipboardOptions {
/** Stores clipboard image bytes where the agent can read them. */
@@ -37,7 +38,8 @@ export function createBrowserClipboardBridge({
return ''
},
writeClipboard: async (text: string) => {
- if (!nativeWriteClipboard) {return false}
+ // No Clipboard API on an insecure origin: the same selection copy as writeClipboardText.
+ if (!nativeWriteClipboard) {return copyTextThroughSelection(text)}
await nativeWriteClipboard(text)
diff --git a/apps/desktop/src/lib/clipboard.test.ts b/apps/desktop/src/lib/clipboard.test.ts
index a48f9650f7c..e89a5aae1c1 100644
--- a/apps/desktop/src/lib/clipboard.test.ts
+++ b/apps/desktop/src/lib/clipboard.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { createBrowserClipboardBridge } from './browser-clipboard'
import { installClipboardShim, writeClipboardText } from './clipboard'
+import { copySvgAsPng } from './svg-image'
const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }
@@ -104,4 +105,75 @@ describe('writeClipboardText', () => {
await expect(writeClipboardText('payload')).rejects.toThrow('Clipboard write is unavailable')
})
+
+ // Safari does not focus a clicked button, so the dialog itself can hold focus when its Copy is clicked.
+ it.each(['a button in it', 'the dialog itself'])(
+ 'copies through a selection where an insecure origin has no Clipboard API, inside a focus trap while %s has focus',
+ async holder => {
+ document.documentElement.dataset.hermesDesktopHost = 'browser'
+ desktopWindow.hermesDesktop = createBrowserClipboardBridge({
+ saveBuffer: async () => ''
+ }) as Window['hermesDesktop']
+ installClipboardShim()
+ // A modal dialog that pulls focus back inside itself, as Radix's FocusScope does.
+ const dialog = document.body.appendChild(document.createElement('div'))
+ dialog.tabIndex = -1
+ const trigger = dialog.appendChild(document.createElement('button'))
+ const note = dialog.appendChild(document.createElement('p'))
+ note.textContent = 'selected before the copy'
+ const focused = holder === 'the dialog itself' ? dialog : trigger
+
+ const trap = (event: FocusEvent) => {
+ if (!dialog.contains(event.target as Node)) {
+ focused.focus()
+ }
+ }
+
+ document.addEventListener('focusin', trap)
+ focused.focus()
+ const copied: string[] = []
+ let copies = true
+
+ const execCommand = vi.fn((command: string) => {
+ const area = document.activeElement
+
+ copied.push(
+ area instanceof HTMLTextAreaElement
+ ? `${command}:${area.value.slice(area.selectionStart, area.selectionEnd)}`
+ : `${command} in ${area?.tagName}`
+ )
+ // A browser moves the document's selection into the textarea it selects; jsdom does not.
+ document.getSelection()!.removeAllRanges()
+
+ return copies
+ })
+
+ Object.defineProperty(document, 'execCommand', { configurable: true, value: execCommand })
+
+ try {
+ await writeClipboardText('copy me')
+ await copySvgAsPng('<svg/>')
+ // Copy path / Copy link call the bridge directly.
+ expect(await desktopWindow.hermesDesktop!.writeClipboard('/repo/file.ts')).toBe(true)
+ expect(copied).toEqual(['copy:copy me', 'copy:<svg/>', 'copy:/repo/file.ts'])
+ // A copy the browser refuses fails, and still gives back focus and the page's selection.
+ copies = false
+ document.getSelection()!.selectAllChildren(note)
+ let selected = ''
+ // jsdom collapses the selection on every focus(), which a browser does not do for a
+ // non-editable element: read it as focus comes back.
+ focused.addEventListener('focus', () => (selected = document.getSelection()!.toString()), { once: true })
+ await expect(writeClipboardText('refused')).rejects.toThrow('Clipboard API is unavailable')
+ expect(copied.at(-1)).toBe('copy:refused')
+ expect(document.querySelector('textarea')).toBeNull()
+ expect(document.activeElement).toBe(focused)
+ expect(selected).toBe('selected before the copy')
+ } finally {
+ Reflect.deleteProperty(document, 'execCommand')
+ document.removeEventListener('focusin', trap)
+ document.getSelection()!.removeAllRanges()
+ dialog.remove()
+ }
+ }
+ )
})
diff --git a/apps/desktop/src/lib/clipboard.ts b/apps/desktop/src/lib/clipboard.ts
index 7179b8499e7..bf2876b367a 100644
--- a/apps/desktop/src/lib/clipboard.ts
+++ b/apps/desktop/src/lib/clipboard.ts
@@ -3,10 +3,51 @@ import { isBrowserHostedDesktop } from '@/lib/platform'
// Primitives and CopyButton enter one policy, never nested fallback retries.
const nativeWrites = new WeakMap<Clipboard, Clipboard['writeText'] | undefined>()
+// Natively focusable elements (controls, links, embedded content): the textarea never goes inside one.
+const FOCUSABLE_LEAVES = 'a, area, audio, button, embed, iframe, input, object, select, summary, textarea, video'
+
+/** An insecure origin (a Webapp opened over plain HTTP from another machine) has no Clipboard API;
+ * the legacy copy command still works there, inside the click that asked for the copy. The
+ * textarea goes inside a focused element that holds focus through tabindex (a dialog, a menu or
+ * its item, maybe the trap's own root: Safari does not focus a clicked button), else beside the
+ * focused control or editor, so a dialog or menu that traps focus keeps it in scope and lets it
+ * take focus. True when the browser reports the copy done. */
+export function copyTextThroughSelection(text: string): boolean {
+ if (typeof document.execCommand !== 'function') {
+ return false
+ }
+
+ const active = document.activeElement
+ const focused = active instanceof HTMLElement && active !== document.body ? active : null
+ const selection = document.getSelection()
+ const ranges = Array.from({ length: selection?.rangeCount ?? 0 }, (_, index) => selection!.getRangeAt(index))
+ const area = document.createElement('textarea')
+ area.value = text
+ area.setAttribute('readonly', '')
+ area.style.cssText = 'position:fixed;top:0;left:0;width:1px;height:1px;padding:0;border:0;opacity:0'
+ const holds = focused && !focused.isContentEditable && !focused.matches(FOCUSABLE_LEAVES)
+ const scope = (holds ? focused : focused?.parentElement) ?? document.body
+ scope.append(area)
+ area.focus({ preventScroll: true })
+ area.select()
+ area.setSelectionRange(0, text.length)
+
+ try {
+ return document.execCommand('copy')
+ } catch {
+ return false
+ } finally {
+ area.remove()
+ selection?.removeAllRanges()
+ ranges.forEach(range => selection?.addRange(range))
+ focused?.focus({ preventScroll: true })
+ }
+}
+
// Electron writes through IPC first: the main process writes the clipboard even after the document
// loses focus (a portaled Radix menu), where the renderer's clipboard API refuses with "Write
// permission denied". The native API is the fallback. The browser-hosted Desktop has only the native
-// API; its bridge's writeClipboard calls that same API.
+// API; its bridge's writeClipboard calls that same API. Without it, both copy through a selection.
export async function writeClipboardText(text: string) {
if (!text) {
return
@@ -32,6 +73,10 @@ export async function writeClipboardText(text: string) {
}
if (!native) {
+ if (!ipc && copyTextThroughSelection(text)) {
+ return
+ }
+
throw new Error(ipc ? 'Clipboard write is unavailable' : 'Clipboard API is unavailable')
}
diff --git a/apps/desktop/src/lib/svg-image.ts b/apps/desktop/src/lib/svg-image.ts
index d5e8d759b1d..28bb3ab0a6e 100644
--- a/apps/desktop/src/lib/svg-image.ts
+++ b/apps/desktop/src/lib/svg-image.ts
@@ -2,6 +2,8 @@
// SVGs only (inline styles) — mermaid output qualifies. Falls back to copying
// the SVG markup as text where image clipboard writes aren't permitted.
+import { writeClipboardText } from '@/lib/clipboard'
+
// Mermaid emits width="100%" plus a viewBox. That percentage is not an
// intrinsic size: the zoom overlay's shrink-to-fit grid can collapse it, and
// parseFloat("100%") makes a 100px PNG. Replace percentage attrs with the
@@ -140,11 +142,16 @@ export function svgToPngBlob(svg: string, scale = 2): Promise<Blob> {
}
export async function copySvgAsPng(svg: string): Promise<void> {
+ // An insecure origin has no image clipboard: copy the markup while the click still counts.
+ if (!navigator.clipboard?.write || typeof ClipboardItem === 'undefined') {
+ return writeClipboardText(svg)
+ }
+
try {
const blob = await svgToPngBlob(svg)
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])
} catch {
- await navigator.clipboard.writeText(svg)
+ await writeClipboardText(svg)
}
}
diff --git a/apps/desktop/src/plugins/kanban/drawer.tsx b/apps/desktop/src/plugins/kanban/drawer.tsx
index a398c9f06b5..d5e80435158 100644
--- a/apps/desktop/src/plugins/kanban/drawer.tsx
+++ b/apps/desktop/src/plugins/kanban/drawer.tsx
@@ -33,7 +33,8 @@ import {
useMutation,
useQuery,
useQueryClient,
- useValue
+ useValue,
+ writeClipboardText
} from '@hermes/plugin-sdk'
import { type ReactNode, useEffect, useRef, useState } from 'react'
@@ -249,7 +250,7 @@ function Diagnostics({
} else if (action.kind === 'unblock') {
onUnblock()
} else if (action.kind === 'cli_hint') {
- void navigator.clipboard.writeText(String(action.payload?.command ?? action.label))
+ void writeClipboardText(String(action.payload?.command ?? action.label))
host.notify({ kind: 'info', message: k.commandCopied })
}
}
@@ -996,7 +997,7 @@ export function TaskDrawer({
<DropdownMenuContent align="end">
<DropdownMenuItem
onSelect={() => {
- void navigator.clipboard.writeText(task.id)
+ void writeClipboardText(task.id)
host.notify({ kind: 'info', message: k.copiedId(task.id) })
}}
>
@@ -1005,7 +1006,7 @@ export function TaskDrawer({
</DropdownMenuItem>
<DropdownMenuItem
onSelect={() => {
- void navigator.clipboard.writeText(task.title || task.id)
+ void writeClipboardText(task.title || task.id)
host.notify({ kind: 'info', message: k.copiedTitle })
}}
>
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index b4afb8b33d9..e88a75eeb87 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -1814,6 +1814,10 @@ export { type BudgetedLoop, type BudgetedLoopOptions, createBudgetedLoop } from
/** The blank transcript as a contribution area: claim the sessions you own and
* render what stands in the gap. Core's own splash keeps a fresh draft. */
export { CHAT_EMPTY_AREA, type ChatEmptyContribution, type ChatEmptyProps } from '@/lib/chat-empty'
+/** THE copy-to-clipboard path (CopyButton's): Electron's IPC first, the Clipboard API, and a
+ * selection copy where an insecure origin has no Clipboard API. Never call
+ * `navigator.clipboard.writeText` directly. */
+export { writeClipboardText } from '@/lib/clipboard'
/** THE confirm flow for guarded model switches — when a gateway model-switch
* RPC answers `confirm_required` (data-policy / expensive-model guard),
* route it through this shared applier instead of forking a per-surface
diff --git a/apps/desktop/src/store/onboarding.ts b/apps/desktop/src/store/onboarding.ts
index 0a224235a57..dade2006e92 100644
--- a/apps/desktop/src/store/onboarding.ts
+++ b/apps/desktop/src/store/onboarding.ts
@@ -16,6 +16,7 @@ import {
validateProviderCredential
} from '@/hermes'
import { translateNow } from '@/i18n'
+import { writeClipboardText } from '@/lib/clipboard'
import { restOfLongPollGap } from '@/lib/long-poll'
import { isProviderSetupErrorMessage } from '@/lib/provider-setup-errors'
import { evaluateRuntimeReadiness, type RuntimeReadinessResult } from '@/lib/runtime-readiness'
@@ -1125,7 +1126,7 @@ export function cancelOnboardingFlow() {
async function copyAndFlash(text: string, predicate: (flow: OnboardingFlow) => boolean) {
try {
- await navigator.clipboard.writeText(text)
+ await writeClipboardText(text)
} catch {
return
}