gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit00517faf00517fafgitoria: shell 404 page for unknown paths (catch-all route, status 404, JSON 404 under /api), 390 gate checksMG00517faf/tests/e2e-real.mjs

16.5 KB

  1. // tests/e2e-real.mjs — the gitoria walk in a REAL browser (an existing tab of lisbeth's test Chrome, over the CDP tunnel), not a gate:
  2. // prints numbers and writes screenshots. Own ident + gitoria on a throw-away store (ports from the env), the tab reaches them through
  3. // `ssh -R <port>:127.0.0.1:<port> lisbeth` as http://gitoria.localhost:<port> (*.localhost is loopback in Chrome, no resolver rule).
  4. // E2E_APP=<app dir> E2E_PORT=8742 E2E_IDENT_PORT=8743 E2E_TAG=old|new E2E_SHOTS=<dir> E2E_CDP=http://127.0.0.1:9223 E2E_TAB=<target id>
  5. // node tests/e2e-real.mjs
  6. import { spawn, execFileSync } from 'node:child_process';
  7. import { rmSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
  8. import { dirname, join, resolve } from 'node:path';
  9. import { fileURLToPath } from 'node:url';
  10. import { launchBrowser, Page } from './cdp.mjs';
  11. import { startIdent } from './identkit.mjs';
  12. const HERE = dirname(fileURLToPath(import.meta.url));
  13. const APP = resolve(process.env.E2E_APP || join(HERE, '..'));
  14. const PORT = Number(process.env.E2E_PORT), IPORT = Number(process.env.E2E_IDENT_PORT);
  15. const TAG = process.env.E2E_TAG || 'x', SHOTS = process.env.E2E_SHOTS, TAB = process.env.E2E_TAB;
  16. const STORE = join(process.env.E2E_STORE, TAG);
  17. const BASE = `http://gitoria.localhost:${PORT}`, REPO = (s) => `http://${s}.gitoria.localhost:${PORT}`, IDENT_B = `http://ident.gitoria.localhost:${IPORT}`;
  18. const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || '/media/STORAGE/projects/WorldAPI/ident.worldapi.org';
  19. const MEASURE = readFileSync(join(HERE, 'mobile-measure.js'), 'utf8');
  20. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  21. const J = JSON.stringify;
  22. mkdirSync(SHOTS, { recursive: true }); rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  23. process.env.HL_CDP_URL = process.env.E2E_CDP || 'http://127.0.0.1:9223';
  24. let browserConn = null; let ident = null, server = null, page = null, slog = () => ''; const results = [];
  25. const noise = /ERR_|Failed to load resource|WebSocket connection/;
  26. const seen = new Set();
  27. const report = (where) => { for (const m of page.messages) { if ((m.level === 'error' || m.level === 'warning') && !noise.test(m.text) && !seen.has(m)) { seen.add(m); console.log('CONSOLE ERROR at', where, '|', m.text.split('\n')[0].slice(0, 160)); } } };
  28. const hydrated = () => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'hydrated', timeout: 30000 });
  29. const shows = (sel) => page.evaluate(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`);
  30. async function view(w) {
  31. if (w < 600) { await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: 844, deviceScaleFactor: 2, mobile: true }); await page.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 }); }
  32. else { await page.send('Emulation.setTouchEmulationEnabled', { enabled: false }); await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: 900, deviceScaleFactor: 1, mobile: false }); }
  33. await sleep(300);
  34. }
  35. async function shot(name) { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SHOTS, `${TAG}-${name}.png`), Buffer.from(data, 'base64')); }
  36. async function measure(name, w) {
  37. await hydrated(); await sleep(500);
  38. await page.evaluate(`window.__ev = []; document.addEventListener('pointerdown', e => window.__ev.push('pd:' + e.pointerType + ':' + e.target.tagName), true); document.addEventListener('click', e => window.__ev.push('click:' + e.target.tagName), true); 1`);
  39. const m = await page.evaluate(`window.__W = ${w};` + MEASURE);
  40. report(name + ' (after load)');
  41. const r = { name, w, scrollWidth: m.docScrollWidth, tapsSmall: m.tapsSmall, taps: m.taps, smallList: (m.tapsSmallList || []).slice(0, 6), inputsSmall: (m.inputsSmallList || []).length, header: m.headerH, boxesOver: (m.boxesOver || []).length };
  42. results.push(r); console.log(J(r)); await shot(name.replace(/[^a-z0-9]+/gi, '-'));
  43. }
  44. async function go(url, ready) {
  45. await page.goto(url); await page.send('Page.bringToFront'); await page.waitForSelector(ready, { timeout: 30000 }); }
  46. async function toggle(sel, box) {
  47. const open = `!!document.querySelector(${J(box)}) && document.querySelector(${J(box)}).matches(':popover-open')`;
  48. for (let i = 0; i < 4; i++) { // a real tap; when the page was re-rendering under it and nothing opened, tap again (a tap on an open box would close it, so only when closed)
  49. if (await page.evaluate(open)) break;
  50. await page.click(sel); await sleep(1500);
  51. if (i) console.log(' (tap', i + 1, 'for', box + ')');
  52. }
  53. report('tap ' + sel + ' (before it opened)');
  54. await page.waitFor(open, { label: box + ' open', timeout: 5000 }).catch(async (e) => { console.log('DIAG3', await page.evaluate(`(() => { const r = document.querySelector(${J(sel)}).getBoundingClientRect(); const e = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); return JSON.stringify({ r: [r.left, r.top, r.width, r.height], at: e && (e.tagName + '.' + (e.className.baseVal ?? e.className)), vis: document.visibilityState, focus: document.hasFocus(), ev: window.__ev }); })()`)); throw e; });
  55. await sleep(300); report('tap ' + sel + ' (after it opened)');
  56. }
  57. // mission 009 (theme 76f99f6): the main menu marks the current page beyond colour — aria-current="page" on exactly one visible link and an
  58. // inset accent bar (box-shadow). gitoria has ONE item (Repositories) and every page is under it (`current = true`), so "the marker moves"
  59. // is shown as: it is on every page, and it is still there after a REAL click on the item itself (to the home page).
  60. const marks = [];
  61. async function mark(name, w) {
  62. const sel = w < 600 ? '#sidebar main-menu a' : 'application-header main-menu a';
  63. const m = await page.evaluate(`(() => { const ls = [...document.querySelectorAll(${J(sel)})].filter(a => a.getBoundingClientRect().width > 0); const cur = ls.filter(a => a.getAttribute('aria-current') === 'page'); const c = cur[0]; const cs = c && getComputedStyle(c); return { links: ls.length, current: cur.length, text: c && c.textContent, cls: c && c.className, shadow: cs && cs.boxShadow, others: ls.filter(a => a.getAttribute('aria-current') !== 'page' && a.getAttribute('aria-current') !== 'false').length }; })()`);
  64. const ok = m.links === 1 && m.current === 1 && m.cls.includes('current') && !!m.shadow && m.shadow !== 'none';
  65. marks.push({ name, ok }); console.log(ok ? 'ok ' : 'FAIL', 'menu marker', name, J(m));
  66. return ok;
  67. }
  68. async function clickMenuItem(w, name) {
  69. const sel = w < 600 ? '#sidebar main-menu a' : 'application-header main-menu a';
  70. await page.click(sel); await page.waitForSelector('#repos li', { timeout: 30000 }); await hydrated();
  71. if (w < 600) { await toggle('button.menu-toggle', '#sidebar'); }
  72. await mark(name + ' (after a click on the item: home)', w);
  73. }
  74. async function walk(w, signedIn) {
  75. await view(w);
  76. const L = (n) => `${w} ${n}${signedIn ? '' : ' (signed out)'}`;
  77. await go(BASE + '/', '#repos li'); await measure(L('home'), w); if (w >= 600) await mark(L('home'), w);
  78. await go(REPO('alpha') + '/', '#reponame'); await measure(L('readme'), w); if (w >= 600) await mark(L('readme'), w);
  79. await go(REPO('alpha') + '/code', '#entries li'); await measure(L('code folder'), w); if (w >= 600) await mark(L('code folder'), w);
  80. await go(REPO('alpha') + '/code/src/a.txt', '#lines li'); await measure(L('file'), w); if (w >= 600) await mark(L('file'), w);
  81. await go(REPO('alpha') + '/commit/' + process.env.E2E_SHA, '#entries li'); await measure(L('commit'), w); if (w >= 600) await mark(L('commit'), w);
  82. await go(REPO('alpha') + '/pulls', 'repo-pulls'); await measure(L('pulls'), w); if (w >= 600) await mark(L('pulls'), w);
  83. if (signedIn) { await go(REPO('alpha') + '/settings', 'repo-settings'); await measure(L('settings'), w); }
  84. if (w < 600) {
  85. await go(REPO('alpha') + '/code', '#entries li'); await hydrated(); await toggle('button.menu-toggle', '#sidebar'); await measure(L('sidebar open'), w); await mark(L('code, sidebar open'), w); await shot('menu-' + w + '-code-sidebar'); await clickMenuItem(w, L('code'));
  86. if (signedIn) { await go(REPO('alpha') + '/', '#reponame'); await hydrated(); await toggle('button.user-toggle', '#user-menu'); await measure(L('user menu open'), w); }
  87. else { await go(REPO('alpha') + '/', '#reponame'); await hydrated(); await toggle('button.ident-toggle', '#ident-panel'); await measure(L('ident menu open'), w); }
  88. } else if (signedIn) {
  89. await go(REPO('alpha') + '/code', '#entries li'); await hydrated(); await clickMenuItem(w, L('code')); await shot('menu-' + w + '-home-after-click');
  90. await go(REPO('alpha') + '/', '#reponame'); await hydrated(); await toggle('button.user-toggle', '#user-menu'); await measure(L('user menu open'), w);
  91. }
  92. }
  93. try {
  94. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IPORT });
  95. const alice = await ident.signIn('[email protected]');
  96. const APPKEY = await ident.registerApp(alice, 'gitoria (e2e)', [BASE]);
  97. server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  98. env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_WATCH: '0', GITORIA_GIT: join(STORE, 'git'),
  99. GITORIA_PUBLIC_URL: BASE, IDENT_URL: IDENT_B, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret } });
  100. let log = ''; slog = () => log; server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  101. for (let i = 0; i < 600; i++) { try { if ((await fetch(`http://127.0.0.1:${PORT}/api/repos`)).ok) break; } catch {} await sleep(250); }
  102. // the real tab: an EXISTING page target, attached (never created, never closed)
  103. const b = await launchBrowser(); browserConn = b.conn;
  104. const { sessionId } = await b.conn.send('Target.attachToTarget', { targetId: TAB, flatten: true });
  105. page = new Page(b, TAB, sessionId); await page._init();
  106. await b.conn.send('Target.activateTarget', { targetId: TAB }); // a background tab gets no real input: bring it to the front for the run, give the front back at the end
  107. { const wf = page.waitFor.bind(page); page.waitFor = (e, o = {}) => wf(e, { ...o, timeout: (o.timeout || 10000) * 3 }); const gt = page.goto.bind(page); page.goto = (u, o = {}) => gt(u, { ...o, timeout: (o.timeout || 15000) * 3 }); }
  108. await view(1280);
  109. await page.send('Network.enable');
  110. // earlier runs leave cookies, a service worker and caches for these origins in the shared profile: clear exactly these origins, nothing else
  111. for (const o of [BASE, IDENT_B, REPO('alpha')]) await page.send('Storage.clearDataForOrigin', { origin: o, storageTypes: 'all' });
  112. for (const c of (await page.send('Network.getAllCookies')).cookies.filter(c => /gitoria\.localhost/.test(c.domain))) await page.send('Network.deleteCookies', { name: c.name, domain: c.domain, path: c.path });
  113. const [ck, cv] = alice.cookie.split('=');
  114. await page.send('Network.setCookie', { name: ck, value: cv, url: IDENT_B + '/' });
  115. // sign in by real clicks: login button (ident dropdown on a phone), choose the identity, give a name
  116. await view(390);
  117. await go(BASE + '/', '#repos, #heading'); await hydrated();
  118. await page.evaluate(`window.__t = []; document.querySelector('#ident-panel').addEventListener('toggle', e => window.__t.push(e.newState + '@' + Math.round(performance.now()))); document.addEventListener('pointerdown', e => window.__t.push('pd:' + e.pointerType + ':' + e.target.tagName + '@' + Math.round(performance.now())), true); document.addEventListener('click', e => window.__t.push('click:' + e.target.tagName + '@' + Math.round(performance.now())), true); 1`);
  119. if (!(await shows('#loginbutton'))) await page.click('button.ident-toggle');
  120. await page.waitFor(`(() => { const e = document.querySelector('#loginbutton'); return !!e && e.getBoundingClientRect().width > 0; })()`, { label: 'login button shown' }).catch(async (e) => { await page.click('button.ident-toggle'); await sleep(1500); console.log('after 2nd click open:', await page.evaluate(`document.querySelector('#ident-panel').matches(':popover-open')`), 'toggle rect', J(await page.evaluate(`(() => { const r = document.querySelector('button.ident-toggle').getBoundingClientRect(); const e = document.elementFromPoint(r.left + r.width/2, r.top + r.height/2); return [r.left, r.top, r.width, r.height, e && e.tagName + '.' + e.className, innerWidth, innerHeight, document.hasFocus()]; })()`))); console.log('EVENTS', J(await page.evaluate('window.__t'))); console.log('DIAG', await page.evaluate(`J = JSON.stringify; J({ href: location.href, tog: !!document.querySelector('button.ident-toggle'), panel: !!document.querySelector('#ident-panel'), open: document.querySelector('#ident-panel') && document.querySelector('#ident-panel').matches(':popover-open'), lb: !!document.querySelector('#loginbutton'), w: innerWidth, html: (document.querySelector('ident-menu')||{}).outerHTML })`), page.dumpConsole()); throw e; });
  121. await page.click('#loginbutton');
  122. await page.waitForSelector('#chooselist', { timeout: 30000 }); await hydrated(); await page.click('#chooselist li:nth-child(1) .choose');
  123. await page.waitForSelector('#nameform', { timeout: 30000 }); await hydrated(); await page.type('#displayname', 'alice'); await page.click('#namesave');
  124. await page.waitFor('!document.querySelector("#nameform")', { label: 'name saved' });
  125. await page.waitForSelector('#createform', { timeout: 30000 }); await hydrated();
  126. await page.type('#slug', 'alpha'); await page.type('#description', 'The first repository'); await page.click('#createsave');
  127. await page.waitFor('/Created .alpha./.test(document.body.innerText)', { label: 'repo alpha created', timeout: 30000 }).catch(async (e) => { console.log('DIAG2', await page.evaluate('location.href + " | " + document.body.innerText.slice(0, 600)'), page.dumpConsole().slice(-800)); throw e; });
  128. const work = join(STORE, 'work'); mkdirSync(work, { recursive: true });
  129. const git = (...a) => execFileSync('git', ['-C', work, '-c', 'user.name=t', '-c', '[email protected]', ...a], { stdio: 'pipe' }).toString();
  130. git('init', '-q', '-b', 'main'); mkdirSync(join(work, 'src'));
  131. writeFileSync(join(work, 'README.md'), '# Alpha project\n\nSome **strong** text with `code` and a [link](https://example.org/x).\n\n- one\n- two\n\n```\nlet x = 1 < 2\n```\n');
  132. writeFileSync(join(work, 'src/a.txt'), 'line one\nline two\n');
  133. git('add', '-A'); git('commit', '-q', '-m', 'first');
  134. writeFileSync(join(work, 'src/a.txt'), 'line one\nline two changed\nline three\n'); git('add', '-A'); git('commit', '-q', '-m', 'second');
  135. git('push', '-q', '-f', join(STORE, 'git', 'alpha.git'), 'main');
  136. const sha = git('rev-parse', 'HEAD').trim(); process.env.E2E_SHA = sha;
  137. console.log('tag', TAG, 'app', APP, 'sha', sha);
  138. await walk(390, true); await walk(1280, true);
  139. // signed out: drop the gitoria session cookie
  140. const cks = (await page.send('Network.getAllCookies')).cookies.filter(c => /gitoria/.test(c.domain) || /^gitoriasid/.test(c.name));
  141. for (const c of cks) await page.send('Network.deleteCookies', { name: c.name, domain: c.domain, path: c.path });
  142. await walk(390, false);
  143. const bad = results.filter(r => (r.w < 600 && r.tapsSmall > 0) || r.scrollWidth > r.w || r.inputsSmall > 0 || r.boxesOver > 0);
  144. const desk = results.filter(r => r.w >= 600 && r.tapsSmall > 0).length; console.log('1280 audits with a target under 44 px (the theme is denser there on purpose):', desk);
  145. console.log(`SUMMARY ${TAG}: ${results.length} measurements, ${bad.length} with taps<44 / wider than screen / inputs<16 / boxes over`);
  146. for (const r of bad) console.log(' BAD', J(r));
  147. const mfail = marks.filter(m => !m.ok); console.log(`MENU MARKER ${TAG}: ${marks.length} checks, ${mfail.length} failed`); if (mfail.length) process.exitCode = 1;
  148. report('end'); console.log('console errors counted (tunnel network noise left out):', seen.size);
  149. writeFileSync(join(SHOTS, `${TAG}-results.json`), J(results, null, 1));
  150. await page.send('Emulation.clearDeviceMetricsOverride'); await page.send('Emulation.setTouchEmulationEnabled', { enabled: false });
  151. await page.goto('about:blank');
  152. } catch (e) { console.log('E2E ERROR', e.stack || e); console.log('SERVER LOG', slog().slice(-2500)); process.exitCode = 1; }
  153. finally {
  154. try { if (process.env.E2E_RESTORE && browserConn) await browserConn.send('Target.activateTarget', { targetId: process.env.E2E_RESTORE }); } catch {}
  155. try { server && server.kill('SIGTERM'); } catch {} try { ident && ident.stop && ident.stop(); } catch {}
  156. await sleep(500); process.exit(process.exitCode || 0);
  157. }

Branches

Latest commits

  • 00517fafgitoria: shell 404 page for unknown paths (catch-all route, status 404, JSON 404 under /api), 390 gate checksMG
  • d9e977f0reports/MG-mobile.md, LOGMG
  • 2f2725actests/browser.mjs: commit-row check (one row, centred date)MG
  • 4df1ea01tests/browser.mjs: MG phone checks (list first, no dead strip, one branch heading, tab grid, commit rows, PR title row, ticket columns, wrapping commands)MG
  • c52424e9gitoria mobile: repo list before the forms, 3x2 tab grid, no duplicate branch heading, ordered commit rows, aligned ticket rows, pull title on its own row, wrapping clone commands, no dead strip under formsMG
  • 3a95252dG3: cache parsed README blocks by sha256 of the text (bounded LRU), reportmre
  • 570138cddeploy: security gate (tests/security.mjs)mre
  • da6b20fcgitoria SG: security audit fixes (uploadMax 0, Secure cookie on https, session rotation at login, nosniff on function routes, no identity in page data) + tests/security.mjs gate + reportmre
  • f98c981fgitoria B1: report wordingmre
  • c6364cedgitoria B1: compact Markdown blocks (one kind flag per block/span, empty and false fields omitted); same rendered HTML, page values -67%mre
  • cd99d2feWIP gitoria#22: always render the repo level's slot (missing-repo boot hang), pages render nothing without a repo; hydration diagnosis in reports/G2-hydrate.mdmre
  • e5404b9breport: commit idsmre
  • 63cfa21ereports/G2-repotabs.mdmre
  • 9b0516fdgitoria#22: mark the tab underline functional (check-theme), chain E2E: serve/measure split, bring the lisbeth tab to frontmre
  • 19bc1df8gitoria#22: all repo pages under ONE layout level (components/repo.hl, hl:web D-CHAIN): a tab click replaces only the page in the slot; head and tab nav stay the same DOM nodesmre
  • 40658417tests/browser.mjs: wait for the page to be live (hydrated) before clicking Merge — a click on the server-rendered button before the client mounted was lost (flaky 'Clashing change' under load)mre
  • 48a6154bre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • e972e8d7tests: short-id-switch (GITORIA_SWITCH_IDENT_PORT/_PORT) and ssh tunnel (GITORIA_GATE_TUNNEL_PORT) ports from env, defaults unchangedmre
  • f06f5349re-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • c7d3cc87docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre