Open-source AI browser agent for Chrome and Firefox (monorepo) ðŸ§
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
fix(cdp): dismiss unapproved dialogs and scope Leave to authorized navigation
Emre Sokullu43976bf1b1ae
diff --git a/docs/architecture.md b/docs/architecture.mdindex 400015b72..a342aedaf 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -816,19 +816,24 @@ Wraps `chrome.debugger` API for:During active Chrome Act/Dev runs (including saved workflow replay), nativeJavaScript dialogs are continued through `Page.javascriptDialogOpening` and-`Page.handleJavaScriptDialog`. Alerts and confirmations are accepted;-`beforeunload` warnings choose Leave; prompts use the site's default text (or-an empty string when no default exists). This includes accepting confirmation-of the pending page action and potentially discarding unsaved changes. Dialog-text is never interpreted as instructions. The event handler runs independently-of blocked renderer commands, and is removed on Stop, completion, or detach,-even when Dev diagnostics keep the debugger attached. Ask mode and idle tabs-do not auto-answer dialogs. Already-observed dialogs are resolved before-startup commands, so retained Dev connections can resume them. Chrome does not-expose a dialog opened before debugger attachment to the new session; dismiss-that existing dialog manually. Dialog setup responds to Stop and times out after-five seconds rather than holding the run indefinitely. Existing action permission-checks still apply.+`Page.handleJavaScriptDialog`. Alerts are acknowledged; confirmations and text+prompts are dismissed. A dialog event cannot prove which click triggered it,+so a running task or an input command in flight never grants permission to+accept a confirmation. Cached dialogs from idle time are also dismissed.++A `beforeunload` warning chooses Leave only for a one-use navigation permission+created immediately before the navigation tool dispatches, after its existing+permission and unsaved-change checks. The warning must come from the same+top-level source URL. The permission expires on the first accepted warning,+navigation completion/failure, cancellation, or after ten seconds. Other+navigation warnings choose Stay. Dialog text is never treated as instructions.++The handler runs independently of blocked page commands and is removed on+Stop, completion, or detach, even when Dev diagnostics retain the debugger.+Ask mode and idle tabs do not auto-answer dialogs. Already-observed dialogs are+resolved before startup commands. Dialogs opened before debugger attachment+may need manual dismissal. Startup responds to Stop and times out after five+seconds instead of holding the run indefinitely.This does not handle browser permission requests, authentication windows, orOS file pickers. Firefox WebExtensions provide no equivalent native-dialog API;those dialogs still require manual handling in Firefox.diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex 159e11f3e..a2ee1b033 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -33336,6 +33336,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// only proves that a navigation started. For a same-URL or round-trip// redirect, require a real top-frame document commit before claiming// success over the unchanged URL readback.+ let releaseDialogNavigation = () => {};let navigationCommitObserved = false;let navigationLoadingObserved = false;let navigationTerminalResult = null;@@ -33343,6 +33344,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst navigationTerminal = new Promise(resolve => { resolveNavigationTerminal = resolve; });const finishNavigationTerminal = (result) => {if (navigationTerminalResult) return;+ releaseDialogNavigation();navigationTerminalResult = result;resolveNavigationTerminal(result);};@@ -33409,12 +33411,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (navigationTabListener) {try { tabUpdateEvent.removeListener(navigationTabListener); } catch {}}+ releaseDialogNavigation();navigationCommitListener = null;navigationErrorListener = null;navigationTabListener = null;};try {+ releaseDialogNavigation = cdpClient.authorizeNavigationDialog(tabId, beforeUrl, earlyCdpAbortSignal);await chrome.tabs.update(tabId, { url: rawUrl });} catch (e) {removeNavigationListener();diff --git a/src/chrome/src/cdp/cdp-client.js b/src/chrome/src/cdp/cdp-client.jsindex bafdd6e64..7d5a54ca1 100644--- a/src/chrome/src/cdp/cdp-client.js+++ b/src/chrome/src/cdp/cdp-client.js@@ -103,7 +103,7 @@ export class CDPClient {if (tabId == null) return;if (method === 'Page.javascriptDialogOpening') {if (!this.pendingDialogs.has(tabId)) this.pendingDialogs.set(tabId, new Map());- const dialog = { type: params?.type, defaultPrompt: params?.defaultPrompt };+ const dialog = { type: params?.type, navigation: this.dialogRuns.get(tabId)?.navigation, url: params?.url };this.pendingDialogs.get(tabId).set(source.sessionId || '', dialog);this._continueJavaScriptDialog(tabId, source, dialog);} else if (method === 'Page.javascriptDialogClosed') {@@ -323,20 +323,45 @@ export class CDPClient {stopDialogHandling(tabId) {const owner = this.dialogRuns.get(tabId);+ owner?.navigation?.release();owner?.cancelStartup?.();owner?.signal?.removeEventListener('abort', owner.onAbort);this.dialogRuns.delete(tabId);}+ // Only the navigation dispatch path may grant a one-use Leave decision.+ // A click in flight is not proof that a confirm/prompt came from that click.+ authorizeNavigationDialog(tabId, sourceUrl, signal) {+ const owner = this.dialogRuns.get(tabId);+ if (!owner || owner.signal?.aborted || signal?.aborted || !sourceUrl+ || this.pendingDialogs.get(tabId)?.size) return () => {};+ owner.navigation?.release();+ const permit = { sourceUrl };+ const release = () => {+ clearTimeout(timer);+ signal?.removeEventListener('abort', release);+ if (owner.navigation === permit) delete owner.navigation;+ };+ const timer = setTimeout(release, 10000);+ permit.release = release;+ owner.navigation = permit;+ signal?.addEventListener('abort', release, { once: true });+ return release;+ }+_continueJavaScriptDialog(tabId, source, params = {}) {const owner = this.dialogRuns.get(tabId);if (!owner || owner.signal?.aborted || params.handling) return;if (!['alert', 'confirm', 'prompt', 'beforeunload'].includes(params.type)) return;params.handling = true;- const response = { accept: true };- // Use the site's existing default; never invent answers or interpret dialog- // text as instructions. No page-controlled text is sent to status/trace UI.- if (params.type === 'prompt') response.promptText = String(params.defaultPrompt ?? '');+ const navigation = owner.navigation;+ const allowLeave = params.type === 'beforeunload' && navigation+ && params.navigation === navigation && params.url === navigation.sourceUrl+ && !source?.sessionId;+ if (allowLeave) navigation.release();+ // Alerts have no confirmation branch. Everything else fails closed unless+ // it belongs to the current, explicitly dispatched top-level navigation.+ const response = { accept: params.type === 'alert' || !!allowLeave };void this.sendCommand(tabId, 'Page.handleJavaScriptDialog', response, source?.sessionId || '').then(() => {if (this.dialogRuns.get(tabId) !== owner) return;diff --git a/test/browser-dialogs-e2e.mjs b/test/browser-dialogs-e2e.mjsindex 7d927eb02..1e053727f 100644--- a/test/browser-dialogs-e2e.mjs+++ b/test/browser-dialogs-e2e.mjs@@ -26,22 +26,33 @@ try {const answer = prompt('Value?', 'default value'); return { confirmed, answer }; })()`,returnByValue: true,});- assert.deepEqual(result.result.value, { confirmed: true, answer: 'default value' });+ assert.deepEqual(result.result.value, { confirmed: false, answer: null });+ const timerDialog = await session.send('Runtime.evaluate', {+ expression: 'new Promise(resolve => setTimeout(() => resolve(confirm("Timer confirmation")), 0))',+ awaitPromise: true, returnByValue: true,+ });+ assert.equal(timerDialog.result.value, false);await page.evaluate(() => {document.querySelector('#go').onclick = () => {window.onbeforeunload = event => { event.preventDefault(); event.returnValue = ''; };};});await page.click('#go');+ const unmatchedClosed = new Promise(resolve => session.once('Page.javascriptDialogClosed', resolve));+ await assert.rejects(page.goto('data:text/html,unrelated'), /ERR_ABORTED|aborted|canceled/i);+ await unmatchedClosed;+ assert.equal(page.url(), 'about:blank');+ const release = client.authorizeNavigationDialog(1, page.url());await page.goto('about:blank');+ release();assert.equal(page.url(), 'about:blank');- assert.deepEqual(answered, ['alert', 'confirm', 'prompt', 'beforeunload']);+ assert.deepEqual(answered, ['alert', 'confirm', 'prompt', 'confirm', 'beforeunload', 'beforeunload']);client.stopDialogHandling(1);const opened = new Promise(resolve => session.once('Page.javascriptDialogOpening', resolve));const pending = session.send('Runtime.evaluate', { expression: 'confirm("Already open")', returnByValue: true });await opened;await client.startDialogHandling(1);- assert.equal((await pending).result.value, true);+ assert.equal((await pending).result.value, false);client.stopDialogHandling(1);console.log('PASS: real Chrome alert, confirm, prompt, and beforeunload resume renderer/navigation.');} finally {diff --git a/test/browser-dialogs.mjs b/test/browser-dialogs.mjsindex 97c336041..82a81d758 100644--- a/test/browser-dialogs.mjs+++ b/test/browser-dialogs.mjs@@ -12,7 +12,7 @@ function harness() {}const tick = () => new Promise(resolve => setImmediate(resolve));-test('native dialogs continue immediately, preserving prompt defaults and child sessions', async () => {+test('unmatched dialogs are dismissed, including child sessions and supplied prompt defaults', async () => {const { client, calls } = harness();const handled = [];await client.startDialogHandling(7, { onHandled: type => handled.push(type) });@@ -26,7 +26,7 @@ test('native dialogs continue immediately, preserving prompt defaults and childassert.deepEqual(handled, ['alert', 'confirm', 'beforeunload', 'prompt']);assert.deepEqual(calls.slice(1), ['alert', 'confirm', 'beforeunload', 'prompt'].map(type => [7, 'Page.handleJavaScriptDialog',- type === 'prompt' ? { accept: true, promptText: 'existing answer' } : { accept: true }, 'child',+ { accept: type === 'alert' }, 'child',]));});@@ -79,7 +79,7 @@ test('a new action run resumes an already-observed dialog exactly once', async (assert.equal(calls.length, 0);await client.startDialogHandling(7);await client.startDialogHandling(7);- assert.equal(calls.filter(call => call[1] === 'Page.handleJavaScriptDialog').length, 1);+ assert.deepEqual(calls.filter(call => call[1] === 'Page.handleJavaScriptDialog').map(call => call[2]), [{ accept: false }]);client._onDebuggerEvent({ tabId: 7 }, 'Page.javascriptDialogClosed', {});assert.equal(client.pendingDialogs.size, 0);});@@ -178,3 +178,33 @@ test('failed workflow setup releases its debugger but preserves a Dev owner', asglobalThis.chrome = previousChrome;}});++test('only a current matching navigation can accept Leave once', async () => {+ const { client, calls } = harness();+ await client.startDialogHandling(7);+ const emit = (type, url = 'https://example.com/') => {+ client._onDebuggerEvent({ tabId: 7 }, 'Page.javascriptDialogOpening', { type, url });+ client._onDebuggerEvent({ tabId: 7 }, 'Page.javascriptDialogClosed', {});+ };+ const release = client.authorizeNavigationDialog(7, 'https://example.com/');+ emit('confirm');+ emit('prompt');+ emit('beforeunload', 'https://other.example/');+ emit('beforeunload');+ emit('beforeunload');+ release();+ assert.deepEqual(calls.filter(call => call[1] === 'Page.handleJavaScriptDialog').map(call => call[2].accept),+ [false, false, false, true, false]);+});++test('cached dialogs and ended navigation cannot inherit authorization', async () => {+ const { client, calls } = harness();+ client._onDebuggerEvent({ tabId: 7 }, 'Page.javascriptDialogOpening', { type: 'beforeunload', url: 'https://example.com/' });+ await client.startDialogHandling(7);+ client._onDebuggerEvent({ tabId: 7 }, 'Page.javascriptDialogClosed', {});+ const controller = new AbortController();+ client.authorizeNavigationDialog(7, 'https://example.com/', controller.signal);+ controller.abort();+ client._onDebuggerEvent({ tabId: 7 }, 'Page.javascriptDialogOpening', { type: 'beforeunload', url: 'https://example.com/' });+ assert.ok(calls.filter(call => call[1] === 'Page.handleJavaScriptDialog').every(call => !call[2].accept));+});