// Optional browser regression test; see README for setup. Uses an isolated app copy. import { chromium } from './artifacts/node_modules/playwright/index.mjs'; import { mkdtemp, cp, mkdir, rm } from 'node:fs/promises'; import { spawn, execFileSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import path from 'node:path'; import assert from 'node:assert/strict'; const web=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'); const root=await mkdtemp(path.join(web,'tests/artifacts/browser-')); for(const f of ['api.php','index.php','auth.php','callback.php','router.php','sw.js','manifest.webmanifest','lib','assets'])await cp(path.join(web,f),path.join(root,f),{recursive:true,filter:source=>path.basename(source)!=='tablebase'}); await mkdir(path.join(root,'data')); const port=18081; const server=spawn('php',['-S',`127.0.0.1:${port}`,'-t',root,path.join(root,'router.php')],{stdio:'ignore'}); const base=`http://127.0.0.1:${port}`; let browser; try{ for(let i=0;i<100;i++){try{await fetch(base);break;}catch{await new Promise(r=>setTimeout(r,50));}} browser=await chromium.launch({headless:true,args:['--no-sandbox']}); const ca=await browser.newContext({viewport:{width:1440,height:1080}}),cb=await browser.newContext({viewport:{width:1440,height:1080}}); const a=await ca.newPage(),b=await cb.newPage(),errors=[]; for(const p of[a,b]){p.on('pageerror',e=>errors.push(e.message));p.on('console',m=>{if(m.type()==='error')errors.push(m.text());});} await a.goto(base); const intro=a.locator('#notification-dialog'); await intro.waitFor({state:'visible'}); assert.equal(await intro.locator('p').innerText(),"Do you want to be notified when it's your turn? Enable the Notification setting in the Account Settings panel at the top right of the page.",'Exact once-only notification introduction'); await intro.getByRole('button',{name:'Got it',exact:true}).click(); await a.reload();await a.locator('#avatar-button').waitFor(); assert.equal(await intro.isVisible(),false,'Introduction stays dismissed after reload'); await b.goto(base);await b.locator('#avatar-button').waitFor(); assert.equal(await b.locator('#notification-dialog').isVisible(),false,'Introduction is remembered across browser profiles'); await a.evaluate(()=>{ const request=Notification.requestPermission,subscribe=PushManager.prototype.subscribe,permission=Object.getOwnPropertyDescriptor(Notification,'permission'); window.restoreNotificationMocks=()=>{Notification.requestPermission=request;PushManager.prototype.subscribe=subscribe;Object.defineProperty(Notification,'permission',permission);delete navigator.brave;}; Object.defineProperty(Notification,'permission',{get:()=>'granted',configurable:true}); Notification.requestPermission=async()=>'granted'; PushManager.prototype.subscribe=async()=>{throw new DOMException('Registration failed - push service error','AbortError');}; Object.defineProperty(navigator,'brave',{value:{isBrave:async()=>true},configurable:true}); }); await a.locator('#settings-button').click(); await a.locator('[data-toggle-push]').click(); await intro.getByRole('heading',{name:'Enabling notifications failed'}).waitFor(); assert((await intro.innerText()).includes('This may be due to Brave'),'Brave advice does not assert an unproven cause'); assert.equal(await intro.locator('#push-settings-page').inputValue(),'brave://settings/privacy','Concrete Brave settings page'); assert((await intro.innerText()).includes('Use Google services for push messaging'),'Concrete Brave setting'); assert(await a.locator('#modal').evaluate(el=>el.open),'Account dialog remains open underneath error'); await a.screenshot({path:path.join(web,'tests/artifacts/notification-error-desktop.png')}); await a.keyboard.press('Escape'); await intro.waitFor({state:'hidden'}); assert(await a.locator('#modal').evaluate(el=>el.open),'Escape only closes the top dialog'); assert(await a.locator('[data-toggle-push]').evaluate(el=>el===document.activeElement),'Focus returns to notification setting'); await a.evaluate(()=>{navigator.brave.isBrave=async()=>false;}); await a.locator('[data-toggle-push]').click(); await intro.getByRole('heading',{name:'Enabling notifications failed'}).waitFor(); assert((await intro.innerText()).includes('If you use Brave'),'Other browsers get conditional Brave advice'); await a.setViewportSize({width:390,height:844}); assert(await intro.evaluate(el=>el.getBoundingClientRect().width<=innerWidth),'Error fits a mobile viewport'); await a.screenshot({path:path.join(web,'tests/artifacts/notification-error-mobile.png')}); await intro.getByRole('button',{name:'Got it',exact:true}).click(); await a.setViewportSize({width:1440,height:1080}); await a.evaluate(()=>window.restoreNotificationMocks()); await a.locator('#modal-close').click(); await a.locator('#avatar-button').click(); await a.locator('[data-avatar-choice="blue-knight"]').waitFor(); await a.locator('[data-avatar-group="fairy"]').click(); assert.equal(await a.locator('.avatar-choice').count(),67,'Retained fairy collection is selectable'); await a.locator('#avatar-color').selectOption('Pink'); assert.equal(await a.locator('.avatar-choice').count(),3,'All pink fairy pieces are present'); await a.locator('[data-avatar-choice="pink-ferz"]').click(); await a.locator('#avatar-button img[src$="pink-ferz.png"]').waitFor(); await a.reload(); await a.locator('#avatar-button img[src$="pink-ferz.png"]').waitFor(); await a.locator('#avatar-button').click(); await a.locator('[data-avatar-choice="blue-knight"]').waitFor(); await a.locator('[data-avatar-group="standard"]').click(); await a.locator('#avatar-color').selectOption('White'); assert.equal(await a.locator('.avatar-choice').count(),6,'Six white standard chess pieces'); await a.locator('#avatar-color').selectOption('Black'); assert.equal(await a.locator('.avatar-choice').count(),6,'Six black standard chess pieces'); await a.locator('#avatar-color').selectOption('Blue'); assert.equal(await a.locator('.avatar-choice').count(),6,'Six blue standard chess pieces'); await a.screenshot({path:path.join(web,'tests/artifacts/avatar-picker-desktop.png')}); await a.locator('[data-avatar-choice="blue-knight"]').click(); await a.locator('#avatar-button img[src$="blue-knight.png"]').waitFor(); await a.reload();await a.locator('#avatar-button img[src$="blue-knight.png"]').waitFor(); await b.locator('#settings-button').click();await b.getByRole('button',{name:'Switch to test_user_2'}).click(); await b.locator('#account-summary').getByText('test_user_2',{exact:false}).waitFor(); await b.locator('#notification-dialog').getByRole('button',{name:'Got it',exact:true}).click(); await a.locator('#friend-link').click();await a.locator('#share-url').waitFor(); const friendLink=await a.locator('#share-url').inputValue(); await a.locator('#modal-close').click(); await b.goto(friendLink);await b.getByRole('button',{name:'Accept',exact:true}).click(); await a.locator('#friend-list [data-friend="local:test_user_2"]').waitFor(); await b.locator('#friend-list [data-friend="local:test_user_1"] img[src$="blue-knight.png"]').waitFor(); await a.locator('#friend-list [data-friend="local:test_user_2"]').click();await a.getByRole('button',{name:'Challenge to a game'}).click(); await b.getByRole('button',{name:'Accept',exact:true}).click(); await a.locator('.board').waitFor();await b.locator('.board').waitFor(); await b.locator('.card-header img[src$="blue-knight.png"]').waitFor(); async function state(p){return p.evaluate(async()=>{const r=await fetch('api.php');return r.json();});} async function post(p,action,fields={}){return p.evaluate(async({action,fields})=>{const s=await(await fetch('api.php')).json();const r=await fetch('api.php',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':s.csrf},body:JSON.stringify({action,...fields})});const out=await r.json();if(!r.ok)throw Error(out.error);return out;},{action,fields});} const initial=await state(a),id=initial.games[0].id; await a.goto(`${base}/?game=${id}`); await a.locator(`[data-game="${id}"] .notification-highlight`).waitFor(); assert.equal(new URL(a.url()).searchParams.has('game'),false,'Notification link is consumed after loading games'); assert.equal(await a.locator('#modal').evaluate(el=>el.open),false,'Notification opens the home screen'); await a.evaluate(()=>renderGames()); assert.equal(await a.locator('.notification-highlight').count(),1,'Highlight survives rerender'); await a.locator('.notification-highlight').waitFor({state:'detached'}); await a.evaluate(()=>renderGames()); assert.equal(await a.locator('.notification-highlight').count(),0,'Highlight does not repeat on polling'); await a.emulateMedia({reducedMotion:'reduce'}); await a.goto(`${base}/?game=${id}`); await a.locator('.notification-highlight-static').waitFor(); await a.emulateMedia({reducedMotion:'no-preference'}); await a.locator('.notification-highlight').waitFor({state:'detached'}); const manifest=await (await fetch(`${base}/manifest.webmanifest`)).json(); assert.equal(manifest.start_url,'./','Manifest supports deployment in a subdirectory'); assert(await a.evaluate(async()=>!!(await navigator.serviceWorker.ready).active),'Service worker activates'); const white=initial.games[0].color==='w'?a:b,black=white===a?b:a; await white.locator(`[data-game="${id}"] [data-square="15"]`).click(); assert.equal(await white.locator(`[data-game="${id}"] .legal`).count(),1,'Pawn legal dot'); await white.locator(`[data-game="${id}"] [data-square="11"]`).click(); const held=white.locator(`#your-games [data-game="${id}"]`); await held.locator('[data-square="11"]:disabled').waitFor(); const heldAt=Date.now(),heldRect=await held.boundingBox(); assert.equal(await white.locator('.material-bar').getAttribute('aria-valuenow'),'50','Equal starting material gives 50/50'); assert.equal(await black.locator('.material-bar').getAttribute('aria-valuenow'),'50','Material orientation is the same for Black'); assert.equal(await held.locator('.move-feedback').count(),0,'Quiet opening move receives no pulse'); assert.equal(await held.locator('.square:not([disabled])').count(),0,'Confirmed move immediately disables held board'); await white.waitForTimeout(2200); assert.equal(await held.count(),1,'Moved tile stays in Your Turn during pause'); assert.equal(await held.locator('.move-feedback').count(),0,'Feedback stops after one event'); await white.evaluate(()=>renderGames()); assert.equal(await held.locator('.move-feedback').count(),0,'Rerender does not replay feedback'); assert(Math.abs((await held.boundingBox()).y-heldRect.y)<1,'Held tile stays in its original position'); const relocated=white.locator(`#waiting-games [data-game="${id}"]`); await relocated.waitFor({state:'attached'}); assert(Date.now()-heldAt>=2800,'Tile waits approximately three seconds before relocating'); assert(await relocated.evaluate(el=>el.getAnimations().length>0),'Tile animates to the waiting grid'); await relocated.evaluate(el=>Promise.all(el.getAnimations().map(a=>a.finished))); await black.locator(`[data-game="${id}"] [data-square="4"]:not([disabled])`).waitFor(); assert.equal(await white.locator('#waiting-games .square:not([disabled])').count(),0,'Waiting board inert'); // Actual pointer drag. const from=await black.locator(`[data-game="${id}"] [data-square="4"]`).boundingBox(); const to=await black.locator(`[data-game="${id}"] [data-square="8"]`).boundingBox(); await black.mouse.move(from.x+from.width/2,from.y+from.height/2);await black.mouse.down();await black.mouse.move(to.x+to.width/2,to.y+to.height/2,{steps:8});await black.mouse.up(); await white.locator(`[data-game="${id}"] [data-square="11"]:not([disabled])`).waitFor(); assert.equal((await state(white)).games[0].state.ply,2,'Drag move saved'); // Real tactical evaluations, using board fixtures only in this disposable game database. async function tacticalFixture(pieces){ const board=Array(20).fill('.');for(const [i,piece] of Object.entries(pieces))board[Number(i)]=piece; const position={board,turn:'w',halfmove:0,ply:2,history:[board.join('')+'w'],last:null}; execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$q=$db->prepare('UPDATE games SET state=?,version=version+1 WHERE id=?');$q->execute([$argv[2],$argv[3]]);`,path.join(root,'data/microchess.sqlite'),JSON.stringify(position),String(id)]); await white.evaluate(()=>refresh(true)); } for(const [quality,pieces,reduced] of [ ['good',{19:'K',3:'k',12:'R',8:'q'},false], ['poor',{19:'K',1:'k',12:'Q',8:'p',0:'r'},false], ['good',{19:'K',3:'k',12:'R',8:'q'},true], ]){ await white.emulateMedia({reducedMotion:reduced?'reduce':'no-preference'}); await tacticalFixture(pieces); await white.locator(`[data-game="${id}"] [data-square="12"]:not([disabled])`).click(); const started=Date.now(); await white.locator(`[data-game="${id}"] [data-square="8"]`).click(); const pulse=white.locator(`[data-game="${id}"] .move-feedback.${quality}`); await pulse.waitFor({state:'attached'}); assert(Date.now()-started<3000,'Actual API feedback arrives within tile pause locally'); assert.equal(await black.locator('.move-feedback').count(),0,'Only the mover receives feedback'); const bar=white.locator(`[data-game="${id}"] .material-bar`),fill=bar.locator('.material-white'); assert.equal(await bar.getAttribute('aria-valuenow'),quality==='good'?'100':'64','Captured material updates the bar'); if(reduced){ assert.equal(await pulse.evaluate(el=>el.getAnimations().length),0,'Reduced motion shows static feedback'); assert.equal(await fill.evaluate(el=>el.getAnimations().length),0,'Reduced motion updates material without animation'); } else{ await white.evaluate(()=>renderGames()); assert(await pulse.evaluate(el=>el.getAnimations()[0].currentTime>0),'Rerender continues pulse instead of restarting it'); assert(await fill.evaluate(el=>el.getAnimations().length>0),'Material fill interpolates through rerender'); await white.waitForTimeout(250); await white.screenshot({path:path.join(web,`tests/artifacts/feedback-${quality}.png`)}); } await pulse.waitFor({state:'detached'}); const expected=quality==='good'?1:9/14; assert(Math.abs(await fill.evaluate(el=>new DOMMatrixReadOnly(getComputedStyle(el).transform).a)-expected)<.001,'Material fill settles at correct proportion'); await black.evaluate(()=>refresh(true)); assert.equal(await black.locator(`[data-game="${id}"] .material-bar`).getAttribute('data-share'),await bar.getAttribute('data-share'),'Polling uses the same White-left ratio for Black'); await white.evaluate(()=>renderGames()); assert.equal(await white.locator('.move-feedback').count(),0,'Completed pulse is not replayed'); } await white.emulateMedia({reducedMotion:'no-preference'}); const kingsBar=await white.evaluate(()=>materialBar({color:'w',state:{board:['K','k',...Array(18).fill('.')]}})); assert(kingsBar.includes('data-share="0.5"'),'Bare kings give a neutral material bar'); await white.evaluate(() => { window.savedFlights = 0; const original = Element.prototype.animate; Element.prototype.animate = function (...args) { if (this.classList.contains('saved-hourglass')) window.savedFlights++; return original.apply(this, args); }; }); // Fixture a legal promotion position in the isolated database. const fixture={board:['.','.','.','k','.','P','.','.','.','.','.','.','.','.','.','.','K','.','.','.'],turn:'w',halfmove:0,ply:2,history:[],last:null}; fixture.history=[fixture.board.join('')+'w']; execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$q=$db->prepare('UPDATE games SET state=?,version=version+1 WHERE id=?');$q->execute([$argv[2],$argv[3]]);`,path.join(root,'data/microchess.sqlite'),JSON.stringify(fixture),String(id)]); await white.waitForTimeout(3000); await white.locator(`[data-game="${id}"] [data-square="5"]`).click();await white.locator(`[data-game="${id}"] [data-square="1"]`).click(); assert.equal(await white.locator('[data-promotion]').count(),4,'Four promotion options'); await white.locator('[data-promotion="n"]').click(); await white.getByRole('heading',{name:'A game well matched.'}).waitFor(); assert.equal((await state(white)).games[0].state.board[1],'N','Underpromotion saved'); for(const page of [white,black]){ await page.locator('.end-content').waitFor(); assert.equal(await page.locator('.ended-board .square').count(),20,'Final board remains visible for both players'); assert.equal(await page.locator('.ended-board .square.last').count(),2,'Final move stays highlighted'); await page.mouse.move(0,0); await page.waitForTimeout(850); assert(Math.abs(Number(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity))-.72)<.01,'Result starts translucent'); await page.locator('.end-content').hover();await page.waitForTimeout(850); assert.equal(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity),'1','Hover reveals result controls'); } assert.equal(await white.evaluate(()=>window.savedFlights),1,'Finished game animates to history once'); assert.equal(await white.locator(`#your-games [data-game="${id}"]`).count(),1,'Finished game stays in Your Turn'); assert.equal(await black.locator(`#your-games [data-game="${id}"]`).count(),1,'Opponent finished game also stays in Your Turn'); await white.locator('#history-button').click(); await white.locator('.history-entry').waitFor(); await white.locator('.history-entry').first().click(); await white.locator('#replay-card .board').waitFor(); assert.equal(await white.locator('#replay-card [data-square="5"] img').count(),1,'Replay starts before promotion'); assert.equal(await white.locator('.replay-controls button').count(),5,'Replay has start, step, play, step and end controls'); await white.locator('[data-replay-control="end"]').click(); assert.match(await white.locator('#replay-card [data-square="1"] img').getAttribute('src'),/nlt/,'Replay preserves underpromotion'); await white.locator('[data-replay-control="start"]').click(); assert.match(await white.locator('#replay-progress').innerText(),/^0 \/ 1/,'Jump to start returns to beginning'); await white.locator('[data-replay-control="play"]').click(); assert.equal(await white.locator('[data-replay-control="play"]').getAttribute('aria-label'),'Pause','Play becomes pause'); await white.waitForTimeout(600); assert.match(await white.locator('#replay-progress').innerText(),/^1 \/ 1/,'Autoplay advances to end'); assert.equal(await white.locator('[data-replay-control="play"]').getAttribute('aria-label'),'Play','Autoplay stops at end'); assert.equal(await white.locator('#replay-card .material-bar').count(),0,'Replay replaces opponent header and material bar'); assert.equal(await white.locator('.replay-players img[alt="White"]').count(),1,'White king identifies white player'); assert.equal(await white.locator('.replay-players img[alt="Black"]').count(),1,'Black king identifies black player'); await white.context().grantPermissions(['clipboard-read','clipboard-write']); await white.locator('#replay-share').click(); const replayUrl=await white.evaluate(()=>navigator.clipboard.readText()); assert.match(replayUrl,/\?replay=[a-f0-9]{48}$/,'Chain button copies a share URL'); const guestContext=await browser.newContext(),guest=await guestContext.newPage(); guest.on('pageerror',e=>errors.push(e.message)); await guest.goto(replayUrl); await guest.locator('#replay-card .board').waitFor(); assert.equal(await guest.locator('.replay-players').innerText(),await white.locator('.replay-players').innerText(),'Shared page identifies both players'); assert.equal(await guest.locator('#history-return').count(),0,'Public replay has no private history navigation'); assert.equal(await guest.locator('.replay-bottom a[href="./"]').innerText(),'Microchess ↗','Public replay links to the home page'); assert.equal(await guest.locator('dialog, #modal-close, .topbar, .login, #sidebar').count(),0,'Standalone replay has no dialog, close button or background UI'); await guest.keyboard.press('Escape'); await guest.locator('#replay-card .board').waitFor(); await guest.locator('body').click({position:{x:4,y:4}}); await guest.locator('#replay-card .board').waitFor(); await guest.setViewportSize({width:390,height:844}); assert(await guest.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),'Standalone replay fits mobile width'); await guest.screenshot({path:path.join(web,'tests/artifacts/shared-replay-mobile.png')}); await guest.reload(); await guest.locator('#replay-card .board').waitFor(); await guest.locator('[data-replay-control="end"]').click(); assert.match(await guest.locator('#replay-card [data-square="1"] img').getAttribute('src'),/nlt/,'Shared replay plays the same promotion'); await guestContext.close(); await black.goto(replayUrl); await black.locator('#replay-card .board').waitFor(); assert.equal(await black.locator('#replay-page').count(),1,'Signed-in visitor sees the standalone shared replay'); assert.equal(await black.locator('.topbar, .login, #sidebar, #your-games').count(),0,'Signed-in shared replay has no account chrome'); await black.goto(base); await black.locator('#your-games').waitFor(); await white.screenshot({path:path.join(web,'tests/artifacts/game-replay.png')}); await white.locator('#modal-close').click(); await white.evaluate(()=>refresh(true)); assert.equal(await white.locator('.saved-hourglass').count(),0,'Saved animation does not repeat'); await white.getByRole('button',{name:'Rematch',exact:true}).click(); await white.locator(`#waiting-games [data-game="${id}"]`).waitFor(); assert.equal(await white.locator(`#your-games [data-game="${id}"]`).count(),0,'Requested rematch leaves Your Turn'); await black.getByText(/wants a rematch/).waitFor(); assert.equal(await black.locator(`#your-games [data-game="${id}"]`).count(),1,'Opponent rematch offer stays in Your Turn'); await black.getByRole('button',{name:'Rematch',exact:true}).click(); await white.locator('.board').waitFor(); assert.equal((await state(white)).games[0].color,'b','Rematch flips colors'); // Three real game links for desktop layout coverage. for(let i=0;i<3;i++){const link=await post(a,'create_link',{kind:'match'});await post(b,'accept_link',{token:new URL(link.url).searchParams.get('invite')});} await a.reload();await a.locator('.game-card').nth(3).waitFor(); await a.screenshot({path:path.join(web,'tests/artifacts/desktop.png'),fullPage:true}); assert(await a.locator('.square img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'All SVG pieces load'); await a.setViewportSize({width:1440,height:640}); await a.evaluate(()=>scrollTo(0,document.body.scrollHeight)); const sidebar=await a.locator('#sidebar').boundingBox(); assert(sidebar.y>=-1&&sidebar.y+sidebar.height<=641,`Desktop sidebar fits viewport while scrolling: ${JSON.stringify(sidebar)}`); assert.equal(await a.locator('#sidebar').evaluate(e=>getComputedStyle(e).position),'sticky'); const staleId=(await state(a)).games[0].id; execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$db->exec('UPDATE games SET activity_at=unixepoch()-8*86400 WHERE id='.(int)$argv[2]);`,path.join(root,'data/microchess.sqlite'),String(staleId)]); await a.locator(`[data-game="${staleId}"] .stop-inactive`).click(); await a.getByText('This game has been inactive for 8 days. Would you like to stop it?').waitFor(); await a.getByRole('button',{name:'Cancel',exact:true}).click(); assert((await state(a)).games.some(g=>g.id===staleId),'Cancel retains game'); await a.locator(`[data-game="${staleId}"] .stop-inactive`).click(); await a.getByRole('button',{name:'Stop game',exact:true}).click(); await a.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'}); await b.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'}); await a.setViewportSize({width:390,height:844}); assert(await a.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),'No mobile horizontal overflow'); assert.equal(await a.locator('#your-games').evaluate(e=>getComputedStyle(e).gridTemplateColumns.split(' ').length),1,'One tile column'); await a.locator('#friends-toggle').click();await a.locator('#sidebar.open').waitFor();await a.waitForTimeout(250); await a.locator('#avatar-button').click(); await a.locator('[data-avatar-group="fairy"]').click(); await a.locator('#avatar-color').selectOption('Purple'); await a.locator('[data-avatar-choice="purple-elephant"]').waitFor(); await a.locator('.avatar-choice img').evaluateAll(imgs=>Promise.all(imgs.map(i=>i.decode()))); assert(await a.locator('.avatar-choice img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'Fairy avatars load'); await a.screenshot({path:path.join(web,'tests/artifacts/avatar-picker-mobile.png')}); await a.locator('[data-avatar-choice="purple-elephant"]').click(); await a.locator('#avatar-button img[src$="purple-elephant.png"]').waitFor(); await a.screenshot({path:path.join(web,'tests/artifacts/mobile-friends.png'),fullPage:false}); await a.locator('#friends-close').click();await a.waitForTimeout(250);await a.screenshot({path:path.join(web,'tests/artifacts/mobile.png'),fullPage:true}); // Touch events exercise the mobile pointer path, not mouse emulation. const sa=await state(a),sb=await state(b); const owner=sa.games.some(g=>g.yourTurn)?a:b; const mobileContext=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,storageState:await owner.context().storageState()}); const touch=await mobileContext.newPage();await touch.goto(base); const tg=(await state(touch)).games.find(g=>g.yourTurn),tm=tg.legal[0]; const fs=touch.locator(`[data-game="${tg.id}"] [data-square="${tm.from}"]`); await fs.scrollIntoViewIfNeeded();const fb=await fs.boundingBox(); const tb=await touch.locator(`[data-game="${tg.id}"] [data-square="${tm.to}"]`).boundingBox(); const cdp=await mobileContext.newCDPSession(touch); await cdp.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x:fb.x+fb.width/2,y:fb.y+fb.height/2}]}); for(let i=1;i<=8;i++)await cdp.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:fb.x+fb.width/2+(tb.x-fb.x)*i/8,y:fb.y+fb.height/2+(tb.y-fb.y)*i/8}]}); await cdp.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]}); await touch.waitForTimeout(500); assert.equal((await state(touch)).games.find(g=>g.id===tg.id).state.ply,tg.state.ply+1,'Mobile touch drag saved'); assert.equal(await touch.locator(`#your-games [data-game="${tg.id}"]`).count(),1,'Mobile move also stays in place'); const mobileWaiting=touch.locator(`#waiting-games [data-game="${tg.id}"]`); await mobileWaiting.waitFor({state:'attached'}); assert(await mobileWaiting.evaluate(el=>el.getAnimations().length>0),'Mobile tile also slides to waiting grid'); await mobileContext.close(); // New game offers matchmaking below the link, with persistent cancellation. await a.setViewportSize({width:1440,height:1080}); await a.locator('#match-link').click(); await a.getByRole('button',{name:'Challenge a random player',exact:true}).waitFor(); const linkBox=await a.locator('#share-url').boundingBox(); const matchBox=await a.getByRole('button',{name:'Challenge a random player',exact:true}).boundingBox(); assert(matchBox.y>linkBox.y,'Random challenge is below invite link'); await a.getByRole('button',{name:'Challenge a random player',exact:true}).click(); await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor(); await a.reload(); await a.getByRole('button',{name:'Cancel search',exact:true}).waitFor(); await a.locator('#match-link').click(); await a.locator('#matchmaking-actions').getByRole('button',{name:'Cancel search'}).waitFor(); await a.locator('#matchmaking-actions').getByRole('button',{name:'Cancel search'}).click(); await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor({state:'detached'}); await a.locator('#match-link').click(); await a.getByRole('button',{name:'Challenge a random player',exact:true}).click(); await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor(); const priorIds=new Set((await state(a)).games.map(g=>g.id)); await b.locator('#match-link').click(); await b.getByRole('button',{name:'Challenge a random player',exact:true}).click(); await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor({state:'detached'}); const randomGame=(await state(a)).games.find(g=>!priorIds.has(g.id)); assert(randomGame,'Matchmaking creates a new game'); for(const p of[a,b]) await p.locator(`[data-game="${randomGame.id}"] .board`).waitFor(); assert.match(await a.locator('#account-summary').innerText(),/\d+ Elo/,'Own rating is visible'); assert.equal(await a.locator(`[data-game="${randomGame.id}"] .rating`).innerText(),String(randomGame.opponentRating),'Opponent rating is visible'); // The same rivalry modal is available from a game and the friends list. await post(a,'remove_friend',{friend:'local:test_user_2'}); await a.reload(); await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click(); const rivalryStats=await a.locator('.stats').innerText(); await a.getByRole('button',{name:'Send friend request',exact:true}).click(); await a.locator('#modal').waitFor({state:'hidden'}); await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click(); assert(await a.getByRole('button',{name:'Friend request sent',exact:true}).isDisabled(),'Sender sees pending status'); await a.locator('#modal-close').click(); await b.locator('#friend-requests').getByRole('button',{name:'Reject',exact:true}).click(); await b.locator('.friend-request').waitFor({state:'detached'}); await a.reload(); await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click(); await a.getByRole('button',{name:'Send friend request',exact:true}).click(); await b.reload(); await b.setViewportSize({width:390,height:844}); await b.locator('#friends-toggle').click(); await b.locator('#friend-requests').getByRole('button',{name:'Accept',exact:true}).click(); await b.locator('#friend-list [data-friend="local:test_user_1"]').waitFor(); await b.locator('.friend-request').waitFor({state:'detached'}); await a.locator('#friend-list [data-friend="local:test_user_2"]').waitFor(); await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click(); assert.equal(await a.locator('.stats').innerText(),rivalryStats,'Game modal retains rivalry history'); await a.getByRole('button',{name:'Challenge to a game'}).waitFor(); await a.locator('#modal-close').click(); await a.locator('#friend-list [data-friend="local:test_user_2"]').click(); assert.equal(await a.locator('.stats').innerText(),rivalryStats,'Friend and game modals show identical statistics'); await a.locator('#modal-close').click(); assert.deepEqual(errors,[],'No browser errors'); console.log('Browser: friendship, challenge, click/drag moves, promotion, rematch, SVGs, desktop and mobile checks passed.'); }finally{ await browser?.close();if(server.exitCode===null && server.signalCode===null){const exited=new Promise(r=>server.once('exit',r));server.kill();await exited;}await rm(root,{recursive:true,force:true}); }