Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 9f790c041477c078cc34731790c0bfe3a4490b63
parent 208a2c4c9afde59f880d7d249913e23af9e3702d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 17 Nov 2026 14:20:35 -0500

headed Connects find the desktop even when the editor started before it

Connect X account, Connect archive session and Connect forum session open a
headed window. The editor is a systemd user unit started at boot, before the
desktop session, so its environment carries no DISPLAY / WAYLAND_DISPLAY /
XAUTHORITY and every Connect failed with Playwright's "launched a headed
browser without having a XServer running" until a restart.

common/social/headedDisplay.ts resolves the display at each launch: the
process's own keys, else the user manager's (`systemctl --user
show-environment`, argument vector, 2 s timeout, only the three keys,
validated), else the sockets on disk (/tmp/.X11-unix/X<n>,
$XDG_RUNTIME_DIR/wayland-<n>). It is passed as the launch's `env`, merged
over the process's, never written into process.env. No display: refused
before launching with one sentence; a launch that still fails on the
missing-X-server banner becomes the same sentence, the raw text logged. The
log and the result name the display and where it came from (XAUTHORITY's
path never printed). The three Connects share the one headed launch
(sandbox retry included); the e2e fake browser declares opensNoWindow and
needs no display.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
Mcommon/lib/archives/archiveTodaySession.ts | 36++++++++++++++++++++++++++----------
Mcommon/social/fakeXProfileBrowser.ts | 2++
Mcommon/social/forumSession.ts | 40+++++++++++++++++++++++++---------------
Acommon/social/headedDisplay.test.ts | 384+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/headedDisplay.ts | 341+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/playwrightRuntime.ts | 4++++
Mcommon/social/xSessionBroker.ts | 33+++++++++++++++------------------
Meditor/app/settings/xSessionActions.ts | 11+++++++----
8 files changed, 804 insertions(+), 47 deletions(-)

diff --git a/common/lib/archives/archiveTodaySession.ts b/common/lib/archives/archiveTodaySession.ts @@ -19,7 +19,8 @@ import type { Paths } from "../paths"; import { readJsonFile, writeJsonAtomic } from "../jsonFile-server"; import { importPlaywright, type BrowserContextLike, type ChromiumLike, type PageLike } from "../../social/playwrightRuntime"; import { openForumProfile } from "../../social/forumSession"; -import { buildXBrowserLaunchOptions, describeXBrowser, findXBrowser, writeXBrowserRecord } from "../../social/xBrowser"; +import { describeXBrowser, findXBrowser, writeXBrowserRecord } from "../../social/xBrowser"; +import { launchHeadedContext, type HeadedDisplayLaunchDeps } from "../../social/headedDisplay"; import { isArchiveTodayChallenge } from "./archiveToday"; import type { ArchiveTodayBrowser, ArchiveTodayBrowserLoad } from "./archiveTodayClient"; @@ -42,6 +43,9 @@ export type ArchiveSessionRecord = { cleared: boolean; cookies: number; browser?: string; + // The display the window opened on and where it was found + // (social/headedDisplay.ts): "DISPLAY=:0 (from the user session)". + display?: string; }; export type ArchiveSessionStatus = { @@ -136,7 +140,15 @@ export function archiveSessionBrowser( export async function connectArchiveSession( paths: Pick<Paths, "transcriptsDir">, url: string, - o: { onLog?: (l: string) => void; timeoutMs?: number; env?: Record<string, string | undefined> } = {}, + o: { + onLog?: (l: string) => void; + timeoutMs?: number; + env?: Record<string, string | undefined>; + // Injectable for tests: a stand-in browser, and the display search's + // runner and file system (social/headedDisplay.ts). + chromium?: ChromiumLike; + display?: HeadedDisplayLaunchDeps; + } = {}, ): Promise<ArchiveSessionRecord> { const log = o.onLog ?? (() => {}); const host = new URL(url).hostname.toLowerCase(); @@ -144,15 +156,18 @@ export async function connectArchiveSession( await mkdir(profileDir, { recursive: true }); const browser = findXBrowser({ env: o.env }); const label = describeXBrowser(browser); - const { chromium } = await importPlaywright(); + const chromium = o.chromium ?? (await importPlaywright()).chromium; log(`Opening ${label} at ${host}. Pass the check if one shows, wait for the page, then close the window.`); - let context: BrowserContextLike; - try { - context = await chromium.launchPersistentContext(profileDir, buildXBrowserLaunchOptions({ browser, headless: false, sandbox: true })); - } catch (err) { - log(`The sandboxed launch failed (${firstLine(err)}); opening without the sandbox.`); - context = await chromium.launchPersistentContext(profileDir, buildXBrowserLaunchOptions({ browser, headless: false, sandbox: false })); - } + // On the desktop's display, found at this press (social/headedDisplay.ts): + // refused with a sentence when there is none. + const { context, display } = await launchHeadedContext({ + chromium, + profileDir, + browser, + onLog: log, + env: o.env, + display: o.display, + }); await writeXBrowserRecord(profileDir, browser).catch(() => {}); let cleared = false; let cookies = 0; @@ -194,6 +209,7 @@ export async function connectArchiveSession( cleared, cookies, browser: label, + display, }; await writeJsonAtomic(path.join(archiveSessionDir(paths), "session.json"), record, { mkdir: true }); log( diff --git a/common/social/fakeXProfileBrowser.ts b/common/social/fakeXProfileBrowser.ts @@ -95,6 +95,8 @@ export function fakeXProfileChromium( }, }; return { + // Connect's "window" is not one: no display is looked for. + opensNoWindow: true, launch: async () => { throw new Error("the fake X profile browser launches no browser"); }, diff --git a/common/social/forumSession.ts b/common/social/forumSession.ts @@ -45,6 +45,7 @@ import { type XBrowserChoice, } from "./xBrowser"; import { classifyForumPage, type ForumBlock } from "./xenforoParse"; +import { launchHeadedContext, type HeadedDisplayLaunchDeps } from "./headedDisplay"; // A host as a directory name: lowercased, nothing but [a-z0-9.-]. export function forumHostKey(host: string): string { @@ -69,6 +70,9 @@ export type ForumSessionRecord = { cleared: boolean; cookies: number; browser?: string; + // The display the window opened on and where it was found + // (social/headedDisplay.ts): "DISPLAY=:0 (from the user session)". + display?: string; }; export type ForumSessionStatus = { @@ -327,7 +331,15 @@ function cookiesForHost(cookies: ReadonlyArray<CookieLike>, host: string): numbe export async function connectForumSession( paths: Pick<Paths, "transcriptsDir">, url: string, - opts: { onLog?: (line: string) => void; timeoutMs?: number; env?: Record<string, string | undefined> } = {}, + opts: { + onLog?: (line: string) => void; + timeoutMs?: number; + env?: Record<string, string | undefined>; + // Injectable for tests: a stand-in browser, and the display search's + // runner and file system (headedDisplay.ts). + chromium?: ChromiumLike; + display?: HeadedDisplayLaunchDeps; + } = {}, ): Promise<ForumSessionRecord> { const log = opts.onLog ?? (() => {}); const host = new URL(url).hostname.toLowerCase(); @@ -336,21 +348,18 @@ export async function connectForumSession( const browser = findXBrowser({ env: opts.env }); const version = await browserVersion(browser); const label = describeXBrowser(browser, version); - const { chromium } = await importPlaywright(); + const chromium = opts.chromium ?? (await importPlaywright()).chromium; log(`Opening ${label} at ${host}. Clear the check (or log in), wait for the thread to show, then close the window.`); - let context: BrowserContextLike; - try { - context = await chromium.launchPersistentContext( - profileDir, - buildXBrowserLaunchOptions({ browser, headless: false, sandbox: true }), - ); - } catch (err) { - log(`The sandboxed launch failed (${firstLine(err)}); opening without the sandbox.`); - context = await chromium.launchPersistentContext( - profileDir, - buildXBrowserLaunchOptions({ browser, headless: false, sandbox: false }), - ); - } + // On the desktop's display, found at this press (headedDisplay.ts): refused + // with a sentence when there is none. + const { context, display } = await launchHeadedContext({ + chromium, + profileDir, + browser, + onLog: log, + env: opts.env, + display: opts.display, + }); await writeXBrowserRecord(profileDir, browser, version).catch((err) => { log(`Could not record the browser in the profile: ${firstLine(err)}`); }); @@ -395,6 +404,7 @@ export async function connectForumSession( cleared, cookies, browser: label, + display, }; await writeJsonAtomic(path.join(forumSessionDir(paths, host), "session.json"), record, { mkdir: true }); log( diff --git a/common/social/headedDisplay.test.ts b/common/social/headedDisplay.test.ts @@ -0,0 +1,384 @@ +// 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 { 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, + 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). +function fakeFs(dirs: Record<string, { sockets?: string[]; files?: string[] }>): DisplayFs { + return { + readdir: (dir) => { + const d = dirs[dir]; + if (!d) throw Object.assign(new Error(`ENOENT: ${dir}`), { code: "ENOENT" }); + return [...(d.sockets ?? []), ...(d.files ?? [])]; + }, + isSocket: (file) => Boolean(dirs[path.dirname(file)]?.sockets?.includes(path.basename(file))), + }; +} + +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<n> and wayland-<n>; 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("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 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("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<string, unknown> }; + +function fakeContext(html = "<html><body>ok</body></html>"): 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<Error | "ok"> = ["ok"], extra: Partial<ChromiumLike> = {}) { + 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")); +}); + +test("a launch that still fails on the XServer banner becomes the same sentence; the raw text goes to the log", async () => { + const banner = new Error("browserType.launchPersistentContext: Looks like you launched a headed browser without having a XServer running."); + 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 as Error).message === NO_DESKTOP_SENTENCE, + ); + // 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("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<string, string>).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) }) 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<string, string>).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", 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); +}); + +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<string, string>).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); +}); + +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<string, string>).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); +}); diff --git a/common/social/headedDisplay.ts b/common/social/headedDisplay.ts @@ -0,0 +1,341 @@ +// 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<n> → DISPLAY=:<n>, and +// $XDG_RUNTIME_DIR/wayland-<n> → WAYLAND_DISPLAY=wayland-<n>. +// 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, with a sentence a person can act on; a launch that +// still fails on the missing-X-server banner is turned into the same sentence +// (the raw text goes to the log only). +// +// 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 path from "node:path"; +import type { BrowserContextLike, ChromiumLike } from "./playwrightRuntime"; +import { buildXBrowserLaunchOptions, type XBrowserChoice } from "./xBrowser"; + +export type Env = Readonly<Record<string, string | undefined>>; + +export type DisplaySource = "process" | "user-session" | "socket"; + +export const DISPLAY_SOURCE_LABEL: Record<DisplaySource, string> = { + 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. +export type DisplayFs = { + readdir: (dir: string) => string[]; + isSocket: (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"; + +const defaultRun: 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; + } + }, +}; + +// --- 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<string, string | undefined>, +): 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<string, string> = {}; + 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 x = lowestNumbered( + list(X11_SOCKET_DIR).filter((n) => fs.isSocket(path.join(X11_SOCKET_DIR, n))), + /^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((n) => fs.isSocket(path.join(runtime, n))), + /^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<ResolveResult> { + 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 ?? defaultRun; + 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 on disk"); + return { display: null, notes }; +} + +function withTimeout<T>(p: Promise<T>, ms: number): Promise<T> { + return new Promise<T>((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[] = []; + if (d.env.DISPLAY) parts.push(`DISPLAY=${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<string, string> { + const out: Record<string, string> = {}; + 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"; + } +} + +// 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<HeadedDisplayDeps, "env">; + +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<string, string> | undefined; + let shown: string; + if (o.chromium.opensNoWindow) { + shown = "none (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 NoDesktopError(); + }; + 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 }; +} diff --git a/common/social/playwrightRuntime.ts b/common/social/playwrightRuntime.ts @@ -32,6 +32,10 @@ export type ChromiumLike = { dir: string, opts: Record<string, unknown>, ) => Promise<BrowserContextLike>; + // Set by a stand-in that draws no window (the e2e suite's fake, + // fakeXProfileBrowser.ts): a headed launch through it needs no display + // (headedDisplay.ts). Playwright's own chromium never sets it. + opensNoWindow?: boolean; }; export type BrowserLike = { diff --git a/common/social/xSessionBroker.ts b/common/social/xSessionBroker.ts @@ -43,6 +43,7 @@ import { writeXBrowserRecord, type XBrowserChoice, } from "./xBrowser"; +import { launchHeadedContext, type HeadedDisplayLaunchDeps } from "./headedDisplay"; // Where the persistent browser profile lives. One profile per instance: a // single X identity is all the archive needs. @@ -187,8 +188,10 @@ export async function connectXAccount( // Injectable so the flow is testable without a browser (the e2e suite's // fake, social/fakeXProfileBrowser.ts). chromium?: ChromiumLike; + // The display search's runner and file system (headedDisplay.ts), for tests. + display?: HeadedDisplayLaunchDeps; } = {}, -): Promise<XSessionStatus & { browser: string }> { +): Promise<XSessionStatus & { browser: string; display: string }> { const log = opts.onLog ?? (() => {}); const profileDir = xProfileDir(paths); await mkdir(profileDir, { recursive: true }); @@ -198,22 +201,16 @@ export async function connectXAccount( const label = describeXBrowser(browser, version); const chromium = opts.chromium ?? (await importPlaywright()).chromium; log(`Opening ${label}. Log in to X, then close the window.`); - let context: BrowserContextLike; - try { - context = await chromium.launchPersistentContext( - profileDir, - buildXBrowserLaunchOptions({ browser, headless: false, sandbox: true }), - ); - } catch (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`. - log(`The sandboxed launch failed (${firstLine(err)}); opening without the sandbox.`); - context = await chromium.launchPersistentContext( - profileDir, - buildXBrowserLaunchOptions({ browser, headless: false, sandbox: false }), - ); - } + // On the desktop's display, found at this press (headedDisplay.ts): refused + // with a sentence when there is none. + const { context, display } = await launchHeadedContext({ + chromium, + profileDir, + browser, + onLog: log, + env: opts.env, + display: opts.display, + }); await writeXBrowserRecord(profileDir, browser, version).catch((err) => { log(`Could not record the browser in the profile: ${firstLine(err)}`); }); @@ -237,7 +234,7 @@ export async function connectXAccount( } finally { await context.close().catch(() => {}); } - return { ...(await readXSessionStatus(paths)), browser: label }; + return { ...(await readXSessionStatus(paths)), browser: label, display }; } // THE PROFILE, OPENED HEADLESS — the Playwright fallback fetcher (profile diff --git a/editor/app/settings/xSessionActions.ts b/editor/app/settings/xSessionActions.ts @@ -57,7 +57,7 @@ function socialXPatch( // Every session action returns the source in use beside the profile's status: // connecting or forgetting a profile can move the read-time default. export type XSessionActionResult = - | { ok: true; status: XSessionStatus; source: XCookieSourceView; browser?: string } + | { ok: true; status: XSessionStatus; source: XCookieSourceView; browser?: string; display?: string } | { ok: false; error: string }; // Drawn by the client, so through settings.privacy (lib/xSourceDisplay.ts). @@ -75,7 +75,10 @@ export async function xSessionStatusAction(): Promise<XSessionStatus> { export async function connectXAccountAction(): Promise<XSessionActionResult> { return withCookieAction("x", "connect", connectXAccountNow, (r) => r.ok - ? { ok: true, message: `Connected${r.browser ? ` with ${r.browser}` : ""}. Cookies exported.` } + ? { + ok: true, + message: `Connected${r.browser ? ` with ${r.browser}` : ""}${r.display ? `, on ${r.display}` : ""}. Cookies exported.`, + } : { ok: false, message: r.error }, ); } @@ -85,7 +88,7 @@ async function connectXAccountNow(): Promise<XSessionActionResult> { // Under the e2e test server only, the fake browser (fakeXProfileBrowser.ts // says how it is gated); everywhere else null, and the real window opens. const chromium = fakeXProfileChromium(getPaths().transcriptsDir); - const { browser, ...status } = await connectXAccount(getPaths(), { + const { browser, display, ...status } = await connectXAccount(getPaths(), { // Which browser opened, and any fallback, in the editor's log. onLog: (line) => console.log(`[x-session] ${line}`), ...(chromium ? { chromium } : {}), @@ -100,7 +103,7 @@ async function connectXAccountNow(): Promise<XSessionActionResult> { "path where Google's sign-in refuses.", }; } - return { ok: true, status, source: await sourceNow(), browser }; + return { ok: true, status, source: await sourceNow(), browser, display }; } catch (e) { return { ok: false, error: (e as Error).message }; }