The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(desktop): custom translated context menus across the app
ethernet1314a539c2bb
diff --git a/apps/desktop/e2e/context-menu-editables.spec.ts b/apps/desktop/e2e/context-menu-editables.spec.tsnew file mode 100644index 00000000000..5f0c3787ab1--- /dev/null+++ b/apps/desktop/e2e/context-menu-editables.spec.ts@@ -0,0 +1,123 @@+/**+ * Context-menu edit verbs on real editables — the regressions jsdom cannot+ * catch, exercised against the real renderer (real radix focus trap, real+ * React unmount timing, real selection).+ *+ * The class under test: "Select all" from the app context menu must act on+ * the FIELD the menu was opened on, never on the surrounding transcript.+ * The first fix (focus-restore before dispatch) passed unit tests and still+ * failed live because the radix trap steals focus back; the second fix runs+ * selection renderer-side after the trap unmounts. These tests pin the+ * observable outcome, not the mechanism.+ *+ * Menu items are addressed by accessible-name PREFIX (`/^Copy/`): the name+ * includes the shortcut suffix ("Copy Ctrl+V" / "Copy ⌘V"), which is also+ * host-dependent.+ */++import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'+import { expect, test } from './test'++let fixture: MockBackendFixture | null = null++test.beforeAll(async () => {+ fixture = await setupMockBackend()+ await waitForAppReady(fixture, 120_000)+})++test.afterAll(async () => {+ await fixture?.cleanup()+ fixture = null+})++test('select all from the composer context menu selects the draft, not the chat', async () => {+ const page = fixture!.page+ const composer = page.locator('[data-slot="composer-rich-input"]').first()++ // Put a message into the transcript so there is chat text a document-wide+ // select-all WOULD grab — the bug this test exists to catch. Wait for the+ // mock reply to COMPLETE: while the turn is busy the composer is in its+ // steer shape and a typed draft does not land in it.+ await composer.click()+ await composer.pressSequentially('transcript anchor message')+ await page.keyboard.press('Enter')+ await page.waitForFunction(() => (document.body.textContent ?? '').includes('mock inference server'), undefined, {+ timeout: 60_000+ })++ // Draft text in the composer, then right-click it.+ await composer.click()+ await composer.pressSequentially('draft under selection')+ await composer.click({ button: 'right' })++ const selectAll = page.getByRole('menuitem', { name: /^Select all/ })++ await selectAll.waitFor({ state: 'visible', timeout: 10_000 })+ await selectAll.click()++ // The selection must live inside the composer and cover exactly the draft.+ await expect+ .poll(+ () =>+ page.evaluate(() => {+ const selection = window.getSelection()+ const editable = document.querySelector('[data-slot="composer-rich-input"]')++ if (!selection || selection.rangeCount === 0 || !editable) {+ return { inside: false, text: '' }+ }++ return {+ inside: editable.contains(selection.getRangeAt(0).commonAncestorContainer),+ text: selection.toString()+ }+ }),+ { timeout: 10_000 }+ )+ .toEqual({ inside: true, text: 'draft under selection' })++ // Clear the draft so later tests start clean.+ await page.keyboard.press('Delete')+})++test('cut, copy, and select all gray out in an empty composer', async () => {+ const page = fixture!.page+ const composer = page.locator('[data-slot="composer-rich-input"]').first()++ await composer.click()+ await composer.click({ button: 'right' })++ const selectAll = page.getByRole('menuitem', { name: /^Select all/ })++ await selectAll.waitFor({ state: 'visible', timeout: 10_000 })++ await expect(selectAll).toHaveAttribute('data-disabled', /.*/)+ await expect(page.getByRole('menuitem', { name: /^Cut/ })).toHaveAttribute('data-disabled', /.*/)+ await expect(page.getByRole('menuitem', { name: /^Copy/ })).toHaveAttribute('data-disabled', /.*/)++ await page.keyboard.press('Escape')+})++test('paste enables when the clipboard holds text', async () => {+ const page = fixture!.page+ const composer = page.locator('[data-slot="composer-rich-input"]').first()++ // The empty-clipboard branch stays in the unit suite: the e2e app shares+ // the SYSTEM clipboard, and writeText('') does not reliably clear it.+ await page.evaluate(() =>+ (+ window as unknown as { hermesDesktop?: { writeClipboard?: (text: string) => Promise<boolean> } }+ ).hermesDesktop?.writeClipboard?.('clipboard payload')+ )+ await composer.click()+ await composer.click({ button: 'right' })++ const paste = page.getByRole('menuitem', { name: /^Paste/ })++ await paste.waitFor({ state: 'visible', timeout: 10_000 })++ // The clipboard probe is an async IPC — the item enables when it lands.+ await expect.poll(() => paste.getAttribute('data-disabled'), { timeout: 10_000 }).toBeNull()++ await page.keyboard.press('Escape')+})diff --git a/apps/desktop/electron/image-context-menu.test.ts b/apps/desktop/electron/image-context-menu.test.tsdeleted file mode 100644index c36de87b07f..00000000000--- a/apps/desktop/electron/image-context-menu.test.ts+++ /dev/null@@ -1,81 +0,0 @@-import assert from 'node:assert/strict'--import { test } from 'vitest'--import { imageContextMenuItems } from './image-context-menu'--function createActions() {- const calls = {- copyImageAt: [],- openImage: [],- copyImageAddress: [],- saveImage: []- }-- return {- calls,- actions: {- copyImageAt: (x, y) => calls.copyImageAt.push([x, y]),- openImage: url => calls.openImage.push(url),- copyImageAddress: url => calls.copyImageAddress.push(url),- saveImage: url => calls.saveImage.push(url)- }- }-}--test('keeps Copy Image available when Chromium omits a large image srcURL', () => {- const { actions, calls } = createActions()-- const items = imageContextMenuItems(- { mediaType: 'image', hasImageContents: true, srcURL: '', x: 100, y: 120 },- actions- )-- assert.deepEqual(- items.map(item => item.label),- ['Copy Image']- )-- items[0].click()- assert.deepEqual(calls.copyImageAt, [[100, 120]])-})--test('keeps URL-dependent image actions when srcURL is available', () => {- const { actions, calls } = createActions()- const url = 'https://example.com/image.png'-- const items = imageContextMenuItems({ mediaType: 'image', hasImageContents: true, srcURL: url, x: 5, y: 8 }, actions)-- assert.deepEqual(- items.map(item => item.label),- ['Open Image', 'Copy Image', 'Copy Image Address', 'Save Image As...']- )-- items[0].click()- items[1].click()- items[2].click()- items[3].click()-- assert.deepEqual(calls.openImage, [url])- assert.deepEqual(calls.copyImageAt, [[5, 8]])- assert.deepEqual(calls.copyImageAddress, [url])- assert.deepEqual(calls.saveImage, [url])-})--test('does not add image actions for a non-image target', () => {- const { actions } = createActions()-- assert.deepEqual(- imageContextMenuItems({ mediaType: 'none', hasImageContents: false, srcURL: '', x: 0, y: 0 }, actions),- []- )-})--test('does not offer Copy Image when the target has no decoded image contents', () => {- const { actions } = createActions()-- assert.deepEqual(- imageContextMenuItems({ mediaType: 'image', hasImageContents: false, srcURL: '', x: 0, y: 0 }, actions),- []- )-})diff --git a/apps/desktop/electron/image-context-menu.ts b/apps/desktop/electron/image-context-menu.tsdeleted file mode 100644index de817024c0f..00000000000--- a/apps/desktop/electron/image-context-menu.ts+++ /dev/null@@ -1,40 +0,0 @@-export function imageContextMenuItems(params, actions) {- if (params.mediaType !== 'image' || !params.hasImageContents) {- return []- }-- const items = []- const srcURL = params.srcURL || ''-- if (srcURL) {- items.push({- label: 'Open Image',- click: () => {- if (!srcURL.startsWith('data:')) {- actions.openImage(srcURL)- }- },- enabled: !srcURL.startsWith('data:')- })- }-- items.push({- label: 'Copy Image',- click: () => actions.copyImageAt(params.x, params.y)- })-- if (srcURL) {- items.push(- {- label: 'Copy Image Address',- click: () => actions.copyImageAddress(srcURL)- },- {- label: 'Save Image As...',- click: () => actions.saveImage(srcURL)- }- )- }-- return items-}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex b0b25c49b99..eb5e9f3169c 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -206,7 +206,6 @@ import { cursorPointInWindow } from './hud-cursor'import { snapHudBounds } from './hud-snap'import { createHudSnapShortcut } from './hud-snap-shortcut'import { buildHudWindowUrl } from './hud-url'-import { imageContextMenuItems } from './image-context-menu'import { createLinkTitleWindow, guardLinkTitleSession, readLinkTitleWindowTitle } from './link-title-window'import { ensureMainWindow } from './main-window-lifecycle'import { createMediaProtocolHandler, MEDIA_PROTOCOL } from './media-protocol'@@ -6397,92 +6396,30 @@ function installZoomShortcuts(window) {})}-function installContextMenu(window) {- window.webContents.on('context-menu', (_event, params) => {- const template = []- const hasSelection = Boolean(params.selectionText?.trim())- const hasLink = Boolean(params.linkURL)- const isEditable = Boolean(params.isEditable)-- template.push(- ...imageContextMenuItems(params, {- copyImageAt: (x, y) => window.webContents.copyImageAt(x, y),- openImage: openExternalUrl,- copyImageAddress: url => clipboard.writeText(url),- saveImage: url => {- void saveImageFromUrl(url).catch(error => rememberLog(`Save image failed: ${error.message}`))- }- })- )-- if (hasLink) {- if (template.length) {- template.push({ type: 'separator' })- }+/**+ * The custom (renderer) context menu's main-process half.+ *+ * The app popups no native menus: the renderer owns the menu UI so labels+ * are translated with the rest of the app. Main keeps only what Chromium+ * reports here and the renderer cannot see:+ * - spell-check facts (misspelled word + suggestions) — forwarded so the+ * renderer appends them to its already-open menu,+ * - the gesture coordinates — kept for copyImageAt, which needs them.+ */+const lastContextMenuPoint = new Map<number, { x: number; y: number }>()- template.push(- {- label: 'Open Link',- click: () => openExternalUrl(params.linkURL)- },- {- label: 'Copy Link',- click: () => clipboard.writeText(params.linkURL)- }- )- }+function installContextMenuBridge(window: BrowserWindow) {+ window.webContents.on('context-menu', (_event, params) => {+ lastContextMenuPoint.set(window.webContents.id, { x: params.x, y: params.y })- // Spell-check suggestions for the misspelled word under the caret.- // Chromium surfaces them on `params.dictionarySuggestions`; we offer the- // top 5 plus a "Add to dictionary" affordance.const suggestions = Array.isArray(params.dictionarySuggestions) ? params.dictionarySuggestions : []- if (isEditable && params.misspelledWord && suggestions.length > 0) {- if (template.length) {- template.push({ type: 'separator' })- }-- for (const suggestion of suggestions.slice(0, 5)) {- template.push({- label: suggestion,- click: () => window.webContents.replaceMisspelling(suggestion)- })- }-- template.push({ type: 'separator' })- template.push({- label: 'Add to dictionary',- click: () => window.webContents.session.addWordToSpellCheckerDictionary(params.misspelledWord)+ if (params.isEditable && params.misspelledWord) {+ window.webContents.send('hermes:context-menu-spellcheck', {+ misspelledWord: params.misspelledWord,+ suggestions})}-- if (hasSelection || isEditable) {- if (template.length) {- template.push({ type: 'separator' })- }-- if (isEditable) {- template.push(- { role: 'cut', enabled: params.editFlags.canCut },- { role: 'copy', enabled: params.editFlags.canCopy },- { role: 'paste', enabled: params.editFlags.canPaste },- { type: 'separator' },- { role: 'selectAll', enabled: params.editFlags.canSelectAll }- )- } else {- template.push({ role: 'copy', enabled: params.editFlags.canCopy })- }- }-- // Bare right-click on non-editable, non-selected, non-media content (a pane- // body, the sidebar, chrome): the renderer's own context menus own those- // surfaces, and anywhere without one shows nothing — not a lone, useless- // "Select All" from the native fallback.- if (!template.length) {- return- }-- Menu.buildFromTemplate(template).popup({ window })})}@@ -10776,7 +10713,7 @@ function wireCommonWindowHandlers(win, { zoom = true }: { zoom?: boolean } = {})win.webContents.on('did-finish-load', () => restorePersistedZoomLevel(win))}- installContextMenu(win)+ installContextMenuBridge(win)win.webContents.setWindowOpenHandler(details => {openExternalUrl(details.url)@@ -13936,6 +13873,58 @@ ipcMain.handle('hermes:saveGatewayFile', (_event, payload) => saveGatewayFile(paipcMain.handle('hermes:saveImageFromUrl', (_event, url) => saveImageFromUrl(String(url || '')))+// The custom context menu's edit verbs. They act on the SENDER's focused+// element, so the renderer restores focus to the editable before invoking.+ipcMain.handle('hermes:context-menu:edit', (event, command) => {+ const contents = event.sender++ if (command === 'copy') {+ contents.copy()+ } else if (command === 'cut') {+ contents.cut()+ } else if (command === 'paste') {+ contents.paste()+ } else if (command === 'selectAll') {+ contents.selectAll()+ }+})++// Copy the image under the sender's LAST context-menu gesture. Chromium only+// exposes image bytes through copyImageAt, and only main saw the coordinates.+ipcMain.handle('hermes:context-menu:copy-image', event => {+ const point = lastContextMenuPoint.get(event.sender.id)++ if (point) {+ event.sender.copyImageAt(point.x, point.y)+ }+})++ipcMain.handle('hermes:context-menu:spellcheck', (event, action) => {+ const kind = action?.kind+ const word = String(action?.word || '')++ if (!word) {+ return+ }++ if (kind === 'replace') {+ event.sender.replaceMisspelling(word)+ } else if (kind === 'add') {+ event.sender.session.addWordToSpellCheckerDictionary(word)+ }+})++// Guest dictionary add: the webview TAG exposes replaceMisspelling but no+// session API, so the renderer names the guest by webContents id.+ipcMain.handle('hermes:context-menu:guest-add-word', (_event, payload) => {+ const word = String(payload?.word || '')+ const guest = electronWebContents.fromId(Number(payload?.webContentsId))++ if (word && guest && !guest.isDestroyed()) {+ guest.session.addWordToSpellCheckerDictionary(word)+ }+})+ipcMain.handle('hermes:saveImageBuffer', async (_event, payload) => {const data = payload?.datadiff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 6b474b56d85..a87ab15f3a5 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -1,4 +1,4 @@-import { contextBridge, ipcRenderer, webUtils } from 'electron'+import { contextBridge, ipcRenderer, webFrame, webUtils } from 'electron'contextBridge.exposeInMainWorld('hermesDesktop', {getConnection: profile => ipcRenderer.invoke('hermes:connection', profile),@@ -185,6 +185,16 @@ contextBridge.exposeInMainWorld('hermesDesktop', {readClipboard: () => ipcRenderer.invoke('hermes:readClipboard'),saveGatewayFile: payload => ipcRenderer.invoke('hermes:saveGatewayFile', payload),saveImageFromUrl: url => ipcRenderer.invoke('hermes:saveImageFromUrl', url),+ contextMenuEdit: command => ipcRenderer.invoke('hermes:context-menu:edit', command),+ contextMenuCopyImage: () => ipcRenderer.invoke('hermes:context-menu:copy-image'),+ contextMenuSpellcheck: action => ipcRenderer.invoke('hermes:context-menu:spellcheck', action),+ contextMenuGuestAddWord: payload => ipcRenderer.invoke('hermes:context-menu:guest-add-word', payload),+ onContextMenuSpellcheck: callback => {+ const listener = (_event, payload) => callback(payload)+ ipcRenderer.on('hermes:context-menu-spellcheck', listener)++ return () => ipcRenderer.removeListener('hermes:context-menu-spellcheck', listener)+ },saveImageBuffer: (data, ext) => ipcRenderer.invoke('hermes:saveImageBuffer', { data, ext }),saveClipboardImage: () => ipcRenderer.invoke('hermes:saveClipboardImage'),getPathForFile: file => {@@ -218,6 +228,9 @@ contextBridge.exposeInMainWorld('hermesDesktop', {zoom: {// Current zoom of this window, as { level, percent }.get: () => ipcRenderer.invoke('hermes:zoom:get'),+ // Synchronous zoom factor (1 = 100%). Coordinate math needs it in the+ // same tick as the event it converts, so no IPC round-trip here.+ factor: () => webFrame.getZoomFactor(),setPercent: percent => ipcRenderer.send('hermes:zoom:set-percent', percent),// Fires on every zoom change, including the Ctrl/Cmd +/-/0 shortcuts,// so the settings UI can stay in sync with the keyboard.diff --git a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx b/apps/desktop/src/app/chat/right-rail/preview-pane.tsxindex 11cfc29340e..52fdc534eb0 100644--- a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-pane.tsx@@ -2,6 +2,7 @@ import { useStore } from '@nanostores/react'import type { PointerEvent as ReactPointerEvent } from 'react'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { openGuestContextMenu } from '@/app/context-menu/store'import { PanelEmpty } from '@/app/overlays/panel'import { Tip } from '@/components/ui/tooltip'import { type Translations, useI18n } from '@/i18n'@@ -34,16 +35,42 @@ type PreviewWebview = HTMLElement & {canGoBack?: () => booleancanGoForward?: () => booleancloseDevTools?: () => void+ copy?: () => void+ cut?: () => voidexecuteJavaScript?: (code: string) => Promise<unknown>getTitle?: () => stringgetURL?: () => string+ getWebContentsId?: () => numbergoBack?: () => voidgoForward?: () => void+ inspectElement?: (x: number, y: number) => voidisDevToolsOpened?: () => booleanloadURL?: (url: string) => Promise<void>openDevTools?: () => void+ paste?: () => voidreload?: () => voidreloadIgnoringCache?: () => void+ replaceMisspelling?: (word: string) => void+ selectAll?: () => void+}++/** The raw Chromium params riding the webview tag's `context-menu` event. */+interface GuestContextMenuParams {+ dictionarySuggestions?: string[]+ editFlags?: {+ canCopy?: boolean+ canCut?: boolean+ canPaste?: boolean+ canSelectAll?: boolean+ }+ hasImageContents?: boolean+ isEditable?: boolean+ linkURL?: string+ misspelledWord?: string+ selectionText?: string+ srcURL?: string+ x: number+ y: number}interface PreviewPaneProps {@@ -723,7 +750,82 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =const onDevToolsOpened = () => setDevtoolsOpen(true)const onDevToolsClosed = () => setDevtoolsOpen(false)+ // Right-clicks INSIDE the guest page. The tag surfaces Chromium's full+ // context-menu params (link, image, editable, selection, spellcheck), so+ // the app coordinator renders the same translated menu it shows+ // everywhere else.+ //+ // Coordinates: params.x/y are WINDOW-relative device-independent pixels+ // — the guest offset is already included, and CSS values are multiplied+ // by the window zoom factor. Measured live (zoom 0.9): a click whose+ // true window CSS point was (901, 272) arrived as params (811, 246) =+ // (901*0.9, 272*0.9). Dividing by the zoom factor recovers CSS+ // coordinates; adding the webview rect on top double-counted the offset+ // and dropped the menu far right+below the click.+ const onGuestContextMenu = (event: Event) => {+ const detail = event as Event & { params?: GuestContextMenuParams }+ const params = detail.params++ if (!params) {+ return+ }++ const zoom = window.hermesDesktop?.zoom?.factor?.() || 1+ // Window CSS point of the click (the menu anchors here).+ const windowX = params.x / zoom+ const windowY = params.y / zoom+ // Guest CSS point (inspectElement wants coordinates INSIDE the page):+ // subtract the webview's own offset from the window point.+ const rect = webview.getBoundingClientRect()+ const guestX = Math.max(0, Math.round(windowX - rect.left))+ const guestY = Math.max(0, Math.round(windowY - rect.top))++ openGuestContextMenu(+ windowX,+ windowY,+ {+ dictionarySuggestions: Array.isArray(params.dictionarySuggestions) ? params.dictionarySuggestions : [],+ // Chromium's availability verdict for the edit verbs. Absent only+ // if a future Electron drops it — then everything stays enabled,+ // which is the pre-editFlags behavior, not a lockout.+ editFlags: {+ canCopy: params.editFlags?.canCopy ?? true,+ canCut: params.editFlags?.canCut ?? true,+ canPaste: params.editFlags?.canPaste ?? true,+ canSelectAll: params.editFlags?.canSelectAll ?? true+ },+ hasImageContents: Boolean(params.hasImageContents),+ isEditable: Boolean(params.isEditable),+ linkURL: params.linkURL || '',+ misspelledWord: params.misspelledWord || '',+ selectionText: params.selectionText || '',+ srcURL: params.srcURL || ''+ },+ {+ addToDictionary: (word: string) => {+ const webContentsId = webview.getWebContentsId?.()++ if (typeof webContentsId === 'number') {+ void window.hermesDesktop?.contextMenuGuestAddWord?.({ webContentsId, word })+ }+ },+ copyImage: () => void window.hermesDesktop?.contextMenuCopyImage?.(),+ // The tag's edit commands act on the focused webContents, and the+ // menu click just parked focus on the HOST body — measured live:+ // selectAll() with host focus selected the address bar + chat+ // instead of the page. Focus the webview first, every verb.+ editCommand: (command: 'copy' | 'cut' | 'paste' | 'selectAll') => {+ webview.focus()+ webview[command]?.()+ },+ inspectElement: () => webview.inspectElement?.(guestX, guestY),+ replaceMisspelling: (word: string) => webview.replaceMisspelling?.(word)+ }+ )+ }+webview.addEventListener('console-message', onConsole)+ webview.addEventListener('context-menu', onGuestContextMenu)webview.addEventListener('devtools-closed', onDevToolsClosed)webview.addEventListener('devtools-opened', onDevToolsOpened)webview.addEventListener('did-fail-load', onFail)@@ -736,6 +838,7 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =return () => {webview.removeEventListener('console-message', onConsole)+ webview.removeEventListener('context-menu', onGuestContextMenu)webview.removeEventListener('devtools-closed', onDevToolsClosed)webview.removeEventListener('devtools-opened', onDevToolsOpened)webview.removeEventListener('did-fail-load', onFail)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.tsxnew file mode 100644index 00000000000..ea406caa10a--- /dev/null+++ b/apps/desktop/src/app/context-menu/app-context-menu.test.tsx@@ -0,0 +1,569 @@+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { MemoryRouter } from 'react-router'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { registerTerminalContextMenu } from '@/app/right-sidebar/terminal/terminal-context-menu'+import { formatCombo } from '@/lib/keybinds/combo'+import { $previewTabs, closeRightRail } from '@/store/preview'+import { $connection } from '@/store/session'++import { AppContextMenu } from './app-context-menu'+import {+ $contextMenu,+ augmentSpellcheck,+ type GuestMenuHandle,+ type GuestMenuParams,+ openGuestContextMenu+} from './store'+import { resolveDomTarget } from './target'++const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }++function installBridge(partial: Partial<Window['hermesDesktop']> = {}) {+ desktopWindow.hermesDesktop = {+ openExternal: vi.fn().mockResolvedValue(undefined),+ writeClipboard: vi.fn().mockResolvedValue(undefined),+ ...partial+ } as unknown as Window['hermesDesktop']+}++function mountMenu() {+ return render(+ <MemoryRouter>+ <AppContextMenu />+ </MemoryRouter>+ )+}++function attach(html: string): HTMLElement {+ const host = document.createElement('div')++ host.innerHTML = html+ document.body.appendChild(host)++ return host+}++afterEach(() => {+ $contextMenu.set(null)+ $connection.set(null)+ closeRightRail()+ cleanup()+ vi.restoreAllMocks()+ document.body.innerHTML = ''+ delete desktopWindow.hermesDesktop+})++describe('resolveDomTarget', () => {+ it('resolves an anchor and its href', () => {+ const host = attach('<a href="https://example.com/x">link</a>')++ expect(resolveDomTarget(host.querySelector('a')).linkUrl).toBe('https://example.com/x')+ })++ it('ignores hash-only placeholder anchors', () => {+ const host = attach('<a href="#">stub</a>')++ expect(resolveDomTarget(host.querySelector('a')).linkUrl).toBe('')+ })++ it('resolves an image, and the anchor wrapping it', () => {+ const host = attach('<a href="https://example.com/page"><img src="https://example.com/pic.png"></a>')+ const target = resolveDomTarget(host.querySelector('img'))++ expect(target.onImage).toBe(true)+ expect(target.imageUrl).toContain('pic.png')+ expect(target.linkUrl).toBe('https://example.com/page')+ })++ it('resolves editables, skipping disabled and readonly fields', () => {+ const host = attach('<textarea></textarea><input readonly><div contenteditable="true"><span>x</span></div>')++ expect(resolveDomTarget(host.querySelector('textarea')).editable).toBeTruthy()+ expect(resolveDomTarget(host.querySelector('input')).editable).toBeNull()+ })+})++describe('AppContextMenu', () => {+ it('opens the link menu on a chat link right-click', async () => {+ installBridge()+ mountMenu()+ const host = attach('<a href="https://example.com/docs">Docs</a>')++ fireEvent.contextMenu(host.querySelector('a')!)++ expect(await screen.findByText('Open in in-app browser')).toBeTruthy()+ expect(screen.getByText('Open in external browser')).toBeTruthy()+ expect(screen.getByText('Copy URL')).toBeTruthy()+ expect(screen.queryByText('Copy resolved URL')).toBeNull()+ })++ it('opens the in-app browser from the link menu', async () => {+ installBridge()+ mountMenu()+ const host = attach('<a href="https://example.com/docs">Docs</a>')++ fireEvent.contextMenu(host.querySelector('a')!)+ fireEvent.click(await screen.findByText('Open in in-app browser'))++ await waitFor(() => expect($previewTabs.get().at(-1)?.target.url).toBe('https://example.com/docs'))+ })++ it('offers the resolved copy only for loopback links on a remote gateway', async () => {+ $connection.set({ mode: 'remote' } as never)+ const reachPreviewUrl = vi.fn(async () => 'http://127.0.0.1:45173/')+ const writeClipboard = vi.fn().mockResolvedValue(undefined)++ installBridge({+ reachPreviewUrl: reachPreviewUrl as unknown as Window['hermesDesktop']['reachPreviewUrl'],+ writeClipboard: writeClipboard as unknown as Window['hermesDesktop']['writeClipboard']+ })+ mountMenu()+ const host = attach('<a href="http://localhost:5173/">Dev</a>')++ fireEvent.contextMenu(host.querySelector('a')!)+ fireEvent.click(await screen.findByText('Copy resolved URL'))++ await waitFor(() => expect(writeClipboard).toHaveBeenCalledWith('http://127.0.0.1:45173/'))+ })++ it('opens the image menu with copy, address, and save', async () => {+ installBridge()+ mountMenu()+ const host = attach('<img src="https://example.com/pic.png" alt="pic">')++ fireEvent.contextMenu(host.querySelector('img')!)++ expect(await screen.findByText('Copy image')).toBeTruthy()+ expect(screen.getByText('Copy image address')).toBeTruthy()+ expect(screen.getByText('Save image as…')).toBeTruthy()+ })++ it('opens the edit menu in an editable and augments it with spellcheck', async () => {+ installBridge()+ mountMenu()+ const host = attach('<textarea></textarea>')++ fireEvent.contextMenu(host.querySelector('textarea')!)++ expect(await screen.findByText('Select all')).toBeTruthy()+ expect(screen.getByText('Paste')).toBeTruthy()+ expect(screen.queryByText('Add to dictionary')).toBeNull()++ // The main-process forward lands after the menu opened.+ augmentSpellcheck({ misspelledWord: 'teh', suggestions: ['the', 'ten'] })++ expect(await screen.findByText('Add to dictionary')).toBeTruthy()+ expect(screen.getByText('the')).toBeTruthy()+ })++ it('shows edit verbs without icons and with faded accelerators', async () => {+ installBridge()+ mountMenu()+ const host = attach('<textarea></textarea>')++ fireEvent.contextMenu(host.querySelector('textarea')!)++ // formatCombo picks ⌘/Ctrl from the host running the test, exactly like+ // the menu itself — so the assertion is platform-honest, not hardcoded.+ const pasteItem = (await screen.findByText('Paste')).closest('[data-slot="dropdown-menu-item"]')!++ expect(pasteItem.querySelector('[data-slot="dropdown-menu-shortcut"]')?.textContent).toBe(formatCombo('mod+v'))+ expect(pasteItem.querySelector('.codicon')).toBeNull()++ const selectAllItem = screen.getByText('Select all').closest('[data-slot="dropdown-menu-item"]')!++ expect(selectAllItem.querySelector('[data-slot="dropdown-menu-shortcut"]')?.textContent).toBe(formatCombo('mod+a'))+ expect(selectAllItem.querySelector('.codicon')).toBeNull()+ })++ it('runs edit verbs after the menu closed, with focus back on the editable', async () => {+ const contextMenuEdit = vi.fn().mockResolvedValue(undefined)++ installBridge({ contextMenuEdit: contextMenuEdit as unknown as Window['hermesDesktop']['contextMenuEdit'] })+ 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)+ fireEvent.click(await screen.findByText('Copy'))++ // The verb waits a frame so the radix focus trap unmounts first —+ // dispatching while the trap holds focus sent the command to `body`.+ expect(contextMenuEdit).not.toHaveBeenCalled()++ await waitFor(() => expect(contextMenuEdit).toHaveBeenCalledWith('copy'))+ expect($contextMenu.get()).toBeNull()+ expect(document.activeElement).toBe(textarea)+ })++ it('grays out cut and copy when the field has text but no selection', async () => {+ installBridge()+ mountMenu()+ const host = attach('<textarea>plenty of text, none selected</textarea>')+ const textarea = host.querySelector('textarea')!++ textarea.setSelectionRange(0, 0)+ fireEvent.contextMenu(textarea)++ const item = (label: string) => screen.getByText(label).closest('[data-slot="dropdown-menu-item"]') as HTMLElement++ await screen.findByText('Select all')++ expect(item('Cut').getAttribute('data-disabled')).not.toBeNull()+ expect(item('Copy').getAttribute('data-disabled')).not.toBeNull()+ // Content is there, so select all stays live.+ expect(item('Select all').getAttribute('data-disabled')).toBeNull()+ })++ it('enables cut and copy when the field has a selection', async () => {+ installBridge()+ mountMenu()+ const host = attach('<textarea>pick some of this</textarea>')+ const textarea = host.querySelector('textarea')!++ textarea.setSelectionRange(0, 4)+ fireEvent.contextMenu(textarea)++ const item = (label: string) => screen.getByText(label).closest('[data-slot="dropdown-menu-item"]') as HTMLElement++ await screen.findByText('Select all')++ expect(item('Cut').getAttribute('data-disabled')).toBeNull()+ expect(item('Copy').getAttribute('data-disabled')).toBeNull()+ })++ it('select all stays inside the field and never reaches main', async () => {+ const contextMenuEdit = vi.fn().mockResolvedValue(undefined)++ installBridge({ contextMenuEdit: contextMenuEdit as unknown as Window['hermesDesktop']['contextMenuEdit'] })+ mountMenu()+ const host = attach('<textarea>alpha beta gamma</textarea>')+ const textarea = host.querySelector('textarea')!++ fireEvent.contextMenu(textarea)+ fireEvent.click(await screen.findByText('Select all'))++ // Renderer-side selection scoped to the field: main's selectAll acts on+ // the focused FRAME and selected the whole transcript when focus+ // slipped (the edit composer re-parents focus on blur).+ await waitFor(() => {+ expect(textarea.selectionStart).toBe(0)+ expect(textarea.selectionEnd).toBe('alpha beta gamma'.length)+ })+ expect(contextMenuEdit).not.toHaveBeenCalled()+ expect(document.activeElement).toBe(textarea)+ })++ it('splits select all into its own section under the edit verbs', async () => {+ installBridge()+ mountMenu()+ const host = attach('<textarea>text</textarea>')++ fireEvent.contextMenu(host.querySelector('textarea')!)++ const selectAllItem = (await screen.findByText('Select all')).closest('[data-slot="dropdown-menu-item"]')!+ const pasteItem = screen.getByText('Paste').closest('[data-slot="dropdown-menu-item"]')!++ // Sections render as sibling `.contents` wrappers with the separator+ // inside the later one — different wrappers = different sections.+ expect(pasteItem.parentElement).not.toBe(selectAllItem.parentElement)+ expect(selectAllItem.parentElement?.querySelector('[data-slot="dropdown-menu-separator"]')).not.toBeNull()+ })++ it('grays out cut, copy, and select all in an empty field', async () => {+ installBridge()+ mountMenu()+ const host = attach('<textarea></textarea>')++ fireEvent.contextMenu(host.querySelector('textarea')!)++ const item = (label: string) => screen.getByText(label).closest('[data-slot="dropdown-menu-item"]') as HTMLElement++ await screen.findByText('Select all')++ expect(item('Cut').getAttribute('data-disabled')).not.toBeNull()+ expect(item('Copy').getAttribute('data-disabled')).not.toBeNull()+ expect(item('Select all').getAttribute('data-disabled')).not.toBeNull()+ })++ it('grays out paste until the clipboard reports text', async () => {+ const readClipboard = vi.fn().mockResolvedValue('clip content')++ installBridge({ readClipboard: readClipboard as unknown as Window['hermesDesktop']['readClipboard'] })+ mountMenu()+ const host = attach('<textarea>text</textarea>')++ fireEvent.contextMenu(host.querySelector('textarea')!)++ // The clipboard read is async — the item enables when it lands.+ const pasteItem = (await screen.findByText('Paste')).closest('[data-slot="dropdown-menu-item"]')!++ await waitFor(() => expect(pasteItem.getAttribute('data-disabled')).toBeNull())+ })++ it('keeps paste grayed out on an empty clipboard', async () => {+ const readClipboard = vi.fn().mockResolvedValue('')++ installBridge({ readClipboard: readClipboard as unknown as Window['hermesDesktop']['readClipboard'] })+ mountMenu()+ const host = attach('<textarea>text</textarea>')++ fireEvent.contextMenu(host.querySelector('textarea')!)++ const pasteItem = (await screen.findByText('Paste')).closest('[data-slot="dropdown-menu-item"]')!++ await waitFor(() => expect(readClipboard).toHaveBeenCalled())+ expect(pasteItem.getAttribute('data-disabled')).not.toBeNull()+ })++ it('offers the window verbs on bare chrome', async () => {+ installBridge()+ mountMenu()+ const host = attach('<div><p>plain chrome</p></div>')++ fireEvent.contextMenu(host.querySelector('p')!)++ expect(await screen.findByText('Settings')).toBeTruthy()+ })++ it('skips plain right-clicks inside a skip-marked surface, but not links in it', async () => {+ installBridge()+ mountMenu()++ const host = attach(+ '<div data-context-menu-skip=""><p>bubble text</p><a href="https://example.com/in">In-bubble</a></div>'+ )++ fireEvent.contextMenu(host.querySelector('p')!)+ expect($contextMenu.get()).toBeNull()++ fireEvent.contextMenu(host.querySelector('a')!)+ expect(await screen.findByText('Copy URL')).toBeTruthy()+ })++ it('leaves surfaces with their own radix menu alone', () => {+ installBridge()+ mountMenu()+ const host = attach('<div data-slot="context-menu-trigger"><span>session row</span></div>')++ fireEvent.contextMenu(host.querySelector('span')!)++ expect($contextMenu.get()).toBeNull()+ })++ it('shows the terminal menu through a registered handle', async () => {+ installBridge()+ mountMenu()+ const host = attach('<div data-terminal=""><canvas></canvas></div>')+ const paste = vi.fn()++ const unregister = registerTerminalContextMenu(host.querySelector('[data-terminal]')!, {+ getSelection: () => 'picked text',+ paste,+ selectAll: vi.fn()+ })++ fireEvent.contextMenu(host.querySelector('canvas')!)++ expect(await screen.findByText('Copy')).toBeTruthy()+ expect(screen.getByText('Paste')).toBeTruthy()+ expect(screen.getByText('Select all')).toBeTruthy()+ unregister()+ })++ it('hides paste on the read-only agent terminal', async () => {+ installBridge()+ mountMenu()+ const host = attach('<div data-terminal=""><canvas></canvas></div>')++ const unregister = registerTerminalContextMenu(host.querySelector('[data-terminal]')!, {+ getSelection: () => '',+ paste: null,+ selectAll: vi.fn()+ })++ fireEvent.contextMenu(host.querySelector('canvas')!)++ expect(await screen.findByText('Select all')).toBeTruthy()+ expect(screen.queryByText('Paste')).toBeNull()+ unregister()+ })+})++describe('AppContextMenu guest (in-app browser)', () => {+ const guestHandle = (overrides: Partial<GuestMenuHandle> = {}): GuestMenuHandle => ({+ addToDictionary: vi.fn(),+ copyImage: vi.fn(),+ editCommand: vi.fn(),+ inspectElement: vi.fn(),+ replaceMisspelling: vi.fn(),+ ...overrides+ })++ const guestParams = (overrides: Partial<GuestMenuParams> = {}): GuestMenuParams => ({+ dictionarySuggestions: [],+ editFlags: { canCopy: true, canCut: true, canPaste: true, canSelectAll: true },+ hasImageContents: false,+ isEditable: false,+ linkURL: '',+ misspelledWord: '',+ selectionText: '',+ srcURL: '',+ ...overrides+ })++ it('shows text tools and inspect on a bare page right-click', async () => {+ installBridge()+ mountMenu()+ const guest = guestHandle()++ openGuestContextMenu(10, 10, guestParams(), guest)++ expect(await screen.findByText('Select all')).toBeTruthy()+ expect(screen.getByText('Inspect element')).toBeTruthy()+ // The page verbs live on the browser bar only now.+ expect(screen.queryByText('Copy page URL')).toBeNull()+ expect(screen.queryByText('Open in browser')).toBeNull()+ expect(screen.queryByText('Show preview console')).toBeNull()+ })++ it('draws a line between select all and inspect element', async () => {+ installBridge()+ mountMenu()++ openGuestContextMenu(10, 10, guestParams(), guestHandle())++ const selectAllItem = (await screen.findByText('Select all')).closest('[data-slot="dropdown-menu-item"]')!+ const inspectItem = screen.getByText('Inspect element').closest('[data-slot="dropdown-menu-item"]')!++ expect(selectAllItem.parentElement).not.toBe(inspectItem.parentElement)+ expect(inspectItem.parentElement?.querySelector('[data-slot="dropdown-menu-separator"]')).not.toBeNull()+ })++ it('runs inspect element against the handle', async () => {+ installBridge()+ mountMenu()+ const guest = guestHandle()++ openGuestContextMenu(10, 10, guestParams(), guest)+ fireEvent.click(await screen.findByText('Inspect element'))++ expect(guest.inspectElement).toHaveBeenCalled()+ })++ it('adds a link section above the tools for guest links', async () => {+ installBridge()+ mountMenu()++ openGuestContextMenu(10, 10, guestParams({ linkURL: 'https://example.com/deep' }), guestHandle())++ expect(await screen.findByText('Open in in-app browser')).toBeTruthy()+ expect(screen.getByText('Copy URL')).toBeTruthy()+ // Inspect element rides every guest menu; the bar-only verbs do not.+ expect(screen.getByText('Inspect element')).toBeTruthy()+ expect(screen.queryByText('Copy page URL')).toBeNull()+ })++ it('keeps inspect element in guest editable menus', async () => {+ installBridge()+ mountMenu()++ openGuestContextMenu(10, 10, guestParams({ isEditable: true }), guestHandle())++ expect(await screen.findByText('Paste')).toBeTruthy()+ expect(screen.getByText('Inspect element')).toBeTruthy()+ expect(screen.queryByText('Copy page URL')).toBeNull()+ expect(screen.queryByText('Open in browser')).toBeNull()+ expect(screen.queryByText('Show preview console')).toBeNull()+ })++ it('grays out guest edit verbs from Chromium editFlags', async () => {+ installBridge()+ mountMenu()++ // An empty input: Chromium reports nothing to cut/copy/select, paste ok.+ openGuestContextMenu(+ 10,+ 10,+ guestParams({+ editFlags: { canCopy: false, canCut: false, canPaste: true, canSelectAll: false },+ isEditable: true+ }),+ guestHandle()+ )++ const item = (label: string) => screen.getByText(label).closest('[data-slot="dropdown-menu-item"]') as HTMLElement++ await screen.findByText('Select all')++ expect(item('Cut').getAttribute('data-disabled')).not.toBeNull()+ expect(item('Copy').getAttribute('data-disabled')).not.toBeNull()+ expect(item('Select all').getAttribute('data-disabled')).not.toBeNull()+ expect(item('Paste').getAttribute('data-disabled')).toBeNull()+ })++ it('splits guest select all into its own section', async () => {+ installBridge()+ mountMenu()++ openGuestContextMenu(10, 10, guestParams({ isEditable: true }), guestHandle())++ const selectAllItem = (await screen.findByText('Select all')).closest('[data-slot="dropdown-menu-item"]')!+ const pasteItem = screen.getByText('Paste').closest('[data-slot="dropdown-menu-item"]')!++ expect(pasteItem.parentElement).not.toBe(selectAllItem.parentElement)+ expect(selectAllItem.parentElement?.querySelector('[data-slot="dropdown-menu-separator"]')).not.toBeNull()+ })++ it('dispatches guest edit verbs a frame after the menu closes', async () => {+ installBridge()+ mountMenu()+ const guest = guestHandle()++ openGuestContextMenu(10, 10, guestParams(), guest)+ fireEvent.click(await screen.findByText('Select all'))++ // Deferred past the radix unmount so the webview focus() is not stolen+ // back — dispatching with host focus selected the address bar + chat.+ expect(guest.editCommand).not.toHaveBeenCalled()++ await waitFor(() => expect(guest.editCommand).toHaveBeenCalledWith('selectAll'))+ expect($contextMenu.get()).toBeNull()+ })++ it('adds an image section with copy and save for guest images', async () => {+ installBridge()+ mountMenu()++ openGuestContextMenu(+ 10,+ 10,+ guestParams({ hasImageContents: true, srcURL: 'https://example.com/pic.png' }),+ guestHandle()+ )++ expect(await screen.findByText('Copy image')).toBeTruthy()+ expect(screen.getByText('Save image as…')).toBeTruthy()+ })++ it('shows spell suggestions immediately for guest editables', async () => {+ installBridge()+ mountMenu()+ const guest = guestHandle()++ openGuestContextMenu(+ 10,+ 10,+ guestParams({ dictionarySuggestions: ['the'], isEditable: true, misspelledWord: 'teh' }),+ guest+ )++ fireEvent.click(await screen.findByText('the'))++ expect(guest.replaceMisspelling).toHaveBeenCalledWith('the')+ expect(screen.queryByText('Add to dictionary')).toBeNull()+ })+})diff --git a/apps/desktop/src/app/context-menu/app-context-menu.tsx b/apps/desktop/src/app/context-menu/app-context-menu.tsxnew file mode 100644index 00000000000..96e478bd069--- /dev/null+++ b/apps/desktop/src/app/context-menu/app-context-menu.tsx@@ -0,0 +1,690 @@+import { useStore } from '@nanostores/react'+import type { ReactNode } from 'react'+import { useEffect } from 'react'+import { useNavigate } from 'react-router'++import { terminalMenuHandleFor } from '@/app/right-sidebar/terminal/terminal-context-menu'+import { Codicon } from '@/components/ui/codicon'+import { writeClipboardText } from '@/components/ui/copy-button'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuShortcut,+ DropdownMenuTrigger+} from '@/components/ui/dropdown-menu'+import { type Translations, useI18n } from '@/i18n'+import { hostPathLabel, normalizeExternalUrl, openExternalLink } from '@/lib/external-link'+import { formatCombo } from '@/lib/keybinds/combo'+import { isRemoteGateway } from '@/lib/media'+import { reachablePreviewUrl } from '@/lib/preview-reach'+import { openCommandPalette } from '@/store/command-palette'+import { openPreview } from '@/store/preview'+import { toggleStatusbarVisible } from '@/store/statusbar-prefs'+import { requestActiveUpdate } from '@/store/updates'+import { canOpenNewWindow, openNewWindow } from '@/store/windows'++import { navigateToWorkspacePage, NEW_CHAT_ROUTE, SETTINGS_ROUTE } from '../routes'++import {+ $contextMenu,+ augmentSpellcheck,+ closeContextMenu,+ type OpenContextMenu,+ openDomContextMenu,+ openTerminalContextMenu+} from './store'+import { 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,+ * selections — still get the app menu. */+export const CONTEXT_MENU_SKIP_ATTR = 'data-context-menu-skip'++const LOOPBACK_HOST_RE = /^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1\]?)$/i++// Accelerators shown beside the edit verbs. Display only — Chromium's+// before-input-event handling already executes the chords; the menu just+// advertises them the way the native menu did. `formatCombo` renders+// mod as ⌘ on macOS and Ctrl elsewhere.+const EDIT_SHORTCUTS = {+ copy: formatCombo('mod+c'),+ cut: formatCombo('mod+x'),+ paste: formatCombo('mod+v'),+ selectAll: formatCombo('mod+a')+} as const++function isLoopbackUrl(url: string): boolean {+ try {+ return LOOPBACK_HOST_RE.test(new URL(url).hostname)+ } catch {+ return false+ }+}++/** An item: codicon + label, or label + faded right-aligned shortcut. Edit+ * verbs (cut/copy/paste/select all) drop the icon and show the accelerator+ * instead, like the native menus they replaced. */+function Item({+ disabled,+ icon,+ label,+ onSelect,+ shortcut+}: {+ disabled?: boolean+ icon?: string+ label: string+ onSelect: () => void+ shortcut?: string+}) {+ return (+ <DropdownMenuItem disabled={disabled} onSelect={onSelect}>+ {icon ? <Codicon name={icon} size="0.875rem" /> : null}+ <span>{label}</span>+ {shortcut ? <DropdownMenuShortcut>{shortcut}</DropdownMenuShortcut> : null}+ </DropdownMenuItem>+ )+}++type ShellVerbs = {+ navigate: ReturnType<typeof useNavigate>+ t: Translations+}++function terminalSections(open: Extract<OpenContextMenu, { kind: 'terminal' }>, t: Translations): ReactNode[][] {+ const { terminal } = open+ const selection = terminal.getSelection()++ return [+ [+ selection ? (+ <Item+ icon="copy"+ key="terminal-copy"+ label={t.common.copy}+ onSelect={() => void writeClipboardText(selection)}+ />+ ) : null,+ terminal.paste ? (+ <Item+ disabled={!open.clipboardHasText}+ icon="clippy"+ key="terminal-paste"+ label={t.contextMenu.edit.paste}+ onSelect={() =>+ void window.hermesDesktop?.readClipboard().then(text => (text ? terminal.paste?.(text) : undefined))+ }+ />+ ) : null,+ <Item+ icon="list-selection"+ key="terminal-select-all"+ label={t.contextMenu.edit.selectAll}+ onSelect={() => terminal.selectAll()}+ />+ ].filter(Boolean)+ ]+}++function domSections(open: Extract<OpenContextMenu, { kind: 'dom' }>, t: Translations): ReactNode[][] {+ const copy = t.contextMenu+ const { spellcheck, target } = open+ const sections: ReactNode[][] = []+ const linkUrl = target.linkUrl ? normalizeExternalUrl(target.linkUrl) : ''+ const linkIsWeb = isWebUrl(linkUrl)+ const imageIsWeb = isWebUrl(target.imageUrl)+ const showResolvedCopy = linkIsWeb && isRemoteGateway() && isLoopbackUrl(linkUrl)++ // The edit verbs and spell-check actions act on the sender's FOCUSED+ // element in main. Focus cannot be restored while the menu is open: the+ // radix content is a focus trap, so a focus() here is immediately stolen+ // back, the command then runs against `body`, and select-all grabs the+ // WHOLE transcript instead of the field. Close the menu first, then focus+ // and dispatch on the next frame — after the trap is unmounted.+ const withEditableFocus = (action: () => void) => {+ const editable = target.editable++ closeContextMenu()+ requestAnimationFrame(() => {+ editable?.focus()+ action()+ })+ }++ const editableCommand = (command: 'copy' | 'cut' | 'paste') => {+ withEditableFocus(() => void window.hermesDesktop?.contextMenuEdit?.(command))+ }++ // Select all runs entirely in the renderer, scoped to the editable itself.+ // Main's selectAll acts on whatever the FOCUSED FRAME considers "all" and+ // has no notion of the field the menu was opened on — with any focus slip+ // (the edit composer re-parents focus on blur) it selected the whole+ // transcript. A renderer range cannot escape the field.+ const selectAllInEditable = () => {+ withEditableFocus(() => {+ const editable = target.editable++ if (editable instanceof HTMLInputElement || editable instanceof HTMLTextAreaElement) {+ editable.select()++ return+ }++ if (editable) {+ const range = document.createRange()++ range.selectNodeContents(editable)++ const selection = window.getSelection()++ selection?.removeAllRanges()+ selection?.addRange(range)+ }+ })+ }++ const spellcheckAction = (action: { kind: 'add' | 'replace'; word: string }) => {+ withEditableFocus(() => void window.hermesDesktop?.contextMenuSpellcheck?.(action))+ }++ if (linkUrl) {+ sections.push(+ [+ linkIsWeb ? (+ <Item+ icon="globe"+ key="link-open-app"+ label={copy.link.openInApp}+ onSelect={() =>+ openPreview(+ { kind: 'url', label: hostPathLabel(linkUrl), source: linkUrl, url: linkUrl },+ 'explicit-link'+ )+ }+ />+ ) : null,+ <Item+ icon="link-external"+ key="link-open-external"+ label={copy.link.openExternal}+ onSelect={() => openExternalLink(linkUrl)}+ />,+ <Item+ icon="copy"+ key="link-copy"+ label={copy.link.copyUrl}+ onSelect={() => void writeClipboardText(linkUrl)}+ />,+ showResolvedCopy ? (+ <Item+ icon="copy"+ key="link-copy-resolved"+ label={copy.link.copyResolvedUrl}+ onSelect={() => void reachablePreviewUrl(linkUrl).then(writeClipboardText)}+ />+ ) : null+ ].filter(Boolean)+ )+ }++ if (target.onImage) {+ sections.push(+ [+ imageIsWeb ? (+ <Item+ icon="globe"+ key="image-open-app"+ label={copy.link.openInApp}+ onSelect={() =>+ openPreview(+ { kind: 'url', label: hostPathLabel(target.imageUrl), source: target.imageUrl, url: target.imageUrl },+ 'explicit-link'+ )+ }+ />+ ) : null,+ imageIsWeb ? (+ <Item+ icon="link-external"+ key="image-open-external"+ label={copy.link.openExternal}+ onSelect={() => openExternalLink(target.imageUrl)}+ />+ ) : null,+ <Item+ icon="file-media"+ key="image-copy"+ label={copy.image.copyImage}+ onSelect={() => void window.hermesDesktop?.contextMenuCopyImage?.()}+ />,+ target.imageUrl ? (+ <Item+ icon="copy"+ key="image-copy-address"+ label={copy.image.copyImageAddress}+ onSelect={() => void writeClipboardText(target.imageUrl)}+ />+ ) : null,+ target.imageUrl ? (+ <Item+ icon="save"+ key="image-save"+ label={copy.image.saveImageAs}+ onSelect={() => void window.hermesDesktop?.saveImageFromUrl?.(target.imageUrl)}+ />+ ) : null+ ].filter(Boolean)+ )+ }++ if (target.editable) {+ if (spellcheck) {+ sections.push([+ ...spellcheck.suggestions+ .slice(0, 5)+ .map(suggestion => (+ <Item+ icon="edit"+ key={`spell-${suggestion}`}+ label={suggestion}+ onSelect={() => spellcheckAction({ kind: 'replace', word: suggestion })}+ />+ )),+ <Item+ icon="book"+ key="spell-add"+ label={copy.edit.addToDictionary}+ onSelect={() => spellcheckAction({ kind: 'add', word: spellcheck.misspelledWord })}+ />+ ])+ }++ // Verb availability mirrors the native menu: cut/copy act on the+ // SELECTION, so they need selected text — not just field content.+ // Inputs and textareas carry their selection on the element (Chrome+ // never reflects it into window.getSelection()); contenteditable uses+ // the document selection the resolver captured. Paste needs a+ // non-empty clipboard, select all needs the field to hold anything.+ const formField =+ target.editable instanceof HTMLInputElement || target.editable instanceof HTMLTextAreaElement+ ? target.editable+ : null++ const fieldText = formField ? formField.value : (target.editable?.textContent ?? '')++ const hasFieldText = fieldText.length > 0++ const canCutCopy = formField+ ? (formField.selectionStart ?? 0) !== (formField.selectionEnd ?? 0)+ : target.selectionText.length > 0++ sections.push([+ <Item+ disabled={!canCutCopy}+ key="edit-cut"+ label={copy.edit.cut}+ onSelect={() => editableCommand('cut')}+ shortcut={EDIT_SHORTCUTS.cut}+ />,+ <Item+ disabled={!canCutCopy}+ key="edit-copy"+ label={t.common.copy}+ onSelect={() => editableCommand('copy')}+ shortcut={EDIT_SHORTCUTS.copy}+ />,+ <Item+ disabled={!open.clipboardHasText}+ key="edit-paste"+ label={copy.edit.paste}+ onSelect={() => editableCommand('paste')}+ shortcut={EDIT_SHORTCUTS.paste}+ />+ ])+ sections.push([+ <Item+ disabled={!hasFieldText}+ key="edit-select-all"+ label={copy.edit.selectAll}+ onSelect={selectAllInEditable}+ shortcut={EDIT_SHORTCUTS.selectAll}+ />+ ])+ } else if (target.selectionText) {+ sections.push([+ <Item+ icon="copy"+ key="selection-copy"+ label={t.common.copy}+ onSelect={() => void writeClipboardText(target.selectionText)}+ />+ ])+ }++ return sections+}++/** The guest (in-app browser) menu: link/image/selection/editable sections+ * from the Chromium params, plus select all for the page, closed by+ * Inspect element. The page-level verbs (copy URL, open externally,+ * console) live on the browser bar, not here. */+function guestSections(open: Extract<OpenContextMenu, { kind: 'guest' }>, t: Translations): ReactNode[][] {+ const copy = t.contextMenu+ const { guest, params } = open+ const sections: ReactNode[][] = []+ const linkUrl = params.linkURL+ const imageUrl = params.srcURL++ // Same trap-timing rule as the dom side: dispatch AFTER the menu closes,+ // so the webview's focus() is not stolen back by the radix content.+ const guestEdit = (command: 'copy' | 'cut' | 'paste' | 'selectAll') => {+ closeContextMenu()+ requestAnimationFrame(() => guest.editCommand(command))+ }++ if (linkUrl) {+ sections.push(+ [+ isWebUrl(linkUrl) ? (+ <Item+ icon="globe"+ key="guest-link-open-app"+ label={copy.link.openInApp}+ onSelect={() =>+ openPreview(+ { kind: 'url', label: hostPathLabel(linkUrl), source: linkUrl, url: linkUrl },+ 'explicit-link'+ )+ }+ />+ ) : null,+ <Item+ icon="link-external"+ key="guest-link-open-external"+ label={copy.link.openExternal}+ onSelect={() => openExternalLink(linkUrl)}+ />,+ <Item+ icon="copy"+ key="guest-link-copy"+ label={copy.link.copyUrl}+ onSelect={() => void writeClipboardText(linkUrl)}+ />+ ].filter(Boolean)+ )+ }++ if (params.hasImageContents || imageUrl) {+ sections.push(+ [+ isWebUrl(imageUrl) ? (+ <Item+ icon="link-external"+ key="guest-image-open-external"+ label={copy.link.openExternal}+ onSelect={() => openExternalLink(imageUrl)}+ />+ ) : null,+ params.hasImageContents ? (+ <Item icon="file-media" key="guest-image-copy" label={copy.image.copyImage} onSelect={guest.copyImage} />+ ) : null,+ imageUrl ? (+ <Item+ icon="copy"+ key="guest-image-copy-address"+ label={copy.image.copyImageAddress}+ onSelect={() => void writeClipboardText(imageUrl)}+ />+ ) : null,+ imageUrl ? (+ <Item+ icon="save"+ key="guest-image-save"+ label={copy.image.saveImageAs}+ onSelect={() => void window.hermesDesktop?.saveImageFromUrl?.(imageUrl)}+ />+ ) : null+ ].filter(Boolean)+ )+ }++ if (params.isEditable) {+ if (params.misspelledWord && params.dictionarySuggestions.length > 0) {+ sections.push([+ ...params.dictionarySuggestions+ .slice(0, 5)+ .map(suggestion => (+ <Item+ icon="edit"+ key={`guest-spell-${suggestion}`}+ label={suggestion}+ onSelect={() => guest.replaceMisspelling(suggestion)}+ />+ )),+ <Item+ icon="book"+ key="guest-spell-add"+ label={copy.edit.addToDictionary}+ onSelect={() => guest.addToDictionary(params.misspelledWord)}+ />+ ])+ }++ // Chromium's editFlags gate the verbs — the same availability verdict+ // the native menu showed (empty field → no cut/copy/select-all, empty+ // clipboard → no paste).+ sections.push([+ <Item+ disabled={!params.editFlags.canCut}+ key="guest-edit-cut"+ label={copy.edit.cut}+ onSelect={() => guestEdit('cut')}+ shortcut={EDIT_SHORTCUTS.cut}+ />,+ <Item+ disabled={!params.editFlags.canCopy}+ key="guest-edit-copy"+ label={t.common.copy}+ onSelect={() => guestEdit('copy')}+ shortcut={EDIT_SHORTCUTS.copy}+ />,+ <Item+ disabled={!params.editFlags.canPaste}+ key="guest-edit-paste"+ label={copy.edit.paste}+ onSelect={() => guestEdit('paste')}+ shortcut={EDIT_SHORTCUTS.paste}+ />+ ])+ sections.push([+ <Item+ disabled={!params.editFlags.canSelectAll}+ key="guest-edit-select-all"+ label={copy.edit.selectAll}+ onSelect={() => guestEdit('selectAll')}+ shortcut={EDIT_SHORTCUTS.selectAll}+ />+ ])+ } else if (params.selectionText.trim()) {+ sections.push([+ <Item icon="copy" key="guest-selection-copy" label={t.common.copy} onSelect={() => guestEdit('copy')} />+ ])+ }++ // Text tool for the page itself: select all works everywhere Chromium+ // says it can (a bare page has no field to scope to, so it selects the+ // page content).+ if (!params.isEditable) {+ sections.push([+ <Item+ disabled={!params.editFlags.canSelectAll}+ key="guest-select-all"+ label={copy.edit.selectAll}+ onSelect={() => guestEdit('selectAll')}+ shortcut={EDIT_SHORTCUTS.selectAll}+ />+ ])+ }++ // Inspect element closes every guest menu — the one page tool that earns+ // its place on any click. The other page verbs (copy URL, open+ // externally, console) live on the browser bar only.+ sections.push([+ <Item icon="inspect" key="guest-inspect" label={copy.page.inspectElement} onSelect={guest.inspectElement} />+ ])++ return sections+}++/** Bare right-click on app chrome: the window verbs (the old shell fallback). */+function shellSections({ navigate, t }: ShellVerbs): ReactNode[][] {+ return [+ [+ <Item+ icon="add"+ key="shell-new-chat"+ label={t.commandCenter.nav.newChat.title}+ onSelect={() => navigateToWorkspacePage(navigate, NEW_CHAT_ROUTE)}+ />,+ canOpenNewWindow() ? (+ <Item+ icon="multiple-windows"+ key="shell-new-window"+ label={t.keybinds.actions['session.newWindow']}+ onSelect={() => void openNewWindow()}+ />+ ) : null,+ <Item icon="search" key="shell-palette" label={t.commandCenter.paletteTitle} onSelect={openCommandPalette} />+ ].filter(Boolean),+ [+ <Item+ icon="layout-statusbar"+ key="shell-statusbar"+ label={t.keybinds.actions['view.toggleStatusbar']}+ onSelect={toggleStatusbarVisible}+ />,+ <Item+ icon="settings-gear"+ key="shell-settings"+ label={t.commandCenter.settings}+ onSelect={() => navigateToWorkspacePage(navigate, SETTINGS_ROUTE)}+ />+ ],+ [+ <Item+ icon="cloud-download"+ key="shell-update"+ label={t.commandCenter.updateHermes}+ onSelect={requestActiveUpdate}+ />+ ]+ ]+}++/**+ * THE app context menu: one capture-phase listener, one store, one menu.+ *+ * Every right-click in the app resolves here first. Radix-owned surfaces+ * (session rows and other `context-menu-trigger` wrappers) keep their own+ * menus; the reaction bubble keeps plain right-clicks; terminals answer+ * through their registered xterm handles; everything else gets a menu+ * assembled from what the click landed on — link, image, editable,+ * selection — with the window verbs as the empty-target fallback. Replaced+ * both the native Electron menu and the shell fallback wrapper, so labels+ * come from the locale files like every other surface.+ */+export function AppContextMenu() {+ const { t } = useI18n()+ const navigate = useNavigate()+ const open = useStore($contextMenu)++ useEffect(() => {+ // stopPropagation beats other renderer handlers; preventDefault is never+ // called because Chromium emits the main-process context-menu event (the+ // spellcheck + image-coordinate source) only for unprevented gestures —+ // and with no Menu.popup anywhere, "default" means no menu at all.+ const onContextMenu = (event: MouseEvent) => {+ const element = event.target instanceof Element ? event.target : null++ // Surfaces with their own Radix context menu keep the whole gesture.+ if (element?.closest('[data-slot="context-menu-trigger"]')) {+ return+ }++ // A terminal's canvas has no DOM to resolve; its registered handle+ // carries the xterm selection and paste path instead.+ const terminal = terminalMenuHandleFor(element)++ if (terminal) {+ event.stopPropagation()+ openTerminalContextMenu(event.clientX, event.clientY, terminal)++ return+ }++ const target = resolveDomTarget(element)+ const owned = Boolean(target.linkUrl || target.onImage || target.editable || target.selectionText)++ // The reaction bubble owns bare right-clicks; a link inside it still+ // opens the link menu.+ if (!owned && element?.closest(`[${CONTEXT_MENU_SKIP_ATTR}]`)) {+ return+ }++ event.stopPropagation()+ openDomContextMenu(event.clientX, event.clientY, target)+ }++ window.addEventListener('contextmenu', onContextMenu, true)++ return () => window.removeEventListener('contextmenu', onContextMenu, true)+ }, [])++ // Spell-check facts arrive from main after the menu opens (Chromium reports+ // them on its own context-menu event); attach them to the open menu.+ useEffect(() => window.hermesDesktop?.onContextMenuSpellcheck?.(augmentSpellcheck), [])++ if (!open) {+ return null+ }++ const sections =+ open.kind === 'terminal'+ ? terminalSections(open, t)+ : open.kind === 'guest'+ ? guestSections(open, t)+ : (list => (list.length ? list : shellSections({ navigate, t })))(domSections(open, t))++ return (+ <DropdownMenu+ onOpenChange={openState => {+ if (!openState) {+ closeContextMenu()+ }+ }}+ open+ >+ <DropdownMenuTrigger asChild>+ {/* A zero-size anchor at the click point: the menu positions against+ it exactly like a real trigger. */}+ <span aria-hidden style={{ left: open.x, position: 'fixed', top: open.y }} />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="start"+ className="w-56"+ onCloseAutoFocus={event => event.preventDefault()}+ side="bottom"+ >+ {sections.map((section, index) => (+ // Sections are positional by construction, so the index IS the key.+ <div className="contents" key={index}>+ {index > 0 && <DropdownMenuSeparator />}+ {section}+ </div>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )+}diff --git a/apps/desktop/src/app/context-menu/store.ts b/apps/desktop/src/app/context-menu/store.tsnew file mode 100644index 00000000000..f88a60ae663--- /dev/null+++ b/apps/desktop/src/app/context-menu/store.ts@@ -0,0 +1,134 @@+import { atom } from 'nanostores'++import type { TerminalMenuHandle } from '@/app/right-sidebar/terminal/terminal-context-menu'++import type { ContextMenuDomTarget } from './target'++/** Spell-check facts for the open editable menu. They arrive AFTER the menu+ * opens: Chromium reports them on the main-process `context-menu` event,+ * which fires after the DOM gesture that opened the menu. */+export interface SpellcheckContext {+ misspelledWord: string+ suggestions: string[]+}++/** What the guest page reported for the click, straight off the webview's+ * `context-menu` event. Unlike the DOM shape, spell-check facts ride along+ * immediately — the guest event IS the Chromium report. */+export interface GuestMenuParams {+ /** Chromium's own availability verdict for the edit verbs at the click+ * point. This is what grays out cut/copy/paste/select-all — the same+ * source the native menu used. */+ editFlags: {+ canCopy: boolean+ canCut: boolean+ canPaste: boolean+ canSelectAll: boolean+ }+ dictionarySuggestions: string[]+ hasImageContents: boolean+ isEditable: boolean+ linkURL: string+ misspelledWord: string+ selectionText: string+ srcURL: string+}++/** Verbs the preview pane binds over its webview element (and the guest IPC+ * for the two things the tag cannot do: image bytes and the dictionary). */+export interface GuestMenuHandle {+ addToDictionary: (word: string) => void+ copyImage: () => void+ editCommand: (command: 'copy' | 'cut' | 'paste' | 'selectAll') => void+ inspectElement: () => void+ replaceMisspelling: (word: string) => void+}++export type OpenContextMenu =+ | {+ kind: 'dom'+ x: number+ y: number+ target: ContextMenuDomTarget+ spellcheck: SpellcheckContext | null+ /** Whether the clipboard held text when the menu opened (grays out+ * Paste). Arrives async right after open; false until then. */+ clipboardHasText: boolean+ }+ | {+ kind: 'guest'+ x: number+ y: number+ params: GuestMenuParams+ guest: GuestMenuHandle+ }+ | {+ kind: 'terminal'+ x: number+ y: number+ terminal: TerminalMenuHandle+ /** Same async clipboard fact as the dom shape, for the paste item. */+ clipboardHasText: boolean+ }++/** The one open context menu, or null. A single atom because two context+ * menus can never be open at once. */+export const $contextMenu = atom<null | OpenContextMenu>(null)++/** Read the clipboard and flag the OPEN menu when text is available. The+ * read is an IPC round-trip, so the menu opens first (empty-clipboard+ * verdict) and the flag lands a tick later — same late-fact pattern as+ * spellcheck. Guarded by identity: a stale read never flags a newer menu. */+function probeClipboard(opened: OpenContextMenu): void {+ void window.hermesDesktop+ ?.readClipboard?.()+ .then((text: string) => {+ const current = $contextMenu.get()++ if (current === opened && (current.kind === 'dom' || current.kind === 'terminal') && text) {+ $contextMenu.set({ ...current, clipboardHasText: true })+ }+ })+ .catch(() => undefined)+}++export function openDomContextMenu(x: number, y: number, target: ContextMenuDomTarget): void {+ const opened: OpenContextMenu = { kind: 'dom', x, y, target, spellcheck: null, clipboardHasText: false }++ $contextMenu.set(opened)++ if (target.editable) {+ probeClipboard(opened)+ }+}++export function openGuestContextMenu(x: number, y: number, params: GuestMenuParams, guest: GuestMenuHandle): void {+ $contextMenu.set({ kind: 'guest', x, y, params, guest })+}++export function openTerminalContextMenu(x: number, y: number, terminal: TerminalMenuHandle): void {+ const opened: OpenContextMenu = { kind: 'terminal', x, y, terminal, clipboardHasText: false }++ $contextMenu.set(opened)++ if (terminal.paste) {+ probeClipboard(opened)+ }+}++export function closeContextMenu(): void {+ $contextMenu.set(null)+}++/** Attach late-arriving spell-check facts to the open editable menu. Ignored+ * when the menu already closed or the click was not in an editable — the+ * forward always belongs to the gesture that opened the current menu. */+export function augmentSpellcheck(payload: SpellcheckContext): void {+ const open = $contextMenu.get()++ if (!open || open.kind !== 'dom' || !open.target.editable || !payload.misspelledWord) {+ return+ }++ $contextMenu.set({ ...open, spellcheck: payload })+}diff --git a/apps/desktop/src/app/context-menu/target.ts b/apps/desktop/src/app/context-menu/target.tsnew file mode 100644index 00000000000..b1a60118e7f--- /dev/null+++ b/apps/desktop/src/app/context-menu/target.ts@@ -0,0 +1,58 @@+/**+ * What a right-click landed on, resolved from the DOM.+ *+ * One resolver so every surface agrees on ownership. Order encodes priority:+ * an editable wins over the link wrapping it (the caret is where the user is+ * working), a link wins over the image inside it for the LINK section — the+ * image section still appears because the target carries both.+ */++export interface ContextMenuDomTarget {+ /** The clicked editable, when the click landed in one. */+ editable: HTMLElement | null+ /** `href` of the enclosing anchor, as written (never absolutized). */+ linkUrl: string+ /** Source URL of the clicked image, when the click landed on one. */+ imageUrl: string+ /** True when the click landed on an `<img>` (imageUrl may still be empty+ * for a broken image; Copy image works through coordinates either way). */+ onImage: boolean+ /** The live selection's text at the moment of the click. */+ selectionText: string+}++/** Form fields and `contenteditable` hosts. Mirrors the keybind helper, but+ * returns the element so the menu can act on it. */+function editableFrom(element: Element | null): HTMLElement | null {+ if (!element) {+ return null+ }++ if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement) {+ return element.disabled || element.readOnly ? null : element+ }++ const host = element.closest('[contenteditable]')++ return host instanceof HTMLElement && host.isContentEditable ? host : null+}++export function resolveDomTarget(element: Element | null): ContextMenuDomTarget {+ const anchor = element?.closest('a[href]')+ const image = element?.closest('img')+ const linkUrl = anchor?.getAttribute('href')?.trim() ?? ''++ return {+ editable: editableFrom(element),+ // A placeholder anchor is not a link the menu can act on.+ linkUrl: linkUrl === '#' ? '' : linkUrl,+ imageUrl: image instanceof HTMLImageElement ? image.currentSrc || image.src : '',+ onImage: Boolean(image),+ selectionText: window.getSelection()?.toString().trim() ?? ''+ }+}++/** True when `url` is something the in-app browser can render. */+export function isWebUrl(url: string): boolean {+ return /^https?:\/\//i.test(url)+}diff --git a/apps/desktop/src/app/contrib/controller.tsx b/apps/desktop/src/app/contrib/controller.tsxindex c48ef1e33a0..92116f3be6b 100644--- a/apps/desktop/src/app/contrib/controller.tsx+++ b/apps/desktop/src/app/contrib/controller.tsx@@ -76,10 +76,10 @@ import {watchSessionTiles,WorkspaceTabMenu} from '../chat/session-tile'+import { AppContextMenu } from '../context-menu/app-context-menu'import { HudShell } from '../hud/hud-shell'import { $terminalTakeover, setTerminalTakeover } from '../right-sidebar/store'import { $workspaceIsPage } from '../routes'-import { ShellContextMenu } from '../shell/shell-context-menu'import { FilesPane, LogsPane, ReviewPaneContent } from './panes'import { ContribWiring, WiredPane } from './wiring'@@ -808,8 +808,8 @@ export function ContribController() {style={{ '--sidebar-width': '100%' } as CSSProperties}><ContribWiring>- <ShellContextMenu>- <div+ <AppContextMenu />+ <divclassName="flex h-screen min-h-0 w-screen flex-col bg-(--ui-bg-chrome) text-(--ui-text-primary)"// Window-glass hook: this div and the sidebar-wrapper above it are// the app shell's two full-window opaque painters; the@@ -880,7 +880,6 @@ export function ContribController() {per-turn readouts stop with it. */}{statusbarVisible && <WiredPane part="statusbar" />}</div>- </ShellContextMenu></ContribWiring></SidebarProvider>)diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminal-context-menu.ts b/apps/desktop/src/app/right-sidebar/terminal/terminal-context-menu.tsnew file mode 100644index 00000000000..fca40ec9896--- /dev/null+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-context-menu.ts@@ -0,0 +1,36 @@+/**+ * Context-menu handles for the GUI terminals.+ *+ * xterm paints to a canvas: a right-click inside it crosses no link, image,+ * editable, or DOM selection, so the app context menu would see a bare+ * surface and offer the window verbs. Each terminal registers a handle for+ * its host instead, and the coordinator resolves a click back to it through+ * the `[data-terminal]` focus-scope marker both terminal flavours carry.+ */++export interface TerminalMenuHandle {+ getSelection: () => string+ /** Null on the read-only agent mirror — it has no PTY to paste into. */+ paste: ((text: string) => void) | null+ selectAll: () => void+}++const handles = new WeakMap<Element, TerminalMenuHandle>()++/** Register the handle for a terminal host. Returns an idempotent remove. */+export function registerTerminalContextMenu(host: Element, handle: TerminalMenuHandle): () => void {+ handles.set(host, handle)++ return () => {+ if (handles.get(host) === handle) {+ handles.delete(host)+ }+ }+}++/** The handle owning `element`, when the click landed inside a terminal. */+export function terminalMenuHandleFor(element: Element | null): TerminalMenuHandle | null {+ const host = element?.closest('[data-terminal]')++ return host ? (handles.get(host) ?? null) : null+}diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts b/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.tsindex 339d70144be..d1b7f34380f 100644--- a/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts@@ -15,6 +15,7 @@ import { makeTerminalReader, registerTerminalReader } from './buffer'import { mirrorSelection, terminalClipboardIntent } from './clipboard'import { terminalLinkHandler, terminalWebLinksAddon } from './links'import { isMacPlatform, resolveSurfaceColor, terminalTheme } from './selection'+import { registerTerminalContextMenu } from './terminal-context-menu'import { prepareTerminalFontFamily } from './terminal-font'import { useTerminalFontController } from './use-terminal-font'@@ -83,6 +84,15 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:// No paste path: this terminal has no PTY to paste into.const selectionDisposable = term.onSelectionChange(() => mirrorSelection(host, term.getSelection()))+ // Right-clicks resolve through the app context menu; the handle carries+ // the xterm selection the DOM resolver cannot see. paste stays null —+ // there is nothing to paste into.+ const contextMenuDisposable = registerTerminalContextMenu(host, {+ getSelection: () => term.getSelection(),+ paste: null,+ selectAll: () => term.selectAll()+ })+term.attachCustomKeyEventHandler(event => {const intent = terminalClipboardIntent(event, {hasSelection: Boolean(term.getSelection()),@@ -161,6 +171,7 @@ export function useAgentTerminal({ active, id, procId }: { active: boolean; id:unregister()unregisterReader()selectionDisposable.dispose()+ contextMenuDisposable()fitRef.current = nullterm.dispose()termRef.current = nulldiff --git a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.tsindex 24531cabe26..09fd431ee8b 100644--- a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts@@ -26,6 +26,7 @@ import {terminalSelectionLabel,terminalTheme} from './selection'+import { registerTerminalContextMenu } from './terminal-context-menu'import { prepareTerminalFontFamily } from './terminal-font'import { closeTerminal, updateTerminalRestoreCwd, updateTerminalReviveBuffer } from './terminals'import { useTerminalFontController } from './use-terminal-font'@@ -793,6 +794,21 @@ export function useTerminalSession({cleanup.push(() => selectionDisposable.dispose())+ // The app context menu resolves right-clicks on this host through the+ // registered handle: xterm's selection is not a DOM selection, so the+ // DOM resolver would see nothing here.+ cleanup.push(+ registerTerminalContextMenu(host, {+ getSelection: () => term.getSelection(),+ paste: text => {+ hasSessionActivityRef.current = true+ term.focus()+ term.paste(text)+ },+ selectAll: () => term.selectAll()+ })+ )+// Copy/paste chords. Returning false stops xterm from also sending the key// to the PTY; every path that doesn't copy or paste returns true, so plain// Ctrl+C with no selection still interrupts the running process.diff --git a/apps/desktop/src/app/shell/shell-context-menu.tsx b/apps/desktop/src/app/shell/shell-context-menu.tsxdeleted file mode 100644index 43fff330ca2..00000000000--- a/apps/desktop/src/app/shell/shell-context-menu.tsx+++ /dev/null@@ -1,101 +0,0 @@-import type * as React from 'react'-import { useNavigate } from 'react-router'--import { hasTextSelection } from '@/components/assistant-ui/thread/user-message'-import { ActionsContextMenu, type MenuKit, renderActionItem } from '@/components/ui/actions-menu'-import { useI18n } from '@/i18n'-import { isEditableTarget } from '@/lib/keybinds/combo'-import { openCommandPalette } from '@/store/command-palette'-import { toggleStatusbarVisible } from '@/store/statusbar-prefs'-import { requestActiveUpdate } from '@/store/updates'-import { canOpenNewWindow, openNewWindow } from '@/store/windows'--import { navigateToWorkspacePage, NEW_CHAT_ROUTE, SETTINGS_ROUTE } from '../routes'--/**- * The app's fallback context menu: right-clicking chrome that owns no menu of- * its own (the titlebar gutter, a pane's empty body, the sidebar background)- * gets the window-level verbs instead of nothing.- *- * It wraps the whole shell, so the guard below is what keeps it a FALLBACK: a- * right-click that lands inside a surface with its own context menu, on an- * editable, or on a live selection is stopped before Radix's trigger sees it,- * leaving that surface's menu — or Electron's native edit menu — in charge.- * `stopPropagation` (never `preventDefault`) is the mechanism, because- * preventing the default is what would swallow the native menu.- */-export function ShellContextMenu({ children }: { children: React.ReactNode }) {- const { t } = useI18n()- const navigate = useNavigate()-- const items = (kit: MenuKit) => (- <>- {renderActionItem(kit, {- icon: 'add',- label: t.commandCenter.nav.newChat.title,- onSelect: () => navigateToWorkspacePage(navigate, NEW_CHAT_ROUTE)- })}- {canOpenNewWindow() &&- renderActionItem(kit, {- icon: 'multiple-windows',- label: t.keybinds.actions['session.newWindow'],- onSelect: () => void openNewWindow()- })}- {renderActionItem(kit, {- icon: 'search',- label: t.commandCenter.paletteTitle,- onSelect: openCommandPalette- })}- <kit.Separator />- {renderActionItem(kit, {- icon: 'layout-statusbar',- label: t.keybinds.actions['view.toggleStatusbar'],- onSelect: toggleStatusbarVisible- })}- {renderActionItem(kit, {- icon: 'settings-gear',- label: t.commandCenter.settings,- onSelect: () => navigateToWorkspacePage(navigate, SETTINGS_ROUTE)- })}- <kit.Separator />- {renderActionItem(kit, {- icon: 'cloud-download',- label: t.commandCenter.updateHermes,- onSelect: requestActiveUpdate- })}- </>- )-- return (- <ActionsContextMenu contentClassName="w-44" items={items}>- <div className="contents" data-shell-context-menu="">- {/* The guard sits on an INNER element on purpose: Radix's trigger props- are merged onto the same node as ours (asChild), so a handler there- can't stop the trigger's — but a child's stopPropagation never- reaches it. */}- <div className="contents" onContextMenu={guard}>- {children}- </div>- </div>- </ActionsContextMenu>- )-}--/** Right-clicks that already have an owner keep it: a surface with its own- * context menu, an editable, a live selection (Electron's native edit menu),- * or an image/media element (Electron's native image menu — Copy Image,- * Save Image As...). Never `preventDefault` — that is what would swallow the- * native menu. */-function guard(event: React.MouseEvent<HTMLDivElement>) {- const target = event.target as HTMLElement | null- const owner = target?.closest('[data-slot="context-menu-trigger"]')-- if (- (owner && !owner.hasAttribute('data-shell-context-menu')) ||- target?.closest('img, picture, video, canvas') ||- isEditableTarget(target) ||- hasTextSelection()- ) {- event.stopPropagation()- }-}diff --git a/apps/desktop/src/components/assistant-ui/thread/user-message.tsx b/apps/desktop/src/components/assistant-ui/thread/user-message.tsxindex 7ac4fd1d04b..9e5e5877494 100644--- a/apps/desktop/src/components/assistant-ui/thread/user-message.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/user-message.tsx@@ -453,6 +453,11 @@ export const UserMessage: FC<{><divclassName="relative w-full"+ // The app context menu skips PLAIN right-clicks here (the+ // attr below) so this handler keeps the picker gesture; a+ // link/image/selection inside the bubble still gets the app+ // menu, and this handler's selection guard keeps ⌘C flows.+ data-context-menu-skip=""onContextMenu={// Right-click is the desktop stand-in for iOS touch-and-hold —// but only when there's nothing selected. A live highlightdiff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 55be4019271..2a5136c744b 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -214,6 +214,22 @@ declare global {saved: boolean}>saveImageFromUrl: (url: string) => Promise<boolean>+ /** Edit verb against the window's focused element (the custom context+ * menu's Cut/Copy/Paste/Select all). */+ contextMenuEdit?: (command: 'copy' | 'cut' | 'paste' | 'selectAll') => Promise<void>+ /** Copy the image under the LAST context-menu gesture (Chromium tracks+ * its coordinates on the main-process context-menu event). */+ contextMenuCopyImage?: () => Promise<void>+ /** Replace the misspelled word or add it to the dictionary. */+ contextMenuSpellcheck?: (action: { kind: 'add' | 'replace'; word: string }) => Promise<void>+ /** Add a word to the spell-check dictionary of a webview guest's+ * session (the tag exposes no session API). */+ contextMenuGuestAddWord?: (payload: { webContentsId: number; word: string }) => Promise<void>+ /** Spell-check facts for the gesture that opened the current menu;+ * fires shortly after the DOM contextmenu event. */+ onContextMenuSpellcheck?: (+ callback: (payload: { misspelledWord: string; suggestions: string[] }) => void+ ) => () => voidsaveImageBuffer: (data: ArrayBuffer | Uint8Array, ext: string) => Promise<string>saveClipboardImage: () => Promise<string>getPathForFile: (file: File) => string@@ -242,6 +258,8 @@ declare global {}zoom?: {get: () => Promise<{ level: number; percent: number }>+ /** Synchronous zoom factor of this window (1 = 100%). */+ factor?: () => numbersetPercent: (percent: number) => voidonChanged: (callback: (payload: { level: number; percent: number }) => void) => () => void}diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 3dd1ee8b9e4..ec765be5cca 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -2371,6 +2371,29 @@ export const ar = defineLocale({zoneCount: count => `${count} مناطق`,tabCount: count => `${count} تبويبات`},+ contextMenu: {+ link: {+ openInApp: 'فتح في متصفح التطبيق',+ openExternal: 'فتح في المتصفح الخارجي',+ copyUrl: 'نسخ الرابط',+ copyResolvedUrl: 'نسخ الرابط المُحلَّل'+ },+ image: {+ copyImage: 'نسخ الصورة',+ copyImageAddress: 'نسخ عنوان الصورة',+ saveImageAs: 'حفظ الصورة باسم…'+ },+ edit: {+ cut: 'قص',+ paste: 'لصق',+ selectAll: 'تحديد الكل',+ addToDictionary: 'إضافة إلى القاموس'+ },+ page: {+ copyPageUrl: 'نسخ رابط الصفحة',+ inspectElement: 'فحص العنصر'+ }+ },assistant: {thread: {loadingSession: 'جار تحميل الجلسة...',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 7bb35b33133..05990c44f13 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -3003,6 +3003,30 @@ export const en: Translations = {tabCount: count => `${count} tabs`},+ contextMenu: {+ link: {+ openInApp: 'Open in in-app browser',+ openExternal: 'Open in external browser',+ copyUrl: 'Copy URL',+ copyResolvedUrl: 'Copy resolved URL'+ },+ image: {+ copyImage: 'Copy image',+ copyImageAddress: 'Copy image address',+ saveImageAs: 'Save image as…'+ },+ edit: {+ cut: 'Cut',+ paste: 'Paste',+ selectAll: 'Select all',+ addToDictionary: 'Add to dictionary'+ },+ page: {+ copyPageUrl: 'Copy page URL',+ inspectElement: 'Inspect element'+ }+ },+assistant: {thread: {loadingSession: 'Loading session',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 443039f8eab..bbe89872101 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -2660,6 +2660,30 @@ export const ja = defineLocale({tabCount: count => `${count} 個のタブ`},+ contextMenu: {+ link: {+ openInApp: 'アプリ内ブラウザーで開く',+ openExternal: '外部ブラウザーで開く',+ copyUrl: 'URL をコピー',+ copyResolvedUrl: '解決後の URL をコピー'+ },+ image: {+ copyImage: '画像をコピー',+ copyImageAddress: '画像アドレスをコピー',+ saveImageAs: '画像を名前を付けて保存…'+ },+ edit: {+ cut: '切り取り',+ paste: '貼り付け',+ selectAll: 'すべて選択',+ addToDictionary: '辞書に追加'+ },+ page: {+ copyPageUrl: 'ページの URL をコピー',+ inspectElement: '要素を調査'+ }+ },+assistant: {thread: {loadingSession: 'セッションを読み込み中',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 55f2a5af567..49275a74fd3 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -2574,6 +2574,30 @@ export interface Translations {tabCount: (count: number) => string}+ contextMenu: {+ link: {+ openInApp: string+ openExternal: string+ copyUrl: string+ copyResolvedUrl: string+ }+ image: {+ copyImage: string+ copyImageAddress: string+ saveImageAs: string+ }+ edit: {+ cut: string+ paste: string+ selectAll: string+ addToDictionary: string+ }+ page: {+ copyPageUrl: string+ inspectElement: string+ }+ }+assistant: {thread: {loadingSession: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 622e3f74fa0..b56687236b3 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -2573,6 +2573,30 @@ export const zhHant = defineLocale({tabCount: count => `${count} 個分頁`},+ contextMenu: {+ link: {+ openInApp: '在應用程式內瀏覽器中開啟',+ openExternal: '在外部瀏覽器中開啟',+ copyUrl: '複製 URL',+ copyResolvedUrl: '複製解析後的 URL'+ },+ image: {+ copyImage: '複製圖片',+ copyImageAddress: '複製圖片位址',+ saveImageAs: '圖片另存為…'+ },+ edit: {+ cut: '剪下',+ paste: '貼上',+ selectAll: '全選',+ addToDictionary: '新增至字典'+ },+ page: {+ copyPageUrl: '複製頁面 URL',+ inspectElement: '檢查元素'+ }+ },+assistant: {thread: {loadingSession: '正在載入工作階段',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 900102aa749..3b43d0a3b20 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -3168,6 +3168,30 @@ export const zh: Translations = {tabCount: count => `${count} 个标签页`},+ contextMenu: {+ link: {+ openInApp: '在应用内浏览器中打开',+ openExternal: '在外部浏览器中打开',+ copyUrl: '复制 URL',+ copyResolvedUrl: '复制解析后的 URL'+ },+ image: {+ copyImage: '复制图片',+ copyImageAddress: '复制图片地址',+ saveImageAs: '图片另存为…'+ },+ edit: {+ cut: '剪切',+ paste: '粘贴',+ selectAll: '全选',+ addToDictionary: '添加到词典'+ },+ page: {+ copyPageUrl: '复制页面 URL',+ inspectElement: '检查元素'+ }+ },+assistant: {thread: {loadingSession: '正在加载会话',diff --git a/apps/desktop/src/lib/external-link.tsx b/apps/desktop/src/lib/external-link.tsxindex f586a63a215..54a6411d5dd 100644--- a/apps/desktop/src/lib/external-link.tsx+++ b/apps/desktop/src/lib/external-link.tsx@@ -280,6 +280,9 @@ export function ExternalLink({}: ExternalLinkProps) {const target = normalizeExternalUrl(href)+ // No menu wiring here: the app context-menu coordinator resolves a+ // right-click on any `a[href]` to the link menu (open in-app / open+ // external / copy URL / copy resolved URL).return (<aclassName={cn('ref', className)}