Skip to content

The agent that grows with you

fix(webapp): keep the browser's own menu on editables

dokterdokd0b35b5bb06f
diff --git a/apps/desktop/src/app/context-menu/app-context-menu.test.tsx b/apps/desktop/src/app/context-menu/app-context-menu.test.tsx
index b22ec81f7d6..77ca6e5e528 100644
--- a/apps/desktop/src/app/context-menu/app-context-menu.test.tsx
+++ b/apps/desktop/src/app/context-menu/app-context-menu.test.tsx
@@ -2,6 +2,7 @@ import { cleanup, createEvent, fireEvent, render, screen, waitFor } from '@testi
import { MemoryRouter } from 'react-router'
import { afterEach, describe, expect, it, vi } from 'vitest'
+import { FileEntryContextMenu, InlineRenameInput } from '@/app/right-sidebar/file-actions'
import { registerTerminalContextMenu } from '@/app/right-sidebar/terminal/terminal-context-menu'
import { DirectiveContent } from '@/components/assistant-ui/directive-text'
import { ContextMenu, ContextMenuTrigger, HERMES_CONTEXT_MENU_TRIGGER_ATTR } from '@/components/ui/context-menu'
@@ -224,6 +225,87 @@ describe('AppContextMenu', () => {
expect(event.defaultPrevented).toBe(false)
})
+ // The browser bridge has no contextMenuEdit (our Cut/Copy/Paste) and no spellcheck feed:
+ // only the browser's own menu has working edit verbs and spelling suggestions there.
+ it.each([
+ [
+ 'a field in a pane body',
+ '<div data-zone-body="t" data-slot="context-menu-trigger"><textarea>teh</textarea></div>',
+ 'textarea'
+ ],
+ ['the rich composer', '<div contenteditable="true" data-slot="composer-rich-input"><span>teh</span></div>', 'span'],
+ ['a link inside an editable', '<div contenteditable="true"><a href="https://example.com">link</a></div>', 'a']
+ ])('leaves the native menu on %s in the browser Webapp', (_name, html, selector) => {
+ installBridge()
+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'
+ mountMenu()
+ const host = attach(html)
+ // jsdom lacks the browser's isContentEditable.
+ host
+ .querySelectorAll('[contenteditable]')
+ .forEach(node => Object.defineProperty(node, 'isContentEditable', { value: true }))
+ const fallback = vi.fn()
+ host.addEventListener('contextmenu', fallback)
+ const field = host.querySelector(selector)!
+ const event = createEvent.contextMenu(field, { bubbles: true, cancelable: true })
+
+ fireEvent(field, event)
+
+ expect(event.defaultPrevented).toBe(false)
+ expect(fallback).not.toHaveBeenCalled()
+ expect($contextMenu.get()).toBeNull()
+ })
+
+ it('leaves the native menu on an inline file rename in the browser Webapp', () => {
+ installBridge()
+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'
+ render(
+ <MemoryRouter>
+ <AppContextMenu />
+ <FileEntryContextMenu isDirectory={false} name="notes.txt" path="/work/notes.txt">
+ <div>
+ <InlineRenameInput name="notes.txt" path="/work/notes.txt" />
+ </div>
+ </FileEntryContextMenu>
+ </MemoryRouter>
+ )
+ const input = screen.getByRole('textbox', { name: 'New name' })
+ const event = createEvent.contextMenu(input, { bubbles: true, cancelable: true })
+
+ fireEvent(input, event)
+
+ expect(event.defaultPrevented).toBe(false)
+ expect(screen.queryByText('Copy path')).toBeNull()
+ })
+
+ // Only a field the user types in keeps the browser's menu; Electron resolves nothing for a row.
+ it.each([
+ ['browser', 'checkbox'],
+ ['electron', 'text']
+ ])('%s: a %s input inside a row still opens the row menu', async (hostKind, type) => {
+ installBridge()
+ window.document.documentElement.dataset.hermesDesktopHost = hostKind
+ render(
+ <MemoryRouter>
+ <AppContextMenu />
+ <FileEntryContextMenu isDirectory={false} name="notes.txt" path="/work/notes.txt">
+ <div>
+ <input aria-label="Pick" type={type} />
+ </div>
+ </FileEntryContextMenu>
+ </MemoryRouter>
+ )
+ const input = screen.getByLabelText('Pick')
+ const selectionText = vi.spyOn(Selection.prototype, 'toString')
+ const event = createEvent.contextMenu(input, { bubbles: true, cancelable: true })
+
+ fireEvent(input, event)
+
+ expect(event.defaultPrevented).toBe(true)
+ expect(await screen.findByText('Copy path')).toBeTruthy()
+ expect(selectionText).not.toHaveBeenCalled()
+ })
+
it('keeps native media gestures unprevented in Electron', async () => {
installBridge()
window.document.documentElement.dataset.hermesDesktopHost = 'electron'
@@ -348,18 +430,22 @@ describe('AppContextMenu', () => {
expect(screen.getByText('the')).toBeTruthy()
})
- it('runs edit verbs after the menu closed, with focus back on the editable', async () => {
+ // A browser host whose bridge can run the edit verbs keeps the app menu too, cancelling its own.
+ it.each(['electron', 'browser'])('%s: edit verbs run after the menu closed, field refocused', async hostKind => {
const contextMenuEdit = vi.fn().mockResolvedValue(undefined)
installBridge({ contextMenuEdit: contextMenuEdit as unknown as Window['hermesDesktop']['contextMenuEdit'] })
+ window.document.documentElement.dataset.hermesDesktopHost = hostKind
mountMenu()
const host = attach('<textarea>some draft text</textarea>')
const textarea = host.querySelector('textarea')!
// Cut/copy act on the selection, so give the field one.
textarea.setSelectionRange(0, 4)
- fireEvent.contextMenu(textarea)
+ const event = createEvent.contextMenu(textarea, { bubbles: true, cancelable: true })
+ fireEvent(textarea, event)
fireEvent.click(await screen.findByText('Copy'))
+ expect(event.defaultPrevented).toBe(hostKind === 'browser')
// The verb waits a frame so the radix focus trap unmounts first —
// dispatching while the trap holds focus sent the command to `body`.
diff --git a/apps/desktop/src/app/context-menu/app-context-menu.tsx b/apps/desktop/src/app/context-menu/app-context-menu.tsx
index 27dcf7abe2a..644b2f0fd46 100644
--- a/apps/desktop/src/app/context-menu/app-context-menu.tsx
+++ b/apps/desktop/src/app/context-menu/app-context-menu.tsx
@@ -17,6 +17,8 @@ import {
DropdownMenuTrigger
} from '@/components/ui/dropdown-menu'
import { useContributions } from '@/contrib/react/use-contributions'
+import { registry } from '@/contrib/registry'
+import type { Contribution } from '@/contrib/types'
import { type Translations, useI18n } from '@/i18n'
import { writeClipboardText } from '@/lib/clipboard'
import { hostPathLabel, hudForcesNativeLinks, normalizeExternalUrl, openExternalLink } from '@/lib/external-link'
@@ -27,7 +29,7 @@ import { reachablePreviewUrl } from '@/lib/preview-reach'
import { isBrowserOwnedTouch } from '@/lib/touch-interaction'
import { openPreview } from '@/store/preview'
-import { type ComposerMenuRow, resolveComposerMenuSections } from './composer-menu'
+import { type ComposerMenuRow, type ComposerMenuTarget, resolveComposerMenuSections } from './composer-menu'
import { ShellMenuItems } from './shell-menu-items'
import {
$contextMenu,
@@ -37,7 +39,7 @@ import {
openDomContextMenu,
openTerminalContextMenu
} from './store'
-import { isWebUrl, resolveDomTarget } from './target'
+import { type ContextMenuDomTarget, isWebUrl, resolveDomTarget } from './target'
/** Marks a surface that owns PLAIN right-clicks itself (the user-message
* reaction bubble). Owned targets inside it — links, images, editables,
@@ -73,6 +75,72 @@ function claimContextMenuGesture(event: MouseEvent) {
event.stopPropagation()
}
+const resolvedComposerSections = new WeakMap<
+ ComposerMenuTarget,
+ { contributions: readonly Contribution[]; sections: ComposerMenuRow[][] }
+>()
+
+/** A provider's `items` runs once per right-click: a browser host's gesture asks first whether
+ * any rows apply, and the open menu reuses that answer until a plugin registers or unloads. */
+function composerSectionsFor(contributions: readonly Contribution[], target: ComposerMenuTarget): ComposerMenuRow[][] {
+ const resolved = resolvedComposerSections.get(target)
+
+ if (resolved?.contributions === contributions) {
+ return resolved.sections
+ }
+
+ const sections = resolveComposerMenuSections(contributions, target)
+
+ resolvedComposerSections.set(target, { contributions, sections })
+
+ return sections
+}
+
+/** Our Cut, Copy and Paste run through Electron main (`contextMenuEdit`) and our spelling rows
+ * come from its spellcheck feed; a browser host has neither. */
+function lacksEditVerbs(): boolean {
+ return isBrowserHostedDesktop() && !window.hermesDesktop?.contextMenuEdit
+}
+
+/** Without them an editable keeps the browser's own menu, where both work: pane and row menus
+ * stay closed and the native menu is not cancelled. Plugin rows that apply there keep the app
+ * menu, which then leaves out the verbs it cannot run. Returns whether it left the gesture. */
+function leaveEditableToBrowser(event: MouseEvent, target: ContextMenuDomTarget): boolean {
+ const composer = target.composer
+
+ const left = Boolean(
+ target.editable &&
+ lacksEditVerbs() &&
+ !(composer && composerSectionsFor(registry.getArea(COMPOSER_AREAS.contextMenu), composer).length)
+ )
+
+ if (left) {
+ event.stopPropagation()
+ }
+
+ return left
+}
+
+// A checkbox, radio, slider or button has no edit verbs or spelling for the browser to offer.
+const TEXT_INPUT_TYPES = new Set(['email', 'number', 'password', 'search', 'tel', 'text', 'url'])
+
+/** A row, tab or status-bar menu yields only to a text field inside it: any other control there
+ * still opens the row's menu, and a host with our edit verbs resolves nothing. */
+function leaveRowTextFieldToBrowser(event: MouseEvent, element: Element | null) {
+ if (!lacksEditVerbs()) {
+ return
+ }
+
+ const typed =
+ element instanceof HTMLInputElement
+ ? TEXT_INPUT_TYPES.has(element.type)
+ : element instanceof HTMLTextAreaElement || Boolean(element?.closest('[contenteditable]'))
+
+ if (typed) {
+ leaveEditableToBrowser(event, resolveDomTarget(element))
+ }
+}
+
function isLoopbackUrl(url: string): boolean {
try {
return LOOPBACK_HOST_RE.test(new URL(url).hostname)
@@ -151,6 +219,10 @@ function composerItemSections(sections: ComposerMenuRow[][], afterClose: (run: (
)
}
+function hasCuttableSelection(formField: HTMLInputElement | HTMLTextAreaElement | null, selectionText: string) {
+ return formField ? (formField.selectionStart ?? 0) !== (formField.selectionEnd ?? 0) : selectionText.length > 0
+}
+
function domSections(
open: Extract<OpenContextMenu, { kind: 'dom' }>,
t: Translations,
@@ -349,11 +421,9 @@ function domSections(
const hasFieldText = fieldText.length > 0
- const canCutCopy = formField
- ? (formField.selectionStart ?? 0) !== (formField.selectionEnd ?? 0)
- : target.selectionText.length > 0
+ const canCutCopy = hasCuttableSelection(formField, target.selectionText)
- sections.push([
+ const editVerbs = [
<Item
disabled={!canCutCopy}
key="edit-cut"
@@ -374,7 +444,13 @@ function domSections(
onSelect={() => editableCommand('paste')}
shortcut={EDIT_SHORTCUTS.paste}
/>
- ])
+ ]
+
+ // Never offer a verb that cannot run: without contextMenuEdit only plugin rows bring us here.
+ if (!lacksEditVerbs()) {
+ sections.push(editVerbs)
+ }
+
sections.push([
<Item
disabled={!hasFieldText}
@@ -589,16 +665,15 @@ export function AppContextMenu() {
// registers or unloads while the menu is up.
const composerSections = useMemo(
() =>
- composerTarget && composerContributions.length
- ? resolveComposerMenuSections(composerContributions, composerTarget)
- : [],
+ composerTarget && composerContributions.length ? composerSectionsFor(composerContributions, composerTarget) : [],
[composerContributions, composerTarget]
)
useEffect(() => {
// Electron needs unprevented gestures for main-process spellcheck and
// image coordinates. Webapp must cancel the browser's native menu when
- // we own the gesture, or it opens alongside the app menu.
+ // we own the gesture, or it opens alongside the app menu; editables keep
+ // the native menu there, for its working edit verbs and spelling suggestions.
const onContextMenu = (event: MouseEvent) => {
const element = event.target instanceof Element ? event.target : null
@@ -615,6 +690,9 @@ export function AppContextMenu() {
// Only the pane-body wrapper is a fallback menu. Explicit row, tab and
// status-bar menus still own their whole gesture, even inside a pane.
if (trigger && !trigger.hasAttribute('data-zone-body')) {
+ // A text field in one (the Files tree's inline rename) still keeps the browser's own menu.
+ leaveRowTextFieldToBrowser(event, element)
+
return
}
@@ -660,6 +738,10 @@ export function AppContextMenu() {
const owned = Boolean(target.linkUrl || target.onImage || target.editable || selected)
+ if (leaveEditableToBrowser(event, target)) {
+ return
+ }
+
// A selection elsewhere in the same pane must not take its bare menu.
if (!owned && trigger) {
return
diff --git a/apps/desktop/src/app/context-menu/composer-menu.test.tsx b/apps/desktop/src/app/context-menu/composer-menu.test.tsx
index a9e1ea9af68..212ab856379 100644
--- a/apps/desktop/src/app/context-menu/composer-menu.test.tsx
+++ b/apps/desktop/src/app/context-menu/composer-menu.test.tsx
@@ -1,4 +1,4 @@
-import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, cleanup, createEvent, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { createRef, type RefObject } from 'react'
import { MemoryRouter } from 'react-router'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -129,6 +129,41 @@ describe('composer context-menu contribution area', () => {
expect(await screen.findByText('Plugin row')).toBeTruthy()
})
+ // The browser host has no contextMenuEdit: its own menu has the working edit verbs, but plugin
+ // rows exist only in ours.
+ it('keeps plugin rows in the browser Webapp, without the edit verbs it cannot run', async () => {
+ const items = vi.fn((context: ComposerContextMenuContext) =>
+ context.word === 'teh' ? [{ label: 'Plugin row', onSelect: vi.fn() }] : []
+ )
+
+ plugin('alpha', items)
+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'
+
+ try {
+ const editor = composer('teh quick fox')
+
+ select(editor, 1)
+ const withRows = createEvent.contextMenu(editor, { bubbles: true, cancelable: true })
+ fireEvent(editor, withRows)
+
+ expect(await screen.findByText('Plugin row')).toBeTruthy()
+ expect(withRows.defaultPrevented).toBe(true)
+ expect(screen.getByText('Select all')).toBeTruthy()
+ expect(['Cut', 'Copy', 'Paste'].filter(label => screen.queryByText(label))).toEqual([])
+ expect(items).toHaveBeenCalledTimes(1)
+
+ act(() => $contextMenu.set(null))
+ select(editor, 6)
+ const withoutRows = createEvent.contextMenu(editor, { bubbles: true, cancelable: true })
+ fireEvent(editor, withoutRows)
+
+ expect(withoutRows.defaultPrevented).toBe(false)
+ expect($contextMenu.get()).toBeNull()
+ } finally {
+ delete window.document.documentElement.dataset.hermesDesktopHost
+ }
+ })
+
it('hands a provider only the word under the caret and the composer selection', async () => {
const seen: ComposerContextMenuContext[] = []