// THE DISPLAY A HEADED WINDOW OPENS ON — Connect X account, Connect archive // session and Connect forum session (the only headed launches; every other // browser in common is headless, and record-live's is under `xvfb-run`). // // The editor runs as a systemd USER unit, which the user manager starts at // boot (lingering) — often before anyone has logged in to the desktop. Such a // process has no DISPLAY / WAYLAND_DISPLAY / XAUTHORITY in its environment and // never gets them, while the user manager learns them when the desktop session // starts. Measured 17 Nov 2026: the editor up since boot, the desktop up hours // later, every Connect failing with Playwright's "launched a headed browser // without having a XServer running" until the editor was restarted. // // So the display is resolved AT EACH LAUNCH (a desktop can start, or restart // on another number, at any time), first hit wins: // 1. this process's own DISPLAY / WAYLAND_DISPLAY (and XAUTHORITY) — a // process started inside the desktop, or a container given a display; // 2. the user manager's (`systemctl --user show-environment`, an argument // vector with a short timeout, never a shell string; only those three // keys are read); // 3. the sockets on disk: /tmp/.X11-unix/X → DISPLAY=:, and // $XDG_RUNTIME_DIR/wayland- → WAYLAND_DISPLAY=wayland-. // The answer is handed to the launch as `env` (merged over the process's), and // is NEVER written into process.env. No display: the Connect is refused // before anything launches (and before its profile directory is made), with a // sentence a person can act on; a display found but a launch that still fails // on the missing-X-server banner is turned into a second sentence naming the // display (the raw text goes to the log only). A socket counts only when it is // this user's. // // A browser that opens no window (the e2e suite's fake, fakeXProfileBrowser.ts) // says so (`opensNoWindow`) and needs no display. // // Every input is injectable — the environment, the command runner, the file // system — so the resolver is tested without a desktop, a user manager or a // browser (headedDisplay.test.ts). import { execFile } from "node:child_process"; import { readdirSync, statSync } from "node:fs"; import { mkdir } from "node:fs/promises"; import path from "node:path"; import type { BrowserContextLike, ChromiumLike } from "./playwrightRuntime"; import { buildXBrowserLaunchOptions, type XBrowserChoice } from "./xBrowser"; export type Env = Readonly>; export type DisplaySource = "process" | "user-session" | "socket"; export const DISPLAY_SOURCE_LABEL: Record = { process: "the editor's own environment", "user-session": "the user session", socket: "a display socket on disk", }; export type HeadedDisplay = { // Only the display keys, to merge over the process's environment. env: { DISPLAY?: string; WAYLAND_DISPLAY?: string; XAUTHORITY?: string }; source: DisplaySource; }; // The command runner: one executable and its arguments, no shell. Resolves // with what the command printed and its exit code; a command that is missing, // times out or is killed rejects. export type RunCommand = ( file: string, args: readonly string[], opts: { timeoutMs: number }, ) => Promise<{ stdout: string; exitCode: number }>; // The slice of the file system the socket search reads. A socket counts only // when this process's user owns it: a greeter's root-owned :0, a bare Xvfb or // another user's session would take the window where nobody sees it, and the // Connect would wait for a close that never comes. export type DisplayFs = { readdir: (dir: string) => string[]; isSocket: (file: string) => boolean; ownedByMe: (file: string) => boolean; }; export type HeadedDisplayDeps = { env?: Env; run?: RunCommand; fs?: DisplayFs; // For $XDG_RUNTIME_DIR when the environment does not name it. uid?: number; timeoutMs?: number; }; export const USER_SESSION_TIMEOUT_MS = 2_000; export const X11_SOCKET_DIR = "/tmp/.X11-unix"; // The real runner (exported for its own test). export const runCommand: RunCommand = (file, args, opts) => new Promise((resolve, reject) => { execFile( file, [...args], { timeout: opts.timeoutMs, killSignal: "SIGKILL", maxBuffer: 1 << 20, encoding: "utf8" }, (err, stdout) => { if (err && (typeof (err as { code?: unknown }).code !== "number" || (err as { killed?: boolean }).killed)) { reject(err); return; } resolve({ stdout: String(stdout ?? ""), exitCode: err ? Number((err as { code?: number }).code) : 0 }); }, ); }); const defaultFs: DisplayFs = { readdir: (dir) => readdirSync(dir), isSocket: (file) => { try { return statSync(file).isSocket(); } catch { return false; } }, ownedByMe: (file) => { try { const uid = process.getuid?.(); return uid !== undefined && statSync(file).uid === uid; } catch { return false; } }, }; // --- Validation: a value from outside this process is used only when it looks // like what it names. Anything else is ignored, as if absent. const DISPLAY_RE = /^[A-Za-z0-9._/-]{0,253}:\d{1,4}(?:\.\d{1,3})?$/; const WAYLAND_RE = /^(?:[A-Za-z0-9._-]{1,64}|\/[^\0\n\r]{1,1023})$/; const XAUTHORITY_RE = /^\/[^\0\n\r]{1,1023}$/; function clean( raw: Record, ): HeadedDisplay["env"] { const out: HeadedDisplay["env"] = {}; const d = raw.DISPLAY?.trim(); const w = raw.WAYLAND_DISPLAY?.trim(); const a = raw.XAUTHORITY?.trim(); if (d && DISPLAY_RE.test(d)) out.DISPLAY = d; if (w && WAYLAND_RE.test(w)) out.WAYLAND_DISPLAY = w; if (a && XAUTHORITY_RE.test(a)) out.XAUTHORITY = a; return out; } const hasDisplay = (e: HeadedDisplay["env"]) => Boolean(e.DISPLAY || e.WAYLAND_DISPLAY); // `systemctl --user show-environment` prints KEY=VALUE lines; a value with // characters systemd escapes is printed as KEY=$'…' — never the case for a // usable display, so such a line is skipped rather than unquoted. export function parseShowEnvironment(stdout: string): HeadedDisplay["env"] { const raw: Record = {}; for (const line of stdout.split("\n")) { const m = /^(DISPLAY|WAYLAND_DISPLAY|XAUTHORITY)=(.*)$/.exec(line.replace(/\r$/, "")); if (!m || m[2].startsWith("$'")) continue; raw[m[1]] = m[2]; } return clean(raw); } function lowestNumbered(names: string[], re: RegExp): { name: string; n: number } | null { let best: { name: string; n: number } | null = null; for (const name of names) { const m = re.exec(name); if (!m) continue; const n = Number(m[1]); if (!best || n < best.n) best = { name, n }; } return best; } function fromSockets(fs: DisplayFs, env: Env, uid: number | undefined): HeadedDisplay["env"] { const out: HeadedDisplay["env"] = {}; const list = (dir: string): string[] => { try { return fs.readdir(dir); } catch { return []; } }; const mine = (dir: string) => (n: string) => { const file = path.join(dir, n); return fs.isSocket(file) && fs.ownedByMe(file); }; const x = lowestNumbered(list(X11_SOCKET_DIR).filter(mine(X11_SOCKET_DIR)), /^X(\d{1,4})$/); if (x) out.DISPLAY = `:${x.n}`; const runtime = env.XDG_RUNTIME_DIR?.trim() || (uid !== undefined ? `/run/user/${uid}` : ""); if (runtime && path.isAbsolute(runtime)) { const w = lowestNumbered(list(runtime).filter(mine(runtime)), /^wayland-(\d{1,4})$/); if (w) out.WAYLAND_DISPLAY = w.name; } return out; } export type ResolveResult = { display: HeadedDisplay | null; // What was tried and did not answer, for the log (no values). notes: string[]; }; export async function resolveHeadedDisplay(deps: HeadedDisplayDeps = {}): Promise { const env = deps.env ?? process.env; const notes: string[] = []; const own = clean({ DISPLAY: env.DISPLAY, WAYLAND_DISPLAY: env.WAYLAND_DISPLAY, XAUTHORITY: env.XAUTHORITY }); if (hasDisplay(own)) return { display: { env: own, source: "process" }, notes }; const run = deps.run ?? runCommand; const timeoutMs = deps.timeoutMs ?? USER_SESSION_TIMEOUT_MS; try { const res = await withTimeout(run("systemctl", ["--user", "show-environment"], { timeoutMs }), timeoutMs + 500); if (res.exitCode !== 0) { notes.push(`systemctl --user show-environment exited ${res.exitCode}`); } else { const session = parseShowEnvironment(res.stdout); if (hasDisplay(session)) return { display: { env: session, source: "user-session" }, notes }; notes.push("the user session names no display"); } } catch (err) { notes.push(`systemctl --user show-environment did not answer (${shortReason(err)})`); } const sockets = fromSockets(deps.fs ?? defaultFs, env, deps.uid ?? process.getuid?.()); if (hasDisplay(sockets)) return { display: { env: sockets, source: "socket" }, notes }; notes.push("no display socket of this user's on disk"); return { display: null, notes }; } function withTimeout(p: Promise, ms: number): Promise { return new Promise((resolve, reject) => { const t = setTimeout(() => reject(new Error(`timed out after ${ms} ms`)), ms); p.then( (v) => { clearTimeout(t); resolve(v); }, (e: unknown) => { clearTimeout(t); reject(e); }, ); }); } function shortReason(err: unknown): string { const e = err as { code?: unknown; killed?: boolean; message?: string }; if (e?.code === "ENOENT") return "systemctl is not installed"; if (e?.killed) return "timed out"; return String(e?.message ?? err).split("\n")[0].slice(0, 80); } // "DISPLAY=:0, WAYLAND_DISPLAY=wayland-1, XAUTHORITY set (from the user // session)". XAUTHORITY's path is never printed: it can name the home // directory, and the cookie file is not anyone's business. export function describeHeadedDisplay(d: HeadedDisplay): string { const parts: string[] = []; // Only the `:N[.S]` part: a host part ("somehost:10.0") is nobody's // business in a message or a record. The launch env keeps the whole value. if (d.env.DISPLAY) parts.push(`DISPLAY=${/:\d+(?:\.\d+)?$/.exec(d.env.DISPLAY)?.[0] ?? d.env.DISPLAY}`); if (d.env.WAYLAND_DISPLAY) { parts.push(`WAYLAND_DISPLAY=${path.isAbsolute(d.env.WAYLAND_DISPLAY) ? path.basename(d.env.WAYLAND_DISPLAY) : d.env.WAYLAND_DISPLAY}`); } if (d.env.XAUTHORITY) parts.push("XAUTHORITY set"); return `${parts.join(", ")} (from ${DISPLAY_SOURCE_LABEL[d.source]})`; } // The launch's environment: the process's, with the display keys over it. export function headedLaunchEnv(d: HeadedDisplay, base: Env = process.env): Record { const out: Record = {}; for (const [k, v] of Object.entries(base)) if (typeof v === "string") out[k] = v; for (const [k, v] of Object.entries(d.env)) if (v) out[k] = v; return out; } // --- The refusal ------------------------------------------------------------ export const NO_DESKTOP_SENTENCE = "The window opens on the editor's machine, and no desktop session was found there: " + "log in to that machine's desktop, then press Connect again."; export class NoDesktopError extends Error { constructor() { super(NO_DESKTOP_SENTENCE); this.name = "NoDesktopError"; } } // A display WAS resolved, but the browser could not open a window on it: a // stale display left in the user manager after a logout, an Xwayland that // wants an XAUTHORITY the sockets cannot name, Wayland with no X. The person // is logged in, so "log in" would be wrong; the raw error is in the log. export function displayRefusedSentence(described: string): string { return `A display was found (${described}), but the browser could not open a window on it: see the editor log.`; } export class DisplayRefusedError extends Error { constructor(described: string) { super(displayRefusedSentence(described)); this.name = "DisplayRefusedError"; } } // Chromium's "Missing X server" startup line, rewritten by Playwright into its // boxed "launched a headed browser without having a XServer running" banner. export function isMissingDisplayError(err: unknown): boolean { const msg = String((err as Error)?.message ?? err); return /without having a XServer running|Missing X server|cannot open display|Failed to connect to Wayland display/i.test(msg); } // --- The headed launch, shared by the three Connects --------------------------- function firstLine(err: unknown): string { return ((err as Error)?.message ?? String(err)).split("\n")[0]; } export type HeadedDisplayLaunchDeps = Omit; export async function launchHeadedContext(o: { // A browser that draws no window (`opensNoWindow`: a test's fake) needs no display. chromium: ChromiumLike; profileDir: string; browser: XBrowserChoice; onLog: (line: string) => void; // The environment the display is looked for in and the launch inherits; // process.env when absent. env?: Env; display?: HeadedDisplayLaunchDeps; }): Promise<{ context: BrowserContextLike; display: string }> { const base = o.env ?? process.env; let launchEnv: Record | undefined; let shown: string; if (o.chromium.opensNoWindow) { shown = "no display (this browser opens no window)"; } else { const { display, notes } = await resolveHeadedDisplay({ ...o.display, env: base }); if (!display) { o.onLog(`No display for the window: ${notes.join("; ")}.`); throw new NoDesktopError(); } shown = describeHeadedDisplay(display); launchEnv = headedLaunchEnv(display, base); o.onLog(`Opening the window on ${shown}.`); } const options = (sandbox: boolean) => ({ ...buildXBrowserLaunchOptions({ browser: o.browser, headless: false, sandbox }), ...(launchEnv ? { env: launchEnv } : {}), }); // A launch that failed on the missing display becomes the refusal; the // raw text (Playwright's banner) goes to the log only. const refusalFor = (err: unknown): unknown => { if (!isMissingDisplayError(err)) return err; o.onLog(`The browser could not open its window on ${shown}: ${String((err as Error)?.message ?? err)}`); return new DisplayRefusedError(shown); }; // The profile directory only now: a Connect refused for want of a display // leaves no empty profile behind for /cookies to report. await mkdir(o.profileDir, { recursive: true }); let context: BrowserContextLike; try { context = await o.chromium.launchPersistentContext(o.profileDir, options(true)); } catch (err) { if (isMissingDisplayError(err)) throw refusalFor(err); // A host that cannot start Chromium's sandbox (no unprivileged user // namespaces, an AppArmor rule) still gets its window — with the // unsupported-flag bar a system Chrome draws for `--no-sandbox`. o.onLog(`The sandboxed launch failed (${firstLine(err)}); opening without the sandbox.`); try { context = await o.chromium.launchPersistentContext(o.profileDir, options(false)); } catch (err2) { throw refusalFor(err2); } } return { context, display: shown }; }