gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainfe209ffeMerge branch 'w56-owner-members' into mainGitoriamain/tests/person-approval.mjs

30.9 KB

  1. import { requiredPort, requiredPortRange } from './gate-ports.mjs';
  2. // tests/person-approval.mjs — Person approval and app-or-person merge requirements.
  3. // Adapted from the member merge gate: isolated ident, storage, real git and browser clicks.
  4. // GITORIA_PA_PORT (app; +1 receiver, +4 ident), GITORIA_GATE_CHROME (browser range).
  5. // HL_CDP_URL optionally attaches to the shared Chrome under its lock, with before/after target evidence.
  6. import { spawn, execFileSync } from 'node:child_process';
  7. import { request, createServer } from 'node:http';
  8. import { mkdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';
  9. import { dirname, join, resolve } from 'node:path';
  10. import { fileURLToPath } from 'node:url';
  11. import { startIdent } from './identkit.mjs';
  12. import { launchBrowser } from './cdp.mjs';
  13. const HERE = dirname(fileURLToPath(import.meta.url));
  14. const APP = resolve(HERE, '..');
  15. const CHROME = requiredPortRange('GITORIA_GATE_CHROME');
  16. const PORT = requiredPort('GITORIA_PA_PORT'), RPORT = PORT + 1, IDENT_PORT = process.env.GITORIA_PA_IDENT_PORT ? requiredPort('GITORIA_PA_IDENT_PORT') : PORT + 4;
  17. const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  18. const STORE = join(APP, '.scratch/person-approval-store');
  19. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  20. let passes = 0, failures = 0;
  21. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };
  22. const got = [];
  23. const receiver = createServer((req, res) => { const c = []; req.on('data', d => c.push(d)); req.on('end', () => { got.push({ path: req.url, headers: req.headers, body: Buffer.concat(c).toString('utf8') }); if (req.url === '/api/connect/exchange') { res.setHeader('content-type', 'application/json'); res.end(J({ key: 'tktc_w53_gate', project: 'w53', title: 'W53 tickets', api: `http://127.0.0.1:${RPORT}/api/projects/w53` })); return; } res.statusCode = 204; res.end(); }); });
  24. await new Promise(r => receiver.listen(RPORT, '127.0.0.1', r));
  25. function raw(method, path, { host = `localhost:${PORT}`, headers = {}, body = null, cookie = null } = {}) {
  26. return new Promise((res, rej) => {
  27. const h = { host, ...headers }; if (cookie) h.cookie = cookie;
  28. if (body !== null) h['content-length'] = Buffer.byteLength(body);
  29. const r = request({ host: '127.0.0.1', port: PORT, method, path, headers: h }, (m) => { const c = []; m.on('data', d => c.push(d)); m.on('end', () => res({ status: m.statusCode, headers: m.headers, body: Buffer.concat(c).toString('utf8') })); });
  30. r.on('error', rej); if (body !== null) r.write(body); r.end();
  31. });
  32. }
  33. const get = (path, o = {}) => raw('GET', path, o);
  34. const errOf = (r) => { try { return JSON.parse(r.body).error; } catch { return {}; } };
  35. let server = null, log = '';
  36. async function up() { for (let i = 0; i < 960; i++) { try { if ((await get('/api/repos')).status === 200) return; } catch {} await sleep(250); } throw new Error('gitoria did not come up\n' + log); }
  37. const stop = async () => { if (server) { const p = server; server = null; p.kill(); await new Promise(r => p.once('exit', r)); } };
  38. let ident;
  39. let browser, pg, mirror, beforePages, chromeLock;
  40. try {
  41. rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  42. const probeEnv = { ...process.env, GITORIA_STORAGE: join(STORE, 'probe-db'), GITORIA_GIT: join(STORE, 'probe-git') };
  43. execFileSync(join(APP, 'bin/hybriel'), ['tests/person-approval-seed.hl'], { cwd: APP, env: probeEnv, stdio: ['ignore', 'pipe', 'pipe'] });
  44. const probeLines = execFileSync(join(APP, 'bin/hybriel'), ['tests/person-approval-probe.hl'], { cwd: APP, env: probeEnv, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim().split('\n');
  45. const probe = JSON.parse(probeLines.at(-1));
  46. check('indexed approval reads and withdrawal keep other PRs', probe.indexed && probe.withdrawn && probe.isolated);
  47. check('choices include owner, repo member, org owner and org member exactly once', J(probe.choices.map(u => u.name).sort()) === J(['Owner', 'Repo member', 'Org owner', 'Org member'].sort()));
  48. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  49. const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]'), carol = await ident.signIn('[email protected]');
  50. const BASE = `http://localhost:${PORT}`;
  51. const app = await ident.registerApp(alice, 'gitoria (member-merge gate)', [BASE]);
  52. const GIT = join(STORE, 'git');
  53. const env = { GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_GIT: GIT, IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: app.key, IDENT_API_SECRET: app.secret };
  54. server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  55. env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: BASE, GITORIA_SSH_SECRET: 'sshsecret-mm-gate', GITORIA_TICKETS_URL: `http://127.0.0.1:${RPORT}`, GITORIA_APP_HOSTS: `http://127.0.0.1:${RPORT}`, GITORIA_EVENTS_TICK: '0.3', ...env } });
  56. writeFileSync(join(STORE, 'pids.txt'), `gitoria ${server.pid}\nident ${ident.proc.pid}\n`);
  57. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  58. await up();
  59. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  60. const login = async (who) => { const ck = cookieOf(await get('/')); const cb = await get('/login/callback?ident_code=' + await ident.selectorCode(who, app, BASE) + '&next=%2F', { cookie: ck }); return { cookie: cookieOf(cb) || ck }; };
  61. let n = 0;
  62. const face = async (who, event, payload) => { const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: who && who.cookie, body: J({ t: 'emit', i: ++n, event, payload }) }); let j = null; try { j = JSON.parse(r.body); } catch {} return j && j.value; };
  63. const A = await login(alice), B = await login(bob), C = await login(carol);
  64. await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']); await face(C, 'gitoriaSaveName', ['Carol']);
  65. const tA = (await face(A, 'gitoriaMakeToken', ['a'])).token, tB = (await face(B, 'gitoriaMakeToken', ['b'])).token, tC = (await face(C, 'gitoriaMakeToken', ['c'])).token;
  66. const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });
  67. const genv = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_GLOBAL: '/dev/null', GIT_AUTHOR_NAME: 'a', GIT_AUTHOR_EMAIL: 'a@a', GIT_COMMITTER_NAME: 'a', GIT_COMMITTER_EMAIL: 'a@a' };
  68. const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });
  69. const bare = (...a) => execFileSync('git', a, { cwd: join(GIT, 'mm.git'), encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] }).trim();
  70. const push = (...refs) => { try { g('push', '-q', `http://a:${tA}@mm.localhost:${PORT}/mm.git`, ...refs); return true; } catch { return false; } };
  71. const sha = () => g('rev-parse', 'HEAD').trim();
  72. const mkPr = (branch, title) => { g('checkout', '-q', 'main'); g('checkout', '-q', '-b', branch); writeFileSync(join(W, branch + '.txt'), branch + '\n'); g('add', '-A'); g('commit', '-q', '-m', '|||PR ' + title); const s = sha(); push(branch); return s; };
  73. g('init', '-q', '-b', 'main'); writeFileSync(join(W, 'README.md'), '# t\n'); g('add', '-A'); g('commit', '-q', '-m', 'init');
  74. check('alice creates "mm", pushes main', !!(await face(A, 'gitoriaCreate', ['mm', 'm'])).repo && push('main'));
  75. const added = await face(A, 'gitoriaChangeMember', ['mm', 'Bob', true]);
  76. check('alice adds Bob as a member (Carol is not)', added && added.members && added.members.length === 1, J(added));
  77. const kApp = await face(A, 'gitoriaAppAdd', ['mm', 'Kunibert', `http://127.0.0.1:${RPORT}/a`]);
  78. const tApp = JSON.parse((await raw('POST', '/api/apps/token', { host: `mm.localhost:${PORT}`, headers: { authorization: 'Bearer ' + kApp.key } })).body).token;
  79. const idK = (kApp.rows.find(x => x.name === 'Kunibert') || {}).id;
  80. check('an app (Kunibert) is connected to mm and has a token', /^gak_/.test(kApp.key || '') && !!tApp && !!idK);
  81. const HOST = `mm.localhost:${PORT}`;
  82. const merge = (token, num, body = null) => raw('POST', `/api/pulls/${num}/merge`, { host: HOST, headers: { ...(token ? { authorization: 'Bearer ' + token } : {}), 'content-type': 'application/json' }, body });
  83. const put = (sha_, state) => raw('PUT', '/api/statuses/' + sha_, { host: HOST, headers: { authorization: 'Bearer ' + tApp, 'content-type': 'application/json' }, body: J({ context: 'ci', state, title: 't', summary: '', url: null }) });
  84. const prNum = async (s) => { const l = JSON.parse((await raw('GET', '/api/pulls?state=all', { host: HOST, headers: { authorization: 'Bearer ' + tApp } })).body).pulls; const p = l.find(x => x.head === s || x.sha === s); return p ? p.number : null; };
  85. const s1 = mkPr('f1', 'person approval'), n1 = await prNum(s1);
  86. const s2 = mkPr('f2', 'app only'), n2 = await prNum(s2);
  87. const pull = async (num = n1) => JSON.parse((await get('/api/pulls/' + num, { host: HOST })).body);
  88. const settings = (await get('/settings', { host: HOST, cookie: A.cookie })).body;
  89. writeFileSync(join(STORE, 'settings.html'), settings);
  90. // Resolve public user ids through the owner-only select, never by position.
  91. const choices = [...settings.matchAll(/<option value="([^"]+)"[^>]*>([^<]+)<\/option>/g)];
  92. const aliceId = choices.find(x => x[2] === 'Alice')?.[1];
  93. check('settings lists owner and member as people by stable id', !!aliceId && choices.some(x => x[2] === 'Bob') && !choices.some(x => x[2] === 'Carol'));
  94. await face(A, 'gitoriaRequiredAdd', ['mm', idK, 'ci']);
  95. const req = await face(A, 'gitoriaRequiredPersonAdd', ['mm', aliceId]);
  96. check('owner requires app context and a person', req?.rows?.length === 2, J(req));
  97. check('member cannot change required people', !!(await face(B, 'gitoriaRequiredPersonAdd', ['mm', aliceId]))?.error);
  98. check('owner cannot require an unknown person', !!(await face(A, 'gitoriaRequiredPersonAdd', ['mm', 'unknown']))?.error);
  99. const blocked = await merge(tA, n1);
  100. const details = errOf(blocked).details;
  101. check('no status or approval: 422 names both alternatives and preserves detail rows', blocked.status === 422 && errOf(blocked).code === 'checks_failed' && details?.length === 1 && details[0].app.id === idK && !details[0].approval && errOf(blocked).approval?.users[0].id === aliceId && errOf(blocked).approval.state === 'missing' && / or an approval from Alice/.test(errOf(blocked).message), blocked.body);
  102. const btnClass = async () => ((await get('/pulls/' + n1, { host: HOST, cookie: A.cookie })).body.match(/id="mergepull" class="([^"]+)"/) || [])[1];
  103. check('PR Merge button is off with neither alternative met', await btnClass() === 'nomerge');
  104. check('list Merge button is off', !/class="quiet mergepr"/.test((await get('/pulls', { host: HOST, cookie: A.cookie })).body));
  105. check('non-member and anonymous server clicks refused', !!(await face(C, 'gitoriaPrApprove', ['mm', '' + n1, s1, true]))?.error && !!(await face(null, 'gitoriaPrApprove', ['mm', '' + n1, s1, true]))?.error);
  106. const outsider = (await get('/pulls/' + n1, { host: HOST, cookie: C.cookie })).body.replace(/<script[\s\S]*?<\/script>/g, '');
  107. check('non-member sees no Approve button', !/id="approve-pull"/.test(outsider));
  108. const appForge = await raw('POST', '/__hl/emit', { headers: { authorization: 'Bearer ' + tApp, 'content-type': 'application/json' }, body: J({ t: 'emit', i: ++n, event: 'gitoriaPrApprove', payload: ['mm', '' + n1, s1, true] }) });
  109. check('app token cannot approve as a person', !JSON.parse(appForge.body)?.value?.view && (await pull()).approvals.length === 0);
  110. const member = await face(B, 'gitoriaPrApprove', ['mm', '' + n1, s1, true]);
  111. check('unlisted member can approve but does not satisfy required people', member?.view?.approvals?.length === 1 && (await merge(tA, n1)).status === 422);
  112. const yes = await face(A, 'gitoriaPrApprove', ['mm', '' + n1, s1, true]);
  113. check('owner approves current head; Merge becomes available', yes?.view?.approved === true && yes.view.mergeClass === 'mergepr' && yes.view.approvalLabel === 'Withdraw approval', J(yes).slice(0, 250));
  114. check('API adds people separately and keeps legacy required app-only', (await pull()).approvals.some(a => a.user.id === aliceId && a.head === s1 && a.current && typeof a.created === 'string') && (await pull()).approvers.some(r => r.user?.id === aliceId) && J((await pull()).required) === J([{app:{id:idK,name:'Kunibert'},context:'ci'}]));
  115. check('list and second visit agree approval allows merge', await btnClass() === 'mergepr' && /class="quiet mergepr"/.test((await get('/pulls', { host: HOST, cookie: A.cookie })).body));
  116. await face(A, 'gitoriaPrApprove', ['mm', '' + n1, s1, false]);
  117. check('withdraw removes current approval and blocks merge', (await merge(tA, n1)).status === 422 && !(await pull()).approvals.some(a => a.user.id === aliceId));
  118. await face(A, 'gitoriaPrApprove', ['mm', '' + n1, s1, true]);
  119. g('checkout', '-q', 'f1'); g('commit', '-q', '--allow-empty', '-m', 'new head'); const sNew = sha(); push('f1');
  120. const stale = await pull();
  121. check('push makes every old approval stale and blocks merge', stale.head === sNew && stale.approvals.every(a => !a.current) && (await merge(tA, n1)).status === 422 && await btnClass() === 'nomerge');
  122. check('old tab cannot approve new unseen head', !!(await face(A, 'gitoriaPrApprove', ['mm', '' + n1, s1, true]))?.error);
  123. check('page calls old approval an earlier head', /approved an earlier head/.test((await get('/pulls/' + n1, { host: HOST, cookie: A.cookie })).body));
  124. await put(sNew, 'success');
  125. check('app success alone meets mixed requirements', await btnClass() === 'mergepr' && (await merge(tA, n1)).status === 200);
  126. const required = (await face(A, 'gitoriaRequiredPersonAdd', ['mm', aliceId])).rows;
  127. await face(A, 'gitoriaRequiredRemove', ['mm', required.find(r => r.name === 'Kunibert · ci').id]);
  128. await put(s2, 'success'); const personOnly = await merge(tA, n2);
  129. check('person-only error has empty legacy details and separate approval', personOnly.status === 422 && J(errOf(personOnly).details) === '[]' && errOf(personOnly).approval?.users[0]?.id === aliceId && (await pull(n2)).required.length === 0);
  130. await face(A, 'gitoriaPrApprove', ['mm', '' + n2, s2, true]);
  131. check('person-only approval permits merge', (await merge(tA, n2)).status === 200);
  132. await face(A, 'gitoriaRequiredRemove', ['mm', required.find(r => r.name === 'Person · Alice').id]);
  133. const s3 = mkPr('f3', 'no requirements'), n3 = await prNum(s3);
  134. check('no requirements behaves as before', (await merge(tA, n3)).status === 200);
  135. await face(A, 'gitoriaRequiredAdd', ['mm', idK, 'ci']);
  136. const s4 = mkPr('f4', 'app requirements'), n4 = await prNum(s4);
  137. await face(A, 'gitoriaPrApprove', ['mm', '' + n4, s4, true]);
  138. const appOnly = await merge(tA, n4);
  139. check('app-only error keeps v1.5.1 details with no approval field', appOnly.status === 422 && !Object.hasOwn(errOf(appOnly), 'approval') && J(errOf(appOnly).details) === J([{app:{id:idK,name:'Kunibert'},context:'ci',state:'missing'}]));
  140. await put(s4, 'success');
  141. check('app-only success behaves as before', (await merge(tA, n4)).status === 200);
  142. // A real tickets connection makes notifyPush read the new marker BEFORE syncAndRaise numbers it.
  143. const connect = await get('/settings/connect', { host: HOST, cookie: A.cookie });
  144. const connectState = new URL(connect.headers.location).searchParams.get('state');
  145. const connected = await get('/settings/connected?code=w53&state=' + encodeURIComponent(connectState), { host: HOST, cookie: A.cookie });
  146. check('tickets-connected regression uses the real connect callback', connected.status === 302 && got.some(r => r.path === '/api/connect/exchange'));
  147. await face(A, 'gitoriaRequiredPersonAdd', ['mm', aliceId]);
  148. const ticketSha = mkPr('tickets-pr', 'tickets-connected approval'), ticketNumber = await prNum(ticketSha);
  149. check('tickets-connected push gets a live PR number', Number.isInteger(ticketNumber) && ticketNumber > 0);
  150. const ticketApproval = await face(A, 'gitoriaPrApprove', ['mm', '' + ticketNumber, ticketSha, true]);
  151. check('listed person approves the tickets-connected PR', ticketApproval?.view?.approved === true);
  152. const ticketList = (await get('/pulls', { host: HOST, cookie: A.cookie })).body;
  153. const ticketRow = [...ticketList.matchAll(/<li>[\s\S]*?<\/li>/g)].find(m => m[0].includes('value="' + ticketSha + '"'))?.[0] || '';
  154. check('warm tickets-connected list sees the live-number approval', /class="quiet mergepr"/.test(ticketRow) && !ticketRow.includes('Merge waits for'));
  155. check('tickets-connected PR merges with listed-person approval', (await merge(tA, ticketNumber)).status === 200);
  156. const ticketRequirements = (await face(A, 'gitoriaRequiredPersonAdd', ['mm', aliceId])).rows;
  157. await face(A, 'gitoriaRequiredRemove', ['mm', ticketRequirements.find(r => r.name === 'Person · Alice').id]);
  158. // Browser gate: real input, head changes during use, reload and Back.
  159. const s5 = mkPr('f5', 'browser approval'), n5 = await prNum(s5);
  160. await face(A, 'gitoriaRequiredRemove', ['mm', (await face(A, 'gitoriaRequiredAdd', ['mm', idK, 'ci'])).rows[0].id]);
  161. await face(A, 'gitoriaRequiredPersonAdd', ['mm', aliceId]);
  162. if (process.env.HL_CDP_URL) {
  163. chromeLock = spawn('timeout', ['600', 'flock', '/media/STORAGE/claude-scratch/atlas/lisbeth.lock', 'sh', '-c', 'echo locked; cat'], { cwd: APP, stdio: ['pipe', 'pipe', 'inherit'] });
  164. await new Promise((resolve, reject) => { chromeLock.stdout.once('data', resolve); chromeLock.once('exit', () => reject(new Error('Chrome lock unavailable'))); });
  165. beforePages = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');
  166. writeFileSync(join(STORE, 'chrome-before.json'), J(beforePages.map(t => ({ id: t.id, title: t.title, url: t.url.split('?')[0] }))));
  167. }
  168. browser = await launchBrowser({ debugPortRange: CHROME });
  169. if (browser.proc) writeFileSync(join(STORE, 'browser-pid.txt'), String(browser.proc.pid));
  170. pg = await browser.newPage();
  171. await pg.send('Network.enable');
  172. await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: 'mm.localhost', path: '/' });
  173. await pg.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  174. await pg.goto(`http://mm.localhost:${PORT}/settings`);
  175. await pg.waitFor(`!!window.__hl && window.__hl.socket?.readyState === 1 && !!document.querySelector('#require-person')`, { timeout: 30000 });
  176. const key = async (name) => {
  177. const code = name === ' ' ? 'Space' : name;
  178. const windowsVirtualKeyCode = name === 'Tab' ? 9 : name === 'Enter' ? 13 : 32;
  179. const text = name === 'Enter' ? '\r' : name === ' ' ? ' ' : '';
  180. await pg.send('Input.dispatchKeyEvent', { type: 'keyDown', key: name, code, windowsVirtualKeyCode, ...(text ? { text, unmodifiedText: text } : {}) });
  181. await pg.send('Input.dispatchKeyEvent', { type: 'keyUp', key: name, code, windowsVirtualKeyCode });
  182. };
  183. const tabTo = async (selector) => {
  184. await pg.send('Page.bringToFront');
  185. for (let i = 0; i < 100; i++) {
  186. await key('Tab');
  187. if (await pg.evaluate(`document.activeElement === document.querySelector(${J(selector)})`)) return;
  188. }
  189. throw new Error('Tab did not reach ' + selector);
  190. };
  191. if (browser.owned) {
  192. mirror = await browser.newPage(); await mirror.goto(`http://mm.localhost:${PORT}/settings`);
  193. await mirror.waitFor(`!!window.__hl && window.__hl.socket?.readyState === 1 && !!document.querySelector('#require-person')`);
  194. }
  195. await pg.click('#requiredlist button');
  196. await pg.waitFor(`document.querySelectorAll('#requiredlist li').length === 0`);
  197. check('settings click removes required person', (await pull(n5)).approvers.length === 0);
  198. if (mirror) { await mirror.waitFor(`document.querySelectorAll('#requiredlist li').length === 0`); check('second Settings tab receives person removal', true); }
  199. await tabTo('#require-person'); await key('Enter');
  200. await pg.waitFor(`document.querySelectorAll('#requiredlist li').length === 1`);
  201. check('settings submit adds selected owner by id', (await pull(n5)).approvers[0]?.user?.id === aliceId);
  202. if (mirror) { await mirror.waitFor(`document.querySelectorAll('#requiredlist li').length === 1`); check('second Settings tab receives keyboard addition', true); }
  203. const settingsShot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  204. writeFileSync(join(STORE, 'settings-390.png'), Buffer.from(settingsShot.data, 'base64'));
  205. const visit = async () => { await pg.goto(`http://mm.localhost:${PORT}/pulls/${n5}`); writeFileSync(join(STORE, 'browser.html'), await pg.html()); await pg.waitFor(`!!window.__hl && window.__hl.socket?.readyState === 1 && !!document.querySelector('#approve-pull')`, { timeout: 30000 }); };
  206. if (mirror) {
  207. await mirror.goto(`http://mm.localhost:${PORT}/pulls/${n5}`);
  208. await mirror.waitFor(`!!window.__hl && window.__hl.socket?.readyState === 1 && !!document.querySelector('#approve-pull')`);
  209. const personRequirement = (await face(A, 'gitoriaRequiredPersonAdd', ['mm', aliceId])).rows.find(r => r.name === 'Person · Alice').id;
  210. await face(A, 'gitoriaRequiredRemove', ['mm', personRequirement]);
  211. await mirror.waitFor(`document.querySelector('#mergepull').className === 'mergepr'`);
  212. check('person requirement removal updates another open PR tab', true);
  213. await face(A, 'gitoriaRequiredPersonAdd', ['mm', aliceId]);
  214. await mirror.waitFor(`document.querySelector('#mergepull').className === 'nomerge'`);
  215. check('person requirement addition blocks another open PR tab', true);
  216. }
  217. for (const [width, height] of [[390, 844], [800, 1280], [1280, 800], [1280, 900]]) {
  218. await pg.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width === 390 });
  219. await visit();
  220. check(`${width}x${height}: initial Approve and blocked Merge`, await pg.text('#approve-pull') === 'Approve' && !(await pg.box('#mergepull')));
  221. await tabTo('#approve-pull'); await key('Enter');
  222. await pg.waitFor(`document.querySelector('#approve-pull').textContent === 'Withdraw approval'`);
  223. if (mirror) { await mirror.waitFor(`document.querySelector('#approve-pull').textContent === 'Withdraw approval'`); check(`${width}: second PR tab receives approval`, true); }
  224. check(`${width}x${height}: keyboard approval enables Merge and shows name/head/time`, !!(await pg.box('#mergepull')) && /Alice/.test(await pg.text('#person-approvals')));
  225. await visit();
  226. check(`${width}x${height}: reload retains approval and fits viewport`, await pg.text('#approve-pull') === 'Withdraw approval' && await pg.evaluate('document.documentElement.scrollWidth <= innerWidth'));
  227. const { data } = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  228. writeFileSync(join(STORE, `approval-${width}x${height}.png`), Buffer.from(data, 'base64'));
  229. await tabTo('#approve-pull'); await key(' ');
  230. await pg.waitFor(`document.querySelector('#approve-pull').textContent === 'Approve'`);
  231. if (mirror) { await mirror.waitFor(`document.querySelector('#approve-pull').textContent === 'Approve'`); check(`${width}: second PR tab receives withdrawal`, true); }
  232. check(`${width}x${height}: keyboard withdraw disables Merge immediately`, !(await pg.box('#mergepull')));
  233. }
  234. // Keep /pulls open while another session request changes requirements and approvals.
  235. // In shared Chrome this reuses our one plain tab; automated gates also keep the PR mirror open.
  236. for (const [width, height] of [[390, 844], [800, 1280], [1280, 800], [1280, 900]]) {
  237. await pg.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width === 390 });
  238. await pg.goto(`http://mm.localhost:${PORT}/pulls`);
  239. await pg.waitFor(`!!window.__hl && window.__hl.socket?.readyState === 1 && !!document.querySelector('#pulllist')`);
  240. const row = `Array.from(document.querySelectorAll('#pulllist li')).find(r => r.querySelector('button')?.value === ${J(s5)})`;
  241. const enabled = `!!(${row})?.querySelector('button.mergepr')`;
  242. const waiting = `(${row})?.textContent.includes('Merge waits for')`;
  243. await pg.waitFor(`!(${enabled}) && ${waiting}`);
  244. const personId = (await face(A, 'gitoriaRequiredPersonAdd', ['mm', aliceId])).rows.find(r => r.name === 'Person · Alice').id;
  245. await face(A, 'gitoriaRequiredRemove', ['mm', personId]);
  246. await pg.waitFor(`${enabled} && !(${waiting})`);
  247. check(`${width}: open pulls list removes person blocker and enables Merge`, true);
  248. await face(A, 'gitoriaRequiredPersonAdd', ['mm', aliceId]);
  249. await pg.waitFor(`!(${enabled}) && ${waiting}`);
  250. check(`${width}: open pulls list adds person blocker and hides Merge`, true);
  251. await face(A, 'gitoriaPrApprove', ['mm', '' + n5, s5, true]);
  252. await pg.waitFor(`${enabled} && !(${waiting})`);
  253. check(`${width}: approval updates open pulls list`, true);
  254. await face(A, 'gitoriaPrApprove', ['mm', '' + n5, s5, false]);
  255. await pg.waitFor(`!(${enabled}) && ${waiting}`);
  256. check(`${width}: withdrawal updates open pulls list`, true);
  257. const appReq = (await face(A, 'gitoriaRequiredAdd', ['mm', idK, 'ci'])).rows.find(r => r.name === 'Kunibert · ci').id;
  258. await pg.waitFor(`(${row})?.textContent.includes('Kunibert') && (${row})?.textContent.includes(' or an approval')`);
  259. check(`${width}: app requirement updates open pulls list`, true);
  260. await face(A, 'gitoriaRequiredRemove', ['mm', appReq]);
  261. await pg.waitFor(`!(${row})?.textContent.includes('Kunibert') && ${waiting}`);
  262. check(`${width}: app requirement removal updates open pulls list`, true);
  263. check(`${width}: pulls list fits viewport`, await pg.evaluate('document.documentElement.scrollWidth <= innerWidth'));
  264. const shot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  265. writeFileSync(join(STORE, `pulls-${width}x${height}.png`), Buffer.from(shot.data, 'base64'));
  266. }
  267. // Status PUTs must update already-open pages without a navigation or reload.
  268. await face(A, 'gitoriaRequiredAdd', ['mm', idK, 'ci']);
  269. await visit();
  270. check('open PR starts with no status badges', !(await pg.box('#pullstatuses')));
  271. await put(s5, 'pending');
  272. await pg.waitFor(`!!document.querySelector('#pullstatuses .pending')`);
  273. check('first status PUT reveals badges on an already-open PR', true);
  274. for (const [width, height] of [[390, 844], [800, 1280], [1280, 800], [1280, 900]]) {
  275. await pg.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width === 390 });
  276. for (const path of [`/pulls/${n5}`, '/pulls']) {
  277. await put(s5, 'pending');
  278. await pg.goto(`http://mm.localhost:${PORT}${path}`);
  279. const row = path === '/pulls' ? `Array.from(document.querySelectorAll('#pulllist li')).find(r => r.querySelector('button')?.value === ${J(s5)})` : `document.querySelector('#pullpage')`;
  280. const enabled = `!!(${row})?.querySelector('button.mergepr')`;
  281. await pg.waitFor(`!!window.__hl && window.__hl.socket?.readyState === 1 && (${row}) && !(${enabled})`);
  282. const shot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  283. writeFileSync(join(STORE, `status-pending-${path === '/pulls' ? 'list' : 'pr'}-${width}x${height}.png`), Buffer.from(shot.data, 'base64'));
  284. await put(s5, 'success');
  285. await pg.waitFor(enabled);
  286. if (path !== '/pulls') {
  287. await pg.waitFor(`!!document.querySelector('#pullstatuses .success') && !document.querySelector('#pullstatuses .pending')`);
  288. check(`${width}x${height}: open PR badge follows success PUT`, true);
  289. }
  290. check(`${width}x${height}: open ${path} enables Merge after pending to success PUT`, true);
  291. const after = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  292. writeFileSync(join(STORE, `status-success-${path === '/pulls' ? 'list' : 'pr'}-${width}x${height}.png`), Buffer.from(after.data, 'base64'));
  293. await put(s5, 'failure');
  294. await pg.waitFor(`!(${enabled})`);
  295. if (path !== '/pulls') {
  296. await pg.waitFor(`!!document.querySelector('#pullstatuses .failure') && !document.querySelector('#pullstatuses .success')`);
  297. check(`${width}x${height}: open PR badge follows failure PUT`, true);
  298. }
  299. check(`${width}x${height}: open ${path} hides Merge after failure PUT`, true);
  300. }
  301. }
  302. const statusReq = (await face(A, 'gitoriaRequiredAdd', ['mm', idK, 'ci'])).rows.find(r => r.name === 'Kunibert · ci');
  303. await face(A, 'gitoriaRequiredRemove', ['mm', statusReq.id]);
  304. await visit();
  305. await pg.click('#approve-pull'); await pg.waitFor(`document.querySelector('#approve-pull').textContent === 'Withdraw approval'`);
  306. g('checkout', '-q', 'f5'); g('commit', '-q', '--allow-empty', '-m', 'browser head changes'); push('f5');
  307. await visit();
  308. check('browser second head shows stale approval and blocks Merge', /approved an earlier head/.test(await pg.text('#person-approvals')) && await pg.text('#approve-pull') === 'Approve' && !(await pg.box('#mergepull')));
  309. await pg.click('#topulls'); await pg.waitForSelector('#pulllist'); await pg.send('Page.navigateToHistoryEntry', { entryId: (await pg.send('Page.getNavigationHistory')).entries.at(-2).id }); await pg.waitForSelector('#approve-pull');
  310. check('Back preserves the current head approval state', await pg.text('#approve-pull') === 'Approve');
  311. await pg.click('#approve-pull'); await pg.waitFor(`document.querySelector('#approve-pull').textContent === 'Withdraw approval'`);
  312. check('current head approval allows actual merge', (await merge(tA, n5)).status === 200);
  313. } catch (e) {
  314. check('the gate ran without an exception', false, String(e && e.stack || e));
  315. if (log) console.log(log.slice(-3000));
  316. if (pg) { console.log(pg.dumpConsole()); const shot = await pg.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(STORE, 'failure.png'), Buffer.from(shot.data, 'base64')); console.log('page error: ' + await pg.text('#pullerror') + ' settings: ' + await pg.text('#requirederror')); }
  317. } finally {
  318. try { if (mirror) await mirror.close(); if (pg) await pg.close(); if (browser) {
  319. if (browser.owned) await browser.close(); else browser.conn.close();
  320. } } catch {}
  321. if (beforePages) {
  322. const after = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');
  323. writeFileSync(join(STORE, 'chrome-after.json'), J(after.map(t => ({ id: t.id, title: t.title, url: t.url.split('?')[0] }))));
  324. check('real Chrome leaves original page targets only', after.every(t => beforePages.some(b => b.id === t.id)) && !after.some(t => t.id === pg?.targetId));
  325. }
  326. if (chromeLock) { chromeLock.stdin.end(); await new Promise(r => chromeLock.once('exit', r)); }
  327. await stop().catch(() => {});
  328. try { receiver.close(); } catch {}
  329. try { ident && ident.stop && await ident.stop(); } catch {}
  330. writeFileSync(join(STORE, 'server.log'), log);
  331. console.log(`\n${passes} passed, ${failures} failed`);
  332. process.exit(failures ? 1 : 0);
  333. }

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