/** Responsive and OAuth navigation fixtures. No real HF login is claimed. */
import {chromium} from 'playwright';
import {readFile,writeFile,mkdir} from 'node:fs/promises';
import assert from 'node:assert/strict';
const origin='http://127.0.0.1:7860',hub='https://huggingface.co/spaces/fffiloni/idol-commons-dev';
const presets=JSON.parse(await readFile('frontend/src/idol-presets.json','utf8'));
const browser=await chromium.launch({headless:true,args:['--no-sandbox','--disable-dev-shm-usage','--use-gl=angle','--use-angle=swiftshader','--enable-unsafe-swiftshader']});
await mkdir('reports/screenshots',{recursive:true});
try {
const context=await browser.newContext({viewport:{width:1512,height:982},reducedMotion:'reduce'});
const page=await context.newPage(),errors=[],sizes=[],navigations=[];page.on('request',r=>{if(r.isNavigationRequest())navigations.push(r.url());});page.on('pageerror',e=>errors.push(e.message));
let selectedImage=null,resume=null,generation=null;
await context.route('**/api/session',r=>{const s={csrf:'fixture',user:null,sign_in_available:true,generation_available:true,image_generation_available:true,publication_available:false,dataset:'test/collection',resume_tab:resume};resume=null;return r.fulfill({json:s});});
await context.route('**/api/workspace',r=>r.fulfill({json:{image:selectedImage,job:null}}));
await context.route('**/api/catalogue',r=>r.fulfill({json:{meta:{assetCount:0,generators:{}},assets:r.request().frame().url().includes('explore.html')?[]:[{demoExample:'examples/fig-axolotl.webp',id:'12345678-1234-4234-8234-123456789abc',author:'fixture-author'}]}}));
await context.route('**/api/images',r=>{selectedImage={id:'selected-example',url:'/fixture/input.png'};return r.fulfill({json:selectedImage});});
await context.route('**/fixture/input.png',r=>r.fulfill({path:'frontend/public/examples/fig-axolotl.webp',contentType:'image/webp'}));
await context.route('**/api/generations',r=>{generation=r.request().postDataJSON();return r.fulfill({json:{id:'fixture-job',image_id:selectedImage.id,parameters:generation.parameters,status:'failed',error:'Test fixture: no GPU inference requested'}});});
await page.goto(origin+'/?tab=create',{waitUntil:'networkidle'});
await page.getByRole('button',{name:'Browse all 94 examples',exact:true}).click();
let dialog=page.getByRole('dialog',{name:'IDOL example library'});await dialog.waitFor();
assert.equal(await dialog.locator('.example-grid button').count(),12);
await dialog.getByRole('button',{name:'Next examples',exact:true}).click();
assert.match(await dialog.locator('.example-pagination').textContent(),/2 \/ 8/);
await dialog.getByLabel('Find an example').fill('axolotl');
assert.equal(await dialog.locator('.example-grid button').count(),1);
await dialog.getByRole('button',{name:'Use Axolotl example',exact:true}).click();
await page.getByAltText('Your input image',{exact:true}).waitFor();
await page.getByText('Original IDOL preset loaded. You can adjust it below.',{exact:true}).waitFor();
await page.getByRole('button',{name:'View existing contribution',exact:true}).waitFor();
await page.getByRole('button',{name:'Generate 3D',exact:true}).click();
await page.getByRole('button',{name:'Keep image & retry',exact:true}).waitFor();
const p=presets.find(p=>p.title==='Axolotl');
assert.deepEqual(generation.parameters,{mode:p.mode,steps:p.steps,cfg_strength:p.cfg,rescale_t:p.rescale_t,seed:p.seed,randomize_requested:false,num_gaussians:p.num_gaussians});
await page.getByRole('button',{name:'Keep image & retry',exact:true}).click();
for(const [width,height] of [[1512,982],[1440,900],[1280,800],[1024,768],[900,700],[820,1000],[1000,820],[720,960],[960,720],[700,900],[390,844],[320,740],[844,390],[1512,982]]){
await page.setViewportSize({width,height});
await page.waitForTimeout(100);
if(width<1440)await page.getByRole('button',{name:'Contribute',exact:true}).click();
const layout=await page.evaluate(()=>{
const rect=s=>{const b=document.querySelector(s).getBoundingClientRect();return {x:b.x,y:b.y,w:b.width,h:b.height};};
const a=rect('.upload-target'),b=rect('.replace-image');
return {overflow:document.documentElement.scrollWidth>innerWidth,split:document.querySelector('.commons').classList.contains('is-split'),create:rect('.create-page'),explore:rect('.explore-page'),replaceCenterError:Math.abs((a.x+a.w/2)-(b.x+b.w/2)),steps:[...document.querySelectorAll('.contribution-steps li')].map(li=>{const a=li.querySelector('.step-number').getBoundingClientRect(),b=li.querySelector('.step-label').getBoundingClientRect();return {circleError:Math.abs(a.width-a.height),centerError:Math.abs((a.y+a.height/2)-(b.y+b.height/2))};})};
});
const theme=await page.getByRole('group',{name:'Color theme'}).boundingBox(),account=await page.locator('.account').boundingBox(),brand=await page.locator('.commons-brand').boundingBox();
assert.ok(theme&&account&&brand&&theme.x>=account.x&&theme.x+theme.width<=width&&brand.x+brand.width<=account.x,'Secondary appearance control must stay beside account without overlapping brand');
assert.equal(await page.locator('.workspace-controls .theme-control').count(),0);
assert.equal(layout.overflow,false,JSON.stringify({width,layout}));assert.equal(layout.split,width>=1440);
assert.ok(layout.replaceCenterError<1);assert.ok(layout.steps.every(x=>x.circleError<.1&&x.centerError<1));
if(width>=1440){assert.ok(layout.create.w>=500&&layout.explore.w>=760);assert.ok(layout.create.x+layout.create.w<=layout.explore.x+1);}
else {assert.equal(await page.locator('.explore-page').isVisible(),false);await page.getByRole('button',{name:'Collection',exact:true}).click();assert.equal(await page.locator('.create-page').isVisible(),false);await page.getByRole('button',{name:'Contribute',exact:true}).click();}
assert.equal(await page.getByAltText('Your input image',{exact:true}).count(),1);
if([1512,820,390,844].includes(width)){
await page.evaluate(()=>{document.querySelector('.create-page').scrollTo(0,0);window.scrollTo(0,0);});
await page.screenshot({path:`reports/screenshots/responsive-${width}-${height}.jpg`,type:'jpeg',quality:78,animations:'disabled',timeout:60000});
}
sizes.push({width,height,...layout});console.log(JSON.stringify({stage:'responsive_size_passed',width,height}));
}
// Simulate the Hub sandbox and issuer callback in a separate top-level tab.
// Server OIDC verification is covered separately in Python.
await context.route(hub,r=>r.fulfill({contentType:'text/html',body:``}));
await context.route('**/auth/login?tab=create',r=>{resume='create';return r.fulfill({contentType:'text/html',body:``});});
// Intercepted redirects bypass further Playwright routes in a redirect chain.
// These issuer pages initiate distinct navigations; real server 303 destinations
// and OIDC state checks are asserted by test_oauth_navigation.py.
await context.route('**/auth/callback?*',r=>r.fulfill({contentType:'text/html',body:``}));
await page.setViewportSize({width:390,height:844});await page.goto(hub,{waitUntil:'networkidle'});
let app=page.frameLocator('iframe[title=Space]');await app.getByRole('button',{name:'Contribute',exact:true}).click();
const popupPromise=context.waitForEvent('page');await app.getByRole('link',{name:'Sign in with Hugging Face',exact:false}).click();const popup=await popupPromise;
try{await popup.waitForURL(hub,{waitUntil:'domcontentloaded',timeout:15000});}catch(e){console.log(JSON.stringify({stage:'oauth_fixture_navigation_failure',url:page.url(),navigations:navigations.slice(-12),frames:page.frames().map(f=>f.url())}));await page.screenshot({path:'reports/screenshots/oauth-fixture-failure.jpg',timeout:10000}).catch(()=>{});throw e;}await page.waitForTimeout(300);
app=popup.frameLocator('iframe[title=Space]');await app.getByRole('heading',{name:'Bring an idea to the commons.',exact:true}).waitFor();
assert.equal(context.pages().length,2);assert.equal(page.url(),hub);assert.equal(popup.url(),hub);assert.equal(await app.getByAltText('Your input image',{exact:true}).count(),1);
await app.locator('.advanced summary').click();
assert.equal(await app.getByLabel('Choose a new seed each time',{exact:true}).isChecked(),false);
assert.equal(await app.getByLabel('Seed',{exact:true}).inputValue(),String(p.seed));
assert.deepEqual(errors,[]);
const report={browser:browser.version(),sizes,originalPresets:presets.length,exactPresetParameters:true,livePublicExampleFetch:true,exampleGallerySearchAndPagination:true,existingExampleNotice:true,newTabSandboxHubReturnFixture:true,workspaceRestored:true,realOAuthCompleted:false,physicalFoldableTested:false};
await writeFile('reports/responsive-acceptance.json',JSON.stringify(report,null,2)+'\n');
console.log(JSON.stringify({stage:'responsive_acceptance_passed',...report}));
await context.close();
}finally{await browser.close();}