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
Authorize beforeunload dialog handling for history navigation
Emre Sokullu532e5309e29c
diff --git a/docs/architecture.md b/docs/architecture.mdindex a342aedaf..460942338 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -822,11 +822,11 @@ so a running task or an input command in flight never grants permission toaccept 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.+created immediately before a navigation or history 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 onStop, completion, or detach, even when Dev diagnostics retain the debugger.diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex f578aa1d4..0c91606d0 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -33563,6 +33563,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// SPAs may push several entries with an identical URL and keep their// route solely in history.state. Listen before dispatch so those entries// can be verified by the browser's navigation events.+ let releaseDialogNavigation = () => {};let navigationTerminalResult = null;let resolveNavigationTerminal;let navigationLoadingObserved = false;@@ -33570,6 +33571,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);};@@ -33608,6 +33610,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (changeInfo.status === 'loading') navigationLoadingObserved = true;});const removeNavigationListeners = () => {+ releaseDialogNavigation();for (const [event, listener] of listenerRecords.splice(0)) {try { event.removeListener(listener); } catch {}}@@ -33623,6 +33626,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst delta = direction === 'back' ? -steps : steps;historyDispatchArmed = true;dispatched = true;+ releaseDialogNavigation = cdpClient.authorizeNavigationDialog(tabId, beforeUrl, earlyCdpAbortSignal);const results = await chrome.scripting.executeScript({target: { tabId },args: [delta],@@ -33634,9 +33638,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d});probe = results?.[0]?.result || null;} catch (e) {+ removeNavigationListeners();return { success: false, dispatched, error: `${name}: cannot navigate history on this page (${e.message}).` };}if (!probe) {+ removeNavigationListeners();return { success: false, dispatched, error: `${name}: history navigation did not run on this page.` };}@@ -33651,6 +33657,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dnavigationWaitResult = await waitForNavigationTerminal(8500, 'deadline');}}+ removeNavigationListeners();let afterUrl = navigationWaitResult.url || probe.before;let finalStatus = '';diff --git a/test/browser-dialogs.mjs b/test/browser-dialogs.mjsindex 82a81d758..e39c37932 100644--- a/test/browser-dialogs.mjs+++ b/test/browser-dialogs.mjs@@ -208,3 +208,101 @@ test('cached dialogs and ended navigation cannot inherit authorization', async (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));});++test('go_back authorizes beforeunload for the current page and cleans up on completion and failure', async () => {+ const previousChrome = globalThis.chrome;+ const previousBrowser = globalThis.browser;+ delete globalThis.browser;+ const area = { get: async () => ({}), set: async () => {}, remove: async () => {} };+ const calls = [];+ const tabId = 42;+ const beforeUrl = 'https://example.com/page2';+ const targetUrl = 'https://example.com/page1';+ const createEvent = () => {+ const listeners = new Set();+ return {+ addListener(fn) { listeners.add(fn); },+ removeListener(fn) { listeners.delete(fn); },+ emit(...args) { for (const fn of [...listeners]) fn(...args); },+ get listenerCount() { return listeners.size; },+ };+ };+ const events = {+ history: createEvent(),+ committed: createEvent(),+ updated: createEvent(),+ };++ const { Agent } = await import('../src/chrome/src/agent/agent.js');+ const { cdpClient } = await import('../src/chrome/src/cdp/cdp-client.js');+ const originalAttach = cdpClient.attach;+ const originalSend = cdpClient.sendCommand;++ try {+ cdpClient.attach = async id => cdpClient.sessions.set(id, { tabId: id });+ cdpClient.sendCommand = async (...args) => { calls.push(args); };++ let currentUrl = beforeUrl;+ let failInjection = false;+ globalThis.chrome = {+ storage: { local: area, session: area },+ runtime: { getURL: value => value },+ tabs: {+ get: async id => ({ id, url: currentUrl, status: 'complete' }),+ onUpdated: events.updated,+ },+ webNavigation: {+ onHistoryStateUpdated: events.history,+ onCommitted: events.committed,+ },+ scripting: {+ executeScript: async () => {+ if (failInjection) throw new Error('injection failed');+ cdpClient._onDebuggerEvent({ tabId }, 'Page.javascriptDialogOpening', {+ type: 'beforeunload',+ url: beforeUrl,+ });+ cdpClient._onDebuggerEvent({ tabId }, 'Page.javascriptDialogClosed', {});+ currentUrl = targetUrl;+ events.committed.emit({+ tabId,+ frameId: 0,+ url: targetUrl,+ transitionQualifiers: ['forward_back'],+ });+ return [{ result: { before: beforeUrl } }];+ },+ },+ };++ await cdpClient.startDialogHandling(tabId);+ const agent = new Agent({ getActive: () => ({ promptTier: 'full' }) });++ // 1. Successful go_back: authorizes beforeunload dialog and accepts Leave+ const result = await agent.executeTool(tabId, 'go_back', { force: true });+ assert.equal(result.success, true);+ assert.equal(result.verified, true);+ assert.equal(result.url, targetUrl);+ const dialogCalls = calls.filter(c => c[1] === 'Page.handleJavaScriptDialog');+ assert.equal(dialogCalls.length, 1);+ assert.deepEqual(dialogCalls[0][2], { accept: true });+ assert.equal(cdpClient.dialogRuns.get(tabId)?.navigation, undefined);+ assert.equal(events.committed.listenerCount, 0);++ // 2. Failed injection: cleans up the authorization permit+ failInjection = true;+ const failedResult = await agent.executeTool(tabId, 'go_back', { force: true });+ assert.equal(failedResult.success, false);+ assert.equal(cdpClient.dialogRuns.get(tabId)?.navigation, undefined);+ assert.equal(events.committed.listenerCount, 0);++ cdpClient.stopDialogHandling(tabId);+ } finally {+ cdpClient.stopDialogHandling(tabId);+ cdpClient.attach = originalAttach;+ cdpClient.sendCommand = originalSend;+ globalThis.chrome = previousChrome;+ if (previousBrowser === undefined) delete globalThis.browser;+ else globalThis.browser = previousBrowser;+ }+});