feat: computer use via agent-browser CDP bridge (#856)

This commit is contained in:
Jinwoo Hong
2026-04-20 20:56:14 -07:00
committed by GitHub
parent 22ae50e0ae
commit 7a9bc4ef6d
35 changed files with 13560 additions and 43 deletions
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+390
View File
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
shellOpenExternalMock,
browserWindowFromWebContentsMock,
menuBuildFromTemplateMock,
guestOffMock,
guestOnMock,
@@ -13,6 +14,7 @@ const {
screenGetCursorScreenPointMock
} = vi.hoisted(() => ({
shellOpenExternalMock: vi.fn(),
browserWindowFromWebContentsMock: vi.fn(),
menuBuildFromTemplateMock: vi.fn(),
guestOffMock: vi.fn(),
guestOnMock: vi.fn(),
@@ -24,6 +26,9 @@ const {
}))
vi.mock('electron', () => ({
BrowserWindow: {
fromWebContents: browserWindowFromWebContentsMock
},
clipboard: { writeText: vi.fn() },
shell: { openExternal: shellOpenExternalMock },
Menu: {
@@ -44,6 +49,7 @@ describe('browserManager', () => {
beforeEach(() => {
shellOpenExternalMock.mockReset()
browserWindowFromWebContentsMock.mockReset()
menuBuildFromTemplateMock.mockReset()
guestOffMock.mockReset()
guestOnMock.mockReset()
@@ -148,6 +154,295 @@ describe('browserManager', () => {
expect(shellOpenExternalMock).toHaveBeenCalledWith('https://example.com/login')
})
it('activates the owning browser workspace when ensuring a page-backed guest is visible', async () => {
const rendererExecuteJavaScriptMock = vi
.fn()
.mockResolvedValueOnce({
prevTabType: 'terminal',
prevActiveWorktreeId: 'wt-1',
prevActiveBrowserWorkspaceId: 'workspace-prev',
prevActiveBrowserPageId: 'page-prev',
prevFocusedGroupTabId: 'tab-prev',
targetWorktreeId: 'wt-1',
targetBrowserWorkspaceId: 'workspace-1',
targetBrowserPageId: 'page-1'
})
.mockResolvedValueOnce(undefined)
const guest = {
id: 707,
isDestroyed: vi.fn(() => false),
getType: vi.fn(() => 'webview'),
setBackgroundThrottling: guestSetBackgroundThrottlingMock,
setWindowOpenHandler: guestSetWindowOpenHandlerMock,
on: guestOnMock,
off: guestOffMock,
openDevTools: guestOpenDevToolsMock
}
const renderer = {
id: rendererWebContentsId,
isDestroyed: vi.fn(() => false),
executeJavaScript: rendererExecuteJavaScriptMock
}
browserWindowFromWebContentsMock.mockReturnValue({ isFocused: vi.fn(() => true) })
webContentsFromIdMock.mockImplementation((id: number) => {
if (id === guest.id) {
return guest
}
if (id === rendererWebContentsId) {
return renderer
}
return null
})
browserManager.attachGuestPolicies(guest as never)
browserManager.registerGuest({
browserPageId: 'page-1',
workspaceId: 'workspace-1',
worktreeId: 'wt-1',
webContentsId: guest.id,
rendererWebContentsId
})
const restore = await browserManager.ensureWebviewVisible(guest.id)
const activationScript = rendererExecuteJavaScriptMock.mock.calls[0]?.[0]
expect(activationScript).toContain('var browserWorkspaceId = "workspace-1";')
expect(activationScript).toContain('var browserPageId = "page-1";')
expect(activationScript).toContain('state.setActiveBrowserTab(browserWorkspaceId);')
expect(activationScript).toContain(
'state.setActiveBrowserPage(browserWorkspaceId, browserPageId);'
)
expect(activationScript).toContain('var targetWorktreeId = "wt-1";')
restore()
})
it('restores the previously focused browser workspace after screenshot prep changes tabs', async () => {
const rendererExecuteJavaScriptMock = vi
.fn()
.mockResolvedValueOnce({
prevTabType: 'browser',
prevActiveWorktreeId: 'wt-prev',
prevActiveBrowserWorkspaceId: 'workspace-prev',
prevActiveBrowserPageId: 'page-prev',
prevFocusedGroupTabId: 'tab-prev',
targetWorktreeId: 'wt-target',
targetBrowserWorkspaceId: 'workspace-target',
targetBrowserPageId: 'page-target'
})
.mockResolvedValueOnce(undefined)
const guest = {
id: 708,
isDestroyed: vi.fn(() => false),
getType: vi.fn(() => 'webview'),
setBackgroundThrottling: guestSetBackgroundThrottlingMock,
setWindowOpenHandler: guestSetWindowOpenHandlerMock,
on: guestOnMock,
off: guestOffMock,
openDevTools: guestOpenDevToolsMock
}
const renderer = {
id: rendererWebContentsId,
isDestroyed: vi.fn(() => false),
executeJavaScript: rendererExecuteJavaScriptMock
}
browserWindowFromWebContentsMock.mockReturnValue({ isFocused: vi.fn(() => true) })
webContentsFromIdMock.mockImplementation((id: number) => {
if (id === guest.id) {
return guest
}
if (id === rendererWebContentsId) {
return renderer
}
return null
})
browserManager.attachGuestPolicies(guest as never)
browserManager.registerGuest({
browserPageId: 'page-target',
workspaceId: 'workspace-target',
worktreeId: 'wt-target',
webContentsId: guest.id,
rendererWebContentsId
})
const restore = await browserManager.ensureWebviewVisible(guest.id)
restore()
const restoreScript = rendererExecuteJavaScriptMock.mock.calls[1]?.[0]
expect(restoreScript).toContain('state.setActiveWorktree("wt-prev");')
expect(restoreScript).toContain('state.setActiveBrowserTab("workspace-prev");')
})
it('restores the previously active page when screenshot prep switches pages inside one workspace', async () => {
const rendererExecuteJavaScriptMock = vi
.fn()
.mockResolvedValueOnce({
prevTabType: 'browser',
prevActiveWorktreeId: 'wt-target',
prevActiveBrowserWorkspaceId: 'workspace-target',
prevActiveBrowserPageId: 'page-prev',
prevFocusedGroupTabId: null,
targetWorktreeId: 'wt-target',
targetBrowserWorkspaceId: 'workspace-target',
targetBrowserPageId: 'page-target'
})
.mockResolvedValueOnce(undefined)
const guest = {
id: 709,
isDestroyed: vi.fn(() => false),
getType: vi.fn(() => 'webview'),
setBackgroundThrottling: guestSetBackgroundThrottlingMock,
setWindowOpenHandler: guestSetWindowOpenHandlerMock,
on: guestOnMock,
off: guestOffMock,
openDevTools: guestOpenDevToolsMock
}
const renderer = {
id: rendererWebContentsId,
isDestroyed: vi.fn(() => false),
executeJavaScript: rendererExecuteJavaScriptMock
}
browserWindowFromWebContentsMock.mockReturnValue({ isFocused: vi.fn(() => true) })
webContentsFromIdMock.mockImplementation((id: number) => {
if (id === guest.id) {
return guest
}
if (id === rendererWebContentsId) {
return renderer
}
return null
})
browserManager.attachGuestPolicies(guest as never)
browserManager.registerGuest({
browserPageId: 'page-target',
workspaceId: 'workspace-target',
worktreeId: 'wt-target',
webContentsId: guest.id,
rendererWebContentsId
})
const restore = await browserManager.ensureWebviewVisible(guest.id)
restore()
const restoreScript = rendererExecuteJavaScriptMock.mock.calls[1]?.[0]
expect(restoreScript).toContain('state.setActiveBrowserPage(')
expect(restoreScript).toContain('"workspace-target"')
expect(restoreScript).toContain('"page-prev"')
})
it('restores remembered browser workspace/page even when the visible pane was terminal', async () => {
const rendererExecuteJavaScriptMock = vi
.fn()
.mockResolvedValueOnce({
prevTabType: 'terminal',
prevActiveWorktreeId: 'wt-target',
prevActiveBrowserWorkspaceId: 'workspace-prev',
prevActiveBrowserPageId: 'page-prev',
prevFocusedGroupTabId: 'tab-prev',
targetWorktreeId: 'wt-target',
targetBrowserWorkspaceId: 'workspace-target',
targetBrowserPageId: 'page-target'
})
.mockResolvedValueOnce(undefined)
const guest = {
id: 7091,
isDestroyed: vi.fn(() => false),
getType: vi.fn(() => 'webview'),
setBackgroundThrottling: guestSetBackgroundThrottlingMock,
setWindowOpenHandler: guestSetWindowOpenHandlerMock,
on: guestOnMock,
off: guestOffMock,
openDevTools: guestOpenDevToolsMock
}
const renderer = {
id: rendererWebContentsId,
isDestroyed: vi.fn(() => false),
executeJavaScript: rendererExecuteJavaScriptMock
}
browserWindowFromWebContentsMock.mockReturnValue({ isFocused: vi.fn(() => true) })
webContentsFromIdMock.mockImplementation((id: number) => {
if (id === guest.id) {
return guest
}
if (id === rendererWebContentsId) {
return renderer
}
return null
})
browserManager.attachGuestPolicies(guest as never)
browserManager.registerGuest({
browserPageId: 'page-target',
workspaceId: 'workspace-target',
worktreeId: 'wt-target',
webContentsId: guest.id,
rendererWebContentsId
})
const restore = await browserManager.ensureWebviewVisible(guest.id)
restore()
const restoreScript = rendererExecuteJavaScriptMock.mock.calls[1]?.[0]
expect(restoreScript).toContain('state.setActiveBrowserTab("workspace-prev");')
expect(restoreScript).toContain('state.setActiveBrowserPage(')
expect(restoreScript).toContain('"workspace-prev"')
expect(restoreScript).toContain('"page-prev"')
expect(restoreScript).toContain('state.activateTab("tab-prev");')
expect(restoreScript).toContain('state.setActiveTabType("terminal");')
})
it('does not focus the Orca window while preparing a screenshot', async () => {
const rendererExecuteJavaScriptMock = vi.fn().mockResolvedValueOnce({
prevTabType: 'terminal',
prevActiveWorktreeId: 'wt-1',
prevActiveBrowserWorkspaceId: 'workspace-prev',
prevActiveBrowserPageId: 'page-prev',
prevFocusedGroupTabId: 'tab-prev',
targetWorktreeId: 'wt-1',
targetBrowserWorkspaceId: 'workspace-1',
targetBrowserPageId: 'page-1'
})
const guest = {
id: 710,
isDestroyed: vi.fn(() => false),
getType: vi.fn(() => 'webview'),
setBackgroundThrottling: guestSetBackgroundThrottlingMock,
setWindowOpenHandler: guestSetWindowOpenHandlerMock,
on: guestOnMock,
off: guestOffMock,
openDevTools: guestOpenDevToolsMock
}
const renderer = {
id: rendererWebContentsId,
isDestroyed: vi.fn(() => false),
executeJavaScript: rendererExecuteJavaScriptMock
}
webContentsFromIdMock.mockImplementation((id: number) => {
if (id === guest.id) {
return guest
}
if (id === rendererWebContentsId) {
return renderer
}
return null
})
browserManager.attachGuestPolicies(guest as never)
browserManager.registerGuest({
browserPageId: 'page-1',
workspaceId: 'workspace-1',
worktreeId: 'wt-1',
webContentsId: guest.id,
rendererWebContentsId
})
await browserManager.ensureWebviewVisible(guest.id)
expect(browserWindowFromWebContentsMock).not.toHaveBeenCalled()
})
it('offers opening a link in another Orca browser tab from the guest context menu', () => {
const rendererSendMock = vi.fn()
const guest = {
@@ -455,6 +750,101 @@ describe('browserManager', () => {
)
})
it('retires stale guest mappings when a page re-registers after a process swap', () => {
const rendererSendMock = vi.fn()
const oldGuestOnMock = vi.fn()
const oldGuestOffMock = vi.fn()
const newGuestOnMock = vi.fn()
const newGuestOffMock = vi.fn()
const oldGuest = {
id: 501,
isDestroyed: vi.fn(() => false),
getType: vi.fn(() => 'webview'),
setBackgroundThrottling: guestSetBackgroundThrottlingMock,
setWindowOpenHandler: guestSetWindowOpenHandlerMock,
on: oldGuestOnMock,
off: oldGuestOffMock,
openDevTools: guestOpenDevToolsMock,
getURL: vi.fn(() => 'https://old.example')
}
const newGuest = {
id: 502,
isDestroyed: vi.fn(() => false),
getType: vi.fn(() => 'webview'),
setBackgroundThrottling: guestSetBackgroundThrottlingMock,
setWindowOpenHandler: guestSetWindowOpenHandlerMock,
on: newGuestOnMock,
off: newGuestOffMock,
openDevTools: guestOpenDevToolsMock,
getURL: vi.fn(() => 'https://new.example')
}
webContentsFromIdMock.mockImplementation((id: number) => {
if (id === oldGuest.id) {
return oldGuest
}
if (id === newGuest.id) {
return newGuest
}
if (id === rendererWebContentsId) {
return { isDestroyed: vi.fn(() => false), send: rendererSendMock }
}
return null
})
browserManager.attachGuestPolicies(oldGuest as never)
browserManager.registerGuest({
browserPageId: 'browser-1',
webContentsId: oldGuest.id,
rendererWebContentsId
})
browserManager.attachGuestPolicies(newGuest as never)
browserManager.registerGuest({
browserPageId: 'browser-1',
webContentsId: newGuest.id,
rendererWebContentsId
})
const oldDidFailLoadHandler = oldGuestOnMock.mock.calls.find(
([event]) => event === 'did-fail-load'
)?.[1] as
| ((
event: unknown,
errorCode: number,
errorDescription: string,
validatedUrl: string,
isMainFrame: boolean
) => void)
| undefined
const newDidFailLoadHandler = newGuestOnMock.mock.calls.find(
([event]) => event === 'did-fail-load'
)?.[1] as
| ((
event: unknown,
errorCode: number,
errorDescription: string,
validatedUrl: string,
isMainFrame: boolean
) => void)
| undefined
oldDidFailLoadHandler?.(null, -105, 'Old guest failed', 'https://old.example', true)
expect(rendererSendMock).not.toHaveBeenCalled()
newDidFailLoadHandler?.(null, -106, 'New guest failed', 'https://new.example', true)
expect(rendererSendMock).toHaveBeenCalledWith('browser:guest-load-failed', {
browserPageId: 'browser-1',
loadError: {
code: -106,
description: 'New guest failed',
validatedUrl: 'https://new.example'
}
})
expect(oldGuestOffMock).toHaveBeenCalled()
expect(browserManager.getGuestWebContentsId('browser-1')).toBe(newGuest.id)
})
it('does not forward ctrl/cmd+r or readline chords from browser guests', () => {
const rendererSendMock = vi.fn()
const guest = {
+269 -2
View File
@@ -38,6 +38,7 @@ export type BrowserGuestRegistration = {
browserPageId?: string
browserTabId?: string
workspaceId?: string
worktreeId?: string
webContentsId: number
rendererWebContentsId: number
}
@@ -71,15 +72,20 @@ function safeOrigin(rawUrl: string): string {
}
}
class BrowserManager {
export class BrowserManager {
private readonly webContentsIdByTabId = new Map<string, number>()
// Why: reverse map enables O(1) guest→tab lookups instead of O(N) linear
// scans on every mouse event, load failure, permission, and popup event.
private readonly tabIdByWebContentsId = new Map<number, string>()
// Why: guest registration is keyed by browser page id, but renderer
// visibility/focus state is keyed by browser workspace id. Screenshot prep
// has to bridge that mismatch to activate the right tab before capture.
private readonly workspaceIdByPageId = new Map<string, string>()
private readonly rendererWebContentsIdByTabId = new Map<string, number>()
private readonly contextMenuCleanupByTabId = new Map<string, () => void>()
private readonly grabShortcutCleanupByTabId = new Map<string, () => void>()
private readonly shortcutForwardingCleanupByTabId = new Map<string, () => void>()
private readonly worktreeIdByTabId = new Map<string, string>()
private readonly policyAttachedGuestIds = new Set<number>()
private readonly policyCleanupByGuestId = new Map<number, () => void>()
private readonly pendingLoadFailuresByGuestId = new Map<
@@ -108,12 +114,230 @@ class BrowserManager {
return renderer
}
// Why: screenshot sessions target guest page ids, but Orca's visible browser
// chrome is keyed by workspace ids. If we activate the page id directly, the
// webview stays hidden under the terminal pane and Page.captureScreenshot
// times out even though the guest still exists.
async ensureWebviewVisible(guestWebContentsId: number): Promise<() => void> {
const browserPageId = this.resolveBrowserTabIdForGuestWebContentsId(guestWebContentsId)
if (!browserPageId) {
return () => {}
}
const browserWorkspaceId = this.workspaceIdByPageId.get(browserPageId) ?? browserPageId
const worktreeId = this.worktreeIdByTabId.get(browserPageId) ?? null
const renderer = this.resolveRendererForBrowserTab(browserPageId)
if (!renderer || renderer.isDestroyed()) {
return () => {}
}
const prev = await renderer
.executeJavaScript(
`(function() {
var store = window.__store;
if (!store) return null;
var state = store.getState();
var prevTabType = state.activeTabType;
var prevActiveWorktreeId = state.activeWorktreeId || null;
var prevActiveBrowserWorkspaceId = state.activeBrowserTabId || null;
var prevActiveBrowserPageId = null;
var prevFocusedGroupTabId = null;
var targetWorktreeId = ${JSON.stringify(worktreeId)};
var browserWorkspaceId = ${JSON.stringify(browserWorkspaceId)};
var browserPageId = ${JSON.stringify(browserPageId)};
var browserTabsByWorktree = state.browserTabsByWorktree || {};
if (prevActiveWorktreeId) {
var prevFocusedGroupId = (state.activeGroupIdByWorktree || {})[prevActiveWorktreeId];
var prevGroups = (state.groupsByWorktree || {})[prevActiveWorktreeId] || [];
for (var pg = 0; pg < prevGroups.length; pg++) {
if (prevGroups[pg].id === prevFocusedGroupId) {
prevFocusedGroupTabId = prevGroups[pg].activeTabId;
break;
}
}
}
if (prevActiveBrowserWorkspaceId) {
for (var prevWtId in browserTabsByWorktree) {
var prevBrowserTabs = browserTabsByWorktree[prevWtId] || [];
for (var pbt = 0; pbt < prevBrowserTabs.length; pbt++) {
if (prevBrowserTabs[pbt].id === prevActiveBrowserWorkspaceId) {
prevActiveBrowserPageId = prevBrowserTabs[pbt].activePageId || null;
break;
}
}
if (prevActiveBrowserPageId) break;
}
}
if (
targetWorktreeId &&
prevActiveWorktreeId !== targetWorktreeId &&
typeof state.setActiveWorktree === 'function'
) {
state.setActiveWorktree(targetWorktreeId);
state = store.getState();
}
var foundWorkspace = null;
for (var wtId in browserTabsByWorktree) {
var tabs = browserTabsByWorktree[wtId] || [];
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].id === browserWorkspaceId) {
foundWorkspace = tabs[i];
if (!targetWorktreeId) {
targetWorktreeId = wtId;
}
break;
}
}
if (foundWorkspace) break;
}
var hasTargetPage = false;
var targetPages = (state.browserPagesByWorkspace || {})[browserWorkspaceId] || [];
for (var pageIndex = 0; pageIndex < targetPages.length; pageIndex++) {
if (targetPages[pageIndex].id === browserPageId) {
hasTargetPage = true;
break;
}
}
if (foundWorkspace) {
if (typeof state.setActiveBrowserTab === 'function') {
state.setActiveBrowserTab(browserWorkspaceId);
state = store.getState();
} else {
var allTabs = state.unifiedTabsByWorktree || {};
var found = null;
for (var unifiedWtId in allTabs) {
var unifiedTabs = allTabs[unifiedWtId] || [];
for (var unifiedIndex = 0; unifiedIndex < unifiedTabs.length; unifiedIndex++) {
if (
unifiedTabs[unifiedIndex].contentType === 'browser' &&
unifiedTabs[unifiedIndex].entityId === browserWorkspaceId
) {
found = unifiedTabs[unifiedIndex];
break;
}
}
if (found) break;
}
if (found) {
state.activateTab(found.id);
}
state.setActiveTabType('browser');
state = store.getState();
}
// Why: activating the workspace alone is not enough for screenshot
// capture when a browser workspace contains multiple pages. The
// compositor only paints the currently mounted page guest.
if (
hasTargetPage &&
foundWorkspace.activePageId !== browserPageId &&
typeof state.setActiveBrowserPage === 'function'
) {
state.setActiveBrowserPage(browserWorkspaceId, browserPageId);
state = store.getState();
}
}
return {
prevTabType: prevTabType,
prevActiveWorktreeId: prevActiveWorktreeId,
prevActiveBrowserWorkspaceId: prevActiveBrowserWorkspaceId,
prevActiveBrowserPageId: prevActiveBrowserPageId,
prevFocusedGroupTabId: prevFocusedGroupTabId,
targetWorktreeId: targetWorktreeId,
targetBrowserWorkspaceId: foundWorkspace ? browserWorkspaceId : null,
targetBrowserPageId: foundWorkspace && hasTargetPage ? browserPageId : null
};
})()`
)
.catch(() => null)
const needsRestore =
prev &&
(prev.prevTabType !== 'browser' ||
prev.prevActiveWorktreeId !== prev.targetWorktreeId ||
prev.prevFocusedGroupTabId !== null ||
prev.prevActiveBrowserWorkspaceId !== prev.targetBrowserWorkspaceId ||
prev.prevActiveBrowserPageId !== prev.targetBrowserPageId)
if (!needsRestore) {
return () => {}
}
return () => {
if (!prev || !renderer || renderer.isDestroyed()) {
return
}
renderer
.executeJavaScript(
`(function() {
var store = window.__store;
if (!store) return;
var state = store.getState();
if (
${JSON.stringify(prev?.prevActiveWorktreeId)} &&
${JSON.stringify(prev?.prevActiveWorktreeId)} !==
${JSON.stringify(prev?.targetWorktreeId)} &&
typeof state.setActiveWorktree === 'function'
) {
state.setActiveWorktree(${JSON.stringify(prev?.prevActiveWorktreeId)});
state = store.getState();
}
if (
${JSON.stringify(prev?.prevActiveBrowserWorkspaceId)} &&
${JSON.stringify(prev?.prevActiveBrowserWorkspaceId)} !==
${JSON.stringify(prev?.targetBrowserWorkspaceId)} &&
typeof state.setActiveBrowserTab === 'function'
) {
state.setActiveBrowserTab(${JSON.stringify(prev?.prevActiveBrowserWorkspaceId)});
state = store.getState();
}
if (
${JSON.stringify(prev?.prevActiveBrowserWorkspaceId)} &&
${JSON.stringify(prev?.prevActiveBrowserPageId)} &&
${JSON.stringify(prev?.prevActiveBrowserPageId)} !==
${JSON.stringify(prev?.targetBrowserPageId)} &&
typeof state.setActiveBrowserPage === 'function'
) {
// Why: Orca remembers the last browser workspace/page even when
// the user is currently in terminal/editor view. Screenshot prep
// temporarily switches that hidden browser selection state, so
// restore it independently of the visible tab type.
state.setActiveBrowserPage(
${JSON.stringify(prev?.prevActiveBrowserWorkspaceId)},
${JSON.stringify(prev?.prevActiveBrowserPageId)}
);
state = store.getState();
}
if (
${JSON.stringify(prev?.prevTabType)} !== 'browser' &&
${JSON.stringify(prev?.prevFocusedGroupTabId)}
) {
state.activateTab(${JSON.stringify(prev?.prevFocusedGroupTabId)});
}
if (${JSON.stringify(prev?.prevTabType)} !== 'browser') {
state.setActiveTabType(${JSON.stringify(prev?.prevTabType)});
}
})()`
)
.catch(() => {})
}
}
attachGuestPolicies(guest: Electron.WebContents): void {
if (this.policyAttachedGuestIds.has(guest.id)) {
return
}
this.policyAttachedGuestIds.add(guest.id)
guest.setBackgroundThrottling(true)
// Why: background throttling must be disabled so agent-driven screenshots
// (Page.captureScreenshot via CDP proxy) can capture frames even when the
// Orca window is not the focused foreground app. With throttling enabled,
// the compositor stops producing frames and capturePage() returns empty.
guest.setBackgroundThrottling(false)
guest.setWindowOpenHandler(({ url }) => {
const browserTabId = this.resolveBrowserTabIdForGuestWebContentsId(guest.id)
const browserUrl = normalizeBrowserNavigationUrl(url)
@@ -189,9 +413,30 @@ class BrowserManager {
})
}
private retireStaleGuestWebContents(previousWebContentsId: number): void {
// Why: a browser page can re-register with a new guest id after Chromium
// swaps renderer processes. Late events from the dead guest must stop
// resolving to the live page, or stale download/popup/permission callbacks
// can be delivered to the wrong session after the swap.
this.tabIdByWebContentsId.delete(previousWebContentsId)
const policyCleanup = this.policyCleanupByGuestId.get(previousWebContentsId)
if (policyCleanup) {
policyCleanup()
this.policyCleanupByGuestId.delete(previousWebContentsId)
}
this.policyAttachedGuestIds.delete(previousWebContentsId)
this.pendingLoadFailuresByGuestId.delete(previousWebContentsId)
this.pendingPermissionEventsByGuestId.delete(previousWebContentsId)
this.pendingPopupEventsByGuestId.delete(previousWebContentsId)
this.pendingDownloadIdsByGuestId.delete(previousWebContentsId)
}
registerGuest({
browserPageId,
browserTabId: legacyBrowserTabId,
workspaceId,
worktreeId,
webContentsId,
rendererWebContentsId
}: BrowserGuestRegistration): void {
@@ -231,9 +476,20 @@ class BrowserManager {
return
}
const previousWebContentsId = this.webContentsIdByTabId.get(browserTabId)
if (previousWebContentsId !== undefined && previousWebContentsId !== webContentsId) {
this.retireStaleGuestWebContents(previousWebContentsId)
}
this.webContentsIdByTabId.set(browserTabId, webContentsId)
this.tabIdByWebContentsId.set(webContentsId, browserTabId)
if (workspaceId) {
this.workspaceIdByPageId.set(browserTabId, workspaceId)
}
this.rendererWebContentsIdByTabId.set(browserTabId, rendererWebContentsId)
if (worktreeId) {
this.worktreeIdByTabId.set(browserTabId, worktreeId)
}
this.setupContextMenu(browserTabId, guest)
this.setupGrabShortcut(browserTabId, guest)
@@ -292,6 +548,8 @@ class BrowserManager {
}
this.webContentsIdByTabId.delete(browserTabId)
this.rendererWebContentsIdByTabId.delete(browserTabId)
this.workspaceIdByPageId.delete(browserTabId)
this.worktreeIdByTabId.delete(browserTabId)
}
unregisterAll(): void {
@@ -313,6 +571,7 @@ class BrowserManager {
}
this.policyCleanupByGuestId.clear()
this.tabIdByWebContentsId.clear()
this.worktreeIdByTabId.clear()
this.pendingLoadFailuresByGuestId.clear()
this.pendingPermissionEventsByGuestId.clear()
this.pendingPopupEventsByGuestId.clear()
@@ -323,6 +582,14 @@ class BrowserManager {
return this.webContentsIdByTabId.get(browserTabId) ?? null
}
getWebContentsIdByTabId(): Map<string, number> {
return this.webContentsIdByTabId
}
getWorktreeIdForTab(browserTabId: string): string | undefined {
return this.worktreeIdByTabId.get(browserTabId)
}
notifyPermissionDenied(args: {
guestWebContentsId: number
permission: string
+6 -2
View File
@@ -373,8 +373,12 @@ class BrowserSessionRegistry {
this.configuredPartitions.add(partition)
const sess = session.fromPartition(partition)
// Why: clipboard-read and clipboard-sanitized-write are required for agent-browser's
// clipboard commands to work. Without these, navigator.clipboard.writeText/readText
// throws NotAllowedError even when invoked via CDP with userGesture:true.
const autoGranted = new Set(['fullscreen', 'clipboard-read', 'clipboard-sanitized-write'])
sess.setPermissionRequestHandler((webContents, permission, callback) => {
const allowed = permission === 'fullscreen'
const allowed = autoGranted.has(permission)
if (!allowed) {
browserManager.notifyPermissionDenied({
guestWebContentsId: webContents.id,
@@ -385,7 +389,7 @@ class BrowserSessionRegistry {
callback(allowed)
})
sess.setPermissionCheckHandler((_webContents, permission) => {
return permission === 'fullscreen'
return autoGranted.has(permission)
})
sess.setDisplayMediaRequestHandler((_request, callback) => {
callback({ video: undefined, audio: undefined })
@@ -0,0 +1,533 @@
/* eslint-disable max-lines -- Why: integration test covering the full browser automation pipeline end-to-end. */
import { mkdtempSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { createConnection } from 'net'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
// ── Electron mocks ──
const { webContentsFromIdMock } = vi.hoisted(() => ({
webContentsFromIdMock: vi.fn()
}))
vi.mock('electron', () => ({
webContents: { fromId: webContentsFromIdMock },
shell: { openExternal: vi.fn() },
ipcMain: { handle: vi.fn(), removeHandler: vi.fn(), on: vi.fn() },
app: { getPath: vi.fn(() => '/tmp'), isPackaged: false }
}))
vi.mock('../git/worktree', () => ({
listWorktrees: vi.fn().mockResolvedValue([])
}))
import { BrowserManager } from './browser-manager'
import { CdpBridge } from './cdp-bridge'
import { OrcaRuntimeService } from '../runtime/orca-runtime'
import { OrcaRuntimeRpcServer } from '../runtime/runtime-rpc'
import { readRuntimeMetadata } from '../runtime/runtime-metadata'
// ── CDP response builders ──
type AXNode = {
nodeId: string
backendDOMNodeId?: number
role?: { type: string; value: string }
name?: { type: string; value: string }
properties?: { name: string; value: { type: string; value: unknown } }[]
childIds?: string[]
ignored?: boolean
}
function axNode(
id: string,
role: string,
name: string,
opts?: { childIds?: string[]; backendDOMNodeId?: number }
): AXNode {
return {
nodeId: id,
backendDOMNodeId: opts?.backendDOMNodeId ?? parseInt(id, 10) * 100,
role: { type: 'role', value: role },
name: { type: 'computedString', value: name },
childIds: opts?.childIds
}
}
const EXAMPLE_COM_TREE: AXNode[] = [
axNode('1', 'WebArea', 'Example Domain', { childIds: ['2', '3', '4'] }),
axNode('2', 'heading', 'Example Domain'),
axNode('3', 'staticText', 'This domain is for use in illustrative examples.'),
axNode('4', 'link', 'More information...', { backendDOMNodeId: 400 })
]
const SEARCH_PAGE_TREE: AXNode[] = [
axNode('1', 'WebArea', 'Search', { childIds: ['2', '3', '4', '5'] }),
axNode('2', 'navigation', 'Main Nav', { childIds: ['3'] }),
axNode('3', 'link', 'Home', { backendDOMNodeId: 300 }),
axNode('4', 'textbox', 'Search query', { backendDOMNodeId: 400 }),
axNode('5', 'button', 'Search', { backendDOMNodeId: 500 })
]
// ── Mock WebContents factory ──
function createMockGuest(id: number, url: string, title: string) {
let currentUrl = url
let currentTitle = title
let currentTree = EXAMPLE_COM_TREE
let navHistoryId = 1
const sendCommandMock = vi.fn(async (method: string, params?: Record<string, unknown>) => {
switch (method) {
case 'Page.enable':
case 'DOM.enable':
case 'Accessibility.enable':
return {}
case 'Accessibility.getFullAXTree':
return { nodes: currentTree }
case 'Page.getNavigationHistory':
return {
entries: [{ id: navHistoryId, url: currentUrl }],
currentIndex: 0
}
case 'Page.navigate': {
const targetUrl = (params as { url: string }).url
if (targetUrl.includes('nonexistent.invalid')) {
return { errorText: 'net::ERR_NAME_NOT_RESOLVED' }
}
navHistoryId++
currentUrl = targetUrl
if (targetUrl.includes('search.example.com')) {
currentTitle = 'Search'
currentTree = SEARCH_PAGE_TREE
} else {
currentTitle = 'Example Domain'
currentTree = EXAMPLE_COM_TREE
}
return {}
}
case 'Runtime.evaluate': {
const expr = (params as { expression: string }).expression
if (expr === 'document.readyState') {
return { result: { value: 'complete' } }
}
if (expr === 'location.origin') {
return { result: { value: new URL(currentUrl).origin } }
}
if (expr.includes('innerWidth')) {
return { result: { value: JSON.stringify({ w: 1280, h: 720 }) } }
}
if (expr.includes('scrollBy')) {
return { result: { value: undefined } }
}
if (expr.includes('dispatchEvent')) {
return { result: { value: undefined } }
}
// eslint-disable-next-line no-eval
return { result: { value: String(eval(expr)), type: 'string' } }
}
case 'DOM.scrollIntoViewIfNeeded':
return {}
case 'DOM.getBoxModel':
return { model: { content: [100, 200, 300, 200, 300, 250, 100, 250] } }
case 'Input.dispatchMouseEvent':
return {}
case 'Input.insertText':
return {}
case 'Input.dispatchKeyEvent':
return {}
case 'DOM.focus':
return {}
case 'DOM.describeNode':
return { node: { nodeId: 1 } }
case 'DOM.requestNode':
return { nodeId: 1 }
case 'DOM.resolveNode':
return { object: { objectId: 'obj-1' } }
case 'Runtime.callFunctionOn':
return { result: { value: undefined } }
case 'DOM.setFileInputFiles':
return {}
case 'Page.captureScreenshot':
return {
data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=='
}
case 'Page.reload':
return {}
case 'Network.enable':
return {}
case 'Target.setAutoAttach':
return {}
case 'Runtime.enable':
return {}
default:
throw new Error(`Unexpected CDP method: ${method}`)
}
})
const debuggerListeners = new Map<string, ((...args: unknown[]) => void)[]>()
const guest = {
id,
isDestroyed: vi.fn(() => false),
getType: vi.fn(() => 'webview'),
getURL: vi.fn(() => currentUrl),
getTitle: vi.fn(() => currentTitle),
setBackgroundThrottling: vi.fn(),
setWindowOpenHandler: vi.fn(),
on: vi.fn(),
off: vi.fn(),
debugger: {
attach: vi.fn(),
detach: vi.fn(),
sendCommand: sendCommandMock,
on: vi.fn((event: string, handler: (...args: unknown[]) => void) => {
const handlers = debuggerListeners.get(event) ?? []
handlers.push(handler)
debuggerListeners.set(event, handlers)
}),
removeListener: vi.fn((event: string, handler: (...args: unknown[]) => void) => {
const handlers = debuggerListeners.get(event) ?? []
const idx = handlers.indexOf(handler)
if (idx >= 0) {
handlers.splice(idx, 1)
}
}),
removeAllListeners: vi.fn((event: string) => {
debuggerListeners.set(event, [])
}),
off: vi.fn()
}
}
return { guest, sendCommandMock }
}
// ── RPC helper ──
async function sendRequest(
endpoint: string,
request: Record<string, unknown>
): Promise<Record<string, unknown>> {
return await new Promise((resolve, reject) => {
const socket = createConnection(endpoint)
let buffer = ''
socket.setEncoding('utf8')
socket.once('error', reject)
socket.on('data', (chunk) => {
buffer += chunk
const newlineIndex = buffer.indexOf('\n')
if (newlineIndex === -1) {
return
}
const message = buffer.slice(0, newlineIndex)
socket.end()
resolve(JSON.parse(message) as Record<string, unknown>)
})
socket.on('connect', () => {
socket.write(`${JSON.stringify(request)}\n`)
})
})
}
// ── Tests ──
describe('Browser automation pipeline (integration)', () => {
let server: OrcaRuntimeRpcServer
let endpoint: string
let authToken: string
const GUEST_WC_ID = 5001
const RENDERER_WC_ID = 1
beforeEach(async () => {
const { guest } = createMockGuest(GUEST_WC_ID, 'https://example.com', 'Example Domain')
webContentsFromIdMock.mockImplementation((id: number) => {
if (id === GUEST_WC_ID) {
return guest
}
return null
})
const browserManager = new BrowserManager()
// Simulate the attach-time policy (normally done in will-attach-webview)
browserManager.attachGuestPolicies(guest as never)
browserManager.registerGuest({
browserPageId: 'page-1',
webContentsId: GUEST_WC_ID,
rendererWebContentsId: RENDERER_WC_ID
})
const cdpBridge = new CdpBridge(browserManager)
cdpBridge.setActiveTab(GUEST_WC_ID)
const userDataPath = mkdtempSync(join(tmpdir(), 'browser-e2e-'))
const runtime = new OrcaRuntimeService()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
runtime.setAgentBrowserBridge(cdpBridge as any)
server = new OrcaRuntimeRpcServer({ runtime, userDataPath })
await server.start()
const metadata = readRuntimeMetadata(userDataPath)!
endpoint = metadata.transport!.endpoint
authToken = metadata.authToken!
})
afterEach(async () => {
await server.stop()
})
async function rpc(method: string, params?: Record<string, unknown>) {
const response = await sendRequest(endpoint, {
id: `req_${method}`,
authToken,
method,
...(params ? { params } : {})
})
return response
}
// ── Snapshot ──
it('takes a snapshot and returns refs for interactive elements', async () => {
const res = await rpc('browser.snapshot')
expect(res.ok).toBe(true)
const result = res.result as {
snapshot: string
refs: { ref: string; role: string; name: string }[]
url: string
title: string
}
expect(result.url).toBe('https://example.com')
expect(result.title).toBe('Example Domain')
expect(result.snapshot).toContain('heading "Example Domain"')
expect(result.snapshot).toContain('link "More information..."')
expect(result.refs).toHaveLength(1)
expect(result.refs[0]).toMatchObject({
ref: '@e1',
role: 'link',
name: 'More information...'
})
})
// ── Click ──
it('clicks an element by ref after snapshot', async () => {
await rpc('browser.snapshot')
const res = await rpc('browser.click', { element: '@e1' })
expect(res.ok).toBe(true)
expect((res.result as { clicked: string }).clicked).toBe('@e1')
})
it('returns error when clicking without a prior snapshot', async () => {
const res = await rpc('browser.click', { element: '@e1' })
expect(res.ok).toBe(false)
expect((res.error as { code: string }).code).toBe('browser_stale_ref')
})
it('returns error for non-existent ref', async () => {
await rpc('browser.snapshot')
const res = await rpc('browser.click', { element: '@e999' })
expect(res.ok).toBe(false)
expect((res.error as { code: string }).code).toBe('browser_ref_not_found')
})
// ── Navigation ──
it('navigates to a URL and invalidates refs', async () => {
await rpc('browser.snapshot')
const gotoRes = await rpc('browser.goto', { url: 'https://search.example.com' })
expect(gotoRes.ok).toBe(true)
const gotoResult = gotoRes.result as { url: string; title: string }
expect(gotoResult.url).toBe('https://search.example.com')
expect(gotoResult.title).toBe('Search')
// Old refs should be stale after navigation
const clickRes = await rpc('browser.click', { element: '@e1' })
expect(clickRes.ok).toBe(false)
expect((clickRes.error as { code: string }).code).toBe('browser_stale_ref')
// Re-snapshot should work and show new page
const snapRes = await rpc('browser.snapshot')
expect(snapRes.ok).toBe(true)
const snapResult = snapRes.result as { snapshot: string; refs: { name: string }[] }
expect(snapResult.snapshot).toContain('Search')
expect(snapResult.refs.map((r) => r.name)).toContain('Search')
expect(snapResult.refs.map((r) => r.name)).toContain('Home')
})
it('returns error for failed navigation', async () => {
const res = await rpc('browser.goto', { url: 'https://nonexistent.invalid' })
expect(res.ok).toBe(false)
expect((res.error as { code: string }).code).toBe('browser_navigation_failed')
})
// ── Fill ──
it('fills an input by ref', async () => {
await rpc('browser.goto', { url: 'https://search.example.com' })
await rpc('browser.snapshot')
// @e2 should be the textbox "Search query" on the search page
const res = await rpc('browser.fill', { element: '@e2', value: 'hello world' })
expect(res.ok).toBe(true)
expect((res.result as { filled: string }).filled).toBe('@e2')
})
// ── Type ──
it('types text at current focus', async () => {
const res = await rpc('browser.type', { input: 'some text' })
expect(res.ok).toBe(true)
expect((res.result as { typed: boolean }).typed).toBe(true)
})
// ── Select ──
it('selects a dropdown option by ref', async () => {
await rpc('browser.goto', { url: 'https://search.example.com' })
await rpc('browser.snapshot')
const res = await rpc('browser.select', { element: '@e2', value: 'option-1' })
expect(res.ok).toBe(true)
expect((res.result as { selected: string }).selected).toBe('@e2')
})
// ── Scroll ──
it('scrolls the viewport', async () => {
const res = await rpc('browser.scroll', { direction: 'down' })
expect(res.ok).toBe(true)
expect((res.result as { scrolled: string }).scrolled).toBe('down')
const res2 = await rpc('browser.scroll', { direction: 'up', amount: 200 })
expect(res2.ok).toBe(true)
expect((res2.result as { scrolled: string }).scrolled).toBe('up')
})
// ── Reload ──
it('reloads the page', async () => {
const res = await rpc('browser.reload')
expect(res.ok).toBe(true)
expect((res.result as { url: string }).url).toBe('https://example.com')
})
// ── Screenshot ──
it('captures a screenshot', async () => {
const res = await rpc('browser.screenshot', { format: 'png' })
expect(res.ok).toBe(true)
const result = res.result as { data: string; format: string }
expect(result.format).toBe('png')
expect(result.data.length).toBeGreaterThan(0)
})
// ── Eval ──
it('evaluates JavaScript in the page context', async () => {
const res = await rpc('browser.eval', { expression: '2 + 2' })
expect(res.ok).toBe(true)
expect((res.result as { result: string }).result).toBe('4')
})
// ── Tab management ──
it('lists open tabs', async () => {
const res = await rpc('browser.tabList')
expect(res.ok).toBe(true)
const result = res.result as { tabs: { index: number; url: string; active: boolean }[] }
expect(result.tabs).toHaveLength(1)
expect(result.tabs[0]).toMatchObject({
index: 0,
url: 'https://example.com',
active: true
})
})
it('returns error for out-of-range tab switch', async () => {
const res = await rpc('browser.tabSwitch', { index: 5 })
expect(res.ok).toBe(false)
expect((res.error as { code: string }).code).toBe('browser_tab_not_found')
})
// ── Full agent workflow simulation ──
it('simulates a complete agent workflow: navigate → snapshot → interact → re-snapshot', async () => {
// 1. Navigate to search page
const gotoRes = await rpc('browser.goto', { url: 'https://search.example.com' })
expect(gotoRes.ok).toBe(true)
// 2. Snapshot the page
const snap1 = await rpc('browser.snapshot')
expect(snap1.ok).toBe(true)
const snap1Result = snap1.result as {
snapshot: string
refs: { ref: string; role: string; name: string }[]
}
// Verify we see the search page structure
expect(snap1Result.snapshot).toContain('[Main Nav]')
expect(snap1Result.snapshot).toContain('text input "Search query"')
expect(snap1Result.snapshot).toContain('button "Search"')
// 3. Fill the search input
const searchInput = snap1Result.refs.find((r) => r.name === 'Search query')
expect(searchInput).toBeDefined()
const fillRes = await rpc('browser.fill', {
element: searchInput!.ref,
value: 'integration testing'
})
expect(fillRes.ok).toBe(true)
// 4. Click the search button
const searchBtn = snap1Result.refs.find((r) => r.name === 'Search')
expect(searchBtn).toBeDefined()
const clickRes = await rpc('browser.click', { element: searchBtn!.ref })
expect(clickRes.ok).toBe(true)
// 5. Take a screenshot
const ssRes = await rpc('browser.screenshot')
expect(ssRes.ok).toBe(true)
// 6. Check tab list
const tabRes = await rpc('browser.tabList')
expect(tabRes.ok).toBe(true)
const tabs = (tabRes.result as { tabs: { url: string }[] }).tabs
expect(tabs[0].url).toBe('https://search.example.com')
})
// ── No tab errors ──
it('returns browser_no_tab when no tabs are registered', async () => {
// Create a fresh setup with no registered tabs
const emptyManager = new BrowserManager()
const emptyBridge = new CdpBridge(emptyManager)
const userDataPath2 = mkdtempSync(join(tmpdir(), 'browser-e2e-empty-'))
const runtime2 = new OrcaRuntimeService()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
runtime2.setAgentBrowserBridge(emptyBridge as any)
const server2 = new OrcaRuntimeRpcServer({ runtime: runtime2, userDataPath: userDataPath2 })
await server2.start()
const metadata2 = readRuntimeMetadata(userDataPath2)!
const res = await sendRequest(metadata2.transport!.endpoint, {
id: 'req_no_tab',
authToken: metadata2.authToken,
method: 'browser.snapshot'
})
expect(res.ok).toBe(false)
expect((res.error as { code: string }).code).toBe('browser_no_tab')
await server2.stop()
})
})
File diff suppressed because it is too large Load Diff
+246
View File
@@ -0,0 +1,246 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { captureFullPageScreenshot, captureScreenshot } from './cdp-screenshot'
function createMockWebContents() {
return {
isDestroyed: vi.fn(() => false),
invalidate: vi.fn(),
capturePage: vi.fn(),
debugger: {
isAttached: vi.fn(() => true),
sendCommand: vi.fn()
}
}
}
describe('captureScreenshot', () => {
afterEach(() => {
vi.useRealTimers()
})
it('invalidates the guest before forwarding Page.captureScreenshot', async () => {
const webContents = createMockWebContents()
webContents.debugger.sendCommand.mockResolvedValueOnce({ data: 'png-data' })
const onResult = vi.fn()
const onError = vi.fn()
captureScreenshot(webContents as never, { format: 'png' }, onResult, onError)
await Promise.resolve()
expect(webContents.invalidate).toHaveBeenCalledTimes(1)
expect(webContents.debugger.sendCommand).toHaveBeenCalledWith('Page.captureScreenshot', {
format: 'png'
})
expect(onResult).toHaveBeenCalledWith({ data: 'png-data' })
expect(onError).not.toHaveBeenCalled()
})
it('falls back to capturePage when Page.captureScreenshot stalls', async () => {
vi.useFakeTimers()
const webContents = createMockWebContents()
webContents.debugger.sendCommand.mockImplementation(() => new Promise(() => {}))
webContents.capturePage.mockResolvedValueOnce({
isEmpty: () => false,
toPNG: () => Buffer.from('fallback-png')
})
const onResult = vi.fn()
const onError = vi.fn()
captureScreenshot(webContents as never, { format: 'png' }, onResult, onError)
await vi.advanceTimersByTimeAsync(8000)
expect(webContents.capturePage).toHaveBeenCalledTimes(1)
expect(onResult).toHaveBeenCalledWith({
data: Buffer.from('fallback-png').toString('base64')
})
expect(onError).not.toHaveBeenCalled()
})
it('crops the fallback image when the request includes a visible clip rect', async () => {
vi.useFakeTimers()
const croppedImage = {
isEmpty: () => false,
toPNG: () => Buffer.from('cropped-png')
}
const webContents = createMockWebContents()
webContents.debugger.sendCommand.mockImplementation(() => new Promise(() => {}))
webContents.capturePage.mockResolvedValueOnce({
isEmpty: () => false,
getSize: () => ({ width: 400, height: 300 }),
crop: vi.fn(() => croppedImage),
toPNG: () => Buffer.from('full-png')
})
const onResult = vi.fn()
const onError = vi.fn()
captureScreenshot(
webContents as never,
{
format: 'png',
clip: { x: 10, y: 20, width: 30, height: 40, scale: 2 }
},
onResult,
onError
)
await vi.advanceTimersByTimeAsync(8000)
const fallbackImage = await webContents.capturePage.mock.results[0]?.value
expect(fallbackImage.crop).toHaveBeenCalledWith({ x: 20, y: 40, width: 60, height: 80 })
expect(onResult).toHaveBeenCalledWith({
data: Buffer.from('cropped-png').toString('base64')
})
expect(onError).not.toHaveBeenCalled()
})
it('keeps the timeout error when the request needs beyond-viewport pixels', async () => {
vi.useFakeTimers()
const webContents = createMockWebContents()
webContents.debugger.sendCommand.mockImplementation(() => new Promise(() => {}))
webContents.capturePage.mockResolvedValueOnce({
isEmpty: () => false,
getSize: () => ({ width: 400, height: 300 }),
crop: vi.fn(),
toPNG: () => Buffer.from('full-png')
})
const onResult = vi.fn()
const onError = vi.fn()
captureScreenshot(
webContents as never,
{
format: 'png',
captureBeyondViewport: true,
clip: { x: 0, y: 0, width: 800, height: 1200, scale: 1 }
},
onResult,
onError
)
await vi.advanceTimersByTimeAsync(8000)
expect(onResult).not.toHaveBeenCalled()
expect(onError).toHaveBeenCalledWith(
'Screenshot timed out — the browser tab may not be visible or the window may not have focus.'
)
})
it('ignores the fallback result when CDP settles first after the timeout fires', async () => {
vi.useFakeTimers()
let resolveCapturePage: ((value: unknown) => void) | null = null
let resolveSendCommand: ((value: unknown) => void) | null = null
const webContents = createMockWebContents()
webContents.debugger.sendCommand.mockImplementation(
() =>
new Promise((resolve) => {
resolveSendCommand = resolve
})
)
webContents.capturePage.mockImplementation(
() =>
new Promise((resolve) => {
resolveCapturePage = resolve
})
)
const onResult = vi.fn()
const onError = vi.fn()
captureScreenshot(webContents as never, { format: 'png' }, onResult, onError)
await vi.advanceTimersByTimeAsync(8000)
expect(resolveSendCommand).toBeTypeOf('function')
resolveSendCommand!({ data: 'cdp-png' })
await Promise.resolve()
expect(resolveCapturePage).toBeTypeOf('function')
resolveCapturePage!({
isEmpty: () => false,
getSize: () => ({ width: 100, height: 100 }),
crop: vi.fn(),
toPNG: () => Buffer.from('fallback-png')
})
await Promise.resolve()
expect(onResult).toHaveBeenCalledTimes(1)
expect(onResult).toHaveBeenCalledWith({ data: 'cdp-png' })
expect(onError).not.toHaveBeenCalled()
})
it('reports the original timeout when the fallback capture is unavailable', async () => {
vi.useFakeTimers()
const webContents = createMockWebContents()
webContents.debugger.sendCommand.mockImplementation(() => new Promise(() => {}))
webContents.capturePage.mockResolvedValueOnce({
isEmpty: () => true,
toPNG: () => Buffer.from('unused')
})
const onResult = vi.fn()
const onError = vi.fn()
captureScreenshot(webContents as never, { format: 'png' }, onResult, onError)
await vi.advanceTimersByTimeAsync(8000)
expect(onResult).not.toHaveBeenCalled()
expect(onError).toHaveBeenCalledWith(
'Screenshot timed out — the browser tab may not be visible or the window may not have focus.'
)
})
})
describe('captureFullPageScreenshot', () => {
it('uses cssContentSize so HiDPI pages are captured at the real page size', async () => {
const webContents = createMockWebContents()
webContents.debugger.sendCommand.mockImplementation((method: string) => {
if (method === 'Page.getLayoutMetrics') {
return Promise.resolve({
cssContentSize: { width: 640.25, height: 1280.75 },
contentSize: { width: 1280.5, height: 2561.5 }
})
}
if (method === 'Page.captureScreenshot') {
return Promise.resolve({ data: 'full-page-data' })
}
return Promise.resolve({})
})
await expect(captureFullPageScreenshot(webContents as never, 'png')).resolves.toEqual({
data: 'full-page-data',
format: 'png'
})
expect(webContents.debugger.sendCommand).toHaveBeenNthCalledWith(1, 'Page.getLayoutMetrics', {})
expect(webContents.debugger.sendCommand).toHaveBeenNthCalledWith(2, 'Page.captureScreenshot', {
format: 'png',
captureBeyondViewport: true,
clip: { x: 0, y: 0, width: 641, height: 1281, scale: 1 }
})
})
it('falls back to legacy contentSize when cssContentSize is unavailable', async () => {
const webContents = createMockWebContents()
webContents.debugger.sendCommand.mockImplementation((method: string) => {
if (method === 'Page.getLayoutMetrics') {
return Promise.resolve({
contentSize: { width: 800, height: 1600 }
})
}
if (method === 'Page.captureScreenshot') {
return Promise.resolve({ data: 'legacy-full-page-data' })
}
return Promise.resolve({})
})
await expect(captureFullPageScreenshot(webContents as never, 'jpeg')).resolves.toEqual({
data: 'legacy-full-page-data',
format: 'jpeg'
})
expect(webContents.debugger.sendCommand).toHaveBeenNthCalledWith(2, 'Page.captureScreenshot', {
format: 'jpeg',
captureBeyondViewport: true,
clip: { x: 0, y: 0, width: 800, height: 1600, scale: 1 }
})
})
})
+264
View File
@@ -0,0 +1,264 @@
import type { WebContents } from 'electron'
const SCREENSHOT_TIMEOUT_MS = 8000
const SCREENSHOT_TIMEOUT_MESSAGE =
'Screenshot timed out — the browser tab may not be visible or the window may not have focus.'
function applyFallbackClip(
image: Electron.NativeImage,
params: Record<string, unknown> | undefined
): Electron.NativeImage | null {
if (params?.captureBeyondViewport) {
// Why: capturePage() can only see the currently painted viewport. If the
// caller asked for beyond-viewport pixels, returning a viewport-sized image
// would silently lie about what was captured.
return null
}
const clip = params?.clip
if (!clip || typeof clip !== 'object') {
return image
}
const clipRect = clip as Record<string, unknown>
const x = typeof clipRect.x === 'number' ? clipRect.x : NaN
const y = typeof clipRect.y === 'number' ? clipRect.y : NaN
const width = typeof clipRect.width === 'number' ? clipRect.width : NaN
const height = typeof clipRect.height === 'number' ? clipRect.height : NaN
const scale =
typeof clipRect.scale === 'number' && Number.isFinite(clipRect.scale) && clipRect.scale > 0
? clipRect.scale
: 1
if (![x, y, width, height].every(Number.isFinite) || width <= 0 || height <= 0) {
return null
}
const cropRect = {
x: Math.round(x * scale),
y: Math.round(y * scale),
width: Math.round(width * scale),
height: Math.round(height * scale)
}
const imageSize = image.getSize()
if (
cropRect.x < 0 ||
cropRect.y < 0 ||
cropRect.width <= 0 ||
cropRect.height <= 0 ||
cropRect.x + cropRect.width > imageSize.width ||
cropRect.y + cropRect.height > imageSize.height
) {
return null
}
return image.crop(cropRect)
}
function encodeNativeImageScreenshot(
image: Electron.NativeImage,
params: Record<string, unknown> | undefined
): { data: string } | null {
if (image.isEmpty()) {
return null
}
const clippedImage = applyFallbackClip(image, params)
if (!clippedImage || clippedImage.isEmpty()) {
return null
}
const format = params?.format === 'jpeg' ? 'jpeg' : 'png'
const quality =
typeof params?.quality === 'number' && Number.isFinite(params.quality)
? Math.max(0, Math.min(100, Math.round(params.quality)))
: undefined
const buffer = format === 'jpeg' ? clippedImage.toJPEG(quality ?? 90) : clippedImage.toPNG()
return { data: buffer.toString('base64') }
}
function getLayoutClip(metrics: {
cssContentSize?: { width?: number; height?: number }
contentSize?: { width?: number; height?: number }
}): { x: number; y: number; width: number; height: number; scale: number } | null {
// Why: Page.captureScreenshot clip coordinates are in CSS pixels. On HiDPI
// Electron guests, `contentSize` can reflect device pixels, which makes
// Chromium tile the page into a duplicated 2x2 grid. Prefer cssContentSize
// and only fall back to contentSize when older Chromium builds omit it.
const size = metrics.cssContentSize ?? metrics.contentSize
const width = size?.width
const height = size?.height
if (
typeof width !== 'number' ||
!Number.isFinite(width) ||
width <= 0 ||
typeof height !== 'number' ||
!Number.isFinite(height) ||
height <= 0
) {
return null
}
return {
x: 0,
y: 0,
width: Math.ceil(width),
height: Math.ceil(height),
scale: 1
}
}
async function sendCommandWithTimeout<T>(
webContents: WebContents,
method: string,
params: Record<string, unknown> | undefined,
timeoutMessage: string
): Promise<T> {
let timer: NodeJS.Timeout | null = null
try {
return await Promise.race([
webContents.debugger.sendCommand(method, params ?? {}) as Promise<T>,
new Promise<T>((_, reject) => {
timer = setTimeout(() => reject(new Error(timeoutMessage)), SCREENSHOT_TIMEOUT_MS)
})
])
} finally {
if (timer) {
clearTimeout(timer)
}
}
}
export async function captureFullPageScreenshot(
webContents: WebContents,
format: 'png' | 'jpeg' = 'png'
): Promise<{ data: string; format: 'png' | 'jpeg' }> {
if (webContents.isDestroyed()) {
throw new Error('WebContents destroyed')
}
const dbg = webContents.debugger
if (!dbg.isAttached()) {
throw new Error('Debugger not attached')
}
try {
webContents.invalidate()
} catch {
// Some guest teardown paths reject repaint requests. Fall through to CDP.
}
const metrics = await sendCommandWithTimeout<{
cssContentSize?: { width?: number; height?: number }
contentSize?: { width?: number; height?: number }
}>(webContents, 'Page.getLayoutMetrics', undefined, SCREENSHOT_TIMEOUT_MESSAGE)
const clip = getLayoutClip(metrics)
if (!clip) {
throw new Error('Unable to determine full-page screenshot bounds')
}
const { data } = await sendCommandWithTimeout<{ data: string }>(
webContents,
'Page.captureScreenshot',
{
format,
captureBeyondViewport: true,
clip
},
SCREENSHOT_TIMEOUT_MESSAGE
)
return { data, format }
}
// Why: Electron's capturePage() is unreliable on webview guests — the compositor
// may not produce frames when the webview panel is inactive, unfocused, or in a
// split-pane layout. Instead, use the debugger's Page.captureScreenshot which
// renders server-side in the Blink compositor and doesn't depend on OS-level
// window focus or display state. Guard with a timeout so agent-browser doesn't
// hang on its 30s CDP timeout if the debugger stalls.
export function captureScreenshot(
webContents: WebContents,
params: Record<string, unknown> | undefined,
onResult: (result: unknown) => void,
onError: (message: string) => void
): void {
if (webContents.isDestroyed()) {
onError('WebContents destroyed')
return
}
const dbg = webContents.debugger
if (!dbg.isAttached()) {
onError('Debugger not attached')
return
}
const screenshotParams: Record<string, unknown> = {}
if (params?.format) {
screenshotParams.format = params.format
}
if (params?.quality) {
screenshotParams.quality = params.quality
}
if (params?.clip) {
screenshotParams.clip = params.clip
}
if (params?.captureBeyondViewport != null) {
screenshotParams.captureBeyondViewport = params.captureBeyondViewport
}
if (params?.fromSurface != null) {
screenshotParams.fromSurface = params.fromSurface
}
let settled = false
// Why: a compositor invalidate is cheap and can recover guest instances that
// are visible but have not produced a fresh frame since being reclaimed into
// the active browser tab.
try {
webContents.invalidate()
} catch {
// Some guest teardown paths reject repaint requests. Fall through to CDP.
}
const timer = setTimeout(async () => {
if (!settled) {
try {
const image = await webContents.capturePage()
if (settled) {
return
}
const fallback = encodeNativeImageScreenshot(image, params)
if (fallback) {
if (settled) {
return
}
settled = true
onResult(fallback)
return
}
} catch {
// Fall through to the original timeout error below.
}
if (!settled) {
settled = true
onError(SCREENSHOT_TIMEOUT_MESSAGE)
}
}
}, SCREENSHOT_TIMEOUT_MS)
dbg
.sendCommand('Page.captureScreenshot', screenshotParams)
.then((result) => {
if (!settled) {
settled = true
clearTimeout(timer)
onResult(result)
}
})
.catch((err) => {
if (!settled) {
settled = true
clearTimeout(timer)
onError((err as Error).message)
}
})
}
+311
View File
@@ -0,0 +1,311 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import WebSocket from 'ws'
import { CdpWsProxy } from './cdp-ws-proxy'
vi.mock('electron', () => ({
webContents: { fromId: vi.fn() }
}))
type DebuggerListener = (...args: unknown[]) => void
function createMockWebContents() {
const listeners = new Map<string, DebuggerListener[]>()
const debuggerObj = {
isAttached: vi.fn(() => false),
attach: vi.fn(),
detach: vi.fn(),
sendCommand: vi.fn(async () => ({})),
on: vi.fn((event: string, handler: DebuggerListener) => {
const arr = listeners.get(event) ?? []
arr.push(handler)
listeners.set(event, arr)
}),
removeListener: vi.fn((event: string, handler: DebuggerListener) => {
const arr = listeners.get(event) ?? []
listeners.set(
event,
arr.filter((h) => h !== handler)
)
})
}
return {
webContents: {
debugger: debuggerObj,
isDestroyed: () => false,
focus: vi.fn(),
getTitle: vi.fn(() => 'Example'),
getURL: vi.fn(() => 'https://example.com')
},
listeners,
emit(event: string, ...args: unknown[]) {
for (const handler of listeners.get(event) ?? []) {
handler(...args)
}
}
}
}
describe('CdpWsProxy', () => {
let mock: ReturnType<typeof createMockWebContents>
let proxy: CdpWsProxy
let endpoint: string
beforeEach(async () => {
mock = createMockWebContents()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
proxy = new CdpWsProxy(mock.webContents as any)
endpoint = await proxy.start()
})
afterEach(async () => {
await proxy.stop()
})
function connect(): Promise<WebSocket> {
return new Promise((resolve) => {
const ws = new WebSocket(endpoint)
ws.on('open', () => resolve(ws))
})
}
function sendAndReceive(
ws: WebSocket,
msg: Record<string, unknown>
): Promise<Record<string, unknown>> {
return new Promise((resolve) => {
ws.once('message', (data) => resolve(JSON.parse(data.toString())))
ws.send(JSON.stringify(msg))
})
}
it('starts on a random port and returns ws:// URL', () => {
expect(endpoint).toMatch(/^ws:\/\/127\.0\.0\.1:\d+$/)
expect(proxy.getPort()).toBeGreaterThan(0)
})
it('attaches debugger on start', () => {
expect(mock.webContents.debugger.attach).toHaveBeenCalledWith('1.3')
})
// ── CDP message ID correlation ──
it('correlates CDP request/response IDs', async () => {
mock.webContents.debugger.sendCommand.mockResolvedValueOnce({ tree: 'nodes' })
const ws = connect()
const client = await ws
const response = await sendAndReceive(client, {
id: 42,
method: 'Accessibility.getFullAXTree',
params: {}
})
expect(response.id).toBe(42)
expect(response.result).toEqual({ tree: 'nodes' })
client.close()
})
it('returns error response when sendCommand fails', async () => {
mock.webContents.debugger.sendCommand.mockRejectedValueOnce(new Error('Node not found'))
const client = await connect()
const response = await sendAndReceive(client, {
id: 7,
method: 'DOM.describeNode',
params: { nodeId: 999 }
})
expect(response.id).toBe(7)
expect(response.error).toEqual({ code: -32000, message: 'Node not found' })
client.close()
})
// ── Concurrent requests get correct responses ──
it('handles concurrent requests with correct correlation', async () => {
let resolveFirst: (v: unknown) => void
const firstPromise = new Promise((r) => {
resolveFirst = r
})
mock.webContents.debugger.sendCommand
.mockImplementationOnce(async () => {
await firstPromise
return { result: 'slow' }
})
.mockResolvedValueOnce({ result: 'fast' })
const client = await connect()
const responses: Record<string, unknown>[] = []
client.on('message', (data) => {
responses.push(JSON.parse(data.toString()))
})
client.send(JSON.stringify({ id: 1, method: 'DOM.enable', params: {} }))
await new Promise((r) => setTimeout(r, 10))
client.send(JSON.stringify({ id: 2, method: 'Page.enable', params: {} }))
await new Promise((r) => setTimeout(r, 20))
resolveFirst!(undefined)
await new Promise((r) => setTimeout(r, 20))
expect(responses).toHaveLength(2)
const resp1 = responses.find((r) => r.id === 1)
const resp2 = responses.find((r) => r.id === 2)
expect(resp1?.result).toEqual({ result: 'slow' })
expect(resp2?.result).toEqual({ result: 'fast' })
client.close()
})
it('does not deliver a late response from a closed client to a newer websocket', async () => {
let resolveSlowCommand: ((value: { result: string }) => void) | null = null
mock.webContents.debugger.sendCommand
.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveSlowCommand = resolve
})
)
.mockResolvedValueOnce({ result: 'new-client' })
const firstClient = await connect()
firstClient.send(JSON.stringify({ id: 1, method: 'DOM.enable', params: {} }))
await new Promise((resolve) => setTimeout(resolve, 10))
const secondClient = await connect()
const responses: Record<string, unknown>[] = []
secondClient.on('message', (data) => {
responses.push(JSON.parse(data.toString()))
})
secondClient.send(JSON.stringify({ id: 2, method: 'Page.enable', params: {} }))
await new Promise((resolve) => setTimeout(resolve, 20))
resolveSlowCommand!({ result: 'old-client' })
await new Promise((resolve) => setTimeout(resolve, 20))
expect(responses).toEqual([{ id: 2, result: { result: 'new-client' } }])
secondClient.close()
})
// ── sessionId envelope translation ──
it('forwards sessionId to sendCommand for OOPIF support', async () => {
mock.webContents.debugger.sendCommand.mockResolvedValueOnce({})
const client = await connect()
await sendAndReceive(client, {
id: 1,
method: 'DOM.enable',
params: {},
sessionId: 'oopif-session-123'
})
expect(mock.webContents.debugger.sendCommand).toHaveBeenCalledWith(
'DOM.enable',
{},
'oopif-session-123'
)
client.close()
})
// ── Event forwarding ──
it('forwards CDP events from debugger to client', async () => {
const client = await connect()
const eventPromise = new Promise<Record<string, unknown>>((resolve) => {
client.on('message', (data) => resolve(JSON.parse(data.toString())))
})
mock.emit('message', {}, 'Console.messageAdded', { entry: { text: 'hello' } })
const event = await eventPromise
expect(event.method).toBe('Console.messageAdded')
expect(event.params).toEqual({ entry: { text: 'hello' } })
client.close()
})
it('forwards sessionId in events when present', async () => {
const client = await connect()
const eventPromise = new Promise<Record<string, unknown>>((resolve) => {
client.on('message', (data) => resolve(JSON.parse(data.toString())))
})
mock.emit('message', {}, 'DOM.nodeInserted', { node: {} }, 'iframe-session-456')
const event = await eventPromise
expect(event.sessionId).toBe('iframe-session-456')
client.close()
})
it('does not focus the guest for Runtime.evaluate polling commands', async () => {
const client = await connect()
await sendAndReceive(client, {
id: 9,
method: 'Runtime.evaluate',
params: { expression: 'document.readyState' }
})
expect(mock.webContents.focus).not.toHaveBeenCalled()
client.close()
})
it('still focuses the guest for Input.insertText', async () => {
const client = await connect()
await sendAndReceive(client, {
id: 10,
method: 'Input.insertText',
params: { text: 'hello' }
})
expect(mock.webContents.focus).toHaveBeenCalledTimes(1)
client.close()
})
// ── Page.frameNavigated interception ──
// ── Cleanup ──
it('detaches debugger and closes server on stop', async () => {
const client = await connect()
await proxy.stop()
expect(mock.webContents.debugger.detach).toHaveBeenCalled()
expect(proxy.getPort()).toBeGreaterThan(0) // port stays set but server is closed
await new Promise<void>((resolve) => {
client.on('close', () => resolve())
if (client.readyState === WebSocket.CLOSED) {
resolve()
}
})
})
it('rejects inflight requests on stop', async () => {
let resolveCommand: (v: unknown) => void
mock.webContents.debugger.sendCommand.mockImplementation(
() =>
new Promise((r) => {
resolveCommand = r as (v: unknown) => void
})
)
const client = await connect()
client.send(JSON.stringify({ id: 1, method: 'Page.enable', params: {} }))
await new Promise((r) => setTimeout(r, 10))
await proxy.stop()
resolveCommand!({})
client.close()
})
})
+301
View File
@@ -0,0 +1,301 @@
import { WebSocketServer, WebSocket } from 'ws'
import { createServer, type Server, type IncomingMessage, type ServerResponse } from 'http'
import type { WebContents } from 'electron'
import { captureScreenshot } from './cdp-screenshot'
export class CdpWsProxy {
private httpServer: Server | null = null
private wss: WebSocketServer | null = null
private client: WebSocket | null = null
private port = 0
private debuggerMessageHandler: ((...args: unknown[]) => void) | null = null
private debuggerDetachHandler: ((...args: unknown[]) => void) | null = null
private attached = false
// Why: agent-browser filters events by sessionId from Target.attachToTarget.
private clientSessionId: string | undefined = undefined
constructor(private readonly webContents: WebContents) {}
async start(): Promise<string> {
await this.attachDebugger()
return new Promise<string>((resolve, reject) => {
this.httpServer = createServer((req, res) => this.handleHttpRequest(req, res))
this.wss = new WebSocketServer({ server: this.httpServer })
this.wss.on('connection', (ws) => {
if (this.client) {
this.client.close()
}
this.client = ws
ws.on('message', (data) => this.handleClientMessage(ws, data.toString()))
ws.on('close', () => {
if (this.client === ws) {
this.client = null
}
})
})
this.httpServer.listen(0, '127.0.0.1', () => {
const addr = this.httpServer!.address()
if (typeof addr === 'object' && addr) {
this.port = addr.port
resolve(`ws://127.0.0.1:${this.port}`)
} else {
reject(new Error('Failed to bind proxy server'))
}
})
this.httpServer.on('error', reject)
})
}
async stop(): Promise<void> {
this.detachDebugger()
if (this.client) {
this.client.close()
this.client = null
}
if (this.wss) {
this.wss.close()
this.wss = null
}
if (this.httpServer) {
this.httpServer.close()
this.httpServer = null
}
}
getPort(): number {
return this.port
}
private send(payload: unknown, client = this.client): void {
if (client?.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(payload))
}
}
private sendResult(clientId: number, result: unknown, client = this.client): void {
this.send({ id: clientId, result }, client)
}
private sendError(clientId: number, message: string, client = this.client): void {
this.send({ id: clientId, error: { code: -32000, message } }, client)
}
private buildTargetInfo(): Record<string, unknown> {
const destroyed = this.webContents.isDestroyed()
return {
targetId: 'orca-proxy-target',
type: 'page',
title: destroyed ? '' : this.webContents.getTitle(),
url: destroyed ? '' : this.webContents.getURL(),
attached: true,
canAccessOpener: false
}
}
private handleHttpRequest(req: IncomingMessage, res: ServerResponse): void {
const url = req.url ?? ''
if (url === '/json/version' || url === '/json/version/') {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(
JSON.stringify({
Browser: 'Orca/CdpWsProxy',
'Protocol-Version': '1.3',
webSocketDebuggerUrl: `ws://127.0.0.1:${this.port}`
})
)
return
}
if (url === '/json' || url === '/json/' || url === '/json/list' || url === '/json/list/') {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(
JSON.stringify([
{
...this.buildTargetInfo(),
id: 'orca-proxy-target',
webSocketDebuggerUrl: `ws://127.0.0.1:${this.port}`
}
])
)
return
}
res.writeHead(404)
res.end()
}
private async attachDebugger(): Promise<void> {
if (this.attached) {
return
}
if (!this.webContents.debugger.isAttached()) {
try {
this.webContents.debugger.attach('1.3')
} catch {
throw new Error('Could not attach debugger. DevTools may already be open for this tab.')
}
}
this.attached = true
this.debuggerMessageHandler = (_event: unknown, ...rest: unknown[]) => {
const [method, params, sessionId] = rest as [
string,
Record<string, unknown>,
string | undefined
]
if (!this.client || this.client.readyState !== WebSocket.OPEN) {
return
}
// Why: Electron passes empty string (not undefined) for root-session events, but
// agent-browser filters events by the sessionId from Target.attachToTarget.
const msg: Record<string, unknown> = { method, params }
msg.sessionId = sessionId || this.clientSessionId
this.client.send(JSON.stringify(msg))
}
this.debuggerDetachHandler = () => {
this.attached = false
this.stop()
}
this.webContents.debugger.on('message', this.debuggerMessageHandler as never)
this.webContents.debugger.on('detach', this.debuggerDetachHandler as never)
}
private detachDebugger(): void {
if (this.debuggerMessageHandler) {
this.webContents.debugger.removeListener('message', this.debuggerMessageHandler as never)
this.debuggerMessageHandler = null
}
if (this.debuggerDetachHandler) {
this.webContents.debugger.removeListener('detach', this.debuggerDetachHandler as never)
this.debuggerDetachHandler = null
}
if (this.attached) {
try {
this.webContents.debugger.detach()
} catch {
/* already detached */
}
this.attached = false
}
}
private handleClientMessage(client: WebSocket, raw: string): void {
let msg: { id?: number; method?: string; params?: Record<string, unknown>; sessionId?: string }
try {
msg = JSON.parse(raw)
} catch {
return
}
if (msg.id == null || !msg.method) {
return
}
const clientId = msg.id
if (msg.method === 'Target.getTargets') {
this.sendResult(clientId, { targetInfos: [this.buildTargetInfo()] }, client)
return
}
if (msg.method === 'Target.getTargetInfo') {
this.sendResult(clientId, { targetInfo: this.buildTargetInfo() }, client)
return
}
if (msg.method === 'Target.setDiscoverTargets' || msg.method === 'Target.detachFromTarget') {
if (msg.method === 'Target.detachFromTarget') {
this.clientSessionId = undefined
}
this.sendResult(clientId, {}, client)
return
}
if (msg.method === 'Target.attachToTarget') {
this.clientSessionId = 'orca-proxy-session'
this.sendResult(clientId, { sessionId: this.clientSessionId }, client)
return
}
if (msg.method === 'Browser.getVersion') {
this.sendResult(
clientId,
{
protocolVersion: '1.3',
product: 'Orca/Electron',
userAgent: '',
jsVersion: ''
},
client
)
return
}
if (msg.method === 'Page.bringToFront') {
if (!this.webContents.isDestroyed()) {
this.webContents.focus()
}
this.sendResult(clientId, {}, client)
return
}
// Why: Page.captureScreenshot via debugger.sendCommand hangs on Electron webview guests.
if (msg.method === 'Page.captureScreenshot') {
this.handleScreenshot(client, clientId, msg.params)
return
}
// Why: Input.insertText can still require native focus in Electron webviews.
// Do not auto-focus generic Runtime.evaluate/callFunctionOn traffic: wait
// polling and read-only JS probes use those methods heavily, and focusing on
// every eval steals the user's foreground window while background automation
// is running.
if (msg.method === 'Input.insertText' && !this.webContents.isDestroyed()) {
this.webContents.focus()
}
// Why: agent-browser waits for network idle to detect navigation completion.
// Electron webview CDP subscriptions silently lapse after cross-process swaps.
if (msg.method === 'Page.navigate' && !this.webContents.isDestroyed()) {
void this.navigateWithLifecycleEnsured(client, clientId, msg.params ?? {})
return
}
this.forwardCommand(client, clientId, msg.method, msg.params ?? {}, msg.sessionId)
}
private forwardCommand(
client: WebSocket,
clientId: number,
method: string,
params: Record<string, unknown>,
msgSessionId?: string
): void {
const sessionId =
msgSessionId && msgSessionId !== this.clientSessionId ? msgSessionId : undefined
this.webContents.debugger
.sendCommand(method, params, sessionId)
.then((result) => {
this.sendResult(clientId, result, client)
})
.catch((err: Error) => {
this.sendError(clientId, err.message, client)
})
}
private async navigateWithLifecycleEnsured(
client: WebSocket,
clientId: number,
params: Record<string, unknown>
): Promise<void> {
try {
const dbg = this.webContents.debugger
// Why: without Network.enable, agent-browser never sees network idle → goto times out.
await dbg.sendCommand('Network.enable', {})
await dbg.sendCommand('Page.enable', {})
await dbg.sendCommand('Page.setLifecycleEventsEnabled', { enabled: true })
} catch {
/* best-effort */
}
this.forwardCommand(client, clientId, 'Page.navigate', params)
}
private handleScreenshot(
client: WebSocket,
clientId: number,
params?: Record<string, unknown>
): void {
captureScreenshot(
this.webContents,
params,
(result) => this.sendResult(clientId, result, client),
(message) => this.sendError(clientId, message, client)
)
}
}
+196
View File
@@ -0,0 +1,196 @@
import { describe, expect, it, vi } from 'vitest'
import { buildSnapshot, type CdpCommandSender } from './snapshot-engine'
type AXNode = {
nodeId: string
backendDOMNodeId?: number
role?: { type: string; value: string }
name?: { type: string; value: string }
properties?: { name: string; value: { type: string; value: unknown } }[]
childIds?: string[]
ignored?: boolean
}
function makeSender(nodes: AXNode[]): CdpCommandSender {
return vi.fn(async (method: string) => {
if (method === 'Accessibility.enable') {
return {}
}
if (method === 'Accessibility.getFullAXTree') {
return { nodes }
}
throw new Error(`Unexpected CDP method: ${method}`)
})
}
function node(
id: string,
role: string,
name: string,
opts?: {
childIds?: string[]
backendDOMNodeId?: number
ignored?: boolean
properties?: AXNode['properties']
}
): AXNode {
return {
nodeId: id,
backendDOMNodeId: opts?.backendDOMNodeId ?? parseInt(id, 10),
role: { type: 'role', value: role },
name: { type: 'computedString', value: name },
childIds: opts?.childIds,
ignored: opts?.ignored,
properties: opts?.properties
}
}
describe('buildSnapshot', () => {
it('returns empty snapshot for empty tree', async () => {
const result = await buildSnapshot(makeSender([]))
expect(result.snapshot).toBe('')
expect(result.refs).toEqual([])
expect(result.refMap.size).toBe(0)
})
it('assigns refs to interactive elements', async () => {
const nodes: AXNode[] = [
node('1', 'WebArea', 'page', { childIds: ['2', '3'] }),
node('2', 'button', 'Submit', { backendDOMNodeId: 10 }),
node('3', 'link', 'Home', { backendDOMNodeId: 11 })
]
const result = await buildSnapshot(makeSender(nodes))
expect(result.refs).toHaveLength(2)
expect(result.refs[0]).toEqual({ ref: '@e1', role: 'button', name: 'Submit' })
expect(result.refs[1]).toEqual({ ref: '@e2', role: 'link', name: 'Home' })
expect(result.snapshot).toContain('[@e1] button "Submit"')
expect(result.snapshot).toContain('[@e2] link "Home"')
})
it('renders text inputs with friendly role name', async () => {
const nodes: AXNode[] = [
node('1', 'WebArea', 'page', { childIds: ['2'] }),
node('2', 'textbox', 'Email', { backendDOMNodeId: 10 })
]
const result = await buildSnapshot(makeSender(nodes))
expect(result.snapshot).toContain('text input "Email"')
})
it('renders landmarks without refs', async () => {
const nodes: AXNode[] = [
node('1', 'WebArea', 'page', { childIds: ['2'] }),
node('2', 'navigation', 'Main Nav', { childIds: ['3'] }),
node('3', 'link', 'About', { backendDOMNodeId: 10 })
]
const result = await buildSnapshot(makeSender(nodes))
expect(result.snapshot).toContain('[Main Nav]')
expect(result.refs).toHaveLength(1)
expect(result.refs[0].name).toBe('About')
})
it('renders headings without refs', async () => {
const nodes: AXNode[] = [
node('1', 'WebArea', 'page', { childIds: ['2'] }),
node('2', 'heading', 'Welcome')
]
const result = await buildSnapshot(makeSender(nodes))
expect(result.snapshot).toContain('heading "Welcome"')
expect(result.refs).toHaveLength(0)
})
it('renders static text without refs', async () => {
const nodes: AXNode[] = [
node('1', 'WebArea', 'page', { childIds: ['2'] }),
node('2', 'staticText', 'Hello world')
]
const result = await buildSnapshot(makeSender(nodes))
expect(result.snapshot).toContain('text "Hello world"')
expect(result.refs).toHaveLength(0)
})
it('skips generic/none/presentation roles', async () => {
const nodes: AXNode[] = [
node('1', 'WebArea', 'page', { childIds: ['2'] }),
node('2', 'generic', '', { childIds: ['3'] }),
node('3', 'button', 'OK', { backendDOMNodeId: 10 })
]
const result = await buildSnapshot(makeSender(nodes))
expect(result.refs).toHaveLength(1)
expect(result.refs[0].name).toBe('OK')
expect(result.snapshot).not.toContain('generic')
})
it('skips ignored nodes but walks their children', async () => {
const nodes: AXNode[] = [
node('1', 'WebArea', 'page', { childIds: ['2'] }),
node('2', 'group', 'ignored group', { childIds: ['3'], ignored: true }),
node('3', 'button', 'Deep', { backendDOMNodeId: 10 })
]
const result = await buildSnapshot(makeSender(nodes))
expect(result.refs).toHaveLength(1)
expect(result.refs[0].name).toBe('Deep')
})
it('skips interactive elements without a name', async () => {
const nodes: AXNode[] = [
node('1', 'WebArea', 'page', { childIds: ['2', '3'] }),
node('2', 'button', '', { backendDOMNodeId: 10 }),
node('3', 'button', 'Labeled', { backendDOMNodeId: 11 })
]
const result = await buildSnapshot(makeSender(nodes))
expect(result.refs).toHaveLength(1)
expect(result.refs[0].name).toBe('Labeled')
})
it('populates refMap with backendDOMNodeId', async () => {
const nodes: AXNode[] = [
node('1', 'WebArea', 'page', { childIds: ['2'] }),
node('2', 'checkbox', 'Agree', { backendDOMNodeId: 42 })
]
const result = await buildSnapshot(makeSender(nodes))
const entry = result.refMap.get('@e1')
expect(entry).toBeDefined()
expect(entry!.backendDOMNodeId).toBe(42)
expect(entry!.role).toBe('checkbox')
expect(entry!.name).toBe('Agree')
})
it('indents children under landmarks', async () => {
const nodes: AXNode[] = [
node('1', 'WebArea', 'page', { childIds: ['2'] }),
node('2', 'main', '', { childIds: ['3'] }),
node('3', 'button', 'Action', { backendDOMNodeId: 10 })
]
const result = await buildSnapshot(makeSender(nodes))
const lines = result.snapshot.split('\n')
const mainLine = lines.find((l) => l.includes('[Main Content]'))
const buttonLine = lines.find((l) => l.includes('Action'))
expect(mainLine).toBeDefined()
expect(buttonLine).toBeDefined()
expect(buttonLine!.startsWith(' ')).toBe(true)
})
it('handles a realistic page structure', async () => {
const nodes: AXNode[] = [
node('1', 'WebArea', 'page', { childIds: ['2', '3', '4'] }),
node('2', 'banner', '', { childIds: ['5'] }),
node('3', 'main', '', { childIds: ['6', '7', '8'] }),
node('4', 'contentinfo', '', {}),
node('5', 'link', 'Logo', { backendDOMNodeId: 10 }),
node('6', 'heading', 'Dashboard'),
node('7', 'textbox', 'Search', { backendDOMNodeId: 20 }),
node('8', 'button', 'Go', { backendDOMNodeId: 21 })
]
const result = await buildSnapshot(makeSender(nodes))
expect(result.refs).toHaveLength(3)
expect(result.refs.map((r) => r.name)).toEqual(['Logo', 'Search', 'Go'])
expect(result.snapshot).toContain('[Header]')
expect(result.snapshot).toContain('[Main Content]')
expect(result.snapshot).toContain('[Footer]')
expect(result.snapshot).toContain('heading "Dashboard"')
})
})
+451
View File
@@ -0,0 +1,451 @@
/* eslint-disable max-lines -- Why: snapshot building, AX tree walking, ref mapping, and cursor-interactive detection are tightly coupled and belong in one module. */
import type { BrowserSnapshotRef } from '../../shared/runtime-types'
export type CdpCommandSender = (
method: string,
params?: Record<string, unknown>
) => Promise<unknown>
type AXNode = {
nodeId: string
backendDOMNodeId?: number
role?: { type: string; value: string }
name?: { type: string; value: string }
properties?: { name: string; value: { type: string; value: unknown } }[]
childIds?: string[]
ignored?: boolean
}
type SnapshotEntry = {
ref: string
role: string
name: string
backendDOMNodeId: number
depth: number
}
export type RefEntry = {
backendDOMNodeId: number
role: string
name: string
sessionId?: string
// Why: when multiple elements share the same role+name, nth tracks which
// occurrence this ref represents (1-indexed). Used during stale ref recovery
// to disambiguate duplicates.
nth?: number
}
export type SnapshotResult = {
snapshot: string
refs: BrowserSnapshotRef[]
refMap: Map<string, RefEntry>
}
const INTERACTIVE_ROLES = new Set([
'button',
'link',
'textbox',
'searchbox',
'combobox',
'checkbox',
'radio',
'switch',
'slider',
'spinbutton',
'menuitem',
'menuitemcheckbox',
'menuitemradio',
'tab',
'option',
'treeitem'
])
const LANDMARK_ROLES = new Set([
'banner',
'navigation',
'main',
'complementary',
'contentinfo',
'region',
'form',
'search'
])
const HEADING_PATTERN = /^heading$/
const SKIP_ROLES = new Set(['none', 'presentation', 'generic'])
export async function buildSnapshot(
sendCommand: CdpCommandSender,
iframeSessions?: Map<string, string>,
makeIframeSender?: (sessionId: string) => CdpCommandSender
): Promise<SnapshotResult> {
await sendCommand('Accessibility.enable')
const { nodes } = (await sendCommand('Accessibility.getFullAXTree')) as { nodes: AXNode[] }
const nodeById = new Map<string, AXNode>()
for (const node of nodes) {
nodeById.set(node.nodeId, node)
}
const entries: SnapshotEntry[] = []
let refCounter = 1
const root = nodes[0]
if (!root) {
return { snapshot: '', refs: [], refMap: new Map() }
}
walkTree(root, nodeById, 0, entries, () => refCounter++)
// Why: many modern SPAs use styled <div>s, <span>s, and custom elements as
// interactive controls without proper ARIA roles. These elements are invisible
// to the accessibility tree walk above but are clearly interactive (cursor:pointer,
// onclick, tabindex, contenteditable). This DOM query pass discovers them and
// promotes them to interactive refs so the agent can interact with them.
const cursorInteractiveEntries = await findCursorInteractiveElements(sendCommand, entries)
for (const cie of cursorInteractiveEntries) {
cie.ref = `@e${refCounter++}`
entries.push(cie)
}
// Why: cross-origin iframes have their own AX trees accessible only through
// their dedicated CDP session. Append their elements after the parent tree
// so the agent can see and interact with iframe content.
const iframeRefSessions: { ref: string; sessionId: string }[] = []
if (iframeSessions && makeIframeSender && iframeSessions.size > 0) {
for (const [_frameId, sessionId] of iframeSessions) {
try {
const iframeSender = makeIframeSender(sessionId)
await iframeSender('Accessibility.enable')
const { nodes: iframeNodes } = (await iframeSender('Accessibility.getFullAXTree')) as {
nodes: AXNode[]
}
if (iframeNodes.length === 0) {
continue
}
const iframeNodeById = new Map<string, AXNode>()
for (const n of iframeNodes) {
iframeNodeById.set(n.nodeId, n)
}
const iframeRoot = iframeNodes[0]
if (iframeRoot) {
const startRef = refCounter
walkTree(iframeRoot, iframeNodeById, 1, entries, () => refCounter++)
for (let i = startRef; i < refCounter; i++) {
iframeRefSessions.push({ ref: `@e${i}`, sessionId })
}
}
} catch {
// Iframe session may be stale — skip silently
}
}
}
const refMap = new Map<string, RefEntry>()
const refs: BrowserSnapshotRef[] = []
const lines: string[] = []
// Why: when multiple elements share the same role+name (e.g. 3 "Submit"
// buttons), the agent can't distinguish them from text alone. Appending a
// disambiguation suffix like "(2nd)" lets the agent refer to duplicates.
const nameCounts = new Map<string, number>()
const nameOccurrence = new Map<string, number>()
for (const entry of entries) {
if (entry.ref) {
const key = `${entry.role}:${entry.name}`
nameCounts.set(key, (nameCounts.get(key) ?? 0) + 1)
}
}
for (const entry of entries) {
const indent = ' '.repeat(entry.depth)
if (entry.ref) {
const key = `${entry.role}:${entry.name}`
const total = nameCounts.get(key) ?? 1
let displayName = entry.name
const nth = (nameOccurrence.get(key) ?? 0) + 1
nameOccurrence.set(key, nth)
if (total > 1 && nth > 1) {
displayName = `${entry.name} (${ordinal(nth)})`
}
lines.push(`${indent}[${entry.ref}] ${entry.role} "${displayName}"`)
refs.push({ ref: entry.ref, role: entry.role, name: displayName })
const iframeSession = iframeRefSessions.find((s) => s.ref === entry.ref)
refMap.set(entry.ref, {
backendDOMNodeId: entry.backendDOMNodeId,
role: entry.role,
name: entry.name,
sessionId: iframeSession?.sessionId,
nth: total > 1 ? nth : undefined
})
} else {
lines.push(`${indent}${entry.role} "${entry.name}"`)
}
}
return { snapshot: lines.join('\n'), refs, refMap }
}
function walkTree(
node: AXNode,
nodeById: Map<string, AXNode>,
depth: number,
entries: SnapshotEntry[],
nextRef: () => number
): void {
if (node.ignored) {
walkChildren(node, nodeById, depth, entries, nextRef)
return
}
const role = node.role?.value ?? ''
const name = node.name?.value ?? ''
if (SKIP_ROLES.has(role)) {
walkChildren(node, nodeById, depth, entries, nextRef)
return
}
const isInteractive = INTERACTIVE_ROLES.has(role)
const isHeading = HEADING_PATTERN.test(role)
const isLandmark = LANDMARK_ROLES.has(role)
const isStaticText = role === 'staticText' || role === 'StaticText'
if (!isInteractive && !isHeading && !isLandmark && !isStaticText) {
walkChildren(node, nodeById, depth, entries, nextRef)
return
}
if (!name && !isLandmark) {
walkChildren(node, nodeById, depth, entries, nextRef)
return
}
const hasFocusable = isInteractive && isFocusable(node)
if (isLandmark) {
entries.push({
ref: '',
role: formatLandmarkRole(role, name),
name: name || role,
backendDOMNodeId: node.backendDOMNodeId ?? 0,
depth
})
walkChildren(node, nodeById, depth + 1, entries, nextRef)
return
}
if (isHeading) {
entries.push({
ref: '',
role: 'heading',
name,
backendDOMNodeId: node.backendDOMNodeId ?? 0,
depth
})
return
}
if (isStaticText && name.trim().length > 0) {
entries.push({
ref: '',
role: 'text',
name: name.trim(),
backendDOMNodeId: node.backendDOMNodeId ?? 0,
depth
})
return
}
if (isInteractive && (hasFocusable || node.backendDOMNodeId)) {
const ref = `@e${nextRef()}`
entries.push({
ref,
role: formatInteractiveRole(role),
name: name || '(unlabeled)',
backendDOMNodeId: node.backendDOMNodeId ?? 0,
depth
})
return
}
walkChildren(node, nodeById, depth, entries, nextRef)
}
function walkChildren(
node: AXNode,
nodeById: Map<string, AXNode>,
depth: number,
entries: SnapshotEntry[],
nextRef: () => number
): void {
if (!node.childIds) {
return
}
for (const childId of node.childIds) {
const child = nodeById.get(childId)
if (child) {
walkTree(child, nodeById, depth, entries, nextRef)
}
}
}
function isFocusable(node: AXNode): boolean {
if (!node.properties) {
return true
}
const focusable = node.properties.find((p) => p.name === 'focusable')
if (focusable && focusable.value.value === false) {
return false
}
return true
}
function formatInteractiveRole(role: string): string {
switch (role) {
case 'textbox':
case 'searchbox':
return 'text input'
case 'combobox':
return 'combobox'
case 'menuitem':
case 'menuitemcheckbox':
case 'menuitemradio':
return 'menu item'
case 'spinbutton':
return 'number input'
case 'treeitem':
return 'tree item'
default:
return role
}
}
function formatLandmarkRole(role: string, name: string): string {
if (name) {
return `[${name}]`
}
switch (role) {
case 'banner':
return '[Header]'
case 'navigation':
return '[Navigation]'
case 'main':
return '[Main Content]'
case 'complementary':
return '[Sidebar]'
case 'contentinfo':
return '[Footer]'
case 'search':
return '[Search]'
default:
return `[${role}]`
}
}
function ordinal(n: number): string {
const s = ['th', 'st', 'nd', 'rd']
const v = n % 100
return `${n}${s[(v - 20) % 10] || s[v] || s[0]}`
}
// Why: finds DOM elements that are visually interactive (cursor:pointer, onclick,
// tabindex, contenteditable) but lack standard ARIA roles. These are common in
// modern SPAs where styled <div>s act as buttons. Returns them as a JS array of
// remote object references that we can resolve to backendNodeIds via CDP.
async function findCursorInteractiveElements(
sendCommand: CdpCommandSender,
existingEntries: SnapshotEntry[]
): Promise<SnapshotEntry[]> {
const existingNodeIds = new Set(existingEntries.map((e) => e.backendDOMNodeId))
const results: SnapshotEntry[] = []
try {
// Single evaluate call that finds interactive elements and returns their info
// along with a way to reference them by index
const { result } = (await sendCommand('Runtime.evaluate', {
expression: `(() => {
const SKIP_ROLES = new Set(['button','link','textbox','checkbox','radio','tab',
'menuitem','option','switch','slider','combobox','searchbox','spinbutton','treeitem',
'menuitemcheckbox','menuitemradio']);
const SKIP_TAGS = new Set(['input','button','select','textarea','a']);
const seen = new Set();
const found = [];
const matchedElements = [];
function check(el) {
if (seen.has(el)) return;
seen.add(el);
const tag = el.tagName.toLowerCase();
if (SKIP_TAGS.has(tag)) return;
const role = el.getAttribute('role');
if (role && SKIP_ROLES.has(role)) return;
const rect = el.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) return;
const text = (el.ariaLabel || el.getAttribute('aria-label') || el.textContent || '').trim().slice(0, 80);
if (!text) return;
found.push({ text, tag });
matchedElements.push(el);
if (found.length >= 50) return;
}
document.querySelectorAll('[onclick], [tabindex]:not([tabindex="-1"]), [contenteditable="true"]').forEach(el => {
if (found.length < 50) check(el);
});
document.querySelectorAll('div, span, li, td, img, svg, label').forEach(el => {
if (found.length >= 50) return;
try {
if (window.getComputedStyle(el).cursor === 'pointer') check(el);
} catch {}
});
window.__orcaCursorInteractive = matchedElements;
return JSON.stringify(found);
})()`,
returnByValue: true
})) as { result: { value: string } }
const elements = JSON.parse(result.value) as { text: string; tag: string }[]
for (let i = 0; i < elements.length; i++) {
try {
const { result: objResult } = (await sendCommand('Runtime.evaluate', {
expression: `window.__orcaCursorInteractive[${i}]`
})) as { result: { objectId?: string } }
if (!objResult.objectId) {
continue
}
const { node } = (await sendCommand('DOM.describeNode', {
objectId: objResult.objectId
})) as { node: { backendNodeId: number } }
if (existingNodeIds.has(node.backendNodeId)) {
continue
}
results.push({
ref: '',
role: 'clickable',
name: elements[i].text,
backendDOMNodeId: node.backendNodeId,
depth: 0
})
} catch {
continue
}
}
// Clean up
await sendCommand('Runtime.evaluate', {
expression: 'delete window.__orcaCursorInteractive',
returnByValue: true
})
} catch {
// DOM query failed — not critical, just return empty
}
return results
}