commit 1675f1124a0430b3217b8dd014d49aa0568127b0
parent 92b66140fd38dc3230d54ee62130c720d4ee7af4
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 17 Nov 2026 22:49:50 -0500
x-trending review 2 (N1, N3): a browser that opens late is closed; bounded never orphans a rejection
N1: the launch promise is kept. When the deadline or a cancel wins the race while
Chromium (or the headed display) is still launching, the browser that opens
afterwards is closed (killed if closing hangs) instead of holding the profile until
a restart; a read already cancelled on entry asks for no browser.
N3: bounded attaches its handlers to the call before the aborted check, so a call
still in flight when the signal was already aborted does not reject unhandled.
Both tests were seen failing first (the second as an unhandledRejection).
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
2 files changed, 108 insertions(+), 4 deletions(-)
diff --git a/common/social/xTrendingRead.test.ts b/common/social/xTrendingRead.test.ts
@@ -9,7 +9,7 @@ import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fakeTrendingPage, type FakeTrendingPage } from "./fakeXProfileBrowser";
-import { isXLoginHref, openXTrendingPage, readXTrendingPage, type TrendingPageRead } from "./xTrendingRead";
+import { bounded, isXLoginHref, openXTrendingPage, readXTrendingPage, type TrendingPageRead } from "./xTrendingRead";
import { readCaptureLines } from "./xTrendingParse";
import {
FIXTURE_TIMELINE_OP,
@@ -411,3 +411,89 @@ test("a context whose first page cannot be made is closed, not left holding the
assert.equal(closed, 1, headed ? "headed" : "headless");
}
});
+
+// --- review 2 ---------------------------------------------------------------
+
+test("N1: a browser that opens after the deadline, or after a cancel, is closed; an aborted read opens none", async () => {
+ // The launch resolves 80 ms in; the read gave it 30.
+ let closed = 0;
+ let opened = 0;
+ const slow = () =>
+ new Promise<{ page: PageLike; close: () => Promise<void> }>((resolve) =>
+ setTimeout(() => {
+ opened++;
+ resolve({ page: fakeTrendingPage(() => ({})), close: async () => void closed++ });
+ }, 80),
+ );
+ const late = await readXTrendingPage({
+ url: FIXTURE_TREND_URL,
+ dir: path.join(TMP, `read-${++dirs}`),
+ openPage: slow,
+ limits: { scrolls: 8, posts: 60 },
+ pauseMs: () => 0,
+ pause: async () => {},
+ signal: new AbortController().signal,
+ timeouts: { load: 30 },
+ });
+ assert.equal(late.stop, "deadline");
+ assert.match(late.error ?? "", /opening the browser/);
+ assert.equal(closed, 0, "not open yet when the read returned");
+ await new Promise((r) => setTimeout(r, 120));
+ assert.equal(opened, 1);
+ assert.equal(closed, 1, "the browser that opened late was closed");
+
+ // Cancelled while it launches.
+ const ac = new AbortController();
+ setTimeout(() => ac.abort(), 20);
+ const cancelled = await readXTrendingPage({
+ url: FIXTURE_TREND_URL,
+ dir: path.join(TMP, `read-${++dirs}`),
+ openPage: slow,
+ limits: { scrolls: 8, posts: 60 },
+ pauseMs: () => 0,
+ pause: async () => {},
+ signal: ac.signal,
+ });
+ assert.equal(cancelled.stop, "cancelled");
+ await new Promise((r) => setTimeout(r, 120));
+ assert.equal(opened, 2);
+ assert.equal(closed, 2);
+
+ // Already cancelled on entry: no browser is asked for at all.
+ const gone = new AbortController();
+ gone.abort();
+ let asked = 0;
+ const never = await readXTrendingPage({
+ url: FIXTURE_TREND_URL,
+ dir: path.join(TMP, `read-${++dirs}`),
+ openPage: async () => {
+ asked++;
+ return { page: fakeTrendingPage(() => ({})), close: async () => {} };
+ },
+ limits: { scrolls: 8, posts: 60 },
+ pauseMs: () => 0,
+ pause: async () => {},
+ signal: gone.signal,
+ });
+ assert.equal(never.stop, "cancelled");
+ assert.equal(asked, 0);
+});
+
+test("N3: a call bounded on a signal already aborted leaves no unhandled rejection behind", async () => {
+ const unhandled: unknown[] = [];
+ const onUnhandled = (e: unknown) => void unhandled.push(e);
+ process.on("unhandledRejection", onUnhandled);
+ try {
+ const ac = new AbortController();
+ ac.abort();
+ let reject!: (e: Error) => void;
+ const orphan = new Promise<string>((_, r) => (reject = r));
+ await assert.rejects(bounded("reading its address", orphan, 1_000, ac.signal), /cancelled/);
+ // The context closes later and the orphaned call rejects.
+ reject(new Error("Target closed"));
+ await new Promise((r) => setTimeout(r, 30));
+ assert.deepEqual(unhandled, []);
+ } finally {
+ process.off("unhandledRejection", onUnhandled);
+ }
+});
diff --git a/common/social/xTrendingRead.ts b/common/social/xTrendingRead.ts
@@ -127,12 +127,15 @@ export function bounded<T>(what: string, p: Promise<T>, ms: number, signal?: Abo
};
const onAbort = () => finish(() => reject(new Error("cancelled")));
const timer = setTimeout(() => finish(() => reject(new PageDeadlineError(what, ms))), ms);
- if (signal?.aborted) return onAbort();
- signal?.addEventListener("abort", onAbort);
+ // The handlers go on `p` FIRST (review 2 N3): were the aborted check to
+ // return before them, a call still in flight would reject with nobody
+ // listening when the context closes under it.
p.then(
(v) => finish(() => resolve(v)),
(e) => finish(() => reject(e)),
);
+ if (signal?.aborted) return onAbort();
+ signal?.addEventListener("abort", onAbort);
});
}
@@ -299,8 +302,15 @@ export async function readXTrendingPage(o: {
unauthorized ? "login-wall" : rateLimited ? "rate-limit" : forbidden ? "forbidden" : null;
let session: TrendingPageSession | undefined;
+ // The launch itself, kept (review 2 N1): when the deadline or a cancel wins
+ // the race below, the browser may still open afterwards, holding the
+ // profile — it is closed the moment it does.
+ let opening: Promise<TrendingPageSession> | undefined;
try {
- session = await bounded("opening the browser", o.openPage(), t.load, signal);
+ // A read cancelled before it began asks for no browser at all.
+ if (signal.aborted) throw new Error("cancelled");
+ opening = o.openPage();
+ session = await bounded("opening the browser", opening, t.load, signal);
const { page } = session;
page.on("response", onResponse as (arg: never) => void);
await bounded("loading the page", page.goto(o.url, { waitUntil: "domcontentloaded", timeout: 60_000 }), t.load, signal);
@@ -359,6 +369,14 @@ export async function readXTrendingPage(o: {
await writes;
// The browser is closed whatever happened; one that does not answer is
// killed, so the profile is never left held by a dead page.
+ if (!session && opening) {
+ void opening
+ .then(async (s) => {
+ log("The browser opened after the read had ended: closing it.");
+ await bounded("closing the browser", s.close(), t.close).catch(() => (s.kill ? s.kill() : undefined));
+ })
+ .catch(() => {});
+ }
if (session) {
const s = session;
await bounded("closing the browser", s.close(), t.close).catch(async (err) => {