Archilyzer · Source

archilyzer

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

commit a1ca78d0742e3a62ff6f0d7cfaf6ed9a7e02d6f2
parent 9f5cdbd16573bc534cfafcf37655c9d162ccded7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 17 Nov 2026 15:47:40 -0500

Merge lane/headed-display: a headed Connect finds the desktop even when the editor started before it -- the three Connects that open a browser window (X account, forum session, archive.today session) look the display up again at each press: the editor's own environment, else the user session's (systemctl --user show-environment, no shell, 2 s), else this user's own display sockets on disk; the display is passed to that launch only and never written into the editor's environment; with no display the Connect refuses before launching and before making a profile ("no desktop session was found there: log in to that machine's desktop, then press Connect again"), and a display that was found but cannot be opened says so and points at the editor log; the result names the display's number, never a host or the X authority path

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

Diffstat:
MENVIRONMENT.md | 5++++-
MOPERATING.md | 9+++++++++
Mcommon/lib/archives/archiveTodaySession.ts | 40++++++++++++++++++++++++++++------------
Mcommon/lib/envVars.ts | 5++++-
Mcommon/social/fakeXProfileBrowser.ts | 2++
Mcommon/social/forumSession.ts | 42++++++++++++++++++++++++++----------------
Acommon/social/headedDisplay.test.ts | 486+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/social/headedDisplay.ts | 375+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/social/playwrightRuntime.ts | 4++++
Mcommon/social/xSessionBroker.ts | 37+++++++++++++++++--------------------
Meditor/CHANGELOG.md | 11+++++++++++
Meditor/app/settings/xSessionActions.ts | 11+++++++----
12 files changed, 973 insertions(+), 54 deletions(-)

diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -182,7 +182,10 @@ The publish pipeline sets these for a process it spawns. Listed so a reader know |---|---|---|---| | `SITE_ID` | — | Which site a compose or an export build is for. The build stage (`archilyzer publish build <id>`) sets it for its children; `compose site`, `build site` and `deploy site` fall back to it when no id is given. | common/bin/compose-site.ts, export/app/lib/site.ts | | `INSTANCE_MODE` | a site | `hub` makes the export build the hub. Set by `archilyzer build hub`. | export/app/lib/mode.ts, common/lib/archive/contract.ts | -| `DISPLAY` | set by `xvfb-run` | record-live's browser fallback (path B) opens the page HEADED when a display is set — the caller runs it under `xvfb-run -a`, because Rumble's Cloudflare refuses a headless Chromium — and headless otherwise. | common/ytdlp/liveSniff.mjs | +| `DISPLAY` | set by `xvfb-run`; for a Connect window, the desktop's | record-live's browser fallback (path B) opens the page HEADED when a display is set — the caller runs it under `xvfb-run -a`, because Rumble's Cloudflare refuses a headless Chromium — and headless otherwise. A Connect window (X, archive.today, a forum) opens on the process's own `DISPLAY` / `WAYLAND_DISPLAY` / `XAUTHORITY` when set, else the user session's (`systemctl --user show-environment`), else a display socket on disk (`/tmp/.X11-unix/X<n>`, `$XDG_RUNTIME_DIR/wayland-<n>`), looked for at each press and handed to that browser only; none found, the press is refused with a sentence. | common/ytdlp/liveSniff.mjs, common/social/headedDisplay.ts | +| `WAYLAND_DISPLAY` | the desktop's, when the process has one | The Wayland display a Connect window opens on, beside `DISPLAY`: the process's own, else the user session's, else the lowest `$XDG_RUNTIME_DIR/wayland-<n>` socket. Handed to that browser only, never set in the process. | common/social/headedDisplay.ts | +| `XAUTHORITY` | the desktop's, when the process has one | The X cookie file a Connect window's browser is handed with `DISPLAY` when the process or the user session names one. Its path is never logged (the log says "XAUTHORITY set"). | common/social/headedDisplay.ts | +| `XDG_RUNTIME_DIR` | `/run/user/<uid>` | Where a Connect window's display search looks for a `wayland-<n>` socket when neither the process nor the user session names a display. | common/social/headedDisplay.ts | | `BUILD_ARCHIVES` | on | `0` skips archive-zip generation for one build (`--skip-archives`). | common/bin/compose-site.ts, common/bin/build-archives.ts | | `REPORTS_ALLOW_MISSING_MEDIA` | off | `1` lets a report citation whose evidence media was not prepared through compose (`--allow-missing-media`): its moment page renders without a clip. Off, compose fails with the list. | common/bin/compose-site.ts | | `ARCHIVES_READONLY` | off | `1` inside a docker-mode build container: materialize archives, never write the shared cache. | common/bin/compose-site.ts | diff --git a/OPERATING.md b/OPERATING.md @@ -177,6 +177,15 @@ pnpm ops get cookies fresh # the same, the browser's cookie store read again **Refresh cookies**. Rumble, YouTube and Odysee: open the site in the browser the row names, then **Check again** (one request, as `recheck-service`). archive.today and each forum host: **Connect**, which opens a window on the editor's machine, not on the phone you pressed it from. +- A Connect window (X, archive.today, a forum) opens on the editor's machine's desktop. That desktop is found at each + press: the editor's own DISPLAY / WAYLAND_DISPLAY, else the user session's (`systemctl --user show-environment`), + else the display sockets on disk. So an editor service started at boot, before anyone logged in, still finds the + desktop that came later, with no restart. The log line `Opening the window on DISPLAY=:0 … (from the user session)` + names the display used and where it came from. Only displays owned by the editor's own user count; a greeter's + or another user's do not. No desktop session at all: the press is refused with a sentence before any browser + starts. Log in to that machine's desktop, then press Connect again. A display that was found but that the browser + cannot open gets a second sentence, "A display was found (…), but the browser could not open a window on it: see + the editor log." A stale display left over after a logout ends there too. - A second press while one runs is refused with a sentence, from any tab and from the dashboard's or /settings' buttons too. The row's "last result" is the last press's answer (`actions` in `transcripts/.service-cookies.json`). diff --git a/common/lib/archives/archiveTodaySession.ts b/common/lib/archives/archiveTodaySession.ts @@ -14,12 +14,13 @@ // transcripts/.archive-session/archive.today/session.json (the last Connect). import path from "node:path"; -import { mkdir, stat } from "node:fs/promises"; +import { stat } from "node:fs/promises"; 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,23 +140,34 @@ 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(); const profileDir = archiveProfileDir(paths); - await mkdir(profileDir, { recursive: true }); + // The profile directory is made by launchHeadedContext, once a display is found. 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/lib/envVars.ts b/common/lib/envVars.ts @@ -189,7 +189,10 @@ const DECLARED: EnvVarDecl[] = [ // ── internal: the pipeline sets these for a process it spawns ────────── { name: "SITE_ID", audience: "internal", default: "—", readBy: "common/bin/compose-site.ts, export/app/lib/site.ts", doc: "Which site a compose or an export build is for. The build stage (`archilyzer publish build <id>`) sets it for its children; `compose site`, `build site` and `deploy site` fall back to it when no id is given." }, { name: "INSTANCE_MODE", audience: "internal", default: "a site", readBy: "export/app/lib/mode.ts, common/lib/archive/contract.ts", doc: "`hub` makes the export build the hub. Set by `archilyzer build hub`." }, - { name: "DISPLAY", audience: "internal", default: "set by `xvfb-run`", readBy: "common/ytdlp/liveSniff.mjs", doc: "record-live's browser fallback (path B) opens the page HEADED when a display is set — the caller runs it under `xvfb-run -a`, because Rumble's Cloudflare refuses a headless Chromium — and headless otherwise." }, + { name: "DISPLAY", audience: "internal", default: "set by `xvfb-run`; for a Connect window, the desktop's", readBy: "common/ytdlp/liveSniff.mjs, common/social/headedDisplay.ts", doc: "record-live's browser fallback (path B) opens the page HEADED when a display is set — the caller runs it under `xvfb-run -a`, because Rumble's Cloudflare refuses a headless Chromium — and headless otherwise. A Connect window (X, archive.today, a forum) opens on the process's own `DISPLAY` / `WAYLAND_DISPLAY` / `XAUTHORITY` when set, else the user session's (`systemctl --user show-environment`), else a display socket on disk (`/tmp/.X11-unix/X<n>`, `$XDG_RUNTIME_DIR/wayland-<n>`), looked for at each press and handed to that browser only; none found, the press is refused with a sentence." }, + { name: "WAYLAND_DISPLAY", audience: "internal", default: "the desktop's, when the process has one", readBy: "common/social/headedDisplay.ts", doc: "The Wayland display a Connect window opens on, beside `DISPLAY`: the process's own, else the user session's, else the lowest `$XDG_RUNTIME_DIR/wayland-<n>` socket. Handed to that browser only, never set in the process." }, + { name: "XAUTHORITY", audience: "internal", default: "the desktop's, when the process has one", readBy: "common/social/headedDisplay.ts", doc: "The X cookie file a Connect window's browser is handed with `DISPLAY` when the process or the user session names one. Its path is never logged (the log says \"XAUTHORITY set\")." }, + { name: "XDG_RUNTIME_DIR", audience: "internal", default: "`/run/user/<uid>`", readBy: "common/social/headedDisplay.ts", doc: "Where a Connect window's display search looks for a `wayland-<n>` socket when neither the process nor the user session names a display." }, { name: "BUILD_ARCHIVES", audience: "internal", default: "on", readBy: "common/bin/compose-site.ts, common/bin/build-archives.ts", doc: "`0` skips archive-zip generation for one build (`--skip-archives`)." }, { name: "REPORTS_ALLOW_MISSING_MEDIA", audience: "internal", default: "off", readBy: "common/bin/compose-site.ts", doc: "`1` lets a report citation whose evidence media was not prepared through compose (`--allow-missing-media`): its moment page renders without a clip. Off, compose fails with the list." }, { name: "ARCHIVES_READONLY", audience: "internal", default: "off", readBy: "common/bin/compose-site.ts", doc: "`1` inside a docker-mode build container: materialize archives, never write the shared cache." }, 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,30 +331,35 @@ 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(); const profileDir = forumProfileDir(paths, host); - await mkdir(profileDir, { recursive: true }); + // The profile directory is made by launchHeadedContext, once a display is found. 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,486 @@ +// 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<string, { sockets?: string[]; foreign?: string[]; files?: string[] }>): 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<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("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<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")); +}); + +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<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, 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<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); + // 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<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); + assert.equal(existsSync(path.join(TMP, "archive2", ".archive-session")), false); +}); diff --git a/common/social/headedDisplay.ts b/common/social/headedDisplay.ts @@ -0,0 +1,375 @@ +// 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 (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<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. 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<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 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<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 ?? 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<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[] = []; + // 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<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"; + } +} + +// 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<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 = "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 }; +} 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 @@ -25,7 +25,7 @@ // (`social.x.cookieSource`, xCookieSource.ts / xBrowserLogin.ts). import path from "node:path"; -import { mkdir, readFile, rm, stat } from "node:fs/promises"; +import { readFile, rm, stat } from "node:fs/promises"; import { execa } from "execa"; import { writeFileAtomic } from "../lib/jsonFile-server"; import type { Paths } from "../lib/paths"; @@ -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,33 +188,29 @@ 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 }); + // The profile directory is made by launchHeadedContext, once a display is found. const browser = findXBrowser({ env: opts.env }); const version = await browserVersion(browser); 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/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,17 @@ # Changelog ## [Unreleased] +- **Connect X account, Connect archive session and Connect forum session open their window even when the editor + started before the desktop.** The editor runs as a user service that starts at boot, so it had no display, and every + Connect failed with "launched a headed browser without having a XServer running" until a restart. Each press now looks + for the desktop's display: the editor's own environment, then the user session's (`systemctl --user + show-environment`), then the display sockets on disk. The log says which display it used and where it found it, and + so does X's result. With no desktop session, the press is refused before any browser starts: "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." Only displays owned by the editor's own user count, so a login screen's or another user's display is never + picked. A display that was found but that the browser cannot open gets its own sentence: "A display was found (…), + but the browser could not open a window on it: see the editor log." A stale display left over after a logout ends + there too. The raw error goes to the log, and the profile is not created until a display is found. - **/cookies now has every cookie and session control /settings has, and logging in to X is one press away.** Each row still starts with its status and its one button, and the whole session block now sits under it: - X: login source, Check, the cookie-age limit, Connect X account, Refresh cookies, Forget session and where X posts 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 }; }