gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit5e11184c5e11184cW60: record partial validation, framework gaps and cleanupmre5e11184c/tests/cleanup-browser.mjs

13.3 KB

  1. // W60: one own plain tab in the existing Chrome, real clicks and keys, own test storage.
  2. // Usage: TMPDIR=<scratch>/tmp HL_CDP_URL=http://127.0.0.1:9223 node tests/cleanup-browser.mjs <old app> <output root>
  3. import { spawn, execFileSync } from 'node:child_process';
  4. import { createServer } from 'node:http';
  5. import { mkdirSync, writeFileSync, readFileSync } from 'node:fs';
  6. import { resolve, join } from 'node:path';
  7. import { launchBrowser } from './cdp.mjs';
  8. import { startIdent } from './identkit.mjs';
  9. const OUT = resolve(process.argv[3]), CURRENT = resolve('.'), OLD = resolve(process.argv[2]);
  10. const PORT = 8731, IPORT = 8732, TPORT = 8733;
  11. const J = JSON.stringify, sleep = ms => new Promise(r => setTimeout(r, ms));
  12. let passed = 0, failed = 0, browser, page, ident, server, fixture;
  13. const pids = [], shots = [];
  14. function check(name, ok) { console.log(`${ok ? 'ok' : 'FAIL'} ${name}`); ok ? passed++ : failed++; }
  15. function track(name, p) { pids.push({name,pid:p.pid}); console.log('PROCESS', name, p.pid); return p; }
  16. async function stop(p) { if (!p || p.exitCode !== null || p.signalCode !== null) return; p.kill('SIGTERM'); await Promise.race([new Promise(r=>p.once('exit',r)),sleep(3000)]); }
  17. async function up(url) { for (const end = Date.now()+240000; Date.now()<end;) { try { if ((await fetch(url)).ok) return; } catch {} await sleep(250); } throw new Error('server did not start '+url); }
  18. async function go(url, ready) { await page.goto(url); await page.waitForSelector(ready,{timeout:30000}); await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1',{timeout:30000}); }
  19. async function shot(tag,name,width) { const path=join(OUT,`${tag}-${name}-${width}.png`); const {data}=await page.send('Page.captureScreenshot',{format:'png',captureBeyondViewport:true});writeFileSync(path,Buffer.from(data,'base64'));shots.push(path); }
  20. const val = sel => page.evaluate(`document.querySelector(${J(sel)}).value`);
  21. async function clear(sel) { await page.focus(sel); await page.send('Input.dispatchKeyEvent',{type:'keyDown',key:'a',code:'KeyA',modifiers:2,windowsVirtualKeyCode:65});await page.send('Input.dispatchKeyEvent',{type:'keyUp',key:'a',code:'KeyA',modifiers:2,windowsVirtualKeyCode:65});await page.send('Input.dispatchKeyEvent',{type:'keyDown',key:'Backspace',code:'Backspace',windowsVirtualKeyCode:8});await page.send('Input.dispatchKeyEvent',{type:'keyUp',key:'Backspace',code:'Backspace',windowsVirtualKeyCode:8}); }
  22. async function shClick(selector) { const b=await page.waitFor(`(()=>{const e=document.querySelector('#selector')?.shadowRoot?.querySelector(${J(selector)});if(!e)return null;e.scrollIntoView({block:'center'});const b=e.getBoundingClientRect();return b.width?{x:b.left+b.width/2,y:b.top+b.height/2}:null})()`,{timeout:30000});for(const [type,buttons]of[['mouseMoved',0],['mousePressed',1],['mouseReleased',0]])await page.send('Input.dispatchMouseEvent',{...b,type,buttons,button:'left',clickCount:1}); }
  23. async function httpFace(base,cookie,event,payload) { const r=await fetch(base+'/__hl/emit',{method:'POST',headers:{cookie,'content-type':'application/json'},body:J({t:'emit',i:Date.now(),event,payload})});const j=await r.json();return j.value; }
  24. try {
  25. mkdirSync(OUT,{recursive:true});
  26. // A dedicated HTTP fixture for the external tickets service. Every write stays in this process.
  27. let tickets=[];
  28. fixture=createServer(async(req,res)=>{ const u=new URL(req.url,`http://127.0.0.1:${TPORT}`);let b='';for await(const c of req)b+=c;
  29. if(u.pathname==='/connect'){res.writeHead(302,{location:u.searchParams.get('return')+'?code=w60&state='+encodeURIComponent(u.searchParams.get('state'))});res.end();return;}
  30. res.setHeader('content-type','application/json');
  31. if(u.pathname==='/api/connect/exchange'){res.end(J({key:'tktc_w60',project:'w60',title:'W60 test tickets',api:`http://127.0.0.1:${TPORT}/api/projects/w60`}));return;}
  32. if(u.pathname==='/api/projects/w60/tickets'&&req.method==='POST'){const j=JSON.parse(b);const t={number:tickets.length+1,subject:j.subject,state:'Open',stateSlug:'open',created:'2026-11-06',updated:'2026-11-06',href:'/projects/w60/'+(tickets.length+1)};tickets.unshift(t);res.writeHead(201);res.end(J({ticket:t}));return;}
  33. if(u.pathname==='/api/projects/w60/tickets'){res.end(J({tickets}));return;}res.end('{}');
  34. });await new Promise(r=>fixture.listen(TPORT,'127.0.0.1',r));
  35. ident=await startIdent({identDir:'/media/STORAGE/projects/WorldAPI/ident.worldapi.org',workDir:join(OUT,'ident'),port:IPORT});track('ident',ident.proc);
  36. const alice=await ident.signIn('[email protected]'), bob=await ident.signIn('[email protected]');
  37. const initial=await(await fetch('http://127.0.0.1:9223/json/list')).json();writeFileSync(join(OUT,'targets-before.json'),J(initial,null,2));
  38. browser=await launchBrowser();browser.disconnect=()=>browser.conn.close();page=await browser.newPage();writeFileSync(join(OUT,'owned-target.txt'),page.targetId);await browser.conn.send('Target.activateTarget',{targetId:page.targetId});
  39. execFileSync('ssh-keygen',['-q','-t','ed25519','-N','','-f',join(OUT,'test-key')]);
  40. const key=readFileSync(join(OUT,'test-key.pub'),'utf8').trim();
  41. for(const[tag,appDir]of[['before',OLD],['after',CURRENT]]){
  42. tickets=[];const base=`http://w60-${tag}.localhost:${PORT}`, repo=`http://alpha.w60-${tag}.localhost:${PORT}`;
  43. const store=join(OUT,tag);mkdirSync(store,{recursive:true});
  44. const app=await ident.registerApp(alice,'W60 '+tag,[base,`http://*.w60-${tag}.localhost:${PORT}`]);
  45. server=track('gitoria-'+tag,spawn(join(appDir,'bin/hybriel'),['project.hl'],{cwd:appDir,env:{...process.env,GITORIA_PORT:String(PORT),GITORIA_STORAGE:join(store,'mpackdb'),GITORIA_GIT:join(store,'git'),GITORIA_SESSIONS:join(store,'sessions')+'/',GITORIA_WATCH:'0',GITORIA_PUBLIC_URL:base,GITORIA_SSH_SECRET:'w60-fixture',GITORIA_APP_HOSTS:`http://127.0.0.1:${TPORT}`,GITORIA_TICKETS_URL:`http://127.0.0.1:${TPORT}`,IDENT_URL:`http://ident.w60-${tag}.localhost:${IPORT}`,IDENT_EXCHANGE_URL:ident.base,IDENT_API_KEY:app.key,IDENT_API_SECRET:app.secret},stdio:['ignore','pipe','pipe']}));
  46. const log=[];server.stdout.on('data',x=>log.push(x));server.stderr.on('data',x=>log.push(x));await up(`http://127.0.0.1:${PORT}/api/repos`);
  47. // Seed Bob's name in this test store so Alice can add him through the member form.
  48. const cb=await fetch(`http://127.0.0.1:${PORT}/login/callback?ident_code=`+await ident.selectorCode(bob,app,base),{redirect:'manual'});const bobCookie=cb.headers.get('set-cookie').split(';')[0];await httpFace(`http://127.0.0.1:${PORT}`,bobCookie,'gitoriaSaveName',['Bob']);
  49. // Log in through the actual ident selector, including its hidden bound code bridge.
  50. const[n,v]=alice.cookie.split('=');await page.send('Network.setCookie',{name:n,value:v,url:`http://ident.w60-${tag}.localhost:${IPORT}/`,httpOnly:true});
  51. await page.send('Emulation.setDeviceMetricsOverride',{width:390,height:844,deviceScaleFactor:1,mobile:true});
  52. await go(base+'/','#heading');await shClick('#choose');await shClick('[part~="identity"]');
  53. await page.waitForSelector('#nameform',{timeout:30000});await page.type('#displayname','Alice');await page.click('#namesave');await page.waitForSelector('#createform',{timeout:30000});
  54. for(const width of [390,1280]){
  55. await page.send('Emulation.setDeviceMetricsOverride',{width,height:width===390?844:900,deviceScaleFactor:1,mobile:width<600});
  56. await go(base+'/','#createform');await shot(tag,'repositories',width);
  57. const slug=width===390?'alpha':'beta';await page.type('#slug',slug);await page.type('#description','W60 test repository');await page.click('#createsave');await page.waitFor(`document.querySelector('#created')?.textContent.includes(${J(slug)})`,{timeout:30000});
  58. check(`${tag} ${width}: repo fields clear and row appears once`,await val('#slug')===''&&await val('#description')===''&&await page.evaluate(`[...document.querySelectorAll('#repos li .slug')].filter(e=>e.textContent===${J(slug)}).length===1`));
  59. // A refusal preserves the existing draft, just as on the starting tree.
  60. await page.type('#slug',slug);await page.type('#description','keep failed draft');await page.click('#createsave');await page.waitFor(`document.querySelector('#createerror').textContent.length>0`);check(`${tag} ${width}: failed repo keeps draft`,await val('#description')==='keep failed draft');await clear('#slug');await clear('#description');
  61. await page.type('#tokenname','Laptop '+width);await page.click('#tokensave');await page.waitFor(`document.querySelector('#tokenlist').textContent.includes('Laptop ${width}')`,{timeout:30000});check(`${tag} ${width}: token clears and appears once`,await val('#tokenname')===''&&await page.evaluate(`document.querySelectorAll('#tokenlist li').length===1`));await shot(tag,'tokens',width);await page.click('#tokenlist button');await page.waitFor(`document.querySelectorAll('#tokenlist li').length===0`);
  62. await page.type('#keyname','Laptop '+width);await page.type('#keytext',key);await page.click('#keysave');await page.waitFor(`document.querySelector('#keylist').textContent.includes('Laptop ${width}')`,{timeout:30000});check(`${tag} ${width}: key clears and appears once`,await val('#keyname')===''&&await val('#keytext')===''&&await page.evaluate(`document.querySelectorAll('#keylist li').length===1`));await shot(tag,'keys',width);await page.click('#keylist button');await page.waitFor(`document.querySelectorAll('#keylist li').length===0`);
  63. await go(base+'/','#createform');check(`${tag} ${width}: second visit has one repo and no removed credentials`,await page.evaluate(`[...document.querySelectorAll('#repos .slug')].filter(e=>e.textContent===${J(slug)}).length===1&&document.querySelectorAll('#keylist li,#tokenlist li').length===0`));
  64. await go(repo+'/settings','#memberform');await shot(tag,'settings',width);await page.type('#membername','Bob');await page.click('#memberadd');await page.waitFor(`document.querySelector('#members').textContent.includes('Bob')`,{timeout:30000});check(`${tag} ${width}: member clears and appears once`,await val('#membername')===''&&await page.evaluate(`document.querySelectorAll('#members li').length===1`));
  65. await go(repo+'/settings','#memberform');check(`${tag} ${width}: second visit retains member`,await page.evaluate(`document.querySelectorAll('#members li').length===1`));await page.click('#members button');await page.waitFor(`document.querySelectorAll('#members li').length===0`);
  66. await page.type('#appname','Review '+width);await page.type('#apphook',`http://127.0.0.1:${TPORT}/receiver`);await page.click('#appadd');await page.waitFor(`document.querySelector('#applist').textContent.includes('Review ${width}')`,{timeout:30000});check(`${tag} ${width}: app fields clear`,await val('#appname')===''&&await val('#apphook')==='');
  67. await page.type('#requiredcontext','build');await page.click('#requiredadd');await page.waitFor(`document.querySelector('#requiredlist').textContent.includes('build')`,{timeout:30000});check(`${tag} ${width}: required context clears`,await val('#requiredcontext')==='');await page.click('#requiredlist button');await page.waitFor(`document.querySelectorAll('#requiredlist li').length===0`);await page.click('#applist button:last-child');await page.waitFor(`document.querySelectorAll('#applist li').length===0`);
  68. await page.click('#connecttickets');await page.waitFor(`document.querySelector('#connectedto')?.textContent.includes('W60 test tickets')`,{timeout:30000});
  69. await go(repo+'/tickets','#newticket');await page.click('#newticket > summary');await shot(tag,'tickets',width);const subject='Ticket '+width;await page.type('#ticketsubject',subject);await page.type('#ticketsummary','A test ticket');await page.click('#ticketsave');await page.waitFor(`document.querySelector('#ticketlist')?.textContent.includes(${J(subject)})`,{timeout:30000});check(`${tag} ${width}: ticket fields clear and row appears once`,await val('#ticketsubject')===''&&await val('#ticketsummary')===''&&await page.evaluate(`[...document.querySelectorAll('#ticketlist .subject')].filter(e=>e.textContent===${J(subject)}).length===1`));
  70. await go(repo+'/tickets','#ticketlist');check(`${tag} ${width}: second visit retains ticket once`,await page.evaluate(`[...document.querySelectorAll('#ticketlist .subject')].filter(e=>e.textContent===${J(subject)}).length===1`));
  71. await page.setOffline(true);await page.waitFor(`!!document.querySelector('#offline')`,{timeout:5000});check(`${tag} ${width}: Chrome offline shows exact note`,await page.evaluate(`document.querySelector('#offline').textContent==='You are offline. Repositories and code need the network.'`));await shot(tag,'offline',width);await page.setOffline(false);await page.waitFor(`!document.querySelector('#offline')`,{timeout:5000});check(`${tag} ${width}: Chrome online hides note`,true);
  72. }
  73. await stop(server);writeFileSync(join(OUT,tag+'-server.log'),Buffer.concat(log));server=null;
  74. }
  75. } catch(e){failed++;console.log('FAIL walk',e.stack);if(page)console.log('CONSOLE',page.dumpConsole().slice(-2500));}
  76. finally{
  77. try{if(page){await page.setOffline(false);await page.close();}}catch{}
  78. try{if(browser)browser.disconnect();}catch{}
  79. await stop(server);if(ident)await ident.stop();if(fixture)await new Promise(r=>fixture.close(r));
  80. writeFileSync(join(OUT,'processes.json'),J(pids,null,2));writeFileSync(join(OUT,'screenshots.json'),J(shots,null,2));
  81. try{const final=await(await fetch('http://127.0.0.1:9223/json/list')).json();writeFileSync(join(OUT,'targets-after.json'),J(final,null,2));}catch{}
  82. console.log(`${passed} passed, ${failed} failed`);
  83. }
  84. process.exitCode=failed?1:0;

Branches

Latest commits

  • 5e11184cW60: record partial validation, framework gaps and cleanupmre
  • 20fe13fagitoria#33: centralize login and tickets connection statemre
  • 859754c0gitoria#29: retain the offline note and record the framework gapmre
  • d140bc04gitoria#30: reproduce the upsert ordering constraintmre
  • 6960e8f8gitoria#28: keep form values in bound component membersmre
  • 0db27200gitoria#32: share character checks and environment lookupmre
  • 452f6a1amission W60: logic clean-upsmre
  • 1448c899log: cleanup, #49 GPTBot, tracker mentions on #36mre
  • fcf95936log: v1.5.1 provenmre
  • 22105420log: W51b livemre
  • 7e8aabeareport: W51b pull source verificationmre
  • 6c18de76fix: preserve pull sources across containing branchesmre
  • fc36fa2elog: W51b pull source bugmre
  • 56bc1220log: v1.5.1 livemre
  • 845fc0aareport: W51mre
  • 83127391fix: return v1.5.1 app and merge error detailsmre
  • b07d0e97log: W51 v1.5.1 startedmre
  • 0b417d06docs: apps-api v1.5 user tokens (#48, W49)mre
  • d046940alog: vinzenz contract note sentmre
  • db443456log: vinzenz note retry 2mre