Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/

import {execSync} from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
Expand Down Expand Up @@ -148,6 +149,24 @@ interface McpLaunchOptions {
enableExtensions?: boolean;
}

export function detectDisplay(): void {
// Only detect display on Linux/UNIX.
if (os.platform() === 'win32' || os.platform() === 'darwin') {
return;
}
if (!process.env['DISPLAY']) {
try {
const result = execSync(
`ps -u $(id -u) -o pid= | xargs -I{} cat /proc/{}/environ 2>/dev/null | tr '\\0' '\\n' | grep -m1 '^DISPLAY=' | cut -d= -f2`,
);
const display = result.toString('utf8').trim();
process.env['DISPLAY'] = display;
} catch {
// no-op
}
}
}

export async function launch(options: McpLaunchOptions): Promise<Browser> {
const {channel, executablePath, headless, isolated} = options;
const profileDirName =
Expand Down Expand Up @@ -189,6 +208,10 @@ export async function launch(options: McpLaunchOptions): Promise<Browser> {
: 'chrome';
}

if (!headless) {
detectDisplay();
}

try {
const browser = await puppeteer.launch({
channel: puppeteerChannel,
Expand Down
6 changes: 5 additions & 1 deletion tests/browser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@ import {describe, it} from 'node:test';

import {executablePath} from 'puppeteer';

import {ensureBrowserConnected, launch} from '../src/browser.js';
import {detectDisplay, ensureBrowserConnected, launch} from '../src/browser.js';

describe('browser', () => {
it('detects display does not crash', () => {
detectDisplay();
});

it('cannot launch multiple times with the same profile', async () => {
const tmpDir = os.tmpdir();
const folderPath = path.join(tmpDir, `temp-folder-${crypto.randomUUID()}`);
Expand Down