-
Notifications
You must be signed in to change notification settings - Fork 708
Expand file tree
/
Copy pathPlaywrightBrowserTunnel.ts
More file actions
693 lines (615 loc) · 25.8 KB
/
Copy pathPlaywrightBrowserTunnel.ts
File metadata and controls
693 lines (615 loc) · 25.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import type { ChildProcess } from 'node:child_process';
import { once } from 'node:events';
import type { BrowserServer, BrowserType, LaunchOptions } from 'playwright-core';
import { type RawData, WebSocket, type WebSocketServer } from 'ws';
import { TerminalProviderSeverity, TerminalStreamWritable, type ITerminal } from '@rushstack/terminal';
import { Executable, FileSystem, Async } from '@rushstack/node-core-library';
import {
getNormalizedErrorString,
getWebSocketCloseReason,
getWebSocketReadyStateString,
WebSocketCloseCode
} from './utilities';
import { LaunchOptionsValidator, type ILaunchOptionsValidationResult } from './LaunchOptionsValidator';
/**
* Allowed Playwright browser names.
* @beta
*/
export type BrowserName = 'chromium' | 'firefox' | 'webkit';
const validBrowserNames: Set<string> = new Set(['chromium', 'firefox', 'webkit'] satisfies BrowserName[]);
function isValidBrowserName(browserName: string): browserName is BrowserName {
return validBrowserNames.has(browserName);
}
/**
* Status values reported by {@link PlaywrightTunnel}.
* @beta
*/
export type TunnelStatus =
| 'waiting-for-connection'
| 'browser-server-running'
| 'stopped'
| 'setting-up-browser-server'
| 'error';
/**
* Handshake data exchanged during the initial WebSocket connection.
* @beta
*/
export interface IHandshake {
action: 'handshake';
browserName: BrowserName;
launchOptions: LaunchOptions;
playwrightVersion: string;
}
type TunnelMode = 'poll-connection' | 'wait-for-incoming-connection';
/**
* Options for configuring a {@link PlaywrightTunnel} instance.
* @beta
*/
export type IPlaywrightTunnelOptions = {
terminal: ITerminal;
onStatusChange: (status: TunnelStatus) => void;
playwrightInstallPath: string;
/**
* Optional callback invoked before launching the browser server.
* Receives the handshake data including launch options.
* If the callback returns false, the browser server launch will be aborted.
* This allows the client to prompt the user for approval before starting.
*/
onBeforeLaunch?: (handshake: IHandshake) => Promise<boolean> | boolean;
} & (
| {
mode: 'poll-connection';
wsEndpoint: string;
}
| {
mode: 'wait-for-incoming-connection';
listenPort: number;
}
);
interface IBrowserServerProxy {
browserServer: BrowserServer;
client: WebSocket;
}
/**
* Hosts a Playwright browser server and forwards traffic over a WebSocket tunnel.
* @beta
*/
export class PlaywrightTunnel {
private readonly _terminal: ITerminal;
private readonly _onStatusChange: (status: TunnelStatus) => void;
private readonly _onBeforeLaunch?: (handshake: IHandshake) => Promise<boolean> | boolean;
private readonly _playwrightBrowsersInstalled: Set<string> = new Set();
private readonly _wsEndpoint: string | undefined;
private readonly _listenPort: number | undefined;
private readonly _playwrightInstallPath: string;
private _status: TunnelStatus = 'stopped';
private _initWsPromise?: Promise<WebSocket | undefined>;
private _keepRunning: boolean = false;
private _ws?: WebSocket;
private _mode: TunnelMode;
private _pendingConnectionAttempt?: Promise<WebSocket>;
private _cancelPendingConnection?: () => void;
private _pollInterval?: NodeJS.Timeout;
public constructor(options: IPlaywrightTunnelOptions) {
const { mode, terminal, onStatusChange, playwrightInstallPath, onBeforeLaunch } = options;
switch (mode) {
case 'poll-connection':
if (!options.wsEndpoint) {
throw new Error('wsEndpoint is required for poll-connection mode');
}
this._wsEndpoint = options.wsEndpoint;
this._listenPort = undefined;
break;
case 'wait-for-incoming-connection':
if (options.listenPort === undefined) {
throw new Error('listenPort is required for wait-for-incoming-connection mode');
}
this._wsEndpoint = undefined;
this._listenPort = options.listenPort;
break;
default:
throw new Error(`Invalid mode: ${mode}`);
}
this._mode = mode;
this._terminal = terminal;
this._onStatusChange = onStatusChange;
this._onBeforeLaunch = onBeforeLaunch;
this._playwrightInstallPath = playwrightInstallPath;
}
public get status(): TunnelStatus {
return this._status;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
private set status(newStatus: TunnelStatus) {
this._status = newStatus;
this._onStatusChange(newStatus);
}
public async waitForCloseAsync(): Promise<void> {
const terminal: ITerminal = this._terminal;
const initWsPromise: Promise<WebSocket | undefined> | undefined = this._initWsPromise;
if (initWsPromise) {
const ws: WebSocket | undefined = await initWsPromise;
if (!ws) {
terminal.writeDebugLine('WebSocket connection was cancelled before it was established.');
this._initWsPromise = undefined;
return;
}
await once(ws, 'close');
terminal.writeDebugLine('WebSocket connection closed. resolving init promise.');
this._initWsPromise = undefined;
}
}
public async startAsync(options: { keepRunning?: boolean } = {}): Promise<void> {
this._keepRunning = options.keepRunning ?? true;
const terminal: ITerminal = this._terminal;
terminal.writeLine(`keepRunning: ${this._keepRunning}`);
while (this._keepRunning) {
if (!this._initWsPromise) {
this._initWsPromise = this._initPlaywrightBrowserTunnelAsync();
} else {
terminal.writeLine(`Tunnel is already running with status: ${this.status}`);
}
await this.waitForCloseAsync();
}
}
public async stopAsync(): Promise<void> {
this._keepRunning = false;
if (this._pollInterval) {
clearInterval(this._pollInterval);
this._pollInterval = undefined;
}
if (!this._ws) {
this._cancelPendingConnection?.();
this._cancelPendingConnection = undefined;
this._pendingConnectionAttempt = undefined;
this._initWsPromise = undefined;
this.status = 'stopped';
return;
}
await this._initWsPromise?.finally(() => {
this._ws?.close(WebSocketCloseCode.NORMAL_CLOSURE, 'Tunnel stopped');
});
}
public async [Symbol.asyncDispose](): Promise<void> {
this._terminal.writeLine('Disposing WebSocket connection.');
await this.stopAsync();
}
public async cleanTempFilesAsync(): Promise<void> {
const tmpPath: string = this._playwrightInstallPath;
this._terminal.writeLine(`Cleaning up temporary files in ${tmpPath}`);
try {
await FileSystem.ensureEmptyFolderAsync(tmpPath);
this._terminal.writeLine(`Temporary files cleaned up.`);
} catch (error) {
this._terminal.writeLine(`Failed to clean up temporary files: ${getNormalizedErrorString(error)}`);
}
}
// TODO: We should implement an uninstall command to remove installed Playwright browsers
// public async uninstallPlaywrightBrowsersAsync(): Promise<void> {}
private async _runCommandAsync(command: string, args: string[]): Promise<void> {
const tmpPath: string = this._playwrightInstallPath;
await FileSystem.ensureFolderAsync(tmpPath);
this._terminal.writeLine(`Running command: ${command} ${args.join(' ')} in ${tmpPath}`);
const cp: ChildProcess = Executable.spawn(command, args, {
stdio: [
'ignore', // stdin
'pipe', // stdout
'pipe' // stderr
],
currentWorkingDirectory: tmpPath
});
cp.stdout?.pipe(
new TerminalStreamWritable({
terminal: this._terminal,
severity: TerminalProviderSeverity.log
})
);
cp.stderr?.pipe(
new TerminalStreamWritable({
terminal: this._terminal,
severity: TerminalProviderSeverity.error
})
);
await Executable.waitForExitAsync(cp, { throwOnNonZeroExitCode: true, throwOnSignal: true });
}
private async _installPlaywrightCoreAsync({
playwrightVersion
}: Pick<IHandshake, 'playwrightVersion'>): Promise<void> {
this._terminal.writeLine(`Installing playwright-core version ${playwrightVersion}`);
await this._runCommandAsync('npm', [
'install',
`playwright-core-${playwrightVersion}@npm:playwright-core@${playwrightVersion}`
]);
}
private async _installPlaywrightBrowsersAsync({
playwrightVersion,
browserName
}: Pick<IHandshake, 'playwrightVersion' | 'browserName'>): Promise<void> {
await this._installPlaywrightCoreAsync({ playwrightVersion });
this._terminal.writeLine(`Executing playwright-core version ${playwrightVersion}`);
await this._runCommandAsync('node', [
`node_modules/playwright-core-${playwrightVersion}/cli.js`,
'install',
browserName
]);
}
private async _tryConnectAsync(): Promise<WebSocket> {
const wsEndpoint: string | undefined = this._wsEndpoint;
if (!wsEndpoint) {
throw new Error('WebSocket endpoint is not defined');
}
return await new Promise<WebSocket>((resolve, reject) => {
const ws: WebSocket = new WebSocket(wsEndpoint);
ws.on('open', () => {
this._terminal.writeLine(`WebSocket connection opened`);
resolve(ws);
});
ws.once('error', (error) => {
reject(error);
});
});
}
// TODO: Only supporting one test at a time.
// Need to support multiple simultaneous connections for parallel tests.
private async _pollConnectionAsync(): Promise<WebSocket | undefined> {
this._terminal.writeLine(`Waiting for WebSocket connection`);
return await new Promise<WebSocket | undefined>((resolve) => {
let settled: boolean = false;
const cleanup = (): void => {
if (this._pollInterval) {
clearInterval(this._pollInterval);
this._pollInterval = undefined;
}
this._pendingConnectionAttempt = undefined;
this._cancelPendingConnection = undefined;
};
this._cancelPendingConnection = (): void => {
if (settled) {
return;
}
settled = true;
cleanup();
resolve(undefined);
};
this._pollInterval = setInterval(() => {
if (this._pendingConnectionAttempt) {
return; // Skip if a connection attempt is already in progress
}
const connectionPromise: Promise<WebSocket> = this._tryConnectAsync();
this._pendingConnectionAttempt = connectionPromise;
connectionPromise
.then((ws: WebSocket) => {
if (settled || !this._keepRunning) {
ws.close(WebSocketCloseCode.NORMAL_CLOSURE, 'Tunnel stopped');
return;
}
settled = true;
cleanup();
this._ws = ws;
ws.removeAllListeners();
resolve(ws);
})
.catch(() => {
// no-op - will retry on next interval
this._pendingConnectionAttempt = undefined;
});
}, 500);
});
}
private async _waitForIncomingConnectionAsync(): Promise<WebSocket> {
this._terminal.writeLine('Waiting for incoming WebSocket connection');
return await new Promise<WebSocket>((resolve, reject) => {
const server: WebSocketServer = new WebSocket.Server({ port: this._listenPort });
const cleanup = (): void => {
server.removeAllListeners();
};
server.once('connection', (ws) => {
this._terminal.writeLine('Incoming WebSocket connection established');
// Stop listening immediately so the port is released
cleanup();
server.close((closeError?: Error) => {
if (closeError) {
this._terminal.writeLine(
`Failed to close WebSocket server: ${
closeError instanceof Error ? closeError.message : closeError
}`
);
}
resolve(ws);
});
});
server.once('error', (error) => {
this._terminal.writeLine(`WebSocket server error: ${getNormalizedErrorString(error)}`);
cleanup();
// Try to close (best-effort), then reject
server.close(() => reject(error));
});
});
}
// TODO: If a user runs this for the first time, `this._playwrightBrowsersInstalled` will be empty
// and it will try to install the browsers every time. We should persist this information. Maybe a cache file with text per
// machine instance?
private async _setupPlaywrightAsync({
playwrightVersion,
browserName
}: Pick<IHandshake, 'playwrightVersion' | 'browserName'>): Promise<typeof import('playwright-core')> {
const browserKey: string = `${playwrightVersion}-${browserName}`;
this._terminal.writeLine(`Checking for installed playwright browsers. Installed browsers: ${browserKey}`);
if (!this._playwrightBrowsersInstalled.has(browserKey)) {
this._terminal.writeLine(
`Playwright browser not found. Installing playwright-core version ${playwrightVersion}`
);
await this._installPlaywrightBrowsersAsync({ playwrightVersion, browserName });
this._playwrightBrowsersInstalled.add(browserKey);
}
this._terminal.writeLine(`Using playwright-core version ${playwrightVersion} for browser server`);
return await import(`${this._playwrightInstallPath}/node_modules/playwright-core-${playwrightVersion}`);
}
private async _getPlaywrightBrowserServerProxyAsync({
browserName,
playwrightVersion,
launchOptions
}: Pick<IHandshake, 'playwrightVersion' | 'browserName' | 'launchOptions'>): Promise<IBrowserServerProxy> {
const terminal: ITerminal = this._terminal;
// Validate launch options against security allowlist
terminal.writeLine('Validating launch options against security allowlist...');
const validationResult: ILaunchOptionsValidationResult =
await LaunchOptionsValidator.validateLaunchOptionsAsync(launchOptions, terminal);
if (!validationResult.isValid) {
terminal.writeWarningLine(
`Some launch options were denied: ${validationResult.deniedOptions.join(', ')}`
);
terminal.writeWarningLine(`Using filtered launch options. Denied options have been removed.`);
}
// Use filtered options and ensure headless: false for headed tests in codespaces
// This is critical for the extension's purpose - enabling headed Playwright tests remotely
const safeOptions: LaunchOptions = {
...validationResult.filteredOptions,
headless: false
};
// Log the validated options, excluding 'headless' since it's always false for this extension
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { headless, ...logOptions } = safeOptions;
terminal.writeLine(
`Launch options after validation: ${JSON.stringify(logOptions)} (headless: false enforced)`
);
const playwright: typeof import('playwright-core') = await this._setupPlaywrightAsync({
playwrightVersion,
browserName
});
const { chromium, firefox, webkit } = playwright;
const browsers: Record<BrowserName, BrowserType> = { chromium, firefox, webkit };
const browserServer: BrowserServer = await browsers[browserName].launchServer(safeOptions);
if (!browserServer) {
throw new Error(
`Failed to launch browser server for ${browserName} with options: ${JSON.stringify(safeOptions)}`
);
}
terminal.writeLine(`Launched ${browserName} browser server`);
const client: WebSocket = new WebSocket(browserServer.wsEndpoint());
return {
browserServer,
client
};
}
private _validateHandshake(rawHandshake: unknown): IHandshake {
if (
typeof rawHandshake !== 'object' ||
rawHandshake === null ||
'action' in rawHandshake === false ||
'browserName' in rawHandshake === false ||
'playwrightVersion' in rawHandshake === false ||
'launchOptions' in rawHandshake === false ||
typeof rawHandshake.action !== 'string' ||
typeof rawHandshake.browserName !== 'string' ||
typeof rawHandshake.playwrightVersion !== 'string' ||
typeof rawHandshake.launchOptions !== 'object'
) {
throw new Error(`Invalid handshake: ${JSON.stringify(rawHandshake)}. Must be an object.`);
}
const { action, browserName, playwrightVersion, launchOptions } = rawHandshake;
if (action !== 'handshake') {
throw new Error(`Invalid action: ${action}. Expected 'handshake'.`);
}
if (!isValidBrowserName(browserName)) {
throw new Error(
`Invalid browser name: ${browserName}. Must be one of ${Array.from(validBrowserNames).join(', ')}.`
);
}
return {
action,
launchOptions: launchOptions as LaunchOptions,
playwrightVersion,
browserName
};
}
// ws1 is the tunnel websocket, ws2 is the browser server websocket
private async _setupForwardingAsync(ws1: WebSocket, ws2: WebSocket): Promise<void> {
this._terminal.writeLine('Setting up message forwarding between ws1 and ws2');
this._terminal.writeLine(` ws1 (tunnel) readyState: ${getWebSocketReadyStateString(ws1.readyState)}`);
this._terminal.writeLine(` ws2 (browser) readyState: ${getWebSocketReadyStateString(ws2.readyState)}`);
const messageCount: { ws1ToWs2: number; ws2ToWs1: number } = { ws1ToWs2: 0, ws2ToWs1: 0 };
ws1.on('message', (data) => {
messageCount.ws1ToWs2++;
if (ws2.readyState === WebSocket.OPEN) {
ws2.send(data);
} else {
this._terminal.writeLine(
`ws2 not open (state: ${getWebSocketReadyStateString(ws2.readyState)}). Dropping message #${messageCount.ws1ToWs2}`
);
}
});
ws2.on('message', (data) => {
messageCount.ws2ToWs1++;
if (ws1.readyState === WebSocket.OPEN) {
ws1.send(data);
} else {
this._terminal.writeLine(
`ws1 not open (state: ${getWebSocketReadyStateString(ws1.readyState)}). Dropping message #${messageCount.ws2ToWs1}`
);
}
});
ws1.once('close', (code: number, reason: Buffer) => {
const reasonStr: string = reason.toString() || 'no reason provided';
const codeDescription: string = getWebSocketCloseReason(code);
this._terminal.writeLine(
`ws1 (tunnel) closed - code: ${code} (${codeDescription}), reason: ${reasonStr}`
);
this._terminal.writeLine(
` Messages forwarded: ws1->ws2: ${messageCount.ws1ToWs2}, ws2->ws1: ${messageCount.ws2ToWs1}`
);
if (ws2.readyState === WebSocket.OPEN) {
this._terminal.writeLine(' Closing ws2 (browser) in response');
ws2.close(WebSocketCloseCode.NORMAL_CLOSURE, 'Tunnel closed');
}
});
ws2.once('close', (code: number, reason: Buffer) => {
const reasonStr: string = reason.toString() || 'no reason provided';
const codeDescription: string = getWebSocketCloseReason(code);
this._terminal.writeLine(
`ws2 (browser) closed - code: ${code} (${codeDescription}), reason: ${reasonStr}`
);
this._terminal.writeLine(
` Messages forwarded: ws1->ws2: ${messageCount.ws1ToWs2}, ws2->ws1: ${messageCount.ws2ToWs1}`
);
if (ws1.readyState === WebSocket.OPEN) {
this._terminal.writeLine(' Closing ws1 (tunnel) in response');
ws1.close(WebSocketCloseCode.NORMAL_CLOSURE, 'Browser closed');
}
});
ws1.once('error', (error) => {
this._terminal.writeErrorLine(`ws1 (tunnel) WebSocket error: ${getNormalizedErrorString(error)}`);
this._terminal.writeErrorLine(` ws1 readyState: ${getWebSocketReadyStateString(ws1.readyState)}`);
});
ws2.once('error', (error) => {
this._terminal.writeErrorLine(`ws2 (browser) WebSocket error: ${getNormalizedErrorString(error)}`);
this._terminal.writeErrorLine(` ws2 readyState: ${getWebSocketReadyStateString(ws2.readyState)}`);
});
}
/**
* Initializes the Playwright browser tunnel by establishing a WebSocket connection
* and setting up the browser server.
* Returns when the handshake is complete and the browser server is running.
*/
private async _initPlaywrightBrowserTunnelAsync(): Promise<WebSocket | undefined> {
let handshake: IHandshake | undefined = undefined;
let client: WebSocket | undefined = undefined;
let browserServer: BrowserServer | undefined = undefined;
this.status = 'waiting-for-connection';
const ws: WebSocket | undefined =
this._mode === 'poll-connection'
? await this._pollConnectionAsync()
: await this._waitForIncomingConnectionAsync();
if (!ws) {
this._terminal.writeLine('Playwright tunnel start cancelled before a WebSocket connected.');
this._initWsPromise = undefined;
this.status = 'stopped';
return undefined;
}
ws.on('open', () => {
this._terminal.writeLine(`WebSocket connection established`);
handshake = undefined;
});
ws.on('error', (error) => {
this._terminal.writeLine(`WebSocket error occurred: ${getNormalizedErrorString(error)}`);
});
ws.on('close', async (code: number, reason: Buffer) => {
const reasonStr: string = reason.toString() || 'no reason provided';
const codeDescription: string = getWebSocketCloseReason(code);
this._initWsPromise = undefined;
this._ws = undefined;
this.status = 'stopped';
this._terminal.writeLine(
`WebSocket connection closed - code: ${code} (${codeDescription}), reason: ${reasonStr}`
);
this._terminal.writeLine(` handshake received: ${handshake !== undefined}`);
this._terminal.writeLine(` browserServer active: ${browserServer !== undefined}`);
if (browserServer) {
this._terminal.writeLine(' Closing browser server...');
await browserServer.close();
this._terminal.writeLine(' Browser server closed');
}
});
return await new Promise<WebSocket>((resolve, reject) => {
const onMessageHandler = async (data: RawData): Promise<void> => {
const terminal: ITerminal = this._terminal;
if (!handshake) {
try {
const rawHandshakeString: string = data.toString();
const rawHandshake: unknown = JSON.parse(rawHandshakeString);
terminal.writeLine(`Received handshake: ${rawHandshakeString}`);
handshake = this._validateHandshake(rawHandshake);
// Call the onBeforeLaunch callback if provided
if (this._onBeforeLaunch) {
terminal.writeLine('Requesting user approval before launching browser server...');
const shouldProceed: boolean = await this._onBeforeLaunch(handshake);
if (!shouldProceed) {
terminal.writeLine('Browser server launch cancelled by user.');
ws.off('message', onMessageHandler);
ws.close(WebSocketCloseCode.NORMAL_CLOSURE, 'Launch cancelled by user');
reject(new Error('Browser server launch cancelled by user'));
return;
}
terminal.writeLine('User approved browser server launch.');
}
this.status = 'setting-up-browser-server';
const browserServerProxy: IBrowserServerProxy =
await this._getPlaywrightBrowserServerProxyAsync(handshake);
client = browserServerProxy.client;
browserServer = browserServerProxy.browserServer;
// Monitor browser server process for crashes
const browserProcess: ChildProcess | null = browserServer.process();
if (browserProcess) {
browserProcess.on('exit', (code: number | null, signal: string | null) => {
terminal.writeErrorLine(`Browser server process exited - code: ${code}, signal: ${signal}`);
});
browserProcess.on('error', (err: Error) => {
terminal.writeErrorLine(`Browser server process error: ${getNormalizedErrorString(err)}`);
});
terminal.writeDebugLine(`Browser server process started with PID: ${browserProcess.pid}`);
} else {
terminal.writeDebugLine('Warning: Browser server process handle not available for monitoring');
}
this.status = 'browser-server-running';
this._ws = ws;
// Send ack so that the counterpart also knows to start forwarding messages.
// NOTE: The 1-second delay is an intentional workaround. In the current
// protocol, the remote tunnel endpoint does not expose an explicit "ready"
// signal for when it has finished initializing its own forwarding logic
// after receiving the initial handshake. This
// delay avoids races where early messages could be dropped or mishandled
// if they arrive before the remote side is fully ready.
//
// TODO: A future improvement would be to replace this delay with a deterministic
// synchronization mechanism (e.g. an explicit "ready" message or event)
// instead of relying on a fixed timeout.
await Async.sleepAsync(2000);
ws.send(JSON.stringify({ action: 'handshakeAck' }));
await this._setupForwardingAsync(ws, client);
// Clean up message handler after successful handshake
ws.off('message', onMessageHandler);
resolve(ws);
} catch (error) {
terminal.writeLine(`Error processing handshake: ${error}`);
this.status = 'error';
// Cleanup and close connection on error
ws.off('message', onMessageHandler);
ws.close(WebSocketCloseCode.INTERNAL_ERROR, 'Handshake error');
reject(error);
return;
}
} else {
if (!client) {
terminal.writeLine('Browser WebSocket client is not initialized.');
ws.off('message', onMessageHandler);
ws.close(WebSocketCloseCode.INTERNAL_ERROR, 'Browser client not initialized');
return;
}
}
};
ws.on('message', onMessageHandler);
});
}
}