const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'); (async()=>{const installed=process.argv.includes('--installed'),profile=fs.mkdtempSync('/tmp/pd-icon-pwa-');const c=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1666,height:1050}}):await(await chromium.launch()).newContext({viewport:{width:1666,height:1050}});const b=c.browser(),base='http://127.0.0.1:5238';try{ await c.addInitScript(()=>localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()}))); await c.route('**/native-companion/status*',r=>r.fulfill({json:{leases:[]}})); let p;if(installed){const tab=c.pages()[0];await tab.goto(base+'/fixture');const d=await b.newBrowserCDPSession(),manifestId=base+'/Projects';await d.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture'});await d.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=c.waitForEvent('page');await d.send('PWA.launch',{manifestId,url:base+'/fixture'});p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else p=await c.newPage(); await c.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'))})); const url=base+'/Writer/Explore?projectId=7&bookId=12',root=p.locator('[data-explore-investigation]'),journey=p.locator('[data-explore-journey]'),layout=p.locator('[data-explore-layout]'); p.setDefaultTimeout(20000);let navigations=0;p.on('request',r=>{if(r.isNavigationRequest()&&r.frame()===p.mainFrame())navigations++;}); const idle=()=>p.waitForFunction(()=>!document.querySelector('[data-explore-investigation]').hasAttribute('aria-busy')); const start=async()=>{await root.getByRole('tab',{name:'New investigation',exact:true}).click();await journey.locator('[name=concern]').first().check();await journey.getByRole('button',{name:'Begin',exact:true}).click();await idle();await p.waitForFunction(()=>!document.querySelector('[data-explore-layout]').hasAttribute('data-resize-animating'));return new URL(p.url()).searchParams.get('investigation');}; const token=()=>root.locator('[name=__RequestVerificationToken]').first().inputValue(); const payload=async id=>({id,projectId:'7',bookId:'12',__RequestVerificationToken:await token()}); const post=(data)=>p.request.post(base+'/Writer/Explore/Investigate/Delete',{form:data}); const landing=async()=>{await journey.getByRole('link',{name:'Return to Explore',exact:true}).evaluate(n=>n.click());await journey.getByRole('button',{name:'Begin',exact:true}).waitFor();await idle();await p.waitForFunction(()=>!document.querySelector('[data-explore-layout]').hasAttribute('data-resize-animating'));}; const selectSaved=async()=>{await root.getByRole('tab',{name:'Saved investigations',exact:true}).click();}; let menuCaptured=false; const openDelete=async id=>{const button=p.locator(`[data-explore-saved] [data-investigation-delete="${id}"]`);if(await button.locator('..').getAttribute('open')===null)await button.locator('..').locator('summary').click();if(!menuCaptured){for(const theme of ['modern-light','modern-dark']){await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);await p.screenshot({path:`/tmp/pd-deletion-evidence/${installed?'pwa':'browser'}-${theme}-actions.png`});}menuCaptured=true;}await button.click();await p.getByRole('dialog',{name:'Delete this investigation?',exact:true}).waitFor();}; const dialog=()=>p.getByRole('dialog',{name:'Delete this investigation?',exact:true}); await p.goto(url);await journey.getByRole('button',{name:'Begin',exact:true}).waitFor();await idle();const initialNav=navigations; const active=await start(),stale=await journey.locator('[data-investigation-answer]').evaluate(f=>Object.fromEntries(new FormData(f))); await journey.getByRole('button',{name:'Keep this investigation alongside my work',exact:true}).click();await p.waitForFunction(id=>window.PlotDirectorGuidanceSummary?.summary?.id===id,active); const sibling=await c.newPage();await sibling.goto(url+'&investigation='+active);await sibling.locator('[data-inline-investigation]').waitFor();await p.bringToFront(); stale.option=await journey.locator('[name=option]').first().inputValue();stale.operation='answer'; const bounds=await layout.boundingBox(),handle=p.locator('[data-explore-divider]'),rect=await handle.boundingBox();await p.mouse.move(rect.x+rect.width/2,rect.y+80);await p.mouse.down();await p.mouse.move(bounds.x+(bounds.width-rect.width)*.4+rect.width/2,rect.y+80,{steps:10});await p.mouse.up(); const pref=()=>p.evaluate(()=>JSON.parse(localStorage.getItem(Object.keys(localStorage).find(k=>k.startsWith('plotdirector.writerExploreLayout.')))).leftRatio); assert(Math.abs(await pref()-.4)<.005); await journey.getByRole('button',{name:'Discard investigation',exact:true}).click();fs.mkdirSync('/tmp/pd-deletion-evidence',{recursive:true});await dialog().screenshot({path:`/tmp/pd-deletion-evidence/${installed?'pwa':'browser'}-confirmation.png`});for(const theme of ['modern-light','modern-dark']){await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);await dialog().screenshot({path:`/tmp/pd-deletion-evidence/${installed?'pwa':'browser'}-${theme}-confirmation.png`});}await dialog().locator('[data-dialog-action=cancel]').click();assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+active)).status(),200); assert.equal((await p.request.post(base+'/Writer/Explore/Investigate/Delete',{form:{id:active,bookId:'12',projectId:'7'}})).status(),400);assert.equal((await post({...await payload(active),projectId:'8'})).status(),404);assert.equal((await post({...await payload(active),bookId:'13'})).status(),404); const other=await b.newContext();await other.addCookies([{name:'fixture-user',value:'5',url:base}]);const html=await(await other.request.get(base+'/fixture')).text(),otherToken=html.match(/name="__RequestVerificationToken"[^>]*value="([^"]+)"/)[1];assert.equal((await other.request.post(base+'/Writer/Explore/Investigate/Delete',{form:{id:active,projectId:'7',bookId:'12',__RequestVerificationToken:otherToken}})).status(),404);await other.close(); let fail=true;await c.route('**/Writer/Explore/Investigate/Delete',r=>fail?r.fulfill({status:503,json:{message:'Fixture failure'}}):r.continue()); await journey.getByRole('button',{name:'Discard investigation',exact:true}).click();await dialog().locator('[data-dialog-action=delete]').click();await dialog().locator('[data-dialog-error]:not([hidden])').waitFor();assert(await dialog().isVisible());assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+active)).status(),200);fail=false; await p.evaluate(()=>{window.deletionFrames=[];window.deletionSampling=true;function frame(){window.deletionFrames.push(Number(document.querySelector('[data-explore-layout]').style.getPropertyValue('--explore-ratio')));if(window.deletionSampling)requestAnimationFrame(frame);}requestAnimationFrame(frame);}); await dialog().locator('[data-dialog-action=delete]').click();await dialog().waitFor({state:'detached'});await journey.getByRole('button',{name:'Begin',exact:true}).waitFor();await idle();await p.waitForFunction(()=>!document.querySelector('[data-explore-layout]').hasAttribute('data-resize-animating'));await p.evaluate(()=>window.deletionSampling=false); assert((await p.evaluate(()=>window.deletionFrames)).filter(v=>v>.405&&v<.495).length>=4,'Discard visibly animates back to landing');assert.equal(await layout.getAttribute('data-explore-state'),'landing');assert(Math.abs(await pref()-.4)<.005);assert.equal(await p.evaluate(()=>sessionStorage.getItem('writer.explore.active.12')),null);assert.equal(new URL(p.url()).searchParams.has('investigation'),false);await p.waitForFunction(()=>window.PlotDirectorGuidanceSummary?.active===false);assert.equal(await p.locator('[data-discovery-active] [data-tile]').count(),0); assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+active)).status(),404);assert.equal((await p.request.post(base+'/Writer/Explore/Investigate/Answer',{form:stale})).status(),404);assert.equal((await post(await payload(active))).status(),200); await sibling.getByRole('button',{name:'Begin',exact:true}).waitFor();assert.equal(await sibling.evaluate(()=>sessionStorage.getItem('writer.explore.active.12')),null);assert.equal(await sibling.locator('[data-explore-layout]').getAttribute('data-explore-state'),'landing');await sibling.close(); await c.unroute('**/Writer/Explore/Investigate/Delete'); const unrelated=await start();await landing(); for(const completed of [false,true]){ const id=await start(); if(completed){for(let n=0;n<20&&await journey.locator('[data-investigation-answer]').count();n++){await journey.locator('[name=option]').first().check();await journey.locator('button[value=answer]').click();await idle();}assert.equal(await journey.locator('[data-investigation-answer]').count(),0,'Completed investigation fixture');} else{const area=journey.locator('textarea');if(await area.count())await area.fill('Disposable saved draft');await journey.locator('button[value=save]').click();await idle();} await landing();await selectSaved();await openDelete(id);await dialog().locator('[data-dialog-action=cancel]').click();assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+id)).status(),200);await openDelete(id);await dialog().locator('[data-dialog-action=delete]').click();await dialog().waitFor({state:'detached'});await p.waitForFunction(id=>!document.querySelector(`[data-explore-saved] [data-investigation-delete="${id}"]`),id);assert.equal((await p.request.get(base+'/Writer/Explore/Investigate?bookId=12&id='+unrelated)).status(),200); } await selectSaved();await openDelete(unrelated);await dialog().locator('[data-dialog-action=delete]').click();await dialog().waitFor({state:'detached'});await p.locator('[data-explore-saved]').filter({hasText:'No saved investigations yet.'}).waitFor();assert.equal(navigations,initialNav,'No full document reload during delete/discard'); for(const theme of ['modern-light','modern-dark']){await p.evaluate(t=>window.PlotDirectorApplyApplicationTheme(t),theme);fs.mkdirSync('/tmp/pd-deletion-evidence',{recursive:true});await p.screenshot({path:`/tmp/pd-deletion-evidence/${installed?'pwa':'browser'}-${theme}.png`});} console.log('PASS '+(installed?'installed PWA':'browser')+' deletion/discard, cancel, error retention/retry, ownership/project/book, stale answer/resume, repeats, saved/completed/partial, empty/unrelated lists, session cleanup and animated landing with retained preference'); }finally{await c.close();await b.close();fs.rmSync(profile,{recursive:true,force:true});}})().catch(e=>{console.error(e);process.exitCode=1});