commit 857cf80f38419c35fbfd34c4ddee99301427dedc
parent aa92ad40a02f8c3e4ac3646f8eef15e87cc69fbc
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 17 Nov 2026 15:20:14 -0500
headed Connects review 1 (1-5): owned sockets only, a second sentence, no early profile
1. A display socket counts only when this user owns it (DisplayFs.ownedByMe,
statSync(file).uid === process.getuid()), X and Wayland both: a
greeter's root-owned :0, a bare Xvfb or another user's server is never
chosen. Only foreign sockets: no display, the refusal.
2. A display resolved but a launch that still hits the XServer banner (the
sandboxed launch or the no-sandbox retry) gets its own sentence, "A
display was found (<description>), but the browser could not open a
window on it: see the editor log." The first sentence stays for nothing
resolved.
3. The profile directory is made by launchHeadedContext after the display
is found: a refused Connect leaves no profile and no session.json.
4. Tests of the real runner against process.execPath -e (non-zero exit, a
missing command, a hang killed) and of headedLaunchEnv's default base.
5. describeHeadedDisplay prints only DISPLAY's :N[.S] part (the record and
the message too); the launch env keeps the whole value.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
5 files changed, 168 insertions(+), 32 deletions(-)
diff --git a/common/lib/archives/archiveTodaySession.ts b/common/lib/archives/archiveTodaySession.ts
@@ -14,7 +14,7 @@
// 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";
@@ -153,7 +153,7 @@ export async function connectArchiveSession(
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 = o.chromium ?? (await importPlaywright()).chromium;
diff --git a/common/social/forumSession.ts b/common/social/forumSession.ts
@@ -344,7 +344,7 @@ export async function connectForumSession(
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);
diff --git a/common/social/headedDisplay.test.ts b/common/social/headedDisplay.test.ts
@@ -6,7 +6,7 @@
import { test, after } from "node:test";
import assert from "node:assert/strict";
-import { mkdtempSync } from "node:fs";
+import { existsSync, mkdtempSync } from "node:fs";
import { rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
@@ -15,6 +15,9 @@ import type { BrowserContextLike, ChromiumLike, PageLike } from "./playwrightRun
import {
NO_DESKTOP_SENTENCE,
NoDesktopError,
+ DisplayRefusedError,
+ displayRefusedSentence,
+ runCommand,
X11_SOCKET_DIR,
describeHeadedDisplay,
headedLaunchEnv,
@@ -51,14 +54,26 @@ function runner(answer: { stdout?: string; exitCode?: number } | Error | "hang")
}
// A file system holding the named sockets (and plain files that are not).
-function fakeFs(dirs: Record<string, { sockets?: string[]; files?: string[] }>): DisplayFs {
+// `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.files ?? [])];
+ 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)));
},
- isSocket: (file) => Boolean(dirs[path.dirname(file)]?.sockets?.includes(path.basename(file))),
};
}
@@ -185,10 +200,41 @@ test("no XDG_RUNTIME_DIR: the runtime dir is found from the uid", async () => {
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 on disk/);
+ 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 () => {
@@ -212,6 +258,38 @@ test("the description names the display and its source, never XAUTHORITY's path"
);
});
+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" });
@@ -307,19 +385,39 @@ test("no display: refused before anything launches, in one sentence", async () =
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 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 as Error).message === NO_DESKTOP_SENTENCE,
+ (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 });
@@ -349,10 +447,11 @@ test("Connect X account: the window gets the display, and the result says which"
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 () => {
+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 () => {
@@ -367,6 +466,8 @@ test("Connect forum session: the window gets the display, and the record says wh
{ 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 () => {
@@ -381,4 +482,5 @@ test("Connect archive session: the window gets the display, and the record says
{ 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
@@ -21,9 +21,11 @@
// $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).
+// 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.
@@ -34,6 +36,7 @@
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";
@@ -63,10 +66,14 @@ export type RunCommand = (
opts: { timeoutMs: number },
) => Promise<{ stdout: string; exitCode: number }>;
-// The slice of the file system the socket search reads.
+// 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 = {
@@ -81,7 +88,8 @@ export type HeadedDisplayDeps = {
export const USER_SESSION_TIMEOUT_MS = 2_000;
export const X11_SOCKET_DIR = "/tmp/.X11-unix";
-const defaultRun: RunCommand = (file, args, opts) =>
+// The real runner (exported for its own test).
+export const runCommand: RunCommand = (file, args, opts) =>
new Promise((resolve, reject) => {
execFile(
file,
@@ -106,6 +114,14 @@ const defaultFs: DisplayFs = {
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
@@ -163,17 +179,15 @@ function fromSockets(fs: DisplayFs, env: Env, uid: number | undefined): HeadedDi
return [];
}
};
- const x = lowestNumbered(
- list(X11_SOCKET_DIR).filter((n) => fs.isSocket(path.join(X11_SOCKET_DIR, n))),
- /^X(\d{1,4})$/,
- );
+ 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((n) => fs.isSocket(path.join(runtime, n))),
- /^wayland-(\d{1,4})$/,
- );
+ const w = lowestNumbered(list(runtime).filter(mine(runtime)), /^wayland-(\d{1,4})$/);
if (w) out.WAYLAND_DISPLAY = w.name;
}
return out;
@@ -192,7 +206,7 @@ export async function resolveHeadedDisplay(deps: HeadedDisplayDeps = {}): Promis
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 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);
@@ -209,7 +223,7 @@ export async function resolveHeadedDisplay(deps: HeadedDisplayDeps = {}): Promis
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");
+ notes.push("no display socket of this user's on disk");
return { display: null, notes };
}
@@ -241,7 +255,9 @@ function shortReason(err: unknown): string {
// 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}`);
+ // 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}`);
}
@@ -270,6 +286,21 @@ export class NoDesktopError extends Error {
}
}
+// 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 {
@@ -320,8 +351,11 @@ export async function launchHeadedContext(o: {
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();
+ 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));
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";
@@ -194,7 +194,7 @@ export async function connectXAccount(
): 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);