// The display a headed window opens on (headedDisplay.ts): the resolver over an // injected environment, command runner and file system, and the three Connects // through a stub launcher. No desktop, no user manager, no browser, no network. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test social/headedDisplay.test.ts import { test, after } from "node:test"; import assert from "node:assert/strict"; import { existsSync, mkdtempSync } from "node:fs"; import { rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { BrowserContextLike, ChromiumLike, PageLike } from "./playwrightRuntime"; import { NO_DESKTOP_SENTENCE, NoDesktopError, DisplayRefusedError, displayRefusedSentence, runCommand, X11_SOCKET_DIR, describeHeadedDisplay, headedLaunchEnv, isMissingDisplayError, launchHeadedContext, parseShowEnvironment, resolveHeadedDisplay, type DisplayFs, type RunCommand, } from "./headedDisplay"; import { connectXAccount } from "./xSessionBroker"; import { connectForumSession } from "./forumSession"; import { connectArchiveSession } from "../lib/archives/archiveTodaySession"; const TMP = mkdtempSync(path.join(os.tmpdir(), "headed-display-")); after(() => rm(TMP, { recursive: true, force: true })); // A runtime dir computed at run time, never a real one. const RUNTIME = path.join(TMP, "run-user"); // An XAUTHORITY under the temp dir: the description must never print it. const XAUTH = path.join(TMP, "home", ".Xauthority"); type Call = { file: string; args: readonly string[]; timeoutMs: number }; function runner(answer: { stdout?: string; exitCode?: number } | Error | "hang"): { run: RunCommand; calls: Call[] } { const calls: Call[] = []; const run: RunCommand = (file, args, opts) => { calls.push({ file, args, timeoutMs: opts.timeoutMs }); if (answer === "hang") return new Promise(() => {}); if (answer instanceof Error) return Promise.reject(answer); return Promise.resolve({ stdout: answer.stdout ?? "", exitCode: answer.exitCode ?? 0 }); }; return { run, calls }; } // A file system holding the named sockets (and plain files that are not). // `foreign` sockets are sockets owned by another user (root's greeter, a bare // Xvfb, someone else's session). function fakeFs(dirs: Record): DisplayFs { const at = (file: string) => dirs[path.dirname(file)]; return { readdir: (dir) => { const d = dirs[dir]; if (!d) throw Object.assign(new Error(`ENOENT: ${dir}`), { code: "ENOENT" }); return [...(d.sockets ?? []), ...(d.foreign ?? []), ...(d.files ?? [])]; }, isSocket: (file) => { const d = at(file); const n = path.basename(file); return Boolean(d?.sockets?.includes(n) || d?.foreign?.includes(n)); }, ownedByMe: (file) => { const d = at(file); const n = path.basename(file); return Boolean(d && !d.foreign?.includes(n) && (d.sockets?.includes(n) || d.files?.includes(n))); }, }; } const NO_SOCKETS = fakeFs({}); const SILENT = runner({ stdout: "HOME=/nowhere\nLANG=C\n" }).run; // --- 1. this process's own environment ------------------------------------------------- test("the process's own DISPLAY wins, and the user manager is not asked", async () => { const r = runner({ stdout: "DISPLAY=:5\n" }); const got = await resolveHeadedDisplay({ env: { DISPLAY: ":1", XAUTHORITY: XAUTH, XDG_RUNTIME_DIR: RUNTIME }, run: r.run, fs: fakeFs({ [X11_SOCKET_DIR]: { sockets: ["X0"] } }), }); assert.deepEqual(got.display, { env: { DISPLAY: ":1", XAUTHORITY: XAUTH }, source: "process" }); assert.equal(r.calls.length, 0); }); test("a Wayland-only process environment is a display too", async () => { const got = await resolveHeadedDisplay({ env: { WAYLAND_DISPLAY: "wayland-0" }, run: SILENT, fs: NO_SOCKETS }); assert.deepEqual(got.display, { env: { WAYLAND_DISPLAY: "wayland-0" }, source: "process" }); }); test("an XAUTHORITY alone in the process environment is not a display", async () => { const got = await resolveHeadedDisplay({ env: { XAUTHORITY: XAUTH }, run: SILENT, fs: NO_SOCKETS }); assert.equal(got.display, null); }); // --- 2. the user manager --------------------------------------------------------------------- test("no display of its own: the user session's, asked as an argument vector with a short timeout", async () => { const r = runner({ stdout: `HOME=/nowhere\nDISPLAY=:0\nWAYLAND_DISPLAY=wayland-1\nXAUTHORITY=${XAUTH}\nPATH=/usr/bin\n`, }); const got = await resolveHeadedDisplay({ env: { XDG_RUNTIME_DIR: RUNTIME }, run: r.run, fs: NO_SOCKETS }); assert.deepEqual(got.display, { env: { DISPLAY: ":0", WAYLAND_DISPLAY: "wayland-1", XAUTHORITY: XAUTH }, source: "user-session", }); assert.equal(r.calls.length, 1); assert.equal(r.calls[0].file, "systemctl"); assert.deepEqual(r.calls[0].args, ["--user", "show-environment"]); assert.ok(r.calls[0].timeoutMs > 0 && r.calls[0].timeoutMs <= 5_000); }); test("only the display keys are taken from the user session", () => { const env = parseShowEnvironment("DISPLAY=:0\nSSH_AUTH_SOCK=/x\nLD_PRELOAD=/evil.so\nDBUS_SESSION_BUS_ADDRESS=unix:path=/x\n"); assert.deepEqual(env, { DISPLAY: ":0" }); }); test("garbage from the user manager is ignored, and the sockets are looked at", async () => { const garbage = [ "\u0000\u0001binary", "DISPLAY=not a display", "DISPLAY=:0; rm -rf /", "WAYLAND_DISPLAY=$'wayland\\n-1'", "XAUTHORITY=relative/path", "DISPLAY", "=:0", ].join("\n"); const got = await resolveHeadedDisplay({ env: { XDG_RUNTIME_DIR: RUNTIME }, run: runner({ stdout: garbage }).run, fs: fakeFs({ [X11_SOCKET_DIR]: { sockets: ["X2"] } }), }); assert.deepEqual(got.display, { env: { DISPLAY: ":2" }, source: "socket" }); assert.match(got.notes.join("; "), /names no display/); }); test("a user manager that hangs is given up on, and the sockets answer", async () => { const t0 = Date.now(); const got = await resolveHeadedDisplay({ env: { XDG_RUNTIME_DIR: RUNTIME }, run: runner("hang").run, timeoutMs: 50, fs: fakeFs({ [RUNTIME]: { sockets: ["wayland-0"] } }), }); assert.ok(Date.now() - t0 < 2_000); assert.deepEqual(got.display, { env: { WAYLAND_DISPLAY: "wayland-0" }, source: "socket" }); assert.match(got.notes.join("; "), /did not answer \(timed out/); }); test("no systemctl (a container) and a failing one both fall through to the sockets", async () => { const missing = await resolveHeadedDisplay({ env: {}, run: runner(Object.assign(new Error("spawn systemctl ENOENT"), { code: "ENOENT" })).run, fs: NO_SOCKETS, }); assert.equal(missing.display, null); assert.match(missing.notes.join("; "), /systemctl is not installed/); const failing = await resolveHeadedDisplay({ env: {}, run: runner({ stdout: "", exitCode: 1 }).run, fs: fakeFs({ [X11_SOCKET_DIR]: { sockets: ["X0"] } }), }); assert.deepEqual(failing.display, { env: { DISPLAY: ":0" }, source: "socket" }); assert.match(failing.notes.join("; "), /exited 1/); }); // --- 3. the sockets on disk ------------------------------------------------------------------- test("sockets: the lowest X and wayland-; locks, plain files and other names are not displays", async () => { const got = await resolveHeadedDisplay({ env: { XDG_RUNTIME_DIR: RUNTIME }, run: SILENT, fs: fakeFs({ [X11_SOCKET_DIR]: { sockets: ["X3", "X1", "Xfoo"], files: ["X0"] }, [RUNTIME]: { sockets: ["wayland-2", "wayland-1", "pipewire-0"], files: ["wayland-0", "wayland-1.lock"] }, }), }); assert.deepEqual(got.display, { env: { DISPLAY: ":1", WAYLAND_DISPLAY: "wayland-1" }, source: "socket" }); }); test("no XDG_RUNTIME_DIR: the runtime dir is found from the uid", async () => { const runtime = "/run/user/4242"; const got = await resolveHeadedDisplay({ env: {}, uid: 4242, run: SILENT, fs: fakeFs({ [runtime]: { sockets: ["wayland-0"] } }), }); assert.deepEqual(got.display, { env: { WAYLAND_DISPLAY: "wayland-0" }, source: "socket" }); }); test("sockets: one owned by another user is never chosen — a root-owned :0 beside an owned :1 picks :1", async () => { const got = await resolveHeadedDisplay({ env: { XDG_RUNTIME_DIR: RUNTIME }, run: SILENT, fs: fakeFs({ [X11_SOCKET_DIR]: { foreign: ["X0"], sockets: ["X1"] }, [RUNTIME]: { foreign: ["wayland-0"], sockets: ["wayland-3"] }, }), }); assert.deepEqual(got.display, { env: { DISPLAY: ":1", WAYLAND_DISPLAY: "wayland-3" }, source: "socket" }); }); test("sockets: only foreign ones (a greeter, a bare Xvfb) is no display, and a Connect is refused", async () => { const fs = fakeFs({ [X11_SOCKET_DIR]: { foreign: ["X0", "X99"] }, [RUNTIME]: { foreign: ["wayland-0"] } }); const got = await resolveHeadedDisplay({ env: { XDG_RUNTIME_DIR: RUNTIME }, run: SILENT, fs }); assert.equal(got.display, null); const { chromium, launches } = stubChromium(); await assert.rejects( launchHeadedContext({ chromium, profileDir: path.join(TMP, "p-foreign"), browser: { kind: "bundled" }, onLog: () => {}, env: { XDG_RUNTIME_DIR: RUNTIME }, display: { run: SILENT, fs }, }), { message: NO_DESKTOP_SENTENCE }, ); assert.equal(launches.length, 0); }); test("nothing anywhere: no display, and the notes say what was tried", async () => { const got = await resolveHeadedDisplay({ env: { XDG_RUNTIME_DIR: RUNTIME }, run: SILENT, fs: NO_SOCKETS }); assert.equal(got.display, null); assert.match(got.notes.join("; "), /names no display; no display socket of this user.s on disk/); }); test("precedence: the user session beats the sockets", async () => { const got = await resolveHeadedDisplay({ env: { XDG_RUNTIME_DIR: RUNTIME }, run: runner({ stdout: "DISPLAY=:7\n" }).run, fs: fakeFs({ [X11_SOCKET_DIR]: { sockets: ["X0"] } }), }); assert.deepEqual(got.display, { env: { DISPLAY: ":7" }, source: "user-session" }); }); // --- the description, the env, the banner ------------------------------------------------- test("the description names the display and its source, never XAUTHORITY's path", () => { const s = describeHeadedDisplay({ env: { DISPLAY: ":0", WAYLAND_DISPLAY: "wayland-1", XAUTHORITY: XAUTH }, source: "user-session" }); assert.equal(s, "DISPLAY=:0, WAYLAND_DISPLAY=wayland-1, XAUTHORITY set (from the user session)"); assert.ok(!s.includes(TMP)); assert.equal( describeHeadedDisplay({ env: { WAYLAND_DISPLAY: path.join(RUNTIME, "wayland-0") }, source: "process" }), "WAYLAND_DISPLAY=wayland-0 (from the editor's own environment)", ); }); test("a DISPLAY with a host part is described as its :N[.S] only; the launch env keeps the whole value", () => { const d = { env: { DISPLAY: "somehost.example:10.0" }, source: "process" as const }; assert.equal(describeHeadedDisplay(d), "DISPLAY=:10.0 (from the editor's own environment)"); assert.equal(describeHeadedDisplay({ env: { DISPLAY: "unix/:3" }, source: "user-session" }), "DISPLAY=:3 (from the user session)"); assert.equal(headedLaunchEnv(d, {}).DISPLAY, "somehost.example:10.0"); }); test("the launch env with no base given is process.env with the display over it (the production path)", () => { const env = headedLaunchEnv({ env: { DISPLAY: ":42", WAYLAND_DISPLAY: "wayland-9" }, source: "socket" }); assert.equal(env.DISPLAY, ":42"); assert.equal(env.WAYLAND_DISPLAY, "wayland-9"); for (const k of ["PATH", "HOME"]) if (process.env[k] !== undefined) assert.equal(env[k], process.env[k]); assert.notEqual(process.env.DISPLAY, ":42"); }); test("the real runner: an argument vector, a non-zero exit answered, a missing command and a hang rejected", async () => { const ok = await runCommand(process.execPath, ["-e", "process.stdout.write('DISPLAY=:0\\n')"], { timeoutMs: 10_000 }); assert.deepEqual(ok, { stdout: "DISPLAY=:0\n", exitCode: 0 }); const failing = await runCommand(process.execPath, ["-e", "process.exit(3)"], { timeoutMs: 10_000 }); assert.equal(failing.exitCode, 3); await assert.rejects( runCommand(path.join(TMP, "no-such-command"), [], { timeoutMs: 10_000 }), (e: unknown) => (e as { code?: unknown }).code === "ENOENT", ); const t0 = Date.now(); await assert.rejects( runCommand(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { timeoutMs: 300 }), (e: unknown) => (e as { killed?: boolean }).killed === true, ); assert.ok(Date.now() - t0 < 10_000); }); test("the launch env is the base with the display over it; process.env is not touched", () => { const before = { DISPLAY: process.env.DISPLAY, WAYLAND_DISPLAY: process.env.WAYLAND_DISPLAY }; const env = headedLaunchEnv({ env: { DISPLAY: ":9" }, source: "socket" }, { PATH: "/bin", DISPLAY: undefined, HOME: "/h" }); assert.deepEqual(env, { PATH: "/bin", HOME: "/h", DISPLAY: ":9" }); assert.deepEqual({ DISPLAY: process.env.DISPLAY, WAYLAND_DISPLAY: process.env.WAYLAND_DISPLAY }, before); }); test("Playwright's missing-X-server banner is recognised", () => { assert.ok( isMissingDisplayError( new Error( "browserType.launchPersistentContext: Target page, context or browser has been closed\n" + "Looks like you launched a headed browser without having a XServer running.", ), ), ); assert.ok(isMissingDisplayError(new Error("[pid=1][err] Missing X server or $DISPLAY"))); assert.ok(!isMissingDisplayError(new Error("No usable sandbox!"))); }); // --- the stub launcher ------------------------------------------------------------------------ type Launch = { dir: string; opts: Record }; function fakeContext(html = "ok"): BrowserContextLike { const page = { goto: async () => null, waitForSelector: async () => null, waitForTimeout: async () => {}, evaluate: async () => html, on: () => {}, } as unknown as PageLike; return { newPage: async () => page, pages: () => [page], cookies: async () => [], addCookies: async () => {}, close: async () => {}, on: (event: string, cb: () => void) => { if (event === "close") setTimeout(cb, 5); }, }; } function stubChromium(answers: Array = ["ok"], extra: Partial = {}) { const launches: Launch[] = []; const chromium: ChromiumLike = { launch: async () => { throw new Error("not used"); }, launchPersistentContext: async (dir, opts) => { launches.push({ dir, opts }); const a = answers[Math.min(launches.length - 1, answers.length - 1)]; if (a instanceof Error) throw a; return fakeContext(); }, ...extra, }; return { chromium, launches }; } const USER_SESSION = { run: runner({ stdout: "DISPLAY=:0\nWAYLAND_DISPLAY=wayland-1\n" }).run, fs: NO_SOCKETS }; const NOWHERE = { run: SILENT, fs: NO_SOCKETS }; const BASE_ENV = { PATH: "", HOME: "/h" }; test("a headed launch is handed the display as env, merged over the base", async () => { const { chromium, launches } = stubChromium(); const log: string[] = []; const got = await launchHeadedContext({ chromium, profileDir: path.join(TMP, "p1"), browser: { kind: "bundled" }, onLog: (l) => log.push(l), env: BASE_ENV, display: USER_SESSION, }); assert.equal(launches.length, 1); assert.equal(launches[0].opts.headless, false); assert.deepEqual(launches[0].opts.env, { PATH: "", HOME: "/h", DISPLAY: ":0", WAYLAND_DISPLAY: "wayland-1" }); assert.equal(got.display, "DISPLAY=:0, WAYLAND_DISPLAY=wayland-1 (from the user session)"); assert.ok(log.some((l) => l === `Opening the window on ${got.display}.`)); }); test("no display: refused before anything launches, in one sentence", async () => { const { chromium, launches } = stubChromium(); const log: string[] = []; await assert.rejects( launchHeadedContext({ chromium, profileDir: path.join(TMP, "p2"), browser: { kind: "bundled" }, onLog: (l) => log.push(l), env: BASE_ENV, display: NOWHERE }), (e: unknown) => e instanceof NoDesktopError && (e as Error).message === NO_DESKTOP_SENTENCE, ); assert.equal(launches.length, 0); assert.ok(log.some((l) => l.startsWith("No display for the window:"))); assert.ok(!NO_DESKTOP_SENTENCE.includes("XServer") && !NO_DESKTOP_SENTENCE.includes("Playwright")); }); const BANNER = () => new Error("browserType.launchPersistentContext: Looks like you launched a headed browser without having a XServer running."); const FOUND = "A display was found (DISPLAY=:0, WAYLAND_DISPLAY=wayland-1 (from the user session)), but the browser could not open a window on it: see the editor log."; test("the second sentence names the display found, never XAUTHORITY's path", () => { assert.equal(displayRefusedSentence("DISPLAY=:0, WAYLAND_DISPLAY=wayland-1 (from the user session)"), FOUND); const e = new DisplayRefusedError(describeHeadedDisplay({ env: { DISPLAY: ":0", XAUTHORITY: XAUTH }, source: "user-session" })); assert.ok(!e.message.includes(TMP)); assert.notEqual(e.message, NO_DESKTOP_SENTENCE); }); test("a display found but the launch hits the XServer banner: the second sentence, the raw text in the log", async () => { const { chromium, launches } = stubChromium([BANNER()]); const log: string[] = []; await assert.rejects( launchHeadedContext({ chromium, profileDir: path.join(TMP, "p3"), browser: { kind: "bundled" }, onLog: (l) => log.push(l), env: BASE_ENV, display: USER_SESSION }), (e: unknown) => e instanceof DisplayRefusedError && (e as Error).message === FOUND, ); // Not retried without the sandbox: the display is the problem, not the sandbox. assert.equal(launches.length, 1); assert.ok(log.some((l) => l.includes("without having a XServer running"))); }); test("the banner on the no-sandbox retry gives the second sentence too", async () => { const { chromium, launches } = stubChromium([new Error("No usable sandbox!"), BANNER()]); const log: string[] = []; await assert.rejects( launchHeadedContext({ chromium, profileDir: path.join(TMP, "p3b"), browser: { kind: "bundled" }, onLog: (l) => log.push(l), env: BASE_ENV, display: USER_SESSION }), { message: FOUND }, ); assert.equal(launches.length, 2); assert.ok(log.some((l) => l.includes("without having a XServer running"))); }); test("a sandbox failure is retried without the sandbox, with the display env still passed", async () => { const { chromium, launches } = stubChromium([new Error("No usable sandbox!"), "ok"]); await launchHeadedContext({ chromium, profileDir: path.join(TMP, "p4"), browser: { kind: "bundled" }, onLog: () => {}, env: BASE_ENV, display: USER_SESSION }); assert.equal(launches.length, 2); assert.equal(launches[0].opts.chromiumSandbox, true); assert.equal(launches[1].opts.chromiumSandbox, undefined); for (const l of launches) assert.equal((l.opts.env as Record).DISPLAY, ":0"); }); test("a browser that opens no window (the e2e fake) needs no display", async () => { const { chromium, launches } = stubChromium(["ok"], { opensNoWindow: true }); const got = await launchHeadedContext({ chromium, profileDir: path.join(TMP, "p5"), browser: { kind: "bundled" }, onLog: () => {}, env: BASE_ENV, display: NOWHERE }); assert.equal(launches.length, 1); assert.equal(launches[0].opts.env, undefined); assert.match(got.display, /opens no window/); }); // --- each Connect passes the env ------------------------------------------------------------------ const paths = (name: string) => ({ transcriptsDir: path.join(TMP, name), autoQueueStateFile: path.join(TMP, name, ".auto-queue", "state.json") }) as unknown as Paths; test("Connect X account: the window gets the display, and the result says which", async () => { const { chromium, launches } = stubChromium(); const res = await connectXAccount(paths("x"), { chromium, env: BASE_ENV, display: USER_SESSION }); assert.equal(launches.length, 1); assert.equal((launches[0].opts.env as Record).DISPLAY, ":0"); assert.equal(res.display, "DISPLAY=:0, WAYLAND_DISPLAY=wayland-1 (from the user session)"); }); test("Connect X account with no desktop: refused, no launch, no profile left behind", async () => { const { chromium, launches } = stubChromium(); await assert.rejects(connectXAccount(paths("x2"), { chromium, env: BASE_ENV, display: NOWHERE }), { message: NO_DESKTOP_SENTENCE }); assert.equal(launches.length, 0); assert.equal(existsSync(path.join(TMP, "x2", ".x-session")), false); }); test("Connect forum session: the window gets the display, and the record says which", async () => { const { chromium, launches } = stubChromium(); const rec = await connectForumSession(paths("forum"), "https://forum.example.test/threads/1/", { chromium, env: BASE_ENV, display: USER_SESSION }); assert.equal(launches.length, 1); assert.equal((launches[0].opts.env as Record).WAYLAND_DISPLAY, "wayland-1"); assert.equal(rec.display, "DISPLAY=:0, WAYLAND_DISPLAY=wayland-1 (from the user session)"); const stub = stubChromium(); await assert.rejects( connectForumSession(paths("forum2"), "https://forum.example.test/threads/1/", { chromium: stub.chromium, env: BASE_ENV, display: NOWHERE }), { message: NO_DESKTOP_SENTENCE }, ); assert.equal(stub.launches.length, 0); // No profile and no session.json: /cookies does not think one exists. assert.equal(existsSync(path.join(TMP, "forum2", ".forum-session")), false); }); test("Connect archive session: the window gets the display, and the record says which", async () => { const { chromium, launches } = stubChromium(); const rec = await connectArchiveSession(paths("archive"), "https://archive.example.test/", { chromium, env: BASE_ENV, display: USER_SESSION }); assert.equal(launches.length, 1); assert.equal((launches[0].opts.env as Record).DISPLAY, ":0"); assert.equal(rec.display, "DISPLAY=:0, WAYLAND_DISPLAY=wayland-1 (from the user session)"); const stub = stubChromium(); await assert.rejects( connectArchiveSession(paths("archive2"), "https://archive.example.test/", { chromium: stub.chromium, env: BASE_ENV, display: NOWHERE }), { message: NO_DESKTOP_SENTENCE }, ); assert.equal(stub.launches.length, 0); assert.equal(existsSync(path.join(TMP, "archive2", ".archive-session")), false); });