Skip to content

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

chore: use run-server for webkit-wsl tests (#38057)

Yury Semikhatsky9cb51c8730d8
diff --git a/packages/playwright-core/bin/install_webkit_wsl.ps1 b/packages/playwright-core/bin/install_webkit_wsl.ps1
index cc16ca9fdd..ed15e7608d 100644
--- a/packages/playwright-core/bin/install_webkit_wsl.ps1
+++ b/packages/playwright-core/bin/install_webkit_wsl.ps1
@@ -1,7 +1,5 @@
$ErrorActionPreference = 'Stop'
-# WebKit WSL Installation Script
-# See webkit-wsl-transport-server.ts for the complete architecture diagram.
# This script sets up a WSL distribution that will be used to run WebKit.
$Distribution = "playwright"
@@ -25,9 +23,9 @@ if [ ! -f "/home/$Username/node/bin/node" ]; then
mkdir -p /home/$Username/node
curl -fsSL https://nodejs.org/dist/v22.17.0/node-v22.17.0-linux-x64.tar.xz -o /home/$Username/node/node-v22.17.0-linux-x64.tar.xz
tar -xJf /home/$Username/node/node-v22.17.0-linux-x64.tar.xz -C /home/$Username/node --strip-components=1
+ echo 'export PATH=/home/$Username/node/bin:$PATH' >> /home/$Username/.bashrc
fi
/home/$Username/node/bin/node cli.js install-deps webkit
-cp lib/server/webkit/wsl/webkit-wsl-transport-client.js /home/$Username/
sudo -u $Username PLAYWRIGHT_SKIP_BROWSER_GC=1 /home/$Username/node/bin/node cli.js install webkit
"@ -replace "\r\n", "`n"
diff --git a/packages/playwright-core/src/server/registry/index.ts b/packages/playwright-core/src/server/registry/index.ts
index a58844ce1d..a4bf18f22f 100644
--- a/packages/playwright-core/src/server/registry/index.ts
+++ b/packages/playwright-core/src/server/registry/index.ts
@@ -845,9 +845,8 @@ export class Registry {
name: 'webkit-wsl',
browserName: 'webkit',
directory: webkit.dir,
- executablePath: () => process.execPath,
- executablePathOrDie: () => process.execPath,
- wslExecutablePath: `/home/pwuser/.cache/ms-playwright/webkit-${webkit.revision}/pw_run.sh`,
+ executablePath: () => webkitExecutable,
+ executablePathOrDie: (sdkLanguage: string) => executablePathOrDie('webkit', webkitExecutable, webkit.installByDefault, sdkLanguage),
installType: 'download-on-demand',
_validateHostRequirements: (sdkLanguage: string) => Promise.resolve(),
_isHermeticInstallation: true,
diff --git a/packages/playwright-core/src/server/webkit/webkit.ts b/packages/playwright-core/src/server/webkit/webkit.ts
index 8113b572d3..02e59bfdaf 100644
--- a/packages/playwright-core/src/server/webkit/webkit.ts
+++ b/packages/playwright-core/src/server/webkit/webkit.ts
@@ -22,7 +22,6 @@ import { wrapInASCIIBox } from '../utils/ascii';
import { BrowserType, kNoXServerRunningError } from '../browserType';
import { WKBrowser } from '../webkit/wkBrowser';
import { spawnAsync } from '../utils/spawnAsync';
-import { registry } from '../registry';
import type { BrowserOptions } from '../browser';
import type { SdkObject } from '../instrumentation';
@@ -43,7 +42,6 @@ export class WebKit extends BrowserType {
return {
...env,
CURL_COOKIE_JAR_PATH: process.platform === 'win32' && isPersistent ? path.join(userDataDir, 'cookiejar.db') : undefined,
- WEBKIT_EXECUTABLE: options.channel === 'webkit-wsl' ? registry.findExecutable('webkit-wsl')!.wslExecutablePath! : undefined
};
}
@@ -69,14 +67,6 @@ export class WebKit extends BrowserType {
throw new Error('Arguments can not specify page to be opened');
const webkitArguments = ['--inspector-pipe'];
- if (options.channel === 'webkit-wsl') {
- if (options.executablePath)
- throw new Error('Cannot specify executablePath when using the "webkit-wsl" channel.');
- webkitArguments.unshift(
- path.join(__dirname, 'wsl/webkit-wsl-transport-server.js'),
- );
- }
-
if (process.platform === 'win32' && options.channel !== 'webkit-wsl')
webkitArguments.push('--disable-accelerated-compositing');
if (headless)
diff --git a/packages/playwright-core/src/server/webkit/wsl/webkit-wsl-transport-client.ts b/packages/playwright-core/src/server/webkit/wsl/webkit-wsl-transport-client.ts
deleted file mode 100644
index 46654a8660..0000000000
--- a/packages/playwright-core/src/server/webkit/wsl/webkit-wsl-transport-client.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-/**
- * 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.
- */
-// @ts-check
-/* eslint-disable no-restricted-properties */
-/* eslint-disable no-console */
-
-// WebKit WSL Transport Client - runs inside WSL/Linux
-// See webkit-wsl-transport-server.ts for the complete architecture diagram.
-// This client connects to the TCP server and bridges it to WebKit via fd3/fd4 pipes.
-
-import net from 'net';
-import fs from 'fs';
-import { spawn, spawnSync } from 'child_process';
-
-(async () => {
- const { PW_WSL_BRIDGE_PORT: socketPort, ...childEnv } = process.env;
- if (!socketPort)
- throw new Error('PW_WSL_BRIDGE_PORT env var is not set');
-
- const [executable, ...args] = process.argv.slice(2);
-
- if (!(await fs.promises.stat(executable)).isFile())
- throw new Error(`Executable does not exist. Did you update Playwright recently? Make sure to run npx playwright install webkit-wsl`);
-
- const address = (() => {
- const res = spawnSync('/usr/bin/wslinfo', ['--networking-mode'], { encoding: 'utf8' });
- if (res.error || res.status !== 0)
- throw new Error(`Failed to run /usr/bin/wslinfo --networking-mode: ${res.error?.message || res.stderr || res.status}`);
- if (res.stdout.trim() === 'nat') {
- const ipRes = spawnSync('/usr/sbin/ip', ['route', 'show'], { encoding: 'utf8' });
- if (ipRes.error || ipRes.status !== 0)
- throw new Error(`Failed to run ip route show: ${ipRes.error?.message || ipRes.stderr || ipRes.status}`);
- const ip = ipRes.stdout.trim().split('\n').find(line => line.includes('default'))?.split(' ')[2];
- if (!ip)
- throw new Error('Could not determine WSL IP address (NAT mode).');
- return ip;
- }
- return '127.0.0.1';
- })();
-
- const socket = net.createConnection(parseInt(socketPort, 10), address);
- // Disable Nagle's algorithm to reduce latency for small, frequent messages.
- socket.setNoDelay(true);
-
- await new Promise((resolve, reject) => {
- socket.on('connect', resolve);
- socket.on('error', reject);
- });
-
- const child = spawn(executable, args, {
- stdio: ['inherit', 'inherit', 'inherit', 'pipe', 'pipe'],
- env: childEnv,
- });
-
- const [childOutput, childInput] = [child.stdio[3] as NodeJS.WritableStream, child.stdio[4] as NodeJS.ReadableStream];
- socket.pipe(childOutput);
- childInput.pipe(socket);
-
- socket.on('end', () => child.kill());
-
- child.on('exit', exitCode => {
- socket.end();
- process.exit(exitCode || 0);
- });
-
- await new Promise((resolve, reject) => {
- child.on('exit', resolve);
- child.on('error', reject);
- });
-})().catch(error => {
- console.error('Error occurred:', error);
- process.exit(1);
-});
diff --git a/packages/playwright-core/src/server/webkit/wsl/webkit-wsl-transport-server.ts b/packages/playwright-core/src/server/webkit/wsl/webkit-wsl-transport-server.ts
deleted file mode 100644
index c6288f3037..0000000000
--- a/packages/playwright-core/src/server/webkit/wsl/webkit-wsl-transport-server.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-/**
- * 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.
- */
-/* eslint-disable no-restricted-properties */
-/* eslint-disable no-console */
-import net from 'net';
-import path from 'path';
-import { spawn } from 'child_process';
-
-// WebKit WSL Transport Architecture Diagram:
-//
-// ┌─────────────────┐ fd3/fd4 ┌──────────────────────┐
-// │ Playwright │◄──────────────►│ webkit-wsl-transport │
-// │ │ (pipes) │ server.ts │
-// └─────────────────┘ │ (Windows/Host) │
-// └──────────┬───────────┘
-// │ spawns
-// ▼
-// ┌──────────────────────┐
-// │ wsl.exe │
-// │ -d playwright │
-// └──────────┬───────────┘
-// │ starts
-// ▼
-// ┌─────────────────┐ TCP socket ┌──────────────────────┐ fd3/fd4 ┌─────────────┐
-// │ TCP Server │◄───────────────►│ webkit-wsl-transport │◄──────────────►│ WebKit │
-// │ (port forwarded │ over WSL │ client.ts │ (pipes) │ Browser │
-// │ via env var) │ boundary │ (WSL/Linux) │ │ Process │
-// └─────────────────┘ └──────────────────────┘ └─────────────┘
-//
-// The TCP server bridges fd3/fd4 pipes across the WSL boundary because wsl.exe
-// only supports forwarding up to 3 file descriptors (stdin/stdout/stderr).
-//
-// Data flow: Playwright ↔ fd3/fd4 ↔ TCP socket ↔ WSL network ↔ TCP socket ↔ fd3/fd4 ↔ WebKit
-//
-// Start a TCP server to bridge between parent (fd3/fd4) and the WSL child process.
-// This is needed because wsl.exe only supports up to 3 forwarded fds, so we can't
-// pass extra pipes directly and must tunnel them over a socket instead.
-
-(async () => {
- const argv = process.argv.slice(2);
- if (!argv.length) {
- console.error(`Usage: node ${path.basename(__filename)} <executable> [args...]`);
- process.exit(1);
- }
-
- // Use net.Socket instead of fs.createReadStream/WriteStream to avoid hanging at shutdown.
- // fs streams use libuv's async fs API which spawns FSReqCallbacks in the threadpool.
- // If fs operations are pending (e.g. waiting for EOF), Node's event loop stays referenced
- // and the process never exits. net.Socket integrates with libuv's event loop directly,
- // making reads/writes non-blocking and allowing clean shutdown via destroy().
- const parentIn = new net.Socket({ fd: 3, readable: true, writable: false }); // parent -> us
- const parentOut = new net.Socket({ fd: 4, readable: false, writable: true }); // us -> parent
-
- const server = net.createServer();
-
- let socket: net.Socket | null = null;
- server.on('connection', s => {
- if (socket) {
- log('Extra connection received, destroying.');
- socket.destroy();
- return;
- }
- socket = s;
- // Disable Nagle's algorithm to reduce latency for small, frequent messages.
- socket.setNoDelay(true);
- log('Client connected, wiring pipes.');
-
- socket.pipe(parentOut);
- parentIn.pipe(socket);
-
- socket.on('close', () => {
- log('Socket closed');
- socket = null;
- });
- });
-
- await new Promise((resolve, reject) => {
- server.once('error', reject);
- server.listen(0, () => resolve(null));
- });
- const address = server.address();
- if (!address || typeof address === 'string') {
- console.error('Failed to obtain listening address');
- process.exit(1);
- }
- const port = address.port;
- log('Server listening on', port);
-
- // Spawn child process with augmented env. PW_WSL_BRIDGE_PORT is added to WSLENV
- // so this environment variable is propagated across Windows <-> WSL boundaries.
- // This does not forward the TCP port itself, only the env var containing it.
- const env = {
- ...process.env,
- // WSLENV is a colon-delimited list of environment variables that should be included when launching WSL processes from Win32 or Win32 processes from WSL
- WSLENV: 'PW_WSL_BRIDGE_PORT',
- PW_WSL_BRIDGE_PORT: String(port),
- };
-
- let shuttingDown = false;
-
- const child = spawn('wsl.exe', [
- '-d',
- 'playwright',
- '--cd',
- '/home/pwuser',
- '/home/pwuser/node/bin/node',
- '/home/pwuser/webkit-wsl-transport-client.js',
- process.env.WEBKIT_EXECUTABLE || '',
- ...argv,
- ], {
- env,
- stdio: ['inherit', 'inherit', 'inherit'], // no fd3/fd4 here; they stay only in this wrapper
- });
-
- log('Spawned child pid', child.pid);
-
- child.on('close', (code, signal) => {
- log('Child exit', { code, signal });
- // Use actual exit code, or 128, or fallback to 1 for unknown signals
- const exitCode = code ?? (signal ? 128 : 0);
- shutdown(exitCode);
- });
- child.on('error', err => {
- console.error('Child process failed to start:', err);
- shutdown(1);
- });
-
- await new Promise(resolve => child.once('close', resolve));
-
- async function shutdown(code = 0) {
- if (shuttingDown)
- return;
- shuttingDown = true;
-
- server.close();
-
- parentIn.destroy();
- parentOut.destroy();
- socket?.destroy();
-
- await new Promise(resolve => server.once('close', resolve));
-
- process.exit(code);
- }
-
- function log(...args: any[]) {
- console.error(new Date(), `[${path.basename(__filename)}]`, ...args);
- }
-})().catch(error => {
- console.error('Error occurred:', error);
- process.exit(1);
-});
diff --git a/tests/config/testMode.ts b/tests/config/testMode.ts
index 02623b6dce..cd35822bf5 100644
--- a/tests/config/testMode.ts
+++ b/tests/config/testMode.ts
@@ -17,7 +17,7 @@
import { start } from '../../packages/playwright-core/lib/outofprocess';
import type { Playwright } from '../../packages/playwright-core/lib/client/playwright';
-export type TestModeName = 'default' | 'driver' | 'service' | 'service2';
+export type TestModeName = 'default' | 'driver' | 'service' | 'service2' | 'wsl';
interface TestMode {
setup(): Promise<Playwright>;
diff --git a/tests/config/testModeFixtures.ts b/tests/config/testModeFixtures.ts
index b247b56299..e2af8fd019 100644
--- a/tests/config/testModeFixtures.ts
+++ b/tests/config/testModeFixtures.ts
@@ -39,6 +39,7 @@ export const testModeTest = test.extend<TestModeTestFixtures, TestModeWorkerOpti
'service': new DefaultTestMode(),
'service2': new DefaultTestMode(),
'service-grid': new DefaultTestMode(),
+ 'wsl': new DefaultTestMode(),
'driver': new DriverTestMode(),
}[mode];
const playwright = await testMode.setup();
diff --git a/tests/library/playwright.config.ts b/tests/library/playwright.config.ts
index 76c82d0998..e3fc2dc757 100644
--- a/tests/library/playwright.config.ts
+++ b/tests/library/playwright.config.ts
@@ -78,6 +78,14 @@ if (mode === 'service2') {
}
};
}
+if (channel === 'webkit-wsl') {
+ connectOptions = { wsEndpoint: 'ws://localhost:3777/' };
+ webServer = {
+ command: 'wsl -d playwright -- npx playwright run-server --port=3777',
+ url: 'http://localhost:3777',
+ reuseExistingServer: !process.env.CI,
+ };
+}
const config: Config<PlaywrightWorkerOptions & PlaywrightTestOptions & TestModeWorkerOptions> = {
testDir,