Chrome DevTools for coding agents
chore: make get_devtools_comments wait for new comments (#3158)
Alex Rudenko5f185f93f764
diff --git a/src/ToolHandler.ts b/src/ToolHandler.tsindex 6d86581d..a7441e4b 100644--- a/src/ToolHandler.ts+++ b/src/ToolHandler.ts@@ -32,6 +32,13 @@ import {logger} from './utils/logger.js';import {fileURLToPath, pathToFileURL} from 'node:url';import {isLocalhost} from './utils/url.js';+type ToolLockGuard = Awaited<ReturnType<Mutex['acquire']>>;++interface ToolLockControl {+ releaseIfYielding: () => void;+ reacquire: () => Promise<void>;+}+/*** Upper bound on how long a tool call may wait to acquire the browser* (connect/launch and McpContext initialization). A connect attempt on a@@ -277,12 +284,16 @@ export class ToolHandler {params: Record<string, unknown>,response: McpResponse,context: McpContext,+ lock: ToolLockControl,): ReturnType<McpResponse['handle']> {try {await validateToolFiles(tool, params, context, true);+ lock.releaseIfYielding();await tool.handler({params}, response, context);} catch (err) {response.setError(err);+ } finally {+ await lock.reacquire();}return await response.handle(context, this.#dataFormat());}@@ -292,6 +303,7 @@ export class ToolHandler {params: Record<string, unknown>,response: McpResponse,context: McpContext,+ lock: ToolLockControl,onTelemetryData: (devToolsData: DevToolsData | undefined,pageUrl: string | undefined,@@ -327,6 +339,7 @@ export class ToolHandler {if (tool.blockedByDialog) {page.throwIfDialogOpen();}+ lock.releaseIfYielding();await tool.handler({params,@@ -336,6 +349,7 @@ export class ToolHandler {context,);} else {+ lock.releaseIfYielding();await tool.handler({params,@@ -346,6 +360,8 @@ export class ToolHandler {}} catch (err) {response.setError(err);+ } finally {+ await lock.reacquire();}onTelemetryData(await context.getDevToolsData(page),@@ -355,9 +371,10 @@ export class ToolHandler {}handle = async (params: Record<string, unknown>): Promise<CallToolResult> => {- using guard = await this.toolMutex.acquire();+ let guard: ToolLockGuard | undefined = await this.toolMutex.acquire();if (this.disabledReason) {+ guard[Symbol.dispose]();return {content: [{@@ -382,13 +399,34 @@ export class ToolHandler {? new SlimMcpResponse(this.serverArgs): new McpResponse(this.serverArgs);response.setRedactNetworkHeaders(this.serverArgs.redactNetworkHeaders);+ // When the tool yields the lock, the handler waits for external events.+ // Release the lock so other tool calls proceed, and re-acquire it+ // before the response is built.+ const lock: ToolLockControl = {+ releaseIfYielding: () => {+ if (this.tool.yieldsToolLock && guard) {+ guard[Symbol.dispose]();+ guard = undefined;+ }+ },+ reacquire: async () => {+ guard ??= await this.toolMutex.acquire();+ },+ };const {content, structuredContent} = isBrowserlessTool(this.tool)- ? await this.#runBrowserlessTool(this.tool, params, response, context)+ ? await this.#runBrowserlessTool(+ this.tool,+ params,+ response,+ context,+ lock,+ ): await this.#runBrowserTool(this.tool,params,response,context,+ lock,(data, url) => {devToolsData = data;pageUrl = url;@@ -423,6 +461,7 @@ export class ToolHandler {isError: true,};} finally {+ guard?.[Symbol.dispose]();void ClearcutLogger.get()?.logToolInvocation({toolName: this.tool.name,params,diff --git a/src/devtools/DevToolsCommentBridge.ts b/src/devtools/DevToolsCommentBridge.tsindex 378c8866..4c58a9d7 100644--- a/src/devtools/DevToolsCommentBridge.ts+++ b/src/devtools/DevToolsCommentBridge.ts@@ -24,6 +24,7 @@ export class DevToolsCommentBridge {readonly #debounceMs: number;#commentDebounceTimer?: NodeJS.Timeout;readonly #attachedPages = new Set<Page>();+ readonly #commentWaiters = new Set<(changed: boolean) => void>();constructor(options?: DevToolsCommentBridgeOptions) {this.#onNotification = options?.onNotification;@@ -116,20 +117,46 @@ export class DevToolsCommentBridge {});}+ /**+ * Resolves `true` on the next debounced comment event, or `false` when+ * `timeoutMs` elapses or the bridge is disposed first.+ */+ waitForCommentEvent(timeoutMs: number): Promise<boolean> {+ return new Promise<boolean>(resolve => {+ const settle = (changed: boolean): void => {+ clearTimeout(timer);+ this.#commentWaiters.delete(settle);+ resolve(changed);+ };+ const timer = setTimeout(() => {+ settle(false);+ }, timeoutMs);+ this.#commentWaiters.add(settle);+ });+ }+#handleCommentEvent(): void {if (this.#commentDebounceTimer) {clearTimeout(this.#commentDebounceTimer);}this.#commentDebounceTimer = setTimeout(() => {this.#onNotification?.('DevTools comment threads updated');+ this.#notifyCommentWaiters(true);}, this.#debounceMs);}+ #notifyCommentWaiters(changed: boolean): void {+ for (const waiter of [...this.#commentWaiters]) {+ waiter(changed);+ }+ }+dispose(): void {if (this.#commentDebounceTimer) {clearTimeout(this.#commentDebounceTimer);this.#commentDebounceTimer = undefined;}+ this.#notifyCommentWaiters(false);for (const page of this.#attachedPages) {try {const result = page.evaluate(() => {diff --git a/src/telemetry/tool_call_metrics.json b/src/telemetry/tool_call_metrics.jsonindex 12974d47..45b5fd1a 100644--- a/src/telemetry/tool_call_metrics.json+++ b/src/telemetry/tool_call_metrics.json@@ -1309,6 +1309,10 @@{"name": "page_id","argType": "number"+ },+ {+ "name": "timeout",+ "argType": "number"}]},diff --git a/src/tools/ToolDefinition.ts b/src/tools/ToolDefinition.tsindex 02de6634..aff12143 100644--- a/src/tools/ToolDefinition.ts+++ b/src/tools/ToolDefinition.ts@@ -112,6 +112,13 @@ export interface BaseToolDefinition<};schema: Schema;blockedByDialog: boolean;+ /**+ * When true, the handler runs without the server tool lock, so other tool+ * calls proceed while this handler waits. Page lookup before the handler+ * and response formatting after it still run under the lock. Only set+ * this for tools that wait for external events.+ */+ yieldsToolLock?: boolean;verifyFilesSchema: Partial<Record<keyof MergeSchema<Schema>, FileVerificationOption>>;diff --git a/src/tools/comments.ts b/src/tools/comments.tsindex ae5fb312..950c4495 100644--- a/src/tools/comments.ts+++ b/src/tools/comments.ts@@ -41,16 +41,36 @@ export const openDevtools = definePageTool(() => ({},}));+const DEFAULT_COMMENT_WAIT_MS = 10_000;+const MAX_COMMENT_WAIT_MS = 30_000;+export const getDevtoolsComments = definePageTool(() => ({name: 'get_devtools_comments',- description: 'Retrieve user comments from the DevTools window for the page.',+ description:+ 'Retrieve user comments from the DevTools window for the page. ' ++ 'If no comment is pending, waits up to `timeout` ms for the user to send one, then returns. ' ++ 'Call it again to keep waiting.',annotations: {category: ToolCategory.DEBUGGING,readOnlyHint: true,conditions: ['devtoolsComments'],},- schema: {},+ schema: {+ timeout: zod+ .number()+ .int()+ .min(0)+ .max(MAX_COMMENT_WAIT_MS)+ .optional()+ .describe(+ `Maximum time in milliseconds to wait for a new comment when none is pending. ` ++ `Defaults to ${DEFAULT_COMMENT_WAIT_MS}, maximum ${MAX_COMMENT_WAIT_MS}. ` ++ `Set to 0 to return immediately without waiting.`,+ ),+ },blockedByDialog: false,+ // The handler waits for comment events. Other tools run during the wait.+ yieldsToolLock: true,verifyFilesSchema: {},handler: async (request, response) => {const page = request.page;@@ -67,8 +87,30 @@ export const getDevtoolsComments = definePageTool(() => ({response.appendResponseLine(DEVTOOLS_COMMENTS_UNAVAILABLE_MESSAGE);return;}- const threads = await bridge.getComments(devtoolsPage);+ const timeout = request.params.timeout ?? DEFAULT_COMMENT_WAIT_MS;+ const start = Date.now();+ const deadline = start + timeout;+ let threads = await bridge.getComments(devtoolsPage);+ while (threads.length === 0) {+ const remaining = deadline - Date.now();+ if (remaining <= 0) {+ break;+ }+ const changed = await bridge.waitForCommentEvent(remaining);+ if (!changed) {+ break;+ }+ // Another tool may have changed state during the wait, so fetch again.+ threads = await bridge.getComments(devtoolsPage);+ }++ if (threads.length === 0 && timeout > 0) {+ response.appendResponseLine(+ `Waited ${Date.now() - start}ms for new DevTools comments. Call get_devtools_comments again to keep waiting.`,+ );+ return;+ }response.setDevToolsComments(threads);},}));diff --git a/tests/ToolHandler.test.ts b/tests/ToolHandler.test.tsindex 9c05338e..3b27cde9 100644--- a/tests/ToolHandler.test.ts+++ b/tests/ToolHandler.test.ts@@ -173,6 +173,185 @@ describe('ToolHandler', () => {assert.strictEqual(result.isError, undefined);});+ describe('yieldsToolLock', () => {+ function createGlobalTool(+ handler: ToolDefinition['handler'],+ options: {name?: string; yieldsToolLock?: boolean} = {},+ ): ToolDefinition {+ return {+ name: options.name ?? 'global_tool',+ description: 'A global tool',+ annotations: {+ category: ToolCategory.NAVIGATION,+ readOnlyHint: true,+ },+ schema: {},+ blockedByDialog: false,+ yieldsToolLock: options.yieldsToolLock,+ verifyFilesSchema: {},+ handler,+ };+ }++ function createHandler(tool: ToolDefinition, toolMutex: Mutex) {+ const mockContext = sinon.createStubInstance(McpContext);+ const mockProcess = sinon.createStubInstance(ChildProcess);+ mockContext.ensureBrowser.resolves(+ getMockBrowser({process: mockProcess}),+ );+ const serverArgs = new ConfigParser('1.0.0', ['node', 'script.js'], {+ CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS: 'true',+ }).parse();+ return new ToolHandler(+ tool,+ serverArgs,+ async () => mockContext,+ toolMutex,+ sinon.spy(),+ );+ }++ it('lets another tool run while a yielding tool waits', async () => {+ const toolMutex = new Mutex();+ const events: string[] = [];+ const {promise: release, resolve: finishWait} =+ Promise.withResolvers<void>();++ const waitingTool = createGlobalTool(+ async () => {+ events.push('waiting:start');+ await release;+ events.push('waiting:end');+ },+ {name: 'waiting_tool', yieldsToolLock: true},+ );+ const otherTool = createGlobalTool(+ async () => {+ events.push('other:run');+ },+ {name: 'other_tool'},+ );++ const waitingHandler = createHandler(waitingTool, toolMutex);+ const otherHandler = createHandler(otherTool, toolMutex);++ const waitingResult = waitingHandler.handle({});+ // Let the waiting tool enter its handler before the other tool is+ // called.+ await new Promise(resolve => setImmediate(resolve));+ const otherResult = await otherHandler.handle({});+ finishWait();+ await waitingResult;++ assert.deepStrictEqual(events, [+ 'waiting:start',+ 'other:run',+ 'waiting:end',+ ]);+ assert.strictEqual(otherResult.isError, undefined);+ });++ it('holds the lock for tools that do not yield', async () => {+ const toolMutex = new Mutex();+ const events: string[] = [];+ const {promise: release, resolve: finishWait} =+ Promise.withResolvers<void>();++ const blockingTool = createGlobalTool(+ async () => {+ events.push('blocking:start');+ await release;+ events.push('blocking:end');+ },+ {name: 'blocking_tool'},+ );+ const otherTool = createGlobalTool(+ async () => {+ events.push('other:run');+ },+ {name: 'other_tool'},+ );++ const blockingHandler = createHandler(blockingTool, toolMutex);+ const otherHandler = createHandler(otherTool, toolMutex);++ const blockingResult = blockingHandler.handle({});+ await new Promise(resolve => setImmediate(resolve));+ const otherResult = otherHandler.handle({});+ await new Promise(resolve => setImmediate(resolve));+ finishWait();+ await Promise.all([blockingResult, otherResult]);++ assert.deepStrictEqual(events, [+ 'blocking:start',+ 'blocking:end',+ 'other:run',+ ]);+ });++ it('builds the response only after a queued tool releases the lock', async () => {+ const toolMutex = new Mutex();+ const events: string[] = [];+ const {promise: otherBlocked, resolve: unblockOther} =+ Promise.withResolvers<void>();++ const waitingTool = createGlobalTool(+ async () => {+ await new Promise(resolve => setImmediate(resolve));+ events.push('waiting:handler-done');+ },+ {name: 'waiting_tool', yieldsToolLock: true},+ );+ const otherTool = createGlobalTool(+ async () => {+ events.push('other:start');+ await otherBlocked;+ events.push('other:end');+ },+ {name: 'other_tool'},+ );++ const waitingHandler = createHandler(waitingTool, toolMutex);+ const otherHandler = createHandler(otherTool, toolMutex);++ const waitingResult = waitingHandler.handle({}).then(result => {+ events.push('waiting:result');+ return result;+ });+ await new Promise(resolve => setImmediate(resolve));+ const otherResult = otherHandler.handle({});+ await new Promise(resolve => setImmediate(resolve));+ await new Promise(resolve => setImmediate(resolve));+ unblockOther();+ await Promise.all([waitingResult, otherResult]);++ assert.deepStrictEqual(events, [+ 'other:start',+ 'waiting:handler-done',+ 'other:end',+ 'waiting:result',+ ]);+ });++ it('re-acquires the lock when a yielding handler throws', async () => {+ const toolMutex = new Mutex();+ const tool = createGlobalTool(+ async () => {+ throw new Error('handler failed');+ },+ {yieldsToolLock: true},+ );+ const handler = createHandler(tool, toolMutex);++ const result = await handler.handle({});++ assert.strictEqual(result.isError, true);+ // The lock is free again: a plain acquire must resolve.+ const guard = await toolMutex.acquire();+ guard[Symbol.dispose]();+ });+ });+const dataFormatCases: Array<{argv: string[]; expected: DataFormat}> = [{argv: [], expected: 'default'},{argv: ['--experimentalToonFormat'], expected: 'toon'},diff --git a/tests/devtools/DevToolsCommentBridge.test.ts b/tests/devtools/DevToolsCommentBridge.test.tsindex c4a8a9d9..c086cac8 100644--- a/tests/devtools/DevToolsCommentBridge.test.ts+++ b/tests/devtools/DevToolsCommentBridge.test.ts@@ -208,4 +208,78 @@ describe('DevToolsCommentBridge', () => {sinon.assert.calledOnce(devtoolsPage.evaluate);assert.deepStrictEqual(threads, mockThreads);});++ describe('waitForCommentEvent', () => {+ async function attachWithCallback(bridge: DevToolsCommentBridge) {+ const devtoolsPage = createMockPuppeteerPage();+ devtoolsPage.evaluate.resolves(true);+ let exposedCallback: (() => void) | undefined;+ devtoolsPage.exposeFunction.callsFake((name: string, fn: unknown) => {+ if (name === '__onDevToolsCommentEvent' && typeof fn === 'function') {+ exposedCallback = () => {+ fn();+ };+ }+ return Promise.resolve();+ });+ await bridge.attach(devtoolsPage);+ assert.ok(exposedCallback);+ return exposedCallback;+ }++ it('resolves true after the debounced comment event', async () => {+ const bridge = new DevToolsCommentBridge({debounceMs: 150});+ const fireEvent = await attachWithCallback(bridge);++ const waiting = bridge.waitForCommentEvent(10_000);+ fireEvent();+ await clock.tickAsync(150);++ assert.strictEqual(await waiting, true);+ });++ it('resolves false at timeout when no event fires', async () => {+ const bridge = new DevToolsCommentBridge({debounceMs: 150});+ await attachWithCallback(bridge);++ const waiting = bridge.waitForCommentEvent(1_000);+ await clock.tickAsync(1_000);++ assert.strictEqual(await waiting, false);+ });++ it('resolves false when the bridge is disposed during the wait', async () => {+ const bridge = new DevToolsCommentBridge({debounceMs: 150});+ await attachWithCallback(bridge);++ const waiting = bridge.waitForCommentEvent(10_000);+ bridge.dispose();++ assert.strictEqual(await waiting, false);+ });++ it('resolves all concurrent waiters on one event', async () => {+ const bridge = new DevToolsCommentBridge({debounceMs: 150});+ const fireEvent = await attachWithCallback(bridge);++ const first = bridge.waitForCommentEvent(10_000);+ const second = bridge.waitForCommentEvent(10_000);+ fireEvent();+ await clock.tickAsync(150);++ assert.deepStrictEqual(await Promise.all([first, second]), [true, true]);+ });++ it('does not resolve a later waiter with an earlier event', async () => {+ const bridge = new DevToolsCommentBridge({debounceMs: 150});+ const fireEvent = await attachWithCallback(bridge);++ fireEvent();+ await clock.tickAsync(150);+ const waiting = bridge.waitForCommentEvent(1_000);+ await clock.tickAsync(1_000);++ assert.strictEqual(await waiting, false);+ });+ });});diff --git a/tests/tools/comments.test.ts b/tests/tools/comments.test.tsindex 321537d2..252eaed7 100644--- a/tests/tools/comments.test.ts+++ b/tests/tools/comments.test.ts@@ -4,6 +4,7 @@* SPDX-License-Identifier: Apache-2.0*/+import assert from 'node:assert';import {afterEach, describe, it} from 'node:test';import sinon from 'sinon';@@ -85,18 +86,97 @@ describe('comments tools', () => {devtoolsPage,);sinon.assert.calledOnceWithExactly(bridge.getComments, devtoolsPage);+ sinon.assert.notCalled(bridge.waitForCommentEvent);+ sinon.assert.notCalled(response.appendResponseLine);sinon.assert.calledOnceWithExactly(response.setDevToolsComments, [mockThread,]);});- it('sets empty comments list when no comments are found', async () => {+ it('yields the tool lock while waiting', () => {+ const {args} = createHandlerMocks();+ assert.strictEqual(getDevtoolsComments(args).yieldsToolLock, true);+ });++ it('waits for a comment event and fetches again', async () => {+ const {page, context, response, args} = createHandlerMocks();+ const devtoolsPage = createMockPuppeteerPage();+ const bridge = sinon.createStubInstance(DevToolsCommentBridge);+ page.getDevToolsPage.resolves(devtoolsPage);+ page.ensureDevToolsCommentBridge.resolves(bridge);+ const mockThread: CommentThreadPayload = {+ id: 'comment-2',+ text: 'Align the header',+ };+ bridge.getComments.onFirstCall().resolves([]);+ bridge.getComments.onSecondCall().resolves([mockThread]);+ bridge.waitForCommentEvent.resolves(true);++ await getDevtoolsComments(args).handler(+ {params: {timeout: 5_000}, page},+ response,+ context,+ );++ sinon.assert.calledTwice(bridge.getComments);+ sinon.assert.calledOnceWithExactly(+ bridge.waitForCommentEvent,+ sinon.match((value: number) => value > 0 && value <= 5_000),+ );+ sinon.assert.notCalled(response.appendResponseLine);+ sinon.assert.calledOnceWithExactly(response.setDevToolsComments, [+ mockThread,+ ]);+ });++ it('keeps waiting when an event yields no new threads', async () => {+ const clock = sinon.useFakeTimers();const {page, context, response, args} = createHandlerMocks();const devtoolsPage = createMockPuppeteerPage();const bridge = sinon.createStubInstance(DevToolsCommentBridge);page.getDevToolsPage.resolves(devtoolsPage);page.ensureDevToolsCommentBridge.resolves(bridge);bridge.getComments.resolves([]);+ bridge.waitForCommentEvent.onFirstCall().callsFake(async () => {+ clock.tick(2_000);+ return true;+ });+ bridge.waitForCommentEvent.onSecondCall().callsFake(async () => {+ clock.tick(3_000);+ return false;+ });++ await getDevtoolsComments(args).handler(+ {params: {timeout: 5_000}, page},+ response,+ context,+ );++ sinon.assert.calledTwice(bridge.getComments);+ sinon.assert.calledTwice(bridge.waitForCommentEvent);+ sinon.assert.calledWithExactly(+ bridge.waitForCommentEvent.secondCall,+ 3_000,+ );+ sinon.assert.calledOnceWithExactly(+ response.appendResponseLine,+ 'Waited 5000ms for new DevTools comments. Call get_devtools_comments again to keep waiting.',+ );+ sinon.assert.notCalled(response.setDevToolsComments);+ });++ it('does not set comments after the wait times out', async () => {+ const clock = sinon.useFakeTimers();+ const {page, context, response, args} = createHandlerMocks();+ const devtoolsPage = createMockPuppeteerPage();+ const bridge = sinon.createStubInstance(DevToolsCommentBridge);+ page.getDevToolsPage.resolves(devtoolsPage);+ page.ensureDevToolsCommentBridge.resolves(bridge);+ bridge.getComments.resolves([]);+ bridge.waitForCommentEvent.callsFake(async () => {+ clock.tick(10_000);+ return false;+ });await getDevtoolsComments(args).handler({params: {}, page},@@ -104,12 +184,59 @@ describe('comments tools', () => {context,);- sinon.assert.calledOnce(page.getDevToolsPage);+ sinon.assert.calledOnceWithExactly(bridge.getComments, devtoolsPage);+ sinon.assert.calledOnceWithExactly(bridge.waitForCommentEvent, 10_000);sinon.assert.calledOnceWithExactly(- page.ensureDevToolsCommentBridge,- devtoolsPage,+ response.appendResponseLine,+ 'Waited 10000ms for new DevTools comments. Call get_devtools_comments again to keep waiting.',+ );+ sinon.assert.notCalled(response.setDevToolsComments);+ });++ it('reports the elapsed time when the wait ends early', async () => {+ const clock = sinon.useFakeTimers();+ const {page, context, response, args} = createHandlerMocks();+ const devtoolsPage = createMockPuppeteerPage();+ const bridge = sinon.createStubInstance(DevToolsCommentBridge);+ page.getDevToolsPage.resolves(devtoolsPage);+ page.ensureDevToolsCommentBridge.resolves(bridge);+ bridge.getComments.resolves([]);+ // The bridge was disposed before the deadline.+ bridge.waitForCommentEvent.callsFake(async () => {+ clock.tick(1_500);+ return false;+ });++ await getDevtoolsComments(args).handler(+ {params: {}, page},+ response,+ context,+ );++ sinon.assert.calledOnceWithExactly(+ response.appendResponseLine,+ 'Waited 1500ms for new DevTools comments. Call get_devtools_comments again to keep waiting.',);+ sinon.assert.notCalled(response.setDevToolsComments);+ });++ it('does not wait when timeout is 0', async () => {+ const {page, context, response, args} = createHandlerMocks();+ const devtoolsPage = createMockPuppeteerPage();+ const bridge = sinon.createStubInstance(DevToolsCommentBridge);+ page.getDevToolsPage.resolves(devtoolsPage);+ page.ensureDevToolsCommentBridge.resolves(bridge);+ bridge.getComments.resolves([]);++ await getDevtoolsComments(args).handler(+ {params: {timeout: 0}, page},+ response,+ context,+ );+sinon.assert.calledOnceWithExactly(bridge.getComments, devtoolsPage);+ sinon.assert.notCalled(bridge.waitForCommentEvent);+ sinon.assert.notCalled(response.appendResponseLine);sinon.assert.calledOnceWithExactly(response.setDevToolsComments, []);});