From c57705bce8e071cc7886afc35d3b11302f673dfe Mon Sep 17 00:00:00 2001 From: kua-agent Date: Tue, 24 Nov 2026 10:27:19 +0400 Subject: [PATCH 1/5] fix(desktop): preview annotation picks elements inside iframes, including opaque sandboxed srcdoc frames The picker only hit-tested the top document, so pointer input over any iframe landed in the frame and never reached it. Main now injects a small relay into every subframe (WebFrameMain.executeJavaScript), which forwards pointer and tool-key input up the frame chain by postMessage, translated into top-level coordinates, and handles capture and style edits for the element it holds. Selectors name the frame chain, e.g. #hub-frame >>> #view-frame >>> #deep-save. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/preview/FramePickAgent.ts | 432 ++++++++++++++++++ .../desktop/src/preview/FramePickInjection.ts | 29 ++ apps/desktop/src/preview/Manager.ts | 4 + apps/desktop/src/preview/PickPreload.ts | 192 +++++++- 4 files changed, 653 insertions(+), 4 deletions(-) create mode 100644 apps/desktop/src/preview/FramePickAgent.ts create mode 100644 apps/desktop/src/preview/FramePickInjection.ts diff --git a/apps/desktop/src/preview/FramePickAgent.ts b/apps/desktop/src/preview/FramePickAgent.ts new file mode 100644 index 0000000000000..f29839dab739c --- /dev/null +++ b/apps/desktop/src/preview/FramePickAgent.ts @@ -0,0 +1,432 @@ +export const FRAME_PICK_MESSAGE_KEY = "__t3codeFramePick"; + +export interface FramePickRect { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; +} + +export interface FramePickHit { + readonly id: string | null; + readonly label: string; + readonly rect: FramePickRect; + readonly styles: Readonly> | null; +} + +export interface FramePickCapture { + readonly selector: string; + readonly htmlPreview: string; + readonly tagName: string; +} + +export type FramePickPointerType = "pointermove" | "pointerdown" | "pointerup" | "pointerout"; + +export type FramePickUp = + | { readonly kind: "hello" } + | { + readonly kind: "pointer"; + readonly type: FramePickPointerType; + readonly x: number; + readonly y: number; + readonly button: number; + readonly shiftKey: boolean; + readonly hit: FramePickHit | null; + } + | { readonly kind: "key"; readonly key: string } + | { + readonly kind: "rects"; + readonly rects: ReadonlyArray<{ readonly id: string; readonly rect: FramePickRect }>; + } + | { + readonly kind: "captured"; + readonly requestId: string; + readonly capture: FramePickCapture | null; + }; + +export type FramePickDown = + | { readonly kind: "start" } + | { readonly kind: "stop" } + | { readonly kind: "refresh" } + | { readonly kind: "capture"; readonly requestId: string; readonly id: string } + | { + readonly kind: "style"; + readonly id: string; + readonly property: string; + readonly value: string; + } + | { readonly kind: "restore"; readonly id: string }; + +export interface FramePickDelivery { + readonly up: FramePickUp; + readonly path: ReadonlyArray; + readonly frames: ReadonlyArray; +} + +export interface FramePickRelay { + readonly send: (path: ReadonlyArray, down: FramePickDown) => void; + readonly dispose: () => void; +} + +export function installFramePickAgent( + key: string, + deliver?: (delivery: FramePickDelivery) => void, +): FramePickRelay { + const registry = window as unknown as Record; + const installed = deliver ? undefined : registry[key]; + if (installed) return installed; + + const styleProperties = [ + "font-family", + "font-size", + "font-weight", + "line-height", + "color", + "background-color", + "border-color", + "border-width", + "border-radius", + "opacity", + "padding", + "margin", + "gap", + ]; + const toolKeys = new Set(["Escape", "v", "r", "d", "e"]); + const elementsById = new Map(); + const idsByElement = new WeakMap(); + const baselines = new Map>(); + let lastId = 0; + let active = false; + let cursorStyle: HTMLStyleElement | null = null; + + const childFrames = (): HTMLIFrameElement[] => + Array.from(document.querySelectorAll("iframe, frame")); + + const post = (target: Window | null | undefined, envelope: unknown): void => { + if (!target) return; + try { + target.postMessage({ [key]: envelope }, "*"); + } catch {} + }; + + const cssPath = (element: Element): string => { + const parts: string[] = []; + for ( + let node: Element | null = element; + node && node !== document.documentElement && node !== document.body; + node = node.parentElement + ) { + if (node.id) { + parts.unshift(`#${CSS.escape(node.id)}`); + break; + } + const tagName = node.tagName; + const siblings = node.parentElement + ? Array.from(node.parentElement.children).filter((child) => child.tagName === tagName) + : []; + const tag = tagName.toLowerCase(); + parts.unshift( + siblings.length > 1 ? `${tag}:nth-of-type(${siblings.indexOf(node) + 1})` : tag, + ); + } + return parts.join(" > "); + }; + + const describe = (element: Element): string => { + const id = element.id ? `#${element.id}` : ""; + const classes = + typeof element.className === "string" + ? element.className + .trim() + .split(/\s+/) + .filter(Boolean) + .slice(0, 2) + .map((name) => `.${name}`) + .join("") + : ""; + return `${element.tagName.toLowerCase()}${id}${classes}`; + }; + + const intersect = (rect: FramePickRect, bounds: FramePickRect): FramePickRect => { + const left = Math.max(rect.x, bounds.x); + const top = Math.max(rect.y, bounds.y); + const right = Math.min(rect.x + rect.width, bounds.x + bounds.width); + const bottom = Math.min(rect.y + rect.height, bounds.y + bounds.height); + return { x: left, y: top, width: Math.max(0, right - left), height: Math.max(0, bottom - top) }; + }; + + const visibleRect = (element: Element): FramePickRect => { + if (!element.isConnected) return { x: 0, y: 0, width: 0, height: 0 }; + const box = element.getBoundingClientRect(); + return intersect( + { x: box.left, y: box.top, width: box.width, height: box.height }, + { + x: 0, + y: 0, + width: document.documentElement.clientWidth, + height: document.documentElement.clientHeight, + }, + ); + }; + + const contentBox = (frame: HTMLIFrameElement): FramePickRect => { + const box = frame.getBoundingClientRect(); + const style = getComputedStyle(frame); + const paddingLeft = Number.parseFloat(style.paddingLeft) || 0; + const paddingTop = Number.parseFloat(style.paddingTop) || 0; + const paddingRight = Number.parseFloat(style.paddingRight) || 0; + const paddingBottom = Number.parseFloat(style.paddingBottom) || 0; + return { + x: box.left + frame.clientLeft + paddingLeft, + y: box.top + frame.clientTop + paddingTop, + width: frame.clientWidth - paddingLeft - paddingRight, + height: frame.clientHeight - paddingTop - paddingBottom, + }; + }; + + const shiftRect = (rect: FramePickRect, box: FramePickRect): FramePickRect => + intersect( + { x: rect.x + box.x, y: rect.y + box.y, width: rect.width, height: rect.height }, + box, + ); + + const translate = (up: FramePickUp, box: FramePickRect): FramePickUp => { + if (up.kind === "pointer") { + return { + ...up, + x: up.x + box.x, + y: up.y + box.y, + hit: up.hit ? { ...up.hit, rect: shiftRect(up.hit.rect, box) } : null, + }; + } + if (up.kind === "rects") { + return { + ...up, + rects: up.rects.map((entry) => ({ id: entry.id, rect: shiftRect(entry.rect, box) })), + }; + } + return up; + }; + + const sendUp = ( + up: FramePickUp, + path: ReadonlyArray = [], + frames: ReadonlyArray = [], + ): void => { + if (deliver) deliver({ up, path, frames }); + else post(window.parent, { up, path, frames }); + }; + + const sendDown = (index: number, down: FramePickDown, path: ReadonlyArray): void => + post(childFrames()[index]?.contentWindow, { down, path }); + + const broadcast = (down: FramePickDown): void => { + childFrames().forEach((_frame, index) => sendDown(index, down, [])); + }; + + const register = (element: Element): string => { + const known = idsByElement.get(element); + if (known) return known; + lastId += 1; + const id = String(lastId); + idsByElement.set(element, id); + elementsById.set(id, element); + return id; + }; + + const snapshotStyles = (element: Element): Record => { + const computed = getComputedStyle(element); + return Object.fromEntries( + styleProperties.map((property) => [property, computed.getPropertyValue(property)]), + ); + }; + + const hitAt = (x: number, y: number, selecting: boolean): FramePickHit | null => { + const element = document + .elementsFromPoint(x, y) + .find((candidate) => candidate !== document.documentElement && candidate !== document.body); + if (!element) return null; + return { + id: selecting ? register(element) : null, + label: describe(element), + rect: visibleRect(element), + styles: selecting ? snapshotStyles(element) : null, + }; + }; + + const reportRects = (): void => { + if (elementsById.size === 0) return; + sendUp({ + kind: "rects", + rects: Array.from(elementsById, ([id, element]) => ({ id, rect: visibleRect(element) })), + }); + }; + + const restore = (id: string): void => { + const element = elementsById.get(id); + const saved = baselines.get(id); + if (!saved || !(element instanceof HTMLElement || element instanceof SVGElement)) return; + for (const [property, value] of saved) { + if (value) element.style.setProperty(property, value); + else element.style.removeProperty(property); + } + baselines.delete(id); + }; + + const applyStyle = (id: string, property: string, value: string): void => { + const element = elementsById.get(id); + if (!(element instanceof HTMLElement || element instanceof SVGElement)) return; + const saved = baselines.get(id) ?? new Map(); + if (!saved.has(property)) saved.set(property, element.style.getPropertyValue(property)); + baselines.set(id, saved); + element.style.setProperty(property, value, "important"); + reportRects(); + }; + + const onPointer = (event: PointerEvent): void => { + if (!event.isTrusted) return; + const type = event.type as FramePickPointerType; + if (type === "pointerout" && event.relatedTarget !== null) return; + if ((type === "pointerdown" || type === "pointerup") && event.button === 0) { + event.preventDefault(); + event.stopImmediatePropagation(); + } + sendUp({ + kind: "pointer", + type, + x: event.clientX, + y: event.clientY, + button: event.button, + shiftKey: event.shiftKey, + hit: + type === "pointerout" ? null : hitAt(event.clientX, event.clientY, type === "pointerdown"), + }); + }; + + const onClick = (event: MouseEvent): void => { + if (!event.isTrusted) return; + event.preventDefault(); + event.stopImmediatePropagation(); + }; + + const onKey = (event: KeyboardEvent): void => { + if (!event.isTrusted || event.isComposing || event.metaKey || event.ctrlKey || event.altKey) + return; + if (!toolKeys.has(event.key)) return; + event.preventDefault(); + event.stopImmediatePropagation(); + sendUp({ kind: "key", key: event.key }); + }; + + const onLayoutChange = (): void => { + reportRects(); + broadcast({ kind: "refresh" }); + }; + + const pointerTypes: ReadonlyArray = [ + "pointermove", + "pointerdown", + "pointerup", + "pointerout", + ]; + + const activate = (): void => { + if (active) return; + active = true; + for (const type of pointerTypes) window.addEventListener(type, onPointer, true); + window.addEventListener("click", onClick, true); + window.addEventListener("keydown", onKey, true); + window.addEventListener("scroll", onLayoutChange, { capture: true, passive: true }); + window.addEventListener("resize", onLayoutChange, { passive: true }); + cursorStyle = document.createElement("style"); + cursorStyle.textContent = "html, html * { cursor: crosshair !important; }"; + document.documentElement.appendChild(cursorStyle); + }; + + const deactivate = (): void => { + if (!active) return; + active = false; + for (const type of pointerTypes) window.removeEventListener(type, onPointer, true); + window.removeEventListener("click", onClick, true); + window.removeEventListener("keydown", onKey, true); + window.removeEventListener("scroll", onLayoutChange, true); + window.removeEventListener("resize", onLayoutChange); + cursorStyle?.remove(); + cursorStyle = null; + for (const id of Array.from(baselines.keys())) restore(id); + elementsById.clear(); + }; + + const handleHere = (down: FramePickDown): void => { + if (down.kind === "start") activate(); + else if (down.kind === "stop") deactivate(); + else if (down.kind === "refresh") reportRects(); + else if (down.kind === "style") applyStyle(down.id, down.property, down.value); + else if (down.kind === "restore") restore(down.id); + else if (down.kind === "capture") { + const element = elementsById.get(down.id); + sendUp({ + kind: "captured", + requestId: down.requestId, + capture: element + ? { + selector: cssPath(element), + htmlPreview: element.outerHTML.slice(0, 500), + tagName: element.tagName.toLowerCase(), + } + : null, + }); + } + }; + + const route = (down: FramePickDown, path: ReadonlyArray): void => { + const [next, ...rest] = path; + if (next !== undefined) { + sendDown(next, down, rest); + return; + } + if (!deliver) handleHere(down); + if (down.kind === "start" || down.kind === "stop" || down.kind === "refresh") broadcast(down); + }; + + const onMessage = (event: MessageEvent): void => { + const envelope = (event.data as Record | null)?.[key] as + | { up?: FramePickUp; down?: FramePickDown; path?: number[]; frames?: string[] } + | undefined; + if (!envelope || typeof envelope !== "object" || !Array.isArray(envelope.path)) return; + if (envelope.up) { + const frames = childFrames(); + const index = frames.findIndex((frame) => frame.contentWindow === event.source); + const frame = frames[index]; + if (!frame) return; + if (envelope.up.kind === "hello") { + if (deliver || active) sendDown(index, { kind: "start" }, []); + return; + } + sendUp( + translate(envelope.up, contentBox(frame)), + [index, ...envelope.path], + [cssPath(frame), ...(envelope.frames ?? [])], + ); + return; + } + if (envelope.down && !deliver && event.source === window.parent) + route(envelope.down, envelope.path); + }; + + window.addEventListener("message", onMessage); + const relay: FramePickRelay = { + send: (path, down) => route(down, path), + dispose: () => { + window.removeEventListener("message", onMessage); + if (deliver) return; + deactivate(); + delete registry[key]; + }, + }; + if (!deliver) { + Object.defineProperty(registry, key, { value: relay, configurable: true }); + sendUp({ kind: "hello" }); + } + return relay; +} diff --git a/apps/desktop/src/preview/FramePickInjection.ts b/apps/desktop/src/preview/FramePickInjection.ts new file mode 100644 index 0000000000000..43c4383aae1ed --- /dev/null +++ b/apps/desktop/src/preview/FramePickInjection.ts @@ -0,0 +1,29 @@ +import { webFrameMain, type WebContents, type WebFrameMain } from "electron"; + +import { FRAME_PICK_MESSAGE_KEY, installFramePickAgent } from "./FramePickAgent.ts"; + +const agentSource = `(${installFramePickAgent.toString()})(${JSON.stringify(FRAME_PICK_MESSAGE_KEY)});`; + +const injectAgent = (frame: WebFrameMain | null | undefined): void => { + if (!frame || frame.detached) return; + frame.executeJavaScript(agentSource).catch(() => undefined); +}; + +export function watchFramesForPick(wc: WebContents): () => void { + const mainFrame = wc.mainFrame; + for (const frame of mainFrame?.framesInSubtree ?? []) { + if (frame !== mainFrame) injectAgent(frame); + } + const onFrameLoaded = ( + _event: Electron.Event, + isMainFrame: boolean, + processId: number, + routingId: number, + ): void => { + if (!isMainFrame) injectAgent(webFrameMain.fromId(processId, routingId)); + }; + wc.on("did-frame-finish-load", onFrameLoaded); + return () => { + wc.off("did-frame-finish-load", onFrameLoaded); + }; +} diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 9ca560b87e6c3..bbe7b42c5b7da 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -91,6 +91,7 @@ import { START_PICK_CHANNEL, THUMB_PRESS_CHANNEL, } from "./GuestProtocol.ts"; +import { watchFramesForPick } from "./FramePickInjection.ts"; import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts"; import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts"; import { DEFAULT_RECORDING_INPUT_OPTIONS, type RecordingInputOptions } from "./RecordingInput.ts"; @@ -2357,6 +2358,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.ipc.removeListener(ANNOTATION_VOICE_EVENT_CHANNEL, onVoiceEvent); wc.off("destroyed", onDestroyed); wc.off("did-start-navigation", onNavigated); + stopWatchingFrames(); }).pipe(Effect.ignore); // A newer session may already own the slot when this one is cancelled. yield* Ref.update(pickSessionsRef, (sessions) => @@ -2367,6 +2369,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function : sessions, ); }); + let stopWatchingFrames = (): void => undefined; let settled = false; const claimSettle = (): boolean => { if (settled) return false; @@ -2510,6 +2513,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function annotationSendEnabled.get(tabId) === true, voice, ); + stopWatchingFrames = watchFramesForPick(wc); }); }); runFork( diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index 9c7c2901b1085..345620612f05c 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -18,6 +18,15 @@ import type { } from "@t3tools/contracts"; import { createAnnotationIdSource } from "./AnnotationIds.ts"; +import { + FRAME_PICK_MESSAGE_KEY, + installFramePickAgent, + type FramePickCapture, + type FramePickDelivery, + type FramePickHit, + type FramePickRelay, + type FramePickUp, +} from "./FramePickAgent.ts"; import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts"; import { addStrokePoint, @@ -163,6 +172,16 @@ interface AnnotationSession { handleOverlayKey: (event: KeyboardEvent) => void; } +interface RemoteTarget { + readonly label: string; + readonly styles: CSSStyleDeclaration; + readonly capture: () => Promise; + readonly setStyle: (property: string, value: string) => void; + readonly restoreStyles: () => void; +} + +const remoteTargets = new WeakMap(); + let activeSession: AnnotationSession | null = null; let annotationTheme: DesktopPreviewAnnotationTheme | null = null; @@ -334,6 +353,8 @@ function pickFromPoint(clientX: number, clientY: number): Element | null { } function describeRawElement(element: Element): string { + const remote = remoteTargets.get(element); + if (remote) return remote.label; const tag = element.tagName.toLowerCase(); const id = element.id ? `#${element.id}` : ""; const classes = @@ -469,6 +490,8 @@ const HTML_PREVIEW_MAX_CHARS = 500; /** Preserve the tag, HTML, and crop rect when React context lookup fails or stalls. */ async function captureElement(element: Element): Promise { + const remote = remoteTargets.get(element); + if (remote) return remote.capture(); const base = { pageUrl: location.href, pageTitle: document.title?.trim() || null, @@ -959,6 +982,7 @@ function startAnnotation( }; const removeSelected = (target: SelectedElement): void => { + remoteTargets.get(target.element)?.restoreStyles(); if (target.element instanceof HTMLElement || target.element instanceof SVGElement) { for (const [property, baseline] of target.baselineStyles) { if (baseline) target.element.style.setProperty(property, baseline); @@ -1007,6 +1031,20 @@ function startAnnotation( const setStyleForSelected = (property: string, value: string): void => { for (const target of selected.values()) { + const remote = remoteTargets.get(target.element); + if (remote) { + const key = `${target.id}:${property}`; + styleChanges.set(key, { + targetId: target.id, + selector: null, + property, + previousValue: + styleChanges.get(key)?.previousValue ?? remote.styles.getPropertyValue(property).trim(), + value, + }); + remote.setStyle(property, value); + continue; + } if (!(target.element instanceof HTMLElement || target.element instanceof SVGElement)) continue; if (!target.baselineStyles.has(property)) { @@ -1227,7 +1265,7 @@ function startAnnotation( const syncStyleControls = (): void => { const first = selected.values().next().value as SelectedElement | undefined; if (!first) return; - const computed = getComputedStyle(first.element); + const computed = remoteTargets.get(first.element)?.styles ?? getComputedStyle(first.element); const rect = first.element.getBoundingClientRect(); aspectRatio = rect.height > 0 ? rect.width / rect.height : 1; widthInput.value = String(Math.round(rect.width)); @@ -1404,7 +1442,7 @@ function startAnnotation( dragHandle.addEventListener("pointerup", onEditorPointerUp); dragHandle.addEventListener("pointercancel", onEditorPointerUp); - const repaint = (): void => { + const repaintSelection = (): void => { for (const target of selected.values()) updateSelectedVisual(target); queueEditorLayout(); }; @@ -1415,6 +1453,11 @@ function startAnnotation( } repaint(); }; + let frameRelay: FramePickRelay | null = null; + const repaint = (): void => { + repaintSelection(); + frameRelay?.send([], { kind: "refresh" }); + }; // A scrollbar appearing narrows the viewport without a window resize. const rootResizeObserver = new ResizeObserver(repaint); @@ -1491,6 +1534,10 @@ function startAnnotation( return candidates.length; }; + let forwardedHit: Element | null | undefined; + const pickAt = (clientX: number, clientY: number): Element | null => + forwardedHit === undefined ? pickFromPoint(clientX, clientY) : forwardedHit; + const clearHoverOutline = (): void => { hoverOutline.style.display = "none"; }; @@ -1501,7 +1548,7 @@ function startAnnotation( return; } if (tool === "select" && dragStart === null) { - const target = pickFromPoint(event.clientX, event.clientY); + const target = pickAt(event.clientX, event.clientY); if (target) positionBox(hoverOutline, visibleElementRect(target)); else clearHoverOutline(); return; @@ -1535,7 +1582,7 @@ function startAnnotation( event.preventDefault(); event.stopPropagation(); if (tool === "select") { - const target = pickFromPoint(event.clientX, event.clientY); + const target = pickAt(event.clientX, event.clientY); if (target) toggleSelected(target, event.shiftKey); return; } @@ -1672,6 +1719,11 @@ function startAnnotation( finished = true; rootResizeObserver.disconnect(); restoreStyles(); + frameRelay?.send([], { kind: "stop" }); + frameRelay?.dispose(); + frameRelay = null; + for (const settle of pendingCaptures.values()) settle(null); + pendingCaptures.clear(); window.removeEventListener("pointermove", onPointerMove, true); window.removeEventListener("pointerdown", onPointerDown, true); window.removeEventListener("pointerup", onPointerUp, true); @@ -1837,6 +1889,138 @@ function startAnnotation( submitAnnotation(submission); }; + const mirrors = new Map(); + const pendingCaptures = new Map void>(); + const mirrorKey = (path: ReadonlyArray, id: string | null): string => + `${path.join(".")}#${id ?? "hover"}`; + + const captureRemote = async ( + path: ReadonlyArray, + frames: ReadonlyArray, + id: string, + label: string, + ): Promise => { + const requestId = nextId("capture"); + const capture = await withCaptureTimeout( + new Promise((resolve) => { + pendingCaptures.set(requestId, resolve); + frameRelay?.send(path, { kind: "capture", requestId, id }); + }), + ELEMENT_CONTEXT_TIMEOUT_MS, + ); + pendingCaptures.delete(requestId); + return { + pageUrl: location.href, + pageTitle: document.title?.trim() || null, + tagName: capture?.tagName ?? label.split(/[#.]/)[0] ?? "", + pickedAt: new Date().toISOString(), + selector: [...frames, capture?.selector ?? label].join(" >>> "), + htmlPreview: capture?.htmlPreview ?? "", + componentName: null, + source: null, + stack: [], + styles: "", + }; + }; + + const mirrorFor = ( + path: ReadonlyArray, + frames: ReadonlyArray, + hit: FramePickHit, + ): Element => { + const key = mirrorKey(path, hit.id); + let mirror = mirrors.get(key); + if (!mirror) { + mirror = document.createElement("div"); + mirror.setAttribute(OVERLAY_ATTRIBUTE, ""); + mirror.style.cssText = "position:fixed;left:0;top:0;visibility:hidden;pointer-events:none"; + root.appendChild(mirror); + mirrors.set(key, mirror); + } + positionBox(mirror, hit.rect); + const styles = document.createElement("div").style; + for (const [property, value] of Object.entries(hit.styles ?? {})) + styles.setProperty(property, value); + const id = hit.id; + remoteTargets.set(mirror, { + label: hit.label, + styles, + capture: () => captureRemote(path, frames, id ?? "", hit.label), + setStyle: (property, value) => { + if (id !== null) frameRelay?.send(path, { kind: "style", id, property, value }); + }, + restoreStyles: () => { + if (id !== null) frameRelay?.send(path, { kind: "restore", id }); + }, + }); + return mirror; + }; + + const forwardedPointerHandlers = { + pointermove: onPointerMove, + pointerdown: onPointerDown, + pointerup: onPointerUp, + pointerout: onPointerOut, + }; + + const forwardPointer = ( + up: Extract, + path: ReadonlyArray, + frames: ReadonlyArray, + ): void => { + if (!Object.hasOwn(forwardedPointerHandlers, up.type)) return; + if (!Number.isFinite(up.x) || !Number.isFinite(up.y)) return; + const handler = forwardedPointerHandlers[up.type]; + const forwarded = { + type: up.type, + clientX: up.x, + clientY: up.y, + button: up.button, + shiftKey: up.shiftKey, + target: document.documentElement, + relatedTarget: null, + preventDefault: () => undefined, + stopPropagation: () => undefined, + } as unknown as PointerEvent; + forwardedHit = up.hit ? mirrorFor(path, frames, up.hit) : null; + try { + handler(forwarded); + } finally { + forwardedHit = undefined; + } + }; + + const forwardKey = (key: string): void => { + onKeyDown({ + key, + code: key, + isTrusted: false, + isComposing: false, + keyCode: 0, + preventDefault: () => undefined, + stopPropagation: () => undefined, + stopImmediatePropagation: () => undefined, + } as unknown as KeyboardEvent); + }; + + const onFrameDelivery = ({ up, path, frames }: FramePickDelivery): void => { + if (finished) return; + if (up.kind === "pointer") forwardPointer(up, path, frames); + else if (up.kind === "key") forwardKey(up.key); + else if (up.kind === "rects") { + for (const entry of up.rects) { + const mirror = mirrors.get(mirrorKey(path, entry.id)); + if (mirror) positionBox(mirror, entry.rect); + } + repaintSelection(); + } else if (up.kind === "captured") { + pendingCaptures.get(up.requestId)?.(up.capture); + } + }; + + frameRelay = installFramePickAgent(FRAME_PICK_MESSAGE_KEY, onFrameDelivery); + frameRelay.send([], { kind: "start" }); + window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false }); window.addEventListener("pointerdown", onPointerDown, { capture: true, passive: false }); window.addEventListener("pointerup", onPointerUp, { capture: true, passive: false }); From 3fb936115312e8025789eddbf530a48c74c3df05 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 06:57:32 +0000 Subject: [PATCH 2/5] fix(desktop): frame pick relay ends with its session and checks relayed messages Subframe agents now remove their listener on stop, so no page can restart them after the annotation session ends. The preload checks every relayed field, since subframe agents run in the page's world. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/preview/FramePickAgent.ts | 4 + apps/desktop/src/preview/PickPreload.ts | 104 ++++++++++++++++++++- 2 files changed, 104 insertions(+), 4 deletions(-) diff --git a/apps/desktop/src/preview/FramePickAgent.ts b/apps/desktop/src/preview/FramePickAgent.ts index f29839dab739c..3fbaece71300a 100644 --- a/apps/desktop/src/preview/FramePickAgent.ts +++ b/apps/desktop/src/preview/FramePickAgent.ts @@ -68,6 +68,8 @@ export interface FramePickRelay { readonly dispose: () => void; } +// Main injects this function's source text into subframes, so it must not reference anything +// outside its own body. export function installFramePickAgent( key: string, deliver?: (delivery: FramePickDelivery) => void, @@ -387,6 +389,8 @@ export function installFramePickAgent( } if (!deliver) handleHere(down); if (down.kind === "start" || down.kind === "stop" || down.kind === "refresh") broadcast(down); + // Main injects a fresh agent into every frame when the next session starts. + if (down.kind === "stop") relay.dispose(); }; const onMessage = (event: MessageEvent): void => { diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index 345620612f05c..d400cbdce0d32 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -24,6 +24,8 @@ import { type FramePickCapture, type FramePickDelivery, type FramePickHit, + type FramePickPointerType, + type FramePickRect, type FramePickRelay, type FramePickUp, } from "./FramePickAgent.ts"; @@ -468,6 +470,100 @@ const pageNumber = (source: unknown, key: string): number | null => { return typeof value === "number" && Number.isFinite(value) ? value : null; }; +const pageRect = (source: unknown): FramePickRect | null => { + const x = pageNumber(source, "x"); + const y = pageNumber(source, "y"); + const width = pageNumber(source, "width"); + const height = pageNumber(source, "height"); + return x === null || y === null || width === null || height === null + ? null + : { x, y, width, height }; +}; + +const pageHit = (source: unknown): FramePickHit | null => { + const label = pageString(source, "label"); + const rect = pageRect(pageField(source, "rect")); + if (label === null || rect === null) return null; + const styles = pageField(source, "styles"); + return { + id: pageString(source, "id"), + label, + rect, + styles: + typeof styles === "object" && styles !== null + ? Object.fromEntries( + Object.entries(styles).filter( + (entry): entry is [string, string] => typeof entry[1] === "string", + ), + ) + : null, + }; +}; + +const FRAME_POINTER_TYPES: ReadonlySet = new Set([ + "pointermove", + "pointerdown", + "pointerup", + "pointerout", +]); + +/** Subframe agents run in the page's world, so a relayed message is checked field by field. */ +function parseFrameDelivery(delivery: FramePickDelivery): FramePickDelivery | null { + const { up, path, frames } = delivery as { up: unknown; path: unknown; frames: unknown }; + if (!Array.isArray(path) || !path.every((index) => Number.isInteger(index))) return null; + if (!Array.isArray(frames) || !frames.every((frame) => typeof frame === "string")) return null; + const relayed = (parsed: FramePickUp | null): FramePickDelivery | null => + parsed && { up: parsed, path, frames }; + const kind = pageField(up, "kind"); + if (kind === "pointer") { + const type = pageField(up, "type"); + const x = pageNumber(up, "x"); + const y = pageNumber(up, "y"); + const button = pageNumber(up, "button"); + if (!FRAME_POINTER_TYPES.has(type) || x === null || y === null || button === null) return null; + return relayed({ + kind, + type: type as FramePickPointerType, + x, + y, + button, + shiftKey: pageField(up, "shiftKey") === true, + hit: pageHit(pageField(up, "hit")), + }); + } + if (kind === "key") { + const key = pageString(up, "key"); + return relayed(key === null ? null : { kind, key }); + } + if (kind === "rects") { + const entries = pageField(up, "rects"); + if (!Array.isArray(entries)) return null; + const rects = entries.flatMap((entry) => { + const id = pageString(entry, "id"); + const rect = pageRect(pageField(entry, "rect")); + return id === null || rect === null ? [] : [{ id, rect }]; + }); + return relayed({ kind, rects }); + } + if (kind === "captured") { + const requestId = pageString(up, "requestId"); + if (requestId === null) return null; + const capture = pageField(up, "capture"); + const selector = pageString(capture, "selector"); + const htmlPreview = pageString(capture, "htmlPreview"); + const tagName = pageString(capture, "tagName"); + return relayed({ + kind, + requestId, + capture: + selector === null || htmlPreview === null || tagName === null + ? null + : { selector, htmlPreview: htmlPreview.slice(0, HTML_PREVIEW_MAX_CHARS), tagName }, + }); + } + return null; +} + const toStackFrame = (frame: unknown): PickedElementStackFrame => ({ functionName: pageString(frame, "functionName"), fileName: pageString(frame, "fileName"), @@ -1968,8 +2064,6 @@ function startAnnotation( path: ReadonlyArray, frames: ReadonlyArray, ): void => { - if (!Object.hasOwn(forwardedPointerHandlers, up.type)) return; - if (!Number.isFinite(up.x) || !Number.isFinite(up.y)) return; const handler = forwardedPointerHandlers[up.type]; const forwarded = { type: up.type, @@ -2003,8 +2097,10 @@ function startAnnotation( } as unknown as KeyboardEvent); }; - const onFrameDelivery = ({ up, path, frames }: FramePickDelivery): void => { - if (finished) return; + const onFrameDelivery = (delivery: FramePickDelivery): void => { + const parsed = parseFrameDelivery(delivery); + if (finished || !parsed) return; + const { up, path, frames } = parsed; if (up.kind === "pointer") forwardPointer(up, path, frames); else if (up.kind === "key") forwardKey(up.key); else if (up.kind === "rects") { From b9331799b7e057d5041aa1b151e14145b7a42eaa Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 07:11:21 +0000 Subject: [PATCH 3/5] fix(desktop): frame pick relay reaches iframes inside open shadow roots Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/preview/FramePickAgent.ts | 29 ++++++++++++++++++---- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/apps/desktop/src/preview/FramePickAgent.ts b/apps/desktop/src/preview/FramePickAgent.ts index 3fbaece71300a..5e66644b79672 100644 --- a/apps/desktop/src/preview/FramePickAgent.ts +++ b/apps/desktop/src/preview/FramePickAgent.ts @@ -101,8 +101,23 @@ export function installFramePickAgent( let active = false; let cursorStyle: HTMLStyleElement | null = null; - const childFrames = (): HTMLIFrameElement[] => - Array.from(document.querySelectorAll("iframe, frame")); + // Frames inside open shadow roots count too. The walk is cached and redone on a lookup miss + // so per-pointermove relays do not rescan the whole document. + let frameCache: HTMLIFrameElement[] | null = null; + const scanFrames = (): HTMLIFrameElement[] => { + const found: HTMLIFrameElement[] = []; + const visit = (root: Document | ShadowRoot): void => { + for (const element of Array.from(root.querySelectorAll("*"))) { + if (element instanceof HTMLIFrameElement || element.tagName === "FRAME") + found.push(element as HTMLIFrameElement); + if (element.shadowRoot) visit(element.shadowRoot); + } + }; + visit(document); + frameCache = found; + return found; + }; + const childFrames = (): HTMLIFrameElement[] => frameCache ?? scanFrames(); const post = (target: Window | null | undefined, envelope: unknown): void => { if (!target) return; @@ -223,7 +238,9 @@ export function installFramePickAgent( post(childFrames()[index]?.contentWindow, { down, path }); const broadcast = (down: FramePickDown): void => { - childFrames().forEach((_frame, index) => sendDown(index, down, [])); + (down.kind === "refresh" ? childFrames() : scanFrames()).forEach((_frame, index) => + sendDown(index, down, []), + ); }; const register = (element: Element): string => { @@ -399,8 +416,10 @@ export function installFramePickAgent( | undefined; if (!envelope || typeof envelope !== "object" || !Array.isArray(envelope.path)) return; if (envelope.up) { - const frames = childFrames(); - const index = frames.findIndex((frame) => frame.contentWindow === event.source); + const isSender = (frame: HTMLIFrameElement): boolean => frame.contentWindow === event.source; + let frames = childFrames(); + if (!frames.some(isSender)) frames = scanFrames(); + const index = frames.findIndex(isSender); const frame = frames[index]; if (!frame) return; if (envelope.up.kind === "hello") { From ba9f20ae754be56f218388814c4e9f6477f03119 Mon Sep 17 00:00:00 2001 From: kua-agent Date: Tue, 24 Nov 2026 12:17:14 +0400 Subject: [PATCH 4/5] fix(desktop): frame pick commands go through main, not page messages Capture, describe, style and restore requests now go from the preload to main over IPC. Main runs them in the frame it injected, addressed by a token per document, so markup and computed styles never pass through postMessage, and a removed sibling frame or a navigation can no longer send a command to the wrong document. Real Escape inside a subframe reaches the session through before-input-event; a relayed Escape is ignored. Rects map through iframe transforms and ancestor overflow clips, the controls use the unclipped size, Attach waits for a fresh rect, a failed capture gives a null selector, Region drags that start in a frame record a region, inline styles restore from the original style attribute, width, height and border-style are snapshotted, both element indexes reset per session, and malformed rect updates are dropped. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/preview/FramePickAgent.ts | 449 ++++++++++++------ .../desktop/src/preview/FramePickInjection.ts | 79 ++- apps/desktop/src/preview/Manager.test.ts | 34 +- apps/desktop/src/preview/PickPreload.ts | 246 ++++++---- 4 files changed, 573 insertions(+), 235 deletions(-) diff --git a/apps/desktop/src/preview/FramePickAgent.ts b/apps/desktop/src/preview/FramePickAgent.ts index 5e66644b79672..bce983d95ce07 100644 --- a/apps/desktop/src/preview/FramePickAgent.ts +++ b/apps/desktop/src/preview/FramePickAgent.ts @@ -1,4 +1,6 @@ export const FRAME_PICK_MESSAGE_KEY = "__t3codeFramePick"; +export const FRAME_PICK_COMMAND_CHANNEL = "preview:frame-pick-command"; +export const FRAME_PICK_ESCAPE_CHANNEL = "preview:frame-pick-escape"; export interface FramePickRect { readonly x: number; @@ -7,11 +9,16 @@ export interface FramePickRect { readonly height: number; } +export interface FramePickSize { + readonly width: number; + readonly height: number; +} + export interface FramePickHit { readonly id: string | null; readonly label: string; - readonly rect: FramePickRect; - readonly styles: Readonly> | null; + readonly visibleRect: FramePickRect; + readonly unclippedSize: FramePickSize; } export interface FramePickCapture { @@ -20,8 +27,25 @@ export interface FramePickCapture { readonly tagName: string; } +export type FramePickCommand = + | { readonly kind: "capture"; readonly id: string } + | { readonly kind: "describe"; readonly id: string } + | { + readonly kind: "style"; + readonly id: string; + readonly property: string; + readonly value: string; + } + | { readonly kind: "restore"; readonly id: string }; + export type FramePickPointerType = "pointermove" | "pointerdown" | "pointerup" | "pointerout"; +export interface FramePickElementBox { + readonly id: string; + readonly visibleRect: FramePickRect; + readonly unclippedSize: FramePickSize; +} + export type FramePickUp = | { readonly kind: "hello" } | { @@ -34,38 +58,23 @@ export type FramePickUp = readonly hit: FramePickHit | null; } | { readonly kind: "key"; readonly key: string } - | { - readonly kind: "rects"; - readonly rects: ReadonlyArray<{ readonly id: string; readonly rect: FramePickRect }>; - } - | { - readonly kind: "captured"; - readonly requestId: string; - readonly capture: FramePickCapture | null; - }; + | { readonly kind: "rects"; readonly rects: ReadonlyArray }; export type FramePickDown = | { readonly kind: "start" } | { readonly kind: "stop" } - | { readonly kind: "refresh" } - | { readonly kind: "capture"; readonly requestId: string; readonly id: string } - | { - readonly kind: "style"; - readonly id: string; - readonly property: string; - readonly value: string; - } - | { readonly kind: "restore"; readonly id: string }; + | { readonly kind: "refresh" }; export interface FramePickDelivery { readonly up: FramePickUp; - readonly path: ReadonlyArray; - readonly frames: ReadonlyArray; + readonly framePathsOutermostFirst: ReadonlyArray; + readonly senderDocumentToken: string | null; } export interface FramePickRelay { - readonly send: (path: ReadonlyArray, down: FramePickDown) => void; + readonly send: (down: FramePickDown) => void; readonly dispose: () => void; + readonly runCommandForDocument: (documentToken: string, command: FramePickCommand) => unknown; } // Main injects this function's source text into subframes, so it must not reference anything @@ -73,10 +82,11 @@ export interface FramePickRelay { export function installFramePickAgent( key: string, deliver?: (delivery: FramePickDelivery) => void, + documentToken: string | null = null, ): FramePickRelay { const registry = window as unknown as Record; - const installed = deliver ? undefined : registry[key]; - if (installed) return installed; + const replaceAgentWhoseStopIsStillInFlight = (): void => registry[key]?.dispose(); + if (!deliver) replaceAgentWhoseStopIsStillInFlight(); const styleProperties = [ "font-family", @@ -87,16 +97,19 @@ export function installFramePickAgent( "background-color", "border-color", "border-width", + "border-style", "border-radius", "opacity", "padding", "margin", "gap", + "width", + "height", ]; const toolKeys = new Set(["Escape", "v", "r", "d", "e"]); const elementsById = new Map(); - const idsByElement = new WeakMap(); - const baselines = new Map>(); + let idsByElement = new WeakMap(); + const styleAttributeBeforeFirstEdit = new Map(); let lastId = 0; let active = false; let cursorStyle: HTMLStyleElement | null = null; @@ -172,80 +185,209 @@ export function installFramePickAgent( return { x: left, y: top, width: Math.max(0, right - left), height: Math.max(0, bottom - top) }; }; - const visibleRect = (element: Element): FramePickRect => { - if (!element.isConnected) return { x: 0, y: 0, width: 0, height: 0 }; - const box = element.getBoundingClientRect(); - return intersect( - { x: box.left, y: box.top, width: box.width, height: box.height }, - { - x: 0, - y: 0, - width: document.documentElement.clientWidth, - height: document.documentElement.clientHeight, - }, + const isNumber = (value: unknown): value is number => + typeof value === "number" && Number.isFinite(value); + const isRect = (value: unknown): value is FramePickRect => { + const rect = value as Partial | null; + return ( + typeof rect === "object" && + rect !== null && + isNumber(rect.x) && + isNumber(rect.y) && + isNumber(rect.width) && + isNumber(rect.height) + ); + }; + const isSize = (value: unknown): value is FramePickSize => { + const size = value as Partial | null; + return ( + typeof size === "object" && size !== null && isNumber(size.width) && isNumber(size.height) ); }; - const contentBox = (frame: HTMLIFrameElement): FramePickRect => { + const transformScale = (element: HTMLElement, box: DOMRect): { sx: number; sy: number } => ({ + sx: element.offsetWidth ? box.width / element.offsetWidth : 1, + sy: element.offsetHeight ? box.height / element.offsetHeight : 1, + }); + + const parentAcrossShadowRoots = (element: Element): Element | null => { + if (element.parentElement) return element.parentElement; + const root = element.getRootNode(); + return root instanceof ShadowRoot ? root.host : null; + }; + + const viewportRect = (): FramePickRect => ({ + x: 0, + y: 0, + width: document.documentElement.clientWidth, + height: document.documentElement.clientHeight, + }); + + const clipByOverflowAncestor = (clip: FramePickRect, ancestor: HTMLElement): FramePickRect => { + const style = getComputedStyle(ancestor); + const clipsX = style.overflowX !== "visible"; + const clipsY = style.overflowY !== "visible"; + if (!clipsX && !clipsY) return clip; + const box = ancestor.getBoundingClientRect(); + const { sx, sy } = transformScale(ancestor, box); + return intersect(clip, { + x: clipsX ? box.left + ancestor.clientLeft * sx : clip.x, + y: clipsY ? box.top + ancestor.clientTop * sy : clip.y, + width: clipsX ? ancestor.clientWidth * sx : clip.width, + height: clipsY ? ancestor.clientHeight * sy : clip.height, + }); + }; + + const visibleAreaFor = (element: Element): FramePickRect => { + let clip = viewportRect(); + for ( + let ancestor = parentAcrossShadowRoots(element); + ancestor && ancestor !== document.documentElement && ancestor !== document.body; + ancestor = parentAcrossShadowRoots(ancestor) + ) { + if (ancestor instanceof HTMLElement) clip = clipByOverflowAncestor(clip, ancestor); + } + return clip; + }; + + const elementBox = (element: Element): Omit => { + if (!element.isConnected) { + return { + visibleRect: { x: 0, y: 0, width: 0, height: 0 }, + unclippedSize: { width: 0, height: 0 }, + }; + } + const box = element.getBoundingClientRect(); + return { + visibleRect: intersect( + { x: box.left, y: box.top, width: box.width, height: box.height }, + visibleAreaFor(element), + ), + unclippedSize: { width: box.width, height: box.height }, + }; + }; + + interface ChildDocumentPlacement { + readonly originX: number; + readonly originY: number; + readonly scaleX: number; + readonly scaleY: number; + readonly visibleArea: FramePickRect; + } + + const childDocumentPlacement = (frame: HTMLIFrameElement): ChildDocumentPlacement => { const box = frame.getBoundingClientRect(); const style = getComputedStyle(frame); + const { sx, sy } = transformScale(frame, box); const paddingLeft = Number.parseFloat(style.paddingLeft) || 0; const paddingTop = Number.parseFloat(style.paddingTop) || 0; const paddingRight = Number.parseFloat(style.paddingRight) || 0; const paddingBottom = Number.parseFloat(style.paddingBottom) || 0; + const originX = box.left + (frame.clientLeft + paddingLeft) * sx; + const originY = box.top + (frame.clientTop + paddingTop) * sy; + const contentBox = { + x: originX, + y: originY, + width: (frame.clientWidth - paddingLeft - paddingRight) * sx, + height: (frame.clientHeight - paddingTop - paddingBottom) * sy, + }; return { - x: box.left + frame.clientLeft + paddingLeft, - y: box.top + frame.clientTop + paddingTop, - width: frame.clientWidth - paddingLeft - paddingRight, - height: frame.clientHeight - paddingTop - paddingBottom, + originX, + originY, + scaleX: sx, + scaleY: sy, + visibleArea: intersect(contentBox, visibleAreaFor(frame)), }; }; - const shiftRect = (rect: FramePickRect, box: FramePickRect): FramePickRect => + const placeRect = (rect: FramePickRect, placement: ChildDocumentPlacement): FramePickRect => intersect( - { x: rect.x + box.x, y: rect.y + box.y, width: rect.width, height: rect.height }, - box, + { + x: placement.originX + rect.x * placement.scaleX, + y: placement.originY + rect.y * placement.scaleY, + width: rect.width * placement.scaleX, + height: rect.height * placement.scaleY, + }, + placement.visibleArea, ); + const placeSize = (size: FramePickSize, placement: ChildDocumentPlacement): FramePickSize => ({ + width: size.width * placement.scaleX, + height: size.height * placement.scaleY, + }); + + const placeValidHit = (hit: unknown, placement: ChildDocumentPlacement): FramePickHit | null => { + const candidate = hit as Partial | null; + if (!candidate || typeof candidate !== "object" || typeof candidate.label !== "string") + return null; + if (!isRect(candidate.visibleRect) || !isSize(candidate.unclippedSize)) return null; + return { + id: typeof candidate.id === "string" ? candidate.id : null, + label: candidate.label, + visibleRect: placeRect(candidate.visibleRect, placement), + unclippedSize: placeSize(candidate.unclippedSize, placement), + }; + }; - const translate = (up: FramePickUp, box: FramePickRect): FramePickUp => { + const placeValidBoxes = ( + boxes: unknown, + placement: ChildDocumentPlacement, + ): FramePickElementBox[] | null => { + if (!Array.isArray(boxes)) return null; + return boxes.flatMap((entry: unknown) => { + const candidate = entry as Partial | null; + if (!candidate || typeof candidate.id !== "string") return []; + if (!isRect(candidate.visibleRect) || !isSize(candidate.unclippedSize)) return []; + return [ + { + id: candidate.id, + visibleRect: placeRect(candidate.visibleRect, placement), + unclippedSize: placeSize(candidate.unclippedSize, placement), + }, + ]; + }); + }; + + const placeChildMessage = ( + up: FramePickUp, + placement: ChildDocumentPlacement, + ): FramePickUp | null => { if (up.kind === "pointer") { + if (!isNumber(up.x) || !isNumber(up.y)) return null; return { ...up, - x: up.x + box.x, - y: up.y + box.y, - hit: up.hit ? { ...up.hit, rect: shiftRect(up.hit.rect, box) } : null, + x: placement.originX + up.x * placement.scaleX, + y: placement.originY + up.y * placement.scaleY, + hit: placeValidHit(up.hit, placement), }; } if (up.kind === "rects") { - return { - ...up, - rects: up.rects.map((entry) => ({ id: entry.id, rect: shiftRect(entry.rect, box) })), - }; + const rects = placeValidBoxes(up.rects, placement); + return rects ? { kind: "rects", rects } : null; } return up; }; const sendUp = ( up: FramePickUp, - path: ReadonlyArray = [], - frames: ReadonlyArray = [], + framePathsOutermostFirst: ReadonlyArray = [], + senderDocumentToken: string | null = documentToken, ): void => { - if (deliver) deliver({ up, path, frames }); - else post(window.parent, { up, path, frames }); + const delivery = { up, framePathsOutermostFirst, senderDocumentToken }; + if (deliver) deliver(delivery); + else post(window.parent, delivery); }; - const sendDown = (index: number, down: FramePickDown, path: ReadonlyArray): void => - post(childFrames()[index]?.contentWindow, { down, path }); + const sendDown = (frame: HTMLIFrameElement, down: FramePickDown): void => + post(frame.contentWindow, { down }); const broadcast = (down: FramePickDown): void => { - (down.kind === "refresh" ? childFrames() : scanFrames()).forEach((_frame, index) => - sendDown(index, down, []), - ); + for (const frame of down.kind === "refresh" ? childFrames() : scanFrames()) + sendDown(frame, down); }; const register = (element: Element): string => { const known = idsByElement.get(element); - if (known) return known; + if (known && elementsById.get(known) === element) return known; lastId += 1; const id = String(lastId); idsByElement.set(element, id); @@ -253,13 +395,6 @@ export function installFramePickAgent( return id; }; - const snapshotStyles = (element: Element): Record => { - const computed = getComputedStyle(element); - return Object.fromEntries( - styleProperties.map((property) => [property, computed.getPropertyValue(property)]), - ); - }; - const hitAt = (x: number, y: number, selecting: boolean): FramePickHit | null => { const element = document .elementsFromPoint(x, y) @@ -268,8 +403,7 @@ export function installFramePickAgent( return { id: selecting ? register(element) : null, label: describe(element), - rect: visibleRect(element), - styles: selecting ? snapshotStyles(element) : null, + ...elementBox(element), }; }; @@ -277,31 +411,64 @@ export function installFramePickAgent( if (elementsById.size === 0) return; sendUp({ kind: "rects", - rects: Array.from(elementsById, ([id, element]) => ({ id, rect: visibleRect(element) })), + rects: Array.from(elementsById, ([id, element]) => ({ id, ...elementBox(element) })), }); }; - const restore = (id: string): void => { + const styleTarget = (id: string): HTMLElement | SVGElement | null => { const element = elementsById.get(id); - const saved = baselines.get(id); - if (!saved || !(element instanceof HTMLElement || element instanceof SVGElement)) return; - for (const [property, value] of saved) { - if (value) element.style.setProperty(property, value); - else element.style.removeProperty(property); - } - baselines.delete(id); + return element instanceof HTMLElement || element instanceof SVGElement ? element : null; + }; + + const restore = (id: string): void => { + const element = styleTarget(id); + if (!element || !styleAttributeBeforeFirstEdit.has(id)) return; + const original = styleAttributeBeforeFirstEdit.get(id) ?? null; + if (original === null) element.removeAttribute("style"); + else element.setAttribute("style", original); + styleAttributeBeforeFirstEdit.delete(id); + reportRects(); }; const applyStyle = (id: string, property: string, value: string): void => { - const element = elementsById.get(id); - if (!(element instanceof HTMLElement || element instanceof SVGElement)) return; - const saved = baselines.get(id) ?? new Map(); - if (!saved.has(property)) saved.set(property, element.style.getPropertyValue(property)); - baselines.set(id, saved); + const element = styleTarget(id); + if (!element) return; + if (!styleAttributeBeforeFirstEdit.has(id)) + styleAttributeBeforeFirstEdit.set(id, element.getAttribute("style")); element.style.setProperty(property, value, "important"); reportRects(); }; + const computedStyles = (element: Element): Record => { + const computed = getComputedStyle(element); + return Object.fromEntries( + styleProperties.map((property) => [property, computed.getPropertyValue(property)]), + ); + }; + + const captureWithFreshRect = (element: Element): FramePickCapture => { + reportRects(); + return { + selector: cssPath(element), + htmlPreview: element.outerHTML.slice(0, 500), + tagName: element.tagName.toLowerCase(), + }; + }; + + const runCommand = (command: FramePickCommand): unknown => { + if (command.kind === "style") { + applyStyle(command.id, command.property, command.value); + return null; + } + if (command.kind === "restore") { + restore(command.id); + return null; + } + const element = elementsById.get(command.id); + if (!element) return null; + return command.kind === "describe" ? computedStyles(element) : captureWithFreshRect(element); + }; + const onPointer = (event: PointerEvent): void => { if (!event.isTrusted) return; const type = event.type as FramePickPointerType; @@ -328,13 +495,15 @@ export function installFramePickAgent( event.stopImmediatePropagation(); }; + const escapeEndsTheSessionThroughMainOnly = (pressed: string): boolean => pressed === "Escape"; + const onKey = (event: KeyboardEvent): void => { if (!event.isTrusted || event.isComposing || event.metaKey || event.ctrlKey || event.altKey) return; if (!toolKeys.has(event.key)) return; event.preventDefault(); event.stopImmediatePropagation(); - sendUp({ kind: "key", key: event.key }); + if (!escapeEndsTheSessionThroughMainOnly(event.key)) sendUp({ kind: "key", key: event.key }); }; const onLayoutChange = (): void => { @@ -372,80 +541,84 @@ export function installFramePickAgent( window.removeEventListener("resize", onLayoutChange); cursorStyle?.remove(); cursorStyle = null; - for (const id of Array.from(baselines.keys())) restore(id); + for (const id of Array.from(styleAttributeBeforeFirstEdit.keys())) restore(id); elementsById.clear(); + idsByElement = new WeakMap(); }; - const handleHere = (down: FramePickDown): void => { - if (down.kind === "start") activate(); - else if (down.kind === "stop") deactivate(); - else if (down.kind === "refresh") reportRects(); - else if (down.kind === "style") applyStyle(down.id, down.property, down.value); - else if (down.kind === "restore") restore(down.id); - else if (down.kind === "capture") { - const element = elementsById.get(down.id); - sendUp({ - kind: "captured", - requestId: down.requestId, - capture: element - ? { - selector: cssPath(element), - htmlPreview: element.outerHTML.slice(0, 500), - tagName: element.tagName.toLowerCase(), - } - : null, - }); + const route = (down: FramePickDown): void => { + if (!deliver) { + if (down.kind === "start") activate(); + else if (down.kind === "stop") deactivate(); + else reportRects(); } + broadcast(down); + // Main injects a fresh agent into every frame when the next session starts. + if (down.kind === "stop") relay.dispose(); }; - const route = (down: FramePickDown, path: ReadonlyArray): void => { - const [next, ...rest] = path; - if (next !== undefined) { - sendDown(next, down, rest); + const senderFrame = (source: MessageEventSource | null): HTMLIFrameElement | undefined => { + const isSender = (frame: HTMLIFrameElement): boolean => frame.contentWindow === source; + return childFrames().find(isSender) ?? scanFrames().find(isSender); + }; + + const relayChildMessage = ( + event: MessageEvent, + envelope: { + up: FramePickUp; + framePathsOutermostFirst?: unknown; + senderDocumentToken?: unknown; + }, + ): void => { + const frame = senderFrame(event.source); + if (!frame) return; + if (envelope.up.kind === "hello") { + if (deliver || active) sendDown(frame, { kind: "start" }); return; } - if (!deliver) handleHere(down); - if (down.kind === "start" || down.kind === "stop" || down.kind === "refresh") broadcast(down); - // Main injects a fresh agent into every frame when the next session starts. - if (down.kind === "stop") relay.dispose(); + const placed = placeChildMessage(envelope.up, childDocumentPlacement(frame)); + if (!placed) return; + const innerPaths = Array.isArray(envelope.framePathsOutermostFirst) + ? envelope.framePathsOutermostFirst.filter((path): path is string => typeof path === "string") + : []; + sendUp( + placed, + [cssPath(frame), ...innerPaths], + typeof envelope.senderDocumentToken === "string" ? envelope.senderDocumentToken : null, + ); }; const onMessage = (event: MessageEvent): void => { const envelope = (event.data as Record | null)?.[key] as - | { up?: FramePickUp; down?: FramePickDown; path?: number[]; frames?: string[] } + | { + up?: FramePickUp; + down?: { kind?: unknown }; + framePathsOutermostFirst?: unknown; + senderDocumentToken?: unknown; + } | undefined; - if (!envelope || typeof envelope !== "object" || !Array.isArray(envelope.path)) return; - if (envelope.up) { - const isSender = (frame: HTMLIFrameElement): boolean => frame.contentWindow === event.source; - let frames = childFrames(); - if (!frames.some(isSender)) frames = scanFrames(); - const index = frames.findIndex(isSender); - const frame = frames[index]; - if (!frame) return; - if (envelope.up.kind === "hello") { - if (deliver || active) sendDown(index, { kind: "start" }, []); - return; - } - sendUp( - translate(envelope.up, contentBox(frame)), - [index, ...envelope.path], - [cssPath(frame), ...(envelope.frames ?? [])], - ); + if (!envelope || typeof envelope !== "object") return; + if (envelope.up && typeof envelope.up === "object") { + relayChildMessage(event, { ...envelope, up: envelope.up }); return; } - if (envelope.down && !deliver && event.source === window.parent) - route(envelope.down, envelope.path); + if (envelope.down && !deliver && event.source === window.parent) { + const kind = envelope.down.kind; + if (kind === "start" || kind === "stop" || kind === "refresh") route({ kind }); + } }; window.addEventListener("message", onMessage); const relay: FramePickRelay = { - send: (path, down) => route(down, path), + send: (down) => route(down), dispose: () => { window.removeEventListener("message", onMessage); if (deliver) return; deactivate(); - delete registry[key]; + if (registry[key] === relay) delete registry[key]; }, + runCommandForDocument: (token, command) => + documentToken !== null && token === documentToken && active ? runCommand(command) : null, }; if (!deliver) { Object.defineProperty(registry, key, { value: relay, configurable: true }); diff --git a/apps/desktop/src/preview/FramePickInjection.ts b/apps/desktop/src/preview/FramePickInjection.ts index 43c4383aae1ed..d9d094f42519b 100644 --- a/apps/desktop/src/preview/FramePickInjection.ts +++ b/apps/desktop/src/preview/FramePickInjection.ts @@ -1,15 +1,54 @@ import { webFrameMain, type WebContents, type WebFrameMain } from "electron"; -import { FRAME_PICK_MESSAGE_KEY, installFramePickAgent } from "./FramePickAgent.ts"; +import { + FRAME_PICK_COMMAND_CHANNEL, + FRAME_PICK_ESCAPE_CHANNEL, + FRAME_PICK_MESSAGE_KEY, + installFramePickAgent, + type FramePickCommand, +} from "./FramePickAgent.ts"; -const agentSource = `(${installFramePickAgent.toString()})(${JSON.stringify(FRAME_PICK_MESSAGE_KEY)});`; +const agentSourceFor = (documentToken: string): string => + `(${installFramePickAgent.toString()})(${JSON.stringify(FRAME_PICK_MESSAGE_KEY)}, undefined, ${JSON.stringify(documentToken)});`; -const injectAgent = (frame: WebFrameMain | null | undefined): void => { - if (!frame || frame.detached) return; - frame.executeJavaScript(agentSource).catch(() => undefined); -}; +const commandSourceFor = (documentToken: string, command: FramePickCommand): string => + `(() => { const agent = window[${JSON.stringify(FRAME_PICK_MESSAGE_KEY)}]; return agent && typeof agent.runCommandForDocument === "function" ? agent.runCommandForDocument(${JSON.stringify(documentToken)}, ${JSON.stringify(command)}) ?? null : null; })()`; + +const CSS_PROPERTY = /^-?[a-z][a-z-]*$/; +const MAX_STYLE_VALUE_CHARS = 1_000; + +function parseFramePickCommand(value: unknown): FramePickCommand | null { + if (typeof value !== "object" || value === null) return null; + const { kind, id, property, value: styleValue } = value as Record; + if (typeof id !== "string" || id.length > 32) return null; + if (kind === "capture" || kind === "describe" || kind === "restore") return { kind, id }; + if ( + kind === "style" && + typeof property === "string" && + CSS_PROPERTY.test(property) && + typeof styleValue === "string" && + styleValue.length <= MAX_STYLE_VALUE_CHARS + ) { + return { kind, id, property, value: styleValue }; + } + return null; +} + +const commandOwnerByWebContents = new WeakMap(); +let injectedDocuments = 0; export function watchFramesForPick(wc: WebContents): () => void { + const owner = Symbol("frame-pick-session"); + const framesByDocumentToken = new Map(); + + const injectAgent = (frame: WebFrameMain | null | undefined): void => { + if (!frame || frame.detached) return; + injectedDocuments += 1; + const documentToken = `${frame.processId}.${frame.routingId}.${injectedDocuments}`; + framesByDocumentToken.set(documentToken, frame); + frame.executeJavaScript(agentSourceFor(documentToken)).catch(() => undefined); + }; + const mainFrame = wc.mainFrame; for (const frame of mainFrame?.framesInSubtree ?? []) { if (frame !== mainFrame) injectAgent(frame); @@ -22,8 +61,36 @@ export function watchFramesForPick(wc: WebContents): () => void { ): void => { if (!isMainFrame) injectAgent(webFrameMain.fromId(processId, routingId)); }; + + const runCommand = async ( + _event: Electron.IpcMainInvokeEvent, + documentToken: unknown, + rawCommand: unknown, + ): Promise => { + const command = parseFramePickCommand(rawCommand); + if (typeof documentToken !== "string" || !command) return null; + const frame = framesByDocumentToken.get(documentToken); + if (!frame || frame.detached) return null; + return frame.executeJavaScript(commandSourceFor(documentToken, command)).catch(() => null); + }; + + const onInput = (_event: Electron.Event, input: Electron.Input): void => { + if (input.type !== "keyDown" || input.key !== "Escape" || input.isAutoRepeat) return; + wc.send(FRAME_PICK_ESCAPE_CHANNEL); + }; + wc.on("did-frame-finish-load", onFrameLoaded); + wc.on("before-input-event", onInput); + wc.ipc.removeHandler(FRAME_PICK_COMMAND_CHANNEL); + wc.ipc.handle(FRAME_PICK_COMMAND_CHANNEL, runCommand); + commandOwnerByWebContents.set(wc, owner); return () => { wc.off("did-frame-finish-load", onFrameLoaded); + wc.off("before-input-event", onInput); + if (commandOwnerByWebContents.get(wc) === owner) { + wc.ipc.removeHandler(FRAME_PICK_COMMAND_CHANNEL); + commandOwnerByWebContents.delete(wc); + } + framesByDocumentToken.clear(); }; } diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index c8e75e841d7c8..0432484cc13aa 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -333,7 +333,7 @@ const makeTestPreviewWebContents = ( isCurrentlyAudible: () => false, on: vi.fn(), off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, + ipc: { on: vi.fn(), off: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), @@ -493,7 +493,7 @@ const makeFaviconWebContents = (options?: { listeners.set(event, listener); }), off, - ipc: { on: vi.fn(), off: vi.fn() }, + ipc: { on: vi.fn(), off: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, send: webviewSend, session: { fetch }, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, @@ -1246,7 +1246,7 @@ describe("PreviewManager", () => { listeners.set(event, listener); }), off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, + ipc: { on: vi.fn(), off: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), @@ -1419,7 +1419,7 @@ describe("PreviewManager", () => { loadURL: vi.fn(async () => undefined), on: vi.fn(), off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, + ipc: { on: vi.fn(), off: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), @@ -1691,7 +1691,7 @@ describe("PreviewManager", () => { once: (event: string, listener: () => void) => { listeners.set(event, listener); }, - ipc: { on: vi.fn(), off: vi.fn() }, + ipc: { on: vi.fn(), off: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), @@ -1837,7 +1837,7 @@ describe("PreviewManager", () => { off: vi.fn((event: string) => { listeners.delete(event); }), - ipc: { on: vi.fn(), off: vi.fn() }, + ipc: { on: vi.fn(), off: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), @@ -2804,7 +2804,7 @@ describe("PreviewManager", () => { isCurrentlyAudible: () => false, on: vi.fn(), off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, + ipc: { on: vi.fn(), off: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), @@ -3406,7 +3406,13 @@ describe("PreviewManager", () => { }); }), off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() }, + ipc: { + on: vi.fn(), + off: vi.fn(), + removeListener: vi.fn(), + handle: vi.fn(), + removeHandler: vi.fn(), + }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), @@ -3467,7 +3473,13 @@ describe("PreviewManager", () => { Deferred.doneUnsafe(registrations++ === 0 ? firstReady : secondReady, Effect.void); }, once: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() }, + ipc: { + on: vi.fn(), + off: vi.fn(), + removeListener: vi.fn(), + handle: vi.fn(), + removeHandler: vi.fn(), + }, }; fromId.mockReturnValue(guest as never); yield* manager.createTab("tab_1"); @@ -3536,6 +3548,8 @@ describe("PreviewManager", () => { ), off: vi.fn(), removeListener: vi.fn(), + handle: vi.fn(), + removeHandler: vi.fn(), }, }), ] as const, @@ -3625,6 +3639,8 @@ describe("PreviewManager", () => { }), off: vi.fn(), removeListener: vi.fn(), + handle: vi.fn(), + removeHandler: vi.fn(), }, }), ); diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index d400cbdce0d32..d1cb42e9e7044 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -19,14 +19,19 @@ import type { import { createAnnotationIdSource } from "./AnnotationIds.ts"; import { + FRAME_PICK_COMMAND_CHANNEL, + FRAME_PICK_ESCAPE_CHANNEL, FRAME_PICK_MESSAGE_KEY, installFramePickAgent, type FramePickCapture, + type FramePickCommand, type FramePickDelivery, + type FramePickElementBox, type FramePickHit, type FramePickPointerType, type FramePickRect, type FramePickRelay, + type FramePickSize, type FramePickUp, } from "./FramePickAgent.ts"; import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts"; @@ -177,6 +182,7 @@ interface AnnotationSession { interface RemoteTarget { readonly label: string; readonly styles: CSSStyleDeclaration; + readonly unclippedSize: () => FramePickSize; readonly capture: () => Promise; readonly setStyle: (property: string, value: string) => void; readonly restoreStyles: () => void; @@ -480,26 +486,47 @@ const pageRect = (source: unknown): FramePickRect | null => { : { x, y, width, height }; }; +const pageSize = (source: unknown): FramePickSize | null => { + const width = pageNumber(source, "width"); + const height = pageNumber(source, "height"); + return width === null || height === null ? null : { width, height }; +}; + const pageHit = (source: unknown): FramePickHit | null => { const label = pageString(source, "label"); - const rect = pageRect(pageField(source, "rect")); - if (label === null || rect === null) return null; - const styles = pageField(source, "styles"); - return { - id: pageString(source, "id"), - label, - rect, - styles: - typeof styles === "object" && styles !== null - ? Object.fromEntries( - Object.entries(styles).filter( - (entry): entry is [string, string] => typeof entry[1] === "string", - ), - ) - : null, - }; + const visibleRect = pageRect(pageField(source, "visibleRect")); + const unclippedSize = pageSize(pageField(source, "unclippedSize")); + if (label === null || visibleRect === null || unclippedSize === null) return null; + return { id: pageString(source, "id"), label, visibleRect, unclippedSize }; }; +const pageElementBox = (source: unknown): FramePickElementBox | null => { + const id = pageString(source, "id"); + const visibleRect = pageRect(pageField(source, "visibleRect")); + const unclippedSize = pageSize(pageField(source, "unclippedSize")); + return id === null || visibleRect === null || unclippedSize === null + ? null + : { id, visibleRect, unclippedSize }; +}; + +const pageCapture = (source: unknown): FramePickCapture | null => { + const selector = pageString(source, "selector"); + const htmlPreview = pageString(source, "htmlPreview"); + const tagName = pageString(source, "tagName"); + return selector === null || htmlPreview === null || tagName === null + ? null + : { selector, htmlPreview: htmlPreview.slice(0, HTML_PREVIEW_MAX_CHARS), tagName }; +}; + +const pageStyles = (source: unknown): Record => + typeof source === "object" && source !== null + ? Object.fromEntries( + Object.entries(source).filter( + (entry): entry is [string, string] => typeof entry[1] === "string", + ), + ) + : {}; + const FRAME_POINTER_TYPES: ReadonlySet = new Set([ "pointermove", "pointerdown", @@ -509,11 +536,19 @@ const FRAME_POINTER_TYPES: ReadonlySet = new Set([ /** Subframe agents run in the page's world, so a relayed message is checked field by field. */ function parseFrameDelivery(delivery: FramePickDelivery): FramePickDelivery | null { - const { up, path, frames } = delivery as { up: unknown; path: unknown; frames: unknown }; - if (!Array.isArray(path) || !path.every((index) => Number.isInteger(index))) return null; - if (!Array.isArray(frames) || !frames.every((frame) => typeof frame === "string")) return null; + const { up, framePathsOutermostFirst, senderDocumentToken } = delivery as { + up: unknown; + framePathsOutermostFirst: unknown; + senderDocumentToken: unknown; + }; + if ( + !Array.isArray(framePathsOutermostFirst) || + !framePathsOutermostFirst.every((path) => typeof path === "string") + ) + return null; + if (typeof senderDocumentToken !== "string") return null; const relayed = (parsed: FramePickUp | null): FramePickDelivery | null => - parsed && { up: parsed, path, frames }; + parsed && { up: parsed, framePathsOutermostFirst, senderDocumentToken }; const kind = pageField(up, "kind"); if (kind === "pointer") { const type = pageField(up, "type"); @@ -538,27 +573,12 @@ function parseFrameDelivery(delivery: FramePickDelivery): FramePickDelivery | nu if (kind === "rects") { const entries = pageField(up, "rects"); if (!Array.isArray(entries)) return null; - const rects = entries.flatMap((entry) => { - const id = pageString(entry, "id"); - const rect = pageRect(pageField(entry, "rect")); - return id === null || rect === null ? [] : [{ id, rect }]; - }); - return relayed({ kind, rects }); - } - if (kind === "captured") { - const requestId = pageString(up, "requestId"); - if (requestId === null) return null; - const capture = pageField(up, "capture"); - const selector = pageString(capture, "selector"); - const htmlPreview = pageString(capture, "htmlPreview"); - const tagName = pageString(capture, "tagName"); return relayed({ kind, - requestId, - capture: - selector === null || htmlPreview === null || tagName === null - ? null - : { selector, htmlPreview: htmlPreview.slice(0, HTML_PREVIEW_MAX_CHARS), tagName }, + rects: entries.flatMap((entry) => { + const box = pageElementBox(entry); + return box ? [box] : []; + }), }); } return null; @@ -583,6 +603,7 @@ function withCaptureTimeout(promise: Promise, millis: number): Promise { @@ -1361,8 +1382,9 @@ function startAnnotation( const syncStyleControls = (): void => { const first = selected.values().next().value as SelectedElement | undefined; if (!first) return; - const computed = remoteTargets.get(first.element)?.styles ?? getComputedStyle(first.element); - const rect = first.element.getBoundingClientRect(); + const remote = remoteTargets.get(first.element); + const computed = remote?.styles ?? getComputedStyle(first.element); + const rect = remote?.unclippedSize() ?? first.element.getBoundingClientRect(); aspectRatio = rect.height > 0 ? rect.width / rect.height : 1; widthInput.value = String(Math.round(rect.width)); heightInput.value = String(Math.round(rect.height)); @@ -1552,7 +1574,7 @@ function startAnnotation( let frameRelay: FramePickRelay | null = null; const repaint = (): void => { repaintSelection(); - frameRelay?.send([], { kind: "refresh" }); + frameRelay?.send({ kind: "refresh" }); }; // A scrollbar appearing narrows the viewport without a window resize. const rootResizeObserver = new ResizeObserver(repaint); @@ -1631,6 +1653,7 @@ function startAnnotation( }; let forwardedHit: Element | null | undefined; + let dragStartedInFrame = false; const pickAt = (clientX: number, clientY: number): Element | null => forwardedHit === undefined ? pickFromPoint(clientX, clientY) : forwardedHit; @@ -1687,6 +1710,7 @@ function startAnnotation( return; } dragStart = { x: event.clientX, y: event.clientY }; + dragStartedInFrame = forwardedHit !== undefined; if (tool === "draw") { const geometry = startStroke(dragStart); const stroke: PreviewAnnotationStrokeTarget = { @@ -1720,7 +1744,7 @@ function startAnnotation( const rect = normalizeRect(dragStart.x, dragStart.y, event.clientX, event.clientY); marqueeBox.style.display = "none"; if (isUsableRect(rect)) { - const found = selectElementsInRect(rect); + const found = dragStartedInFrame ? 0 : selectElementsInRect(rect); if (found === 0) { const region: PreviewAnnotationRegionTarget = { id: nextId("region"), rect }; regions.push(region); @@ -1815,11 +1839,12 @@ function startAnnotation( finished = true; rootResizeObserver.disconnect(); restoreStyles(); - frameRelay?.send([], { kind: "stop" }); + frameRelay?.send({ kind: "stop" }); frameRelay?.dispose(); frameRelay = null; - for (const settle of pendingCaptures.values()) settle(null); - pendingCaptures.clear(); + for (const settle of rectWaiters.values()) settle(); + rectWaiters.clear(); + ipcRenderer.off(FRAME_PICK_ESCAPE_CHANNEL, onFrameEscape); window.removeEventListener("pointermove", onPointerMove, true); window.removeEventListener("pointerdown", onPointerDown, true); window.removeEventListener("pointerup", onPointerUp, true); @@ -1853,6 +1878,14 @@ function startAnnotation( }; const onCancel = (): void => teardown(false); + const focusIsInsideAFrame = (): boolean => { + let focused = document.activeElement; + while (focused?.shadowRoot?.activeElement) focused = focused.shadowRoot.activeElement; + return focused instanceof HTMLIFrameElement || focused?.tagName === "FRAME"; + }; + const onFrameEscape = (): void => { + if (focusIsInsideAFrame()) teardown(true); + }; const onCaptured = (): void => teardown(false); const onVoiceKeyUp = (event: KeyboardEvent): void => { if (!event.isTrusted || (event.code || event.key) !== voiceKeyCode) return; @@ -1880,7 +1913,7 @@ function startAnnotation( return; } } - if (event.key === "Escape" && !event.isComposing) { + if (event.key === "Escape" && event.isTrusted && !event.isComposing) { event.preventDefault(); event.stopPropagation(); teardown(true); @@ -1986,31 +2019,47 @@ function startAnnotation( }; const mirrors = new Map(); - const pendingCaptures = new Map void>(); - const mirrorKey = (path: ReadonlyArray, id: string | null): string => - `${path.join(".")}#${id ?? "hover"}`; + const mirrorSizes = new WeakMap(); + const rectWaiters = new Map void>(); + const mirrorKey = (documentToken: string, id: string | null): string => + `${documentToken}#${id ?? "hover"}`; + + const commandFrame = (documentToken: string, command: FramePickCommand): Promise => + ipcRenderer.invoke(FRAME_PICK_COMMAND_CHANNEL, documentToken, command).catch(() => null); + + const nextRectsFrom = (documentToken: string): Promise => + withCaptureTimeout( + new Promise((resolve) => { + rectWaiters.get(documentToken)?.(); + const settle = (): void => { + if (rectWaiters.get(documentToken) === settle) rectWaiters.delete(documentToken); + resolve(); + }; + rectWaiters.set(documentToken, settle); + }), + FRESH_RECT_TIMEOUT_MS, + ).then(() => undefined); const captureRemote = async ( - path: ReadonlyArray, - frames: ReadonlyArray, + documentToken: string, + framePaths: ReadonlyArray, id: string, label: string, ): Promise => { - const requestId = nextId("capture"); - const capture = await withCaptureTimeout( - new Promise((resolve) => { - pendingCaptures.set(requestId, resolve); - frameRelay?.send(path, { kind: "capture", requestId, id }); - }), - ELEMENT_CONTEXT_TIMEOUT_MS, + const freshRect = nextRectsFrom(documentToken); + const capture = pageCapture( + await withCaptureTimeout( + commandFrame(documentToken, { kind: "capture", id }), + ELEMENT_CONTEXT_TIMEOUT_MS, + ), ); - pendingCaptures.delete(requestId); + if (capture) await freshRect; return { pageUrl: location.href, pageTitle: document.title?.trim() || null, tagName: capture?.tagName ?? label.split(/[#.]/)[0] ?? "", pickedAt: new Date().toISOString(), - selector: [...frames, capture?.selector ?? label].join(" >>> "), + selector: capture ? [...framePaths, capture.selector].join(" >>> ") : null, htmlPreview: capture?.htmlPreview ?? "", componentName: null, source: null, @@ -2019,12 +2068,39 @@ function startAnnotation( }; }; + const placeMirror = (mirror: HTMLDivElement, box: Omit): void => { + positionBox(mirror, box.visibleRect); + mirrorSizes.set(mirror, box.unclippedSize); + }; + + const loadRemoteStyles = ( + mirror: HTMLDivElement, + styles: CSSStyleDeclaration, + documentToken: string, + id: string, + ): void => { + void commandFrame(documentToken, { kind: "describe", id }).then((described) => { + for (const [property, value] of Object.entries(pageStyles(described))) + styles.setProperty(property, value); + if (selected.values().next().value?.element === mirror && editorExpanded) syncStyleControls(); + }); + }; + + const hoverTarget = (label: string): RemoteTarget => ({ + label, + styles: document.createElement("div").style, + unclippedSize: () => ({ width: 0, height: 0 }), + capture: () => Promise.reject(new Error("hover outline only")), + setStyle: () => undefined, + restoreStyles: () => undefined, + }); + const mirrorFor = ( - path: ReadonlyArray, - frames: ReadonlyArray, + documentToken: string, + framePaths: ReadonlyArray, hit: FramePickHit, ): Element => { - const key = mirrorKey(path, hit.id); + const key = mirrorKey(documentToken, hit.id); let mirror = mirrors.get(key); if (!mirror) { mirror = document.createElement("div"); @@ -2033,22 +2109,28 @@ function startAnnotation( root.appendChild(mirror); mirrors.set(key, mirror); } - positionBox(mirror, hit.rect); - const styles = document.createElement("div").style; - for (const [property, value] of Object.entries(hit.styles ?? {})) - styles.setProperty(property, value); + placeMirror(mirror, hit); const id = hit.id; + if (id === null) { + remoteTargets.set(mirror, hoverTarget(hit.label)); + return mirror; + } + if (remoteTargets.has(mirror)) return mirror; + const styles = document.createElement("div").style; + const sizedMirror = mirror; remoteTargets.set(mirror, { label: hit.label, styles, - capture: () => captureRemote(path, frames, id ?? "", hit.label), + unclippedSize: () => mirrorSizes.get(sizedMirror) ?? hit.unclippedSize, + capture: () => captureRemote(documentToken, framePaths, id, hit.label), setStyle: (property, value) => { - if (id !== null) frameRelay?.send(path, { kind: "style", id, property, value }); + void commandFrame(documentToken, { kind: "style", id, property, value }); }, restoreStyles: () => { - if (id !== null) frameRelay?.send(path, { kind: "restore", id }); + void commandFrame(documentToken, { kind: "restore", id }); }, }); + loadRemoteStyles(mirror, styles, documentToken, id); return mirror; }; @@ -2061,8 +2143,8 @@ function startAnnotation( const forwardPointer = ( up: Extract, - path: ReadonlyArray, - frames: ReadonlyArray, + documentToken: string, + framePaths: ReadonlyArray, ): void => { const handler = forwardedPointerHandlers[up.type]; const forwarded = { @@ -2076,7 +2158,7 @@ function startAnnotation( preventDefault: () => undefined, stopPropagation: () => undefined, } as unknown as PointerEvent; - forwardedHit = up.hit ? mirrorFor(path, frames, up.hit) : null; + forwardedHit = up.hit ? mirrorFor(documentToken, framePaths, up.hit) : null; try { handler(forwarded); } finally { @@ -2099,23 +2181,22 @@ function startAnnotation( const onFrameDelivery = (delivery: FramePickDelivery): void => { const parsed = parseFrameDelivery(delivery); - if (finished || !parsed) return; - const { up, path, frames } = parsed; - if (up.kind === "pointer") forwardPointer(up, path, frames); + if (finished || !parsed || parsed.senderDocumentToken === null) return; + const { up, framePathsOutermostFirst, senderDocumentToken } = parsed; + if (up.kind === "pointer") forwardPointer(up, senderDocumentToken, framePathsOutermostFirst); else if (up.kind === "key") forwardKey(up.key); else if (up.kind === "rects") { for (const entry of up.rects) { - const mirror = mirrors.get(mirrorKey(path, entry.id)); - if (mirror) positionBox(mirror, entry.rect); + const mirror = mirrors.get(mirrorKey(senderDocumentToken, entry.id)); + if (mirror) placeMirror(mirror, entry); } repaintSelection(); - } else if (up.kind === "captured") { - pendingCaptures.get(up.requestId)?.(up.capture); + rectWaiters.get(senderDocumentToken)?.(); } }; frameRelay = installFramePickAgent(FRAME_PICK_MESSAGE_KEY, onFrameDelivery); - frameRelay.send([], { kind: "start" }); + frameRelay.send({ kind: "start" }); window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false }); window.addEventListener("pointerdown", onPointerDown, { capture: true, passive: false }); @@ -2133,6 +2214,7 @@ function startAnnotation( host.addEventListener(type, stopAtOverlay, { passive: true }); document.documentElement.addEventListener("focusout", onFocusOutToOverlay); ipcRenderer.on(CANCEL_PICK_CHANNEL, onCancel); + ipcRenderer.on(FRAME_PICK_ESCAPE_CHANNEL, onFrameEscape); ipcRenderer.on(ANNOTATION_CAPTURED_CHANNEL, onCaptured); if (voice) ipcRenderer.on(ANNOTATION_VOICE_STATE_CHANNEL, onVoiceState); if (inputLayer) { From b16cfec34de9170aeffc01281458ca0f7de270bb Mon Sep 17 00:00:00 2001 From: kua-agent Date: Tue, 24 Nov 2026 12:20:49 +0400 Subject: [PATCH 5/5] fix(desktop): reopened style editor shows a framed element's current styles Expanding the editor asks the frame for fresh computed styles, while the edit record keeps the styles read at pick time as its previous values. Co-Authored-By: Claude Opus 5.5 --- apps/desktop/src/preview/PickPreload.ts | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index d1cb42e9e7044..96890dea70286 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -182,6 +182,8 @@ interface AnnotationSession { interface RemoteTarget { readonly label: string; readonly styles: CSSStyleDeclaration; + readonly stylesWhenPicked: CSSStyleDeclaration; + readonly reloadStyles: () => void; readonly unclippedSize: () => FramePickSize; readonly capture: () => Promise; readonly setStyle: (property: string, value: string) => void; @@ -1156,7 +1158,8 @@ function startAnnotation( selector: null, property, previousValue: - styleChanges.get(key)?.previousValue ?? remote.styles.getPropertyValue(property).trim(), + styleChanges.get(key)?.previousValue ?? + remote.stylesWhenPicked.getPropertyValue(property).trim(), value, }); remote.setStyle(property, value); @@ -1509,7 +1512,10 @@ function startAnnotation( adjust.setAttribute("aria-expanded", "true"); adjust.title = "Collapse annotation editor"; adjust.setAttribute("aria-label", "Collapse annotation editor"); - if (selected.size > 0) syncStyleControls(); + if (selected.size > 0) { + syncStyleControls(); + for (const target of selected.values()) remoteTargets.get(target.element)?.reloadStyles(); + } } else { editorExpanded = false; editorPosition = null; @@ -2075,13 +2081,13 @@ function startAnnotation( const loadRemoteStyles = ( mirror: HTMLDivElement, - styles: CSSStyleDeclaration, + targets: ReadonlyArray, documentToken: string, id: string, ): void => { void commandFrame(documentToken, { kind: "describe", id }).then((described) => { for (const [property, value] of Object.entries(pageStyles(described))) - styles.setProperty(property, value); + for (const styles of targets) styles.setProperty(property, value); if (selected.values().next().value?.element === mirror && editorExpanded) syncStyleControls(); }); }; @@ -2089,6 +2095,8 @@ function startAnnotation( const hoverTarget = (label: string): RemoteTarget => ({ label, styles: document.createElement("div").style, + stylesWhenPicked: document.createElement("div").style, + reloadStyles: () => undefined, unclippedSize: () => ({ width: 0, height: 0 }), capture: () => Promise.reject(new Error("hover outline only")), setStyle: () => undefined, @@ -2117,10 +2125,13 @@ function startAnnotation( } if (remoteTargets.has(mirror)) return mirror; const styles = document.createElement("div").style; + const stylesWhenPicked = document.createElement("div").style; const sizedMirror = mirror; remoteTargets.set(mirror, { label: hit.label, styles, + stylesWhenPicked, + reloadStyles: () => loadRemoteStyles(sizedMirror, [styles], documentToken, id), unclippedSize: () => mirrorSizes.get(sizedMirror) ?? hit.unclippedSize, capture: () => captureRemote(documentToken, framePaths, id, hit.label), setStyle: (property, value) => { @@ -2130,7 +2141,7 @@ function startAnnotation( void commandFrame(documentToken, { kind: "restore", id }); }, }); - loadRemoteStyles(mirror, styles, documentToken, id); + loadRemoteStyles(mirror, [styles, stylesWhenPicked], documentToken, id); return mirror; };