gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitfe209ffefe209ffeMerge branch 'w56-owner-members' into mainGitoriafe209ffe/tests/cdp.mjs

31.7 KB

  1. import { requiredPortRange } from './gate-ports.mjs';
  2. // tests/browser/cdp.mjs — a tiny raw-CDP browser driver. ZERO npm dependencies:
  3. // node's native WebSocket speaks the Chrome DevTools Protocol directly, so the
  4. // real-browser tier needs nothing installed beyond `google-chrome` itself.
  5. //
  6. // Two connection modes (mission 073 gate 1):
  7. // • default — launch a LOCAL `google-chrome --headless=new` on a free debug port.
  8. // This is what the suites use: hermetic, no external dependency.
  9. // • HL_CDP_URL=http://host:port — attach to an ALREADY-RUNNING Chrome instead
  10. // (e.g. the creator's notebook at http://lisbeth.tailfd3886.ts.net:9223).
  11. // Nothing is launched or killed in that mode; only the tabs we create are closed.
  12. //
  13. // Everything a browser test needs and nothing else: navigate, wait-for-selector,
  14. // evaluate, REAL mouse/keyboard dispatch (Input domain, not synthetic .click()),
  15. // full console + uncaught-exception capture, and teardown that leaves no process.
  16. import { spawn } from 'node:child_process';
  17. import { mkdtempSync, rmSync } from 'node:fs';
  18. import { tmpdir } from 'node:os';
  19. import { join } from 'node:path';
  20. import { createConnection } from 'node:net';
  21. // One definition of "is this port actually usable", shared with the fixture boot
  22. // path — the whole of mission 285 is that the tier had two different answers to
  23. // that question and neither was the one the kernel gives.
  24. import { portBindable, whoHolds } from './ports.mjs';
  25. const CHROME_CANDIDATES = ['google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser'];
  26. export function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
  27. async function portOpen(host, port) {
  28. return new Promise(resolve => {
  29. const sock = createConnection({ host, port });
  30. const done = (ok) => { try { sock.destroy(); } catch {} resolve(ok); };
  31. sock.setTimeout(400);
  32. sock.on('connect', () => done(true));
  33. sock.on('error', () => done(false));
  34. sock.on('timeout', () => done(false));
  35. });
  36. }
  37. /**
  38. * Wait until `http://host:port/json/version` answers, or throw.
  39. *
  40. * `giveUp` (mission 285) is asked on every turn for a reason to stop early: waiting
  41. * out a full timeout for something that has already announced it will never arrive
  42. * is how a port collision came to look like a twenty-second test failure.
  43. */
  44. async function waitForEndpoint(base, timeoutMs, label, giveUp = () => null) {
  45. const deadline = Date.now() + timeoutMs;
  46. let lastErr = 'no attempt';
  47. while (Date.now() < deadline) {
  48. const stop = giveUp();
  49. if (stop) throw new Error(stop);
  50. try {
  51. const res = await fetch(base + '/json/version', { signal: AbortSignal.timeout(2000) });
  52. if (res.ok) return await res.json();
  53. lastErr = 'HTTP ' + res.status;
  54. } catch (e) { lastErr = String(e && e.message || e); }
  55. await sleep(100);
  56. }
  57. throw new Error(`${label} not reachable at ${base} after ${timeoutMs}ms (${lastErr})`);
  58. }
  59. // --- the protocol connection ------------------------------------------------
  60. class Conn {
  61. constructor(ws) {
  62. this.ws = ws;
  63. this.nextId = 1;
  64. this.pending = new Map();
  65. this.listeners = [];
  66. ws.addEventListener('message', (ev) => {
  67. let msg;
  68. try { msg = JSON.parse(typeof ev.data === 'string' ? ev.data : String(ev.data)); } catch { return; }
  69. if (msg.id !== undefined && this.pending.has(msg.id)) {
  70. const { resolve, reject } = this.pending.get(msg.id);
  71. this.pending.delete(msg.id);
  72. if (msg.error) reject(new Error(`${msg.error.message} (CDP ${msg.error.code})`));
  73. else resolve(msg.result);
  74. return;
  75. }
  76. for (const fn of this.listeners) fn(msg);
  77. });
  78. ws.addEventListener('close', () => {
  79. for (const { reject } of this.pending.values()) reject(new Error('CDP connection closed'));
  80. this.pending.clear();
  81. });
  82. }
  83. onEvent(fn) { this.listeners.push(fn); return () => { this.listeners = this.listeners.filter(f => f !== fn); }; }
  84. send(method, params = {}, sessionId) {
  85. const id = this.nextId++;
  86. const payload = { id, method, params };
  87. if (sessionId) payload.sessionId = sessionId;
  88. return new Promise((resolve, reject) => {
  89. this.pending.set(id, { resolve, reject });
  90. const t = setTimeout(() => {
  91. if (this.pending.delete(id)) reject(new Error(`CDP timeout: ${method}`));
  92. }, 20000);
  93. const clear = () => clearTimeout(t);
  94. const orig = this.pending.get(id);
  95. this.pending.set(id, {
  96. resolve: (v) => { clear(); orig.resolve(v); },
  97. reject: (e) => { clear(); orig.reject(e); },
  98. });
  99. try { this.ws.send(JSON.stringify(payload)); } catch (e) { this.pending.delete(id); clear(); reject(e); }
  100. });
  101. }
  102. close() { try { this.ws.close(); } catch {} }
  103. }
  104. async function connectWs(url) {
  105. const ws = new WebSocket(url);
  106. await new Promise((resolve, reject) => {
  107. const to = setTimeout(() => reject(new Error('WebSocket open timeout: ' + url)), 10000);
  108. ws.addEventListener('open', () => { clearTimeout(to); resolve(); }, { once: true });
  109. ws.addEventListener('error', (e) => { clearTimeout(to); reject(new Error('WebSocket error: ' + url)); }, { once: true });
  110. });
  111. return new Conn(ws);
  112. }
  113. // --- Page -------------------------------------------------------------------
  114. /**
  115. * One tab. Owns its own console/exception log from the moment it is created,
  116. * so nothing that happens during load can be missed.
  117. */
  118. export class Page {
  119. constructor(browser, targetId, sessionId) {
  120. this.browser = browser;
  121. this.conn = browser.conn;
  122. this.targetId = targetId;
  123. this.sessionId = sessionId;
  124. /** every console message AND uncaught exception, in arrival order */
  125. this.messages = [];
  126. this.closed = false;
  127. }
  128. send(method, params) { return this.conn.send(method, params, this.sessionId); }
  129. /** console messages whose level is error/warning (what "console clean" means) */
  130. problems() { return this.messages.filter(m => m.level === 'error' || m.level === 'warning'); }
  131. /** Wait until a captured console message matches — the hydration/apply signals. */
  132. async waitForConsoleMatch(re, { timeout = 10000 } = {}) {
  133. const deadline = Date.now() + timeout;
  134. while (Date.now() < deadline) {
  135. const hit = this.messages.find(m => re.test(m.text));
  136. if (hit) return hit;
  137. await sleep(40);
  138. }
  139. throw new Error(`waitForConsoleMatch timed out (${re}). Console was:\n${this.dumpConsole()}`);
  140. }
  141. /** one-line rendering of everything captured — for failure details */
  142. dumpConsole() { return this.messages.map(m => `[${m.level}] ${m.text}`).join('\n') || '(no console output)'; }
  143. /**
  144. * Run `source` in EVERY document this tab loads, BEFORE any page script.
  145. * The only way to observe something the app sets up on load — mission 080 uses
  146. * it to wrap `EventSource` and capture the raw SSE frames, so the assertion
  147. * "this session was told nothing" is made against the wire, not the DOM.
  148. */
  149. addInitScript(source) { return this.send('Page.addScriptToEvaluateOnNewDocument', { source }); }
  150. /**
  151. * Capture every SSE frame this page receives into `window.__hlSSE`. Must be
  152. * called BEFORE goto(); the wrapper subclasses the real EventSource, so the
  153. * app's own `onmessage` is untouched and the transport is not simulated.
  154. */
  155. captureSse() {
  156. return this.addInitScript(`(() => {
  157. window.__hlSSE = [];
  158. const Native = window.EventSource;
  159. if (!Native) return;
  160. window.EventSource = class extends Native {
  161. constructor(...a) {
  162. super(...a);
  163. this.addEventListener('message', (e) => {
  164. try { window.__hlSSE.push(JSON.parse(e.data)); } catch {}
  165. });
  166. }
  167. };
  168. })()`);
  169. }
  170. /** The SSE frames captured so far (see captureSse), oldest first. */
  171. sseFrames() { return this.evaluate('window.__hlSSE || []'); }
  172. /**
  173. * Mission 090: capture every WebSocket frame this page RECEIVES (`__hlWs`) and
  174. * every one it SENDS (`__hlWsOut`). Must be called BEFORE goto(); the wrapper
  175. * subclasses the real WebSocket, so the app's own listeners are untouched and
  176. * the transport is the real one — "this session was told exactly these bytes"
  177. * is then an assertion about the wire, not about the DOM.
  178. */
  179. captureWs() {
  180. return this.addInitScript(`(() => {
  181. window.__hlWs = [];
  182. window.__hlWsOut = [];
  183. // when the LAST frame arrived, on the page's own clock — the ordering
  184. // assertion "the DOM moved because of the frame" is made against this
  185. window.__hlWsAt = 0;
  186. // ...and when the first STATE PATCH arrived. A patch is an ARRAY frame (the
  187. // protocol's onPatches); control frames — ack, pong, build — are objects,
  188. // and since mission 133 an ack lands right AFTER the patch it belongs to,
  189. // so __hlWsAt alone would put "the last frame" after the DOM had already
  190. // moved for the patch.
  191. window.__hlWsPatchAt = 0;
  192. const Native = window.WebSocket;
  193. if (!Native) return;
  194. window.WebSocket = class extends Native {
  195. constructor(...a) {
  196. super(...a);
  197. this.addEventListener('message', (e) => {
  198. window.__hlWs.push(String(e.data));
  199. window.__hlWsAt = performance.now();
  200. if (!window.__hlWsPatchAt) {
  201. try {
  202. if (Array.isArray(JSON.parse(String(e.data)))) window.__hlWsPatchAt = window.__hlWsAt;
  203. } catch {}
  204. }
  205. });
  206. }
  207. send(d) { window.__hlWsOut.push(String(d)); return super.send(d); }
  208. };
  209. })()`);
  210. }
  211. /** Frames this page RECEIVED / SENT since load (see captureWs), oldest first. */
  212. wsFrames() { return this.evaluate('window.__hlWs || []'); }
  213. wsSent() { return this.evaluate('window.__hlWsOut || []'); }
  214. resetWs() { return this.evaluate('window.__hlWs = []'); }
  215. /**
  216. * Mission 093: the cookies the BROWSER holds for `urls`, as the browser sees
  217. * them — including the httpOnly ones, which is the whole point. `document.cookie`
  218. * cannot see an httpOnly cookie, so "the session id is not reachable from page
  219. * script" and "the session id exists" can only be asserted together from here.
  220. */
  221. async cookies(urls) {
  222. await this.send('Network.enable');
  223. const { cookies } = await this.send('Network.getCookies', urls ? { urls } : {});
  224. return cookies || [];
  225. }
  226. /** Cut THIS tab off the network, or let it back on (CDP emulation). */
  227. async setOffline(offline) {
  228. await this.send('Network.enable');
  229. await this.send('Network.emulateNetworkConditions', {
  230. offline, latency: 0, downloadThroughput: -1, uploadThroughput: -1,
  231. });
  232. }
  233. /**
  234. * Mission 081: serve an APP SHELL PRECACHE from the harness — the part mission
  235. * 082's generated service worker will play (D29/§10.4: the `offline` target
  236. * precaches the shell so a revisit boots with the network down).
  237. *
  238. * 081 owns the STATE layer — "with the network down the state comes from
  239. * IndexedDB" — and that claim is only observable once a document can load at
  240. * all. `snapshot` is a url → {status, contentType, body} map the test captured
  241. * over HTTP while it was still online; those URLs are fulfilled from it, and
  242. * EVERY OTHER request (`?__data=1`, `/emit`, `/events` — all the data
  243. * endpoints) is passed on to the network, which is exactly where it dies. So
  244. * the shell is precached and the data is genuinely unreachable, which is the
  245. * situation §10.2 describes.
  246. *
  247. * Chrome's own HTTP cache cannot stand in for this: a response replayed
  248. * through `Fetch.continueResponse` is not stored in the disk cache (measured),
  249. * and `Page.reload` deliberately revalidates, so it fails offline either way.
  250. */
  251. async servePrecache(snapshot) {
  252. this._precache = snapshot;
  253. await this.send('Fetch.enable', { patterns: [{ urlPattern: '*' }] });
  254. }
  255. /** Stop answering from the precache and let every request reach the network. */
  256. async stopPrecache() {
  257. this._precache = null;
  258. await this.send('Fetch.enable', { patterns: [{ urlPattern: '*/favicon.ico' }] });
  259. }
  260. /**
  261. * Mission 087 (gate 2): capture EVERY request the page makes, from the browser
  262. * itself. `Network.requestWillBeSent` fires for navigations, subresources,
  263. * `fetch`/XHR and beacons alike, so "this interaction cost zero network
  264. * requests" is asserted against the wire and cannot be talked around.
  265. * The favicon request the browser makes on its own is excluded by URL — it is
  266. * the browser's, not the app's (the Fetch handler above already answers it).
  267. */
  268. async captureNetwork() {
  269. this.requests = [];
  270. this._netOn = true;
  271. await this.send('Network.enable');
  272. return this;
  273. }
  274. /** Every request URL captured since the last `resetNetwork()`, oldest first. */
  275. networkUrls() { return (this.requests || []).map(r => r.url); }
  276. /** The same requests as `{ url, method, headers }` — mission 090 asserts all three. */
  277. networkRequests() { return (this.requests || []).slice(); }
  278. /** Forget everything captured so far — the "since this moment" baseline. */
  279. resetNetwork() { this.requests = []; return this; }
  280. _record(level, text, extra) { this.messages.push({ level, text, ...extra }); }
  281. async _init() {
  282. this.conn.onEvent((msg) => {
  283. if (msg.sessionId !== this.sessionId) return;
  284. const p = msg.params || {};
  285. if (msg.method === 'Runtime.consoleAPICalled') {
  286. const level = p.type === 'error' ? 'error' : p.type === 'warning' || p.type === 'warn' ? 'warning' : p.type === 'debug' ? 'debug' : 'info';
  287. this._record(level, (p.args || []).map(describeArg).join(' '), { source: 'console.' + p.type });
  288. } else if (msg.method === 'Runtime.exceptionThrown') {
  289. const d = p.exceptionDetails || {};
  290. const text = (d.exception && (d.exception.description || d.exception.value)) || d.text || 'uncaught exception';
  291. this._record('error', String(text), { source: 'exception' });
  292. } else if (msg.method === 'Log.entryAdded') {
  293. const e = p.entry || {};
  294. const level = e.level === 'error' ? 'error' : e.level === 'warning' ? 'warning' : 'info';
  295. this._record(level, `${e.source}: ${e.text}${e.url ? ' @ ' + e.url : ''}`, { source: 'log.' + e.source });
  296. } else if (msg.method === 'Page.loadEventFired') {
  297. this._loaded = true;
  298. } else if (msg.method === 'Network.requestWillBeSent' && this._netOn) {
  299. const url = (p.request && p.request.url) || '';
  300. if (!/\/favicon\.ico$/.test(url)) {
  301. this.requests.push({
  302. url,
  303. method: (p.request && p.request.method) || 'GET',
  304. headers: (p.request && p.request.headers) || {},
  305. });
  306. }
  307. } else if (msg.method === 'Fetch.requestPaused' && this._precache
  308. && this._precache[(p.request && p.request.url) || '']) {
  309. // the harness precache (servePrecache) answers this one, network untouched
  310. const hit = this._precache[p.request.url];
  311. this.send('Fetch.fulfillRequest', {
  312. requestId: p.requestId, responseCode: hit.status || 200,
  313. responseHeaders: [{ name: 'Content-Type', value: hit.contentType || 'text/html; charset=utf-8' }],
  314. body: Buffer.from(hit.body, 'utf-8').toString('base64'),
  315. }).catch(() => {});
  316. } else if (msg.method === 'Fetch.requestPaused' && this._precache
  317. && !/\/favicon\.ico$/.test((p.request && p.request.url) || '')) {
  318. // not precached: let it go to the network — which is where it must fail
  319. this.send('Fetch.continueRequest', { requestId: p.requestId }).catch(() => {});
  320. } else if (msg.method === 'Fetch.requestPaused') {
  321. // The browser fetches /favicon.ico on every navigation all by itself.
  322. // A fixture server serves no favicon, so that 404 would show up as a
  323. // console error that NO page code caused. Answer it here (empty 200)
  324. // instead of filtering it out later: then "zero console errors" means
  325. // exactly what it says — nothing is excused after the fact.
  326. this.send('Fetch.fulfillRequest', {
  327. requestId: p.requestId, responseCode: 200,
  328. responseHeaders: [{ name: 'Content-Type', value: 'image/x-icon' }], body: '',
  329. }).catch(() => {});
  330. }
  331. });
  332. await this.send('Runtime.enable');
  333. await this.send('Log.enable');
  334. await this.send('Page.enable');
  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({ browserContextId } = {}) {
  496. if (browserContextId && !this.owned) throw new Error('isolated contexts are only allowed in an owned automated browser');
  497. const { targetId } = await this.conn.send('Target.createTarget', { url: 'about:blank', ...(browserContextId ? { browserContextId } : {}) });
  498. const { sessionId } = await this.conn.send('Target.attachToTarget', { targetId, flatten: true });
  499. const page = new Page(this, targetId, sessionId);
  500. await page._init();
  501. this.pages.push(page);
  502. return page;
  503. }
  504. /**
  505. * Teardown. Closes every tab we opened; when WE launched the browser it is also
  506. * killed by PID and waited for, and its profile dir removed. Resolves only once
  507. * the process is actually gone — the run script asserts on that.
  508. */
  509. async close() {
  510. for (const p of this.pages) { try { await p.close(); } catch {} }
  511. this.pages = [];
  512. if (!this.owned) { this.conn.close(); return; }
  513. try { await this.conn.send('Browser.close'); } catch {}
  514. this.conn.close();
  515. const pid = this.proc.pid;
  516. const gone = await waitForExit(this.proc, 5000);
  517. if (!gone) {
  518. try { process.kill(pid, 'SIGKILL'); } catch {}
  519. await waitForExit(this.proc, 3000);
  520. }
  521. if (this.userDataDir) { try { rmSync(this.userDataDir, { recursive: true, force: true }); } catch {} }
  522. const rec = launchedBrowsers.find(r => r.browser === this);
  523. if (rec) rec.closed = true;
  524. }
  525. }
  526. function waitForExit(proc, timeoutMs) {
  527. if (proc.exitCode !== null || proc.signalCode !== null) return Promise.resolve(true);
  528. return new Promise(resolve => {
  529. const t = setTimeout(() => resolve(false), timeoutMs);
  530. proc.once('exit', () => { clearTimeout(t); resolve(true); });
  531. });
  532. }
  533. /**
  534. * MISSION 285 — A PORT IS FREE WHEN IT CAN BE BOUND, NOT WHEN NOTHING ANSWERS.
  535. *
  536. * This used to ask `portOpen('127.0.0.1', p)`: connect, and if it is refused call
  537. * the port free. Chrome then binds it — and when that bind loses, Chrome does NOT
  538. * fail. It falls back to IPv6 and says so on stderr, which nothing read:
  539. *
  540. * ERROR:net/socket/socket_posix.cc:175] bind() failed: Address already in use (98)
  541. * DevTools listening on ws://[::1]:53502/devtools/browser/06fcaa25-…
  542. *
  543. * `waitForEndpoint` only ever polls `http://127.0.0.1:PORT`, so it then spent its
  544. * whole 20 000 ms waiting for an endpoint that was up the entire time at a place it
  545. * never looked, and the test that happened to be launching a peer browser took the
  546. * blame. Measured twice in one tier run (25-sessions and 27-login, both 20 4xx ms,
  547. * both on :53502) and reproduced on demand by putting one listener on 127.0.0.1:P
  548. * before the launch — same bind error, same ::1 fallback, IPv4 never reachable.
  549. *
  550. * So: bind-test the candidate (see `portBindable` in ports.mjs for why a bind is
  551. * the honest question), and check what Chrome actually did afterwards.
  552. */
  553. async function findFreePort(from, to) {
  554. for (let p = from; p <= to; p++) if (await portBindable(p)) return p;
  555. throw new Error(`no bindable port in ${from}-${to}`);
  556. }
  557. /** Where Chrome says it is listening — the only address that is not a guess. */
  558. function announcedEndpoint(stderr) {
  559. const m = /DevTools listening on ws:\/\/(\[[^\]]+\]|[^:/]+):(\d+)\//.exec(stderr);
  560. return m ? { host: m[1], port: Number(m[2]) } : null;
  561. }
  562. /**
  563. * Launch (or attach to) a browser.
  564. * HL_CDP_URL set → attach, never spawn, never kill.
  565. * otherwise → spawn local headless Chrome on the explicit debugPortRange,
  566. * or the required GITORIA_GATE_CHROME env range.
  567. * Optional HL_CHROME overrides the binary; HL_HEADFUL=1 shows the window.
  568. */
  569. // No implicit Chrome debug port block. Callers pass an env-derived range.
  570. /**
  571. * EVERY browser this process launched, whoever asked for it.
  572. *
  573. * The teardown audit used to know only about the ONE browser run.mjs launched,
  574. * so a peer browser started inside a test (25-sessions and 45-server-face-emit
  575. * each launch a second one for a second session) could survive while the audit
  576. * reported "no orphan chrome/servers" — measured 2026-08-23 with a deliberate
  577. * leak, which the audit passed clean. `launchBrowser` is the one choke point
  578. * every browser goes through, so the registry belongs here rather than in the
  579. * runner, and it catches a leak no matter who caused it.
  580. */
  581. export const launchedBrowsers = [];
  582. export async function launchBrowser({ debugPortRange } = {}) {
  583. const attach = process.env.HL_CDP_URL;
  584. if (attach) {
  585. const base = attach.replace(/\/$/, '');
  586. const info = await waitForEndpoint(base, 8000, 'HL_CDP_URL browser');
  587. const conn = await connectWs(info.webSocketDebuggerUrl);
  588. return new Browser(conn, { endpoint: base });
  589. }
  590. debugPortRange ??= requiredPortRange('GITORIA_GATE_CHROME');
  591. const bin = process.env.HL_CHROME || (await firstOnPath(CHROME_CANDIDATES));
  592. if (!bin) throw new Error(`no Chrome binary found (tried ${CHROME_CANDIDATES.join(', ')}); set HL_CHROME or HL_CDP_URL`);
  593. const port = await findFreePort(debugPortRange[0], debugPortRange[1]);
  594. const userDataDir = mkdtempSync(join(tmpdir(), 'hl-browser-tier-'));
  595. const args = [
  596. process.env.HL_HEADFUL ? '--headless=false' : '--headless=new',
  597. `--remote-debugging-port=${port}`,
  598. `--user-data-dir=${userDataDir}`,
  599. '--no-first-run', '--no-default-browser-check', '--disable-extensions',
  600. // WPAD proxy auto-detection stalls the FIRST http navigation for ~20s on this
  601. // machine (measured: data: URL instant, first http nav 20s, later navs instant).
  602. // Going straight-to-direct removes the stall — localhost fixtures need no proxy.
  603. '--no-proxy-server', "--proxy-server=direct://", '--proxy-bypass-list=*',
  604. '--password-store=basic', '--use-mock-keychain',
  605. '--disable-background-networking', '--disable-component-update',
  606. '--disable-default-apps', '--disable-sync', '--metrics-recording-only',
  607. '--mute-audio', '--disable-gpu', '--disable-dev-shm-usage',
  608. '--window-size=1280,900',
  609. ...(process.env.HL_CHROME_ARGS ? process.env.HL_CHROME_ARGS.split('|') : []), // gitoria: --host-resolver-rules for *.gitoria.test
  610. 'about:blank',
  611. ].filter(a => a !== '--headless=false');
  612. const proc = spawn(bin, args, { stdio: ['ignore', 'ignore', 'pipe'] });
  613. const stderr = [];
  614. proc.stderr.on('data', d => { if (stderr.length < 50) stderr.push(String(d)); });
  615. const base = `http://127.0.0.1:${port}`;
  616. const die = (msg) => {
  617. try { process.kill(proc.pid, 'SIGKILL'); } catch {}
  618. rmSync(userDataDir, { recursive: true, force: true });
  619. throw new Error(msg);
  620. };
  621. let info;
  622. try {
  623. // MISSION 285 — stop the moment Chrome says it went somewhere else, instead of
  624. // polling an address it has already told us it is not on. A launch that lost the
  625. // port is a PORT COLLISION and must read as one; twenty silent seconds followed
  626. // by "not reachable" reads as a broken browser or a broken test.
  627. info = await waitForEndpoint(base, 20000, 'headless Chrome', () => {
  628. const said = announcedEndpoint(stderr.join(''));
  629. if (said && said.host !== '127.0.0.1') {
  630. 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(' | ')}`;
  631. }
  632. return null;
  633. });
  634. } catch (e) {
  635. die(e.message + '\nchrome stderr:\n' + stderr.join(''));
  636. }
  637. const conn = await connectWs(info.webSocketDebuggerUrl);
  638. const browser = new Browser(conn, { proc, userDataDir, endpoint: base });
  639. launchedBrowsers.push({ pid: proc.pid, port, userDataDir, closed: false, browser });
  640. return browser;
  641. }
  642. async function firstOnPath(names) {
  643. const { execFile } = await import('node:child_process');
  644. for (const n of names) {
  645. const found = await new Promise(res => execFile('which', [n], (err, out) => res(err ? null : String(out).trim())));
  646. if (found) return found;
  647. }
  648. return null;
  649. }

Branches

Latest commits

  • fe209ffeMerge branch 'w56-owner-members' into mainGitoria
  • fa0754c8|||PR repository owner transfer and members API (#55)mre
  • 8862e537Merge branch 'w55-rename-org' into mainGitoria
  • 014d2b7fOne immutable readers snapshot per move for the left-organization event (#53)mre
  • 1859d506Decide who hears a repo left its organization by its readers before the move (#53)mre
  • 499f25f2Review fixes for the Settings organization move (#53)mre
  • ed3b922b|||PR move a repository into an organization in Settings (#53)mre
  • 74ec2af8Merge branch 'w54-repo-rename-pr' into mainGitoria
  • 9f7ce8d8Preserve rename compatibility and live page titlesmre
  • c3d95b6e|||PR separate names and addresses, rename repositories in Settings (#53)mre
  • ce08920dMerge branch 'w52c-header-phone' into mainGitoria
  • 0bab9e46|||PR header: ident status wraps on phones instead of clippingmre
  • e7af3eceMerge branch 'w52b-approval-followup' into mainGitoria
  • c01e66c6|||PR approvals follow-up: live Merge after status writes, helpers (#52)mre
  • 841da497Merge branch 'w53-pulls-speed-pr' into mainGitoria
  • 80307ae2|||PR pulls page cache: live PR numbers, complete scans onlymre
  • 69141f65|||PR pulls page: cache the git part per repo by branch tipsmre
  • 155861f6Merge branch 'w52-person-approval' into mainGitoria
  • b5435de8|||PR person approvals: second Kunibert round (#52)mre
  • 3a8b2fb8|||PR person approvals: Kunibert review fixes (#52)mre