gitoria

gitoria

All repositories: gitoria

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

53.0 KB

  1. import { requiredPort, requiredPortRange } from './gate-ports.mjs';
  2. // tests/repo-rename.mjs — Live owner rename, stable repo identity, old URLs and display names.
  3. // Isolated storage, ident, real Git transport and keyboard forms.
  4. // GITORIA_RENAME_PORT (app; +1 receiver, +2 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, lstatSync, readlinkSync, realpathSync } 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 HOSTNAME = process.env.HL_CDP_URL ? 'w54.localhost' : 'localhost';
  17. const PORT = requiredPort('GITORIA_RENAME_PORT'), RPORT = PORT + 1, IDENT_PORT = process.env.GITORIA_RENAME_IDENT_PORT ? requiredPort('GITORIA_RENAME_IDENT_PORT') : PORT + 2;
  18. 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')));
  19. const STORE = join(APP, '.scratch/repo-rename-store');
  20. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  21. let passes = 0, failures = 0;
  22. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };
  23. const got = [];
  24. 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(); }); });
  25. await new Promise(r => receiver.listen(RPORT, '127.0.0.1', r));
  26. function raw(method, path, { host = `${HOSTNAME}:${PORT}`, headers = {}, body = null, cookie = null } = {}) {
  27. return new Promise((res, rej) => {
  28. const h = { host, ...headers }; if (cookie) h.cookie = cookie;
  29. if (body !== null) h['content-length'] = Buffer.byteLength(body);
  30. 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') })); });
  31. r.on('error', rej); if (body !== null) r.write(body); r.end();
  32. });
  33. }
  34. const get = (path, o = {}) => raw('GET', path, o);
  35. const errOf = (r) => { try { return JSON.parse(r.body).error; } catch { return {}; } };
  36. let server = null, log = '';
  37. async function up() { for (let i = 0; i < 960; i++) { if (server.exitCode !== null || server.signalCode !== null) throw new Error('gitoria exited: ' + log); try { if ((await get('/api/repos')).status === 200) return; } catch {} await sleep(250); } throw new Error('gitoria did not come up\n' + log); }
  38. const stop = async () => { if (server) { const p = server; server = null; if (p.exitCode === null && p.signalCode === null) { p.kill(); await new Promise(r => p.once('exit', r)); } } };
  39. let ident;
  40. let browser, pg, mirror, beforePages, chromeLock, anon, bobPage;
  41. try {
  42. rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  43. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  44. const alice = await ident.signIn('[email protected]'), bob = await ident.signIn('[email protected]'), carol = await ident.signIn('[email protected]');
  45. const BASE = `http://${HOSTNAME}:${PORT}`;
  46. const app = await ident.registerApp(alice, 'gitoria (member-merge gate)', [BASE]);
  47. const GIT = join(STORE, 'git');
  48. const env = { GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_GIT: GIT, IDENT_URL: process.env.HL_CDP_URL ? `http://ident.${HOSTNAME}:${IDENT_PORT}` : ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: app.key, IDENT_API_SECRET: app.secret };
  49. server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  50. 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 } });
  51. writeFileSync(join(STORE, 'pids.txt'), `gitoria ${server.pid}\nident ${ident.proc.pid}\n`);
  52. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  53. await up();
  54. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  55. 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 }; };
  56. let n = 0;
  57. 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; };
  58. const A = await login(alice), B = await login(bob), C = await login(carol);
  59. await face(A, 'gitoriaSaveName', ['Alice']); await face(B, 'gitoriaSaveName', ['Bob']); await face(C, 'gitoriaSaveName', ['Carol']);
  60. const tA = (await face(A, 'gitoriaMakeToken', ['a'])).token, tB = (await face(B, 'gitoriaMakeToken', ['b'])).token, tC = (await face(C, 'gitoriaMakeToken', ['c'])).token;
  61. const derivedRepo = await face(A, 'gitoriaCreateRepo', ['', 'derived', '', false, ' Hyper Conductor ++ ']);
  62. check('repo derives a lowercase address from Name and trims the stored title', derivedRepo?.repo?.slug === 'hyper-conductor' && derivedRepo.repo.title === 'Hyper Conductor ++');
  63. const explicitRepo = await face(A, 'gitoriaCreateRepo', ['chosen-address', '', '', false, 'Another Name']);
  64. check('repo explicit Address stays independent from Name', explicitRepo?.repo?.slug === 'chosen-address' && explicitRepo.repo.title === 'Another Name');
  65. const derivedOrg = await face(A, 'gitoriaCreateOrg', ['', false, 'EinicherAI']);
  66. check('organization derives address separately from Name', derivedOrg?.org?.slug === 'einicherai' && derivedOrg.org.title === 'EinicherAI');
  67. check('runs of punctuation become one hyphen without edge hyphens', (await face(A, 'gitoriaCreateOrg', ['', false, ' !!! Team ++ 9 ??? ']))?.org?.slug === 'team-9');
  68. check('derived repo/org addresses share the existing namespace', !!(await face(A, 'gitoriaCreateOrg', ['', false, 'Hyper Conductor']))?.error && !!(await face(A, 'gitoriaCreateRepo', ['', '', '', false, 'EinicherAI']))?.error);
  69. check('empty derivations and overlong names are refused', !!(await face(A, 'gitoriaCreateOrg', ['', false, '!!!']))?.error && !!(await face(A, 'gitoriaCreateRepo', ['', '', '', false, 'x'.repeat(81)]))?.error);
  70. const createApi = body => raw('POST', '/api/repos', { headers: { authorization: 'Bearer ' + tA, 'content-type': 'application/json' }, body: J(body) });
  71. const apiNamed = await createApi({ name: 'api-explicit', title: 'API display name' });
  72. const apiDerived = await createApi({ name: '', title: 'API Auto Address' });
  73. check('POST /api/repos accepts title and explicit or derived addresses additively', apiNamed.status === 201 && JSON.parse(apiNamed.body).title === 'API display name' && apiDerived.status === 201 && JSON.parse(apiDerived.body).slug === 'api-auto-address');
  74. check('POST /api/repos validates title type and length', (await createApi({ name: 'bad-title-type', title: 12 })).status === 422 && (await createApi({ name: 'bad-title-length', title: 'x'.repeat(81) })).status === 422);
  75. check('only organization owner can edit its Name', !!(await face(B, 'gitoriaSetOrgTitle', ['einicherai', 'Stolen']))?.error && !!(await face(null, 'gitoriaSetOrgTitle', ['einicherai', 'Stolen']))?.error);
  76. await face(A, 'gitoriaSetOrgTitle', ['einicherai', 'EinicherAI renamed']);
  77. await face(A, 'gitoriaSetOrgPrivate', ['einicherai', true]);
  78. const privateOrgPage = await get('/', { host: `einicherai.${HOSTNAME}:${PORT}`, cookie: A.cookie });
  79. check('organization Name survives visibility changes and slug stays stable', privateOrgPage.body.includes('EinicherAI renamed') && privateOrgPage.body.includes('id="org-address-name"') && privateOrgPage.body.includes('einicherai'));
  80. await face(A, 'gitoriaSetOrgPrivate', ['einicherai', false]);
  81. check('organization Name validates plain text and length', !!(await face(A, 'gitoriaSetOrgTitle', ['einicherai', 'x'.repeat(81)]))?.error && !!(await face(A, 'gitoriaSetOrgTitle', ['einicherai', 'bad\nname']))?.error);
  82. check('organization Name can be cleared to its address', (await face(A, 'gitoriaSetOrgTitle', ['einicherai', '']))?.org?.heading === 'einicherai');
  83. await face(A, 'gitoriaSetOrgTitle', ['einicherai', 'EinicherAI renamed']);
  84. const orgPage = await get('/', { host: `einicherai.${HOSTNAME}:${PORT}`, cookie: A.cookie });
  85. check('organization heading, address and window title show saved Name', orgPage.body.includes('EinicherAI renamed') && orgPage.body.includes('id="org-address-name"') && orgPage.body.includes('<title>EinicherAI renamed · gitoria</title>'));
  86. const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });
  87. 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' };
  88. const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });
  89. const host = name => `${name}.${HOSTNAME}:${PORT}`;
  90. const at = (name, path = '/', cookie = A.cookie) => get(path, { host: host(name), cookie });
  91. const rename = (name, to, who = A, org = name.includes('/') ? name.split('/')[0] : '') => face(who, 'gitoriaRenameRepo', [name, to, org]);
  92. const title = (name, value, who = A) => face(who, 'gitoriaSetRepoTitle', [name, value]);
  93. const oldUrl = `http://a:${tA}@routger.${HOSTNAME}:${PORT}/routger.git`;
  94. g('init', '-q', '-b', 'main'); writeFileSync(join(W, 'README.md'), '# History retained\n'); g('add', '-A'); g('commit', '-q', '-m', 'first');
  95. const created = await face(A, 'gitoriaCreate', ['routger', 'rename gate']); const rid = created.repo.id;
  96. g('push', '-q', oldUrl, 'main'); const mainSha = g('rev-parse', 'HEAD').trim();
  97. g('checkout', '-q', '-b', 'feature'); g('commit', '-q', '--allow-empty', '-m', '|||PR retained pull'); const head = g('rev-parse', 'HEAD').trim(); g('push', '-q', oldUrl, 'feature');
  98. const added = await face(A, 'gitoriaChangeMember', ['routger', 'Bob', true]); const bobId = added.members[0].id;
  99. const appAdded = await face(A, 'gitoriaAppAdd', ['routger', 'Rename reviewer', `http://127.0.0.1:${RPORT}/a`]);
  100. const appId = appAdded.rows[0].id;
  101. const appToken = JSON.parse((await raw('POST', '/api/apps/token', { host: host('routger'), headers: { authorization: 'Bearer ' + appAdded.key } })).body).token;
  102. const putContext = async (sha, context) => raw('PUT', '/api/statuses/' + sha, { host: host('routger'), headers: { authorization: 'Bearer ' + appToken, 'content-type': 'application/json' }, body: J({ context, state: 'success' }) });
  103. await putContext(head, 'older-context'); await sleep(20);
  104. await putContext(mainSha, 'different-head-context');
  105. check('prefill reads newest app status across repo commits', (await face(A, 'gitoriaAppContext', ['routger', appId]))?.context === 'different-head-context');
  106. await sleep(20); await putContext(head, 'older-context');
  107. check('prefill follows updated existing status row', (await face(A, 'gitoriaAppContext', ['routger', appId]))?.context === 'older-context');
  108. const emptyApp = await face(A, 'gitoriaAppAdd', ['routger', 'No status yet', `http://127.0.0.1:${RPORT}/empty`]);
  109. const emptyAppId = emptyApp.rows.find(a => a.name === 'No status yet').id;
  110. check('app without statuses has empty context and non-owner cannot read suggestions', (await face(A, 'gitoriaAppContext', ['routger', emptyAppId]))?.context === '' && (await face(B, 'gitoriaAppContext', ['routger', appId])) == null);
  111. const api = (name, path) => raw('GET', path, { host: host(name), headers: { authorization: 'Bearer ' + appToken } });
  112. const pull = JSON.parse((await api('routger', '/api/pulls')).body).pulls[0];
  113. await face(A, 'gitoriaRequiredAdd', ['routger', appId, 'ci']);
  114. await face(A, 'gitoriaRequiredPersonAdd', ['routger', bobId]);
  115. const mixedRule = 'Merge is allowed when every app check above is success, or one of these people approved the current head.';
  116. const peopleRule = 'Merge needs an approval from one of these people.';
  117. const appsRule = 'Merge needs every app check above to be success.';
  118. const requirements = await face(A, 'gitoriaRequiredRead', ['routger']);
  119. check('Settings explains apps or people with clear form labels', (await at('routger', '/settings')).body.includes(mixedRule) && (await at('routger', '/settings')).body.includes('Require an app check') && (await at('routger', '/settings')).body.includes('Allow a person to approve'));
  120. await face(A, 'gitoriaRequiredRemove', ['routger', requirements.rows.find(r => !r.isPerson).id]);
  121. check('Settings explains people-only requirement', (await at('routger', '/settings')).body.includes(peopleRule));
  122. await face(A, 'gitoriaRequiredAdd', ['routger', appId, 'ci']);
  123. await face(A, 'gitoriaRequiredRemove', ['routger', requirements.rows.find(r => r.isPerson).id]);
  124. check('Settings explains apps-only requirement', (await at('routger', '/settings')).body.includes(appsRule));
  125. await face(A, 'gitoriaRequiredPersonAdd', ['routger', bobId]);
  126. await face(B, 'gitoriaPrApprove', ['routger', '' + pull.number, head, true]);
  127. check('owner, member, pull, approval and requirements fixture exists', !!rid && !!pull.number);
  128. await face(A, 'gitoriaCreate', ['taken', 'taken']); await face(A, 'gitoriaCreateOrg', ['occupied', false]);
  129. await face(A, 'gitoriaCreate', ['other', 'other']); await rename('other', 'other-new');
  130. for (const name of ['taken', 'occupied', 'other', 'INVALID', 'org/name']) check('rename refuses ' + name, !!(await rename('routger', name))?.error);
  131. check('non-owner and anonymous rename refused by server', !!(await rename('routger', 'stolen', B))?.error && !!(await rename('routger', 'stolen', null))?.error);
  132. check('non-owner display-name write refused by server', !!(await title('routger', 'stolen', B))?.error);
  133. check('too-long and multiline display names refused', !!(await title('routger', 'x'.repeat(81)))?.error && !!(await title('routger', 'bad\nname'))?.error);
  134. writeFileSync(join(GIT, 'routger.git/HEAD.lock'), 'busy');
  135. check('Git lock refuses rename without moving folder', !!(await rename('routger', 'hycon'))?.error && existsSync(join(GIT, 'routger.git')) && !existsSync(join(GIT, 'hycon.git')));
  136. rmSync(join(GIT, 'routger.git/HEAD.lock'));
  137. const pushProcess = spawn('git', ['receive-pack', join(GIT, 'routger.git')], { cwd: APP, stdio: ['pipe', 'pipe', 'pipe'] });
  138. await new Promise(resolve => pushProcess.stdout.once('data', resolve));
  139. try {
  140. check('active receive-pack does not block rename; its old path is preserved', (await rename('routger', 'inflight'))?.repo?.id === rid && lstatSync(join(GIT, 'routger.git')).isSymbolicLink());
  141. check('rename back while receive-pack holds its original path avoids a symlink loop', (await rename('inflight', 'routger'))?.repo?.id === rid && !lstatSync(join(GIT, 'routger.git')).isSymbolicLink() && realpathSync(join(GIT, 'inflight.git')) === realpathSync(join(GIT, 'routger.git')));
  142. }
  143. finally { pushProcess.stdin.end(); await new Promise(resolve => pushProcess.once('exit', resolve)); }
  144. const connect = await at('routger', '/settings/connect');
  145. const state = new URL(connect.headers.location).searchParams.get('state');
  146. await at('routger', '/settings/connected?code=rename&state=' + encodeURIComponent(state));
  147. check('display name saved', (await title('routger', 'Hyper Conductor'))?.repo?.title === 'Hyper Conductor');
  148. const moved = await rename('routger', 'hycon');
  149. check('owner live rename keeps repo id and title', moved?.repo?.slug === 'hycon' && moved.repo.id === rid && moved.repo.title === 'Hyper Conductor', J(moved));
  150. check('old name cannot be claimed by an organization', !!(await face(A, 'gitoriaCreateOrg', ['routger', false]))?.error);
  151. check('same folder history moved', lstatSync(join(GIT, 'routger.git')).isSymbolicLink() && !readlinkSync(join(GIT, 'routger.git')).startsWith('/') && execFileSync('git', ['--git-dir=' + join(GIT, 'hycon.git'), 'rev-parse', 'main'], { encoding: 'utf8' }).trim() === mainSha);
  152. check('tickets connection stays attached', (await at('hycon', '/settings')).body.includes('W53 tickets'));
  153. await face(A, 'gitoriaAppPing', ['hycon', appId]);
  154. for (let i = 0; i < 100 && !got.some(x => { try { return JSON.parse(x.body).repo?.full === 'hycon'; } catch { return false; } }); i++) await sleep(100);
  155. check('new app event carries new full name and display title', got.some(x => { try { const r = JSON.parse(x.body).repo; return r?.id === rid && r.full === 'hycon' && r.title === 'Hyper Conductor'; } catch { return false; } }));
  156. check('new page has heading and window title', (await at('hycon')).status === 200 && /id="reponame"[^>]*>Hyper Conductor</.test((await at('hycon')).body) && /<title>Hyper Conductor · gitoria<\/title>/.test((await at('hycon')).body));
  157. const old = await at('routger');
  158. check('old page keeps GO34 moved view and link', old.status === 200 && old.body.includes('This repository moved to') && old.body.includes(`href="http://hycon.${HOSTNAME}:${PORT}/"`));
  159. const list = JSON.parse((await get('/api/repos')).body).repos;
  160. check('repo JSON and list add title without changing slug', list.some(r => r.id === rid && r.title === 'Hyper Conductor' && r.slug === 'hycon') && (await get('/')).body.includes('Hyper Conductor'));
  161. const retained = JSON.parse((await api('routger', '/api/pulls/' + pull.number)).body);
  162. check('old apps API base resolves to retained pull, approval and required rows', retained.number === pull.number && retained.head === head && retained.approvals.some(a => a.user.id === bobId) && retained.required[0]?.app?.id === appId && retained.approvers.some(a => a.user.id === bobId), J(retained).slice(0, 400));
  163. check('app exchanges key for token on old API base', (await raw('POST', '/api/apps/token', { host: host('routger'), headers: { authorization: 'Bearer ' + appAdded.key } })).status === 200);
  164. check('old HTTPS clone retains history', (() => { g('clone', '-q', oldUrl, join(STORE, 'clone')); return execFileSync('git', ['-C', join(STORE, 'clone'), 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim() === mainSha; })());
  165. g('checkout', '-q', 'main'); g('commit', '-q', '--allow-empty', '-m', 'after rename'); g('push', '-q', oldUrl, 'main');
  166. execFileSync('git', ['-C', join(STORE, 'clone'), 'fetch', '-q'], { env: genv, stdio: ['ignore', 'pipe', 'pipe'] });
  167. check('old HTTPS push and fetch land at new name', execFileSync('git', ['--git-dir=' + join(GIT, 'hycon.git'), 'rev-parse', 'main'], { encoding: 'utf8' }).trim() === g('rev-parse', 'HEAD').trim());
  168. const ssh = await get(`/__git/access?user=${bobId}&slug=routger&write=1`, { headers: { 'x-gitoria-secret': 'sshsecret-mm-gate' } });
  169. check('old SSH access resolves new folder and retains member', ssh.status === 200 && ssh.body.trim() === 'ok hycon');
  170. await rename('hycon', 'hycon-next');
  171. check('multiple moves retarget oldest forward in one hop', (await api('routger', '/api/pulls/' + pull.number)).status === 200 && (await get(`/__git/access?user=${bobId}&slug=routger&write=1`, { headers: { 'x-gitoria-secret': 'sshsecret-mm-gate' } })).body.trim() === 'ok hycon-next');
  172. check('rename back to own forward allowed', (await rename('hycon-next', 'routger'))?.repo?.id === rid);
  173. check('former current name now forwards after rename back', (await api('hycon-next', '/api/pulls/' + pull.number)).status === 200);
  174. await face(A, 'gitoriaCreateOrg', ['team', true]); await face(A, 'gitoriaCreateRepo', ['before', 'org repo', 'team', false]);
  175. check('org rename preserves org and effective visibility', (await rename('team/before', 'after'))?.repo?.slug === 'team/after' && (await at('team', '/after')).body.includes('Private'));
  176. check('org rename rejects reserved page name and transfers', !!(await rename('team/after', 'code'))?.error && !!(await rename('team/after', 'elsewhere/name'))?.error);
  177. const orgApp = await face(A, 'gitoriaAppAdd', ['team/after', 'Org reviewer', `http://127.0.0.1:${RPORT}/org`]);
  178. check('context suggestions reject an app from another repository', (await face(A, 'gitoriaAppContext', ['team/after', appId]))?.context === '');
  179. check('org old API bases resolve forward', (await raw('POST', '/api/before/apps/token', { host: host('team'), headers: { authorization: 'Bearer ' + orgApp.key } })).status === 200 && (await raw('POST', '/before/api/apps/token', { host: host('team'), headers: { authorization: 'Bearer ' + orgApp.key } })).status === 200);
  180. await title('team/after', 'Organization display name');
  181. check('organization list shows display name beside address', (await at('team')).body.includes('Organization display name') && (await at('team')).body.includes('team/after'));
  182. check('private org keeps old API private', (await get('/api/before/pulls/1', { host: host('team') })).status === 404);
  183. // W55: Settings → Rename also chooses the organization (none, or one the user belongs to).
  184. await face(A, 'gitoriaCreateOrg', ['mine', false]); await face(B, 'gitoriaCreateOrg', ['bobs', false]);
  185. await face(A, 'gitoriaCreate', ['mover', 'org mover']);
  186. const mvUrl = `http://a:${tA}@mover.${HOSTNAME}:${PORT}/mover.git`;
  187. g('checkout', '-q', 'main'); g('push', '-q', mvUrl, 'main');
  188. const settingsBody = (await at('mover', '/settings')).body;
  189. check('Settings shows an Organization select with None and an owned org, not the other user\'s', /<select[^>]*name="org"/.test(settingsBody) && settingsBody.includes('None (top level)') && settingsBody.includes('value="mine"') && !settingsBody.includes('value="bobs"') && settingsBody.includes('A repository that was private stays private'));
  190. check('into an organization the user does not belong to is refused', (await rename('mover', 'mover', A, 'bobs'))?.error === 'you can only move a repository into an organization you belong to');
  191. check('into an organization that does not exist is refused and none is created', (await rename('mover', 'mover', A, 'ghost-org'))?.error === 'you can only move a repository into an organization you belong to' && (await get('/api/repos', { cookie: A.cookie })).body.indexOf('ghost-org') < 0);
  192. check('non-owner cannot move into their own org either', !!(await rename('mover', 'mover', B, 'bobs'))?.error);
  193. check('a move that changes nothing is refused', !!(await rename('mover', 'mover', A, ''))?.error);
  194. const intoOrg = await rename('mover', 'mover', A, 'mine');
  195. check('top level repo moves into the user\'s own org', intoOrg?.repo?.slug === 'mine/mover' && intoOrg.repo.org === 'mine' && intoOrg.repo.id && intoOrg.repo.isPrivate === false, J(intoOrg));
  196. check('org page lists the moved repo', (await at('mine')).body.includes('mover'));
  197. const movedOld = await at('mover');
  198. check('old address shows moved to', movedOld.body.includes('This repository moved to') && movedOld.body.includes(`mine.${HOSTNAME}:${PORT}/mover`), movedOld.body.slice(0, 200));
  199. g('clone', '-q', mvUrl, join(STORE, 'mv-clone'));
  200. execFileSync('git', ['-C', join(STORE, 'mv-clone'), 'commit', '-q', '--allow-empty', '-m', 'via old url'], { env: genv });
  201. execFileSync('git', ['-C', join(STORE, 'mv-clone'), 'push', '-q', 'origin', 'main'], { env: genv });
  202. check('git clone and push over the old URL still work after moving into an org', execFileSync('git', ['--git-dir=' + join(GIT, 'mine/mover.git'), 'log', '-1', '--format=%s', 'main'], { encoding: 'utf8' }).trim() === 'via old url');
  203. await face(A, 'gitoriaSetOrgPrivate', ['mine', true]);
  204. const pm = await at('mine', '/mover', null); const pa = await at('mine', '/mover', A.cookie);
  205. check('a public repo in a private org is private by its organization', pm.status === 404 && pa.status === 200);
  206. const out = await rename('mine/mover', 'mover', A, '');
  207. check('moving out of a private org keeps the repository private (no leak)', out?.repo?.slug === 'mover' && out.repo.isPrivate === true && /No such repository/.test((await at('mover', '/', null)).body) && !/No such repository/.test((await at('mover', '/', A.cookie)).body), J(out));
  208. await face(A, 'gitoriaSetOrgPrivate', ['mine', false]);
  209. check('private repo moved between public orgs stays private', (await rename('mover', 'mover', A, 'mine'))?.repo?.isPrivate === true);
  210. await face(A, 'gitoriaCreate', ['pubone', 'public one']);
  211. check('a public repo moved out of a public org stays public', (await rename('pubone', 'pubone', A, 'mine'))?.repo?.isPrivate === false && (await rename('mine/pubone', 'pubone', A, ''))?.repo?.isPrivate === false);
  212. check('the repo id stays the same through every move', (await rename('mine/mover', 'mover', A, ''))?.repo?.id === intoOrg.repo.id);
  213. // Direct bare paths model the path captured by the SSH container before a rename.
  214. await face(A, 'gitoriaCreate', ['path-old', 'captured Git path']);
  215. g('push', '-q', join(GIT, 'path-old.git'), 'main');
  216. const pathClone = join(STORE, 'path-clone');
  217. g('clone', '-q', '--no-local', join(GIT, 'path-old.git'), pathClone);
  218. check('rename preserves a previously cloned direct Git origin', !!(await rename('path-old', 'path-new'))?.repo);
  219. const pathGit = (...args) => execFileSync('git', args, { cwd: pathClone, env: genv, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
  220. pathGit('commit', '-q', '--allow-empty', '-m', 'push after captured-path rename');
  221. pathGit('push', '-q', 'origin', 'main');
  222. const capturedSha = pathGit('rev-parse', 'HEAD').trim();
  223. check('clone made through old bare path pushes to the moved folder', execFileSync('git', ['--git-dir=' + join(GIT, 'path-new.git'), 'rev-parse', 'main'], { encoding: 'utf8' }).trim() === capturedSha);
  224. await rename('path-new', 'path-third'); await rename('path-third', 'path-old');
  225. pathGit('commit', '-q', '--allow-empty', '-m', 'after rename-back'); pathGit('push', '-q', 'origin', 'main');
  226. check('all filesystem aliases resolve directly after later moves and rename-back', ['path-new', 'path-third'].every(name => realpathSync(join(GIT, name + '.git')) === realpathSync(join(GIT, 'path-old.git')) && readlinkSync(join(GIT, name + '.git')) === 'path-old.git'));
  227. await face(A, 'gitoriaCreateRepo', ['path-org', '', 'team', false]);
  228. g('push', '-q', join(GIT, 'team/path-org.git'), 'main');
  229. await rename('team/path-org', 'path-org-new');
  230. check('organization filesystem alias is relative to its containing directory', readlinkSync(join(GIT, 'team/path-org.git')) === '../team/path-org-new.git' && execFileSync('git', ['--git-dir=' + join(GIT, 'team/path-org.git'), 'rev-parse', 'main'], { encoding: 'utf8' }).trim() === g('rev-parse', 'main').trim());
  231. await rename('team/path-org-new', 'path-org');
  232. check('organization rename-back replaces its own symlink with the bare directory', !lstatSync(join(GIT, 'team/path-org.git')).isSymbolicLink() && realpathSync(join(GIT, 'team/path-org-new.git')) === realpathSync(join(GIT, 'team/path-org.git')));
  233. // Real ticket notifications before and after rename, using only this gate's receiver.
  234. await face(A, 'gitoriaCreate', ['ticket-old', 'notification dedup']);
  235. const ticketConnect = await at('ticket-old', '/settings/connect');
  236. const ticketState = new URL(ticketConnect.headers.location).searchParams.get('state');
  237. await at('ticket-old', '/settings/connected?code=rename&state=' + encodeURIComponent(ticketState));
  238. const ticketUrl = name => `http://a:${tA}@${name}.${HOSTNAME}:${PORT}/${name}.git`;
  239. const ticketPush = (name, ref) => new Promise((resolve, reject) => {
  240. const p = spawn('git', ['push', '-q', ticketUrl(name), ref], { cwd: W, env: genv, stdio: ['ignore', 'pipe', 'pipe'] });
  241. let error = ''; p.stderr.on('data', d => error += d);
  242. p.on('error', reject); p.on('close', code => code === 0 ? resolve() : reject(new Error('ticket fixture push: ' + error)));
  243. });
  244. g('checkout', '-q', 'main'); g('commit', '-q', '--allow-empty', '-m', 'mention #11'); await ticketPush('ticket-old', 'main');
  245. g('checkout', '-q', '-b', 'ticket-fix'); g('commit', '-q', '--allow-empty', '-m', '|||PR fixes #12'); const ticketHead = g('rev-parse', 'HEAD').trim(); await ticketPush('ticket-old', 'ticket-fix');
  246. const ticketMerged = await face(A, 'gitoriaMergePull', ['ticket-old', ticketHead]);
  247. const notifications = () => got.filter(x => /^\/api\/projects\/w53\/tickets\/\d+\/(comments|state)$/.test(x.path));
  248. const oldNotifications = notifications();
  249. check('ticket fixture emitted real comments and a merged-PR review state', !ticketMerged?.error && oldNotifications.some(x => x.path.endsWith('/comments')) && oldNotifications.some(x => x.path.endsWith('/state')));
  250. await rename('ticket-old', 'ticket-new');
  251. g('checkout', '-q', 'main'); g('fetch', '-q', ticketUrl('ticket-new'), 'main'); g('merge', '-q', '--ff-only', 'FETCH_HEAD');
  252. g('commit', '-q', '--allow-empty', '-m', 'push without new references'); await ticketPush('ticket-new', 'main');
  253. check('rename then push repeats no old ticket comments or state changes', notifications().length === oldNotifications.length, J(notifications().map(x => x.path)));
  254. g('commit', '-q', '--allow-empty', '-m', 'new mention #13'); await ticketPush('ticket-old', 'main');
  255. check('new ticket references still notify once through old forwarded URL', notifications().length === oldNotifications.length + 1 && notifications().at(-1).path.endsWith('/13/comments'), J(notifications().map(x => x.path)));
  256. await rename('ticket-new', 'ticket-old');
  257. g('commit', '-q', '--allow-empty', '-m', 'push after ticket rename-back'); await ticketPush('ticket-old', 'main');
  258. check('ticket dedup history also survives rename-back', notifications().length === oldNotifications.length + 1);
  259. g('checkout', '-q', 'feature');
  260. if (process.env.HL_CDP_URL) {
  261. chromeLock = spawn('timeout', ['600', 'flock', '/media/STORAGE/claude-scratch/atlas/lisbeth.lock', 'sh', '-c', 'echo locked; cat'], { cwd: APP, stdio: ['pipe', 'pipe', 'inherit'] });
  262. await new Promise((resolve, reject) => { chromeLock.stdout.once('data', resolve); chromeLock.once('exit', () => reject(new Error('Chrome lock unavailable'))); });
  263. beforePages = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');
  264. writeFileSync(join(STORE, 'chrome-before.json'), J(beforePages.map(t => ({ id: t.id, title: t.title, url: t.url.split('?')[0] }))));
  265. }
  266. browser = await launchBrowser({ debugPortRange: CHROME });
  267. if (browser.proc) writeFileSync(join(STORE, 'browser-pid.txt'), String(browser.proc.pid));
  268. pg = await browser.newPage(); await pg.send('Network.enable');
  269. if (process.env.HL_CDP_URL) {
  270. const wait = pg.waitFor.bind(pg); pg.waitFor = (expression, options = {}) => wait(expression, { ...options, timeout: options.timeout || 30000 });
  271. }
  272. await pg.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  273. await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: 'routger.' + HOSTNAME, path: '/' });
  274. for (const [path, prefix] of [['/', ''], ['/code', 'Code · '], ['/branch/main', 'Branch · '], ['/commit/' + head, 'Commit · '], ['/pulls', 'Pull requests · '], ['/pulls/' + pull.number, 'Pull request #' + pull.number + ' · '], ['/releases', 'Releases · '], ['/tickets', 'Tickets · '], ['/settings', 'Settings · ']]) {
  275. await pg.goto(`http://routger.${HOSTNAME}:${PORT}` + path);
  276. await pg.waitFor('!!window.__hl && window.__hl.socket?.readyState === 1');
  277. await pg.evaluate('window.__w54KeptPage = 54');
  278. const newTitle = 'Kept page ' + path;
  279. await title('routger', newTitle);
  280. await pg.waitFor(`document.title === ${J(prefix)} + ${J(newTitle)} + ' · gitoria'`);
  281. check('kept ' + path + ' receives updated window title from another writer', await pg.evaluate('window.__w54KeptPage === 54'));
  282. await title('routger', 'Hyper Conductor');
  283. await pg.waitFor(`document.title === ${J(prefix)} + 'Hyper Conductor · gitoria'`);
  284. }
  285. const key = async name => { const n = { Tab: 9, Enter: 13, Home: 36, ArrowDown: 40 }[name]; await pg.send('Input.dispatchKeyEvent', { type: 'keyDown', key: name, code: name, windowsVirtualKeyCode: n, ...(name === 'Enter' ? { text: '\r' } : {}) }); await pg.send('Input.dispatchKeyEvent', { type: 'keyUp', key: name, code: name, windowsVirtualKeyCode: n }); };
  286. const tabTo = async selector => { for (let i = 0; i < 120; i++) { await key('Tab'); if (await pg.evaluate(`document.activeElement === document.querySelector(${J(selector)})`)) return; } throw new Error('Tab cannot reach ' + selector); };
  287. const chooseApp = async id => {
  288. await tabTo('#requiredapp');
  289. const index = await pg.evaluate(`Array.from(document.querySelector('#requiredapp').options).findIndex(o => o.value === ${J(id)})`);
  290. if (index < 0) throw new Error('missing app option');
  291. await key('Home'); for (let i = 0; i < index; i++) await key('ArrowDown');
  292. };
  293. const visit = async name => { await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: name + '.' + HOSTNAME, path: '/' }); await pg.goto(`http://${name}.${HOSTNAME}:${PORT}/settings`); await pg.waitFor(`!!window.__hl && window.__hl.socket?.readyState === 1 && !!document.querySelector('#rename-name')`, { timeout: 30000 }); };
  294. const formShot = async (selector, name) => {
  295. await pg.evaluate(`new Promise(resolve => { const r = document.querySelector(${J(selector)}).getBoundingClientRect(); window.scrollTo({ top: Math.max(0, r.top + scrollY - 64), behavior: 'instant' }); requestAnimationFrame(() => requestAnimationFrame(resolve)); })`);
  296. const box = await pg.evaluate(`(() => { const r = document.querySelector(${J(selector)}).getBoundingClientRect(); return { x: r.x + scrollX, y: r.y + scrollY, width: r.width, height: r.height, scale: 1 }; })()`);
  297. const shot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true, clip: box });
  298. writeFileSync(join(STORE, name), Buffer.from(shot.data, 'base64'));
  299. };
  300. let current = 'routger';
  301. for (const [width, height] of [[390, 844], [800, 1280], [1280, 800]]) {
  302. await pg.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width === 390 });
  303. await visit(current);
  304. await pg.send('Page.bringToFront');
  305. await pg.waitFor(`document.querySelector('#merge-rule')?.textContent === ${J(mixedRule)}`);
  306. await chooseApp(appId);
  307. await pg.waitFor(`document.querySelector('#requiredcontext')?.value === 'older-context'`);
  308. await pg.type('#requiredcontext', 'editable-context', { clear: true });
  309. check(`${width}: selected app prefills its latest context and allows editing`, await pg.evaluate(`document.querySelector('#requiredcontext').value === 'editable-context'`));
  310. await chooseApp(emptyAppId);
  311. await pg.waitFor(`document.querySelector('#requiredcontext')?.value === ''`);
  312. await chooseApp(appId);
  313. await pg.waitFor(`document.querySelector('#requiredcontext')?.value === 'older-context'`);
  314. check(`${width}: changing apps clears absent history and restores newest context`, true);
  315. await formShot('#required', `merge-rule-${width}.png`);
  316. const liveRows = (await face(A, 'gitoriaRequiredRead', [current])).rows;
  317. await face(A, 'gitoriaRequiredRemove', [current, liveRows.find(r => !r.isPerson).id]);
  318. await pg.waitFor(`document.querySelector('#merge-rule')?.textContent === ${J(peopleRule)}`);
  319. await face(A, 'gitoriaRequiredAdd', [current, appId, 'ci']);
  320. await face(A, 'gitoriaRequiredRemove', [current, liveRows.find(r => r.isPerson).id]);
  321. await pg.waitFor(`document.querySelector('#merge-rule')?.textContent === ${J(appsRule)}`);
  322. await face(A, 'gitoriaRequiredPersonAdd', [current, bobId]);
  323. await pg.waitFor(`document.querySelector('#merge-rule')?.textContent === ${J(mixedRule)}`);
  324. check(`${width}: merge-rule line follows live apps/people changes`, await pg.evaluate('document.documentElement.scrollWidth <= innerWidth'));
  325. const beforeShot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); writeFileSync(join(STORE, `before-${width}x${height}.png`), Buffer.from(beforeShot.data, 'base64'));
  326. await tabTo('#display-name'); await pg.type('#display-name', 'Keyboard title ' + width, { clear: true }); await key('Enter');
  327. await pg.waitFor(`document.querySelector('#reponame').textContent === 'Keyboard title ${width}' && document.title.includes('Keyboard title ${width}')`);
  328. check(`${width}: title Enter submission updates heading and window title`, await pg.evaluate(`document.title.includes('Keyboard title ${width}')`));
  329. const titleShot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); writeFileSync(join(STORE, `title-${width}x${height}.png`), Buffer.from(titleShot.data, 'base64'));
  330. await visit(current);
  331. check(`${width}: reload retains display name`, await pg.evaluate(`document.querySelector('#display-name').value === 'Keyboard title ${width}'`));
  332. await tabTo('#navcode'); await key('Enter'); await pg.waitFor(`location.pathname === '/code' && !!document.querySelector('#entries') && !document.querySelector('#display-name')`);
  333. const history = await pg.send('Page.getNavigationHistory'); await pg.send('Page.navigateToHistoryEntry', { entryId: history.entries[history.currentIndex - 1].id });
  334. await pg.waitFor(`!!document.querySelector('#display-name') && document.title.startsWith('Settings')`);
  335. check(`${width}: Back restores saved title and address`, await pg.evaluate(`document.querySelector('#display-name').value === 'Keyboard title ${width}' && location.pathname === '/settings'`));
  336. await tabTo('#display-name'); await pg.type('#display-name', '', { clear: true }); await tabTo('#save-title'); await key('Enter');
  337. await pg.waitFor(`document.querySelector('#reponame').textContent === ${J(current)} && document.title.includes(${J(current)})`);
  338. check(`${width}: keyboard clears title to address name`, await pg.evaluate(`!document.querySelector('#repo-address-name') && document.title.includes(${J(current)})`));
  339. await tabTo('#rename-name'); const next = 'keyboard-' + width; await pg.type('#rename-name', next, { clear: true });
  340. // The new subdomain has its own host-only test cookie.
  341. await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: next + '.' + HOSTNAME, path: '/' });
  342. await key('Enter'); await pg.waitFor(`location.hostname === '${next}.${HOSTNAME}' && !!document.querySelector('#rename-name')`, { timeout: 30000 });
  343. check(`${width}: Enter renames and browser lands at new Settings`, await pg.evaluate(`document.querySelector('#reponame').textContent === '${next}'`));
  344. current = next;
  345. check(`${width}: form fits viewport`, await pg.evaluate('document.documentElement.scrollWidth <= innerWidth'));
  346. const shot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); writeFileSync(join(STORE, `rename-${width}x${height}.png`), Buffer.from(shot.data, 'base64'));
  347. await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], url: `http://${HOSTNAME}:${PORT}/` });
  348. await pg.goto(`http://${HOSTNAME}:${PORT}/`); await pg.waitFor(`!!document.querySelector('#repo-name') && window.__hl?.socket?.readyState === 1`);
  349. const repoLabel = 'Repo keyboard ' + width, repoAddress = width === 800 ? 'explicit-repo-800' : 'repo-keyboard-' + width;
  350. await tabTo('#repo-name'); await pg.type('#repo-name', repoLabel, { clear: true });
  351. await tabTo('#slug'); await pg.type('#slug', width === 800 ? repoAddress : '', { clear: true });
  352. await formShot('#createform', `create-repo-${width}.png`);
  353. await tabTo('#createsave'); await key('Enter');
  354. await pg.waitFor(`document.querySelector('#created')?.textContent.includes(${J(repoAddress)})`);
  355. check(`${width}: repository Name and Address submit from keyboard`, await pg.evaluate(`document.querySelector('#repos').textContent.includes(${J(repoLabel)})`));
  356. const orgLabel = 'Org keyboard ' + width, orgAddress = width === 800 ? 'explicit-org-800' : 'org-keyboard-' + width;
  357. await tabTo('#org-name'); await pg.type('#org-name', orgLabel, { clear: true });
  358. await tabTo('#orgslug'); await pg.type('#orgslug', width === 800 ? orgAddress : '', { clear: true });
  359. await formShot('#orgform', `create-org-${width}.png`);
  360. await tabTo('#orgsave'); await key('Enter');
  361. await pg.waitFor(`document.querySelector('#created')?.textContent.includes(${J(orgAddress)})`);
  362. check(`${width}: organization Name and Address submit from keyboard`, await pg.evaluate(`document.querySelector('#orgs').textContent.includes(${J(orgLabel)})`));
  363. await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: orgAddress + '.' + HOSTNAME, path: '/' });
  364. await pg.goto(`http://${orgAddress}.${HOSTNAME}:${PORT}/`); await pg.waitFor(`!!document.querySelector('#organization-name') && window.__hl?.socket?.readyState === 1`);
  365. const orgNewName = 'Named organization ' + width;
  366. await tabTo('#organization-name'); await pg.type('#organization-name', orgNewName, { clear: true }); await key('Enter');
  367. await pg.waitFor(`document.querySelector('#orgname').textContent === ${J(orgNewName)} && document.title.includes(${J(orgNewName)})`);
  368. check(`${width}: owner changes org Name without changing Address`, await pg.evaluate(`location.hostname === ${J(orgAddress + '.' + HOSTNAME)} && document.querySelector('#org-address-name').textContent === ${J(orgAddress)}`));
  369. await pg.goto(`http://${orgAddress}.${HOSTNAME}:${PORT}/`); await pg.waitFor(`document.querySelector('#organization-name')?.value === ${J(orgNewName)}`);
  370. check(`${width}: org Name survives reload and fits viewport`, await pg.evaluate('document.documentElement.scrollWidth <= innerWidth'));
  371. const orgShot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); writeFileSync(join(STORE, `org-name-${width}.png`), Buffer.from(orgShot.data, 'base64'));
  372. if (process.env.HL_CDP_URL) {
  373. await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: 'team.' + HOSTNAME, path: '/' });
  374. for (const [label, url] of [['main-list', `http://${HOSTNAME}:${PORT}/`], ['org-list', `http://team.${HOSTNAME}:${PORT}/`]]) {
  375. if (label === 'main-list') await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], url: `http://${HOSTNAME}:${PORT}/` });
  376. await pg.goto(url); await pg.waitFor(`document.querySelector('#repos')?.textContent.includes('Organization display name')`);
  377. check(`${width}: ${label} display name fits`, await pg.evaluate('document.documentElement.scrollWidth <= innerWidth'));
  378. const listShot = await pg.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); writeFileSync(join(STORE, `${label}-${width}x${height}.png`), Buffer.from(listShot.data, 'base64'));
  379. }
  380. }
  381. }
  382. // W55: choose the organization in Settings with the keyboard at phone and desktop width.
  383. for (const [width, height] of [[390, 844], [1280, 800]]) {
  384. await pg.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width === 390 });
  385. const nm = 'orgmove-' + width;
  386. await face(A, 'gitoriaCreate', [nm, 'browser org move']);
  387. await face(A, 'gitoriaSetOrgPrivate', ['mine', false]);
  388. await visit(nm);
  389. check(`${width}: Organization select starts on None and lists the owned org`, await pg.evaluate(`(() => { const s = document.querySelector('#rename-org'); return !!s && s.value === '' && [...s.options].map(o => o.value).includes('mine') && !s.closest('form').querySelectorAll('form').length; })()`));
  390. check(`${width}: the select sits in the one Rename form with the privacy line`, await pg.evaluate(`(() => { const f = document.querySelector('#rename-form'); return f.contains(document.querySelector('#rename-org')) && f.contains(document.querySelector('#rename-name')) && f.textContent.includes('A repository that was private stays private; change that below.') && document.documentElement.scrollWidth <= innerWidth; })()`));
  391. await formShot('#rename-form', `org-select-${width}.png`);
  392. await tabTo('#rename-org');
  393. const idx = await pg.evaluate(`[...document.querySelector('#rename-org').options].findIndex(o => o.value === 'mine')`);
  394. for (let i = 0; i < idx; i++) await key('ArrowDown');
  395. await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: 'mine.' + HOSTNAME, path: '/' });
  396. await tabTo('#rename-name'); await key('Enter');
  397. await pg.waitFor(`location.hostname === 'mine.${HOSTNAME}' && location.pathname === '/${nm}/settings' && !!document.querySelector('#rename-org')`, { timeout: 30000 });
  398. check(`${width}: Enter moves the repo into the org and the page lands at its new Settings`, await pg.evaluate(`document.querySelector('#rename-org').value === 'mine' && document.querySelector('#rename-name').value === ${J(nm)}`));
  399. await formShot('#rename-form', `org-moved-${width}.png`);
  400. const oldPage = await at(nm);
  401. check(`${width}: old address shows moved to`, oldPage.body.includes('This repository moved to'));
  402. await tabTo('#rename-org'); await key('Home'); await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: nm + '.' + HOSTNAME, path: '/' });
  403. await tabTo('#rename-name'); await key('Enter');
  404. await pg.waitFor(`location.hostname === '${nm}.${HOSTNAME}' && location.pathname === '/settings' && !!document.querySelector('#rename-org')`, { timeout: 30000 });
  405. check(`${width}: choosing None moves it back to the top level`, await pg.evaluate(`document.querySelector('#rename-org').value === ''`));
  406. }
  407. // W55 round 2: an OPEN list of the source organization drops the repo when it moves away (to the top level and to another org).
  408. await pg.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  409. await face(A, 'gitoriaCreateOrg', ['mine2', false]);
  410. await face(A, 'gitoriaCreateRepo', ['leaver-a', '', 'mine', false]); await face(A, 'gitoriaCreateRepo', ['leaver-b', '', 'mine', false]);
  411. await pg.send('Network.setCookie', { name: 'gitoriasid', value: A.cookie.split('=')[1], domain: 'mine.' + HOSTNAME, path: '/' });
  412. await pg.goto(`http://mine.${HOSTNAME}:${PORT}/`);
  413. await pg.waitFor(`window.__hl?.socket?.readyState === 1 && document.querySelector('#repos')?.textContent.includes('leaver-a') && document.querySelector('#repos').textContent.includes('leaver-b')`);
  414. await rename('mine/leaver-a', 'leaver-a', A, '');
  415. await pg.waitFor(`!document.querySelector('#repos').textContent.includes('leaver-a')`);
  416. check('open org list drops a repo moved to the top level and keeps the others', await pg.evaluate(`document.querySelector('#repos').textContent.includes('leaver-b')`));
  417. await rename('mine/leaver-b', 'leaver-b', A, 'mine2');
  418. await pg.waitFor(`!document.querySelector('#repos').textContent.includes('leaver-b')`);
  419. check('open org list drops a repo moved to another org', await pg.evaluate(`!document.querySelector('#repos').textContent.includes('leaver-b')`));
  420. await pg.goto(`http://mine.${HOSTNAME}:${PORT}/`); await pg.waitFor(`!!document.querySelector('#repos')`);
  421. check('after a reload the source org list still lacks both', await pg.evaluate(`!/leaver-/.test(document.querySelector('#repos').textContent)`));
  422. // W55 round 3: who hears "left the organization" is decided by the readers BEFORE the move.
  423. await face(A, 'gitoriaCreateOrg', ['pubo', false]); await face(A, 'gitoriaCreateOrg', ['privo', true]);
  424. const secretId = (await face(A, 'gitoriaCreateRepo', ['secret-out', '', 'pubo', true]))?.repo?.id; const openId = (await face(A, 'gitoriaCreateRepo', ['open-out', '', 'pubo', false]))?.repo?.id;
  425. await face(A, 'gitoriaCreateRepo', ['member-out', '', 'privo', false]); await face(A, 'gitoriaChangeMember', ['privo/member-out', 'Bob', true]);
  426. const frames = [];
  427. const stopFrames = browser.conn.onEvent(m => { if (m.method === 'Network.webSocketFrameReceived') { const d = m.params?.response?.payloadData || ''; frames.push({ sid: m.sessionId, text: d + '|' + Buffer.from(d, 'base64').toString('latin1') }); } });
  428. anon = await browser.newPage(); await anon.send('Network.enable');
  429. bobPage = await browser.newPage(); await bobPage.send('Network.enable');
  430. await bobPage.send('Network.setCookie', { name: 'gitoriasid', value: B.cookie.split('=')[1], domain: 'privo.' + HOSTNAME, path: '/' });
  431. await anon.goto(`http://pubo.${HOSTNAME}:${PORT}/`);
  432. await anon.waitFor(`window.__hl?.socket?.readyState === 1 && document.querySelector('#repos')?.textContent.includes('open-out')`);
  433. check('anonymous observer on a public org page never saw the private repo', await anon.evaluate(`!document.querySelector('#repos').textContent.includes('secret-out')`));
  434. await bobPage.goto(`http://privo.${HOSTNAME}:${PORT}/`);
  435. await bobPage.waitFor(`window.__hl?.socket?.readyState === 1 && document.querySelector('#repos')?.textContent.includes('member-out')`);
  436. check('fixture ids found', !!secretId && !!openId);
  437. await rename('pubo/open-out', 'open-out', A, '');
  438. await anon.waitFor(`!document.querySelector('#repos').textContent.includes('open-out')`);
  439. check('control: the anonymous observer hears a PUBLIC repo leave (its frames carry the id)', frames.some(f => f.sid === anon.sessionId && f.text.includes(openId)));
  440. await rename('pubo/secret-out', 'secret-out', A, '');
  441. await sleep(1500);
  442. check('anonymous observer does not receive the event when a PRIVATE repo leaves the public org', !frames.some(f => f.sid === anon.sessionId && f.text.includes(secretId)) && !frames.some(f => f.sid === anon.sessionId && f.text.includes('secret-out')));
  443. // replay: each move keeps its own readers. Private repo leaves (anon must not hear), is made public, goes in again and leaves again (anon hears that one only).
  444. const replayId = (await face(A, 'gitoriaCreateRepo', ['replay-x', '', 'pubo', true]))?.repo?.id;
  445. await rename('pubo/replay-x', 'replay-x', A, ''); await face(A, 'gitoriaSetPrivate', ['replay-x', false]);
  446. await rename('replay-x', 'replay-x', A, 'pubo'); await rename('pubo/replay-x', 'replay-x', A, '');
  447. await anon.waitFor(`!document.querySelector('#repos').textContent.includes('replay-x')`);
  448. await anon.evaluate(`window.__hl.socket.close()`); await sleep(500);
  449. await anon.waitFor(`window.__hl?.socket?.readyState === 1`, { timeout: 30000 }); await sleep(1500);
  450. const replayFrames = frames.filter(f => f.sid === anon.sessionId && f.text.includes(replayId) && f.text.includes('repoLeftOrg')).length;
  451. check('anonymous tab: across private-leave, make-public, re-enter, leave and a reconnect it gets exactly one leave event (the last, public one)', replayFrames === 1, 'frames with the id: ' + replayFrames);
  452. await rename('privo/member-out', 'member-out', A, '');
  453. await bobPage.waitFor(`!document.querySelector('#repos').textContent.includes('member-out')`);
  454. check('a member of only that one repo has the row dropped from the open private-org list', true);
  455. stopFrames(); await anon.close(); await bobPage.close();
  456. } catch (e) {
  457. check('the gate ran without an exception', false, String(e && e.stack || e).replace(/(?:gtr|gat|gak)_[a-f0-9]+/g, '[redacted]'));
  458. if (log) console.log(log.slice(-3000));
  459. if (pg) { console.log(pg.dumpConsole()); console.log(await pg.evaluate(`JSON.stringify({ title: document.title, heading: document.querySelector('#reponame')?.textContent, input: document.querySelector('#display-name')?.value, active: document.activeElement?.id, text: document.querySelector('#title-form')?.textContent })`)); }
  460. } finally {
  461. for (const t of [anon, bobPage]) { try { if (t) await t.close(); } catch {} }
  462. try { if (pg) await pg.close(); if (browser) { if (browser.owned) await browser.close(); else browser.conn.close(); } } catch {}
  463. if (beforePages) {
  464. let after = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');
  465. if (pg && after.some(t => t.id === pg.targetId) && !beforePages.some(t => t.id === pg.targetId)) await fetch(process.env.HL_CDP_URL + '/json/close/' + pg.targetId);
  466. after = (await (await fetch(process.env.HL_CDP_URL + '/json/list')).json()).filter(t => t.type === 'page');
  467. writeFileSync(join(STORE, 'chrome-after.json'), J(after.map(t => ({ id: t.id, title: t.title, url: t.url.split('?')[0] }))));
  468. check('shared Chrome original tabs preserved and own tab closed', after.length === beforePages.length && after.every(t => beforePages.some(b => b.id === t.id)));
  469. }
  470. if (chromeLock) { chromeLock.stdin.end(); await new Promise(r => chromeLock.once('exit', r)); }
  471. await stop().catch(() => {}); try { receiver.close(); } catch {} try { ident && await ident.stop(); } catch {}
  472. writeFileSync(join(STORE, 'server.log'), log);
  473. console.log(`\n${passes} passed, ${failures} failed`); process.exit(failures ? 1 : 0);
  474. }

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