diff --git a/src/main/browser/browser-grab-payload.ts b/src/main/browser/browser-grab-payload.ts new file mode 100644 index 000000000..0e8a7c2f6 --- /dev/null +++ b/src/main/browser/browser-grab-payload.ts @@ -0,0 +1,178 @@ +import type { BrowserGrabPayload, BrowserGrabRect } from '../../shared/browser-grab-types' +import { + GRAB_BUDGET, + GRAB_SAFE_ATTRIBUTE_NAMES, + GRAB_SECRET_PATTERNS +} from '../../shared/browser-grab-types' + +/** + * Re-validate and clamp all string, array, and budget fields in a grab payload + * before forwarding to the renderer. This is the main-side safety net: even if + * the guest runtime is compromised, the payload that reaches renderer chrome + * respects the documented budgets. + * + * Returns null if the payload is structurally invalid (missing required fields). + */ +export function clampGrabPayload(raw: unknown): BrowserGrabPayload | null { + // Why: the guest payload is completely untrusted. A compromised or + // malfunctioning guest could return anything. Validate structural shape + // before accessing nested properties to avoid unhandled TypeErrors. + if (!raw || typeof raw !== 'object') { + return null + } + const obj = raw as Record + if (!obj.page || typeof obj.page !== 'object') { + return null + } + if (!obj.target || typeof obj.target !== 'object') { + return null + } + + const page = obj.page as Record + const target = obj.target as Record + + const clampStr = (s: unknown, max: number): string => { + const str = typeof s === 'string' ? s : '' + if (str.length <= max) { + return str + } + return `${str.slice(0, max)} (truncated)` + } + + const clampArray = (arr: unknown, maxEntries: number, maxEntryLength: number): string[] => { + const items = Array.isArray(arr) ? arr : [] + return items.slice(0, maxEntries).map((item) => clampStr(item, maxEntryLength)) + } + + const safeStr = (s: unknown, max = 500): string => clampStr(s, max) + + const safeNum = (n: unknown, fallback = 0): number => + typeof n === 'number' && Number.isFinite(n) ? n : fallback + + // Why: mirror the guest-side secret detection on the main side so a + // compromised guest cannot smuggle secret-bearing values through attributes + // or URLs. This is the defense-in-depth layer. + const containsSecret = (val: string): boolean => { + const lower = val.toLowerCase() + return GRAB_SECRET_PATTERNS.some((p) => lower.includes(p)) + } + + // Why: mirror the guest-side URL sanitization. Strip query strings and + // fragments to prevent token leakage even if the guest is compromised. + const sanitizeUrl = (rawUrl: unknown): string => { + const str = typeof rawUrl === 'string' ? rawUrl : '' + if (!str) { + return '' + } + try { + const url = new URL(str) + url.search = '' + url.hash = '' + return url.toString() + } catch { + // Why: returning the raw string on parse failure could preserve + // javascript: URIs or other non-http schemes. Return empty. + return '' + } + } + + // Why: re-filter attributes on the main side so a compromised guest cannot + // smuggle unsafe attribute names (e.g., event handlers) or secret-bearing + // values into the payload that reaches the renderer. + const safeAttributes = (attrs: unknown): Record => { + if (!attrs || typeof attrs !== 'object') { + return {} + } + const filtered: Record = {} + for (const [key, value] of Object.entries(attrs as Record)) { + const name = key.toLowerCase() + const isAria = name.startsWith('aria-') + const isSafe = GRAB_SAFE_ATTRIBUTE_NAMES.has(name) + if (!isAria && !isSafe) { + continue + } + const strValue = safeStr(value, 2000) + if (containsSecret(strValue)) { + filtered[name] = '[redacted]' + } else if ((name === 'href' || name === 'src' || name === 'action') && strValue) { + filtered[name] = sanitizeUrl(strValue) + } else if (name === 'class') { + filtered[name] = safeStr(value, 200) + } else { + filtered[name] = safeStr(value, 500) + } + } + return filtered + } + + const safeRect = (r: unknown): BrowserGrabRect => { + if (!r || typeof r !== 'object') { + return { x: 0, y: 0, width: 0, height: 0 } + } + const rect = r as Record + return { + x: safeNum(rect.x), + y: safeNum(rect.y), + width: safeNum(rect.width), + height: safeNum(rect.height) + } + } + + const accessibility = target.accessibility as Record | null | undefined + const computedStyles = target.computedStyles as Record | null | undefined + + return { + page: { + // Why: re-sanitize the URL main-side so a compromised guest cannot + // pass through query strings containing tokens or secrets. + sanitizedUrl: sanitizeUrl(page.sanitizedUrl), + title: safeStr(page.title, 500), + viewportWidth: safeNum(page.viewportWidth), + viewportHeight: safeNum(page.viewportHeight), + scrollX: safeNum(page.scrollX), + scrollY: safeNum(page.scrollY), + devicePixelRatio: safeNum(page.devicePixelRatio, 1), + capturedAt: safeStr(page.capturedAt, 100) + }, + target: { + tagName: safeStr(target.tagName, 50), + selector: safeStr(target.selector, 500), + textSnippet: clampStr(target.textSnippet, GRAB_BUDGET.textSnippetMaxLength), + htmlSnippet: clampStr(target.htmlSnippet, GRAB_BUDGET.htmlSnippetMaxLength), + attributes: safeAttributes(target.attributes), + accessibility: { + role: safeStr(accessibility?.role) || null, + accessibleName: safeStr(accessibility?.accessibleName) || null, + ariaLabel: safeStr(accessibility?.ariaLabel) || null, + ariaLabelledBy: safeStr(accessibility?.ariaLabelledBy) || null + }, + rectViewport: safeRect(target.rectViewport), + rectPage: safeRect(target.rectPage), + computedStyles: { + display: safeStr(computedStyles?.display), + position: safeStr(computedStyles?.position), + width: safeStr(computedStyles?.width), + height: safeStr(computedStyles?.height), + margin: safeStr(computedStyles?.margin), + padding: safeStr(computedStyles?.padding), + color: safeStr(computedStyles?.color), + backgroundColor: safeStr(computedStyles?.backgroundColor), + border: safeStr(computedStyles?.border), + borderRadius: safeStr(computedStyles?.borderRadius), + fontFamily: safeStr(computedStyles?.fontFamily), + fontSize: safeStr(computedStyles?.fontSize), + fontWeight: safeStr(computedStyles?.fontWeight), + lineHeight: safeStr(computedStyles?.lineHeight), + textAlign: safeStr(computedStyles?.textAlign), + zIndex: safeStr(computedStyles?.zIndex) + } + }, + nearbyText: clampArray( + obj.nearbyText, + GRAB_BUDGET.nearbyTextMaxEntries, + GRAB_BUDGET.nearbyTextEntryMaxLength + ), + ancestorPath: clampArray(obj.ancestorPath, GRAB_BUDGET.ancestorPathMaxEntries, 200), + screenshot: null + } +} diff --git a/src/main/browser/browser-grab-screenshot.ts b/src/main/browser/browser-grab-screenshot.ts new file mode 100644 index 000000000..54e403b13 --- /dev/null +++ b/src/main/browser/browser-grab-screenshot.ts @@ -0,0 +1,96 @@ +import type { BrowserGrabRect, BrowserGrabScreenshot } from '../../shared/browser-grab-types' +import { GRAB_BUDGET } from '../../shared/browser-grab-types' + +/** + * Capture a screenshot of the guest surface and optionally crop it to + * the given CSS-pixel rect. + */ +export async function captureSelectionScreenshot( + rect: BrowserGrabRect, + guest: Electron.WebContents +): Promise { + try { + // Why: the rect comes from the renderer via IPC. Validate that all fields + // are finite numbers before using them in arithmetic, so NaN cannot reach + // Electron's image.crop() and cause undefined behavior. + const safeN = (n: unknown, fallback = 0): number => + typeof n === 'number' && Number.isFinite(n) ? n : fallback + const safeRect = { + x: safeN(rect.x), + y: safeN(rect.y), + width: safeN(rect.width), + height: safeN(rect.height) + } + + // Why: hide the grab overlay before capturing so the highlight box and + // label don't appear in the screenshot. The overlay is restored after. + // Wrapped in try/finally so the overlay is always restored even if + // capturePage() throws (e.g., guest destroyed mid-capture). + await guest + .executeJavaScript( + `(function(){ var g = window.__orcaGrab; if (g && g.host) g.host.style.display = 'none'; })()` + ) + .catch(() => {}) + let image: Electron.NativeImage + try { + image = await guest.capturePage() + } finally { + await guest + .executeJavaScript( + `(function(){ var g = window.__orcaGrab; if (g && g.host) g.host.style.display = ''; })()` + ) + .catch(() => {}) + } + if (image.isEmpty()) { + return null + } + + const bitmapSize = image.getSize() + // Why: capturePage returns a bitmap in physical pixels. The grab rect is + // in CSS pixels. To map between them we need the combined scale factor + // (zoomFactor * deviceScaleFactor). Rather than using the primary display + // (which is wrong on multi-monitor setups with mixed DPI), we derive the + // scale factor empirically: ask the guest for its CSS viewport width, then + // compute scaleFactor = bitmapWidth / viewportCSSWidth. This is correct + // regardless of which display the window is on. + const viewportCSSWidth: number = await guest.executeJavaScript('window.innerWidth') + if (!viewportCSSWidth || viewportCSSWidth <= 0) { + return null + } + const scaleFactor = bitmapSize.width / viewportCSSWidth + + // Map CSS-pixel rect to bitmap coordinates + const cropX = Math.max(0, Math.round(safeRect.x * scaleFactor)) + const cropY = Math.max(0, Math.round(safeRect.y * scaleFactor)) + const cropW = Math.min(bitmapSize.width - cropX, Math.round(safeRect.width * scaleFactor)) + const cropH = Math.min(bitmapSize.height - cropY, Math.round(safeRect.height * scaleFactor)) + + if (cropW <= 0 || cropH <= 0) { + return null + } + + const cropped = image.crop({ x: cropX, y: cropY, width: cropW, height: cropH }) + const pngBuffer = cropped.toPNG() + + // Why: downscaling would add complexity for v1. Fail closed to + // "no screenshot" rather than send an oversized payload. + if (pngBuffer.byteLength > GRAB_BUDGET.screenshotMaxBytes) { + return null + } + + const dataUrl = `data:image/png;base64,${pngBuffer.toString('base64')}` + // Why: cropW/cropH are in physical pixels (bitmap coordinates) but the + // rest of the grab payload uses CSS pixels. Divide by scaleFactor so the + // screenshot dimensions are consistent with rectViewport/rectPage. + return { + mimeType: 'image/png', + dataUrl, + width: Math.round(cropW / scaleFactor), + height: Math.round(cropH / scaleFactor) + } + } catch { + // Why: screenshot capture can fail if the guest is being torn down + // or the compositor surface is not available. Fail closed. + return null + } +} diff --git a/src/main/browser/browser-grab-session-controller.ts b/src/main/browser/browser-grab-session-controller.ts new file mode 100644 index 000000000..152460abe --- /dev/null +++ b/src/main/browser/browser-grab-session-controller.ts @@ -0,0 +1,194 @@ +import type { BrowserGrabCancelReason, BrowserGrabResult } from '../../shared/browser-grab-types' +import { buildGuestOverlayScript } from './grab-guest-script' +import { clampGrabPayload } from './browser-grab-payload' + +/** Tracks the lifecycle of a single grab operation on one browser tab. */ +type ActiveGrabOp = { + opId: string + browserTabId: string + guestWebContentsId: number + resolve: (result: BrowserGrabResult) => void + /** Cleanup listeners and optionally inject teardown. + * @param preserveOverlay When true, skip teardown injection so the guest + * overlay stays visible (used when a selection succeeds and the copy menu + * is shown). */ + cleanup: (preserveOverlay?: boolean) => void + /** When true, cleanup skips the teardown injection. Set by awaitGrabSelection + * when replacing an existing op so the freshly-armed overlay is preserved. */ + skipTeardown?: boolean +} + +/** Hard timeout for an armed grab operation to prevent indefinite hangs. */ +const GRAB_OP_TIMEOUT_MS = 120_000 + +export class BrowserGrabSessionController { + private readonly activeGrabOps = new Map() + + hasActiveGrabOp(browserTabId: string): boolean { + return this.activeGrabOps.has(browserTabId) + } + + cancelGrabOp(browserTabId: string, reason: BrowserGrabCancelReason): void { + const op = this.activeGrabOps.get(browserTabId) + if (!op) { + return + } + // Why: settleOnce (op.resolve) already calls op.cleanup() and deletes the + // map entry. Calling them again here would double-inject the teardown script. + op.resolve({ opId: op.opId, kind: 'cancelled', reason }) + } + + cancelAll(reason: BrowserGrabCancelReason): void { + for (const browserTabId of this.activeGrabOps.keys()) { + this.cancelGrabOp(browserTabId, reason) + } + } + + /** + * Await a single grab selection on the given tab. Returns a Promise that + * resolves exactly once when the user clicks, cancels, or an error occurs. + * + * Why the click is handled in-guest rather than via main-side interception: + * Electron's `before-input-event` only fires for keyboard events, not mouse + * events on guest webContents. The design doc anticipated a main-owned + * interceptor, but the spike showed this API gap. The fallback (documented + * in the design doc) is to let the guest overlay's full-viewport hit-catcher + * consume the click. The overlay calls `stopPropagation()` and + * `preventDefault()` so the page underneath does not receive the event. + * This is not a perfect guarantee (capture-phase listeners on window may + * still fire), but it covers the vast majority of sites. + */ + awaitGrabSelection( + browserTabId: string, + opId: string, + guest: Electron.WebContents + ): Promise { + // Why: only one active grab operation per tab prevents race conditions + // where a late click from a previous operation resolves the wrong Promise. + const existing = this.activeGrabOps.get(browserTabId) + if (existing) { + // Why: skip teardown injection when replacing an op. The new op will + // reuse the already-armed overlay. If we injected teardown here, it + // would race with the new awaitClick script in the guest's JS queue + // and destroy the overlay before the click handler is installed. + existing.skipTeardown = true + existing.resolve({ opId: existing.opId, kind: 'cancelled', reason: 'user' }) + } + + return new Promise((resolve) => { + const guestWebContentsId = guest.id + let settled = false + + const settleOnce = (result: BrowserGrabResult): void => { + if (settled) { + return + } + settled = true + clearTimeout(timeoutId) + // Why: when the user successfully selects an element, keep the guest + // overlay visible so the highlight box persists while the renderer + // shows the copy menu. Teardown happens later when the renderer calls + // setGrabMode(false) or re-arms with a fresh armAndAwait cycle. + op.cleanup(result.kind === 'selected' || result.kind === 'context-selected') + this.activeGrabOps.delete(browserTabId) + resolve(result) + } + + // Why: the guest overlay runtime handles the click in-page and calls + // __orcaGrabResolve() which is wired by the 'awaitClick' script to + // resolve the executeJavaScript Promise with the extracted payload. + // Main just needs to run that script and await its result. + const awaitGuestClick = async (): Promise => { + try { + const rawPayload = await guest.executeJavaScript(buildGuestOverlayScript('awaitClick')) + if (!rawPayload || typeof rawPayload !== 'object') { + settleOnce({ opId, kind: 'cancelled', reason: 'user' }) + return + } + // Why: the guest wraps right-click results in { __orcaContextMenu, payload } + // so the renderer can show the full action dropdown instead of auto-copying. + const isContextMenu = + '__orcaContextMenu' in (rawPayload as Record) && + (rawPayload as Record).__orcaContextMenu === true + const payloadSource = isContextMenu + ? (rawPayload as Record).payload + : rawPayload + const payload = clampGrabPayload(payloadSource) + if (!payload) { + settleOnce({ opId, kind: 'error', reason: 'Guest returned invalid payload structure' }) + return + } + settleOnce({ + opId, + kind: isContextMenu ? 'context-selected' : 'selected', + payload + }) + } catch (err) { + const message = err instanceof Error ? err.message : 'Selection failed' + if (message.includes('cancelled')) { + settleOnce({ opId, kind: 'cancelled', reason: 'user' }) + } else { + settleOnce({ opId, kind: 'error', reason: message }) + } + } + } + + // Why: only cancel on main-frame navigations. Subframe navigations + // (e.g., iframe ads loading) should not spuriously cancel the grab. + const handleNavigation = ( + _event: unknown, + _url: unknown, + _isInPlace: unknown, + isMainFrame: boolean + ): void => { + if (isMainFrame) { + settleOnce({ opId, kind: 'cancelled', reason: 'navigation' }) + } + } + + const handleDestroyed = (): void => { + settleOnce({ opId, kind: 'cancelled', reason: 'evicted' }) + } + + const timeoutId = setTimeout(() => { + settleOnce({ opId, kind: 'cancelled', reason: 'timeout' }) + }, GRAB_OP_TIMEOUT_MS) + + guest.on('did-start-navigation', handleNavigation) + guest.on('destroyed', handleDestroyed) + + const cleanup = (preserveOverlay?: boolean): void => { + try { + guest.off('did-start-navigation', handleNavigation) + guest.off('destroyed', handleDestroyed) + } catch { + // Why: the guest may already be destroyed during teardown. + // Cleanup is best-effort. + } + // Why: skip teardown injection when (a) the op is being replaced by a + // new op (skipTeardown), or (b) the selection succeeded and the overlay + // should stay visible while the copy menu is shown (preserveOverlay). + if (op.skipTeardown || preserveOverlay) { + return + } + try { + if (!guest.isDestroyed()) { + void guest.executeJavaScript(buildGuestOverlayScript('teardown')) + } + } catch { + // Best-effort overlay removal + } + } + + const op: ActiveGrabOp = { + opId, + browserTabId, + guestWebContentsId, + resolve: settleOnce, + cleanup + } + this.activeGrabOps.set(browserTabId, op) + void awaitGuestClick() + }) + } +} diff --git a/src/main/browser/browser-guest-ui.ts b/src/main/browser/browser-guest-ui.ts new file mode 100644 index 000000000..0ead72552 --- /dev/null +++ b/src/main/browser/browser-guest-ui.ts @@ -0,0 +1,267 @@ +import { clipboard, Menu, webContents } from 'electron' +import { normalizeExternalBrowserUrl } from '../../shared/browser-url' +import { + isWindowShortcutModifierChord, + resolveWindowShortcutAction +} from '../../shared/window-shortcut-policy' + +type ResolveRenderer = (browserTabId: string) => Electron.WebContents | null + +export function setupGuestContextMenu(args: { + browserTabId: string + guest: Electron.WebContents + openValidatedExternal: (rawUrl: string) => void + openDevTools: (browserTabId: string) => Promise +}): () => void { + const { browserTabId, guest, openValidatedExternal, openDevTools } = args + const handler = (_event: Electron.Event, params: Electron.ContextMenuParams): void => { + const pageUrl = guest.getURL() + const linkUrl = params.linkURL || '' + + const template: Electron.MenuItemConstructorOptions[] = [] + + if (linkUrl) { + const externalLinkUrl = normalizeExternalBrowserUrl(linkUrl) + template.push( + { + label: 'Open Link In Default Browser', + enabled: Boolean(externalLinkUrl && externalLinkUrl !== 'about:blank'), + click: () => { + openValidatedExternal(linkUrl) + } + }, + { + label: 'Copy Link Address', + click: () => { + clipboard.writeText(linkUrl) + } + }, + { type: 'separator' } + ) + } + + const externalPageUrl = normalizeExternalBrowserUrl(pageUrl) + + template.push( + { + label: 'Back', + enabled: guest.canGoBack(), + click: () => guest.goBack() + }, + { + label: 'Forward', + enabled: guest.canGoForward(), + click: () => guest.goForward() + }, + { + label: 'Reload', + click: () => guest.reload() + }, + { type: 'separator' }, + { + label: 'Open Page In Default Browser', + enabled: Boolean(externalPageUrl && externalPageUrl !== 'about:blank'), + click: () => { + openValidatedExternal(pageUrl) + } + }, + { + label: 'Copy Page URL', + enabled: Boolean(pageUrl), + click: () => { + clipboard.writeText(pageUrl) + } + }, + { type: 'separator' }, + { + label: 'Inspect Page', + click: () => { + void openDevTools(browserTabId) + } + } + ) + + Menu.buildFromTemplate(template).popup() + } + + guest.on('context-menu', handler) + return () => { + try { + guest.off('context-menu', handler) + } catch { + // Why: browser tabs can outlive the guest webContents briefly during + // teardown. Cleanup should be best-effort instead of throwing while the + // IDE is closing a tab. + } + } +} + +// Why: browser grab mode intentionally uses Cmd/Ctrl+C as its entry +// gesture, but a focused webview guest is a separate Chromium process so +// the renderer's window-level keydown handler never sees that shortcut. +// Only forward the chord when Chromium would not perform a normal copy: +// no editable element is focused and there is no selected text. That keeps +// native page copy working while still making the grab shortcut reachable +// from focused web content. +export function setupGrabShortcutForwarding(args: { + browserTabId: string + guest: Electron.WebContents + resolveRenderer: ResolveRenderer + hasActiveGrabOp: (browserTabId: string) => boolean +}): () => void { + const { browserTabId, guest, resolveRenderer, hasActiveGrabOp } = args + const handler = (event: Electron.Event, input: Electron.Input): void => { + if (input.type !== 'keyDown') { + return + } + const bareKey = input.key.toLowerCase() + if ( + !input.meta && + !input.control && + !input.alt && + !input.shift && + (bareKey === 'c' || bareKey === 's') && + hasActiveGrabOp(browserTabId) + ) { + const renderer = resolveRenderer(browserTabId) + if (!renderer) { + return + } + // Why: a focused guest swallows bare keys before the renderer sees them. + // While grab mode is actively awaiting a pick, plain C/S belong to Orca's + // copy/screenshot shortcuts rather than the page's typing behavior. + event.preventDefault() + renderer.send('browser:grabActionShortcut', { browserTabId, key: bareKey }) + return + } + + const isMod = process.platform === 'darwin' ? input.meta : input.control + if (!isMod || input.shift || input.alt || bareKey !== 'c') { + return + } + + void guest + .executeJavaScript(`(() => { + const active = document.activeElement + const tag = active?.tagName + const isEditable = + active instanceof HTMLInputElement || + active instanceof HTMLTextAreaElement || + active?.isContentEditable === true || + tag === 'SELECT' || + tag === 'IFRAME' + if (isEditable) { + return false + } + const selection = window.getSelection() + return Boolean(selection && selection.type === 'Range' && selection.toString().trim().length > 0) + ? false + : true + })()`) + .then((shouldToggle) => { + if (!shouldToggle) { + return + } + event.preventDefault() + const renderer = resolveRenderer(browserTabId) + if (!renderer) { + return + } + renderer.send('browser:grabModeToggle', browserTabId) + }) + .catch(() => { + // Why: shortcut forwarding is best-effort. Guest teardown or a + // transient executeJavaScript failure should not break normal copy. + }) + } + + guest.on('before-input-event', handler) + return () => { + try { + guest.off('before-input-event', handler) + } catch { + // Why: browser tabs can outlive the guest webContents briefly during + // teardown. Cleanup should be best-effort. + } + } +} + +// Why: a focused webview guest is a separate Chromium process — keyboard +// events go to the guest's own webContents and never fire the renderer's +// window-level keydown handler or the main window's before-input-event. +// Intercept common app shortcuts on the guest and forward them to the +// renderer so they work consistently regardless of which surface has focus. +export function setupGuestShortcutForwarding(args: { + browserTabId: string + guest: Electron.WebContents + resolveRenderer: ResolveRenderer +}): () => void { + const { browserTabId, guest, resolveRenderer } = args + const handler = (event: Electron.Event, input: Electron.Input): void => { + if (input.type !== 'keyDown') { + return + } + // Why: browser guests need a broader modifier-chord gate than the main + // window because they also forward guest-specific tab shortcuts + // (Cmd/Ctrl+T/W/Shift+B/Shift+[ / ]) in addition to the shared allowlist + // handled by resolveWindowShortcutAction(). + if (!isWindowShortcutModifierChord(input, process.platform)) { + return + } + + const renderer = resolveRenderer(browserTabId) + if (!renderer) { + return + } + + // Why: centralizing the shared subset still keeps guest forwarding in + // lockstep with the main window for the chords that must never steal + // readline control input above the terminal. + const action = resolveWindowShortcutAction(input, process.platform) + + if (input.code === 'KeyB' && input.shift) { + renderer.send('ui:newBrowserTab') + } else if (input.code === 'KeyT' && !input.shift) { + renderer.send('ui:newTerminalTab') + } else if (input.code === 'KeyW' && !input.shift) { + renderer.send('ui:closeActiveTab') + } else if (input.shift && (input.code === 'BracketRight' || input.code === 'BracketLeft')) { + renderer.send('ui:switchTab', input.code === 'BracketRight' ? 1 : -1) + } else if (action?.type === 'toggleWorktreePalette') { + renderer.send('ui:toggleWorktreePalette') + } else if (action?.type === 'openQuickOpen') { + renderer.send('ui:openQuickOpen') + } else if (action?.type === 'jumpToWorktreeIndex') { + renderer.send('ui:jumpToWorktreeIndex', action.index) + } else { + return + } + // Why: preventDefault stops the guest page from also processing the chord + // (e.g. Cmd+T opening a browser-internal new-tab page). + event.preventDefault() + } + + guest.on('before-input-event', handler) + return () => { + try { + guest.off('before-input-event', handler) + } catch { + // Why: best-effort — guest may already be destroyed during teardown. + } + } +} + +export function resolveRendererWebContents( + rendererWebContentsIdByTabId: ReadonlyMap, + browserTabId: string +): Electron.WebContents | null { + const rendererWcId = rendererWebContentsIdByTabId.get(browserTabId) + if (!rendererWcId) { + return null + } + const renderer = webContents.fromId(rendererWcId) + if (!renderer || renderer.isDestroyed()) { + return null + } + return renderer +} diff --git a/src/main/browser/browser-manager-grab.test.ts b/src/main/browser/browser-manager-grab.test.ts index 6511e9b5e..101e08cc5 100644 --- a/src/main/browser/browser-manager-grab.test.ts +++ b/src/main/browser/browser-manager-grab.test.ts @@ -3,6 +3,7 @@ lifecycle (arm/await/cancel/teardown), navigation/destruction auto-cancel, and main-side payload validation. Splitting across files would scatter the shared mock setup and make it harder to verify the grab contract holistically. */ import { beforeEach, describe, expect, it, vi } from 'vitest' +import { GRAB_BUDGET } from '../../shared/browser-grab-types' const { webContentsFromIdMock, @@ -182,6 +183,62 @@ describe('browserManager grab operations', () => { expect(preventDefault).not.toHaveBeenCalled() expect(rendererSendMock).not.toHaveBeenCalled() }) + + it('forwards bare s from the guest while a grab op is active', async () => { + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + void browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + + const handler = guestOnMock.mock.calls.find( + ([eventName]) => eventName === 'before-input-event' + )?.[1] + expect(handler).toBeTypeOf('function') + + const preventDefault = vi.fn() + handler?.( + { preventDefault } as never, + { + type: 'keyDown', + meta: false, + control: false, + shift: false, + alt: false, + key: 's' + } as never + ) + + expect(preventDefault).toHaveBeenCalledTimes(1) + expect(rendererSendMock).toHaveBeenCalledWith('browser:grabActionShortcut', { + browserTabId: 'tab-1', + key: 's' + }) + }) + }) + + describe('guest app shortcut forwarding', () => { + it('forwards Cmd/Ctrl+Shift+B to the renderer and prevents the guest default', () => { + const handlers = guestOnMock.mock.calls + .filter(([eventName]) => eventName === 'before-input-event') + .map(([, handler]) => handler) + const forwardingHandler = handlers[1] + expect(forwardingHandler).toBeTypeOf('function') + + const preventDefault = vi.fn() + forwardingHandler?.( + { preventDefault } as never, + { + type: 'keyDown', + meta: true, + control: true, + shift: true, + alt: false, + code: 'KeyB', + key: 'B' + } as never + ) + + expect(preventDefault).toHaveBeenCalledTimes(1) + expect(rendererSendMock).toHaveBeenCalledWith('ui:newBrowserTab') + }) }) describe('hasActiveGrabOp', () => { @@ -458,6 +515,85 @@ describe('browserManager grab operations', () => { ) expect(teardownCalls).toHaveLength(0) }) + + it('times out if the guest never settles the armed selection', async () => { + vi.useFakeTimers() + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + + const resultPromise = browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + await vi.advanceTimersByTimeAsync(120_000) + + const result = await resultPromise + expect(result).toEqual({ opId: 'op-1', kind: 'cancelled', reason: 'timeout' }) + + vi.useRealTimers() + }) + + it('ignores a late guest selection after the op was already cancelled', async () => { + let resolveGuestSelection!: (value: unknown) => void + guestExecuteJavaScriptMock.mockImplementation( + () => + new Promise((resolve) => { + resolveGuestSelection = resolve + }) + ) + + const resultPromise = browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + browserManager.cancelGrabOp('tab-1', 'user') + + expect(resolveGuestSelection).toBeTypeOf('function') + resolveGuestSelection({ + page: { + sanitizedUrl: 'https://example.com/', + title: 'Late result', + viewportWidth: 1280, + viewportHeight: 720, + scrollX: 0, + scrollY: 0, + devicePixelRatio: 2, + capturedAt: '2026-04-10T00:00:00.000Z' + }, + target: { + tagName: 'button', + selector: 'button', + textSnippet: 'Late click', + htmlSnippet: '', + attributes: {}, + accessibility: { + role: 'button', + accessibleName: 'Late click', + ariaLabel: null, + ariaLabelledBy: null + }, + rectViewport: { x: 0, y: 0, width: 100, height: 40 }, + rectPage: { x: 0, y: 0, width: 100, height: 40 }, + computedStyles: { + display: 'block', + position: 'static', + width: '100px', + height: '40px', + margin: '0', + padding: '0', + color: '#000', + backgroundColor: '#fff', + border: 'none', + borderRadius: '0', + fontFamily: 'sans-serif', + fontSize: '14px', + fontWeight: '400', + lineHeight: '20px', + textAlign: 'left', + zIndex: 'auto' + } + }, + nearbyText: [], + ancestorPath: [], + screenshot: null + }) + + const result = await resultPromise + expect(result).toEqual({ opId: 'op-1', kind: 'cancelled', reason: 'user' }) + }) }) describe('cancelGrabOp', () => { @@ -500,6 +636,37 @@ describe('browserManager grab operations', () => { const result = await promise expect(result).toEqual({ opId: 'op-1', kind: 'cancelled', reason: 'evicted' }) }) + + it('cancels active grab when the same tab is re-registered to a new guest', async () => { + const replacementGuest = makeGuest(202) + guestExecuteJavaScriptMock.mockImplementation(() => new Promise(() => {})) + + const promise = browserManager.awaitGrabSelection('tab-1', 'op-1', guest) + webContentsFromIdMock.mockImplementation((id: number) => { + if (id === 101) { + return guest + } + if (id === 202) { + return replacementGuest + } + if (id === rendererWebContentsId) { + return { + isDestroyed: rendererIsDestroyedMock, + send: rendererSendMock + } + } + return null + }) + browserManager.attachGuestPolicies(replacementGuest) + browserManager.registerGuest({ + browserTabId: 'tab-1', + webContentsId: 202, + rendererWebContentsId + }) + + const result = await promise + expect(result).toEqual({ opId: 'op-1', kind: 'cancelled', reason: 'evicted' }) + }) }) describe('navigation auto-cancel', () => { @@ -556,4 +723,137 @@ describe('browserManager grab operations', () => { expect(result).toEqual({ opId: 'op-1', kind: 'cancelled', reason: 'evicted' }) }) }) + + describe('captureSelectionScreenshot', () => { + it('captures, crops, and converts screenshot dimensions back to CSS pixels', async () => { + const cropMock = vi.fn(() => ({ + toPNG: vi.fn(() => Buffer.from('png-data')) + })) + guestCapturePageMock.mockResolvedValue({ + isEmpty: vi.fn(() => false), + getSize: vi.fn(() => ({ width: 2000, height: 1000 })), + crop: cropMock + }) + guestExecuteJavaScriptMock.mockImplementation(async (script: string) => + script === 'window.innerWidth' ? 1000 : undefined + ) + + const screenshot = await browserManager.captureSelectionScreenshot( + 'tab-1', + { x: 10, y: 20, width: 100, height: 50 }, + guest + ) + + expect(cropMock).toHaveBeenCalledWith({ x: 20, y: 40, width: 200, height: 100 }) + expect(screenshot).toEqual({ + mimeType: 'image/png', + dataUrl: `data:image/png;base64,${Buffer.from('png-data').toString('base64')}`, + width: 100, + height: 50 + }) + expect(guestExecuteJavaScriptMock).toHaveBeenNthCalledWith( + 1, + `(function(){ var g = window.__orcaGrab; if (g && g.host) g.host.style.display = 'none'; })()` + ) + expect(guestExecuteJavaScriptMock).toHaveBeenNthCalledWith( + 2, + `(function(){ var g = window.__orcaGrab; if (g && g.host) g.host.style.display = ''; })()` + ) + expect(guestExecuteJavaScriptMock).toHaveBeenNthCalledWith(3, 'window.innerWidth') + }) + + it('omits screenshots that exceed the byte budget', async () => { + const oversizedBuffer = Buffer.alloc(GRAB_BUDGET.screenshotMaxBytes + 1) + guestCapturePageMock.mockResolvedValue({ + isEmpty: vi.fn(() => false), + getSize: vi.fn(() => ({ width: 1000, height: 500 })), + crop: vi.fn(() => ({ + toPNG: vi.fn(() => oversizedBuffer) + })) + }) + guestExecuteJavaScriptMock.mockImplementation(async (script: string) => + script === 'window.innerWidth' ? 1000 : undefined + ) + + const screenshot = await browserManager.captureSelectionScreenshot( + 'tab-1', + { x: 0, y: 0, width: 100, height: 50 }, + guest + ) + + expect(screenshot).toBeNull() + }) + }) + + describe('extractHoverPayload', () => { + it('returns a clamped payload when the guest reports a hovered element', async () => { + guestExecuteJavaScriptMock.mockResolvedValueOnce({ + page: { + sanitizedUrl: 'https://example.com/path?token=secret#hash', + title: 'Hover target', + viewportWidth: 1200, + viewportHeight: 800, + scrollX: 0, + scrollY: 0, + devicePixelRatio: 2, + capturedAt: '2026-04-10T00:00:00.000Z' + }, + target: { + tagName: 'div', + selector: 'div.card', + textSnippet: 'x'.repeat(500), + htmlSnippet: '
Hover
', + attributes: { + href: 'https://example.com/path?api_key=secret', + onclick: 'alert(1)' + }, + accessibility: { + role: 'generic', + accessibleName: 'Card', + ariaLabel: null, + ariaLabelledBy: null + }, + rectViewport: { x: 5, y: 10, width: 50, height: 25 }, + rectPage: { x: 5, y: 10, width: 50, height: 25 }, + computedStyles: { + display: 'block', + position: 'relative', + width: '50px', + height: '25px', + margin: '0', + padding: '0', + color: '#000', + backgroundColor: '#fff', + border: 'none', + borderRadius: '0', + fontFamily: 'sans-serif', + fontSize: '14px', + fontWeight: '400', + lineHeight: '20px', + textAlign: 'left', + zIndex: '1' + } + }, + nearbyText: [], + ancestorPath: [], + screenshot: null + }) + + const payload = await browserManager.extractHoverPayload('tab-1', guest) + + expect(payload).not.toBeNull() + expect(payload?.page.sanitizedUrl).toBe('https://example.com/path') + expect(payload?.target.textSnippet).toContain('(truncated)') + expect(payload?.target.attributes.href).toBe('[redacted]') + expect(payload?.target.attributes.onclick).toBeUndefined() + }) + + it('returns null for structurally invalid guest payloads', async () => { + guestExecuteJavaScriptMock.mockResolvedValueOnce({ page: { title: 'missing-target' } }) + + const payload = await browserManager.extractHoverPayload('tab-1', guest) + + expect(payload).toBeNull() + }) + }) }) diff --git a/src/main/browser/browser-manager.test.ts b/src/main/browser/browser-manager.test.ts index a2069e269..cc21403b3 100644 --- a/src/main/browser/browser-manager.test.ts +++ b/src/main/browser/browser-manager.test.ts @@ -205,7 +205,7 @@ describe('browserManager', () => { expect(guestOnMock.mock.calls.filter(([event]) => event === 'will-redirect')).toHaveLength(1) }) - it('does not forward ctrl/cmd+r or readline chords from browser guests', () => { + it('replays a queued main-frame load failure after the guest registers', () => { const rendererSendMock = vi.fn() const guest = { id: 404, @@ -215,6 +215,69 @@ describe('browserManager', () => { setWindowOpenHandler: guestSetWindowOpenHandlerMock, on: guestOnMock, off: guestOffMock, + openDevTools: guestOpenDevToolsMock, + getURL: vi.fn(() => 'http://localhost:3000/') + } + + webContentsFromIdMock.mockImplementation((id: number) => { + if (id === 404) { + return guest + } + if (id === rendererWebContentsId) { + return { + isDestroyed: vi.fn(() => false), + send: rendererSendMock + } + } + return null + }) + + browserManager.attachGuestPolicies(guest as never) + + const didFailLoadHandler = guestOnMock.mock.calls.find( + ([event]) => event === 'did-fail-load' + )?.[1] as + | (( + event: unknown, + errorCode: number, + errorDescription: string, + validatedUrl: string, + isMainFrame: boolean + ) => void) + | undefined + + expect(didFailLoadHandler).toBeTypeOf('function') + didFailLoadHandler?.(null, -105, 'Name not resolved', 'http://localhost:3000/', true) + + expect(rendererSendMock).not.toHaveBeenCalled() + + browserManager.registerGuest({ + browserTabId: 'browser-1', + webContentsId: 404, + rendererWebContentsId + }) + + expect(rendererSendMock).toHaveBeenCalledTimes(1) + expect(rendererSendMock).toHaveBeenCalledWith('browser:guest-load-failed', { + browserTabId: 'browser-1', + loadError: { + code: -105, + description: 'Name not resolved', + validatedUrl: 'http://localhost:3000/' + } + }) + }) + + it('does not forward ctrl/cmd+r or readline chords from browser guests', () => { + const rendererSendMock = vi.fn() + const guest = { + id: 405, + isDestroyed: vi.fn(() => false), + getType: vi.fn(() => 'webview'), + setBackgroundThrottling: guestSetBackgroundThrottlingMock, + setWindowOpenHandler: guestSetWindowOpenHandlerMock, + on: guestOnMock, + off: guestOffMock, openDevTools: guestOpenDevToolsMock } @@ -293,7 +356,7 @@ describe('browserManager', () => { const isDarwin = process.platform === 'darwin' const rendererSendMock = vi.fn() const guest = { - id: 405, + id: 406, isDestroyed: vi.fn(() => false), getType: vi.fn(() => 'webview'), setBackgroundThrottling: guestSetBackgroundThrottlingMock, @@ -388,4 +451,45 @@ describe('browserManager', () => { expect(rendererSendMock).toHaveBeenNthCalledWith(4, 'ui:switchTab', 1) expect(rendererSendMock).toHaveBeenNthCalledWith(5, 'ui:openQuickOpen') }) + + it('cleans up prior guest listeners before re-registering the same tab', () => { + const guest = { + id: 808, + isDestroyed: vi.fn(() => false), + getType: vi.fn(() => 'webview'), + setBackgroundThrottling: guestSetBackgroundThrottlingMock, + setWindowOpenHandler: guestSetWindowOpenHandlerMock, + on: guestOnMock, + off: guestOffMock, + openDevTools: guestOpenDevToolsMock, + getURL: vi.fn(() => 'https://example.com/'), + canGoBack: vi.fn(() => false), + canGoForward: vi.fn(() => false), + goBack: vi.fn(), + goForward: vi.fn(), + reload: vi.fn(), + executeJavaScript: vi.fn() + } + webContentsFromIdMock.mockReturnValue(guest) + + browserManager.attachGuestPolicies(guest as never) + browserManager.registerGuest({ + browserTabId: 'browser-1', + webContentsId: 808, + rendererWebContentsId + }) + + guestOffMock.mockClear() + + browserManager.registerGuest({ + browserTabId: 'browser-1', + webContentsId: 808, + rendererWebContentsId + }) + + expect(guestOffMock).toHaveBeenCalledWith('context-menu', expect.any(Function)) + expect( + guestOffMock.mock.calls.filter(([eventName]) => eventName === 'before-input-event') + ).toHaveLength(2) + }) }) diff --git a/src/main/browser/browser-manager.ts b/src/main/browser/browser-manager.ts index 1b3ebfc16..60207d44e 100644 --- a/src/main/browser/browser-manager.ts +++ b/src/main/browser/browser-manager.ts @@ -1,16 +1,12 @@ -/* eslint-disable max-lines -- Why: BrowserManager is the single owner of guest -lifecycle, context menus, and grab operations. Splitting these into separate -modules would scatter the guest authorization and tab-lookup logic that must -stay consistent when new privileged operations are added. */ -import { clipboard, Menu, shell, webContents } from 'electron' +/* eslint-disable max-lines -- Why: BrowserManager intentionally remains the +single privileged facade for guest registration, authorization, and lifecycle +cleanup even after extracting the grab/session helpers. Keeping that ownership +in one file avoids scattering the browser security boundary across modules. */ +import { shell, webContents } from 'electron' import { normalizeBrowserNavigationUrl, normalizeExternalBrowserUrl } from '../../shared/browser-url' -import { - isWindowShortcutModifierChord, - resolveWindowShortcutAction -} from '../../shared/window-shortcut-policy' import type { BrowserGrabCancelReason, BrowserGrabPayload, @@ -18,12 +14,16 @@ import type { BrowserGrabResult, BrowserGrabScreenshot } from '../../shared/browser-grab-types' -import { - GRAB_BUDGET, - GRAB_SAFE_ATTRIBUTE_NAMES, - GRAB_SECRET_PATTERNS -} from '../../shared/browser-grab-types' import { buildGuestOverlayScript } from './grab-guest-script' +import { clampGrabPayload } from './browser-grab-payload' +import { captureSelectionScreenshot as captureGrabSelectionScreenshot } from './browser-grab-screenshot' +import { BrowserGrabSessionController } from './browser-grab-session-controller' +import { + resolveRendererWebContents, + setupGrabShortcutForwarding, + setupGuestContextMenu, + setupGuestShortcutForwarding +} from './browser-guest-ui' export type BrowserGuestRegistration = { browserTabId: string @@ -31,197 +31,6 @@ export type BrowserGuestRegistration = { rendererWebContentsId: number } -/** Tracks the lifecycle of a single grab operation on one browser tab. */ -type ActiveGrabOp = { - opId: string - browserTabId: string - guestWebContentsId: number - resolve: (result: BrowserGrabResult) => void - /** Cleanup listeners and optionally inject teardown. - * @param preserveOverlay When true, skip teardown injection so the guest - * overlay stays visible (used when a selection succeeds and the copy menu - * is shown). */ - cleanup: (preserveOverlay?: boolean) => void - /** When true, cleanup skips the teardown injection. Set by awaitGrabSelection - * when replacing an existing op so the freshly-armed overlay is preserved. */ - skipTeardown?: boolean -} - -/** Hard timeout for an armed grab operation to prevent indefinite hangs. */ -const GRAB_OP_TIMEOUT_MS = 120_000 - -/** - * Re-validate and clamp all string, array, and budget fields in a grab payload - * before forwarding to the renderer. This is the main-side safety net: even if - * the guest runtime is compromised, the payload that reaches renderer chrome - * respects the documented budgets. - * - * Returns null if the payload is structurally invalid (missing required fields). - */ -function clampGrabPayload(raw: unknown): BrowserGrabPayload | null { - // Why: the guest payload is completely untrusted. A compromised or - // malfunctioning guest could return anything. Validate structural shape - // before accessing nested properties to avoid unhandled TypeErrors. - if (!raw || typeof raw !== 'object') { - return null - } - const obj = raw as Record - if (!obj.page || typeof obj.page !== 'object') { - return null - } - if (!obj.target || typeof obj.target !== 'object') { - return null - } - - const page = obj.page as Record - const target = obj.target as Record - - const clampStr = (s: unknown, max: number): string => { - const str = typeof s === 'string' ? s : '' - if (str.length <= max) { - return str - } - return `${str.slice(0, max)} (truncated)` - } - - const clampArray = (arr: unknown, maxEntries: number, maxEntryLength: number): string[] => { - const items = Array.isArray(arr) ? arr : [] - return items.slice(0, maxEntries).map((item) => clampStr(item, maxEntryLength)) - } - - const safeStr = (s: unknown, max = 500): string => clampStr(s, max) - - const safeNum = (n: unknown, fallback = 0): number => - typeof n === 'number' && Number.isFinite(n) ? n : fallback - - // Why: mirror the guest-side secret detection on the main side so a - // compromised guest cannot smuggle secret-bearing values through attributes - // or URLs. This is the defense-in-depth layer. - const containsSecret = (val: string): boolean => { - const lower = val.toLowerCase() - return GRAB_SECRET_PATTERNS.some((p) => lower.includes(p)) - } - - // Why: mirror the guest-side URL sanitization. Strip query strings and - // fragments to prevent token leakage even if the guest is compromised. - const sanitizeUrl = (raw: unknown): string => { - const str = typeof raw === 'string' ? raw : '' - if (!str) { - return '' - } - try { - const u = new URL(str) - u.search = '' - u.hash = '' - return u.toString() - } catch { - // Why: returning the raw string on parse failure could preserve - // javascript: URIs or other non-http schemes. Return empty. - return '' - } - } - - // Why: re-filter attributes on the main side so a compromised guest cannot - // smuggle unsafe attribute names (e.g., event handlers) or secret-bearing - // values into the payload that reaches the renderer. - const safeAttributes = (attrs: unknown): Record => { - if (!attrs || typeof attrs !== 'object') { - return {} - } - const filtered: Record = {} - for (const [key, value] of Object.entries(attrs as Record)) { - const name = key.toLowerCase() - const isAria = name.startsWith('aria-') - const isSafe = GRAB_SAFE_ATTRIBUTE_NAMES.has(name) - if (!isAria && !isSafe) { - continue - } - const strValue = safeStr(value, 2000) - if (containsSecret(strValue)) { - filtered[name] = '[redacted]' - } else if ((name === 'href' || name === 'src' || name === 'action') && strValue) { - filtered[name] = sanitizeUrl(strValue) - } else if (name === 'class') { - filtered[name] = safeStr(value, 200) - } else { - filtered[name] = safeStr(value, 500) - } - } - return filtered - } - - const safeRect = (r: unknown): BrowserGrabRect => { - if (!r || typeof r !== 'object') { - return { x: 0, y: 0, width: 0, height: 0 } - } - const rect = r as Record - return { - x: safeNum(rect.x), - y: safeNum(rect.y), - width: safeNum(rect.width), - height: safeNum(rect.height) - } - } - - const accessibility = target.accessibility as Record | null | undefined - const computedStyles = target.computedStyles as Record | null | undefined - - return { - page: { - // Why: re-sanitize the URL main-side so a compromised guest cannot - // pass through query strings containing tokens or secrets. - sanitizedUrl: sanitizeUrl(page.sanitizedUrl), - title: safeStr(page.title, 500), - viewportWidth: safeNum(page.viewportWidth), - viewportHeight: safeNum(page.viewportHeight), - scrollX: safeNum(page.scrollX), - scrollY: safeNum(page.scrollY), - devicePixelRatio: safeNum(page.devicePixelRatio, 1), - capturedAt: safeStr(page.capturedAt, 100) - }, - target: { - tagName: safeStr(target.tagName, 50), - selector: safeStr(target.selector, 500), - textSnippet: clampStr(target.textSnippet, GRAB_BUDGET.textSnippetMaxLength), - htmlSnippet: clampStr(target.htmlSnippet, GRAB_BUDGET.htmlSnippetMaxLength), - attributes: safeAttributes(target.attributes), - accessibility: { - role: safeStr(accessibility?.role) || null, - accessibleName: safeStr(accessibility?.accessibleName) || null, - ariaLabel: safeStr(accessibility?.ariaLabel) || null, - ariaLabelledBy: safeStr(accessibility?.ariaLabelledBy) || null - }, - rectViewport: safeRect(target.rectViewport), - rectPage: safeRect(target.rectPage), - computedStyles: { - display: safeStr(computedStyles?.display), - position: safeStr(computedStyles?.position), - width: safeStr(computedStyles?.width), - height: safeStr(computedStyles?.height), - margin: safeStr(computedStyles?.margin), - padding: safeStr(computedStyles?.padding), - color: safeStr(computedStyles?.color), - backgroundColor: safeStr(computedStyles?.backgroundColor), - border: safeStr(computedStyles?.border), - borderRadius: safeStr(computedStyles?.borderRadius), - fontFamily: safeStr(computedStyles?.fontFamily), - fontSize: safeStr(computedStyles?.fontSize), - fontWeight: safeStr(computedStyles?.fontWeight), - lineHeight: safeStr(computedStyles?.lineHeight), - textAlign: safeStr(computedStyles?.textAlign), - zIndex: safeStr(computedStyles?.zIndex) - } - }, - nearbyText: clampArray( - obj.nearbyText, - GRAB_BUDGET.nearbyTextMaxEntries, - GRAB_BUDGET.nearbyTextEntryMaxLength - ), - ancestorPath: clampArray(obj.ancestorPath, GRAB_BUDGET.ancestorPathMaxEntries, 200), - screenshot: null - } -} - class BrowserManager { private readonly webContentsIdByTabId = new Map() private readonly rendererWebContentsIdByTabId = new Map() @@ -233,7 +42,7 @@ class BrowserManager { number, { code: number; description: string; validatedUrl: string } >() - private readonly activeGrabOps = new Map() + private readonly grabSessionController = new BrowserGrabSessionController() private openValidatedExternal(rawUrl: string): void { const externalUrl = normalizeExternalBrowserUrl(rawUrl) @@ -293,6 +102,12 @@ class BrowserManager { webContentsId, rendererWebContentsId }: BrowserGuestRegistration): void { + // Why: re-registering the same browser tab can happen when Chromium swaps + // or recreates the underlying guest surface. Any active grab is bound to + // the old guest's listeners and teardown path, so keeping it alive would + // leave the session attached to a stale webContents until timeout. + this.cancelGrabOp(browserTabId, 'evicted') + const previousCleanup = this.contextMenuCleanupByTabId.get(browserTabId) if (previousCleanup) { previousCleanup() @@ -355,9 +170,7 @@ class BrowserManager { unregisterAll(): void { // Cancel all active grab ops before tearing down registrations - for (const browserTabId of this.activeGrabOps.keys()) { - this.cancelGrabOp(browserTabId, 'evicted') - } + this.grabSessionController.cancelAll('evicted') for (const browserTabId of this.webContentsIdByTabId.keys()) { this.unregisterGuest(browserTabId) } @@ -416,7 +229,7 @@ class BrowserManager { /** Returns true if a grab operation is currently active for this tab. */ hasActiveGrabOp(browserTabId: string): boolean { - return this.activeGrabOps.has(browserTabId) + return this.grabSessionController.hasActiveGrabOp(browserTabId) } /** @@ -463,154 +276,14 @@ class BrowserManager { opId: string, guest: Electron.WebContents ): Promise { - // Why: only one active grab operation per tab prevents race conditions - // where a late click from a previous operation resolves the wrong Promise. - const existing = this.activeGrabOps.get(browserTabId) - if (existing) { - // Why: skip teardown injection when replacing an op. The new op will - // reuse the already-armed overlay. If we injected teardown here, it - // would race with the new awaitClick script in the guest's JS queue - // and destroy the overlay before the click handler is installed. - existing.skipTeardown = true - existing.resolve({ opId: existing.opId, kind: 'cancelled', reason: 'user' }) - } - - return new Promise((resolve) => { - const guestWebContentsId = guest.id - let settled = false - - const settleOnce = (result: BrowserGrabResult): void => { - if (settled) { - return - } - settled = true - clearTimeout(timeoutId) - // Why: when the user successfully selects an element, keep the guest - // overlay visible so the highlight box persists while the renderer - // shows the copy menu. Teardown happens later when the renderer calls - // setGrabMode(false) or re-arms with a fresh armAndAwait cycle. - op.cleanup(result.kind === 'selected' || result.kind === 'context-selected') - this.activeGrabOps.delete(browserTabId) - resolve(result) - } - - // Why: the guest overlay runtime handles the click in-page and calls - // __orcaGrabResolve() which is wired by the 'awaitClick' script to - // resolve the executeJavaScript Promise with the extracted payload. - // Main just needs to run that script and await its result. - const awaitGuestClick = async (): Promise => { - try { - const rawPayload = await guest.executeJavaScript(buildGuestOverlayScript('awaitClick')) - if (!rawPayload || typeof rawPayload !== 'object') { - settleOnce({ opId, kind: 'cancelled', reason: 'user' }) - return - } - // Why: the guest wraps right-click results in { __orcaContextMenu, payload } - // so the renderer can show the full action dropdown instead of auto-copying. - const isContextMenu = - '__orcaContextMenu' in (rawPayload as Record) && - (rawPayload as Record).__orcaContextMenu === true - const payloadSource = isContextMenu - ? (rawPayload as Record).payload - : rawPayload - const payload = clampGrabPayload(payloadSource) - if (!payload) { - settleOnce({ opId, kind: 'error', reason: 'Guest returned invalid payload structure' }) - return - } - settleOnce({ - opId, - kind: isContextMenu ? 'context-selected' : 'selected', - payload - }) - } catch (err) { - const message = err instanceof Error ? err.message : 'Selection failed' - // Distinguish cancellation from errors - if (message.includes('cancelled')) { - settleOnce({ opId, kind: 'cancelled', reason: 'user' }) - } else { - settleOnce({ opId, kind: 'error', reason: message }) - } - } - } - - // --- Auto-cancel on top-level navigation --- - // Why: only cancel on main-frame navigations. Subframe navigations - // (e.g., iframe ads loading) should not spuriously cancel the grab. - const handleNavigation = ( - _event: unknown, - _url: unknown, - _isInPlace: unknown, - isMainFrame: boolean - ): void => { - if (isMainFrame) { - settleOnce({ opId, kind: 'cancelled', reason: 'navigation' }) - } - } - - // --- Auto-cancel on guest destruction --- - const handleDestroyed = (): void => { - settleOnce({ opId, kind: 'cancelled', reason: 'evicted' }) - } - - // --- Hard timeout --- - const timeoutId = setTimeout(() => { - settleOnce({ opId, kind: 'cancelled', reason: 'timeout' }) - }, GRAB_OP_TIMEOUT_MS) - - // Install listeners - guest.on('did-start-navigation', handleNavigation) - guest.on('destroyed', handleDestroyed) - - const cleanup = (preserveOverlay?: boolean): void => { - try { - guest.off('did-start-navigation', handleNavigation) - guest.off('destroyed', handleDestroyed) - } catch { - // Why: the guest may already be destroyed during teardown. - // Cleanup is best-effort. - } - // Why: skip teardown injection when (a) the op is being replaced by a - // new op (skipTeardown), or (b) the selection succeeded and the overlay - // should stay visible while the copy menu is shown (preserveOverlay). - if (op.skipTeardown || preserveOverlay) { - return - } - // Tell the guest to remove the overlay - try { - if (!guest.isDestroyed()) { - void guest.executeJavaScript(buildGuestOverlayScript('teardown')) - } - } catch { - // Best-effort overlay removal - } - } - - const op: ActiveGrabOp = { - opId, - browserTabId, - guestWebContentsId, - resolve: settleOnce, - cleanup - } - this.activeGrabOps.set(browserTabId, op) - - // Start awaiting the click in the guest - void awaitGuestClick() - }) + return this.grabSessionController.awaitGrabSelection(browserTabId, opId, guest) } /** * Cancel an active grab operation for the given tab. */ cancelGrabOp(browserTabId: string, reason: BrowserGrabCancelReason): void { - const op = this.activeGrabOps.get(browserTabId) - if (!op) { - return - } - // Why: settleOnce (op.resolve) already calls op.cleanup() and deletes the - // map entry. Calling them again here would double-inject the teardown script. - op.resolve({ opId: op.opId, kind: 'cancelled', reason }) + this.grabSessionController.cancelGrabOp(browserTabId, reason) } /** @@ -622,91 +295,7 @@ class BrowserManager { rect: BrowserGrabRect, guest: Electron.WebContents ): Promise { - try { - // Why: the rect comes from the renderer via IPC. Validate that all fields - // are finite numbers before using them in arithmetic, so NaN cannot reach - // Electron's image.crop() and cause undefined behavior. - const safeN = (n: unknown, fallback = 0): number => - typeof n === 'number' && Number.isFinite(n) ? n : fallback - const safeRect = { - x: safeN(rect.x), - y: safeN(rect.y), - width: safeN(rect.width), - height: safeN(rect.height) - } - - // Why: hide the grab overlay before capturing so the highlight box and - // label don't appear in the screenshot. The overlay is restored after. - // Wrapped in try/finally so the overlay is always restored even if - // capturePage() throws (e.g., guest destroyed mid-capture). - await guest - .executeJavaScript( - `(function(){ var g = window.__orcaGrab; if (g && g.host) g.host.style.display = 'none'; })()` - ) - .catch(() => {}) - let image: Electron.NativeImage - try { - image = await guest.capturePage() - } finally { - await guest - .executeJavaScript( - `(function(){ var g = window.__orcaGrab; if (g && g.host) g.host.style.display = ''; })()` - ) - .catch(() => {}) - } - if (image.isEmpty()) { - return null - } - - const bitmapSize = image.getSize() - // Why: capturePage returns a bitmap in physical pixels. The grab rect is - // in CSS pixels. To map between them we need the combined scale factor - // (zoomFactor * deviceScaleFactor). Rather than using the primary display - // (which is wrong on multi-monitor setups with mixed DPI), we derive the - // scale factor empirically: ask the guest for its CSS viewport width, then - // compute scaleFactor = bitmapWidth / viewportCSSWidth. This is correct - // regardless of which display the window is on. - const viewportCSSWidth: number = await guest.executeJavaScript('window.innerWidth') - if (!viewportCSSWidth || viewportCSSWidth <= 0) { - return null - } - const scaleFactor = bitmapSize.width / viewportCSSWidth - - // Map CSS-pixel rect to bitmap coordinates - const cropX = Math.max(0, Math.round(safeRect.x * scaleFactor)) - const cropY = Math.max(0, Math.round(safeRect.y * scaleFactor)) - const cropW = Math.min(bitmapSize.width - cropX, Math.round(safeRect.width * scaleFactor)) - const cropH = Math.min(bitmapSize.height - cropY, Math.round(safeRect.height * scaleFactor)) - - if (cropW <= 0 || cropH <= 0) { - return null - } - - const cropped = image.crop({ x: cropX, y: cropY, width: cropW, height: cropH }) - const pngBuffer = cropped.toPNG() - - // Enforce screenshot byte budget - if (pngBuffer.byteLength > GRAB_BUDGET.screenshotMaxBytes) { - // Why: downscaling would add complexity for v1. Fail closed to - // "no screenshot" rather than send an oversized payload. - return null - } - - const dataUrl = `data:image/png;base64,${pngBuffer.toString('base64')}` - // Why: cropW/cropH are in physical pixels (bitmap coordinates) but the - // rest of the grab payload uses CSS pixels. Divide by scaleFactor so the - // screenshot dimensions are consistent with rectViewport/rectPage. - return { - mimeType: 'image/png', - dataUrl, - width: Math.round(cropW / scaleFactor), - height: Math.round(cropH / scaleFactor) - } - } catch { - // Why: screenshot capture can fail if the guest is being torn down - // or the compositor surface is not available. Fail closed. - return null - } + return captureGrabSelectionScreenshot(rect, guest) } /** @@ -730,86 +319,17 @@ class BrowserManager { } private setupContextMenu(browserTabId: string, guest: Electron.WebContents): void { - const handler = (_event: Electron.Event, params: Electron.ContextMenuParams): void => { - const pageUrl = guest.getURL() - const linkUrl = params.linkURL || '' - - const template: Electron.MenuItemConstructorOptions[] = [] - - if (linkUrl) { - const externalLinkUrl = normalizeExternalBrowserUrl(linkUrl) - template.push( - { - label: 'Open Link In Default Browser', - enabled: Boolean(externalLinkUrl && externalLinkUrl !== 'about:blank'), - click: () => { - this.openValidatedExternal(linkUrl) - } - }, - { - label: 'Copy Link Address', - click: () => { - clipboard.writeText(linkUrl) - } - }, - { type: 'separator' } - ) - } - - const externalPageUrl = normalizeExternalBrowserUrl(pageUrl) - - template.push( - { - label: 'Back', - enabled: guest.canGoBack(), - click: () => guest.goBack() + this.contextMenuCleanupByTabId.set( + browserTabId, + setupGuestContextMenu({ + browserTabId, + guest, + openValidatedExternal: (rawUrl) => { + this.openValidatedExternal(rawUrl) }, - { - label: 'Forward', - enabled: guest.canGoForward(), - click: () => guest.goForward() - }, - { - label: 'Reload', - click: () => guest.reload() - }, - { type: 'separator' }, - { - label: 'Open Page In Default Browser', - enabled: Boolean(externalPageUrl && externalPageUrl !== 'about:blank'), - click: () => { - this.openValidatedExternal(pageUrl) - } - }, - { - label: 'Copy Page URL', - enabled: Boolean(pageUrl), - click: () => { - clipboard.writeText(pageUrl) - } - }, - { type: 'separator' }, - { - label: 'Inspect Page', - click: () => { - void this.openDevTools(browserTabId) - } - } - ) - - Menu.buildFromTemplate(template).popup() - } - - guest.on('context-menu', handler) - this.contextMenuCleanupByTabId.set(browserTabId, () => { - try { - guest.off('context-menu', handler) - } catch { - // Why: browser tabs can outlive the guest webContents briefly during - // teardown. Cleanup should be best-effort instead of throwing while the - // IDE is closing a tab. - } - }) + openDevTools: async (tabId) => this.openDevTools(tabId) + }) + ) } // Why: browser grab mode intentionally uses Cmd/Ctrl+C as its entry @@ -826,63 +346,16 @@ class BrowserManager { this.grabShortcutCleanupByTabId.delete(browserTabId) } - const handler = (event: Electron.Event, input: Electron.Input): void => { - if (input.type !== 'keyDown') { - return - } - const isMod = process.platform === 'darwin' ? input.meta : input.control - if (!isMod || input.shift || input.alt || input.key.toLowerCase() !== 'c') { - return - } - - void guest - .executeJavaScript(`(() => { - const active = document.activeElement - const tag = active?.tagName - const isEditable = - active instanceof HTMLInputElement || - active instanceof HTMLTextAreaElement || - active?.isContentEditable === true || - tag === 'SELECT' || - tag === 'IFRAME' - if (isEditable) { - return false - } - const selection = window.getSelection() - return Boolean(selection && selection.type === 'Range' && selection.toString().trim().length > 0) - ? false - : true - })()`) - .then((shouldToggle) => { - if (!shouldToggle) { - return - } - event.preventDefault() - const rendererWcId = this.rendererWebContentsIdByTabId.get(browserTabId) - if (!rendererWcId) { - return - } - const rendererWc = webContents.fromId(rendererWcId) - if (!rendererWc || rendererWc.isDestroyed()) { - return - } - rendererWc.send('browser:grabModeToggle', browserTabId) - }) - .catch(() => { - // Why: shortcut forwarding is best-effort. Guest teardown or a - // transient executeJavaScript failure should not break normal copy. - }) - } - - guest.on('before-input-event', handler) - this.grabShortcutCleanupByTabId.set(browserTabId, () => { - try { - guest.off('before-input-event', handler) - } catch { - // Why: browser tabs can outlive the guest webContents briefly during - // teardown. Cleanup should be best-effort. - } - }) + this.grabShortcutCleanupByTabId.set( + browserTabId, + setupGrabShortcutForwarding({ + browserTabId, + guest, + resolveRenderer: (tabId) => + resolveRendererWebContents(this.rendererWebContentsIdByTabId, tabId), + hasActiveGrabOp: (tabId) => this.hasActiveGrabOp(tabId) + }) + ) } // Why: a focused webview guest is a separate Chromium process — keyboard @@ -897,62 +370,15 @@ class BrowserManager { this.shortcutForwardingCleanupByTabId.delete(browserTabId) } - const handler = (_event: Electron.Event, input: Electron.Input): void => { - if (input.type !== 'keyDown') { - return - } - // Why: browser guests need a broader modifier-chord gate than the main - // window because they also forward guest-specific tab shortcuts - // (Cmd/Ctrl+T/W/Shift+B/Shift+[ / ]) in addition to the shared allowlist - // handled by resolveWindowShortcutAction(). - if (!isWindowShortcutModifierChord(input, process.platform)) { - return - } - - // Why: centralizing the shared subset still keeps guest forwarding in - // lockstep with the main window for the chords that must never steal - // readline control input above the terminal. - const action = resolveWindowShortcutAction(input, process.platform) - - const rendererWcId = this.rendererWebContentsIdByTabId.get(browserTabId) - if (!rendererWcId) { - return - } - const rendererWc = webContents.fromId(rendererWcId) - if (!rendererWc || rendererWc.isDestroyed()) { - return - } - - if (input.code === 'KeyB' && input.shift) { - rendererWc.send('ui:newBrowserTab') - } else if (input.code === 'KeyT' && !input.shift) { - rendererWc.send('ui:newTerminalTab') - } else if (input.code === 'KeyW' && !input.shift) { - rendererWc.send('ui:closeActiveTab') - } else if (input.shift && (input.code === 'BracketRight' || input.code === 'BracketLeft')) { - rendererWc.send('ui:switchTab', input.code === 'BracketRight' ? 1 : -1) - } else if (action?.type === 'toggleWorktreePalette') { - rendererWc.send('ui:toggleWorktreePalette') - } else if (action?.type === 'openQuickOpen') { - rendererWc.send('ui:openQuickOpen') - } else if (action?.type === 'jumpToWorktreeIndex') { - rendererWc.send('ui:jumpToWorktreeIndex', action.index) - } else { - return - } - // Why: preventDefault stops the guest page from also processing the chord - // (e.g. Cmd+T opening a browser-internal new-tab page). - _event.preventDefault() - } - - guest.on('before-input-event', handler) - this.shortcutForwardingCleanupByTabId.set(browserTabId, () => { - try { - guest.off('before-input-event', handler) - } catch { - // Why: best-effort — guest may already be destroyed during teardown. - } - }) + this.shortcutForwardingCleanupByTabId.set( + browserTabId, + setupGuestShortcutForwarding({ + browserTabId, + guest, + resolveRenderer: (tabId) => + resolveRendererWebContents(this.rendererWebContentsIdByTabId, tabId) + }) + ) } private forwardOrQueueGuestLoadFailure( diff --git a/src/preload/api-types.d.ts b/src/preload/api-types.d.ts index c3af3683e..7ecc1c92a 100644 --- a/src/preload/api-types.d.ts +++ b/src/preload/api-types.d.ts @@ -79,6 +79,9 @@ export type BrowserApi = { ) => Promise extractHoverPayload: (args: BrowserExtractHoverArgs) => Promise onGrabModeToggle: (callback: (browserTabId: string) => void) => () => void + onGrabActionShortcut: ( + callback: (args: { browserTabId: string; key: 'c' | 's' }) => void + ) => () => void } export type PreflightStatus = { diff --git a/src/preload/index.ts b/src/preload/index.ts index 69456eb6c..b1e95fad1 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -378,6 +378,17 @@ const api = { callback(browserTabId) ipcRenderer.on('browser:grabModeToggle', listener) return () => ipcRenderer.removeListener('browser:grabModeToggle', listener) + }, + + onGrabActionShortcut: ( + callback: (args: { browserTabId: string; key: 'c' | 's' }) => void + ): (() => void) => { + const listener = ( + _event: Electron.IpcRendererEvent, + data: { browserTabId: string; key: 'c' | 's' } + ) => callback(data) + ipcRenderer.on('browser:grabActionShortcut', listener) + return () => ipcRenderer.removeListener('browser:grabActionShortcut', listener) } }, diff --git a/src/renderer/src/components/browser-pane/BrowserPane.tsx b/src/renderer/src/components/browser-pane/BrowserPane.tsx index 370fd3f8c..c085ac9db 100644 --- a/src/renderer/src/components/browser-pane/BrowserPane.tsx +++ b/src/renderer/src/components/browser-pane/BrowserPane.tsx @@ -44,6 +44,7 @@ import type { } from '../../../../shared/browser-grab-types' import { useGrabMode } from './useGrabMode' import { formatGrabPayloadAsText } from './GrabConfirmationSheet' +import { isEditableKeyboardTarget } from './browser-keyboard' type BrowserTabPageState = Partial< Pick< @@ -755,8 +756,7 @@ export default function BrowserPane({ // Why: let native Cmd+C work in text inputs (address bar, search fields, // contentEditable regions). Only intercept when focus is on a non-input // element so grab-mode toggle doesn't swallow copy in form controls. - const tag = (e.target as HTMLElement)?.tagName - if (tag === 'INPUT' || tag === 'TEXTAREA' || (e.target as HTMLElement)?.isContentEditable) { + if (isEditableKeyboardTarget(e.target)) { return } const isMod = navigator.userAgent.includes('Mac') ? e.metaKey : e.ctrlKey @@ -789,22 +789,8 @@ export default function BrowserPane({ // with normal typing elsewhere. const grabPayloadRef = useRef(grab.payload) grabPayloadRef.current = grab.payload - useEffect(() => { - if (grab.state === 'idle' || grab.state === 'error') { - return - } - const handleKeyDown = (e: KeyboardEvent): void => { - // Ignore if modifier keys are held — user may be doing Cmd+C etc. - if (e.metaKey || e.ctrlKey || e.altKey) { - return - } - const key = e.key.toLowerCase() - if (key !== 'c' && key !== 's') { - return - } - e.preventDefault() - e.stopPropagation() - + const handleGrabActionShortcut = useCallback( + (key: 'c' | 's'): void => { const copyFromPayload = (payload: BrowserGrabPayload): void => { if (key === 'c') { const text = formatGrabPayloadAsText(payload) @@ -849,7 +835,6 @@ export default function BrowserPane({ } const payload = result.payload as BrowserGrabPayload - // For screenshot shortcut, also capture the screenshot if (key === 's') { try { const ssResult = await window.api.browser.captureSelectionScreenshot({ @@ -867,10 +852,45 @@ export default function BrowserPane({ copyFromPayload(payload) })() } + }, + [grab, showGrabToast] + ) + + useEffect(() => { + if (grab.state === 'idle' || grab.state === 'error') { + return + } + const handleKeyDown = (e: KeyboardEvent): void => { + if (isEditableKeyboardTarget(e.target)) { + return + } + // Ignore if modifier keys are held — user may be doing Cmd+C etc. + if (e.metaKey || e.ctrlKey || e.altKey) { + return + } + const key = e.key.toLowerCase() + if (key !== 'c' && key !== 's') { + return + } + e.preventDefault() + e.stopPropagation() + handleGrabActionShortcut(key as 'c' | 's') } window.addEventListener('keydown', handleKeyDown, true) return () => window.removeEventListener('keydown', handleKeyDown, true) - }, [grab, showGrabToast]) + }, [grab.state, handleGrabActionShortcut]) + + useEffect(() => { + if (grab.state === 'idle' || grab.state === 'error') { + return + } + return window.api.browser.onGrabActionShortcut(({ browserTabId, key }) => { + if (browserTabId !== browserTab.id) { + return + } + handleGrabActionShortcut(key) + }) + }, [browserTab.id, grab.state, handleGrabActionShortcut]) // Why: Radix DropdownMenu fires onOpenChange(false) before onSelect, so // the rearm in onOpenChange would clear the payload before the handler runs. diff --git a/src/renderer/src/components/browser-pane/browser-keyboard.test.ts b/src/renderer/src/components/browser-pane/browser-keyboard.test.ts new file mode 100644 index 000000000..54c79cfac --- /dev/null +++ b/src/renderer/src/components/browser-pane/browser-keyboard.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' +import { isEditableKeyboardTarget } from './browser-keyboard' + +describe('isEditableKeyboardTarget', () => { + it('returns true for input elements', () => { + const input = { + isContentEditable: false, + closest: (selector: string) => (selector.includes('input') ? {} : null) + } + expect(isEditableKeyboardTarget(input)).toBe(true) + }) + + it('returns true for descendants inside editable hosts', () => { + const child = { + isContentEditable: false, + closest: (selector: string) => (selector.includes('[contenteditable="true"]') ? {} : null) + } + expect(isEditableKeyboardTarget(child)).toBe(true) + }) + + it('returns false for non-editable elements', () => { + const div = { + isContentEditable: false, + closest: () => null + } + expect(isEditableKeyboardTarget(div)).toBe(false) + }) +}) diff --git a/src/renderer/src/components/browser-pane/browser-keyboard.ts b/src/renderer/src/components/browser-pane/browser-keyboard.ts new file mode 100644 index 000000000..087f22bc2 --- /dev/null +++ b/src/renderer/src/components/browser-pane/browser-keyboard.ts @@ -0,0 +1,26 @@ +type EditableTargetLike = { + isContentEditable?: boolean + closest?: (selector: string) => unknown +} + +export function isEditableKeyboardTarget(target: EventTarget | EditableTargetLike | null): boolean { + const element = + target && typeof target === 'object' && ('closest' in target || 'isContentEditable' in target) + ? (target as EditableTargetLike) + : null + if (!element) { + return false + } + + // Why: grab-mode single-key shortcuts should never fire while the user is + // typing into the browser chrome itself (address bar/search fields) or any + // other editable control. Treat nested elements inside those controls as + // editable too so composition wrappers or icons inside the input don't cause + // C/S to be swallowed unexpectedly. + const editableHost = element.closest?.('input, textarea, [contenteditable="true"]') + if (editableHost) { + return true + } + + return element.isContentEditable === true +}