gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit9b3c25599b3c2559tmdb fix: revalidate planned identities and reserve target idsmre9b3c2559/tests/cdp.mjs

32.1 KB

  1. // tests/browser/cdp.mjs — a tiny raw-CDP browser driver. ZERO npm dependencies:
  2. // node's native WebSocket speaks the Chrome DevTools Protocol directly, so the
  3. // real-browser tier needs nothing installed beyond `google-chrome` itself.
  4. //
  5. // Two connection modes (mission 073 gate 1):
  6. // • default — launch a LOCAL `google-chrome --headless=new` on a free debug port.
  7. // This is what the suites use: hermetic, no external dependency.
  8. // • HL_CDP_URL=http://host:port — attach to an ALREADY-RUNNING Chrome instead
  9. // (e.g. the creator's notebook at http://lisbeth.tailfd3886.ts.net:9223).
  10. // Nothing is launched or killed in that mode; only the tabs we create are closed.
  11. //
  12. // Everything a browser test needs and nothing else: navigate, wait-for-selector,
  13. // evaluate, REAL mouse/keyboard dispatch (Input domain, not synthetic .click()),
  14. // full console + uncaught-exception capture, and teardown that leaves no process.
  15. import { spawn } from 'node:child_process';
  16. import { mkdtempSync, rmSync } from 'node:fs';
  17. import { tmpdir } from 'node:os';
  18. import { join } from 'node:path';
  19. import { createConnection } from 'node:net';
  20. // One definition of "is this port actually usable", shared with the fixture boot
  21. // path — the whole of mission 285 is that the tier had two different answers to
  22. // that question and neither was the one the kernel gives.
  23. import { portBindable, whoHolds } from './ports.mjs';
  24. const CHROME_CANDIDATES = ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser'];
  25. export function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
  26. async function portOpen(host, port) {
  27. return new Promise(resolve => {
  28. const sock = createConnection({ host, port });
  29. const done = (ok) => { try { sock.destroy(); } catch {} resolve(ok); };
  30. sock.setTimeout(400);
  31. sock.on('connect', () => done(true));
  32. sock.on('error', () => done(false));
  33. sock.on('timeout', () => done(false));
  34. });
  35. }
  36. /**
  37. * Wait until `http://host:port/json/version` answers, or throw.
  38. *
  39. * `giveUp` (mission 285) is asked on every turn for a reason to stop early: waiting
  40. * out a full timeout for something that has already announced it will never arrive
  41. * is how a port collision came to look like a twenty-second test failure.
  42. */
  43. async function waitForEndpoint(base, timeoutMs, label, giveUp = () => null) {
  44. const deadline = Date.now() + timeoutMs;
  45. let lastErr = 'no attempt';
  46. while (Date.now() < deadline) {
  47. const stop = giveUp();
  48. if (stop) throw new Error(stop);
  49. try {
  50. const res = await fetch(base + '/json/version', { signal: AbortSignal.timeout(2000) });
  51. if (res.ok) return await res.json();
  52. lastErr = 'HTTP ' + res.status;
  53. } catch (e) { lastErr = String(e && e.message || e); }
  54. await sleep(100);
  55. }
  56. throw new Error(`${label} not reachable at ${base} after ${timeoutMs}ms (${lastErr})`);
  57. }
  58. // --- the protocol connection ------------------------------------------------
  59. class Conn {
  60. constructor(ws) {
  61. this.ws = ws;
  62. this.nextId = 1;
  63. this.pending = new Map();
  64. this.listeners = [];
  65. ws.addEventListener('message', (ev) => {
  66. let msg;
  67. try { msg = JSON.parse(typeof ev.data === 'string' ? ev.data : String(ev.data)); } catch { return; }
  68. if (msg.id !== undefined && this.pending.has(msg.id)) {
  69. const { resolve, reject } = this.pending.get(msg.id);
  70. this.pending.delete(msg.id);
  71. if (msg.error) reject(new Error(`${msg.error.message} (CDP ${msg.error.code})`));
  72. else resolve(msg.result);
  73. return;
  74. }
  75. for (const fn of this.listeners) fn(msg);
  76. });
  77. ws.addEventListener('close', () => {
  78. for (const { reject } of this.pending.values()) reject(new Error('CDP connection closed'));
  79. this.pending.clear();
  80. });
  81. }
  82. onEvent(fn) { this.listeners.push(fn); return () => { this.listeners = this.listeners.filter(f => f !== fn); }; }
  83. send(method, params = {}, sessionId) {
  84. const id = this.nextId++;
  85. const payload = { id, method, params };
  86. if (sessionId) payload.sessionId = sessionId;
  87. return new Promise((resolve, reject) => {
  88. this.pending.set(id, { resolve, reject });
  89. const t = setTimeout(() => {
  90. if (this.pending.delete(id)) reject(new Error(`CDP timeout: ${method}`));
  91. }, 20000);
  92. const clear = () => clearTimeout(t);
  93. const orig = this.pending.get(id);
  94. this.pending.set(id, {
  95. resolve: (v) => { clear(); orig.resolve(v); },
  96. reject: (e) => { clear(); orig.reject(e); },
  97. });
  98. try { this.ws.send(JSON.stringify(payload)); } catch (e) { this.pending.delete(id); clear(); reject(e); }
  99. });
  100. }
  101. close() { try { this.ws.close(); } catch {} }
  102. }
  103. async function connectWs(url) {
  104. const ws = new WebSocket(url);
  105. await new Promise((resolve, reject) => {
  106. const to = setTimeout(() => reject(new Error('WebSocket open timeout: ' + url)), 10000);
  107. ws.addEventListener('open', () => { clearTimeout(to); resolve(); }, { once: true });
  108. ws.addEventListener('error', (e) => { clearTimeout(to); reject(new Error('WebSocket error: ' + url)); }, { once: true });
  109. });
  110. return new Conn(ws);
  111. }
  112. // --- Page -------------------------------------------------------------------
  113. /**
  114. * One tab. Owns its own console/exception log from the moment it is created,
  115. * so nothing that happens during load can be missed.
  116. */
  117. export class Page {
  118. constructor(browser, targetId, sessionId) {
  119. this.browser = browser;
  120. this.conn = browser.conn;
  121. this.targetId = targetId;
  122. this.sessionId = sessionId;
  123. /** every console message AND uncaught exception, in arrival order */
  124. this.messages = [];
  125. this.closed = false;
  126. }
  127. send(method, params) { return this.conn.send(method, params, this.sessionId); }
  128. /** console messages whose level is error/warning (what "console clean" means) */
  129. problems() { return this.messages.filter(m => m.level === 'error' || m.level === 'warning'); }
  130. /** Wait until a captured console message matches — the hydration/apply signals. */
  131. async waitForConsoleMatch(re, { timeout = 10000 } = {}) {
  132. const deadline = Date.now() + timeout;
  133. while (Date.now() < deadline) {
  134. const hit = this.messages.find(m => re.test(m.text));
  135. if (hit) return hit;
  136. await sleep(40);
  137. }
  138. throw new Error(`waitForConsoleMatch timed out (${re}). Console was:\n${this.dumpConsole()}`);
  139. }
  140. /** one-line rendering of everything captured — for failure details */
  141. dumpConsole() { return this.messages.map(m => `[${m.level}] ${m.text}`).join('\n') || '(no console output)'; }
  142. /**
  143. * Run `source` in EVERY document this tab loads, BEFORE any page script.
  144. * The only way to observe something the app sets up on load — mission 080 uses
  145. * it to wrap `EventSource` and capture the raw SSE frames, so the assertion
  146. * "this session was told nothing" is made against the wire, not the DOM.
  147. */
  148. addInitScript(source) { return this.send('Page.addScriptToEvaluateOnNewDocument', { source }); }
  149. /**
  150. * Capture every SSE frame this page receives into `window.__hlSSE`. Must be
  151. * called BEFORE goto(); the wrapper subclasses the real EventSource, so the
  152. * app's own `onmessage` is untouched and the transport is not simulated.
  153. */
  154. captureSse() {
  155. return this.addInitScript(`(() => {
  156. window.__hlSSE = [];
  157. const Native = window.EventSource;
  158. if (!Native) return;
  159. window.EventSource = class extends Native {
  160. constructor(...a) {
  161. super(...a);
  162. this.addEventListener('message', (e) => {
  163. try { window.__hlSSE.push(JSON.parse(e.data)); } catch {}
  164. });
  165. }
  166. };
  167. })()`);
  168. }
  169. /** The SSE frames captured so far (see captureSse), oldest first. */
  170. sseFrames() { return this.evaluate('window.__hlSSE || []'); }
  171. /**
  172. * Mission 090: capture every WebSocket frame this page RECEIVES (`__hlWs`) and
  173. * every one it SENDS (`__hlWsOut`). Must be called BEFORE goto(); the wrapper
  174. * subclasses the real WebSocket, so the app's own listeners are untouched and
  175. * the transport is the real one — "this session was told exactly these bytes"
  176. * is then an assertion about the wire, not about the DOM.
  177. */
  178. captureWs() {
  179. return this.addInitScript(`(() => {
  180. window.__hlWs = [];
  181. window.__hlWsOut = [];
  182. // when the LAST frame arrived, on the page's own clock — the ordering
  183. // assertion "the DOM moved because of the frame" is made against this
  184. window.__hlWsAt = 0;
  185. // ...and when the first STATE PATCH arrived. A patch is an ARRAY frame (the
  186. // protocol's onPatches); control frames — ack, pong, build — are objects,
  187. // and since mission 133 an ack lands right AFTER the patch it belongs to,
  188. // so __hlWsAt alone would put "the last frame" after the DOM had already
  189. // moved for the patch.
  190. window.__hlWsPatchAt = 0;
  191. const Native = window.WebSocket;
  192. if (!Native) return;
  193. window.WebSocket = class extends Native {
  194. constructor(...a) {
  195. super(...a);
  196. this.addEventListener('message', (e) => {
  197. window.__hlWs.push(String(e.data));
  198. window.__hlWsAt = performance.now();
  199. if (!window.__hlWsPatchAt) {
  200. try {
  201. if (Array.isArray(JSON.parse(String(e.data)))) window.__hlWsPatchAt = window.__hlWsAt;
  202. } catch {}
  203. }
  204. });
  205. }
  206. send(d) { window.__hlWsOut.push(String(d)); return super.send(d); }
  207. };
  208. })()`);
  209. }
  210. /** Frames this page RECEIVED / SENT since load (see captureWs), oldest first. */
  211. wsFrames() { return this.evaluate('window.__hlWs || []'); }
  212. wsSent() { return this.evaluate('window.__hlWsOut || []'); }
  213. resetWs() { return this.evaluate('window.__hlWs = []'); }
  214. /**
  215. * Mission 093: the cookies the BROWSER holds for `urls`, as the browser sees
  216. * them — including the httpOnly ones, which is the whole point. `document.cookie`
  217. * cannot see an httpOnly cookie, so "the session id is not reachable from page
  218. * script" and "the session id exists" can only be asserted together from here.
  219. */
  220. async cookies(urls) {
  221. await this.send('Network.enable');
  222. const { cookies } = await this.send('Network.getCookies', urls ? { urls } : {});
  223. return cookies || [];
  224. }
  225. /** Cut THIS tab off the network, or let it back on (CDP emulation). */
  226. async setOffline(offline) {
  227. await this.send('Network.enable');
  228. await this.send('Network.emulateNetworkConditions', {
  229. offline, latency: 0, downloadThroughput: -1, uploadThroughput: -1,
  230. });
  231. }
  232. /**
  233. * Mission 081: serve an APP SHELL PRECACHE from the harness — the part mission
  234. * 082's generated service worker will play (D29/§10.4: the `offline` target
  235. * precaches the shell so a revisit boots with the network down).
  236. *
  237. * 081 owns the STATE layer — "with the network down the state comes from
  238. * IndexedDB" — and that claim is only observable once a document can load at
  239. * all. `snapshot` is a url → {status, contentType, body} map the test captured
  240. * over HTTP while it was still online; those URLs are fulfilled from it, and
  241. * EVERY OTHER request (`?__data=1`, `/emit`, `/events` — all the data
  242. * endpoints) is passed on to the network, which is exactly where it dies. So
  243. * the shell is precached and the data is genuinely unreachable, which is the
  244. * situation §10.2 describes.
  245. *
  246. * Chrome's own HTTP cache cannot stand in for this: a response replayed
  247. * through `Fetch.continueResponse` is not stored in the disk cache (measured),
  248. * and `Page.reload` deliberately revalidates, so it fails offline either way.
  249. */
  250. async servePrecache(snapshot) {
  251. this._precache = snapshot;
  252. await this.send('Fetch.enable', { patterns: [{ urlPattern: '*' }] });
  253. }
  254. /** Stop answering from the precache and let every request reach the network. */
  255. async stopPrecache() {
  256. this._precache = null;
  257. await this.send('Fetch.enable', { patterns: [{ urlPattern: '*/favicon.ico' }] });
  258. }
  259. /**
  260. * Mission 087 (gate 2): capture EVERY request the page makes, from the browser
  261. * itself. `Network.requestWillBeSent` fires for navigations, subresources,
  262. * `fetch`/XHR and beacons alike, so "this interaction cost zero network
  263. * requests" is asserted against the wire and cannot be talked around.
  264. * The favicon request the browser makes on its own is excluded by URL — it is
  265. * the browser's, not the app's (the Fetch handler above already answers it).
  266. */
  267. async captureNetwork() {
  268. this.requests = [];
  269. this._netOn = true;
  270. await this.send('Network.enable');
  271. return this;
  272. }
  273. /** Every request URL captured since the last `resetNetwork()`, oldest first. */
  274. networkUrls() { return (this.requests || []).map(r => r.url); }
  275. /** The same requests as `{ url, method, headers }` — mission 090 asserts all three. */
  276. networkRequests() { return (this.requests || []).slice(); }
  277. /** Forget everything captured so far — the "since this moment" baseline. */
  278. resetNetwork() { this.requests = []; return this; }
  279. _record(level, text, extra) { this.messages.push({ level, text, ...extra }); }
  280. async _init() {
  281. this.conn.onEvent((msg) => {
  282. if (msg.sessionId !== this.sessionId) return;
  283. const p = msg.params || {};
  284. if (msg.method === 'Runtime.consoleAPICalled') {
  285. const level = p.type === 'error' ? 'error' : p.type === 'warning' || p.type === 'warn' ? 'warning' : p.type === 'debug' ? 'debug' : 'info';
  286. this._record(level, (p.args || []).map(describeArg).join(' '), { source: 'console.' + p.type });
  287. } else if (msg.method === 'Runtime.exceptionThrown') {
  288. const d = p.exceptionDetails || {};
  289. const text = (d.exception && (d.exception.description || d.exception.value)) || d.text || 'uncaught exception';
  290. this._record('error', String(text), { source: 'exception' });
  291. } else if (msg.method === 'Log.entryAdded') {
  292. const e = p.entry || {};
  293. const level = e.level === 'error' ? 'error' : e.level === 'warning' ? 'warning' : 'info';
  294. this._record(level, `${e.source}: ${e.text}${e.url ? ' @ ' + e.url : ''}`, { source: 'log.' + e.source });
  295. } else if (msg.method === 'Page.loadEventFired') {
  296. this._loaded = true;
  297. } else if (msg.method === 'Network.requestWillBeSent' && this._netOn) {
  298. const url = (p.request && p.request.url) || '';
  299. if (!/\/favicon\.ico$/.test(url)) {
  300. this.requests.push({
  301. url,
  302. method: (p.request && p.request.method) || 'GET',
  303. headers: (p.request && p.request.headers) || {},
  304. });
  305. }
  306. } else if (msg.method === 'Fetch.requestPaused' && this._precache
  307. && this._precache[(p.request && p.request.url) || '']) {
  308. // the harness precache (servePrecache) answers this one, network untouched
  309. const hit = this._precache[p.request.url];
  310. this.send('Fetch.fulfillRequest', {
  311. requestId: p.requestId, responseCode: hit.status || 200,
  312. responseHeaders: [{ name: 'Content-Type', value: hit.contentType || 'text/html; charset=utf-8' }],
  313. body: Buffer.from(hit.body, 'utf-8').toString('base64'),
  314. }).catch(() => {});
  315. } else if (msg.method === 'Fetch.requestPaused' && this._precache
  316. && !/\/favicon\.ico$/.test((p.request && p.request.url) || '')) {
  317. // not precached: let it go to the network — which is where it must fail
  318. this.send('Fetch.continueRequest', { requestId: p.requestId }).catch(() => {});
  319. } else if (msg.method === 'Fetch.requestPaused') {
  320. // The browser fetches /favicon.ico on every navigation all by itself.
  321. // A fixture server serves no favicon, so that 404 would show up as a
  322. // console error that NO page code caused. Answer it here (empty 200)
  323. // instead of filtering it out later: then "zero console errors" means
  324. // exactly what it says — nothing is excused after the fact.
  325. this.send('Fetch.fulfillRequest', {
  326. requestId: p.requestId, responseCode: 200,
  327. responseHeaders: [{ name: 'Content-Type', value: 'image/x-icon' }], body: '',
  328. }).catch(() => {});
  329. }
  330. });
  331. await this.send('Runtime.enable');
  332. await this.send('Log.enable');
  333. await this.send('Page.enable');
  334. if (process.env.H2_THROTTLE) await this.send('Emulation.setCPUThrottlingRate', { rate: Number(process.env.H2_THROTTLE) });
  335. await this.send('DOM.enable');
  336. await this.send('Fetch.enable', { patterns: [{ urlPattern: '*/favicon.ico' }] });
  337. }
  338. /** Navigate and wait for the load event (plus a settled DOM). */
  339. async goto(url, { timeout = 15000 } = {}) {
  340. this._loaded = false;
  341. await this.send('Page.navigate', { url });
  342. const deadline = Date.now() + timeout;
  343. while (!this._loaded && Date.now() < deadline) await sleep(25);
  344. if (!this._loaded) throw new Error(`navigate: load event never fired for ${url}`);
  345. return this;
  346. }
  347. /** Evaluate an expression (or a function body via a plain string) in the page. */
  348. async evaluate(expression, { awaitPromise = true } = {}) {
  349. const src = typeof expression === 'function' ? `(${expression.toString()})()` : expression;
  350. const res = await this.send('Runtime.evaluate', {
  351. expression: src, returnByValue: true, awaitPromise, userGesture: true,
  352. });
  353. if (res.exceptionDetails) {
  354. const d = res.exceptionDetails;
  355. const text = (d.exception && (d.exception.description || d.exception.value)) || d.text;
  356. throw new Error('evaluate threw: ' + text);
  357. }
  358. return res.result && res.result.value;
  359. }
  360. /** Poll a JS expression until it is truthy. Returns its value. */
  361. async waitFor(expression, { timeout = 10000, interval = 50, label } = {}) {
  362. const deadline = Date.now() + timeout;
  363. let last;
  364. while (Date.now() < deadline) {
  365. try { last = await this.evaluate(expression); } catch (e) { last = undefined; }
  366. if (last) return last;
  367. await sleep(interval);
  368. }
  369. throw new Error(`waitFor timed out after ${timeout}ms: ${label || String(expression).slice(0, 120)}`);
  370. }
  371. waitForSelector(selector, opts = {}) {
  372. return this.waitFor(`!!document.querySelector(${JSON.stringify(selector)})`, { ...opts, label: `selector ${selector}` });
  373. }
  374. text(selector) {
  375. return this.evaluate(`(document.querySelector(${JSON.stringify(selector)}) || {}).textContent`);
  376. }
  377. html(selector = 'body') {
  378. return this.evaluate(`(document.querySelector(${JSON.stringify(selector)}) || {}).innerHTML`);
  379. }
  380. /** Element centre in viewport coordinates, or null when it isn't laid out. */
  381. async box(selector) {
  382. return this.evaluate(`(() => {
  383. const el = document.querySelector(${JSON.stringify(selector)});
  384. if (!el) return null;
  385. // a real click lands at viewport coordinates: an element below the fold is
  386. // scrolled into view first, as a user would have to (2026-09-12: a grown
  387. // list pushed a heading off-screen and the press hit nothing)
  388. el.scrollIntoView({ block: 'center', inline: 'nearest' });
  389. const r = el.getBoundingClientRect();
  390. if (r.width === 0 && r.height === 0) return null;
  391. return { x: r.left + r.width / 2, y: r.top + r.height / 2, w: r.width, h: r.height };
  392. })()`);
  393. }
  394. /**
  395. * A REAL click: an Input-domain mouse press/release at the element's centre.
  396. * Not `el.click()` — this goes through Chrome's real hit-testing and event path,
  397. * so an overlay, a zero-size element or a detached node makes it fail here.
  398. */
  399. async click(selector, { timeout = 10000 } = {}) {
  400. await this.waitForSelector(selector, { timeout });
  401. const box = await this.box(selector);
  402. if (!box) throw new Error(`click: ${selector} has no layout box (not visible)`);
  403. const base = { x: Math.round(box.x), y: Math.round(box.y), button: 'left', clickCount: 1, buttons: 1 };
  404. await this.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...base, buttons: 0 });
  405. await this.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...base });
  406. await this.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...base, buttons: 0 });
  407. return this;
  408. }
  409. /**
  410. * A REAL DRAG (mission 127): press over `fromSel`, walk the pointer to
  411. * `toSel` in `steps` intermediate moves, then release — all through the Input
  412. * domain, so Chrome does its own hit-testing and produces the genuine
  413. * pointerdown / pointermove / pointerenter / pointerup sequence. Nothing here
  414. * is synthesised in page script.
  415. *
  416. * `hold` is awaited while the button is DOWN over the destination, which is the
  417. * only moment a mid-drag assertion (a "dragging: X" label) can be made.
  418. * The destination box is measured AFTER the press, because a drag may already
  419. * have moved the layout by then.
  420. */
  421. async drag(fromSel, toSel, { steps = 8, hold = null, onStep = null, timeout = 10000 } = {}) {
  422. await this.waitForSelector(fromSel, { timeout });
  423. await this.waitForSelector(toSel, { timeout });
  424. const from = await this.box(fromSel);
  425. if (!from) throw new Error(`drag: ${fromSel} has no layout box (not visible)`);
  426. const at = (x, y, extra) => this.send('Input.dispatchMouseEvent', {
  427. x: Math.round(x), y: Math.round(y), button: 'left', clickCount: 1, ...extra,
  428. });
  429. await at(from.x, from.y, { type: 'mouseMoved', buttons: 0 });
  430. await at(from.x, from.y, { type: 'mousePressed', buttons: 1 });
  431. const to = await this.box(toSel);
  432. if (!to) throw new Error(`drag: ${toSel} has no layout box (not visible)`);
  433. for (let i = 1; i <= steps; i++) {
  434. const t = i / steps;
  435. const x = from.x + (to.x - from.x) * t;
  436. const y = from.y + (to.y - from.y) * t;
  437. await at(x, y, { type: 'mouseMoved', buttons: 1 });
  438. // MID-DRAG SAMPLING (mission 134): the only place from which "the row
  439. // follows the pointer" can be measured is BETWEEN two moves, while the
  440. // button is still down — `hold` runs once, at the end, and so can never
  441. // show that the row tracked anything.
  442. if (onStep) await onStep(i, x, y);
  443. }
  444. if (hold) await hold();
  445. await at(to.x, to.y, { type: 'mouseReleased', buttons: 0 });
  446. return this;
  447. }
  448. /** Focus an element (real DOM focus, so keystrokes land in it). */
  449. async focus(selector) {
  450. await this.waitForSelector(selector);
  451. const ok = await this.evaluate(`(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return false; el.focus(); return document.activeElement === el; })()`);
  452. if (!ok) throw new Error(`focus: ${selector} did not take focus`);
  453. return this;
  454. }
  455. /**
  456. * REAL typing: per-character rawKeyDown/char/keyUp through the Input domain.
  457. * The page sees genuine keydown/keypress/input/keyup — an `onInput` binding that
  458. * only listens for synthetic events would fail here.
  459. */
  460. async type(selector, textToType, { clear = false } = {}) {
  461. await this.focus(selector);
  462. if (clear) {
  463. await this.evaluate(`(() => { const el = document.querySelector(${JSON.stringify(selector)}); el.value = ''; el.dispatchEvent(new Event('input', { bubbles: true })); })()`);
  464. }
  465. for (const ch of textToType) {
  466. await this.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });
  467. await this.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
  468. }
  469. return this;
  470. }
  471. async close() {
  472. if (this.closed) return;
  473. this.closed = true;
  474. try { await this.conn.send('Target.closeTarget', { targetId: this.targetId }); } catch {}
  475. }
  476. }
  477. function describeArg(a) {
  478. if (!a) return '';
  479. if ('value' in a) return typeof a.value === 'object' ? JSON.stringify(a.value) : String(a.value);
  480. if (a.description) return a.description;
  481. if (a.unserializableValue) return a.unserializableValue;
  482. return a.type || '';
  483. }
  484. // --- Browser ----------------------------------------------------------------
  485. export class Browser {
  486. constructor(conn, { proc = null, userDataDir = null, endpoint }) {
  487. this.conn = conn;
  488. this.proc = proc;
  489. this.userDataDir = userDataDir;
  490. this.endpoint = endpoint;
  491. this.pages = [];
  492. }
  493. /** Whether this driver launched the browser (and therefore must kill it). */
  494. get owned() { return this.proc !== null; }
  495. async newPage() {
  496. const { targetId } = await this.conn.send('Target.createTarget', { url: 'about:blank' });
  497. const { sessionId } = await this.conn.send('Target.attachToTarget', { targetId, flatten: true });
  498. const page = new Page(this, targetId, sessionId);
  499. await page._init();
  500. this.pages.push(page);
  501. return page;
  502. }
  503. /**
  504. * Teardown. Closes every tab we opened; when WE launched the browser it is also
  505. * killed by PID and waited for, and its profile dir removed. Resolves only once
  506. * the process is actually gone — the run script asserts on that.
  507. */
  508. async close() {
  509. for (const p of this.pages) { try { await p.close(); } catch {} }
  510. this.pages = [];
  511. if (!this.owned) { this.conn.close(); return; }
  512. try { await this.conn.send('Browser.close'); } catch {}
  513. this.conn.close();
  514. const pid = this.proc.pid;
  515. const gone = await waitForExit(this.proc, 5000);
  516. if (!gone) {
  517. try { process.kill(pid, 'SIGKILL'); } catch {}
  518. await waitForExit(this.proc, 3000);
  519. }
  520. if (this.userDataDir) { try { rmSync(this.userDataDir, { recursive: true, force: true }); } catch {} }
  521. const rec = launchedBrowsers.find(r => r.browser === this);
  522. if (rec) rec.closed = true;
  523. }
  524. }
  525. function waitForExit(proc, timeoutMs) {
  526. if (proc.exitCode !== null || proc.signalCode !== null) return Promise.resolve(true);
  527. return new Promise(resolve => {
  528. const t = setTimeout(() => resolve(false), timeoutMs);
  529. proc.once('exit', () => { clearTimeout(t); resolve(true); });
  530. });
  531. }
  532. /**
  533. * MISSION 285 — A PORT IS FREE WHEN IT CAN BE BOUND, NOT WHEN NOTHING ANSWERS.
  534. *
  535. * This used to ask `portOpen('127.0.0.1', p)`: connect, and if it is refused call
  536. * the port free. Chrome then binds it — and when that bind loses, Chrome does NOT
  537. * fail. It falls back to IPv6 and says so on stderr, which nothing read:
  538. *
  539. * ERROR:net/socket/socket_posix.cc:175] bind() failed: Address already in use (98)
  540. * DevTools listening on ws://[::1]:53502/devtools/browser/06fcaa25-…
  541. *
  542. * `waitForEndpoint` only ever polls `http://127.0.0.1:PORT`, so it then spent its
  543. * whole 20 000 ms waiting for an endpoint that was up the entire time at a place it
  544. * never looked, and the test that happened to be launching a peer browser took the
  545. * blame. Measured twice in one tier run (25-sessions and 27-login, both 20 4xx ms,
  546. * both on :53502) and reproduced on demand by putting one listener on 127.0.0.1:P
  547. * before the launch — same bind error, same ::1 fallback, IPv4 never reachable.
  548. *
  549. * So: bind-test the candidate (see `portBindable` in ports.mjs for why a bind is
  550. * the honest question), and check what Chrome actually did afterwards.
  551. */
  552. async function findFreePort(from, to) {
  553. for (let p = from; p <= to; p++) if (await portBindable(p)) return p;
  554. throw new Error(`no bindable port in ${from}-${to}`);
  555. }
  556. /** Where Chrome says it is listening — the only address that is not a guess. */
  557. function announcedEndpoint(stderr) {
  558. const m = /DevTools listening on ws:\/\/(\[[^\]]+\]|[^:/]+):(\d+)\//.exec(stderr);
  559. return m ? { host: m[1], port: Number(m[2]) } : null;
  560. }
  561. /**
  562. * Launch (or attach to) a browser.
  563. * HL_CDP_URL set → attach, never spawn, never kill.
  564. * otherwise → spawn local headless Chrome on a free port in PORT_BASE+200..+209
  565. * (8800-8809 by default; `HL_PORT_BASE` moves the block so two
  566. * worktrees can run the tier at once).
  567. * Optional HL_CHROME overrides the binary; HL_HEADFUL=1 shows the window.
  568. *
  569. * THE OFFSET HAS NOW MOVED TWICE FOR THE SAME REASON. It was +40 until the tier's
  570. * fixture ports grew past forty and the last test was handed the debug port
  571. * itself; it became +100, and on 2026-09-06 the tier's 101st fixture port was
  572. * handed 8700 — the running Chrome's debug endpoint — and that test could not
  573. * start at all ("PORT COLLISION, not a server fault: :8700 could not be bound").
  574. * +200 buys the next hundred. See run.mjs's PORT_BASE comment.
  575. */
  576. const DEBUG_PORT_BASE = (Number(process.env.HL_PORT_BASE) || 8600) + 200;
  577. /** The debug block this process may spawn into — the runner audits ALL of it. */
  578. export const DEBUG_PORT_RANGE = [DEBUG_PORT_BASE, DEBUG_PORT_BASE + 9];
  579. /**
  580. * EVERY browser this process launched, whoever asked for it.
  581. *
  582. * The teardown audit used to know only about the ONE browser run.mjs launched,
  583. * so a peer browser started inside a test (25-sessions and 45-server-face-emit
  584. * each launch a second one for a second session) could survive while the audit
  585. * reported "no orphan chrome/servers" — measured 2026-08-23 with a deliberate
  586. * leak, which the audit passed clean. `launchBrowser` is the one choke point
  587. * every browser goes through, so the registry belongs here rather than in the
  588. * runner, and it catches a leak no matter who caused it.
  589. */
  590. export const launchedBrowsers = [];
  591. export async function launchBrowser({ debugPortRange = [DEBUG_PORT_BASE, DEBUG_PORT_BASE + 9] } = {}) {
  592. const attach = process.env.HL_CDP_URL;
  593. if (attach) {
  594. const base = attach.replace(/\/$/, '');
  595. const info = await waitForEndpoint(base, 8000, 'HL_CDP_URL browser');
  596. const conn = await connectWs(info.webSocketDebuggerUrl);
  597. return new Browser(conn, { endpoint: base });
  598. }
  599. const bin = process.env.HL_CHROME || (await firstOnPath(CHROME_CANDIDATES));
  600. if (!bin) throw new Error(`no Chrome binary found (tried ${CHROME_CANDIDATES.join(', ')}); set HL_CHROME or HL_CDP_URL`);
  601. const port = await findFreePort(debugPortRange[0], debugPortRange[1]);
  602. const userDataDir = mkdtempSync(join(tmpdir(), 'hl-browser-tier-'));
  603. const args = [
  604. process.env.HL_HEADFUL ? '--headless=false' : '--headless=new',
  605. `--remote-debugging-port=${port}`,
  606. `--user-data-dir=${userDataDir}`,
  607. '--no-first-run', '--no-default-browser-check', '--disable-extensions',
  608. // WPAD proxy auto-detection stalls the FIRST http navigation for ~20s on this
  609. // machine (measured: data: URL instant, first http nav 20s, later navs instant).
  610. // Going straight-to-direct removes the stall — localhost fixtures need no proxy.
  611. '--no-proxy-server', "--proxy-server=direct://", '--proxy-bypass-list=*',
  612. '--password-store=basic', '--use-mock-keychain',
  613. '--disable-background-networking', '--disable-component-update',
  614. '--disable-default-apps', '--disable-sync', '--metrics-recording-only',
  615. '--mute-audio', '--disable-gpu', '--disable-dev-shm-usage',
  616. '--window-size=1280,900', 'about:blank',
  617. ].filter(a => a !== '--headless=false');
  618. const proc = spawn(bin, args, { stdio: ['ignore', 'ignore', 'pipe'] });
  619. const stderr = [];
  620. proc.stderr.on('data', d => { if (stderr.length < 50) stderr.push(String(d)); });
  621. const base = `http://127.0.0.1:${port}`;
  622. const die = (msg) => {
  623. try { process.kill(proc.pid, 'SIGKILL'); } catch {}
  624. rmSync(userDataDir, { recursive: true, force: true });
  625. throw new Error(msg);
  626. };
  627. let info;
  628. try {
  629. // MISSION 285 — stop the moment Chrome says it went somewhere else, instead of
  630. // polling an address it has already told us it is not on. A launch that lost the
  631. // port is a PORT COLLISION and must read as one; twenty silent seconds followed
  632. // by "not reachable" reads as a broken browser or a broken test.
  633. info = await waitForEndpoint(base, 20000, 'headless Chrome', () => {
  634. const said = announcedEndpoint(stderr.join(''));
  635. if (said && said.host !== '127.0.0.1') {
  636. return `PORT COLLISION, not a browser fault: Chrome could not bind 127.0.0.1:${port} and listened on ${said.host}:${said.port} instead, so nothing was ever going to answer at ${base}.\n sockets: ${whoHolds(port)}\n chrome said: ${stderr.join('').split('\n').filter(l => /bind\(\) failed|DevTools listening/.test(l)).join(' | ')}`;
  637. }
  638. return null;
  639. });
  640. } catch (e) {
  641. die(e.message + '\nchrome stderr:\n' + stderr.join(''));
  642. }
  643. const conn = await connectWs(info.webSocketDebuggerUrl);
  644. const browser = new Browser(conn, { proc, userDataDir, endpoint: base });
  645. launchedBrowsers.push({ pid: proc.pid, port, userDataDir, closed: false, browser });
  646. return browser;
  647. }
  648. async function firstOnPath(names) {
  649. const { execFile } = await import('node:child_process');
  650. for (const n of names) {
  651. const found = await new Promise(res => execFile('which', [n], (err, out) => res(err ? null : String(out).trim())));
  652. if (found) return found;
  653. }
  654. return null;
  655. }

Branches

Latest commits

  • 9b3c2559tmdb fix: revalidate planned identities and reserve target idsmre
  • d56ee0daT36A: report unsafe TMDB apply revalidation and stop before livemre
  • 08e55255log: HM56 done, T36A startedmre
  • 5fd2ac75status: #36 GOmre
  • 0d253b45mission: T36Amre
  • 2aa22d23log: #36 GOmre
  • 833aee2flog: #50 closed, HM56 startedmre
  • ac58c1e5mission: HM56mre
  • 58979c0clog: HM54 held for decision, DP65 startedmre
  • bb2ebc67log: #64 live, #53 mergedmre
  • 27cde42fMerge hm53-dom: tracker#53 inputs bound to membersmre
  • 2156cc7flog: HM54 reviewmre
  • 9fb82efclog: HM54 gap, fill continuesmre
  • b632eb8dlog: HM53 done, HM54 startedmre
  • ccb1a263tracker#53: bind editor drafts and use key event focus targetmre
  • 3356fcfclog: #52 blocked, HM53 startedmre
  • 833dcfc9Merge hm52-search: report only, tracker#52 blocked by framework gapmre
  • 73010cc0HM52: report replace-navigation search draft regressionmre
  • 1742e92bstatus: DP64 and HM52 runningmre
  • 29ad5b58log: #64 merged, DP64 and HM52 startedmre