Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 103 additions & 22 deletions apps/desktop/src/main/browser-agent/driver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1020,32 +1020,113 @@ describe('executeTool', () => {
}
)

it('waits for a tab still loading its first page instead of calling it blank', async () => {
await driver.executeTool('chat-test', 'browser_open_tab', {})
const contents = session.requireTab().view.webContents
vi.mocked(contents.getURL).mockReturnValue('')
vi.mocked(contents.isLoading).mockReturnValue(true)
const loadListeners = () =>
vi
.mocked(contents.on)
.mock.calls.filter(([event]) => String(event) === 'did-stop-loading')
.map(([, listener]) => listener as () => void)
const registered = loadListeners().length
const evaluated = new Promise<void>((resolve) => {
vi.mocked(contents.executeJavaScript).mockImplementation(() => {
resolve()
return new Promise<never>(() => {})
describe('a tab still loading its first page', () => {
const openLoadingTab = async () => {
await driver.executeTool('chat-test', 'browser_open_tab', {})
const contents = session.requireTab().view.webContents
vi.mocked(contents.getURL).mockReturnValue('')
vi.mocked(contents.isLoading).mockReturnValue(true)
const listeners = (event: string) =>
vi
.mocked(contents.on)
.mock.calls.filter(([name]) => String(name) === event)
.map(([, listener]) => listener as (...args: unknown[]) => void)
const registered = listeners('did-stop-loading').length
const waiting = () =>
vi.waitFor(() => expect(listeners('did-stop-loading').length).toBeGreaterThan(registered))
return { contents, listeners, registered, waiting }
}

it('snapshots the page once it commits instead of calling the tab blank', async () => {
const { contents, listeners, registered, waiting } = await openLoadingTab()
vi.mocked(contents.executeJavaScript).mockResolvedValue({
url: 'http://127.0.0.1/popup',
title: 'popup',
outline: '- link "Open popup" [ref=0]',
truncated: false,
refIds: [0],
refLineIndexes: { 0: 0 },
nextElementId: 1,
})

const snapshot = driver.executeTool('chat-test', 'browser_snapshot', {})
await waiting()
expect(contents.executeJavaScript).not.toHaveBeenCalled()

vi.mocked(contents.getURL).mockReturnValue('http://127.0.0.1/popup')
vi.mocked(contents.isLoading).mockReturnValue(false)
for (const onNavigate of listeners('did-navigate')) onNavigate({}, 'http://127.0.0.1/popup')
for (const onLoaded of listeners('did-stop-loading').slice(registered)) onLoaded()

await expect(snapshot).resolves.toMatchObject({
ok: true,
result: { outline: expect.stringContaining('Open popup') },
})
})

it('never acts on the page when the action is cancelled during the wait', async () => {
const { contents, listeners, registered, waiting } = await openLoadingTab()

const scroll = driver.executeTool(
'chat-test',
'browser_scroll',
{ direction: 'down' },
'scroll-into-loading-popup'
)
await waiting()
expect(driver.cancelTool('chat-test', 'scroll-into-loading-popup')).toBe(true)
await expect(scroll).resolves.toMatchObject({
ok: false,
error: expect.stringContaining('cancelled'),
})

// The page commits after the cancel; a wait that ignored the cancel would act on it now.
vi.mocked(contents.getURL).mockReturnValue('http://127.0.0.1/popup')
vi.mocked(contents.isLoading).mockReturnValue(false)
for (const onLoaded of listeners('did-stop-loading').slice(registered)) onLoaded()
await driver.executeTool('chat-test', 'browser_list_tabs', {})
expect(contents.executeJavaScript).not.toHaveBeenCalled()
expect(contents.debugger.sendCommand).not.toHaveBeenCalledWith(
'Input.dispatchMouseEvent',
expect.anything()
)
})

void driver.executeTool('chat-test', 'browser_snapshot', {})
await vi.waitFor(() => expect(loadListeners().length).toBeGreaterThan(registered))
expect(contents.executeJavaScript).not.toHaveBeenCalled()
it('refuses a page that outlasts the bounded wait, and never acts on it once it loads', async () => {
const { contents, listeners, registered } = await openLoadingTab()
const watchdogMs = driver.browserToolWatchdogMs('browser_scroll', { direction: 'down' })
const navigationTimeoutMs = 25_000
const waitMs =
watchdogMs === null
? navigationTimeoutMs
: Math.min(navigationTimeoutMs, Math.floor(watchdogMs / 2))
vi.useFakeTimers()
try {
let outcome: unknown
void driver
.executeTool('chat-test', 'browser_scroll', { direction: 'down' }, 'scroll-slow-popup')
.then((result) => {
outcome = result
})
await vi.advanceTimersByTimeAsync(0)
expect(listeners('did-stop-loading').length).toBeGreaterThan(registered)

await vi.advanceTimersByTimeAsync(waitMs + 1)
expect(outcome).toEqual({
ok: false,
error:
'The active tab is blank. Call browser_navigate before using page inspection or interaction tools.',
})

vi.mocked(contents.getURL).mockReturnValue('http://127.0.0.1/popup')
vi.mocked(contents.isLoading).mockReturnValue(false)
for (const onLoadComplete of loadListeners().slice(registered)) onLoadComplete()
await evaluated
vi.mocked(contents.getURL).mockReturnValue('http://127.0.0.1/popup')
vi.mocked(contents.isLoading).mockReturnValue(false)
for (const onLoaded of listeners('did-stop-loading').slice(registered)) onLoaded()
await vi.advanceTimersByTimeAsync(0)
expect(contents.executeJavaScript).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
})
})

it('leaves no watchdog timer pending once a tool finishes', async () => {
Expand Down
83 changes: 75 additions & 8 deletions apps/desktop/src/main/browser-agent/driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1385,13 +1385,8 @@ async function execInPage<Args extends unknown[], Result>(
userGesture = false,
notAfter?: number
): Promise<Result> {
const isBlank = (url: string) => url === '' || url === 'about:blank'
// A tab a link or popup just opened reports no URL until its first page commits.
if ('getURL' in target && isBlank(target.getURL()) && target.isLoading()) {
const remaining = notAfter === undefined ? NAVIGATION_TIMEOUT_MS : notAfter - Date.now()
await waitForLoadComplete(target, Math.max(0, Math.min(NAVIGATION_TIMEOUT_MS, remaining)))
}
if ('getURL' in target && isBlank(target.getURL())) {
const url = 'getURL' in target ? target.getURL() : target.url
if ('getURL' in target && (url === '' || url === 'about:blank')) {
throw new ToolError(
'The active tab is blank. Call browser_navigate before using page inspection or interaction tools.'
)
Expand Down Expand Up @@ -1638,11 +1633,16 @@ function unwrapPageResult(result: unknown): unknown {
return result
}

function waitForLoadComplete(contents: WebContents, timeoutMs: number): Promise<void> {
function waitForLoadComplete(
contents: WebContents,
timeoutMs: number,
signal?: AbortSignal
): Promise<void> {
return new Promise((resolve, reject) => {
let settled = false
let sawStart = contents.isLoading()
const cleanup = () => {
signal?.removeEventListener('abort', finish)
contents.removeListener('did-start-loading', start)
contents.removeListener('did-stop-loading', finish)
contents.removeListener('did-fail-load', fail)
Expand Down Expand Up @@ -1693,9 +1693,60 @@ function waitForLoadComplete(contents: WebContents, timeoutMs: number): Promise<
contents.on('did-stop-loading', finish)
contents.on('did-fail-load', fail)
contents.on('destroyed', destroyed)
signal?.addEventListener('abort', finish)
})
}

/** Tools that read or act in the page itself, which a tab with no page yet cannot serve. */
const BROWSER_TOOL_USES_PAGE = {
browser_navigate: false,
browser_open_url: false,
browser_go_back: false,
browser_go_forward: false,
browser_reload: false,
browser_open_tab: false,
browser_switch_tab: false,
browser_close_tab: false,
browser_list_tabs: false,
browser_list_sessions: false,
browser_list_downloads: false,
browser_save_download: false,
browser_wait_for: true,
browser_snapshot: true,
browser_find: true,
browser_read_text: true,
browser_screenshot: true,
browser_extract: true,
browser_click: true,
browser_click_at: true,
browser_type: true,
browser_fill_form: true,
browser_batch: true,
browser_insert_text: true,
browser_press_key: true,
browser_scroll: true,
browser_select_option: true,
browser_set_checked: true,
browser_upload_file: true,
browser_hover: true,
browser_drag: true,
browser_zoom: false,
browser_request_takeover: false,
} as const satisfies Readonly<Record<BrowserToolName, boolean>>

/**
* A tab a link or popup just opened reports no URL until its first page commits, so a page tool
* reaching it first would refuse it as blank. Returns the wait for that first load, run before the
* action records any page state, or null when the agent's tab already has a page.
*/
function firstPageLoad(signal: AbortSignal, maxWaitMs: number): Promise<void> | null {
const contents = session.automationTab()?.view.webContents
if (!contents || contents.isDestroyed() || !contents.isLoading()) return null
const url = contents.getURL()
if (url !== '' && url !== 'about:blank') return null
return waitForLoadComplete(contents, maxWaitMs, signal)
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
}

async function navigationResult(
contents: WebContents,
completion = waitForLoadComplete(contents, NAVIGATION_TIMEOUT_MS)
Expand Down Expand Up @@ -5459,6 +5510,22 @@ export async function executeTool(
: Math.min(USER_TAKEOVER_MAX_WAIT_MS, Math.floor(watchdogMs / 2))
)
}
const firstPage = BROWSER_TOOL_USES_PAGE[tool]
? firstPageLoad(
executionController.signal,
watchdogMs === null
? NAVIGATION_TIMEOUT_MS
: Math.min(NAVIGATION_TIMEOUT_MS, Math.floor(watchdogMs / 2))
)
: null
if (firstPage) {
// Raced with the cancellation so its rejection is observed; a cancel aborts the wait
// before it rejects, which is why the abort is checked again afterwards.
await Promise.race([firstPage, cancellation])
if (executionController.signal.aborted) {
throw new ToolError('This browser action was cancelled.')
}
}
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
const response = dialogResponse(tool, params)
state.dialogResponse = response
? { contents: session.requireAutomationTab().view.webContents, response }
Expand Down
Loading