Skip to content

Chrome DevTools for coding agents

fix: defer focus emulation until a page is explicitly targeted (#3230)

Yash D.35abe350a4f4
diff --git a/src/McpContext.ts b/src/McpContext.ts
index 5d973bdd..e40c775a 100644
--- a/src/McpContext.ts
+++ b/src/McpContext.ts
@@ -521,7 +521,7 @@ export class McpContext implements Context, BrowserlessContext {
page = await this.browser.newPage({background});
}
const mcpPage = this.#createMcpPage(page.target());
- await mcpPage.init();
+ await mcpPage.init({emulateFocus: true});
this.selectPage(mcpPage);
await this.createPagesSnapshot();
return mcpPage;
@@ -844,7 +844,8 @@ export class McpContext implements Context, BrowserlessContext {
}
if (this.#selectedPage && !this.#selectedPage.isClosed()) {
- await this.#selectedPage.init();
+ // Automatic page snapshots must preserve real focus on untouched tabs.
+ await this.#selectedPage.init({emulateFocus: false});
}
return pages;
diff --git a/src/McpPage.ts b/src/McpPage.ts
index 14fb6612..9533ad6b 100644
--- a/src/McpPage.ts
+++ b/src/McpPage.ts
@@ -153,6 +153,7 @@ export class McpPage implements ContextPage {
#pptrPage?: Page;
#initPromise?: Promise<void>;
+ #focusEmulationRequested = false;
#disposed = false;
#closed = false;
@@ -291,19 +292,26 @@ export class McpPage implements ContextPage {
await page?.close({runBeforeUnload: false});
}
- async init(): Promise<void> {
+ async init(options?: {emulateFocus?: boolean}): Promise<void> {
if (this.#disposed) {
throw new Error(`McpPage (id=${this.id}) has already been disposed.`);
}
- if (this.#initPromise) {
- return await this.#initPromise;
+ if (!this.#initPromise) {
+ this.#initPromise = this.#doInit().catch(err => {
+ this.#initPromise = undefined;
+ throw err;
+ });
}
- this.#initPromise = this.#doInit();
- try {
- await this.#initPromise;
- } catch (err) {
- this.#initPromise = undefined;
- throw err;
+ await this.#initPromise;
+ // Discovery skips focus emulation, but a later page tool still needs it.
+ if (
+ options?.emulateFocus !== false &&
+ !this.#disposed &&
+ !this.#focusEmulationRequested
+ ) {
+ // Prevent duplicate requests while pending and after success.
+ this.#focusEmulationRequested = true;
+ this.#initFocusEmulationNoThrow();
}
}
@@ -336,18 +344,17 @@ export class McpPage implements ContextPage {
});
}
this.updateTimeouts();
- await Promise.allSettled([
- this.#initDevToolsUniverseNoThrow(),
- this.#initFocusEmulationNoThrow(),
- ]);
+ await this.#initDevToolsUniverseNoThrow();
if (this.#disposed) {
this.dispose();
}
}
- async #initFocusEmulationNoThrow(): Promise<void> {
- // We emulate a focused page for all pages to support multi-agent workflows.
+ #initFocusEmulationNoThrow(): void {
+ // Background pages need emulated focus for multi-agent workflows.
void this.pptrPage.emulateFocusedPage(true).catch(error => {
+ // Allow the next page operation to retry a transient failure.
+ this.#focusEmulationRequested = false;
logger?.('Error turning on focused page emulation', error);
});
}
diff --git a/src/ToolHandler.ts b/src/ToolHandler.ts
index 6a0c3729..448cd7cc 100644
--- a/src/ToolHandler.ts
+++ b/src/ToolHandler.ts
@@ -387,7 +387,7 @@ export class ToolHandler {
serverArgs.pageIdRouting && pageId !== undefined && !isSlimTool(tool)
? context.getPageById(pageId)
: context.getSelectedMcpPage();
- await page?.init();
+ await page?.init({emulateFocus: true});
response.setPage(page);
if (tool.blockedByDialog) {
page.throwIfDialogOpen();
diff --git a/src/tools/ToolDefinition.ts b/src/tools/ToolDefinition.ts
index fe984d5b..1aba388c 100644
--- a/src/tools/ToolDefinition.ts
+++ b/src/tools/ToolDefinition.ts
@@ -457,7 +457,7 @@ export type ContextPage = Readonly<{
readonly pptrPage: Page;
readonly cpuThrottlingRate: number;
readonly networkConditions: string | null;
- init(): Promise<void>;
+ init(options?: {emulateFocus?: boolean}): Promise<void>;
getAXNodeByUid(uid: string): TextSnapshotNode | undefined;
getElementByUid(uid: string): Promise<ElementHandle<Element>>;
getMatchedStylesForUid(uid: string): Promise<MatchedStyles>;
diff --git a/src/tools/pages.ts b/src/tools/pages.ts
index 53754b4c..afa50466 100644
--- a/src/tools/pages.ts
+++ b/src/tools/pages.ts
@@ -59,7 +59,7 @@ export const selectPage = defineTool((args: ParsedArguments) => ({
verifyFilesSchema: {},
handler: async (request, response, context) => {
const page = context.getPageById(request.params.pageId);
- await page.init();
+ await page.init({emulateFocus: true});
context.selectPage(page);
response.setIncludePages(true);
response.setListThirdPartyDeveloperTools();
diff --git a/src/tools/script.ts b/src/tools/script.ts
index c2dd6d2c..18d5c9b9 100644
--- a/src/tools/script.ts
+++ b/src/tools/script.ts
@@ -163,7 +163,7 @@ Example with arguments: \`(el) => el.innerText\`
cliArgs.pageIdRouting && request.params.pageId
? context.getPageById(request.params.pageId)
: context.getSelectedMcpPage();
- await mcpPage.init();
+ await mcpPage.init({emulateFocus: true});
// evaluate_script is not page-scoped, so ToolHandler does not run the
// blockedByDialog check for it. Without this, an evaluation started
// while a dialog is open waits until the protocol timeout.
diff --git a/tests/McpContext.test.ts b/tests/McpContext.test.ts
index 5c6f70ad..ca51b2fa 100644
--- a/tests/McpContext.test.ts
+++ b/tests/McpContext.test.ts
@@ -69,6 +69,32 @@ const EXTENSION_CONTENT_SCRIPT_PATH = path.join(
);
describe('McpContext', () => {
+ it('preserves real focus during page listing and automatic fallback', async () => {
+ const focusStates: boolean[] = [];
+ await withMcpContext(async (_response, context) => {
+ const initialPage = context.getSelectedMcpPage().pptrPage;
+ const fallbackPage = await context.browser.newPage();
+ const foregroundPage = await context.browser.newPage();
+ await foregroundPage.bringToFront();
+
+ focusStates.push(await initialPage.evaluate(() => document.hasFocus()));
+ await context.createPagesSnapshot();
+ focusStates.push(await initialPage.evaluate(() => document.hasFocus()));
+
+ await initialPage.close();
+ await context.createPagesSnapshot();
+ assert.strictEqual(context.getSelectedMcpPage().pptrPage, fallbackPage);
+ focusStates.push(await fallbackPage.evaluate(() => document.hasFocus()));
+
+ const createdPage = await context.newPage(true);
+ focusStates.push(
+ await createdPage.pptrPage.evaluate(() => document.hasFocus()),
+ await fallbackPage.evaluate(() => document.hasFocus()),
+ );
+ });
+ assert.deepStrictEqual(focusStates, [false, false, false, true, false]);
+ });
+
function createPageTarget() {
const page = createMockPuppeteerPage();
page.emulateFocusedPage.resolves();
diff --git a/tests/McpPage.test.ts b/tests/McpPage.test.ts
index 139c039e..90e822d6 100644
--- a/tests/McpPage.test.ts
+++ b/tests/McpPage.test.ts
@@ -410,6 +410,114 @@ describe('McpPage', () => {
});
});
+ describe('focus emulation', () => {
+ function createPage() {
+ const pptrPage = createMockPuppeteerPage();
+ pptrPage.emulateFocusedPage.resolves();
+ const target = createMockPuppeteerTarget({page: pptrPage});
+ const mcpPage = new McpPage(target, 1, {
+ config: createMockServerConfig(),
+ locatorClass: Locator,
+ });
+ return {mcpPage, pptrPage, target};
+ }
+
+ it('requests focus once on default initialization', async () => {
+ const {mcpPage, pptrPage, target} = createPage();
+
+ await mcpPage.init();
+ await mcpPage.init();
+ await mcpPage.init({emulateFocus: false});
+
+ sinon.assert.calledOnceWithExactly(pptrPage.emulateFocusedPage, true);
+ sinon.assert.calledOnceWithExactly(target.page);
+ });
+
+ it('initializes without focus until a tool requests it', async () => {
+ const {mcpPage, pptrPage, target} = createPage();
+
+ await mcpPage.init({emulateFocus: false});
+ await mcpPage.init({emulateFocus: false});
+
+ assert.strictEqual(mcpPage.pptrPage, pptrPage);
+ sinon.assert.notCalled(pptrPage.emulateFocusedPage);
+
+ await mcpPage.init();
+ await mcpPage.init();
+
+ sinon.assert.calledOnceWithExactly(pptrPage.emulateFocusedPage, true);
+ sinon.assert.calledOnceWithExactly(target.page);
+ });
+
+ it('shares initialization and requests focus once for concurrent callers', async () => {
+ const {mcpPage, pptrPage, target} = createPage();
+
+ await Promise.all([
+ mcpPage.init({emulateFocus: false}),
+ mcpPage.init(),
+ mcpPage.init(),
+ ]);
+
+ sinon.assert.calledOnceWithExactly(target.page);
+ sinon.assert.calledOnceWithExactly(pptrPage.emulateFocusedPage, true);
+ });
+
+ it('retries a failed focus request and retains successful emulation', async () => {
+ const {mcpPage, pptrPage} = createPage();
+ pptrPage.emulateFocusedPage
+ .onFirstCall()
+ .rejects(new Error('Target closed'));
+
+ await mcpPage.init();
+ await mcpPage.init();
+ await mcpPage.init();
+
+ assert.strictEqual(mcpPage.pptrPage, pptrPage);
+ sinon.assert.calledTwice(pptrPage.emulateFocusedPage);
+ sinon.assert.alwaysCalledWithExactly(pptrPage.emulateFocusedPage, true);
+ });
+
+ it('does not wait for or duplicate a pending focus request', async () => {
+ const {mcpPage, pptrPage} = createPage();
+ const focus = Promise.withResolvers<void>();
+ pptrPage.emulateFocusedPage.returns(focus.promise);
+
+ try {
+ await Promise.all([mcpPage.init(), mcpPage.init()]);
+ sinon.assert.calledOnceWithExactly(pptrPage.emulateFocusedPage, true);
+ } finally {
+ focus.resolve();
+ }
+ });
+
+ it('skips focus when disposed during initialization', async () => {
+ const {mcpPage, pptrPage, target} = createPage();
+ const page = Promise.withResolvers<typeof pptrPage>();
+ target.page.returns(page.promise);
+
+ const initialization = mcpPage.init();
+ mcpPage.dispose();
+ page.resolve(pptrPage);
+ await initialization;
+
+ sinon.assert.notCalled(pptrPage.emulateFocusedPage);
+ await assert.rejects(mcpPage.init(), /already been disposed/);
+ });
+
+ it('retries base initialization after a failure before requesting focus', async () => {
+ const {mcpPage, pptrPage, target} = createPage();
+ target.page.onFirstCall().rejects(new Error('Target unavailable'));
+
+ await assert.rejects(mcpPage.init(), /Target unavailable/);
+ sinon.assert.notCalled(pptrPage.emulateFocusedPage);
+
+ await mcpPage.init();
+
+ sinon.assert.calledTwice(target.page);
+ sinon.assert.calledOnceWithExactly(pptrPage.emulateFocusedPage, true);
+ });
+ });
+
describe('getTitle()', () => {
function createPage(url: string, title: string): McpPage {
const target = createMockPuppeteerTarget({url, title});
diff --git a/tests/ToolHandler.test.ts b/tests/ToolHandler.test.ts
index 2d34b9df..5fa1d5ac 100644
--- a/tests/ToolHandler.test.ts
+++ b/tests/ToolHandler.test.ts
@@ -36,7 +36,7 @@ import {
import {evaluateScript} from '../src/tools/script.js';
import {createTools} from '../src/tools/tools.js';
import {createMockMcpContext} from './mocks.js';
-import {getMockBrowser} from './utils.js';
+import {getMockBrowser, withMcpContext} from './utils.js';
describe('ToolHandler', () => {
afterEach(() => {
@@ -87,7 +87,7 @@ describe('ToolHandler', () => {
await toolHandler.handle({pageId: 1});
sinon.assert.calledOnceWithExactly(mockContext.getPageById, 1);
- sinon.assert.calledOnceWithExactly(mockPage.init);
+ sinon.assert.calledOnceWithExactly(mockPage.init, {emulateFocus: true});
assert.strictEqual(handlerCalled, true);
});
@@ -129,7 +129,7 @@ describe('ToolHandler', () => {
await toolHandler.handle({});
sinon.assert.calledOnceWithExactly(mockContext.getSelectedMcpPage);
- sinon.assert.calledOnceWithExactly(mockPage.init);
+ sinon.assert.calledOnceWithExactly(mockPage.init, {emulateFocus: true});
assert.strictEqual(handlerCalled, true);
});
@@ -1569,7 +1569,8 @@ describe('ToolHandler', () => {
sinon.spy(),
);
- const clock = sinon.useFakeTimers();
+ // Keep the test runner's clocks real while advancing the tool timeout.
+ const clock = sinon.useFakeTimers({toFake: ['setTimeout', 'clearTimeout']});
try {
const resultPromise = toolHandler.handle({});
await clock.tickAsync(TOOL_CALL_TIMEOUT_MS * 2);
@@ -1621,7 +1622,7 @@ describe('ToolHandler', () => {
abandonPendingBrowserAttemptSpy,
);
- const clock = sinon.useFakeTimers();
+ const clock = sinon.useFakeTimers({toFake: ['setTimeout', 'clearTimeout']});
try {
const resultPromise = toolHandler.handle({});
await clock.tickAsync(TOOL_CALL_TIMEOUT_MS);
@@ -1638,6 +1639,42 @@ describe('ToolHandler', () => {
}
});
+ it('emulates focus before a page tool acts on an untouched background page', async () => {
+ const focusStates: boolean[] = [];
+ const config = parseConfig();
+ await withMcpContext(async (_response, context) => {
+ const page = context.getSelectedMcpPage();
+ const foregroundPage = await context.browser.newPage();
+ await foregroundPage.bringToFront();
+ focusStates.push(await page.pptrPage.evaluate(() => document.hasFocus()));
+
+ const tool = definePageTool(() => ({
+ name: 'page_tool',
+ description: 'A page scoped tool',
+ annotations: {category: ToolCategory.INPUT, readOnlyHint: true},
+ schema: {},
+ blockedByDialog: false,
+ verifyFilesSchema: {},
+ handler: async ({page}) => {
+ focusStates.push(
+ await page.pptrPage.evaluate(() => document.hasFocus()),
+ );
+ },
+ }))(config.resolved);
+ const handler = new ToolHandler(
+ tool,
+ config,
+ async () => context,
+ new Mutex(),
+ sinon.spy(),
+ );
+
+ const result = await handler.handle({pageId: page.id});
+ assert.notStrictEqual(result.isError, true);
+ });
+ assert.deepStrictEqual(focusStates, [false, true]);
+ });
+
describe('browserless tools', () => {
function createBrowserlessTool(
handler: BrowserlessToolDefinition['handler'],
diff --git a/tests/tools/pages.test.ts b/tests/tools/pages.test.ts
index 01fce61a..9baf4c36 100644
--- a/tests/tools/pages.test.ts
+++ b/tests/tools/pages.test.ts
@@ -771,7 +771,7 @@ describe('pages', () => {
await selectPage(args).handler({params: {pageId: 1}}, response, context);
- sinon.assert.calledOnceWithExactly(page.init);
+ sinon.assert.calledOnceWithExactly(page.init, {emulateFocus: true});
sinon.assert.calledOnceWithExactly(context.selectPage, page);
sinon.assert.calledOnceWithExactly(response.setIncludePages, true);
sinon.assert.calledOnceWithExactly(
@@ -800,6 +800,7 @@ describe('pages', () => {
});
it('selects a page and keeps it focused in the background', async () => {
await withMcpContext(async (response, context, args) => {
+ await context.getPageById(1).init();
await context.newPage();
assert.strictEqual(
context.getPageById(2),
diff --git a/tests/tools/script.test.ts b/tests/tools/script.test.ts
index c1d84304..d364cd4d 100644
--- a/tests/tools/script.test.ts
+++ b/tests/tools/script.test.ts
@@ -273,6 +273,7 @@ describe('script', () => {
),
{message: 'A dialog is open (alert: hello).'},
);
+ sinon.assert.calledOnceWithExactly(page.init, {emulateFocus: true});
sinon.assert.calledOnceWithExactly(page.throwIfDialogOpen);
sinon.assert.callOrder(page.init, page.throwIfDialogOpen);
sinon.assert.notCalled(page.waitForEventsAfterAction);