PlotDirector/PlotLine.Tests/Browser/writer3-investigations.cjs

16 lines
8.5 KiB
JavaScript

const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('fs');
const base=process.env.PD_INV_BASE||'http://127.0.0.1:5238',identity=process.env.PD_INV_IDENTITY?JSON.parse(fs.readFileSync(process.env.PD_INV_IDENTITY)):null,w=identity||{UserID:4,book:12,other:13,project:7};
const report=JSON.parse(fs.readFileSync(process.env.PD_INV_COVERAGE||'Docs/Writer/Writer3/Evidence/Phase3D1/simulation.json'));const path=report.RepresentativePaths.find(p=>p.concern==='story'&&p.target==='motivation'&&p.recommendations.includes('motivation'));assert(path,'unexpected destination witness');
(async()=>{const browser=await chromium.launch();try{for(const pwa of[false,true]){const c=await browser.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(({user,pwa})=>{localStorage.setItem('plotdirector.desktop.v1.'+user,JSON.stringify({dismissedAt:Date.now()}));if(pwa)Object.defineProperty(navigator,'standalone',{value:true});},{user:w.UserID,pwa});const p=await c.newPage(),errors=[],external=[];p.on('pageerror',e=>errors.push(e.message));p.on('request',r=>{if(/openai|anthropic|generativelanguage|inference/i.test(r.url()))external.push(r.url());});if(identity){await p.goto(base+'/Account/Login');await p.locator('[name=Email]').fill(w.Email);await p.locator('[name=Password]').fill(w.Password);await Promise.all([p.waitForURL('**/Projects'),p.locator('button[type=submit]').click()]);}
await p.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`);await p.getByRole('link',{name:'Explore a concern',exact:true}).click();assert((await p.locator('#investigation-question').textContent()).includes("What's troubling"));assert.equal(await p.locator('iframe').count(),0);assert((await p.locator('#ribbon-panel-writer a[aria-current=page]').allTextContents()).some(t=>t.trim()==='Explore'));assert.equal(await p.locator('#ribbon-panel-writer a[href*="writing-problems"]').count(),0);if(process.env.PD_INV_SCREENSHOTS&&!pwa){fs.mkdirSync(process.env.PD_INV_SCREENSHOTS,{recursive:true});await p.screenshot({path:process.env.PD_INV_SCREENSHOTS+'/Explore-investigation-start.png'});}
await p.locator('[name=concern][value=story]').check();await p.getByRole('button',{name:'Begin',exact:true}).click();await p.locator('[data-investigation-answer]').waitFor();const id=new URL(p.url()).searchParams.get('id'),url=p.url();const explanation=p.locator('#investigation-explanation');await explanation.fill('Unfinished explanation retained for later');await p.getByRole('button',{name:'Save for later',exact:true}).click();assert.equal(await p.locator('#investigation-explanation').inputValue(),'Unfinished explanation retained for later');
let firstQuestion;for(const entry of path.answers){const form=p.locator('[data-investigation-answer]');if(!await form.count())break;const current=await form.locator('[name=question]').inputValue();firstQuestion??=current;const expected=path.answers.find(x=>x.startsWith(current+'='));assert(expected,'dynamic current question is in deterministic witness');await form.locator(`[name=option][value="${expected.split('=')[1]}"]`).check();await form.locator('[name=explanation]').fill('Synthetic browser answer <script>text only</script>');await form.locator('button[value=answer]').click();}
assert.equal(await p.locator('[data-investigation-answer]').count(),0);assert((await p.locator('#investigation-question').textContent()).includes('possible next step'));assert((await p.locator('body').textContent()).includes('Character'));assert.equal(external.length,0);const open=p.locator('form[action$="/Open"]').first();const formData=await open.evaluate(f=>Object.fromEntries(new FormData(f)));formData.capability=await open.locator('[name=capability]').getAttribute('value');const destination=await p.request.post(base+'/Writer/Explore/Investigate/Open',{form:formData,maxRedirects:0});assert.equal(destination.status(),302);assert(!destination.headers().location.toLowerCase().includes('solver'));assert(destination.headers().location.includes('projectId='+w.project));assert(destination.headers().location.includes('bookId='+w.book));await p.reload();
if(process.env.PD_INV_SCREENSHOTS&&!pwa)await p.screenshot({path:process.env.PD_INV_SCREENSHOTS+'/Explore-investigation-result.png'});
assert.equal((await p.request.get(`${base}/Writer/Explore/Investigate?bookId=${w.other}&id=${id}`)).status(),404);assert.equal((await p.request.post(base+'/Writer/Explore/Investigate/Start',{form:{bookId:String(w.book),concern:'story'},maxRedirects:0})).status(),400);
firstQuestion='motivation-4';await p.goto(url+'&question='+firstQuestion);const stale=await p.locator('[data-investigation-answer]').evaluate(f=>Object.fromEntries(new FormData(f)));stale.operation='answer';stale.option='unsure';stale.explanation='Keep this stale browser text';const q=await c.newPage();await q.goto(url+'&question='+firstQuestion);await q.locator('[name=option][value=yes]').check();await q.locator('button[value=answer]').click();await q.close();const conflict=await p.request.post(base+'/Writer/Explore/Investigate/Answer',{form:stale,maxRedirects:0});assert.equal(conflict.status(),409);assert((await conflict.text()).includes('Keep this stale browser text'));await p.goto(url);assert((await p.locator('body').textContent()).includes('questions answered'));
await p.setViewportSize({width:390,height:844});assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await p.locator('[name=option]').first().focus();await p.keyboard.press('Space');assert(await p.locator('[name=option]').first().isChecked());if(process.env.PD_INV_SCREENSHOTS&&!pwa)await p.screenshot({path:process.env.PD_INV_SCREENSHOTS+'/Explore-investigation-narrow.png'});await p.locator('[data-help-key="writer3.investigations"] button').click();await p.locator('.plotline-help-popover').waitFor();await p.locator('.plotline-help-more').click();await p.locator('[data-help-content] .help-drawer-article').waitFor();await p.locator('[data-help-close]').click();
if(!identity){assert.equal((await p.request.get(base+'/admin/writer-investigations')).status(),403);const other=await browser.newContext();await other.addCookies([{name:'fixture-user',value:'5',url:base}]);assert.equal((await other.request.get(url)).status(),404);await other.close();await c.addCookies([{name:'solver-reviewer',value:'true',url:base}]);assert.equal((await p.request.get(base+'/admin/writer-investigations')).status(),200);const diag=await(await p.request.get(`${base}/admin/writer-investigations/diagnostics?bookId=${w.book}&id=${id}`)).json();assert(diag.events.length>8);assert(diag.evaluation.candidates.length>0);const sim=await p.request.get(`${base}/admin/writer-investigations/simulator?bookId=${w.book}&id=${id}`);assert.equal(sim.status(),200);assert(!(await sim.text()).includes('matches: False'));const exp=await(await p.request.get(base+'/admin/writer-investigations/export')).json();assert(exp.Synthetic);assert.equal(diag.investigation.catalogueVersion,exp.Version);if(!pwa){const admin=await p.request.get(base+'/admin/writer-investigations');const token=(await admin.text()).match(/name="__RequestVerificationToken"[^>]*value="([^"]+)"/)[1];const bad=structuredClone(exp);bad.Questions[0].Options[0].Contributions[0].Weight=99;assert.equal((await p.request.post(base+'/admin/writer-investigations',{form:{json:JSON.stringify(bad),operation:'publish',__RequestVerificationToken:token}})).status(),400);assert.equal((await(await p.request.get(base+'/admin/writer-investigations/export')).json()).Version,exp.Version);exp.Version='synthetic-browser-next';assert.equal((await p.request.post(base+'/admin/writer-investigations',{form:{json:JSON.stringify(exp),operation:'publish',__RequestVerificationToken:token}})).status(),200);assert.equal((await(await p.request.get(base+'/admin/writer-investigations/export')).json()).Version,exp.Version);assert.notEqual((await(await p.request.get(`${base}/admin/writer-investigations/diagnostics?bookId=${w.book}&id=${id}`)).json()).investigation.catalogueVersion,exp.Version);}
}
assert.deepEqual(errors,[]);await c.close();}console.log('PASS Guided Investigation browser/simulated PWA: authenticated Explore, dynamic deterministic witness from general concern to character destination, saved unfinished explanation, resume, authored evidence summary, safe scoped destination, CSRF400, cross-book404, stale409 retained text, revision, narrow keyboard/radio/overflow, Markdown Help, no iframe or AI calls; isolated admin diagnostics/replay and cross-user controls where enabled.');}finally{await browser.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1});