Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

12.6 KB
Raw Blame
/**
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import crypto from 'crypto';
import fs from 'fs';
import path from 'path';

import { playwright } from '../../inprocess';
import { defaultCacheDirectory } from '../../server/registry/index';
import { testDebug } from './log';
import { outputDir } from '../backend/context';
import { IdleTimer, defaultIdleTimeout } from '../backend/idleTimer';
import { createExtensionBrowser } from './extensionContextFactory';
import { connectToBrowserAcrossVersions, descriptorEndpoint } from '../utils/connect';
import { serverRegistry } from '../../serverRegistry';
import { resolveExtensionOptions } from './config';
// eslint-disable-next-line no-restricted-imports
import { connectToBrowser } from '../../client/connect';

import type { CLIOptions, FullConfig } from './config';
import type { ClientInfo } from '../utils/mcp/server';
// eslint-disable-next-line no-restricted-imports
import type { Playwright } from '../../client/playwright';
import type * as playwrightTypes from '../../..';
import type { BrowserInfo } from '../../serverRegistry';

export type BrowserWithInfo = {
  browser: playwrightTypes.Browser,
  browserInfo: BrowserInfo,
  endpoint: string,
  ownership: 'attached' | 'own',
  idleTimer?: IdleTimer,
};

export type BindOptions = {
  title: string,
  workspaceDir?: string,
};

export async function createBrowserWithInfo(config: FullConfig, clientInfo: ClientInfo, cliOptions: CLIOptions, bindOptions: BindOptions): Promise<BrowserWithInfo> {
  const info = await createBrowser(config, clientInfo, cliOptions, bindOptions);
  info.idleTimer = createIdleTimer(config, info.ownership, () => info.browser.close().catch(() => {}));
  info.browser.once('disconnected', () => info.idleTimer?.dispose());
  return info;
}

export function createIdleTimer(config: FullConfig, ownership: BrowserWithInfo['ownership'], onIdle: () => void): IdleTimer | undefined {
  const idleTimeout = config.timeouts?.idle ?? (ownership === 'own' && config.browser.launchOptions.headless ? defaultIdleTimeout : undefined);
  return idleTimeout ? new IdleTimer(idleTimeout, onIdle) : undefined;
}

async function createBrowser(config: FullConfig, clientInfo: ClientInfo, cliOptions: CLIOptions, bindOptions: BindOptions): Promise<BrowserWithInfo> {
  if (config.browser.remoteEndpoint)
    return await createRemoteBrowser(config);

  let browser: playwrightTypes.Browser;
  let ownership: 'attached' | 'own' = 'own';
  if (config.browser.cdpEndpoint) {
    browser = await createCDPBrowser(config, clientInfo);
    ownership = 'attached';
  } else if (config.browser.isolated) {
    browser = await createIsolatedBrowser(config, clientInfo);
    ownership = 'own';
  } else if (config.extension) {
    const { channel, executablePath, profileDirName } = resolveExtensionOptions(cliOptions);
    browser = await createExtensionBrowser(channel, executablePath, config.browser.userDataDir, profileDirName, clientInfo.clientName);
    ownership = 'attached';
  } else {
    browser = await createPersistentBrowser(config, clientInfo);
    ownership = 'own';
  }

  try {
    const { endpoint } = await browser.bind(bindOptions.title, { workspaceDir: bindOptions.workspaceDir });
    return { browser, browserInfo: browserInfo(browser, config), endpoint, ownership };
  } catch (error) {
    await browser.close().catch(() => {});
    throw error;
  }
}

export async function connectToBrowserEndpoint(config: FullConfig, browser: playwrightTypes.Browser, endpoint: string): Promise<playwrightTypes.Browser> {
  const options = config.browser.remoteEndpoint ? remoteConnectOptions(config).options : {};
  return await browser.browserType().connect(endpoint, options);
}

export interface BrowserContextFactory {
  contexts(clientInfo: ClientInfo): Promise<playwrightTypes.BrowserContext[]>;
  createContext(clientInfo: ClientInfo): Promise<playwrightTypes.BrowserContext>;
}

function browserInfo(browser: playwrightTypes.Browser, config: FullConfig): BrowserInfo {
  return {
    // eslint-disable-next-line no-restricted-syntax
    guid: (browser as any)._guid,
    browserName: config.browser.browserName,
    launchOptions: config.browser.launchOptions,
    userDataDir: config.browser.userDataDir
  };
}

async function createIsolatedBrowser(config: FullConfig, clientInfo: ClientInfo): Promise<playwrightTypes.Browser> {
  testDebug('create browser (isolated)');
  const browserType = playwright[config.browser.browserName];
  const tracesDir = await computeTracesDir(config, clientInfo);
  const browser = await browserType.launch({
    tracesDir,
    ...config.browser.launchOptions,
    handleSIGINT: false,
    handleSIGTERM: false,
  }).catch(error => {
    throwIfExecutableMissing(error, config);
    throw error;
  });
  return browser;
}

async function createCDPBrowser(config: FullConfig, clientInfo: ClientInfo): Promise<playwrightTypes.Browser> {
  testDebug('create browser (cdp)');
  const artifactsDir = await computeTracesDir(config, clientInfo);
  const browser = await playwright.chromium.connectOverCDP(config.browser.cdpEndpoint!, {
    headers: config.browser.cdpHeaders,
    timeout: config.browser.cdpTimeout,
    noDefaults: true,
    artifactsDir,
  });
  return browser;
}

// `remoteEndpoint` may be a plain URL string or a ConnectOptions object that
// carries additional fields such as `exposeNetwork`, `headers`, `slowMo`, and
// `timeout`. Normalize once so every connect deals with a single shape.
function remoteConnectOptions(config: FullConfig): { endpoint: string, options: playwrightTypes.ConnectOptions } {
  const remote = config.browser.remoteEndpoint!;
  // `remoteHeaders` is for back-compat, `remoteEndpoint.headers` takes precedence.
  // eslint-disable-next-line no-restricted-syntax
  const remoteHeaders = (config.browser as any).remoteHeaders as Record<string, string> | undefined;
  if (typeof remote === 'string')
    return { endpoint: remote, options: { headers: remoteHeaders } };
  const { endpoint, ...options } = remote;
  return { endpoint, options: { ...options, headers: { ...remoteHeaders, ...remote.headers } } };
}

async function createRemoteBrowser(config: FullConfig): Promise<BrowserWithInfo> {
  testDebug('create browser (remote)');
  const { endpoint, options } = remoteConnectOptions(config);

  const descriptor = await serverRegistry.find(endpoint);
  if (descriptor) {
    const browser = await connectToBrowserAcrossVersions(descriptor);
    return {
      browser,
      browserInfo: {
        guid: descriptor.browser.guid,
        browserName: descriptor.browser.browserName,
        launchOptions: descriptor.browser.launchOptions,
        userDataDir: descriptor.browser.userDataDir
      },
      endpoint: descriptorEndpoint(descriptor),
      ownership: 'attached'
    };
  }

  const playwrightObject = playwright as Playwright;
  // Use connectToBrowser instead of playwright[browserName].connect because we don't have browserName.
  const browser = await connectToBrowser(playwrightObject, { endpoint, ...options });
  browser._connectToBrowserType(playwrightObject[browser._browserName], {}, undefined);
  // A browser started via `launchServer` exposes no contexts until one is
  // created, so create one when attaching to such a server.
  if (!browser.contexts().length)
    await browser.newContext(config.browser.contextOptions);
  return { browser, browserInfo: { ...browserInfo(browser, config), browserName: browser._browserName }, endpoint, ownership: 'attached' };
}

async function createPersistentBrowser(config: FullConfig, clientInfo: ClientInfo): Promise<playwrightTypes.Browser> {
  testDebug('create browser (persistent)');
  const userDataDir = config.browser.userDataDir ?? await createUserDataDir(config, clientInfo);
  const tracesDir = await computeTracesDir(config, clientInfo);

  if (await isProfileLocked5Times(userDataDir))
    throw new Error(`Browser is already in use for ${userDataDir}, use --isolated to run multiple instances of the same browser`);

  const browserType = playwright[config.browser.browserName];
  const configIgnoreDefaultArgs = config.browser.launchOptions?.ignoreDefaultArgs;
  const launchOptions: playwrightTypes.LaunchOptions & playwrightTypes.BrowserContextOptions = {
    tracesDir,
    ...config.browser.launchOptions,
    ...config.browser.contextOptions,
    handleSIGINT: false,
    handleSIGTERM: false,
    ignoreDefaultArgs: configIgnoreDefaultArgs === true
      ? true
      : [
        '--disable-extensions',
        ...Array.isArray(configIgnoreDefaultArgs) ? configIgnoreDefaultArgs : [],
      ],
  };
  try {
    const browserContext = await browserType.launchPersistentContext(userDataDir, launchOptions);
    const browser = browserContext.browser()!;
    return browser;
  } catch (error: any) {
    throwIfExecutableMissing(error, config);
    if (error.message.includes('cannot open shared object file: No such file or directory')) {
      const browserName = launchOptions.channel ?? config.browser.browserName;
      throw new Error(`Missing system dependencies required to run browser ${browserName}. Install them with: sudo npx playwright install-deps ${browserName}`);
    }
    if (error.message.includes('ProcessSingleton') || error.message.includes('exitCode=21'))
      throw new Error(`Browser is already in use for ${userDataDir}, use --isolated to run multiple instances of the same browser`);
    throw error;
  }
}

async function createUserDataDir(config: FullConfig, clientInfo: ClientInfo) {
  const dir = process.env.PWMCP_PROFILES_DIR_FOR_TEST ?? path.join(defaultCacheDirectory(), 'ms-playwright-mcp');
  const browserToken = config.browser.launchOptions?.channel ?? config.browser?.browserName;
  // Hesitant putting hundreds of files into the user's workspace, so using it for hashing instead.
  const rootPathToken = createHash(clientInfo.cwd);
  const result = path.join(dir, `mcp-${browserToken}-${rootPathToken}`);
  await fs.promises.mkdir(result, { recursive: true });
  return result;
}

function createHash(data: string): string {
  return crypto.createHash('sha256').update(data).digest('hex').slice(0, 7);
}

async function computeTracesDir(config: FullConfig, clientInfo: ClientInfo): Promise<string | undefined> {
  return path.resolve(outputDir({ config, cwd: clientInfo.cwd }), 'traces');
}

async function isProfileLocked5Times(userDataDir: string): Promise<boolean> {
  for (let i = 0; i < 5; i++) {
    if (!isProfileLocked(userDataDir))
      return false;
    await new Promise(f => setTimeout(f, 1000));
  }
  return true;
}

export function isProfileLocked(userDataDir: string): boolean {
  const lockFile = process.platform === 'win32' ? 'lockfile' : 'SingletonLock';
  const lockPath = path.join(userDataDir, lockFile);

  if (process.platform === 'win32') {
    try {
      const fd = fs.openSync(lockPath, 'r+');
      fs.closeSync(fd);
      return false;
    } catch (e: any) {
      return e.code !== 'ENOENT';
    }
  }

  try {
    const target = fs.readlinkSync(lockPath);
    const pid = parseInt(target.split('-').pop() || '', 10);
    if (isNaN(pid))
      return false;
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}

function throwIfExecutableMissing(error: Error, config: FullConfig): void {
  // The "Executable doesn't exist" prefix is shared by all managed binaries
  // (browser, ffmpeg, winldd). Disambiguate by the path so the user is told
  // which dependency to install, and surface the executable path itself so a
  // version mismatch (an installed build vs. the expected build) is
  // diagnosable rather than looking like a missing install.
  if (!error.message.includes(`Executable doesn't exist`))
    return;
  const target = error.message.includes('ffmpeg') ? 'ffmpeg' : (config.browser.launchOptions?.channel ?? config.browser.browserName);
  const label = target === 'ffmpeg' ? 'FFmpeg' : `Browser "${target}"`;
  const command = config.skillMode ? `playwright-cli install-browser ${target}` : `npx @playwright/mcp install-browser ${target}`;
  const match = error.message.match(/Executable doesn't exist at ([^\r\n]+)/);
  const location = match ? `; expected executable at ${match[1].trim()}` : '';
  throw new Error(`${label} is not installed${location}. Run \`${command}\` to install`);
}