Add browser page annotations (#1979)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinwoo Hong
2026-05-15 18:39:32 -07:00
committed by GitHub
co-authored by Orca
parent c4cd233ae5
commit 727ccf7c69
26 changed files with 2376 additions and 142 deletions
@@ -0,0 +1,125 @@
import { describe, expect, it } from 'vitest'
import { clampGrabPayload } from './browser-grab-payload'
function makeRawPayload(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
page: {
sanitizedUrl: 'https://example.com/page?access_token=secret#hash',
title: 'Example',
viewportWidth: 1280,
viewportHeight: 720,
scrollX: 0,
scrollY: 0,
devicePixelRatio: 1,
capturedAt: '2026-05-15T00:00:00.000Z'
},
target: {
tagName: 'button',
selector: 'button.primary',
elementPath: 'main > button.primary',
fullPath: 'html > body > main > button.primary',
cssClasses: 'primary',
nearbyElements: ['span "Label"'],
selectedText: '',
isFixed: false,
reactComponents: '<App> <Button>',
sourceFile: 'src/Button.tsx:12:4',
textSnippet: 'Submit',
htmlSnippet: '<button class="primary">Submit</button>',
attributes: { class: 'primary', type: 'button' },
accessibility: {
role: 'button',
accessibleName: 'Submit',
ariaLabel: null,
ariaLabelledBy: null
},
rectViewport: { x: 10, y: 20, width: 100, height: 40 },
rectPage: { x: 10, y: 20, width: 100, height: 40 },
computedStyles: {
display: 'inline-flex',
position: 'static',
width: '100px',
height: '40px',
margin: '0px',
padding: '8px',
color: 'rgb(0, 0, 0)',
backgroundColor: 'rgba(0, 0, 0, 0)',
border: '0px none',
borderRadius: '0px',
fontFamily: 'Geist',
fontSize: '14px',
fontWeight: '400',
lineHeight: '20px',
textAlign: 'center',
zIndex: 'auto'
}
},
nearbyText: ['Submit'],
ancestorPath: ['button', 'main'],
screenshot: null,
...overrides
}
}
describe('clampGrabPayload', () => {
it('redacts secret-bearing cssClasses outside the attribute path', () => {
const payload = clampGrabPayload(
makeRawPayload({
target: {
...(makeRawPayload().target as Record<string, unknown>),
cssClasses: 'primary access_token=secret'
}
})
)
expect(payload?.target.cssClasses).toBe('[redacted]')
})
it('redacts secret-bearing browser annotation metadata fields', () => {
const payload = clampGrabPayload(
makeRawPayload({
target: {
...(makeRawPayload().target as Record<string, unknown>),
elementPath: 'main > button[aria-label="access_token=secret"]',
fullPath: 'body > main > button#client_secret',
reactComponents: '<App> <PasswordSecretPanel>',
sourceFile: 'src/client_secret/Button.tsx:12:4',
nearbyElements: ['span "api_key=secret"'],
selectedText: 'password=secret',
accessibility: {
role: 'button',
accessibleName: 'access_token=secret',
ariaLabel: 'access_token=secret',
ariaLabelledBy: null
}
}
})
)
expect(payload?.target.elementPath).toBe('[redacted]')
expect(payload?.target.fullPath).toBe('[redacted]')
expect(payload?.target.reactComponents).toBe('[redacted]')
expect(payload?.target.sourceFile).toBe('[redacted]')
expect(payload?.target.nearbyElements).toEqual(['[redacted]'])
expect(payload?.target.selectedText).toBe('[redacted]')
expect(payload?.target.accessibility.accessibleName).toBe('[redacted]')
expect(payload?.target.accessibility.ariaLabel).toBe('[redacted]')
})
it('keeps and clamps browser annotation metadata fields', () => {
const payload = clampGrabPayload(
makeRawPayload({
target: {
...(makeRawPayload().target as Record<string, unknown>),
nearbyElements: Array.from({ length: 10 }, (_, index) => `item-${index}`),
reactComponents: '<App>'.repeat(200),
sourceFile: 'src/Button.tsx:12:4'
}
})
)
expect(payload?.target.nearbyElements).toHaveLength(6)
expect(payload?.target.reactComponents?.length).toBeLessThanOrEqual(512)
expect(payload?.target.sourceFile).toBe('src/Button.tsx:12:4')
})
})
+40 -5
View File
@@ -105,6 +105,26 @@ export function clampGrabPayload(raw: unknown): BrowserGrabPayload | null {
return filtered
}
const safeMetadataStr = (value: unknown, max: number): string => {
const strValue = safeStr(value, max)
return strValue && containsSecret(strValue) ? '[redacted]' : strValue
}
const safeNullableMetadataStr = (value: unknown, max: number): string | null =>
safeMetadataStr(value, max) || null
const safeMetadataArray = (
arr: unknown,
maxEntries: number,
maxEntryLength: number
): string[] => {
const items = Array.isArray(arr) ? arr : []
return items
.slice(0, maxEntries)
.map((item) => safeMetadataStr(item, maxEntryLength))
.filter(Boolean)
}
const safeRect = (r: unknown): BrowserGrabRect => {
if (!r || typeof r !== 'object') {
return { x: 0, y: 0, width: 0, height: 0 }
@@ -136,15 +156,30 @@ export function clampGrabPayload(raw: unknown): BrowserGrabPayload | null {
},
target: {
tagName: safeStr(target.tagName, 50),
selector: safeStr(target.selector, 500),
selector: safeStr(target.selector, GRAB_BUDGET.selectorMaxLength),
elementPath: safeMetadataStr(target.elementPath, GRAB_BUDGET.pathMaxLength),
fullPath: safeMetadataStr(target.fullPath, GRAB_BUDGET.pathMaxLength),
cssClasses: safeMetadataStr(target.cssClasses, GRAB_BUDGET.cssClassesMaxLength),
nearbyElements: safeMetadataArray(
target.nearbyElements,
GRAB_BUDGET.nearbyElementsMaxEntries,
GRAB_BUDGET.nearbyElementMaxLength
),
selectedText: safeMetadataStr(target.selectedText, GRAB_BUDGET.selectedTextMaxLength) || null,
isFixed: target.isFixed === true,
reactComponents: safeNullableMetadataStr(
target.reactComponents,
GRAB_BUDGET.reactComponentsMaxLength
),
sourceFile: safeNullableMetadataStr(target.sourceFile, GRAB_BUDGET.sourceFileMaxLength),
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
role: safeNullableMetadataStr(accessibility?.role, 500),
accessibleName: safeNullableMetadataStr(accessibility?.accessibleName, 500),
ariaLabel: safeNullableMetadataStr(accessibility?.ariaLabel, 500),
ariaLabelledBy: safeNullableMetadataStr(accessibility?.ariaLabelledBy, 500)
},
rectViewport: safeRect(target.rectViewport),
rectPage: safeRect(target.rectPage),
+20 -10
View File
@@ -1,6 +1,24 @@
import type { BrowserGrabRect, BrowserGrabScreenshot } from '../../shared/browser-grab-types'
import { GRAB_BUDGET } from '../../shared/browser-grab-types'
const HIDE_BROWSER_GRAB_OVERLAY_SCRIPT = `(function(){
var g = window.__orcaGrab;
if (g && g.host) g.host.style.display = 'none';
document.querySelectorAll('[data-orca-browser-annotation-overlay]').forEach(function(el) {
el.setAttribute('data-orca-previous-display', el.style.display || '');
el.style.display = 'none';
});
})()`
const RESTORE_BROWSER_GRAB_OVERLAY_SCRIPT = `(function(){
var g = window.__orcaGrab;
if (g && g.host) g.host.style.display = '';
document.querySelectorAll('[data-orca-browser-annotation-overlay]').forEach(function(el) {
el.style.display = el.getAttribute('data-orca-previous-display') || '';
el.removeAttribute('data-orca-previous-display');
});
})()`
/**
* Capture a screenshot of the guest surface and optionally crop it to
* the given CSS-pixel rect.
@@ -26,20 +44,12 @@ export async function captureSelectionScreenshot(
// 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(() => {})
await guest.executeJavaScript(HIDE_BROWSER_GRAB_OVERLAY_SCRIPT).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(() => {})
await guest.executeJavaScript(RESTORE_BROWSER_GRAB_OVERLAY_SCRIPT).catch(() => {})
}
if (image.isEmpty()) {
return null
@@ -12,6 +12,7 @@ const {
guestSetBackgroundThrottlingMock,
guestSetWindowOpenHandlerMock,
guestExecuteJavaScriptMock,
guestExecuteJavaScriptInIsolatedWorldMock,
guestIsDestroyedMock,
guestGetZoomFactorMock,
guestCapturePageMock,
@@ -25,6 +26,7 @@ const {
guestSetBackgroundThrottlingMock: vi.fn(),
guestSetWindowOpenHandlerMock: vi.fn(),
guestExecuteJavaScriptMock: vi.fn(),
guestExecuteJavaScriptInIsolatedWorldMock: vi.fn(),
guestIsDestroyedMock: vi.fn(() => false),
guestGetZoomFactorMock: vi.fn(() => 1),
guestCapturePageMock: vi.fn(),
@@ -53,6 +55,7 @@ function makeGuest(id: number) {
off: guestOffMock,
openDevTools: vi.fn(),
executeJavaScript: guestExecuteJavaScriptMock,
executeJavaScriptInIsolatedWorld: guestExecuteJavaScriptInIsolatedWorldMock,
getZoomFactor: guestGetZoomFactorMock,
capturePage: guestCapturePageMock,
getURL: vi.fn(() => 'https://example.com/')
@@ -67,6 +70,7 @@ describe('browserManager grab operations', () => {
vi.clearAllMocks()
guestIsDestroyedMock.mockReturnValue(false)
guestExecuteJavaScriptMock.mockResolvedValue(true)
guestExecuteJavaScriptInIsolatedWorldMock.mockResolvedValue(true)
browserManager.unregisterAll()
guest = makeGuest(101)
@@ -753,11 +757,11 @@ describe('browserManager grab operations', () => {
})
expect(guestExecuteJavaScriptMock).toHaveBeenNthCalledWith(
1,
`(function(){ var g = window.__orcaGrab; if (g && g.host) g.host.style.display = 'none'; })()`
expect.stringContaining('__orcaGrab')
)
expect(guestExecuteJavaScriptMock).toHaveBeenNthCalledWith(
2,
`(function(){ var g = window.__orcaGrab; if (g && g.host) g.host.style.display = ''; })()`
expect.stringContaining('__orcaGrab')
)
expect(guestExecuteJavaScriptMock).toHaveBeenNthCalledWith(3, 'window.innerWidth')
})
+30
View File
@@ -1220,6 +1220,7 @@ describe('browserManager', () => {
on: guestOnMock,
off: guestOffMock,
openDevTools: guestOpenDevToolsMock,
executeJavaScriptInIsolatedWorld: vi.fn().mockResolvedValue(true),
debugger: {
isAttached: debuggerIsAttached,
attach: debuggerAttach,
@@ -1358,5 +1359,34 @@ describe('browserManager', () => {
expect(debuggerAttach).toHaveBeenCalledWith('1.3')
expect(debuggerSendCommand).not.toHaveBeenCalled()
})
it('installs annotation viewport bridge in an isolated world', async () => {
const { guest } = makeGuest(4646)
webContentsFromIdMock.mockReturnValue(guest)
browserManager.attachGuestPolicies(guest as never)
browserManager.registerGuest({
browserPageId: 'tab-annotations',
webContentsId: guest.id as number,
rendererWebContentsId
})
const ok = await browserManager.setAnnotationViewportBridge('tab-annotations', {
emitViewport: false,
enabled: true,
markers: [],
token: 'annotationviewporttoken'
})
expect(ok).toBe(true)
expect(guest.executeJavaScriptInIsolatedWorld).toHaveBeenCalledWith(
expect.any(Number),
[
expect.objectContaining({
code: expect.stringContaining('__orcaBrowserAnnotationViewportBridge')
})
],
false
)
})
})
})
+55
View File
@@ -37,6 +37,11 @@ import {
import { ANTI_DETECTION_SCRIPT } from './anti-detection'
import { cleanElectronUserAgent } from './browser-session-ua'
import type { BrowserViewportOverride } from '../../shared/types'
import {
type BrowserAnnotationViewportBridgeOptions,
BROWSER_ANNOTATION_VIEWPORT_BRIDGE_WORLD_ID,
buildBrowserAnnotationViewportBridgeScript
} from '../../shared/browser-annotation-viewport-bridge'
// Why: mobile presets need a touch-capable UA or responsive sites serve the
// desktop variant based on UA sniffing. This is the Chrome DevTools default
@@ -109,6 +114,7 @@ export class BrowserManager {
private readonly contextMenuCleanupByTabId = new Map<string, () => void>()
private readonly grabShortcutCleanupByTabId = new Map<string, () => void>()
private readonly shortcutForwardingCleanupByTabId = new Map<string, () => void>()
private readonly annotationViewportBridgeOpsByTabId = new Map<string, Promise<unknown>>()
private readonly worktreeIdByTabId = new Map<string, string>()
private readonly policyAttachedGuestIds = new Set<number>()
private readonly policyCleanupByGuestId = new Map<number, () => void>()
@@ -681,6 +687,7 @@ export class BrowserManager {
// Why: drop any pending viewport-op chain for this tab so the Map doesn't
// retain a resolved promise keyed to a destroyed guest.
this.viewportOpsByTabId.delete(browserTabId)
this.annotationViewportBridgeOpsByTabId.delete(browserTabId)
}
unregisterAll(): void {
@@ -708,6 +715,7 @@ export class BrowserManager {
this.pendingPermissionEventsByGuestId.clear()
this.pendingPopupEventsByGuestId.clear()
this.pendingDownloadIdsByGuestId.clear()
this.annotationViewportBridgeOpsByTabId.clear()
}
getGuestWebContentsId(browserTabId: string): number | null {
@@ -956,6 +964,53 @@ export class BrowserManager {
}
}
async setAnnotationViewportBridge(
browserTabId: string,
options: BrowserAnnotationViewportBridgeOptions
): Promise<boolean> {
const prev = this.annotationViewportBridgeOpsByTabId.get(browserTabId) ?? Promise.resolve()
const next = prev
.catch(() => {})
.then(() => this.doSetAnnotationViewportBridgeImpl(browserTabId, options))
this.annotationViewportBridgeOpsByTabId.set(browserTabId, next)
try {
return await next
} finally {
if (this.annotationViewportBridgeOpsByTabId.get(browserTabId) === next) {
this.annotationViewportBridgeOpsByTabId.delete(browserTabId)
}
}
}
private async doSetAnnotationViewportBridgeImpl(
browserTabId: string,
options: BrowserAnnotationViewportBridgeOptions
): Promise<boolean> {
const webContentsId = this.webContentsIdByTabId.get(browserTabId)
if (!webContentsId) {
return false
}
const guest = webContents.fromId(webContentsId)
if (!guest || guest.isDestroyed()) {
this.webContentsIdByTabId.delete(browserTabId)
this.tabIdByWebContentsId.delete(webContentsId)
return false
}
try {
// Why: the scroll bridge runs outside the page world so page monkey
// patches cannot read the per-tab token or tamper with bridge state.
await guest.executeJavaScriptInIsolatedWorld(
BROWSER_ANNOTATION_VIEWPORT_BRIDGE_WORLD_ID,
[{ code: buildBrowserAnnotationViewportBridgeScript(options) }],
false
)
return true
} catch {
return false
}
}
private async doSetViewportOverrideImpl(
browserTabId: string,
override: BrowserViewportOverride | null
@@ -119,4 +119,22 @@ describe('buildGuestOverlayScript', () => {
// The catch block should return '' not the raw URL
expect(script).toContain("return '';")
})
it('arm script slices text nodes before normalizing bounded text', () => {
const script = buildGuestOverlayScript('arm')
expect(script).toContain("normalizeText((node.nodeValue || '').slice(0, remaining))")
expect(script).toContain('value = value.slice(start, end)')
expect(script).not.toContain('normalizeText(node.nodeValue ||')
expect(script).not.toContain("(el.textContent || '').trim()")
expect(script).not.toContain('ref.textContent')
})
it('arm script walks nearby siblings without materializing sibling arrays', () => {
const script = buildGuestOverlayScript('arm')
expect(script).toContain('previousElementSibling')
expect(script).toContain('nextElementSibling')
expect(script).not.toContain('Array.from(parent.children)')
})
})
+418 -34
View File
@@ -68,8 +68,18 @@ const ARM_SCRIPT = `(function() {
nearbyTextEntryMaxLength: 200,
nearbyTextMaxEntries: 10,
htmlSnippetMaxLength: 4096,
ancestorPathMaxEntries: 10
ancestorPathMaxEntries: 10,
nearbyElementsMaxEntries: 6,
nearbyElementMaxLength: 160,
selectorMaxLength: 700,
pathMaxLength: 900,
cssClassesMaxLength: 500,
selectedTextMaxLength: 500,
sourceFileMaxLength: 500,
reactComponentsMaxLength: 500
};
var TEXT_NODE_SCAN_LIMIT = 80;
var NEARBY_ELEMENT_SCAN_LIMIT = 80;
// --- Safe attribute names ---
var SAFE_ATTRS = new Set([
@@ -118,9 +128,96 @@ const ARM_SCRIPT = `(function() {
}
}
function normalizeText(text) {
return String(text || '').trim().replace(/\\s+/g, ' ');
}
function getBoundedText(el, max) {
try {
var walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
var chunks = [];
var length = 0;
var inspected = 0;
var node = walker.nextNode();
while (node && length < max + 20 && inspected < TEXT_NODE_SCAN_LIMIT) {
inspected++;
var separatorLength = chunks.length > 0 ? 1 : 0;
var remaining = max + 20 - length - separatorLength;
if (remaining <= 0) break;
var value = normalizeText((node.nodeValue || '').slice(0, remaining));
if (value) {
chunks.push(value.slice(0, remaining));
length += Math.min(value.length, remaining) + separatorLength;
}
node = walker.nextNode();
}
return clampStr(normalizeText(chunks.join(' ')), max);
} catch (e) {
return '';
}
}
function getTextSnippet(el) {
var text = (el.textContent || '').trim().replace(/\\s+/g, ' ');
return clampStr(text, BUDGET.textSnippetMaxLength);
return getBoundedText(el, BUDGET.textSnippetMaxLength);
}
function getSelectedText() {
try {
var selection = window.getSelection ? window.getSelection() : null;
if (!selection || selection.rangeCount === 0) return '';
var chunks = [];
var length = 0;
var inspected = 0;
for (var i = 0; i < selection.rangeCount && length < BUDGET.selectedTextMaxLength + 20; i++) {
var range = selection.getRangeAt(i);
var walkerRoot = range.commonAncestorContainer;
var walker = document.createTreeWalker(
walkerRoot,
NodeFilter.SHOW_TEXT,
{
acceptNode: function(node) {
if (range.intersectsNode && !range.intersectsNode(node)) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
}
}
);
var node = walkerRoot.nodeType === Node.TEXT_NODE ? walkerRoot : walker.nextNode();
while (
node &&
length < BUDGET.selectedTextMaxLength + 20 &&
inspected < TEXT_NODE_SCAN_LIMIT
) {
inspected++;
var textNode = node;
var value = textNode.nodeValue || '';
var separatorLength = chunks.length > 0 ? 1 : 0;
var remaining = BUDGET.selectedTextMaxLength + 20 - length - separatorLength;
if (remaining <= 0) break;
if (value) {
var start = textNode === range.startContainer ? range.startOffset : 0;
var end = textNode === range.endContainer ? range.endOffset : value.length;
if (end > start + remaining) {
end = start + remaining;
}
if (textNode === range.startContainer) {
start = Math.min(start, value.length);
}
value = value.slice(start, end);
value = normalizeText(value);
}
if (value) {
chunks.push(value.slice(0, remaining));
length += Math.min(value.length, remaining) + separatorLength;
}
node = walker.nextNode();
}
}
return clampStr(chunks.join(' '), BUDGET.selectedTextMaxLength);
} catch (e) {
return '';
}
}
function getHtmlSnippet(el) {
@@ -171,14 +268,14 @@ const ARM_SCRIPT = `(function() {
var names = [];
for (var i = 0; i < parts.length; i++) {
var ref = document.getElementById(parts[i]);
if (ref) names.push((ref.textContent || '').trim());
if (ref) names.push(getBoundedText(ref, 100));
}
if (names.length) accessibleName = names.join(' ');
} else {
// Fall back to text content for buttons/links
var tag = el.tagName.toLowerCase();
if (tag === 'button' || tag === 'a' || tag === 'label') {
accessibleName = clampStr((el.textContent || '').trim(), 100);
accessibleName = getBoundedText(el, 100);
} else if (el.getAttribute('title')) {
accessibleName = el.getAttribute('title');
} else if (el.getAttribute('alt')) {
@@ -204,47 +301,162 @@ const ARM_SCRIPT = `(function() {
return result;
}
function cssEscape(value) {
if (window.CSS && typeof window.CSS.escape === 'function') {
return window.CSS.escape(value);
}
return String(value).replace(/[^a-zA-Z0-9_-]/g, function(ch) {
return '\\\\' + ch;
});
}
function looksHashy(value) {
return /^[A-Za-z0-9_-]{12,}$/.test(value) && /\\d/.test(value) && /[A-Z]/.test(value);
}
function getStableClasses(el, maxCount) {
if (!el.classList) return [];
var result = [];
for (var i = 0; i < el.classList.length && result.length < maxCount; i++) {
var cls = el.classList[i];
if (!cls || cls.length > 60 || containsSecret(cls)) continue;
if (/^css-[a-z0-9]+$/i.test(cls) || looksHashy(cls)) continue;
result.push(cls);
}
return result;
}
function buildSelectorPart(el) {
var tag = el.tagName.toLowerCase();
var id = el.id;
if (id && !containsSecret(id)) {
return tag + '#' + cssEscape(id);
}
var classes = getStableClasses(el, 2);
if (classes.length > 0) {
return tag + classes.map(function(cls) { return '.' + cssEscape(cls); }).join('');
}
return tag;
}
function isUniqueSelector(selector) {
try {
return document.querySelectorAll(selector).length === 1;
} catch(e) {
return false;
}
}
function getNthOfTypeSuffix(current) {
var tag = current.tagName;
var index = 1;
var sibling = current.previousElementSibling;
while (sibling) {
if (sibling.tagName === tag) index++;
sibling = sibling.previousElementSibling;
}
if (index > 1) return ':nth-of-type(' + index + ')';
sibling = current.nextElementSibling;
while (sibling) {
if (sibling.tagName === tag) return ':nth-of-type(1)';
sibling = sibling.nextElementSibling;
}
return '';
}
function buildSelector(el) {
var parts = [];
var current = el;
while (current && current !== document.body && parts.length < 10) {
var tag = current.tagName.toLowerCase();
var id = current.id;
if (id) {
parts.unshift(tag + '#' + CSS.escape(id));
break;
}
while (current && current.nodeType === Node.ELEMENT_NODE && current !== document.body && parts.length < 10) {
var part = buildSelectorPart(current);
var parent = current.parentElement;
if (parent) {
var siblings = Array.from(parent.children).filter(
function(c) { return c.tagName === current.tagName; }
);
if (siblings.length > 1) {
var index = siblings.indexOf(current) + 1;
parts.unshift(tag + ':nth-of-type(' + index + ')');
} else {
parts.unshift(tag);
}
} else {
parts.unshift(tag);
if (parent && !isUniqueSelector(parts.concat([part]).reverse().join(' > '))) {
part += getNthOfTypeSuffix(current);
}
parts.unshift(part);
var selector = parts.join(' > ');
if (isUniqueSelector(selector)) {
return clampStr(selector, BUDGET.selectorMaxLength);
}
current = parent;
}
return parts.join(' > ') || el.tagName.toLowerCase();
return clampStr(parts.join(' > ') || el.tagName.toLowerCase(), BUDGET.selectorMaxLength);
}
function buildReadablePath(el) {
var parts = [];
var current = el;
while (current && current !== document.documentElement && parts.length < 6) {
var tag = current.tagName.toLowerCase();
if (tag === 'html' || tag === 'body') break;
var label = tag;
var aria = current.getAttribute('aria-label');
var role = current.getAttribute('role');
var stableClasses = getStableClasses(current, 1);
if (current.id && !containsSecret(current.id)) {
label = '#' + cssEscape(current.id);
} else if (aria && !containsSecret(aria)) {
label = tag + '[aria-label="' + clampStr(aria, 40).replace(/"/g, '\\\\"') + '"]';
} else if (role && !containsSecret(role)) {
label = tag + '[role="' + clampStr(role, 30).replace(/"/g, '\\\\"') + '"]';
} else if (stableClasses.length > 0) {
label = '.' + cssEscape(stableClasses[0]);
}
parts.unshift(label);
current = current.parentElement;
}
return clampStr(parts.join(' > '), BUDGET.pathMaxLength);
}
function buildFullPath(el) {
var parts = [];
var current = el;
while (current && current.nodeType === Node.ELEMENT_NODE && current !== document.documentElement && parts.length < 20) {
parts.unshift(buildSelectorPart(current));
current = current.parentElement;
}
return clampStr(parts.join(' > '), BUDGET.pathMaxLength);
}
function getNearbyText(el) {
var results = [];
var parent = el.parentElement;
if (!parent) return results;
var siblings = parent.children;
for (var i = 0; i < siblings.length && results.length < BUDGET.nearbyTextMaxEntries; i++) {
if (siblings[i] === el) continue;
var text = (siblings[i].textContent || '').trim().replace(/\\s+/g, ' ');
function addSiblingText(sibling) {
if (!sibling) return;
var text = getBoundedText(sibling, BUDGET.nearbyTextEntryMaxLength);
if (text) {
results.push(clampStr(text, BUDGET.nearbyTextEntryMaxLength));
}
}
var inspected = 0;
var previous = el.previousElementSibling;
var next = el.nextElementSibling;
while (
results.length < BUDGET.nearbyTextMaxEntries &&
inspected < NEARBY_ELEMENT_SCAN_LIMIT &&
(previous || next)
) {
if (previous) {
var previousSibling = previous;
previous = previous.previousElementSibling;
inspected++;
addSiblingText(previousSibling);
}
if (
next &&
results.length < BUDGET.nearbyTextMaxEntries &&
inspected < NEARBY_ELEMENT_SCAN_LIMIT
) {
var nextSibling = next;
next = next.nextElementSibling;
inspected++;
addSiblingText(nextSibling);
}
}
return results;
}
@@ -260,9 +472,149 @@ const ARM_SCRIPT = `(function() {
return path;
}
function getNearbyElements(el) {
var parent = el.parentElement;
if (!parent) return [];
var result = [];
function addSibling(sibling) {
if (!sibling) return;
if (sibling === el) return;
var rect = sibling.getBoundingClientRect();
if (rect.width === 0 && rect.height === 0) return;
var label = sibling.tagName.toLowerCase();
var stableClasses = getStableClasses(sibling, 1);
if (stableClasses.length > 0) label += '.' + stableClasses[0];
var text = getBoundedText(sibling, 50);
if (text) label += ' "' + clampStr(text, 50) + '"';
result.push(clampStr(label, BUDGET.nearbyElementMaxLength));
}
var inspected = 0;
var previous = el.previousElementSibling;
var next = el.nextElementSibling;
while (
result.length < BUDGET.nearbyElementsMaxEntries &&
inspected < NEARBY_ELEMENT_SCAN_LIMIT &&
(previous || next)
) {
if (previous) {
var previousSibling = previous;
previous = previous.previousElementSibling;
inspected++;
addSibling(previousSibling);
}
if (
next &&
result.length < BUDGET.nearbyElementsMaxEntries &&
inspected < NEARBY_ELEMENT_SCAN_LIMIT
) {
var nextSibling = next;
next = next.nextElementSibling;
inspected++;
addSibling(nextSibling);
}
}
return result;
}
function isElementFixed(el) {
var current = el;
while (current && current !== document.body) {
var position = window.getComputedStyle(current).position;
if (position === 'fixed' || position === 'sticky') return true;
current = current.parentElement;
}
return false;
}
function getFiberFromElement(el) {
var keys = Object.keys(el);
for (var i = 0; i < keys.length; i++) {
if (keys[i].indexOf('__reactFiber$') === 0 || keys[i].indexOf('__reactInternalInstance$') === 0) {
try {
return el[keys[i]] || null;
} catch (e) {
return null;
}
}
}
return null;
}
function getComponentNameFromFiber(fiber) {
if (!fiber) return null;
var type = fiber.type || fiber.elementType;
if (!type || typeof type === 'string') return null;
if (type.displayName || type.name) return type.displayName || type.name;
if (type.render && (type.render.displayName || type.render.name)) {
return type.render.displayName || type.render.name;
}
if (type.type && (type.type.displayName || type.type.name)) {
return type.type.displayName || type.type.name;
}
return null;
}
function shouldSkipReactName(name) {
if (!name || name.length <= 2) return true;
return /^(Fragment|Root|Routes|Route|Outlet|Provider|Consumer|Profiler|Suspense)$/.test(name) ||
/(?:Boundary|BoundaryHandler|Router|Provider|Consumer|Context|Wrapper)$/.test(name) ||
/^(Inner|Outer|Client|Server|RSC|Dev|React|Hot)/.test(name);
}
function cleanSourcePath(path) {
if (!path) return '';
return String(path)
.replace(/[?#].*$/, '')
.replace(/^turbopack:\\/\\/\\/\\[project\\]\\//, '')
.replace(/^webpack-internal:\\/\\/\\/\\.\\//, '')
.replace(/^webpack-internal:\\/\\/\\//, '')
.replace(/^webpack:\\/\\/\\/\\.\\//, '')
.replace(/^webpack:\\/\\/\\//, '')
.replace(/^turbopack:\\/\\/\\//, '')
.replace(/^https?:\\/\\/[^/]+\\//, '')
.replace(/^file:\\/\\/\\//, '/')
.replace(/^\\([^)]+\\)\\/\\.\\//, '')
.replace(/^\\.\\//, '');
}
function getReactMetadata(el) {
try {
var fiber = getFiberFromElement(el);
var components = [];
var sourceFile = null;
var depth = 0;
while (fiber && depth < 35) {
var name = getComponentNameFromFiber(fiber);
if (name && !shouldSkipReactName(name) && components.indexOf(name) === -1 && components.length < 6) {
components.push(name);
}
var source = fiber._debugSource || (fiber._debugOwner && fiber._debugOwner._debugSource);
if (!sourceFile && source && source.fileName && source.lineNumber) {
sourceFile = cleanSourcePath(source.fileName) + ':' + source.lineNumber +
(source.columnNumber !== undefined ? ':' + source.columnNumber : '');
if (containsSecret(sourceFile)) {
sourceFile = null;
}
}
fiber = fiber.return;
depth++;
}
return {
reactComponents: components.length > 0
? clampStr(components.slice().reverse().map(function(c) { return '<' + c + '>'; }).join(' '), BUDGET.reactComponentsMaxLength)
: null,
sourceFile: sourceFile ? clampStr(sourceFile, BUDGET.sourceFileMaxLength) : null
};
} catch (e) {
return { reactComponents: null, sourceFile: null };
}
}
// --- Build full payload for an element ---
function extractPayload(el) {
var rect = el.getBoundingClientRect();
var react = getReactMetadata(el);
return {
page: {
sanitizedUrl: sanitizeUrl(window.location.href),
@@ -277,6 +629,16 @@ const ARM_SCRIPT = `(function() {
target: {
tagName: el.tagName.toLowerCase(),
selector: buildSelector(el),
elementPath: buildReadablePath(el),
fullPath: buildFullPath(el),
cssClasses: containsSecret(el.getAttribute('class') || '')
? '[redacted]'
: clampStr(el.getAttribute('class') || '', BUDGET.cssClassesMaxLength),
nearbyElements: getNearbyElements(el),
selectedText: getSelectedText() || null,
isFixed: isElementFixed(el),
reactComponents: react.reactComponents,
sourceFile: react.sourceFile,
textSnippet: getTextSnippet(el),
htmlSnippet: getHtmlSnippet(el),
attributes: getSafeAttributes(el),
@@ -349,7 +711,7 @@ const ARM_SCRIPT = `(function() {
// Build label text
var tag = el.tagName.toLowerCase();
var role = el.getAttribute('role');
var text = (el.textContent || '').trim().replace(/\\s+/g, ' ');
var text = getBoundedText(el, 40);
if (text.length > 40) text = text.slice(0, 37) + '...';
var w = Math.round(rect.width);
var h = Math.round(rect.height);
@@ -420,6 +782,16 @@ const AWAIT_CLICK_SCRIPT = `new Promise(function(resolve, reject) {
return;
}
function extractSelectedPayload(el) {
try {
return grab.extractPayload(el);
} catch (error) {
grab.cleanup();
reject(error instanceof Error ? error : new Error('Failed to extract element context'));
return null;
}
}
function onClick(e) {
e.preventDefault();
e.stopPropagation();
@@ -432,7 +804,8 @@ const AWAIT_CLICK_SCRIPT = `new Promise(function(resolve, reject) {
reject(new Error('cancelled'));
return;
}
var payload = grab.extractPayload(el);
var payload = extractSelectedPayload(el);
if (!payload) return;
// Why: freeze the highlight instead of removing it so the user sees
// which element was selected while the copy menu is shown. Teardown
// happens later when the renderer calls setGrabMode(false) or re-arms.
@@ -456,7 +829,8 @@ const AWAIT_CLICK_SCRIPT = `new Promise(function(resolve, reject) {
reject(new Error('cancelled'));
return;
}
var payload = grab.extractPayload(el);
var payload = extractSelectedPayload(el);
if (!payload) return;
grab.freezeHighlight();
resolve({ __orcaContextMenu: true, payload: payload });
}
@@ -482,7 +856,13 @@ const FINALIZE_SCRIPT = `(function() {
if (!grab) return null;
var el = grab.getCurrentElement();
if (!el) return null;
var payload = grab.extractPayload(el);
var payload = null;
try {
payload = grab.extractPayload(el);
} catch (e) {
grab.cleanup();
return null;
}
grab.cleanup();
return payload;
})()`
@@ -499,7 +879,11 @@ const EXTRACT_HOVER_SCRIPT = `(function() {
if (!grab) return null;
var el = grab.getCurrentElement();
if (!el) return null;
return grab.extractPayload(el);
try {
return grab.extractPayload(el);
} catch (e) {
return null;
}
})()`
// ---------------------------------------------------------------------------
+68
View File
@@ -8,6 +8,7 @@ const {
getGuestWebContentsIdMock,
getWorktreeIdForTabMock,
openDevToolsMock,
setAnnotationViewportBridgeMock,
getDownloadPromptMock,
acceptDownloadMock,
cancelDownloadMock,
@@ -21,6 +22,7 @@ const {
getGuestWebContentsIdMock: vi.fn(),
getWorktreeIdForTabMock: vi.fn(),
openDevToolsMock: vi.fn().mockResolvedValue(true),
setAnnotationViewportBridgeMock: vi.fn().mockResolvedValue(true),
getDownloadPromptMock: vi.fn(),
acceptDownloadMock: vi.fn(),
cancelDownloadMock: vi.fn(),
@@ -48,6 +50,7 @@ vi.mock('../browser/browser-manager', () => ({
getGuestWebContentsId: getGuestWebContentsIdMock,
getWorktreeIdForTab: getWorktreeIdForTabMock,
openDevTools: openDevToolsMock,
setAnnotationViewportBridge: setAnnotationViewportBridgeMock,
getDownloadPrompt: getDownloadPromptMock,
acceptDownload: acceptDownloadMock,
cancelDownload: cancelDownloadMock
@@ -66,12 +69,14 @@ describe('registerBrowserHandlers', () => {
getGuestWebContentsIdMock.mockReset()
getWorktreeIdForTabMock.mockReset()
openDevToolsMock.mockReset()
setAnnotationViewportBridgeMock.mockReset()
getDownloadPromptMock.mockReset()
acceptDownloadMock.mockReset()
cancelDownloadMock.mockReset()
showSaveDialogMock.mockReset()
browserWindowFromWebContentsMock.mockReset()
openDevToolsMock.mockResolvedValue(true)
setAnnotationViewportBridgeMock.mockResolvedValue(true)
setAgentBrowserBridgeRef(null)
})
@@ -159,4 +164,67 @@ describe('registerBrowserHandlers', () => {
expect(result).toBe(true)
expect(onTabChangedMock).toHaveBeenCalledWith(4242, 'wt-browser')
})
it('validates annotation viewport bridge requests before syncing to the guest', async () => {
registerBrowserHandlers()
const syncHandler = handleMock.mock.calls.find(
([channel]) => channel === 'browser:setAnnotationViewportBridge'
)?.[1] as (event: { sender: Electron.WebContents }, args: unknown) => Promise<boolean> | boolean
const sender = {
id: 91,
isDestroyed: () => false,
getType: () => 'window',
getURL: () => 'file:///renderer/index.html'
} as Electron.WebContents
const result = await syncHandler(
{ sender },
{
browserPageId: 'page-1',
emitViewport: false,
enabled: true,
markers: [],
token: 'annotationviewporttoken'
}
)
expect(result).toBe(true)
expect(setAnnotationViewportBridgeMock).toHaveBeenCalledWith('page-1', {
emitViewport: false,
enabled: true,
markers: [],
token: 'annotationviewporttoken'
})
})
it('rejects invalid annotation viewport bridge requests', async () => {
registerBrowserHandlers()
const syncHandler = handleMock.mock.calls.find(
([channel]) => channel === 'browser:setAnnotationViewportBridge'
)?.[1] as (event: { sender: Electron.WebContents }, args: unknown) => boolean
const result = syncHandler(
{
sender: {
id: 91,
isDestroyed: () => false,
getType: () => 'window',
getURL: () => 'file:///renderer/index.html'
} as Electron.WebContents
},
{
browserPageId: 'page-1',
emitViewport: false,
enabled: true,
markers: [],
token: 'short'
}
)
expect(result).toBe(false)
expect(setAnnotationViewportBridgeMock).not.toHaveBeenCalled()
})
})
+30
View File
@@ -28,6 +28,11 @@ import type {
BrowserSessionProfileScope,
BrowserViewportOverride
} from '../../shared/types'
import {
isValidBrowserAnnotationViewportBridgeMarkers,
isValidBrowserAnnotationViewportBridgeToken,
type BrowserSetAnnotationViewportBridgeArgs
} from '../../shared/browser-annotation-viewport-bridge'
let trustedBrowserRendererWebContentsId: number | null = null
let agentBrowserBridgeRef: AgentBrowserBridge | null = null
@@ -86,6 +91,7 @@ export function registerBrowserHandlers(): void {
ipcMain.removeHandler('browser:unregisterGuest')
ipcMain.removeHandler('browser:openDevTools')
ipcMain.removeHandler('browser:setViewportOverride')
ipcMain.removeHandler('browser:setAnnotationViewportBridge')
ipcMain.removeHandler('browser:acceptDownload')
ipcMain.removeHandler('browser:cancelDownload')
ipcMain.removeHandler('browser:setGrabMode')
@@ -216,6 +222,30 @@ export function registerBrowserHandlers(): void {
}
)
ipcMain.handle(
'browser:setAnnotationViewportBridge',
(event, args: BrowserSetAnnotationViewportBridgeArgs): Promise<boolean> | boolean => {
if (!isTrustedBrowserRenderer(event.sender)) {
return false
}
if (
typeof args?.browserPageId !== 'string' ||
typeof args.enabled !== 'boolean' ||
typeof args.emitViewport !== 'boolean' ||
!isValidBrowserAnnotationViewportBridgeMarkers(args.markers) ||
!isValidBrowserAnnotationViewportBridgeToken(args.token)
) {
return false
}
return browserManager.setAnnotationViewportBridge(args.browserPageId, {
enabled: args.enabled,
emitViewport: args.emitViewport,
markers: args.markers,
token: args.token
})
}
)
ipcMain.handle('browser:acceptDownload', async (event, args: { downloadId: string }) => {
if (!isTrustedBrowserRenderer(event.sender)) {
return { ok: false, reason: 'not-authorized' as const }
+2
View File
@@ -145,6 +145,7 @@ import type {
BrowserPopupEvent
} from '../shared/browser-guest-events'
import type { ElectronAPI } from '@electron-toolkit/preload'
import type { BrowserSetAnnotationViewportBridgeArgs } from '../shared/browser-annotation-viewport-bridge'
import type { CliInstallStatus } from '../shared/cli-install-types'
import type { E2EConfig } from '../shared/e2e-config'
import type { AgentHookInstallStatus } from '../shared/agent-hook-types'
@@ -263,6 +264,7 @@ export type BrowserApi = {
browserPageId: string
override: BrowserViewportOverride | null
}) => Promise<boolean>
setAnnotationViewportBridge: (args: BrowserSetAnnotationViewportBridgeArgs) => Promise<boolean>
onGuestLoadFailed: (
callback: (args: { browserPageId: string; loadError: BrowserLoadError }) => void
) => () => void
+3
View File
@@ -1315,6 +1315,9 @@ const api = {
override: BrowserViewportOverride | null
}): Promise<boolean> => ipcRenderer.invoke('browser:setViewportOverride', args),
setAnnotationViewportBridge: (args): Promise<boolean> =>
ipcRenderer.invoke('browser:setAnnotationViewportBridge', args),
onGuestLoadFailed: (
callback: (args: {
browserPageId: string
File diff suppressed because it is too large Load Diff
@@ -23,6 +23,12 @@ export function formatGrabPayloadAsText(payload: BrowserGrabPayload): string {
lines.push(`Role: ${payload.target.accessibility.role}`)
}
lines.push(`Selector: ${payload.target.selector}`)
if (payload.target.sourceFile) {
lines.push(`Source: ${payload.target.sourceFile}`)
}
if (payload.target.reactComponents) {
lines.push(`React: ${payload.target.reactComponents}`)
}
const { rectViewport } = payload.target
lines.push(`Dimensions: ${Math.round(rectViewport.width)}x${Math.round(rectViewport.height)}`)
lines.push('')
@@ -80,6 +86,9 @@ export function formatGrabPayloadAsText(payload: BrowserGrabPayload): string {
if (payload.ancestorPath.length > 0) {
lines.push(`Ancestor path: ${payload.ancestorPath.join(' > ')}`)
}
if (payload.target.fullPath) {
lines.push(`Full DOM path: ${payload.target.fullPath}`)
}
return lines.join('\n').trimEnd()
}
@@ -0,0 +1,138 @@
import { describe, expect, it } from 'vitest'
import type { BrowserPageAnnotation } from '../../../../shared/browser-grab-types'
import { formatBrowserAnnotationsAsMarkdown } from './browser-annotation-output'
function makeAnnotation(overrides?: Partial<BrowserPageAnnotation>): BrowserPageAnnotation {
return {
id: 'annotation-1',
browserPageId: 'page-1',
comment: 'Make this primary action more obvious.',
intent: 'change',
priority: 'important',
createdAt: '2026-05-15T00:00:00.000Z',
payload: {
page: {
sanitizedUrl: 'https://example.com/pricing',
title: 'Pricing - Example',
viewportWidth: 1280,
viewportHeight: 720,
scrollX: 0,
scrollY: 0,
devicePixelRatio: 2,
capturedAt: '2026-05-15T00:00:00.000Z'
},
target: {
tagName: 'button',
selector: 'main.pricing > button.primary',
elementPath: 'main > .pricing > button',
fullPath: 'html > body > main.pricing > button.primary',
cssClasses: 'primary',
nearbyElements: ['span "$29/month"'],
selectedText: null,
isFixed: false,
reactComponents: '<App> <PricingCta>',
sourceFile: 'src/components/PricingCta.tsx:42:8',
textSnippet: 'Start free trial',
htmlSnippet: '<button class="primary">Start free trial</button>',
attributes: { class: 'primary', type: 'button' },
accessibility: {
role: 'button',
accessibleName: 'Start free trial',
ariaLabel: null,
ariaLabelledBy: null
},
rectViewport: { x: 400, y: 300, width: 148, height: 44 },
rectPage: { x: 400, y: 300, width: 148, height: 44 },
computedStyles: {
display: 'inline-flex',
position: 'relative',
width: '148px',
height: '44px',
margin: '0px',
padding: '12px 24px',
color: 'rgb(255, 255, 255)',
backgroundColor: 'rgb(99, 102, 241)',
border: '0px none',
borderRadius: '8px',
fontFamily: 'Geist, sans-serif',
fontSize: '16px',
fontWeight: '600',
lineHeight: '20px',
textAlign: 'center',
zIndex: 'auto'
}
},
nearbyText: ['Pro', '$29/month'],
ancestorPath: ['section', 'main', 'body'],
screenshot: null
},
...overrides
}
}
describe('formatBrowserAnnotationsAsMarkdown', () => {
it('includes agent-useful selectors, source, react tree, styles, and feedback', () => {
const markdown = formatBrowserAnnotationsAsMarkdown([makeAnnotation()])
expect(markdown).toContain('## Design Feedback: /pricing')
expect(markdown).toContain('**Browser tab id:** page-1')
expect(markdown).toContain('**Orca CLI:** Use `--page page-1` to target this browser tab.')
expect(markdown).not.toContain('Page Feedback')
expect(markdown).toContain('**Selector:** `main.pricing > button.primary`')
expect(markdown).toContain('**Source:** src/components/PricingCta.tsx:42:8')
expect(markdown).toContain('**React:** <App> <PricingCta>')
expect(markdown).toContain('**Intent:** change')
expect(markdown).toContain('**Priority:** important')
expect(markdown).toContain('- font-size: 16px')
expect(markdown).toContain('**Feedback:** Make this primary action more obvious.')
})
it('returns an empty string when no annotations exist', () => {
expect(formatBrowserAnnotationsAsMarkdown([])).toBe('')
})
it('uses longer inline code fences when selector content contains backticks', () => {
const annotation = makeAnnotation()
const markdown = formatBrowserAnnotationsAsMarkdown([
makeAnnotation({
payload: {
...annotation.payload,
target: {
...annotation.payload.target,
selector: 'button[data-label="Save `draft`"]',
cssClasses: 'primary `generated`'
}
}
})
])
expect(markdown).toContain('**Selector:** ``button[data-label="Save `draft`"]``')
expect(markdown).toContain('**Classes:** `` primary `generated` ``')
})
it('collapses page-controlled newlines before putting text in headings and lists', () => {
const annotation = makeAnnotation()
const markdown = formatBrowserAnnotationsAsMarkdown([
makeAnnotation({
comment: 'Keep this change scoped.\n## injected',
payload: {
...annotation.payload,
target: {
...annotation.payload.target,
accessibility: {
...annotation.payload.target.accessibility,
accessibleName: 'Start\n## injected heading'
},
textSnippet: 'Start\n## injected text'
},
nearbyText: ['Plan\n# injected']
}
})
])
expect(markdown).toContain('### 1. <App> <PricingCta> button "Start ## injected heading"')
expect(markdown).toContain('- Plan # injected')
expect(markdown).toContain('**Feedback:** Keep this change scoped. ## injected')
expect(markdown).not.toContain('\n## injected')
})
})
@@ -0,0 +1,157 @@
import type {
BrowserGrabComputedStyles,
BrowserGrabPayload,
BrowserPageAnnotation
} from '../../../../shared/browser-grab-types'
function formatPageHeading(payload: BrowserGrabPayload): string {
try {
const url = new URL(payload.page.sanitizedUrl)
return `${url.pathname}${url.search}`
} catch {
return payload.page.sanitizedUrl || 'current page'
}
}
function annotationElementLabel(payload: BrowserGrabPayload): string {
const react = payload.target.reactComponents
const accessibleName = payload.target.accessibility.accessibleName
const base = accessibleName
? `${payload.target.tagName} "${inlineText(accessibleName)}"`
: payload.target.textSnippet
? `${payload.target.tagName} "${inlineText(payload.target.textSnippet).slice(0, 60)}"`
: payload.target.tagName
return react ? `${inlineText(react)} ${base}` : base
}
function inlineText(content: string): string {
return content.replace(/\s+/g, ' ').trim()
}
function formatStyles(styles: BrowserGrabComputedStyles): string[] {
const lines: string[] = []
const entries: [string, string][] = [
['display', styles.display],
['position', styles.position],
['width', styles.width],
['height', styles.height],
['margin', styles.margin],
['padding', styles.padding],
['color', styles.color],
['background', styles.backgroundColor],
['border', styles.border],
['border-radius', styles.borderRadius],
['font-family', styles.fontFamily],
['font-size', styles.fontSize],
['font-weight', styles.fontWeight],
['line-height', styles.lineHeight],
['text-align', styles.textAlign],
['z-index', styles.zIndex]
]
for (const [name, value] of entries) {
if (!value || value === 'auto' || value === 'normal') {
continue
}
if (name === 'position' && value === 'static') {
continue
}
if (name === 'display' && value === 'inline') {
continue
}
if (name === 'background' && value === 'rgba(0, 0, 0, 0)') {
continue
}
lines.push(`- ${name}: ${value}`)
}
return lines
}
function fence(language: string, content: string): string[] {
const maxRun = Math.max(3, ...Array.from(content.matchAll(/`+/g), (match) => match[0].length))
const marker = '`'.repeat(maxRun + 1)
return [`${marker}${language}`, content, marker]
}
function inlineCode(content: string): string {
const maxRun = Math.max(0, ...Array.from(content.matchAll(/`+/g), (match) => match[0].length))
const marker = '`'.repeat(maxRun + 1)
const padding = content.startsWith('`') || content.endsWith('`') ? ' ' : ''
return `${marker}${padding}${content}${padding}${marker}`
}
export function formatBrowserAnnotationsAsMarkdown(annotations: BrowserPageAnnotation[]): string {
if (annotations.length === 0) {
return ''
}
const firstAnnotation = annotations[0]
const first = firstAnnotation.payload
const lines: string[] = [
`## Design Feedback: ${formatPageHeading(first)}`,
'',
`**URL:** ${first.page.sanitizedUrl}`,
`**Browser tab id:** ${firstAnnotation.browserPageId}`,
`**Orca CLI:** Use ${inlineCode(`--page ${firstAnnotation.browserPageId}`)} to target this browser tab.`,
`**Viewport:** ${first.page.viewportWidth}x${first.page.viewportHeight}`,
''
]
annotations.forEach((annotation, index) => {
const { payload } = annotation
const { target } = payload
const rect = target.rectViewport
const styleLines = formatStyles(target.computedStyles)
lines.push(`### ${index + 1}. ${annotationElementLabel(payload)}`)
lines.push(`**Intent:** ${annotation.intent}`)
lines.push(`**Priority:** ${annotation.priority}`)
lines.push(`**Selector:** ${inlineCode(target.selector)}`)
if (target.elementPath) {
lines.push(`**Location:** ${inlineCode(target.elementPath)}`)
}
if (target.sourceFile) {
lines.push(`**Source:** ${inlineText(target.sourceFile)}`)
}
if (target.reactComponents) {
lines.push(`**React:** ${inlineText(target.reactComponents)}`)
}
lines.push(
`**Bounds:** x=${Math.round(rect.x)}, y=${Math.round(rect.y)}, ${Math.round(rect.width)}x${Math.round(rect.height)}`
)
if (target.cssClasses) {
lines.push(`**Classes:** ${inlineCode(target.cssClasses)}`)
}
if (target.selectedText) {
lines.push(`**Selected text:** "${inlineText(target.selectedText)}"`)
} else if (target.textSnippet) {
lines.push(`**Text:** "${inlineText(target.textSnippet)}"`)
}
if (payload.nearbyText.length > 0) {
lines.push('**Nearby text:**')
for (const text of payload.nearbyText) {
lines.push(`- ${inlineText(text)}`)
}
}
if (target.nearbyElements?.length) {
lines.push('**Nearby elements:**')
for (const element of target.nearbyElements) {
lines.push(`- ${inlineText(element)}`)
}
}
if (styleLines.length > 0) {
lines.push('**Computed styles:**')
lines.push(...styleLines)
}
if (target.fullPath) {
lines.push(`**Full DOM path:** ${inlineCode(target.fullPath)}`)
}
if (target.htmlSnippet) {
lines.push('**HTML:**')
lines.push(...fence('html', target.htmlSnippet))
}
lines.push(`**Feedback:** ${inlineText(annotation.comment)}`)
lines.push('')
})
return lines.join('\n').trimEnd()
}
@@ -3,6 +3,7 @@ import type {
BrowserGrabPayload,
BrowserGrabScreenshot
} from '../../../../shared/browser-grab-types'
import { isEditableKeyboardTarget } from './browser-keyboard'
// ---------------------------------------------------------------------------
// Grab mode state machine
@@ -193,6 +194,16 @@ export function useGrabMode(browserPageId: string): GrabModeHook {
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent): void => {
if (e.key === 'Escape' && state !== 'idle') {
const element =
e.target && typeof e.target === 'object' && 'closest' in e.target
? (e.target as { closest: (selector: string) => unknown })
: null
if (
isEditableKeyboardTarget(e.target) ||
element?.closest('[data-slot="select-trigger"], [data-slot="select-content"]')
) {
return
}
e.preventDefault()
e.stopPropagation()
cancel()
+5 -2
View File
@@ -21,10 +21,13 @@ function PopoverContent({
className,
align = 'center',
sideOffset = 4,
portalContainer,
style,
onWheel,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
}: React.ComponentProps<typeof PopoverPrimitive.Content> & {
portalContainer?: HTMLElement | null
}) {
const handleWheel = React.useCallback(
(event: React.WheelEvent<HTMLDivElement>) => {
onWheel?.(event)
@@ -63,7 +66,7 @@ function PopoverContent({
)
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Portal container={portalContainer ?? undefined}>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
+5 -2
View File
@@ -49,10 +49,13 @@ function SelectContent({
children,
position = 'item-aligned',
align = 'center',
portalContainer,
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
}: React.ComponentProps<typeof SelectPrimitive.Content> & {
portalContainer?: HTMLElement | null
}) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Portal container={portalContainer ?? undefined}>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
@@ -7,6 +7,7 @@ import {
createCompatibleRuntimeStatusResponseIfNeeded,
type RuntimeEnvironmentCallRequest
} from '../../runtime/runtime-compatibility-test-fixture'
import { GRAB_BUDGET, type BrowserPageAnnotation } from '../../../../shared/browser-grab-types'
import { clearRuntimeCompatibilityCacheForTests } from '../../runtime/runtime-rpc-client'
const runtimeEnvironmentCall = vi.fn()
@@ -56,6 +57,129 @@ function settingsWithRuntime(id: string): AppState['settings'] {
return { activeRuntimeEnvironmentId: id } as AppState['settings']
}
function makeAnnotation(pageId: string, id = 'annotation-1'): BrowserPageAnnotation {
return {
id,
browserPageId: pageId,
comment: 'Fix this button',
intent: 'fix',
priority: 'important',
createdAt: '2026-05-15T00:00:00.000Z',
payload: {
page: {
sanitizedUrl: 'https://example.com',
title: 'Example',
viewportWidth: 1280,
viewportHeight: 720,
scrollX: 0,
scrollY: 0,
devicePixelRatio: 1,
capturedAt: '2026-05-15T00:00:00.000Z'
},
target: {
tagName: 'button',
selector: 'button',
textSnippet: 'Submit',
htmlSnippet: '<button>Submit</button>',
attributes: {},
accessibility: {
role: 'button',
accessibleName: 'Submit',
ariaLabel: null,
ariaLabelledBy: null
},
rectViewport: { x: 0, y: 0, width: 100, height: 40 },
rectPage: { x: 0, y: 0, width: 100, height: 40 },
computedStyles: {
display: 'inline-flex',
position: 'static',
width: '100px',
height: '40px',
margin: '0px',
padding: '0px',
color: 'rgb(0, 0, 0)',
backgroundColor: 'rgba(0, 0, 0, 0)',
border: '0px none',
borderRadius: '0px',
fontFamily: 'Geist',
fontSize: '14px',
fontWeight: '400',
lineHeight: '20px',
textAlign: 'center',
zIndex: 'auto'
}
},
nearbyText: [],
ancestorPath: [],
screenshot: null
}
}
}
describe('createBrowserSlice annotations', () => {
it('clears page annotations when the browser page URL changes', () => {
const store = createTestStore()
const tab = store.getState().createBrowserTab('wt-1', 'https://example.com')
const pageId = tab.activePageId
if (!pageId) {
throw new Error('Expected a new browser page')
}
store.getState().addBrowserPageAnnotation(makeAnnotation(pageId))
expect(store.getState().browserAnnotationsByPageId[pageId]).toHaveLength(1)
store.getState().setBrowserPageUrl(pageId, 'https://example.com/next')
expect(store.getState().browserAnnotationsByPageId[pageId]).toBeUndefined()
})
it('caps stored browser annotations per page', () => {
const store = createTestStore()
const tab = store.getState().createBrowserTab('wt-1', 'https://example.com')
const pageId = tab.activePageId
if (!pageId) {
throw new Error('Expected a new browser page')
}
for (let index = 0; index < GRAB_BUDGET.annotationsMaxPerPage + 3; index++) {
store.getState().addBrowserPageAnnotation(makeAnnotation(pageId, `annotation-${index}`))
}
const annotations = store.getState().browserAnnotationsByPageId[pageId] ?? []
expect(annotations).toHaveLength(GRAB_BUDGET.annotationsMaxPerPage)
expect(annotations[0]?.id).toBe('annotation-3')
})
it('sanitizes persistent annotation payloads at the store boundary', () => {
const store = createTestStore()
const tab = store.getState().createBrowserTab('wt-1', 'https://example.com')
const pageId = tab.activePageId
if (!pageId) {
throw new Error('Expected a new browser page')
}
const annotation = makeAnnotation(pageId)
const oversizedComment = 'a'.repeat(GRAB_BUDGET.annotationCommentMaxLength + 10)
store.getState().addBrowserPageAnnotation({
...annotation,
comment: oversizedComment,
payload: {
...annotation.payload,
screenshot: {
mimeType: 'image/png',
dataUrl: 'data:image/png;base64,abc',
width: 1,
height: 1
}
} as unknown as BrowserPageAnnotation['payload']
})
const stored = store.getState().browserAnnotationsByPageId[pageId]?.[0]
expect(stored?.comment).toHaveLength(GRAB_BUDGET.annotationCommentMaxLength)
expect(stored?.payload.screenshot).toBeNull()
})
})
describe('createBrowserSlice runtime guard', () => {
beforeEach(() => {
vi.clearAllMocks()
+89 -5
View File
@@ -12,6 +12,7 @@ import type {
BrowserWorkspace,
WorkspaceSessionState
} from '../../../../shared/types'
import { GRAB_BUDGET, type BrowserPageAnnotation } from '../../../../shared/browser-grab-types'
import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/constants'
import { redactKagiSessionToken } from '../../../../shared/browser-url'
import {
@@ -71,6 +72,22 @@ type ClosedBrowserWorkspaceSnapshot = {
pages: BrowserPage[]
}
function sanitizeBrowserPageAnnotation(annotation: BrowserPageAnnotation): BrowserPageAnnotation {
return {
...annotation,
comment:
annotation.comment.length > GRAB_BUDGET.annotationCommentMaxLength
? annotation.comment.slice(0, GRAB_BUDGET.annotationCommentMaxLength)
: annotation.comment,
payload: {
...annotation.payload,
// Why: annotations live in persisted renderer state; screenshots are
// transient copy payloads and can retain megabytes per note.
screenshot: null
}
}
}
export type RemoteBrowserPageHandle = {
environmentId: string
remotePageId: string
@@ -79,6 +96,7 @@ export type RemoteBrowserPageHandle = {
export type BrowserSlice = {
browserTabsByWorktree: Record<string, BrowserWorkspace[]>
browserPagesByWorkspace: Record<string, BrowserPage[]>
browserAnnotationsByPageId: Record<string, BrowserPageAnnotation[]>
remoteBrowserPageHandlesByPageId: Record<string, RemoteBrowserPageHandle>
activeBrowserTabId: string | null
activeBrowserTabIdByWorktree: Record<string, string | null>
@@ -130,6 +148,9 @@ export type BrowserSlice = {
pageId: string,
viewportPresetId: BrowserViewportPresetId | null
) => void
addBrowserPageAnnotation: (annotation: BrowserPageAnnotation) => void
deleteBrowserPageAnnotation: (pageId: string, annotationId: string) => void
clearBrowserPageAnnotations: (pageId: string) => void
hydrateBrowserSession: (session: WorkspaceSessionState) => void
switchBrowserTabProfile: (workspaceId: string, profileId: string | null) => void
browserSessionProfiles: BrowserSessionProfile[]
@@ -339,6 +360,7 @@ function findPage(
export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> = (set, get) => ({
browserTabsByWorktree: {},
browserPagesByWorkspace: {},
browserAnnotationsByPageId: {},
remoteBrowserPageHandlesByPageId: {},
activeBrowserTabId: null,
activeBrowserTabIdByWorktree: {},
@@ -480,6 +502,10 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
const closedPages = s.browserPagesByWorkspace[tabId] ?? []
const nextBrowserPagesByWorkspace = { ...s.browserPagesByWorkspace }
delete nextBrowserPagesByWorkspace[tabId]
const nextBrowserAnnotationsByPageId = { ...s.browserAnnotationsByPageId }
for (const page of closedPages) {
delete nextBrowserAnnotationsByPageId[page.id]
}
remotePagesToClose = closedPages.flatMap((page) => {
const handle = s.remoteBrowserPageHandlesByPageId[page.id]
return handle ? [{ worktreeId: page.worktreeId, handle }] : []
@@ -561,7 +587,8 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
activeTabTypeByWorktree: nextActiveTabTypeByWorktree,
recentlyClosedBrowserTabsByWorktree: nextRecentlyClosedBrowserTabsByWorktree,
recentlyClosedBrowserPagesByWorkspace: nextRecentlyClosedBrowserPagesByWorkspace,
remoteBrowserPageHandlesByPageId: nextRemoteBrowserPageHandlesByPageId
remoteBrowserPageHandlesByPageId: nextRemoteBrowserPageHandlesByPageId,
browserAnnotationsByPageId: nextBrowserAnnotationsByPageId
}
})
@@ -822,6 +849,8 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
...s.remoteBrowserPageHandlesByPageId
}
delete nextRemoteBrowserPageHandlesByPageId[pageId]
const nextBrowserAnnotationsByPageId = { ...s.browserAnnotationsByPageId }
delete nextBrowserAnnotationsByPageId[pageId]
return {
browserPagesByWorkspace: {
@@ -853,7 +882,8 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
([pendingPageId]) => pendingPageId !== pageId
)
),
remoteBrowserPageHandlesByPageId: nextRemoteBrowserPageHandlesByPageId
remoteBrowserPageHandlesByPageId: nextRemoteBrowserPageHandlesByPageId,
browserAnnotationsByPageId: nextBrowserAnnotationsByPageId
}
})
@@ -1119,18 +1149,28 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
if (!workspace) {
return s
}
const nextUrl = normalizeUrl(url)
// Why: annotations point at DOM coordinates from one loaded document.
// A real URL change invalidates those markers and copied context.
const shouldClearAnnotations = normalizeUrl(page.url) !== nextUrl
const nextPages = (s.browserPagesByWorkspace[workspace.id] ?? []).map((entry) =>
entry.id === pageId
? {
...entry,
url: normalizeUrl(url),
title: normalizeBrowserTitle(entry.title, normalizeUrl(url)),
url: nextUrl,
title: normalizeBrowserTitle(entry.title, nextUrl),
loading: true,
loadError: null
}
: entry
)
const nextWorkspace = mirrorWorkspaceFromActivePage(workspace, nextPages)
const nextBrowserAnnotationsByPageId = shouldClearAnnotations
? { ...s.browserAnnotationsByPageId }
: s.browserAnnotationsByPageId
if (shouldClearAnnotations) {
delete nextBrowserAnnotationsByPageId[pageId]
}
return {
browserPagesByWorkspace: {
...s.browserPagesByWorkspace,
@@ -1141,7 +1181,10 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
[workspace.worktreeId]: (s.browserTabsByWorktree[workspace.worktreeId] ?? []).map((tab) =>
tab.id === workspace.id ? nextWorkspace : tab
)
}
},
...(shouldClearAnnotations
? { browserAnnotationsByPageId: nextBrowserAnnotationsByPageId }
: {})
}
}),
@@ -1196,6 +1239,46 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
}
}),
addBrowserPageAnnotation: (annotation) =>
set((s) => {
const existing = s.browserAnnotationsByPageId[annotation.browserPageId] ?? []
const next = [...existing, sanitizeBrowserPageAnnotation(annotation)].slice(
-GRAB_BUDGET.annotationsMaxPerPage
)
return {
browserAnnotationsByPageId: {
...s.browserAnnotationsByPageId,
[annotation.browserPageId]: next
}
}
}),
deleteBrowserPageAnnotation: (pageId, annotationId) =>
set((s) => {
const existing = s.browserAnnotationsByPageId[pageId] ?? []
const next = existing.filter((annotation) => annotation.id !== annotationId)
if (next.length === existing.length) {
return s
}
const nextByPageId = { ...s.browserAnnotationsByPageId }
if (next.length > 0) {
nextByPageId[pageId] = next
} else {
delete nextByPageId[pageId]
}
return { browserAnnotationsByPageId: nextByPageId }
}),
clearBrowserPageAnnotations: (pageId) =>
set((s) => {
if (!s.browserAnnotationsByPageId[pageId]?.length) {
return s
}
const nextByPageId = { ...s.browserAnnotationsByPageId }
delete nextByPageId[pageId]
return { browserAnnotationsByPageId: nextByPageId }
}),
hydrateBrowserSession: (session) => {
const persistedTabsByWorktree = session.browserTabsByWorktree ?? {}
const currentState = get()
@@ -1356,6 +1439,7 @@ export const createBrowserSlice: StateCreator<AppState, [], [], BrowserSlice> =
activeTabTypeByWorktree: nextActiveTabTypeByWorktree,
activeTabType,
remoteBrowserPageHandlesByPageId: {},
browserAnnotationsByPageId: {},
browserUrlHistory: normalizeBrowserHistoryEntries(session.browserUrlHistory ?? [])
}
})
@@ -85,6 +85,7 @@ function runtimeScopedStateReset(): Partial<AppState> {
recentlyClosedEditorTabsByWorktree: {},
browserTabsByWorktree: {},
browserPagesByWorkspace: {},
browserAnnotationsByPageId: {},
remoteBrowserPageHandlesByPageId: {},
activeBrowserTabId: null,
activeBrowserTabIdByWorktree: {},
+1
View File
@@ -550,6 +550,7 @@ function createBrowserApi(): NonNullable<Partial<PreloadApi>['browser']> {
unregisterGuest: () => Promise.resolve(),
openDevTools: () => Promise.resolve(false),
setViewportOverride: () => Promise.resolve(false),
setAnnotationViewportBridge: () => Promise.resolve(false),
onGuestLoadFailed: () => noopUnsubscribe,
onPermissionDenied: () => noopUnsubscribe,
onPopup: () => noopUnsubscribe,
@@ -0,0 +1,257 @@
import type { BrowserGrabRect } from './browser-grab-types'
export type BrowserAnnotationViewportBridgeMarker = {
id: string
index: number
rectPage: BrowserGrabRect
rectViewport: BrowserGrabRect
isFixed: boolean
}
export type BrowserSetAnnotationViewportBridgeArgs = {
browserPageId: string
enabled: boolean
emitViewport: boolean
markers: BrowserAnnotationViewportBridgeMarker[]
token: string
}
export type BrowserAnnotationViewportBridgeOptions = {
enabled: boolean
emitViewport: boolean
markers: BrowserAnnotationViewportBridgeMarker[]
token: string
}
export const BROWSER_ANNOTATION_VIEWPORT_BRIDGE_WORLD_ID = 1207
export const BROWSER_ANNOTATION_VIEWPORT_MESSAGE_PREFIX = '__orca_annotation_viewport__:'
export function isValidBrowserAnnotationViewportBridgeToken(value: unknown): value is string {
return typeof value === 'string' && /^[a-zA-Z0-9_-]{16,80}$/.test(value)
}
function isValidBrowserGrabRect(value: unknown): value is BrowserGrabRect {
if (!value || typeof value !== 'object') {
return false
}
const rect = value as Record<string, unknown>
return (
typeof rect.x === 'number' &&
Number.isFinite(rect.x) &&
typeof rect.y === 'number' &&
Number.isFinite(rect.y) &&
typeof rect.width === 'number' &&
Number.isFinite(rect.width) &&
rect.width >= 0 &&
typeof rect.height === 'number' &&
Number.isFinite(rect.height) &&
rect.height >= 0
)
}
export function isValidBrowserAnnotationViewportBridgeMarkers(
value: unknown
): value is BrowserAnnotationViewportBridgeMarker[] {
return (
Array.isArray(value) &&
value.length <= 50 &&
value.every((marker) => {
if (!marker || typeof marker !== 'object') {
return false
}
const candidate = marker as Record<string, unknown>
return (
typeof candidate.id === 'string' &&
candidate.id.length > 0 &&
candidate.id.length <= 100 &&
Number.isInteger(candidate.index) &&
(candidate.index as number) >= 0 &&
(candidate.index as number) < 100 &&
typeof candidate.isFixed === 'boolean' &&
isValidBrowserGrabRect(candidate.rectPage) &&
isValidBrowserGrabRect(candidate.rectViewport)
)
})
)
}
// Why: persisted badges need to follow guest scroll without a React roundtrip;
// the bridge mirrors only numeric marker geometry into a closed shadow overlay.
export function buildBrowserAnnotationViewportBridgeScript({
emitViewport,
enabled,
markers,
token
}: BrowserAnnotationViewportBridgeOptions): string {
return `(() => {
'use strict';
const enabled = ${JSON.stringify(enabled)};
const emitViewportMessages = ${JSON.stringify(emitViewport)};
const markers = ${JSON.stringify(markers)};
const token = ${JSON.stringify(token)};
const prefix = ${JSON.stringify(BROWSER_ANNOTATION_VIEWPORT_MESSAGE_PREFIX)};
const stateKey = '__orcaBrowserAnnotationViewportBridge';
const hostAttribute = 'data-orca-browser-annotation-overlay';
const markerSize = 24;
const removeOverlay = (state) => {
if (state && state.host && state.host.parentNode) {
state.host.parentNode.removeChild(state.host);
}
};
const cleanup = (state) => {
if (!state) return;
if (state.raf) {
cancelAnimationFrame(state.raf);
}
if (state.requestUpdate) {
window.removeEventListener('scroll', state.requestUpdate, true);
document.removeEventListener('scroll', state.requestUpdate, true);
window.removeEventListener('resize', state.requestUpdate, true);
}
removeOverlay(state);
};
const existing = globalThis[stateKey];
if (!enabled) {
cleanup(existing);
delete globalThis[stateKey];
return true;
}
const toNumber = (value, fallback) =>
typeof value === 'number' && Number.isFinite(value) ? value : fallback;
const readViewport = () => ({
scrollX: toNumber(window.scrollX, toNumber(window.pageXOffset, 0)),
scrollY: toNumber(window.scrollY, toNumber(window.pageYOffset, 0))
});
const emitViewport = () => {
if (!emitViewportMessages) return;
try {
console.debug(prefix + token + ':' + JSON.stringify(readViewport()));
} catch (e) {}
};
const getRoot = () => document.body || document.documentElement;
const ensureOverlay = (state) => {
if (state.host && state.shadowRoot) {
return state.shadowRoot;
}
const root = getRoot();
if (!root) return null;
const host = document.createElement('div');
host.setAttribute(hostAttribute, '');
host.style.cssText = 'position:fixed;inset:0;z-index:2147483646;pointer-events:none;contain:layout style paint;overflow:hidden;';
const shadowRoot = host.attachShadow({ mode: 'closed' });
const style = document.createElement('style');
style.textContent = '.marker{box-sizing:border-box;position:absolute;left:0;top:0;width:24px;height:24px;display:flex;align-items:center;justify-content:center;border-radius:9999px;border:1px solid rgba(255,255,255,0.95);background:#2563eb;color:#fff;font:600 11px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;box-shadow:0 10px 24px rgba(0,0,0,.18);will-change:transform;pointer-events:none;user-select:none;}';
shadowRoot.appendChild(style);
root.appendChild(host);
state.host = host;
state.shadowRoot = shadowRoot;
return shadowRoot;
};
const updateMarkers = (state, nextMarkers) => {
state.markers = Array.isArray(nextMarkers) ? nextMarkers : [];
if (state.markers.length === 0) {
removeOverlay(state);
state.host = null;
state.shadowRoot = null;
state.markerElements = new Map();
return;
}
const shadowRoot = ensureOverlay(state);
if (!shadowRoot) return;
const liveIds = new Set();
state.markers.forEach((marker) => {
liveIds.add(marker.id);
let element = state.markerElements.get(marker.id);
if (!element) {
element = document.createElement('span');
element.className = 'marker';
shadowRoot.appendChild(element);
state.markerElements.set(marker.id, element);
}
element.textContent = String(marker.index + 1);
});
state.markerElements.forEach((element, id) => {
if (!liveIds.has(id)) {
element.remove();
state.markerElements.delete(id);
}
});
};
const positionMarkers = (state) => {
if (!state.markers || state.markers.length === 0) return;
const viewport = readViewport();
const viewportWidth = toNumber(window.innerWidth, 0);
const viewportHeight = toNumber(window.innerHeight, 0);
state.markers.forEach((marker) => {
const element = state.markerElements.get(marker.id);
if (!element) return;
const sourceRect = marker.isFixed ? marker.rectViewport : marker.rectPage;
const x = marker.isFixed ? sourceRect.x : sourceRect.x - viewport.scrollX;
const y = marker.isFixed ? sourceRect.y : sourceRect.y - viewport.scrollY;
const width = toNumber(sourceRect.width, 0);
const height = toNumber(sourceRect.height, 0);
const visible =
x + width >= 0 &&
y + height >= 0 &&
x <= viewportWidth &&
y <= viewportHeight;
if (!visible) {
element.style.display = 'none';
return;
}
element.style.display = 'flex';
element.style.transform =
'translate3d(' +
(x + width / 2 - markerSize / 2) +
'px,' +
(y + height - markerSize / 2) +
'px,0)';
});
};
if (existing && existing.requestUpdate) {
existing.emitViewport = emitViewport;
updateMarkers(existing, markers);
existing.requestUpdate();
return true;
}
const state = {
raf: 0,
emitViewport,
host: null,
markerElements: new Map(),
markers: [],
shadowRoot: null,
requestUpdate: null
};
state.requestUpdate = () => {
if (state.raf) return;
state.raf = requestAnimationFrame(() => {
state.raf = 0;
positionMarkers(state);
state.emitViewport();
});
};
updateMarkers(state, markers);
window.addEventListener('scroll', state.requestUpdate, true);
document.addEventListener('scroll', state.requestUpdate, true);
window.addEventListener('resize', state.requestUpdate, true);
globalThis[stateKey] = state;
state.requestUpdate();
return true;
})();`
}
+4
View File
@@ -15,6 +15,10 @@ describe('browser-grab-types', () => {
expect(GRAB_BUDGET.nearbyTextMaxEntries).toBe(10)
expect(GRAB_BUDGET.htmlSnippetMaxLength).toBe(4096)
expect(GRAB_BUDGET.ancestorPathMaxEntries).toBe(10)
expect(GRAB_BUDGET.nearbyElementMaxLength).toBe(160)
expect(GRAB_BUDGET.cssClassesMaxLength).toBe(500)
expect(GRAB_BUDGET.selectedTextMaxLength).toBe(500)
expect(GRAB_BUDGET.annotationsMaxPerPage).toBe(20)
expect(GRAB_BUDGET.screenshotMaxBytes).toBe(2 * 1024 * 1024)
})
})
+37
View File
@@ -58,6 +58,14 @@ export type BrowserGrabRect = {
export type BrowserGrabTarget = {
tagName: string
selector: string
elementPath?: string
fullPath?: string
cssClasses?: string
nearbyElements?: string[]
selectedText?: string | null
isFixed?: boolean
reactComponents?: string | null
sourceFile?: string | null
textSnippet: string
htmlSnippet: string
attributes: Record<string, string>
@@ -84,6 +92,11 @@ export type BrowserGrabPayload = {
screenshot: BrowserGrabScreenshot | null
}
/** Persisted annotation payloads keep DOM context but drop transient screenshots. */
export type BrowserAnnotationPayload = Omit<BrowserGrabPayload, 'screenshot'> & {
screenshot: null
}
// ---------------------------------------------------------------------------
// Grab operation lifecycle
// ---------------------------------------------------------------------------
@@ -138,6 +151,20 @@ export type BrowserExtractHoverResult =
| { ok: true; payload: BrowserGrabPayload }
| { ok: false; reason: string }
export type BrowserAnnotationIntent = 'fix' | 'change' | 'question' | 'approve'
export type BrowserAnnotationPriority = 'blocking' | 'important' | 'suggestion'
export type BrowserPageAnnotation = {
id: string
browserPageId: string
comment: string
intent: BrowserAnnotationIntent
priority: BrowserAnnotationPriority
createdAt: string
payload: BrowserAnnotationPayload
}
// ---------------------------------------------------------------------------
// Payload budgets — enforced in both guest and main
// ---------------------------------------------------------------------------
@@ -148,6 +175,16 @@ export const GRAB_BUDGET = {
nearbyTextMaxEntries: 10,
htmlSnippetMaxLength: 4096,
ancestorPathMaxEntries: 10,
nearbyElementsMaxEntries: 6,
nearbyElementMaxLength: 160,
selectorMaxLength: 700,
pathMaxLength: 900,
cssClassesMaxLength: 500,
selectedTextMaxLength: 500,
sourceFileMaxLength: 500,
reactComponentsMaxLength: 500,
annotationCommentMaxLength: 2000,
annotationsMaxPerPage: 20,
/** Hard byte budget for screenshot PNG data URL before we omit the screenshot. */
screenshotMaxBytes: 2 * 1024 * 1024
} as const