Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(browser): native context menu in webview guests
Bas Milius863214f3b625
diff --git a/src/main/index.ts b/src/main/index.tsindex 70f2b3b8a..d5355dcb5 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -16,6 +16,7 @@ installLogSink(logBuffer)import { writeFilesToClipboard } from './clipboard-files'import { pickProjectIcon } from './project-icon-upload'import { allowGuestNavigation } from './webview-nav'+import { guestContextMenuTemplate } from './webview-context-menu'import { BrowserControlLedger } from './browser-control-ledger'import {recordOpenProjectGrant,@@ -1155,6 +1156,44 @@ app.whenReady().then(async () => {}return { action: 'deny' }})+ // Electron ships no context menu for web content, so a right-click inside a guest page did+ // nothing at all. Passing `frame` is what turns on macOS's own AutoFill, Writing Tools and+ // Services submenus (off by default in Electron): that is the "AutoFill > Passwords..." row+ // on a password field. Template and its refusals: webview-context-menu.ts.+ contents.on('context-menu', (_e, params) => {+ const template = guestContextMenuTemplate(+ {+ linkURL: params.linkURL,+ srcURL: params.srcURL,+ mediaType: params.mediaType,+ hasImageContents: params.hasImageContents,+ isEditable: params.isEditable,+ selectionText: params.selectionText,+ misspelledWord: params.misspelledWord,+ dictionarySuggestions: params.dictionarySuggestions,+ editFlags: params.editFlags,+ canGoBack: contents.navigationHistory.canGoBack(),+ canGoForward: contents.navigationHistory.canGoForward()+ },+ {+ back: () => contents.navigationHistory.goBack(),+ forward: () => contents.navigationHistory.goForward(),+ reload: () => contents.reload(),+ // Same route a popup takes: a new browser node, never a real window.+ openLinkInNode: (url) => {+ const sourceNodeId = browserGuests.get(contents.id)?.nodeId+ if (sourceNodeId) sendToMain(IPC.browserNewWindow, { url, sourceNodeId })+ },+ copyText: (text) => clipboard.writeText(text),+ copyImage: () => contents.copyImageAt(params.x, params.y),+ replaceMisspelling: (word) => contents.replaceMisspelling(word),+ inspect: () => contents.inspectElement(params.x, params.y)+ }+ )+ // `frame` is null once the frame navigated away or died; the menu still opens, just without+ // the AppKit additions.+ Menu.buildFromTemplate(template).popup(params.frame ? { frame: params.frame } : {})+ })})settingsStore.init()diff --git a/src/main/webview-context-menu.test.ts b/src/main/webview-context-menu.test.tsnew file mode 100644index 000000000..2cf9432d5--- /dev/null+++ b/src/main/webview-context-menu.test.ts@@ -0,0 +1,166 @@+import { describe, expect, it, vi } from 'vitest'+import type { MenuItemConstructorOptions } from 'electron'+import {+ guestContextMenuTemplate,+ SPELLING_SUGGESTION_MAX,+ type GuestMenuContext,+ type GuestMenuHandlers+} from './webview-context-menu'++const handlers = (): GuestMenuHandlers => ({+ back: vi.fn(),+ forward: vi.fn(),+ reload: vi.fn(),+ openLinkInNode: vi.fn(),+ copyText: vi.fn(),+ copyImage: vi.fn(),+ replaceMisspelling: vi.fn(),+ inspect: vi.fn()+})++const ctx = (over: Partial<GuestMenuContext> = {}): GuestMenuContext => ({+ linkURL: '',+ srcURL: '',+ mediaType: 'none',+ hasImageContents: false,+ isEditable: false,+ selectionText: '',+ misspelledWord: '',+ dictionarySuggestions: [],+ editFlags: {+ canUndo: true,+ canRedo: true,+ canCut: true,+ canCopy: true,+ canPaste: true,+ canDelete: true,+ canSelectAll: true+ },+ canGoBack: false,+ canGoForward: false,+ ...over+})++const labels = (items: MenuItemConstructorOptions[]): string[] =>+ items.map((item) => item.label ?? item.role ?? item.type ?? '')++describe('guestContextMenuTemplate', () => {+ it('offers the editing roles on an editable field', () => {+ const items = guestContextMenuTemplate(ctx({ isEditable: true }), handlers())+ expect(labels(items)).toEqual([+ 'undo',+ 'redo',+ 'separator',+ 'cut',+ 'copy',+ 'paste',+ 'delete',+ 'separator',+ 'selectAll',+ 'separator',+ 'Back',+ 'Forward',+ 'Reload',+ 'separator',+ 'Inspect Element'+ ])+ })++ it('disables an editing role the renderer says is impossible', () => {+ const flags = { ...ctx().editFlags, canPaste: false, canUndo: false }+ const items = guestContextMenuTemplate(ctx({ isEditable: true, editFlags: flags }), handlers())+ expect(items.find((i) => i.role === 'paste')?.enabled).toBe(false)+ expect(items.find((i) => i.role === 'undo')?.enabled).toBe(false)+ expect(items.find((i) => i.role === 'copy')?.enabled).toBe(true)+ })++ it('offers copy for a selection outside an editable field, and nothing else from that block', () => {+ const items = guestContextMenuTemplate(ctx({ selectionText: 'hello' }), handlers())+ expect(labels(items)).toEqual([+ 'copy',+ 'separator',+ 'Back',+ 'Forward',+ 'Reload',+ 'separator',+ 'Inspect Element'+ ])+ })++ it('leaves no leading or doubled separator when every optional block is empty', () => {+ const items = guestContextMenuTemplate(ctx(), handlers())+ expect(labels(items)).toEqual(['Back', 'Forward', 'Reload', 'separator', 'Inspect Element'])+ })++ it('routes a link to a new browser node rather than a popup', () => {+ const h = handlers()+ const items = guestContextMenuTemplate(ctx({ linkURL: 'https://example.com/a' }), h)+ const open = items.find((i) => i.label === 'Open Link in New Browser Node')+ open?.click?.(undefined as never, undefined, undefined as never)+ expect(h.openLinkInNode).toHaveBeenCalledWith('https://example.com/a')+ items.find((i) => i.label === 'Copy Link Address')?.click?.(+ undefined as never,+ undefined,+ undefined as never+ )+ expect(h.copyText).toHaveBeenCalledWith('https://example.com/a')+ })++ it('refuses a non-http link, the same schemes setWindowOpenHandler drops', () => {+ for (const url of ['javascript:alert(1)', 'file:///etc/passwd', 'data:text/html,x']) {+ const items = guestContextMenuTemplate(ctx({ linkURL: url }), handlers())+ expect(labels(items)).not.toContain('Open Link in New Browser Node')+ }+ })++ it('offers the image rows only for an image that has contents', () => {+ const withImage = guestContextMenuTemplate(+ ctx({ mediaType: 'image', hasImageContents: true, srcURL: 'https://x/y.png' }),+ handlers()+ )+ expect(labels(withImage)).toContain('Copy Image')+ expect(labels(withImage)).toContain('Copy Image Address')++ const empty = guestContextMenuTemplate(+ ctx({ mediaType: 'image', hasImageContents: false, srcURL: 'https://x/y.png' }),+ handlers()+ )+ expect(labels(empty)).not.toContain('Copy Image')+ })++ it('omits the image address row when the element has no source url', () => {+ const items = guestContextMenuTemplate(+ ctx({ mediaType: 'image', hasImageContents: true, srcURL: '' }),+ handlers()+ )+ expect(labels(items)).toContain('Copy Image')+ expect(labels(items)).not.toContain('Copy Image Address')+ })++ it('caps the spelling suggestions and replaces the word it was built from', () => {+ const h = handlers()+ const suggestions = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg']+ const items = guestContextMenuTemplate(+ ctx({ isEditable: true, misspelledWord: 'aaa', dictionarySuggestions: suggestions }),+ h+ )+ const shown = suggestions.filter((word) => labels(items).includes(word))+ expect(shown).toEqual(suggestions.slice(0, SPELLING_SUGGESTION_MAX))+ items.find((i) => i.label === 'bb')?.click?.(undefined as never, undefined, undefined as never)+ expect(h.replaceMisspelling).toHaveBeenCalledWith('bb')+ })++ it('shows no suggestions when there is no misspelled word under the cursor', () => {+ const items = guestContextMenuTemplate(+ ctx({ isEditable: true, dictionarySuggestions: ['aa'] }),+ handlers()+ )+ expect(labels(items)).not.toContain('aa')+ })++ it('gates back and forward on the guest history', () => {+ const items = guestContextMenuTemplate(ctx({ canGoBack: true }), handlers())+ expect(items.find((i) => i.label === 'Back')?.enabled).toBe(true)+ expect(items.find((i) => i.label === 'Forward')?.enabled).toBe(false)+ })+})diff --git a/src/main/webview-context-menu.ts b/src/main/webview-context-menu.tsnew file mode 100644index 000000000..aaffe3ae2--- /dev/null+++ b/src/main/webview-context-menu.ts@@ -0,0 +1,142 @@+import type { MenuItemConstructorOptions } from 'electron'++/**+ * The context menu for a <webview> guest (browser and web nodes).+ *+ * Electron ships no menu for web content (Chromium's own is a Chrome-browser feature), so a+ * right-click inside a guest page did nothing at all. Nothing disabled it; it was never built.+ *+ * The reason it matters beyond cut/copy/paste: on macOS the AutoFill, Writing Tools and Services+ * submenus are contributed by AppKit and are **off by default** in Electron. They are enabled by+ * handing the invoking frame to `menu.popup({ frame })`, which the caller in `index.ts` does.+ * That is what puts "AutoFill > Passwords..." on a password field. Note that macOS routes that+ * item to Apple's own Passwords app and ignores third-party managers; there is no API to change+ * it.+ *+ * The template is built here without importing Electron at runtime (the type import is erased),+ * so the shape of the menu is unit-testable: `src/main` has no Electron available under vitest.+ */++/** What the menu can ask of the guest. The caller binds each to its webContents. */+export interface GuestMenuHandlers {+ back(): void+ forward(): void+ reload(): void+ /** Open a link in a NEW browser node, mirroring `setWindowOpenHandler`, never a real popup. */+ openLinkInNode(url: string): void+ copyText(text: string): void+ copyImage(): void+ replaceMisspelling(word: string): void+ inspect(): void+}++/** The subset of Electron's `ContextMenuParams` the template reads. */+export interface GuestMenuContext {+ linkURL: string+ srcURL: string+ mediaType: string+ hasImageContents: boolean+ isEditable: boolean+ selectionText: string+ misspelledWord: string+ dictionarySuggestions: string[]+ editFlags: {+ canUndo: boolean+ canRedo: boolean+ canCut: boolean+ canCopy: boolean+ canPaste: boolean+ canDelete: boolean+ canSelectAll: boolean+ }+ canGoBack: boolean+ canGoForward: boolean+}++/** How many of the spellchecker's suggestions get a row. */+export const SPELLING_SUGGESTION_MAX = 5++const SEPARATOR: MenuItemConstructorOptions = { type: 'separator' }++const isHttpUrl = (url: string): boolean => /^https?:\/\//i.test(url)++/**+ * Drop leading, trailing and doubled separators, so a section that contributed nothing leaves no+ * rule behind. Same rule as the renderer's own menus (`tidySeparators` in lib/ui-visibility.ts),+ * duplicated rather than shared because the renderer may not import `src/main`.+ */+function tidy(items: MenuItemConstructorOptions[]): MenuItemConstructorOptions[] {+ const out: MenuItemConstructorOptions[] = []+ for (const item of items) {+ if (item.type === 'separator' && out.length === 0) continue+ if (item.type === 'separator' && out[out.length - 1]?.type === 'separator') continue+ out.push(item)+ }+ while (out.length > 0 && out[out.length - 1]?.type === 'separator') out.pop()+ return out+}++/**+ * Build the guest's context menu.+ *+ * The editing block uses Electron **roles** rather than explicit `webContents.cut()` calls: the+ * roles carry the OS's own localized labels and accelerators, which is what makes our menu look+ * like the native one the AutoFill and Services items are appended to. Enablement comes from+ * `editFlags`, because a role does not disable itself.+ */+export function guestContextMenuTemplate(+ ctx: GuestMenuContext,+ handlers: GuestMenuHandlers+): MenuItemConstructorOptions[] {+ const items: MenuItemConstructorOptions[] = []++ if (ctx.misspelledWord && ctx.dictionarySuggestions.length > 0) {+ for (const word of ctx.dictionarySuggestions.slice(0, SPELLING_SUGGESTION_MAX)) {+ items.push({ label: word, click: () => handlers.replaceMisspelling(word) })+ }+ items.push(SEPARATOR)+ }++ if (isHttpUrl(ctx.linkURL)) {+ items.push(+ { label: 'Open Link in New Browser Node', click: () => handlers.openLinkInNode(ctx.linkURL) },+ { label: 'Copy Link Address', click: () => handlers.copyText(ctx.linkURL) },+ SEPARATOR+ )+ }++ if (ctx.mediaType === 'image' && ctx.hasImageContents) {+ items.push({ label: 'Copy Image', click: () => handlers.copyImage() })+ if (ctx.srcURL) {+ items.push({ label: 'Copy Image Address', click: () => handlers.copyText(ctx.srcURL) })+ }+ items.push(SEPARATOR)+ }++ if (ctx.isEditable) {+ items.push(+ { role: 'undo', enabled: ctx.editFlags.canUndo },+ { role: 'redo', enabled: ctx.editFlags.canRedo },+ SEPARATOR,+ { role: 'cut', enabled: ctx.editFlags.canCut },+ { role: 'copy', enabled: ctx.editFlags.canCopy },+ { role: 'paste', enabled: ctx.editFlags.canPaste },+ { role: 'delete', enabled: ctx.editFlags.canDelete },+ SEPARATOR,+ { role: 'selectAll', enabled: ctx.editFlags.canSelectAll },+ SEPARATOR+ )+ } else if (ctx.selectionText) {+ items.push({ role: 'copy', enabled: ctx.editFlags.canCopy }, SEPARATOR)+ }++ items.push(+ { label: 'Back', enabled: ctx.canGoBack, click: () => handlers.back() },+ { label: 'Forward', enabled: ctx.canGoForward, click: () => handlers.forward() },+ { label: 'Reload', click: () => handlers.reload() },+ SEPARATOR,+ { label: 'Inspect Element', click: () => handlers.inspect() }+ )++ return tidy(items)+}