Chrome DevTools for coding agents
feat: run independent tool calls in parallel with a TaskRunner (#3243)
Alex Rudenko8a8d8771c241
diff --git a/src/BrowserManager.ts b/src/BrowserManager.tsindex 54ed3962..23d0fb24 100644--- a/src/BrowserManager.ts+++ b/src/BrowserManager.ts@@ -186,8 +186,9 @@ export class BrowserManager {* McpContext initialization built on it — if ensureBrowser() already* resolved and it's that later step hanging (e.g. a dead CDP transport),* the token rotation alone does nothing, since #browser is already- * cached. Safe to forget unconditionally here: the tool mutex serializes- * every call, so there's no concurrent caller to disrupt.+ * cached. Safe to forget unconditionally here: a tool call that already+ * received a Browser keeps using it, so forgetting the cached value only+ * makes the next ensureBrowser() reconnect.*/abandonPendingAttempt(): void {this.#browserAttempt = new BrowserAttempt();@@ -361,7 +362,7 @@ export class BrowserManager {// periodically and terminates it on a missed pong, which rejects the// in-flight CDP calls and fires `disconnected` so #evictIfCurrent()// drops the stale handle. Without this, such a call would hang until- // protocolTimeout while holding the tool mutex.+ // protocolTimeout inside the context queue.wsOptions: {keepAlive: true,headers: wsHeaders,diff --git a/src/McpContext.ts b/src/McpContext.tsindex e40c775a..54552950 100644--- a/src/McpContext.ts+++ b/src/McpContext.ts@@ -24,6 +24,7 @@ import {type UncaughtError} from './collectors/PageCollector.js';import {ServiceWorkerConsoleCollector} from './collectors/ServiceWorkerCollector.js';import {Locator,+ Mutex,type Browser,type BrowserContext,type Connection,@@ -57,6 +58,7 @@ import type {Logger} from './types.js';import {McpWorker} from './McpWorker.js';import {getTempFilePath, resolveCanonicalPath} from './utils/files.js';import {escapeForLog} from './utils/logger.js';+import type {TaskQueue, TaskRunner} from './utils/TaskRunner.js';import {isAllowedUrl} from './utils/url.js';export interface McpContextOptions {@@ -65,6 +67,8 @@ export interface McpContextOptions {navigationTimeout?: number;// Shared heap snapshot manager to preserve loaded snapshots across browser reconnects.heapSnapshotManager: HeapSnapshotManager;+ // Creates the context queue and the page queues.+ taskRunner: TaskRunner;// Returns the browser to use. Called by ensureBrowser(), so the browser// connection is only established once a tool needs it.getBrowser: () => Promise<Browser>;@@ -121,6 +125,19 @@ export class McpContext implements Context, BrowserlessContext {#workers = new Map<Target, McpWorker>();#mcpPages = new Map<Target, McpPage>();+ /**+ * Queue for the browser-wide state (page list, selected page, trace+ * state). Every page queue is a child of it, so a task on it waits for+ * every page task and blocks later page tasks.+ */+ readonly taskQueue: TaskQueue;+ #taskRunner: TaskRunner;+ #pageTaskQueues = new Map<number, TaskQueue>();+ /**+ * Serializes `createPagesSnapshot()`. Two tasks on different page queues+ * can call it at the same time.+ */+ #pagesSnapshotMutex = new Mutex();#selectedPage?: McpPage;#selectedPageFallback?: {wasClosed: boolean};#selectedPageFallbackRead = false;@@ -150,6 +167,8 @@ export class McpContext implements Context, BrowserlessContext {this.logger = logger;this.#locatorClass = locatorClass;+ this.#taskRunner = options.taskRunner;+ this.taskQueue = options.taskRunner.createQueue();this.#config = options.config;this.#options = options;this.#heapSnapshotManager = options.heapSnapshotManager;@@ -329,7 +348,7 @@ export class McpContext implements Context, BrowserlessContext {this.#serviceWorkerConsoleCollector?.dispose();for (const mcpPage of this.#allMcpPages()) {- mcpPage.dispose();+ this.#disposeMcpPage(mcpPage);}this.#mcpPages.clear();this.#workers.clear();@@ -366,7 +385,7 @@ export class McpContext implements Context, BrowserlessContext {try {const mcpPage = this.#mcpPages.get(target);if (mcpPage) {- mcpPage.dispose();+ this.#disposeMcpPage(mcpPage);this.#mcpPages.delete(target);}this.#workers.delete(target);@@ -672,6 +691,28 @@ export class McpContext implements Context, BrowserlessContext {return page;}+ /**+ * The queue for tasks on page `pageId`. The queue exists before the page+ * does, so a tool call can enter it before the browser connects. It is a+ * child of {@link taskQueue}.+ */+ pageTaskQueue(pageId: number): TaskQueue {+ let queue = this.#pageTaskQueues.get(pageId);+ if (!queue) {+ queue = this.#taskRunner.createQueue(this.taskQueue);+ this.#pageTaskQueues.set(pageId, queue);+ }+ return queue;+ }++ #disposeMcpPage(mcpPage: McpPage): void {+ mcpPage.dispose();+ this.#pageTaskQueues+ .get(mcpPage.id)+ ?.dispose(new Error(`Page ${mcpPage.id} is closed.`));+ this.#pageTaskQueues.delete(mcpPage.id);+ }+isPageSelected(page: McpPage): boolean {return this.#selectedPage === page;}@@ -688,7 +729,7 @@ export class McpContext implements Context, BrowserlessContext {this.#selectedPage !== newPage &&!this.#mcpPages.has(this.#selectedPage.target)) {- this.#selectedPage.dispose();+ this.#disposeMcpPage(this.#selectedPage);}this.#selectedPage = newPage;newPage.updateTimeouts();@@ -791,6 +832,7 @@ export class McpContext implements Context, BrowserlessContext {if (!this.#browser) {return [];}+ using guard = await this.#pagesSnapshotMutex.acquire();const allTargets = this.#fetchPageTargets();for (const target of allTargets) {@@ -802,7 +844,7 @@ export class McpContext implements Context, BrowserlessContext {for (const [target, mcpPage] of this.#mcpPages) {if (!currentTargets.has(target)) {if (mcpPage !== this.#selectedPage || mcpPage.isClosed()) {- mcpPage.dispose();+ this.#disposeMcpPage(mcpPage);}this.#mcpPages.delete(target);}@@ -836,7 +878,7 @@ export class McpContext implements Context, BrowserlessContext {} else if (this.#selectedPage) {const wasClosed = Boolean(this.#selectedPage.isClosed());if (!wasClosed) {- this.#selectedPage.dispose();+ this.#disposeMcpPage(this.#selectedPage);}this.#selectedPage = undefined;this.#selectedPageFallback = {wasClosed};diff --git a/src/ToolHandler.ts b/src/ToolHandler.tsindex 697e3cc7..3cd8c473 100644--- a/src/ToolHandler.ts+++ b/src/ToolHandler.ts@@ -11,7 +11,7 @@ import type {McpPage} from './McpPage.js';import {McpResponse, type DataFormat} from './McpResponse.js';import {SlimMcpResponse} from './SlimMcpResponse.js';import {ClearcutLogger} from './telemetry/ClearcutLogger.js';-import type {Browser, CallToolResult, Mutex} from './third_party/index.js';+import type {Browser, CallToolResult} from './third_party/index.js';import {ProtocolError, ProtocolErrorCode, zod} from './third_party/index.js';import {labels} from './tools/categories.js';import {categoryToFlagName} from './config/category-options.js';@@ -29,18 +29,13 @@ import {isPageScopedTool,isSlimTool,} from './tools/ToolDefinition.js';+import {getErrorMessage} from './utils/errorHandling.js';import {logger} from './utils/logger.js';+import type {TaskQueue} from './utils/TaskRunner.js';import {fileURLToPath, pathToFileURL} from 'node:url';import {isDeepStrictEqual} from 'node:util';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@@ -223,7 +218,7 @@ function errorResult(text: string): CallToolResult {/*** The page id a page tool call targets, or `undefined` when the call targets- * the selected page.+ * the selected page. `args` can be the raw or the parsed arguments.*/function routedPageId(tool: AnyToolDefinition,@@ -250,7 +245,6 @@ export class ToolHandler {tool: AnyToolDefinition,config: ReadonlyServerConfig,private readonly getContext: () => Promise<McpContext>,- private readonly toolMutex: Mutex,private readonly abandonPendingBrowserAttemptOnTimeout: () => void,) {this.#tool = tool;@@ -283,9 +277,9 @@ export class ToolHandler {/*** Replaces the tool definition and re-evaluates its status against the- * current server config. Callers must hold the tool mutex, so calls that- * are already waiting for it run with the new state. Returns true if the- * tool listing visible to the client changed.+ * current server config. Callers must pause the task runner, so calls that+ * are already waiting run with the new state. Returns true if the tool+ * listing visible to the client changed.*/update(tool: AnyToolDefinition): boolean {const previousTool = this.#tool;@@ -363,16 +357,12 @@ 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(serverArgs));}@@ -383,7 +373,6 @@ export class ToolHandler {params: Record<string, unknown>,response: McpResponse,context: McpContext,- lock: ToolLockControl,onTelemetryData: (devToolsData: DevToolsData | undefined,pageUrl: string | undefined,@@ -416,7 +405,6 @@ export class ToolHandler {if (tool.blockedByDialog) {page.throwIfDialogOpen();}- lock.releaseIfYielding();await tool.handler({params,@@ -426,7 +414,6 @@ export class ToolHandler {context,);} else {- lock.releaseIfYielding();await tool.handler({params,@@ -437,8 +424,6 @@ export class ToolHandler {}} catch (err) {response.setError(err);- } finally {- await lock.reacquire();}onTelemetryData(await context.getDevToolsData(page),@@ -447,113 +432,122 @@ export class ToolHandler {return await response.handle(context, this.#dataFormat(serverArgs));}+ /**+ * The queue the call runs on. `'none'` tools run outside the runner.+ * `'page'` tools run on the queue of the page named by `rawArgs.pageId`+ * when page id routing applies; every other call runs on the context+ * queue.+ */+ #queueFor(+ context: McpContext,+ rawArgs: Record<string, unknown>,+ ): TaskQueue | undefined {+ const tool = this.#tool;+ switch (tool.concurrency) {+ case 'none':+ return undefined;+ case 'page': {+ const pageId = routedPageId(tool, this.#config.resolved, rawArgs);+ return pageId !== undefined+ ? context.pageTaskQueue(pageId)+ : context.taskQueue;+ }+ default:+ return context.taskQueue;+ }+ }+handle = async (rawArgs: Record<string, unknown> = {},options?: {viaMcp?: boolean},): Promise<CallToolResult> => {- let guard: ToolLockGuard | undefined = await this.toolMutex.acquire();+ const context = await this.getContext();+ let queueGuard: Disposable | undefined;try {- if (options?.viaMcp && this.#disabled) {- throw new ProtocolError(- ProtocolErrorCode.InvalidParams,- `Tool ${this.#tool.name} disabled`,- );- }+ queueGuard = await this.#queueFor(context, rawArgs)?.scheduleTask();+ } catch (err) {+ // The queue was disposed while the call waited, e.g. the page closed.+ return errorResult(getErrorMessage(err));+ }+ using guard = queueGuard;+ if (options?.viaMcp && this.#disabled) {+ throw new ProtocolError(+ ProtocolErrorCode.InvalidParams,+ `Tool ${this.#tool.name} disabled`,+ );+ }- if (this.#disabledReason) {- return errorResult(this.#disabledReason);- }+ if (this.#disabledReason) {+ return errorResult(this.#disabledReason);+ }- const tool = this.#tool;- const serverArgs = this.#config.resolved;- const parseResult = this.#registeredInputSchema.safeParse(rawArgs);- if (!parseResult.success) {- return errorResult(formatValidationError(tool.name, parseResult.error));+ const tool = this.#tool;+ const serverArgs = this.#config.resolved;+ const parseResult = this.#registeredInputSchema.safeParse(rawArgs);+ if (!parseResult.success) {+ return errorResult(formatValidationError(tool.name, parseResult.error));+ }+ const params = parseResult.data;++ const startTime = Date.now();+ let success = false;+ let devToolsData: DevToolsData | undefined;+ let pageUrl: string | undefined;+ try {+ logger?.(`${tool.name} request: ${JSON.stringify(params, null, ' ')}`);+ const response = isSlimTool(tool)+ ? new SlimMcpResponse(serverArgs)+ : new McpResponse(serverArgs);+ response.setRedactNetworkHeaders(serverArgs.redactNetworkHeaders);+ const {content, structuredContent} = isBrowserlessTool(tool)+ ? await this.#runBrowserlessTool(+ tool,+ serverArgs,+ params,+ response,+ context,+ )+ : await this.#runBrowserTool(+ tool,+ serverArgs,+ params,+ response,+ context,+ (data, url) => {+ devToolsData = data;+ pageUrl = url;+ },+ );+ const result: CallToolResult & {+ structuredContent?: Record<string, unknown>;+ } = {+ content,+ };+ if (response.error) {+ result.isError = true;}- const params = parseResult.data;-- const startTime = Date.now();- let success = false;- let devToolsData: DevToolsData | undefined;- let pageUrl: string | undefined;- try {- logger?.(`${tool.name} request: ${JSON.stringify(params, null, ' ')}`);- const context = await this.getContext();- const response = isSlimTool(tool)- ? new SlimMcpResponse(serverArgs)- : new McpResponse(serverArgs);- response.setRedactNetworkHeaders(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 (tool.yieldsToolLock && guard) {- guard[Symbol.dispose]();- guard = undefined;- }- },- reacquire: async () => {- guard ??= await this.toolMutex.acquire();- },- };- const {content, structuredContent} = isBrowserlessTool(tool)- ? await this.#runBrowserlessTool(- tool,- serverArgs,- params,- response,- context,- lock,- )- : await this.#runBrowserTool(- tool,- serverArgs,- params,- response,- context,- lock,- (data, url) => {- devToolsData = data;- pageUrl = url;- },- );- const result: CallToolResult & {- structuredContent?: Record<string, unknown>;- } = {- content,- };- if (response.error) {- result.isError = true;- }- success = true;- if (serverArgs.experimentalStructuredContent) {- result.structuredContent = structuredContent as Record<- string,- unknown- >;- }- return result;- } catch (err) {- logger?.(`${tool.name} error:`, err, err?.stack);- let errorText = err && 'message' in err ? err.message : String(err);- if ('cause' in err && err.cause) {- errorText += `\nCause: ${err.cause.message}`;- }- return errorResult(errorText);- } finally {- void ClearcutLogger.get()?.logToolInvocation({- toolName: tool.name,- params,- schema: tool.schema,- success,- latencyMs: Date.now() - startTime,- devToolsData,- pageUrl,- });+ success = true;+ if (serverArgs.experimentalStructuredContent) {+ result.structuredContent = structuredContent as Record<string, unknown>;+ }+ return result;+ } catch (err) {+ logger?.(`${tool.name} error:`, err, err?.stack);+ let errorText = err && 'message' in err ? err.message : String(err);+ if ('cause' in err && err.cause) {+ errorText += `\nCause: ${err.cause.message}`;}+ return errorResult(errorText);} finally {- guard?.[Symbol.dispose]();+ void ClearcutLogger.get()?.logToolInvocation({+ toolName: tool.name,+ params,+ schema: tool.schema,+ success,+ latencyMs: Date.now() - startTime,+ devToolsData,+ pageUrl,+ });}};}diff --git a/src/index.ts b/src/index.tsindex 381e9e98..76a22d53 100644--- a/src/index.ts+++ b/src/index.ts@@ -26,7 +26,6 @@ import {type RegisteredTool,type Root,type Transport,- Mutex,puppeteer,} from './third_party/index.js';import {ToolHandler} from './ToolHandler.js';@@ -35,15 +34,16 @@ import {createTools} from './tools/tools.js';import {logCruxDisclaimer} from './utils/disclaimers.js';import {getErrorMessage} from './utils/errorHandling.js';import {logger} from './utils/logger.js';+import {TaskRunner} from './utils/TaskRunner.js';import {VERSION} from './version.js';puppeteer.setFollowSymlinks(false);/*** Timeout for a `roots/list` that a tool call is waiting on, matching the 5s- * default used for page operations. `getContext()` awaits it while- * `ToolHandler` holds the tool mutex, so leaving it unbounded lets a client- * that negotiates `roots` but does not answer block every tool for the SDK's+ * default used for page operations. `getContext()` awaits it before+ * `ToolHandler` enters the task runner, so leaving it unbounded lets a client+ * that negotiates `roots` but does not answer delay every tool for the SDK's* default of 60s. Background refreshes are not bounded by this, so roots a* slow client sends late still land.*/@@ -64,7 +64,9 @@ export class McpServer {#config: ServerConfig;#browserManager: BrowserManager;#context: McpContext;- #heapSnapshotManager = new HeapSnapshotManager();+ /** Runs every tool call and config reload. */+ #taskRunner = new TaskRunner();+ #heapSnapshotManager = new HeapSnapshotManager(this.#taskRunner);/*** Client roots stay valid across browser reconnects and only the client can@@ -73,11 +75,11 @@ export class McpServer {*/#lastClientRoots?: Root[];/**- * Whether a tool call already waited for the initial `roots/list`, so a- * client that negotiates roots but never answers only delays the first call.+ * The bounded initial `roots/list` request. Every tool call that starts+ * before the client answered waits on the same request, so a client that+ * negotiates roots but never answers only delays the first calls.*/- #awaitedInitialRoots = false;- #toolMutex = new Mutex();+ #initialRoots?: Promise<void>;#configWatcher?: ConfigWatcher;#tools = new Map<string, ToolEntry>();@@ -113,6 +115,7 @@ export class McpServer {this.#context = McpContext.create(logger, {config: this.#config,heapSnapshotManager: this.#heapSnapshotManager,+ taskRunner: this.#taskRunner,getBrowser: () => this.#browserManager.ensureBrowser(),});this.#context.setRoots(this.#combinedRoots());@@ -180,7 +183,9 @@ export class McpServer {* notification.*/async applyConfig(config: ServerConfig): Promise<void> {- using guard = await this.#toolMutex.acquire();+ // Goes ahead of waiting tool calls and waits for running ones, so every+ // waiting call runs with the new config.+ using guard = await this.#taskRunner.pause();await this.#applyConfigLocked(this.#config.mergeReloadable(config));}@@ -253,7 +258,7 @@ export class McpServer {configPath: string,reload: () => ServerConfig,): Promise<void> {- using guard = await this.#toolMutex.acquire();+ using guard = await this.#taskRunner.pause();if (this.#configWatcher !== watcher) {return;}@@ -364,11 +369,11 @@ export class McpServer {}async #getContext(): Promise<McpContext> {- if (this.#lastClientRoots === undefined && !this.#awaitedInitialRoots) {- this.#awaitedInitialRoots = true;- // Nothing listed yet, so this call has to wait – bounded, since it is- // holding the tool mutex, and a later background refresh still lands- await this.#updateRoots(ROOTS_REQUEST_TIMEOUT);+ if (this.#lastClientRoots === undefined) {+ // Nothing listed yet, so this call has to wait – bounded, since every+ // tool call waits on it, and a later background refresh still lands+ this.#initialRoots ??= this.#updateRoots(ROOTS_REQUEST_TIMEOUT);+ await this.#initialRoots;}return this.#context;}@@ -378,14 +383,13 @@ export class McpServer {tool,this.#config,() => this.#getContext(),- this.#toolMutex,() => this.#browserManager.abandonPendingAttempt(),);}/*** Overrides the SDK's `tools/call` handler so enabled and input-schema- * checks run inside `ToolHandler.handle()` after acquiring `#toolMutex`.+ * checks run inside `ToolHandler.handle()` inside the task runner.*/#setToolCallRequestHandler(): void {this.server.server.setRequestHandler('tools/call', async request => {diff --git a/src/processors/HeapSnapshotManager.ts b/src/processors/HeapSnapshotManager.tsindex 11edd783..bb7aa23b 100644--- a/src/processors/HeapSnapshotManager.ts+++ b/src/processors/HeapSnapshotManager.ts@@ -9,6 +9,7 @@ import path from 'node:path';import {DevTools} from '../third_party/index.js';import {createIdGenerator} from '../utils/id.js';+import type {TaskQueue, TaskRunner} from '../utils/TaskRunner.js';export interface HeapSnapshotAggregate {id: number;@@ -129,6 +130,38 @@ function hasValidHeapSnapshotExtension(filePath: string): boolean {export class HeapSnapshotManager {#snapshotIdGenerator = createIdGenerator();#snapshots = new Map<string, Promise<HeapSnapshot>>();+ /**+ * Queue for all heap snapshot work, with one child queue per absolute file+ * path. A read of one file holds the file queue, so reads of different+ * files run at the same time. A read of several files holds this queue.+ * `disposeSnapshot()` holds the file queue, so it waits for in-flight+ * reads of the file, and a read that starts after it loads the file again.+ */+ #taskQueue: TaskQueue;+ #taskRunner: TaskRunner;+ #fileTaskQueues = new Map<string, TaskQueue>();++ constructor(taskRunner: TaskRunner) {+ this.#taskRunner = taskRunner;+ this.#taskQueue = taskRunner.createQueue();+ }++ /**+ * Holds the queue of `filePath`, or the heap queue without a path, until+ * the guard is disposed.+ */+ async #scheduleTask(filePath?: string): Promise<Disposable> {+ if (filePath === undefined) {+ return await this.#taskQueue.scheduleTask();+ }+ const absolutePath = path.resolve(filePath);+ let queue = this.#fileTaskQueues.get(absolutePath);+ if (!queue) {+ queue = this.#taskRunner.createQueue(this.#taskQueue);+ this.#fileTaskQueues.set(absolutePath, queue);+ }+ return await queue.scheduleTask();+ }async getSnapshot(filePath: string): Promise<HeapSnapshot> {if (!hasValidHeapSnapshotExtension(filePath)) {@@ -174,6 +207,7 @@ export class HeapSnapshotManager {filterName?: string,objectId?: number,): Promise<HeapSnapshotAggregateData> {+ using guard = await this.#scheduleTask(filePath);const snapshot = await this.getSnapshot(filePath);const filter =new DevTools.HeapSnapshotModel.HeapSnapshotModel.NodeFilter();@@ -211,6 +245,7 @@ export class HeapSnapshotManager {async getStats(filePath: string,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.Statistics> {+ using guard = await this.#scheduleTask(filePath);const snapshot = await this.getSnapshot(filePath);return await snapshot.proxy.getStatistics();}@@ -218,6 +253,7 @@ export class HeapSnapshotManager {async getStaticData(filePath: string,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.StaticData | null> {+ using guard = await this.#scheduleTask(filePath);const snapshot = await this.getSnapshot(filePath);return snapshot.proxy.staticData;}@@ -225,6 +261,7 @@ export class HeapSnapshotManager {async getNativeContextSizes(filePath: string,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.NativeContextSizes> {+ using guard = await this.#scheduleTask(filePath);const snapshot = await this.getSnapshot(filePath);return await snapshot.proxy.getNativeContextSizes();}@@ -232,6 +269,7 @@ export class HeapSnapshotManager {async getRetainedByContextSummary(filePath: string,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.RetainedByContextSummary> {+ using guard = await this.#scheduleTask(filePath);const snapshot = await this.getSnapshot(filePath);return await snapshot.proxy.getRetainedByContextSummary();}@@ -242,6 +280,7 @@ export class HeapSnapshotManager {filterName?: string,objectId?: number,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.ItemsRange> {+ using guard = await this.#scheduleTask(filePath);const snapshot = await this.getSnapshot(filePath);const filter =new DevTools.HeapSnapshotModel.HeapSnapshotModel.NodeFilter();@@ -262,6 +301,7 @@ export class HeapSnapshotManager {filePath: string,nodeId: number,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.ItemsRange> {+ using guard = await this.#scheduleTask(filePath);const snapshot = await this.getSnapshot(filePath);const nodeIndex = await snapshot.proxy.nodeIndexForId(nodeId);if (nodeIndex === undefined) {@@ -275,6 +315,7 @@ export class HeapSnapshotManager {filePath: string,nodeId: number,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.ObjectInfo> {+ using guard = await this.#scheduleTask(filePath);const snapshot = await this.getSnapshot(filePath);const nodeIndex = await snapshot.proxy.nodeIndexForId(nodeId);if (nodeIndex === undefined) {@@ -286,6 +327,7 @@ export class HeapSnapshotManager {async analyzeContexts(filePath: string,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.ContextAnalysisResult> {+ using guard = await this.#scheduleTask(filePath);const snapshot = await this.getSnapshot(filePath);return await snapshot.proxy.analyzeContexts();}@@ -297,6 +339,7 @@ export class HeapSnapshotManager {maxNodes?: number,maxSiblings?: number,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.RetainingPaths> {+ using guard = await this.#scheduleTask(filePath);const snapshot = await this.getSnapshot(filePath);const nodeIndex = await snapshot.proxy.nodeIndexForId(nodeId);if (nodeIndex === undefined) {@@ -314,6 +357,7 @@ export class HeapSnapshotManager {filePath: string,nodeId: number,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.DominatorChain> {+ using guard = await this.#scheduleTask(filePath);const snapshot = await this.getSnapshot(filePath);const nodeIndex = await snapshot.proxy.nodeIndexForId(nodeId);if (nodeIndex === undefined) {@@ -327,6 +371,7 @@ export class HeapSnapshotManager {nodeId: number,options?: HeapEdgesQueryOptions,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.ItemsRange> {+ using guard = await this.#scheduleTask(filePath);const snapshot = await this.getSnapshot(filePath);const nodeIndex = await snapshot.proxy.nodeIndexForId(nodeId);if (nodeIndex === undefined) {@@ -401,6 +446,7 @@ export class HeapSnapshotManager {baseFilePath: string,currentFilePath: string,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.Diff[]> {+ using guard = await this.#scheduleTask();const [baseSnapshot, currentSnapshot] = await Promise.all([this.getSnapshot(baseFilePath),this.getSnapshot(currentFilePath),@@ -480,6 +526,7 @@ export class HeapSnapshotManager {}async getDuplicateStrings(filePath: string): Promise<DuplicateStringGroup[]> {+ using guard = await this.#scheduleTask(filePath);const snapshot = await this.getSnapshot(filePath);return await snapshot.proxy.getDuplicateStrings();}@@ -488,6 +535,7 @@ export class HeapSnapshotManager {filePath: string,options: HeapQueryOptions,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.ItemsRange> {+ using guard = await this.#scheduleTask(filePath);const snapshot = await this.getSnapshot(filePath);const provider = snapshot.proxy.queryObjects(options);return await provider.serializeItemsRange(0, Infinity);@@ -498,6 +546,7 @@ export class HeapSnapshotManager {}async disposeSnapshot(filePath: string): Promise<boolean> {+ using guard = await this.#scheduleTask(filePath);const absolutePath = path.resolve(filePath);const cached = this.#snapshots.get(absolutePath);if (cached) {diff --git a/src/tools/ToolDefinition.ts b/src/tools/ToolDefinition.tsindex 1aba388c..5cc88ea1 100644--- a/src/tools/ToolDefinition.ts+++ b/src/tools/ToolDefinition.ts@@ -78,6 +78,24 @@ export type FileVerificationOption =type AllKeys<T> = T extends unknown ? keyof T : never;+/**+ * Which task queue `ToolHandler` runs a tool call on. A task on a queue+ * waits for tasks on the same queue, on its parent, and on its children.+ *+ * - `'exclusive'`: the context queue, for the whole call. No other browser+ * tool runs at the same time. This is the default.+ * - `'page'`: the queue of the page named by `pageId`, a child of the+ * context queue. Tools on different pages run at the same time; tools on+ * one page and `'exclusive'` tools wait. Without page id routing the call+ * runs on the context queue. Only for page-scoped tools whose handler+ * touches the target page and no browser-global state.+ * - `'none'`: no queue. The tool runs at the same time as any other tool.+ * For browserless tools, whose data guards itself (see+ * `HeapSnapshotManager`), and for page tools that only read page state+ * and wait for external events.+ */+export type ToolConcurrency = 'exclusive' | 'page' | 'none';+type ExtractSchemaField<Schema, K extends PropertyKey> = Schema extends unknown? K extends keyof Schema? Exclude<Schema[K], undefined>@@ -119,12 +137,10 @@ 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.+ * Which queues the server holds while the tool runs. Defaults to+ * `'exclusive'`. See {@link ToolConcurrency}.*/- yieldsToolLock?: boolean;+ concurrency?: ToolConcurrency;verifyFilesSchema: Partial<Record<keyof MergeSchema<Schema>, FileVerificationOption>>;@@ -139,6 +155,11 @@ export interface ToolDefinition<* non-page tool must handle dialogs itself.*/blockedByDialog: false;+ /**+ * A non-page tool has no target page, so it cannot take the page queue. It+ * touches browser state, so it always runs in a queue.+ */+ concurrency?: Exclude<ToolConcurrency, 'page' | 'none'>;handler(request: Request<Schema>,response: Response,@@ -525,6 +546,11 @@ export function defineTool<Schema extends zod.ZodRawShape>(interface PageToolDefinition<Schema extends zod.ZodRawShape = zod.ZodRawShape,> extends BaseToolDefinition<Schema> {+ /**+ * A page tool with `'none'` must only read page state. Its page lookup and+ * response formatting run at the same time as other tools on the page.+ */+ concurrency?: ToolConcurrency;handler(request: Request<Schema> & {page: ContextPage},response: Response,@@ -563,6 +589,10 @@ export interface BrowserlessToolDefinition<* dialogs.*/blockedByDialog: false;+ /**+ * A browserless tool has no page.+ */+ concurrency?: Exclude<ToolConcurrency, 'page'>;handler(request: Request<Schema>,response: Response,@@ -573,6 +603,8 @@ export interface BrowserlessToolDefinition</*** Defines a tool that does not need a browser connection, e.g. a tool that only* analyzes local files. Its handler only receives a {@link BrowserlessContext}.+ * Such a tool runs without the context queue (`concurrency: 'none'`) unless+ * the definition sets another value.*/export function defineBrowserlessTool<Schema extends zod.ZodRawShape>(definition: (@@ -581,6 +613,7 @@ export function defineBrowserlessTool<Schema extends zod.ZodRawShape>(): (args: ParsedArguments) => BrowserlessToolDefinition<Schema> {return (args: ParsedArguments): BrowserlessToolDefinition<Schema> => {return {+ concurrency: 'none',...definition(args),browserless: true,};diff --git a/src/tools/comments.ts b/src/tools/comments.tsindex 950c4495..d324b704 100644--- a/src/tools/comments.ts+++ b/src/tools/comments.ts@@ -69,8 +69,9 @@ export const getDevtoolsComments = definePageTool(() => ({),},blockedByDialog: false,- // The handler waits for comment events. Other tools run during the wait.- yieldsToolLock: true,+ // The handler only reads page state and waits for comment events, so it+ // runs outside the task runner and other tools run during the wait.+ concurrency: 'none',verifyFilesSchema: {},handler: async (request, response) => {const page = request.page;diff --git a/src/utils/TaskRunner.ts b/src/utils/TaskRunner.tsnew file mode 100644index 00000000..e523e2a9--- /dev/null+++ b/src/utils/TaskRunner.ts@@ -0,0 +1,176 @@+/**+ * @license+ * Copyright 2026 Google LLC+ * SPDX-License-Identifier: Apache-2.0+ */++type Priority = 'normal' | 'high';++interface Entry {+ queue: TaskQueue;+ priority: Priority;+ running: boolean;+ resolve: () => void;+ reject: (error: Error) => void;+}++/** The runner methods a queue uses. Not part of the public API. */+interface QueueHooks {+ scheduleTask(queue: TaskQueue): Promise<Disposable>;+ cancel(queue: TaskQueue, reason: Error): void;+}++/**+ * A queue that the {@link TaskRunner} created. Tasks on one queue run one+ * at a time. Tasks on a queue and on its ancestors or descendants also run+ * one at a time. Tasks on unrelated queues run at the same time.+ */+export class TaskQueue {+ readonly parent?: TaskQueue;+ readonly #hooks: QueueHooks;+ #disposed?: Error;++ constructor(hooks: QueueHooks, parent: TaskQueue | undefined) {+ this.#hooks = hooks;+ this.parent = parent;+ }++ /**+ * Schedules a task on this queue. Resolves when no earlier task on a+ * related queue runs, with a guard that holds the queue until it is+ * disposed. Rejects when the queue is disposed while the task waits. A+ * second dispose of the guard throws.+ */+ async scheduleTask(): Promise<Disposable> {+ if (this.#disposed) {+ throw this.#disposed;+ }+ return await this.#hooks.scheduleTask(this);+ }++ /**+ * Rejects the callers that wait on this queue with `reason`, and rejects+ * every later `scheduleTask()` call. The current holder keeps the queue.+ */+ dispose(reason: Error): void {+ this.#disposed = reason;+ this.#hooks.cancel(this, reason);+ }++ /** True when `other` is this queue, an ancestor, or a descendant. */+ isRelatedTo(other: TaskQueue): boolean {+ return this.#isAncestorOrSelf(other) || other.#isAncestorOrSelf(this);+ }++ #isAncestorOrSelf(other: TaskQueue): boolean {+ for (+ let queue: TaskQueue | undefined = other;+ queue;+ queue = queue.parent+ ) {+ if (queue === this) {+ return true;+ }+ }+ return false;+ }+}++/**+ * Runs every task of the server from one ordered list. Each task names the+ * queue it runs on. A task starts when every earlier task on a related queue+ * has finished. Waiting tasks count, so a waiting task blocks later related+ * tasks and no task starves. `pause()` enters the list ahead of waiting tasks+ * and relates to every queue.+ */+export class TaskRunner {+ readonly #hooks: QueueHooks = {+ scheduleTask: queue => this.#scheduleTask(queue),+ cancel: (queue, reason) => this.#cancel(queue, reason),+ };+ readonly #root = new TaskQueue(this.#hooks, undefined);+ #entries: Entry[] = [];++ /**+ * Creates a queue. Tasks on the new queue and tasks on `parent` wait for+ * each other. Without `parent`, the queue is a child of the root, so only+ * `pause()` relates to it.+ */+ createQueue(parent: TaskQueue = this.#root): TaskQueue {+ return new TaskQueue(this.#hooks, parent);+ }++ /**+ * Stops new tasks on every queue. The pause goes ahead of waiting tasks and+ * resolves when every running task has finished. Disposing the guard+ * resumes the runner.+ */+ async pause(): Promise<Disposable> {+ return await this.#scheduleTask(this.#root, 'high');+ }++ async #scheduleTask(+ queue: TaskQueue,+ priority: Priority = 'normal',+ ): Promise<Disposable> {+ const {guard, started} = this.#enter(queue, priority);+ await started;+ return guard;+ }++ #cancel(queue: TaskQueue, reason: Error): void {+ for (const entry of [...this.#entries]) {+ if (entry.queue === queue && !entry.running) {+ this.#leave(entry);+ entry.reject(reason);+ }+ }+ }++ #enter(+ queue: TaskQueue,+ priority: Priority,+ ): {guard: Disposable; started: Promise<void>} {+ const {promise, resolve, reject} = Promise.withResolvers<void>();+ const entry: Entry = {queue, priority, running: false, resolve, reject};+ // A high-priority entry goes before the first waiting normal entry.+ const index =+ priority === 'high'+ ? this.#entries.findIndex(e => !e.running && e.priority === 'normal')+ : -1;+ this.#entries.splice(index === -1 ? this.#entries.length : index, 0, entry);+ this.#schedule();+ return {+ started: promise,+ guard: {+ [Symbol.dispose]: () => {+ this.#leave(entry);+ },+ },+ };+ }++ #leave(entry: Entry): void {+ const index = this.#entries.indexOf(entry);+ if (index === -1) {+ throw new Error('The guard was already disposed.');+ }+ this.#entries.splice(index, 1);+ this.#schedule();+ }++ #schedule(): void {+ for (const [index, entry] of this.#entries.entries()) {+ if (entry.running) {+ continue;+ }+ const blocked = this.#entries+ .slice(0, index)+ .some(earlier => earlier.queue.isRelatedTo(entry.queue));+ if (!blocked) {+ entry.running = true;+ entry.resolve();+ }+ }+ }+}diff --git a/src/utils/WaitForHelper.ts b/src/utils/WaitForHelper.tsindex 3a092938..ec537953 100644--- a/src/utils/WaitForHelper.ts+++ b/src/utils/WaitForHelper.ts@@ -53,7 +53,7 @@ export class WaitForHelper {async waitForStableDom(): Promise<void> {// Bound the setup evaluation against the stable-DOM timeout. Without this// cap a paused renderer (e.g. an open dialog) would make evaluateHandle- // hang until protocolTimeout (default 180s) while the tool mutex is held.+ // hang until protocolTimeout (default 180s) inside the context queue.using stableDomObserver = await Promise.race([this.#page.evaluateHandle(timeout => {let timeoutId: ReturnType<typeof setTimeout>;diff --git a/tests/McpContext.test.ts b/tests/McpContext.test.tsindex ca51b2fa..31060d50 100644--- a/tests/McpContext.test.ts+++ b/tests/McpContext.test.ts@@ -20,6 +20,7 @@ import {NetworkFormatter} from '../src/formatters/NetworkFormatter.js';import {McpContext} from '../src/McpContext.js';import {McpPage} from '../src/McpPage.js';import {HeapSnapshotManager} from '../src/processors/HeapSnapshotManager.js';+import {TaskRunner} from '../src/utils/TaskRunner.js';import {TextSnapshot} from '../src/TextSnapshot.js';import {type Browser,@@ -117,7 +118,8 @@ describe('McpContext', () => {{config: options?.config ?? createMockServerConfig(),heapSnapshotManager:- options?.heapSnapshotManager ?? new HeapSnapshotManager(),+ options?.heapSnapshotManager ??+ new HeapSnapshotManager(new TaskRunner()),},Locator,);@@ -133,7 +135,7 @@ describe('McpContext', () => {config: createMockServerConfig({performanceCrux: false,}),- heapSnapshotManager: new HeapSnapshotManager(),+ heapSnapshotManager: new HeapSnapshotManager(new TaskRunner()),},Locator,);@@ -180,7 +182,7 @@ describe('McpContext', () => {config: createMockServerConfig({performanceCrux: false,}),- heapSnapshotManager: new HeapSnapshotManager(),+ heapSnapshotManager: new HeapSnapshotManager(new TaskRunner()),},Locator,);@@ -767,7 +769,7 @@ describe('McpContext', () => {config: createMockServerConfig({performanceCrux: false,}),- heapSnapshotManager: new HeapSnapshotManager(),+ heapSnapshotManager: new HeapSnapshotManager(new TaskRunner()),};const first = await createConnectedMcpContext(browser, options, Locator);const idBeforeReconnect = (await first.newPage()).id;@@ -807,13 +809,15 @@ describe('McpContext', () => {describe('lazy browser connection', () => {function createLazyContext(getBrowser: () => Promise<Browser>) {+ const taskRunner = new TaskRunner();return McpContext.create(undefined,{config: createMockServerConfig({performanceCrux: false,}),- heapSnapshotManager: new HeapSnapshotManager(),+ heapSnapshotManager: new HeapSnapshotManager(taskRunner),+ taskRunner,getBrowser,},Locator,@@ -826,6 +830,59 @@ describe('McpContext', () => {return browser;}+ it('serializes concurrent createPagesSnapshot() calls', async () => {+ const browser = createBrowser();+ browser.targets.returns([createMockPuppeteerTarget()]);+ const {promise: initDone, resolve: finishInit} =+ Promise.withResolvers<void>();+ const init = sinon.stub(McpPage.prototype, 'init').resolves();+ init.onSecondCall().returns(initDone);+ const context = createLazyContext(async () => browser);+ await context.ensureBrowser();+ sinon.assert.calledOnce(init);++ const first = context.createPagesSnapshot();+ const second = context.createPagesSnapshot();+ await new Promise(resolve => setImmediate(resolve));+ sinon.assert.calledTwice(init);++ finishInit();+ await Promise.all([first, second]);+ sinon.assert.calledThrice(init);+ context.dispose();+ });++ it('returns one page task queue per page id', async () => {+ const context = createLazyContext(async () => createBrowser());+ const queue = context.pageTaskQueue(1);+ assert.strictEqual(context.pageTaskQueue(1), queue);+ assert.notStrictEqual(context.pageTaskQueue(2), queue);+ assert.strictEqual(queue.parent, context.taskQueue);+ context.dispose();+ });++ it('disposes the page task queue with the page', async () => {+ const browser = createBrowser();+ browser.targets.returns([createMockPuppeteerTarget()]);+ sinon.stub(McpPage.prototype, 'init').resolves();+ const context = createLazyContext(async () => browser);+ await context.ensureBrowser();+ const page = context.getSelectedMcpPage();+ const {promise: release, resolve: finishRunning} =+ Promise.withResolvers<void>();+ const running = (async () => {+ using guard = await context.pageTaskQueue(page.id).scheduleTask();+ await release;+ })();+ const waiting = context.pageTaskQueue(page.id).scheduleTask();++ context.dispose();++ await assert.rejects(waiting, new RegExp(`Page ${page.id} is closed\\.`));+ finishRunning();+ await running;+ });+it('does not connect until ensureBrowser() is called', async () => {const browser = createBrowser();const getBrowser = sinon.stub<[], Promise<Browser>>().resolves(browser);@@ -1338,7 +1395,7 @@ describe('McpContext', () => {allowedUrlPattern: options.allowlist,blockedUrlPattern: options.blocklist,}),- heapSnapshotManager: new HeapSnapshotManager(),+ heapSnapshotManager: new HeapSnapshotManager(new TaskRunner()),},Locator,);@@ -1799,7 +1856,7 @@ describe('McpContext', () => {});it('disposes loaded heap snapshots', async () => {- const heapSnapshotManager = new HeapSnapshotManager();+ const heapSnapshotManager = new HeapSnapshotManager(new TaskRunner());const context = await createMockContext({heapSnapshotManager,});@@ -1813,7 +1870,7 @@ describe('McpContext', () => {});it('does not dispose heapSnapshotManager when no snapshots are loaded', async () => {- const heapSnapshotManager = new HeapSnapshotManager();+ const heapSnapshotManager = new HeapSnapshotManager(new TaskRunner());const disposeSpy = sinon.spy(heapSnapshotManager, 'dispose');const context = await createMockContext({heapSnapshotManager});diff --git a/tests/ToolHandler.test.ts b/tests/ToolHandler.test.tsindex 5fa1d5ac..f6ec6d97 100644--- a/tests/ToolHandler.test.ts+++ b/tests/ToolHandler.test.ts@@ -13,12 +13,11 @@ import {pathToFileURL} from 'node:url';import sinon from 'sinon';import {ConfigParser} from '../src/config/ConfigParser.js';-import {McpContext} from '../src/McpContext.js';+import type {McpContext} from '../src/McpContext.js';import {McpPage} from '../src/McpPage.js';import {McpResponse, type DataFormat} from '../src/McpResponse.js';import {ClearcutLogger} from '../src/telemetry/ClearcutLogger.js';import {- Mutex,ProtocolError,ProtocolErrorCode,zod,@@ -28,6 +27,7 @@ import {ToolCategory} from '../src/tools/categories.js';import {defineBrowserlessTool,definePageTool,+ type AnyToolDefinition,type BrowserlessToolDefinition,type DefinedPageTool,type DevToolsData,@@ -35,10 +35,16 @@ import {} from '../src/tools/ToolDefinition.js';import {evaluateScript} from '../src/tools/script.js';import {createTools} from '../src/tools/tools.js';-import {createMockMcpContext} from './mocks.js';+import {TaskRunner, type TaskQueue} from '../src/utils/TaskRunner.js';+import {createMockMcpContext, createMockMcpPage} from './mocks.js';import {getMockBrowser, withMcpContext} from './utils.js';describe('ToolHandler', () => {+ /** Runs `fn` as a task on `queue`. */+ async function runOn(queue: TaskQueue, fn: () => Promise<void>) {+ using guard = await queue.scheduleTask();+ await fn();+ }afterEach(() => {ClearcutLogger.resetForTesting();});@@ -67,19 +73,16 @@ describe('ToolHandler', () => {},}))(config.resolved);- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}));const mockPage = sinon.createStubInstance(McpPage);mockContext.getPageById.returns(mockPage);- const toolMutex = new Mutex();-const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -109,19 +112,16 @@ describe('ToolHandler', () => {},}))(config.resolved);- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}));const mockPage = sinon.createStubInstance(McpPage);mockContext.getSelectedMcpPage.returns(mockPage);- const toolMutex = new Mutex();-const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -150,18 +150,16 @@ describe('ToolHandler', () => {},};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}));- const toolMutex = new Mutex();const config = parseConfig();const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -175,10 +173,13 @@ describe('ToolHandler', () => {assert.strictEqual(result.isError, undefined);});- describe('yieldsToolLock', () => {+ describe("concurrency: 'exclusive'", () => {function createGlobalTool(handler: ToolDefinition['handler'],- options: {name?: string; yieldsToolLock?: boolean} = {},+ options: {+ name?: string;+ concurrency?: ToolDefinition['concurrency'];+ } = {},): ToolDefinition {return {name: options.name ?? 'global_tool',@@ -189,40 +190,43 @@ describe('ToolHandler', () => {},schema: {},blockedByDialog: false,- yieldsToolLock: options.yieldsToolLock,+ concurrency: options.concurrency,verifyFilesSchema: {},handler,};}- function createHandler(tool: ToolDefinition, toolMutex: Mutex) {- const mockContext = sinon.createStubInstance(McpContext);+ function createContext() {+ const mockContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}),);+ return mockContext;+ }++ function createHandler(tool: AnyToolDefinition, mockContext: McpContext) {return new ToolHandler(tool,parseConfig(),async () => mockContext,- toolMutex,sinon.spy(),);}- it('lets another tool run while a yielding tool waits', async () => {- const toolMutex = new Mutex();+ it('serializes exclusive tools', async () => {+ const mockContext = createContext();const events: string[] = [];const {promise: release, resolve: finishWait} =Promise.withResolvers<void>();- const waitingTool = createGlobalTool(+ const blockingTool = createGlobalTool(async () => {- events.push('waiting:start');+ events.push('blocking:start');await release;- events.push('waiting:end');+ events.push('blocking:end');},- {name: 'waiting_tool', yieldsToolLock: true},+ {name: 'blocking_tool'},);const otherTool = createGlobalTool(async () => {@@ -231,29 +235,30 @@ describe('ToolHandler', () => {{name: 'other_tool'},);- const waitingHandler = createHandler(waitingTool, toolMutex);- const otherHandler = createHandler(otherTool, toolMutex);+ const blockingHandler = createHandler(blockingTool, mockContext);+ const otherHandler = createHandler(otherTool, mockContext);- const waitingResult = waitingHandler.handle({});- // Let the waiting tool enter its handler before the other tool is- // called.+ const blockingResult = blockingHandler.handle({});+ await new Promise(resolve => setImmediate(resolve));+ const otherResult = otherHandler.handle({});await new Promise(resolve => setImmediate(resolve));- const otherResult = await otherHandler.handle({});finishWait();- await waitingResult;+ await Promise.all([blockingResult, otherResult]);assert.deepStrictEqual(events, [- 'waiting:start',+ 'blocking:start',+ 'blocking:end','other:run',- 'waiting:end',]);- assert.strictEqual(otherResult.isError, undefined);});- it('holds the lock for tools that do not yield', async () => {- const toolMutex = new Mutex();+ it('runs a none page tool while an exclusive tool holds the context queue', async () => {+ sinon+ .stub(McpResponse.prototype, 'handle')+ .resolves({content: [], structuredContent: {}});+ const mockContext = createContext();const events: string[] = [];- const {promise: release, resolve: finishWait} =+ const {promise: release, resolve: finishBlocking} =Promise.withResolvers<void>();const blockingTool = createGlobalTool(@@ -264,90 +269,391 @@ describe('ToolHandler', () => {},{name: 'blocking_tool'},);- const otherTool = createGlobalTool(- async () => {- events.push('other:run');+ const waitingTool = definePageTool(() => ({+ name: 'waiting_tool',+ description: 'A page tool that waits for events',+ annotations: {+ category: ToolCategory.DEBUGGING,+ readOnlyHint: true,},- {name: 'other_tool'},- );-- const blockingHandler = createHandler(blockingTool, toolMutex);- const otherHandler = createHandler(otherTool, toolMutex);+ schema: {},+ blockedByDialog: false,+ concurrency: 'none',+ verifyFilesSchema: {},+ handler: async () => {+ events.push('waiting:run');+ },+ }))(parseConfig().resolved);- const blockingResult = blockingHandler.handle({});- await new Promise(resolve => setImmediate(resolve));- const otherResult = otherHandler.handle({});+ const blockingResult = createHandler(blockingTool, mockContext).handle(+ {},+ );await new Promise(resolve => setImmediate(resolve));- finishWait();- await Promise.all([blockingResult, otherResult]);+ const waitingResult = await createHandler(+ waitingTool,+ mockContext,+ ).handle({pageId: 1});+ finishBlocking();+ await blockingResult;+ assert.strictEqual(waitingResult.isError, undefined);assert.deepStrictEqual(events, ['blocking:start',+ 'waiting:run','blocking:end',- 'other:run',]);});+ });++ describe("concurrency: 'page'", () => {+ function createPageTool(+ name: string,+ handler: () => Promise<void>,+ options: {+ concurrency?: DefinedPageTool['concurrency'];+ argv?: string[];+ } = {},+ ): DefinedPageTool {+ return definePageTool(() => ({+ name,+ description: 'A page tool',+ annotations: {+ category: ToolCategory.INPUT,+ readOnlyHint: false,+ },+ schema: {},+ blockedByDialog: false,+ concurrency: options.concurrency ?? 'page',+ verifyFilesSchema: {},+ handler,+ }))(parseConfig(options.argv).resolved);+ }- it('builds the response only after a queued tool releases the lock', async () => {- const toolMutex = new Mutex();+ function createExclusiveTool(+ name: string,+ handler: () => Promise<void>,+ ): ToolDefinition {+ return {+ name,+ description: 'A global tool',+ annotations: {+ category: ToolCategory.NAVIGATION,+ readOnlyHint: true,+ },+ schema: {},+ blockedByDialog: false,+ verifyFilesSchema: {},+ handler,+ };+ }++ function createPages(ids: number[]) {+ const mockContext = createMockMcpContext();+ const mockProcess = sinon.createStubInstance(ChildProcess);+ mockContext.ensureBrowser.resolves(+ getMockBrowser({process: mockProcess}),+ );+ const pages = new Map(ids.map(id => [id, createMockMcpPage({id})]));+ mockContext.getPageById.callsFake(id => {+ const page = pages.get(id);+ assert.ok(page);+ return page;+ });+ return mockContext;+ }++ function createHandler(tool: AnyToolDefinition, mockContext: McpContext) {+ return new ToolHandler(+ tool,+ parseConfig(),+ async () => mockContext,+ sinon.spy(),+ );+ }++ async function settle() {+ await new Promise(resolve => setImmediate(resolve));+ }++ it('runs page tools on different pages at the same time', async () => {+ sinon+ .stub(McpResponse.prototype, 'handle')+ .resolves({content: [], structuredContent: {}});+ const mockContext = createPages([1, 2]);const events: string[] = [];- const {promise: otherBlocked, resolve: unblockOther} =+ const {promise: release, resolve: finishFirst} =Promise.withResolvers<void>();- const waitingTool = createGlobalTool(- async () => {- await new Promise(resolve => setImmediate(resolve));- events.push('waiting:handler-done');- },- {name: 'waiting_tool', yieldsToolLock: true},+ const first = createHandler(+ createPageTool('first', async () => {+ events.push('first:start');+ await release;+ events.push('first:end');+ }),+ mockContext,);- const otherTool = createGlobalTool(- async () => {- events.push('other:start');- await otherBlocked;- events.push('other:end');- },- {name: 'other_tool'},+ const second = createHandler(+ createPageTool('second', async () => {+ events.push('second:run');+ }),+ mockContext,+ );++ const firstResult = first.handle({pageId: 1});+ await settle();+ await second.handle({pageId: 2});+ finishFirst();+ await firstResult;++ assert.deepStrictEqual(events, [+ 'first:start',+ 'second:run',+ 'first:end',+ ]);+ });++ it('serializes page tools on the same page', async () => {+ sinon+ .stub(McpResponse.prototype, 'handle')+ .resolves({content: [], structuredContent: {}});+ const mockContext = createPages([1]);+ const events: string[] = [];+ const {promise: release, resolve: finishFirst} =+ Promise.withResolvers<void>();++ const first = createHandler(+ createPageTool('first', async () => {+ events.push('first:start');+ await release;+ events.push('first:end');+ }),+ mockContext,+ );+ const second = createHandler(+ createPageTool('second', async () => {+ events.push('second:run');+ }),+ mockContext,);- const waitingHandler = createHandler(waitingTool, toolMutex);- const otherHandler = createHandler(otherTool, toolMutex);+ const firstResult = first.handle({pageId: 1});+ await settle();+ const secondResult = second.handle({pageId: 1});+ await settle();+ assert.deepStrictEqual(events, ['first:start']);- const waitingResult = waitingHandler.handle({}).then(result => {- events.push('waiting:result');- return result;+ finishFirst();+ await Promise.all([firstResult, secondResult]);+ assert.deepStrictEqual(events, [+ 'first:start',+ 'first:end',+ 'second:run',+ ]);+ });++ it('queues an exclusive tool behind running page tools in FIFO order', async () => {+ sinon+ .stub(McpResponse.prototype, 'handle')+ .resolves({content: [], structuredContent: {}});+ const mockContext = createPages([1, 2]);+ const events: string[] = [];+ const {promise: release, resolve: finishFirst} =+ Promise.withResolvers<void>();++ const pageTool = createHandler(+ createPageTool('page_tool', async () => {+ events.push('page:start');+ await release;+ events.push('page:end');+ }),+ mockContext,+ );+ const exclusiveTool = createHandler(+ createExclusiveTool('exclusive_tool', async () => {+ events.push('exclusive:run');+ }),+ mockContext,+ );+ const latePageTool = createHandler(+ createPageTool('late_page_tool', async () => {+ events.push('late:run');+ }),+ mockContext,+ );++ const pageResult = pageTool.handle({pageId: 1});+ await settle();+ const exclusiveResult = exclusiveTool.handle({});+ await settle();+ // Targets another page, but waits behind the queued exclusive tool.+ const lateResult = latePageTool.handle({pageId: 2});+ await settle();+ assert.deepStrictEqual(events, ['page:start']);++ finishFirst();+ await Promise.all([pageResult, exclusiveResult, lateResult]);+ assert.deepStrictEqual(events, [+ 'page:start',+ 'page:end',+ 'exclusive:run',+ 'late:run',+ ]);+ });++ it('holds the page queue until the response is built', async () => {+ const {promise: responseReady, resolve: finishResponse} =+ Promise.withResolvers<void>();+ const handleStub = sinon.stub(McpResponse.prototype, 'handle');+ handleStub.onFirstCall().callsFake(async () => {+ await responseReady;+ return {content: [], structuredContent: {}};});- 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]);+ handleStub.resolves({content: [], structuredContent: {}});+ const mockContext = createPages([1]);+ const events: string[] = [];++ const first = createHandler(+ createPageTool('first', async () => {+ events.push('first:run');+ }),+ mockContext,+ );+ const second = createHandler(+ createPageTool('second', async () => {+ events.push('second:run');+ }),+ mockContext,+ );++ const firstResult = first.handle({pageId: 1});+ await settle();+ const secondResult = second.handle({pageId: 1});+ await settle();+ assert.deepStrictEqual(events, ['first:run']);++ finishResponse();+ await Promise.all([firstResult, secondResult]);+ assert.deepStrictEqual(events, ['first:run', 'second:run']);+ });++ it('runs the call on the page queue', async () => {+ sinon+ .stub(McpResponse.prototype, 'handle')+ .resolves({content: [], structuredContent: {}});+ const mockContext = createPages([7]);+ const events: string[] = [];+ const {promise: release, resolve: finishHandler} =+ Promise.withResolvers<void>();++ const result = createHandler(+ createPageTool('page_tool', async () => {+ events.push('handler:start');+ await release;+ events.push('handler:end');+ }),+ mockContext,+ ).handle({pageId: 7});+ await settle();+ const pageTask = runOn(mockContext.pageTaskQueue(7), async () => {+ events.push('page-task');+ });+ const contextTask = runOn(mockContext.taskQueue, async () => {+ events.push('context-task');+ });+ await settle();+ assert.deepStrictEqual(events, ['handler:start']);+ finishHandler();+ await Promise.all([result, pageTask, contextTask]);assert.deepStrictEqual(events, [- 'other:start',- 'waiting:handler-done',- 'other:end',- 'waiting:result',+ 'handler:start',+ 'handler:end',+ 'page-task',+ 'context-task',]);});- it('re-acquires the lock when a yielding handler throws', async () => {- const toolMutex = new Mutex();- const tool = createGlobalTool(- async () => {+ it('runs a page tool without pageId on the context queue', async () => {+ sinon+ .stub(McpResponse.prototype, 'handle')+ .resolves({content: [], structuredContent: {}});+ const argv = ['--no-page-id-routing'];+ const mockContext = createPages([]);+ const {promise: release, resolve: finishHandler} =+ Promise.withResolvers<void>();++ const result = new ToolHandler(+ createPageTool(+ 'page_tool',+ async () => {+ await release;+ },+ {argv},+ ),+ parseConfig(argv),+ async () => mockContext,+ sinon.spy(),+ ).handle({});+ await settle();+ let contextTaskRan = false;+ const contextTask = runOn(mockContext.taskQueue, async () => {+ contextTaskRan = true;+ });+ await settle();+ assert.strictEqual(contextTaskRan, false);+ sinon.assert.notCalled(mockContext.pageTaskQueue);++ finishHandler();+ await Promise.all([result, contextTask]);+ assert.strictEqual(contextTaskRan, true);+ });++ it('releases the page queue when the handler throws', async () => {+ sinon+ .stub(McpResponse.prototype, 'handle')+ .resolves({content: [], structuredContent: {}});+ const mockContext = createPages([1]);++ const result = await createHandler(+ createPageTool('failing', async () => {throw new Error('handler failed');- },- {yieldsToolLock: true},- );- const handler = createHandler(tool, toolMutex);+ }),+ mockContext,+ ).handle({pageId: 1});- const result = await handler.handle({});+ assert.strictEqual(result.isError, true);+ await runOn(mockContext.pageTaskQueue(1), async () => {});+ });++ it('fails a waiting page tool when the page queue is disposed', async () => {+ sinon+ .stub(McpResponse.prototype, 'handle')+ .resolves({content: [], structuredContent: {}});+ const mockContext = createPages([1]);+ const handler = sinon.stub<[], Promise<void>>().resolves();+ const {promise: release, resolve: finishFirst} =+ Promise.withResolvers<void>();+ const first = createHandler(+ createPageTool('first', async () => {+ await release;+ }),+ mockContext,+ ).handle({pageId: 1});+ await settle();+ const second = createHandler(+ createPageTool('second', handler),+ mockContext,+ ).handle({pageId: 1});+ await settle();+ mockContext.pageTaskQueue(1).dispose(new Error('Page 1 is closed.'));+ finishFirst();++ const [, result] = await Promise.all([first, second]);assert.strictEqual(result.isError, true);- // The lock is free again: a plain acquire must resolve.- const guard = await toolMutex.acquire();- guard[Symbol.dispose]();+ assert.ok(result.content[0].type === 'text');+ assert.match(result.content[0].text, /Page 1 is closed\./);+ sinon.assert.notCalled(handler);});});@@ -378,7 +684,7 @@ describe('ToolHandler', () => {verifyFilesSchema: {},handler: async () => undefined,};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();mockContext.ensureBrowser.resolves(getMockBrowser({process: sinon.createStubInstance(ChildProcess),@@ -393,7 +699,6 @@ describe('ToolHandler', () => {tool,config,async () => mockContext,- new Mutex(),sinon.spy(),).handle({});@@ -448,7 +753,7 @@ describe('ToolHandler', () => {handlerCalled = true;};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}),@@ -463,13 +768,10 @@ describe('ToolHandler', () => {logToolInvocation: logSpy,} as unknown as ClearcutLogger);- const toolMutex = new Mutex();-const toolHandler = new ToolHandler(testCase.tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -506,16 +808,14 @@ describe('ToolHandler', () => {},};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();- const toolMutex = new Mutex();const config = parseConfig();const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -558,15 +858,13 @@ describe('ToolHandler', () => {},};- const mockContext = sinon.createStubInstance(McpContext);- const toolMutex = new Mutex();+ const mockContext = createMockMcpContext();const config = parseConfig(['--categoryEmulation=false']);const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -582,8 +880,7 @@ describe('ToolHandler', () => {});it('registers evaluate_script by default and disables it when javascriptEvaluation is false', async () => {- const mockContext = sinon.createStubInstance(McpContext);- const toolMutex = new Mutex();+ const mockContext = createMockMcpContext();const defaultConfig = parseConfig();const defaultTool = createTools(defaultConfig.resolved).find(@@ -596,7 +893,6 @@ describe('ToolHandler', () => {defaultTool,defaultConfig,async () => mockContext,- toolMutex,sinon.spy(),);assert.strictEqual(defaultHandler.disabled, false);@@ -612,7 +908,6 @@ describe('ToolHandler', () => {disabledTool,disabledConfig,async () => mockContext,- toolMutex,sinon.spy(),);assert.strictEqual(disabledHandler.disabled, true);@@ -637,7 +932,6 @@ describe('ToolHandler', () => {cliTool,cliConfig,async () => mockContext,- toolMutex,sinon.spy(),);assert.strictEqual(cliHandler.disabled, false);@@ -650,8 +944,7 @@ describe('ToolHandler', () => {});it('disables slim evaluate tool when javascriptEvaluation is false', async () => {- const mockContext = sinon.createStubInstance(McpContext);- const toolMutex = new Mutex();+ const mockContext = createMockMcpContext();const defaultConfig = parseConfig(['--slim']);const defaultTool = createTools(defaultConfig.resolved).find(@@ -664,7 +957,6 @@ describe('ToolHandler', () => {defaultTool,defaultConfig,async () => mockContext,- toolMutex,sinon.spy(),);assert.strictEqual(defaultHandler.disabled, false);@@ -683,7 +975,6 @@ describe('ToolHandler', () => {disabledTool,disabledConfig,async () => mockContext,- toolMutex,sinon.spy(),);assert.strictEqual(disabledHandler.disabled, true);@@ -699,8 +990,7 @@ describe('ToolHandler', () => {return new ToolHandler(tool,config,- async () => sinon.createStubInstance(McpContext),- new Mutex(),+ async () => createMockMcpContext(),sinon.spy(),);}@@ -769,7 +1059,7 @@ describe('ToolHandler', () => {},};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}));mockContext.validatePath.callsFake(async p => {@@ -782,14 +1072,12 @@ describe('ToolHandler', () => {);});- const toolMutex = new Mutex();const config = parseConfig();const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -850,21 +1138,19 @@ describe('ToolHandler', () => {},};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}));mockContext.validatePath.rejects(new Error('Access denied: path is outside roots'),);- const toolMutex = new Mutex();const config = parseConfig();const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -883,7 +1169,7 @@ describe('ToolHandler', () => {it('validates evaluate_script sourcePath before reading the file', async () => {const config = parseConfig();const tool = evaluateScript(config.resolved);- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}));mockContext.validatePath.rejects(@@ -894,7 +1180,6 @@ describe('ToolHandler', () => {tool,config,async () => mockContext,- new Mutex(),sinon.spy(),);const sourcePath = path.resolve('/outside/workspace/script.js');@@ -936,20 +1221,18 @@ describe('ToolHandler', () => {},};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}));const canonicalPath = path.resolve('/canonical/workspace/upload.png');mockContext.validatePath.resolves(canonicalPath);- const toolMutex = new Mutex();const config = parseConfig();const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -991,7 +1274,7 @@ describe('ToolHandler', () => {},};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();mockContext.ensureBrowser.resolves(getMockBrowser({wsEndpoint: 'ws://127.0.0.1:9222/devtools/browser/test',@@ -1000,14 +1283,12 @@ describe('ToolHandler', () => {const canonicalBundlePath = path.resolve('/canonical/workspace/app.swbn');mockContext.validatePath.resolves(canonicalBundlePath);- const toolMutex = new Mutex();const config = parseConfig();const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -1054,21 +1335,19 @@ describe('ToolHandler', () => {},};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();mockContext.ensureBrowser.resolves(getMockBrowser({wsEndpoint: 'ws://remote-host.com:9222/devtools/browser/test',}),);- const toolMutex = new Mutex();const config = parseConfig();const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -1107,17 +1386,15 @@ describe('ToolHandler', () => {},};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();mockContext.ensureBrowser.resolves(getMockBrowser());- const toolMutex = new Mutex();const config = parseConfig();const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -1154,18 +1431,16 @@ describe('ToolHandler', () => {},};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}));- const toolMutex = new Mutex();const config = parseConfig();const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -1203,18 +1478,16 @@ describe('ToolHandler', () => {},};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}));- const toolMutex = new Mutex();const config = parseConfig();const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -1258,7 +1531,7 @@ describe('ToolHandler', () => {},};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();mockContext.ensureBrowser.resolves(getMockBrowser({wsEndpoint: 'ws://remote-host.com:9222/devtools/browser/test',@@ -1267,14 +1540,12 @@ describe('ToolHandler', () => {const canonicalOutputPath = path.resolve('/canonical/output.json');mockContext.validatePath.resolves(canonicalOutputPath);- const toolMutex = new Mutex();const config = parseConfig();const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -1320,21 +1591,19 @@ describe('ToolHandler', () => {},};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}));mockContext.validatePath.rejects(new Error('Path is outside configured roots'),);- const toolMutex = new Mutex();const config = parseConfig();const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -1373,11 +1642,10 @@ describe('ToolHandler', () => {},};- const toolMutex = new Mutex();const config = parseConfig();// Remote browser: should validate- const mockRemoteContext = sinon.createStubInstance(McpContext);+ const mockRemoteContext = createMockMcpContext();mockRemoteContext.ensureBrowser.resolves(getMockBrowser({wsEndpoint: 'ws://remote-host.com:9222/devtools/browser/test',@@ -1389,7 +1657,6 @@ describe('ToolHandler', () => {tool,config,async () => mockRemoteContext,- toolMutex,sinon.spy(),);@@ -1401,7 +1668,7 @@ describe('ToolHandler', () => {);// Local browser: should skip- const mockLocalContext = sinon.createStubInstance(McpContext);+ const mockLocalContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockLocalContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}),@@ -1411,7 +1678,6 @@ describe('ToolHandler', () => {tool,config,async () => mockLocalContext,- toolMutex,sinon.spy(),);@@ -1441,7 +1707,7 @@ describe('ToolHandler', () => {},}))(config.resolved);- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}));mockContext.getDevToolsData.resolves({});@@ -1460,13 +1726,10 @@ describe('ToolHandler', () => {const canonicalFilePath = path.resolve('/canonical/output.png');mockContext.validatePath.resolves(canonicalFilePath);- const toolMutex = new Mutex();-const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -1516,7 +1779,6 @@ describe('ToolHandler', () => {tool,config,async () => mockContext,- new Mutex(),sinon.spy(),);@@ -1554,18 +1816,16 @@ describe('ToolHandler', () => {},};- const mockContext = sinon.createStubInstance(McpContext);+ const mockContext = createMockMcpContext();const mockProcess = sinon.createStubInstance(ChildProcess);mockContext.ensureBrowser.resolves(getMockBrowser({process: mockProcess}));- const toolMutex = new Mutex();const config = parseConfig();const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,sinon.spy(),);@@ -1611,14 +1871,12 @@ describe('ToolHandler', () => {);const abandonPendingBrowserAttemptSpy = sinon.spy();- const toolMutex = new Mutex();const config = parseConfig();const toolHandler = new ToolHandler(tool,config,async () => mockContext,- toolMutex,abandonPendingBrowserAttemptSpy,);@@ -1665,7 +1923,6 @@ describe('ToolHandler', () => {tool,config,async () => context,- new Mutex(),sinon.spy(),);@@ -1707,7 +1964,6 @@ describe('ToolHandler', () => {createBrowserlessTool(handler),parseConfig(),async () => mockContext,- new Mutex(),sinon.spy(),).handle({filePath: 'file.heapsnapshot'});@@ -1727,6 +1983,56 @@ describe('ToolHandler', () => {);sinon.assert.calledOnceWithExactly(handleStub, mockContext, 'default');});++ it('defaults to concurrency none', () => {+ const tool = createBrowserlessTool(sinon.stub().resolves());+ assert.strictEqual(tool.concurrency, 'none');+ });++ it('does not enter the context queue', async () => {+ const mockContext = createMockMcpContext();+ mockContext.validatePath.resolves('/canonical/file.heapsnapshot');+ sinon+ .stub(McpResponse.prototype, 'handle')+ .resolves({content: [], structuredContent: {}});+ const scheduleTask = sinon.stub(mockContext.taskQueue, 'scheduleTask');++ const result = await new ToolHandler(+ createBrowserlessTool(sinon.stub().resolves()),+ parseConfig(),+ async () => mockContext,+ sinon.spy(),+ ).handle({filePath: 'file.heapsnapshot'});++ assert.strictEqual(result.isError, undefined);+ sinon.assert.notCalled(scheduleTask);+ });++ it('runs while another tool holds the context queue', async () => {+ const mockContext = createMockMcpContext();+ mockContext.validatePath.resolves('/canonical/file.heapsnapshot');+ sinon+ .stub(McpResponse.prototype, 'handle')+ .resolves({content: [], structuredContent: {}});+ const handler = sinon.stub().resolves();+ const {promise: release, resolve: finishExclusive} =+ Promise.withResolvers<void>();++ const exclusive = runOn(mockContext.taskQueue, async () => {+ await release;+ });+ const result = await new ToolHandler(+ createBrowserlessTool(handler),+ parseConfig(),+ async () => mockContext,+ sinon.spy(),+ ).handle({filePath: 'file.heapsnapshot'});+ finishExclusive();+ await exclusive;++ assert.strictEqual(result.isError, undefined);+ sinon.assert.calledOnce(handler);+ });});describe('update', () => {@@ -1752,24 +2058,24 @@ describe('ToolHandler', () => {};}- it('applies to calls that wait for the mutex', async () => {+ it('applies to calls that wait for the queue', async () => {const config = parseConfig();const handler = sinon.stub().resolves();const tool = createGlobalTool({}, handler);- const toolMutex = new Mutex();+ const taskRunner = new TaskRunner();+ const mockContext = createMockMcpContext({taskRunner});const toolHandler = new ToolHandler(tool,config,- async () => createMockMcpContext(),- toolMutex,+ async () => mockContext,sinon.spy(),);- await toolMutex.acquire();+ const guard = await taskRunner.pause();const call = toolHandler.handle({});config.commit(parseConfig(['--no-category-navigation']));toolHandler.update(tool);- toolMutex.release();+ guard[Symbol.dispose]();const result = await call;assert.strictEqual(result.isError, true);@@ -1783,16 +2089,16 @@ describe('ToolHandler', () => {it('validates waiting calls against the updated schema', async () => {const config = parseConfig();const handler = sinon.stub().resolves();- const toolMutex = new Mutex();+ const taskRunner = new TaskRunner();+ const mockContext = createMockMcpContext({taskRunner});const toolHandler = new ToolHandler(createGlobalTool({a: zod.string().optional()}, handler),config,- async () => createMockMcpContext(),- toolMutex,+ async () => mockContext,sinon.spy(),);- await toolMutex.acquire();+ const guard = await taskRunner.pause();const call = toolHandler.handle({a: 'value'});const listingChanged = toolHandler.update(createGlobalTool(@@ -1800,7 +2106,7 @@ describe('ToolHandler', () => {handler,),);- toolMutex.release();+ guard[Symbol.dispose]();const result = await call;assert.strictEqual(listingChanged, true);@@ -1816,23 +2122,22 @@ describe('ToolHandler', () => {const config = parseConfig();const initialHandler = sinon.stub().resolves();const updatedHandler = sinon.stub().resolves();- const toolMutex = new Mutex();- const mockContext = createMockMcpContext();+ const taskRunner = new TaskRunner();+ const mockContext = createMockMcpContext({taskRunner});mockContext.ensureBrowser.resolves(getMockBrowser());const toolHandler = new ToolHandler(createGlobalTool({a: zod.string()}, initialHandler),config,async () => mockContext,- toolMutex,sinon.spy(),);- await toolMutex.acquire();+ const guard = await taskRunner.pause();const call = toolHandler.handle({a: 'value', b: 'extra'});const listingChanged = toolHandler.update(createGlobalTool({a: zod.string(), b: zod.string()}, updatedHandler),);- toolMutex.release();+ guard[Symbol.dispose]();const result = await call;assert.strictEqual(listingChanged, true);@@ -1850,20 +2155,20 @@ describe('ToolHandler', () => {const config = parseConfig();const handler = sinon.stub().resolves();const tool = createGlobalTool({}, handler);- const toolMutex = new Mutex();+ const taskRunner = new TaskRunner();+ const mockContext = createMockMcpContext({taskRunner});const toolHandler = new ToolHandler(tool,config,- async () => createMockMcpContext(),- toolMutex,+ async () => mockContext,sinon.spy(),);- await toolMutex.acquire();+ const guard = await taskRunner.pause();const call = toolHandler.handle({}, {viaMcp: true});config.commit(parseConfig(['--no-category-navigation']));toolHandler.update(tool);- toolMutex.release();+ guard[Symbol.dispose]();await assert.rejects(call, (error: unknown) => {assert.ok(error instanceof ProtocolError);@@ -1878,24 +2183,23 @@ describe('ToolHandler', () => {const config = parseConfig();const initialHandler = sinon.stub().resolves();const updatedHandler = sinon.stub().resolves();- const toolMutex = new Mutex();- const mockContext = createMockMcpContext();+ const taskRunner = new TaskRunner();+ const mockContext = createMockMcpContext({taskRunner});mockContext.ensureBrowser.resolves(getMockBrowser());const toolHandler = new ToolHandler(createGlobalTool({a: zod.string().optional()}, initialHandler),config,async () => mockContext,- toolMutex,sinon.spy(),);- await toolMutex.acquire();+ const guard = await taskRunner.pause();const call = toolHandler.handle({a: 'value'});config.commit(parseConfig(['--redact-network-headers']));const listingChanged = toolHandler.update(createGlobalTool({a: zod.string().optional()}, updatedHandler),);- toolMutex.release();+ guard[Symbol.dispose]();await call;assert.strictEqual(listingChanged, false);@@ -1915,7 +2219,6 @@ describe('ToolHandler', () => {tool,config,async () => createMockMcpContext(),- new Mutex(),sinon.spy(),);@@ -1933,7 +2236,6 @@ describe('ToolHandler', () => {createGlobalTool({}, handler),config,async () => createMockMcpContext(),- new Mutex(),sinon.spy(),);@@ -1964,7 +2266,6 @@ describe('ToolHandler', () => {createGlobalTool({a: zod.string().optional()}, handler),config,async () => createMockMcpContext(),- new Mutex(),sinon.spy(),);diff --git a/tests/formatters/HeapSnapshotFormatter.test.ts b/tests/formatters/HeapSnapshotFormatter.test.tsindex e591f8ba..b31b3291 100644--- a/tests/formatters/HeapSnapshotFormatter.test.ts+++ b/tests/formatters/HeapSnapshotFormatter.test.ts@@ -22,6 +22,7 @@ import {} from '../../src/processors/HeapSnapshotManager.js';import {DevTools} from '../../src/third_party/index.js';import {parseByteSizeRange} from '../../src/utils/bytes.js';+import {TaskRunner} from '../../src/utils/TaskRunner.js';import {createMockContextAnalysisResult} from '../mocks.js';const {formatBytesToKb} = DevTools.I18n.ByteUtilities;@@ -500,7 +501,7 @@ describe('HeapSnapshotFormatter', () => {const heap3Path = join(process.cwd(), 'tests/fixtures/heap-3.heapsnapshot');before(() => {- manager = new HeapSnapshotManager();+ manager = new HeapSnapshotManager(new TaskRunner());});after(() => {diff --git a/tests/index.test.ts b/tests/index.test.tsindex dfa8de3c..d6158e00 100644--- a/tests/index.test.ts+++ b/tests/index.test.ts@@ -239,11 +239,54 @@ describe('e2e', {concurrency: true}, () => {);});+ it('makes concurrent first calls wait for the same roots/list', async () => {+ const fixturesRoot = path.resolve('tests/fixtures');+ await withClient(+ async client => {+ // Answers late enough that both calls start before the roots arrive.+ // Browserless tools hold no lock, so without a shared initial roots+ // request the second call validates its path against no roots.+ client.setRequestHandler('roots/list', async () => {+ await new Promise(resolve => setTimeout(resolve, 1_000));+ return {+ roots: [{uri: pathToFileURL(fixturesRoot).href, name: 'fixtures'}],+ };+ });++ const results = await Promise.all([+ client.callTool({+ name: 'get_heapsnapshot_summary',+ arguments: {+ filePath: path.join(fixturesRoot, 'example.heapsnapshot'),+ },+ }),+ client.callTool({+ name: 'get_heapsnapshot_summary',+ arguments: {+ filePath: path.join(fixturesRoot, 'example.heapsnapshot'),+ },+ }),+ ]);++ for (const result of results) {+ const content = result.content as TextContent[];+ assert.strictEqual(result.isError, undefined, content[0]?.text);+ }+ },+ ['--memoryDebugging'],+ {+ capabilities: {+ roots: {listChanged: true},+ },+ },+ );+ });+it('does not block tools if the client never answers roots/list', async () => {await withClient(async client => {// A client that negotiates roots but never responds. getContext()- // awaits updateRoots() while holding the tool mutex, so an unbounded+ // awaits updateRoots() while holding the context lock, so an unbounded// request would stall this call for the SDK default of 60s.client.setRequestHandler('roots/list', () => {return new Promise<never>(() => {diff --git a/tests/mocks.ts b/tests/mocks.tsindex 45608a70..d831a903 100644--- a/tests/mocks.ts+++ b/tests/mocks.ts@@ -35,6 +35,7 @@ import {McpContext} from '../src/McpContext.js';import {McpPage} from '../src/McpPage.js';import {McpResponse} from '../src/McpResponse.js';import {McpWorker, type WorkerType} from '../src/McpWorker.js';+import {TaskRunner, type TaskQueue} from '../src/utils/TaskRunner.js';import type {DuplicateStringGroup,HeapSnapshotAggregate,@@ -435,12 +436,16 @@ export function createMockPuppeteerTarget(export function createMockMcpPage(options: {+ id?: number;pptrPage?: MockPuppeteerPage;target?: sinon.SinonStubbedInstance<MockTarget>;} = {},): MockMcpPage {const page = sinon.createStubInstance(McpPage);page.emulationSettings = {};+ if (options.id !== undefined) {+ Object.defineProperty(page, 'id', {value: options.id});+ }const pptrPage = options.pptrPage ?? createMockPuppeteerPage();const target = options.target ?? createMockPuppeteerTarget({page: pptrPage});page.init.resolves();@@ -539,12 +544,25 @@ export function createMockMcpWorker(}export function createMockMcpContext(- options: {selectedPage?: MockMcpPage} = {},+ options: {selectedPage?: MockMcpPage; taskRunner?: TaskRunner} = {},): MockMcpContext {const context = sinon.createStubInstance(McpContext);const page = options.selectedPage ?? createMockMcpPage();context.getSelectedMcpPage.returns(page satisfies McpPage);context.getTargetInfos.resolves(new Map());+ // Real queues, so handler tests observe the real scheduling.+ const taskRunner = options.taskRunner ?? new TaskRunner();+ const taskQueue = taskRunner.createQueue();+ Object.defineProperty(context, 'taskQueue', {value: taskQueue});+ const pageTaskQueues = new Map<number, TaskQueue>();+ context.pageTaskQueue.callsFake(pageId => {+ let queue = pageTaskQueues.get(pageId);+ if (!queue) {+ queue = taskRunner.createQueue(taskQueue);+ pageTaskQueues.set(pageId, queue);+ }+ return queue;+ });return context;}diff --git a/tests/processors/HeapSnapshotManager.test.ts b/tests/processors/HeapSnapshotManager.test.tsindex dc06dcca..1f8e2222 100644--- a/tests/processors/HeapSnapshotManager.test.ts+++ b/tests/processors/HeapSnapshotManager.test.ts@@ -10,11 +10,12 @@ import {describe, it, after, before} from 'node:test';import sinon from 'sinon';import {HeapSnapshotManager} from '../../src/processors/HeapSnapshotManager.js';+import {TaskRunner} from '../../src/utils/TaskRunner.js';import {DevTools} from '../../src/third_party/index.js';describe('HeapSnapshotManager', () => {it('rejects when a file without .heapsnapshot or .heaptimeline extension is passed', async () => {- const manager = new HeapSnapshotManager();+ const manager = new HeapSnapshotManager(new TaskRunner());await assert.rejects(manager.getSnapshot('tests/fixtures/snapshot_diffs.js'),@@ -29,7 +30,7 @@ describe('HeapSnapshotManager', () => {'dispose',);- const manager = new HeapSnapshotManager();+ const manager = new HeapSnapshotManager(new TaskRunner());// A path that passes into #loadSnapshot but fails on read. The worker is// created before the read, so a failed load must still dispose it,@@ -51,7 +52,7 @@ describe('HeapSnapshotManager', () => {let manager: HeapSnapshotManager;before(() => {- manager = new HeapSnapshotManager();+ manager = new HeapSnapshotManager(new TaskRunner());});after(() => {@@ -108,7 +109,7 @@ describe('HeapSnapshotManager', () => {let manager: HeapSnapshotManager;before(() => {- manager = new HeapSnapshotManager();+ manager = new HeapSnapshotManager(new TaskRunner());});after(() => {@@ -124,7 +125,7 @@ describe('HeapSnapshotManager', () => {});it('resolves class IDs in getNodesById without calling getAggregates first', async () => {- const freshManager = new HeapSnapshotManager();+ const freshManager = new HeapSnapshotManager(new TaskRunner());try {const {aggregates} = await manager.getAggregates(filePath);const functionAggregate = aggregates.find(@@ -150,7 +151,7 @@ describe('HeapSnapshotManager', () => {});it('assigns deterministic class IDs even when getAggregates is called with a filter first', async () => {- const filteredFirstManager = new HeapSnapshotManager();+ const filteredFirstManager = new HeapSnapshotManager(new TaskRunner());try {const unfilteredFirst = await manager.getAggregates(filePath);const unfilteredById = new Map(@@ -182,7 +183,7 @@ describe('HeapSnapshotManager', () => {});it('gets stats and staticData, and disposes snapshot', async () => {- const manager = new HeapSnapshotManager();+ const manager = new HeapSnapshotManager(new TaskRunner());try {const filePath = 'tests/fixtures/example.heapsnapshot';const stats = await manager.getStats(filePath);@@ -201,4 +202,27 @@ describe('HeapSnapshotManager', () => {manager.dispose();}});++ it('makes disposeSnapshot wait for an in-flight read of the same file', async () => {+ const manager = new HeapSnapshotManager(new TaskRunner());+ try {+ const filePath = 'tests/fixtures/example.heapsnapshot';+ const order: string[] = [];+ const read = manager.getStats(filePath).then(stats => {+ order.push('read');+ return stats;+ });+ const dispose = manager.disposeSnapshot(filePath).then(disposed => {+ order.push('dispose');+ return disposed;+ });+ const [stats, disposed] = await Promise.all([read, dispose]);+ assert.ok(stats.total > 0);+ assert.strictEqual(disposed, true);+ assert.deepStrictEqual(order, ['read', 'dispose']);+ assert.strictEqual(manager.hasSnapshots(), false);+ } finally {+ manager.dispose();+ }+ });});diff --git a/tests/roots.test.ts b/tests/roots.test.tsindex 6b7003af..b09ebdd8 100644--- a/tests/roots.test.ts+++ b/tests/roots.test.ts@@ -15,6 +15,7 @@ import sinon from 'sinon';import type {McpContext} from '../src/McpContext.js';import {HeapSnapshotManager} from '../src/processors/HeapSnapshotManager.js';+import {TaskRunner} from '../src/utils/TaskRunner.js';import {resolveCanonicalPath} from '../src/utils/files.js';import {escapeForLog} from '../src/utils/logger.js';@@ -176,7 +177,7 @@ describe('McpContext path validation escaping', () => {config: createMockServerConfig({performanceCrux: false,}),- heapSnapshotManager: new HeapSnapshotManager(),+ heapSnapshotManager: new HeapSnapshotManager(new TaskRunner()),});}diff --git a/tests/tools/comments.test.ts b/tests/tools/comments.test.tsindex 135ba270..29b6285a 100644--- a/tests/tools/comments.test.ts+++ b/tests/tools/comments.test.ts@@ -89,9 +89,9 @@ describe('comments tools', () => {]);});- it('yields the tool lock while waiting', () => {+ it('runs the handler unlocked while waiting', () => {const {args} = createHandlerMocks();- assert.strictEqual(getDevtoolsComments(args).yieldsToolLock, true);+ assert.strictEqual(getDevtoolsComments(args).concurrency, 'none');});it('waits for a comment event and fetches again', async () => {diff --git a/tests/utils.ts b/tests/utils.tsindex 0ebf7ab6..eac542af 100644--- a/tests/utils.ts+++ b/tests/utils.ts@@ -34,6 +34,7 @@ import {isDaemonRunning} from '../src/daemon/utils.js';import {McpContext, type McpContextOptions} from '../src/McpContext.js';import {McpResponse} from '../src/McpResponse.js';import {HeapSnapshotManager} from '../src/processors/HeapSnapshotManager.js';+import {TaskRunner} from '../src/utils/TaskRunner.js';import {TextSnapshot} from '../src/TextSnapshot.js';import {DevTools} from '../src/third_party/index.js';import {stableIdSymbol} from '../src/utils/id.js';@@ -177,12 +178,18 @@ export async function withBrowser(*/export async function createConnectedMcpContext(browser: Browser,- options: Omit<McpContextOptions, 'getBrowser'>,+ options: Omit<McpContextOptions, 'getBrowser' | 'taskRunner'> & {+ taskRunner?: TaskRunner;+ },locatorClass?: typeof Locator,): Promise<McpContext> {const context = McpContext.create(undefined,- {...options, getBrowser: async () => browser},+ {+ taskRunner: new TaskRunner(),+ ...options,+ getBrowser: async () => browser,+ },locatorClass,);await context.ensureBrowser();@@ -225,7 +232,7 @@ export async function withMcpContext(}),});const response = new McpResponse(parsedArgs);- const heapSnapshotManager = new HeapSnapshotManager();+ const heapSnapshotManager = new HeapSnapshotManager(new TaskRunner());if (context) {context.dispose();}diff --git a/tests/utils/TaskRunner.test.ts b/tests/utils/TaskRunner.test.tsnew file mode 100644index 00000000..b804399e--- /dev/null+++ b/tests/utils/TaskRunner.test.ts@@ -0,0 +1,271 @@+/**+ * @license+ * Copyright 2026 Google LLC+ * SPDX-License-Identifier: Apache-2.0+ */++import assert from 'node:assert';+import {describe, it} from 'node:test';++import sinon from 'sinon';++import {TaskRunner, type TaskQueue} from '../../src/utils/TaskRunner.js';++async function settle(): Promise<void> {+ await new Promise(resolve => setImmediate(resolve));+}++interface ControlledTask {+ /** True once the queue is held. */+ started: boolean;+ /** Settles when the queue is released. */+ done: Promise<void>;+ /** Releases the queue. */+ finish: () => void;+}++/** Acquires `queue` and holds it until `finish()` is called. */+function start(queue: TaskQueue): ControlledTask {+ const {promise: release, resolve: finish} = Promise.withResolvers<void>();+ const controlled: ControlledTask = {+ started: false,+ done: Promise.resolve(),+ finish,+ };+ controlled.done = (async () => {+ using guard = await queue.scheduleTask();+ controlled.started = true;+ await release;+ })();+ return controlled;+}++function createTree() {+ const runner = new TaskRunner();+ const parent = runner.createQueue();+ const childA = runner.createQueue(parent);+ const childB = runner.createQueue(parent);+ return {runner, parent, childA, childB};+}++describe('TaskRunner', () => {+ it('runs tasks on unrelated queues at the same time', async () => {+ const {childA, childB} = createTree();+ const a = start(childA);+ const b = start(childB);+ await settle();+ assert.strictEqual(a.started, true);+ assert.strictEqual(b.started, true);+ a.finish();+ b.finish();+ await Promise.all([a.done, b.done]);+ });++ it('runs tasks on queues of different roots at the same time', async () => {+ const runner = new TaskRunner();+ const a = start(runner.createQueue());+ const b = start(runner.createQueue());+ await settle();+ assert.strictEqual(a.started, true);+ assert.strictEqual(b.started, true);+ a.finish();+ b.finish();+ await Promise.all([a.done, b.done]);+ });++ it('serializes holders of one queue in FIFO order', async () => {+ const queue = new TaskRunner().createQueue();+ const order: number[] = [];+ await Promise.all(+ [1, 2, 3].map(async id => {+ using guard = await queue.scheduleTask();+ await settle();+ order.push(id);+ }),+ );+ assert.deepStrictEqual(order, [1, 2, 3]);+ });++ it('orders by queue, not by task duration', async () => {+ const clock = sinon.useFakeTimers();+ try {+ const runner = new TaskRunner();+ const order: string[] = [];+ const run = async (queue: TaskQueue, name: string, ms: number) => {+ using guard = await queue.scheduleTask();+ await new Promise(resolve => setTimeout(resolve, ms));+ order.push(name);+ };++ const shared = runner.createQueue();+ const sameQueue = Promise.all([+ run(shared, 'slow', 300),+ run(shared, 'fast', 100),+ ]);+ await clock.tickAsync(1_000);+ await sameQueue;+ assert.deepStrictEqual(order, ['slow', 'fast']);++ order.length = 0;+ const unrelated = Promise.all([+ run(runner.createQueue(), 'slow', 300),+ run(runner.createQueue(), 'fast', 100),+ ]);+ await clock.tickAsync(1_000);+ await unrelated;+ assert.deepStrictEqual(order, ['fast', 'slow']);+ } finally {+ clock.restore();+ }+ });++ it('makes a parent task wait for a running child task', async () => {+ const {parent, childA} = createTree();+ const child = start(childA);+ const parentTask = start(parent);+ await settle();+ assert.strictEqual(parentTask.started, false);+ child.finish();+ await settle();+ assert.strictEqual(parentTask.started, true);+ parentTask.finish();+ await Promise.all([child.done, parentTask.done]);+ });++ it('makes a child task wait for a running parent task', async () => {+ const {parent, childA} = createTree();+ const parentTask = start(parent);+ const child = start(childA);+ await settle();+ assert.strictEqual(child.started, false);+ parentTask.finish();+ await settle();+ assert.strictEqual(child.started, true);+ child.finish();+ await Promise.all([child.done, parentTask.done]);+ });++ it('blocks a later child task behind a waiting parent task', async () => {+ const {parent, childA, childB} = createTree();+ const a = start(childA);+ const parentTask = start(parent);+ const b = start(childB);+ await settle();+ assert.strictEqual(b.started, false);+ a.finish();+ await settle();+ assert.strictEqual(parentTask.started, true);+ assert.strictEqual(b.started, false);+ parentTask.finish();+ await settle();+ assert.strictEqual(b.started, true);+ b.finish();+ await Promise.all([a.done, parentTask.done, b.done]);+ });++ it('throws when a guard is disposed twice', async () => {+ const queue = new TaskRunner().createQueue();+ const guard = await queue.scheduleTask();+ guard[Symbol.dispose]();+ assert.throws(+ () => guard[Symbol.dispose](),+ /The guard was already disposed\./,+ );+ });++ it('releases the queue when the holder throws', async () => {+ const queue = new TaskRunner().createQueue();+ await assert.rejects(+ (async () => {+ using guard = await queue.scheduleTask();+ throw new Error('task failed');+ })(),+ /task failed/,+ );+ const next = start(queue);+ await settle();+ assert.strictEqual(next.started, true);+ next.finish();+ await next.done;+ });++ describe('pause', () => {+ it('stops new tasks and resolves after running tasks finish', async () => {+ const {runner, childA, childB} = createTree();+ const running = start(childA);+ await settle();+ let paused = false;+ const pause = runner.pause().then(guard => {+ paused = true;+ return guard;+ });+ const late = start(childB);+ await settle();+ assert.strictEqual(paused, false);+ assert.strictEqual(late.started, false);+ running.finish();+ await running.done;+ const guard = await pause;+ await settle();+ assert.strictEqual(late.started, false);+ guard[Symbol.dispose]();+ await settle();+ assert.strictEqual(late.started, true);+ late.finish();+ await late.done;+ });++ it('goes ahead of waiting tasks', async () => {+ const {runner, childA} = createTree();+ const running = start(childA);+ const waiting = start(childA);+ await settle();+ const pause = runner.pause();+ running.finish();+ const guard = await pause;+ await settle();+ assert.strictEqual(waiting.started, false);+ guard[Symbol.dispose]();+ await settle();+ assert.strictEqual(waiting.started, true);+ waiting.finish();+ await Promise.all([running.done, waiting.done]);+ });+ });++ describe('dispose', () => {+ it('rejects waiting tasks with the reason and keeps the running task', async () => {+ const queue = new TaskRunner().createQueue();+ const running = start(queue);+ const waiting = start(queue);+ await settle();+ queue.dispose(new Error('Page 1 is closed.'));+ await assert.rejects(waiting.done, /Page 1 is closed\./);+ assert.strictEqual(running.started, true);+ running.finish();+ await running.done;+ });++ it('rejects a later scheduleTask()', async () => {+ const queue = new TaskRunner().createQueue();+ queue.dispose(new Error('Page 1 is closed.'));+ await assert.rejects(queue.scheduleTask(), /Page 1 is closed\./);+ });++ it('lets a parent task run after a waiting child task is rejected', async () => {+ const {parent, childA} = createTree();+ const running = start(childA);+ const waiting = start(childA);+ await settle();+ childA.dispose(new Error('closed'));+ await assert.rejects(waiting.done, /closed/);+ running.finish();+ await running.done;+ const parentTask = start(parent);+ await settle();+ assert.strictEqual(parentTask.started, true);+ parentTask.finish();+ await parentTask.done;+ });+ });+});diff --git a/tests/utils/WaitForHelper.test.ts b/tests/utils/WaitForHelper.test.tsindex 9c3cddd3..1078a8e0 100644--- a/tests/utils/WaitForHelper.test.ts+++ b/tests/utils/WaitForHelper.test.ts@@ -66,7 +66,7 @@ describe('WaitForHelper', () => {// The action opens a dialog asynchronously and passes no handleDialog.// The dialog leaves the renderer paused; without the fix,// waitForStableDom's setup evaluation would hang until protocolTimeout- // (~180s) while the tool mutex is held, freezing the session.+ // (~180s) while the context lock is held, freezing the session.try {const result = await Promise.race([mcpPage.waitForEventsAfterAction(async () => {