diff --git a/PlotLine.Tests/Browser/context-panel-lifecycle.cjs b/PlotLine.Tests/Browser/context-panel-lifecycle.cjs new file mode 100644 index 00000000..87745896 --- /dev/null +++ b/PlotLine.Tests/Browser/context-panel-lifecycle.cjs @@ -0,0 +1,4 @@ +const{chromium}=require('playwright'),fs=require('fs'),assert=require('node:assert/strict'); +(async()=>{const b=await chromium.launch();try{const p=await b.newPage({viewport:{width:1440,height:1000}});const panel=side=>``;await p.setContent(`
${panel('left')}
Main work
${panel('right')}
`);await p.addScriptTag({content:fs.readFileSync('PlotLine/wwwroot/js/context-panels.js','utf8')});await p.evaluate(()=>{window.panels={};for(const root of document.querySelectorAll('[data-context-panel]')){const values={};panels[root.dataset.side]=PlotDirectorContextPanels.create(root,{read:k=>values[k],write:(k,v)=>values[k]=v,changed:({state})=>{if(root.dataset.side==='right'){root.parentElement.classList.toggle('help-open',state!=='closed');root.parentElement.classList.toggle('help-collapsed',state==='collapsed');}}});}}); +for(const left of['open','collapsed','closed'])for(const right of['open','collapsed','closed']){await p.evaluate(({left,right})=>{for(const[side,state]of Object.entries({left,right})){panels[side].open();if(state==='closed')panels[side].close();if(state==='collapsed')panels[side].collapse();}},{left,right});for(const[side,state]of Object.entries({left,right})){const r=p.locator(`[data-side=${side}]`);assert.equal(await r.isVisible(),state!=='closed');assert.equal(await r.locator('.plotline-help-drawer-panel').isVisible(),state==='open');assert.equal(await r.locator('[data-panel-expand]').isVisible(),state==='collapsed');}} +await p.evaluate(()=>{panels.left.open();panels.right.open();panels.left.pin();panels.left.collapse();panels.right.close();});assert.equal(await p.locator('[data-side=left]').getAttribute('data-state'),'collapsed');await p.evaluate(()=>panels.left.restore());assert.equal(await p.locator('[data-side=left]').getAttribute('data-state'),'collapsed');await p.evaluate(()=>panels.left.close());await p.evaluate(()=>panels.left.restore());assert.equal(await p.locator('[data-side=left]').isVisible(),false);await p.setViewportSize({width:800,height:1000});await p.evaluate(()=>{panels.left.open();panels.right.open()});assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));console.log('PASS shared panel lifecycle: nine state combinations, independent pins/close, collapsed pin restoration, closed restoration and narrow flow');}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/PlotLine.Tests/Browser/investigation-companion.cjs b/PlotLine.Tests/Browser/investigation-companion.cjs index ecc42417..ca1c625b 100644 --- a/PlotLine.Tests/Browser/investigation-companion.cjs +++ b/PlotLine.Tests/Browser/investigation-companion.cjs @@ -1,55 +1,4 @@ -const {chromium}=require('playwright'),fs=require('fs'),assert=require('node:assert/strict'); -const live=!!process.env.PD_GUIDANCE_IDENTITY,w=live?JSON.parse(fs.readFileSync(process.env.PD_GUIDANCE_IDENTITY)):{UserID:4,project:7,book:12,otherBook:13}; -const base=live?'https://dev.plotdirector.com':'http://127.0.0.1:5238',out=process.env.PD_GUIDANCE_SCREENSHOTS; -(async()=>{const b=await chromium.launch();let state;try{ - const c=await b.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(u=>{Object.defineProperty(navigator,'standalone',{value:true});localStorage.setItem('plotdirector.desktop.v1.'+u,JSON.stringify({dismissedAt:Date.now()}));},w.UserID); - const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message)); - const snap=async name=>{if(out){fs.mkdirSync(out,{recursive:true});await p.mouse.move(2,995);await p.waitForTimeout(150);await p.screenshot({path:out+'/'+name+'.png'});}}; - const expandRibbon=async()=>{const toggle=p.locator('[data-ribbon-collapse]');if(await toggle.getAttribute('aria-expanded')==='false')await toggle.click();}; - if(live){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 expandRibbon();await p.getByRole('link',{name:'Explore a concern',exact:true}).click(); - if(live){await p.locator(`a[href*="id=${w.investigation}"]`).first().click();} - else{await p.locator('[name=concern][value=A]').check();await p.getByRole('button',{name:'Begin',exact:true}).click();for(const[q,o]of[['Q02','B'],['Q03','C'],['Q17','F'],['Q19','F'],['Q04','A'],['Q14','D'],['Q15','A'],['Q16','E']]){assert.equal(await p.locator('[data-investigation-answer] [name=question]').inputValue(),q);await p.locator(`[name=option][value=${o}]`).check();await p.getByRole('button',{name:'Continue',exact:true}).click();}w.investigation=await p.locator('[data-investigation-id]').getAttribute('data-investigation-id');} - await p.locator('[data-conclusion]').waitFor();assert.equal(await p.locator('form[target=_blank]').count(),0);const pages=c.pages().length; - if(live){await p.locator('form[action$="/Investigate/Open"]').first().getByRole('button').click();await p.waitForURL(/\/PlotLineWorkspace/);} - else{await p.getByRole('button',{name:'Keep this investigation alongside my work'}).click();await p.goto(`${base}/Writer/Write?projectId=${w.project}&bookId=${w.book}`);} - const root=p.locator('[data-investigation-companion]'),content=root.locator('[data-guidance-content]');await root.locator('#guidance-finding').waitFor();assert.equal(c.pages().length,pages); - assert.equal(await root.getAttribute('data-collapsed'),'false');assert(await p.locator('[data-app-back]').evaluate(n=>!!n.closest('#ribbon-surface')));assert.equal(await p.locator('.pd-ribbon-heading [data-app-back]').count(),0);await snap('Left-expanded-ribbon-Back'); - assert((await root.locator('#guidance-finding option').count())>=2);await root.locator('#guidance-finding').selectOption('causality');await p.waitForFunction(()=>document.querySelector('#guidance-finding')?.value==='causality'&&!document.querySelector('#guidance-finding').disabled);await p.reload();await root.locator('#guidance-finding').waitFor();assert.equal(await root.locator('#guidance-finding').inputValue(),'causality');await root.locator('#guidance-finding').selectOption('disconnected');await p.waitForFunction(()=>document.querySelectorAll('.pd-guidance-tool').length===2&&!document.querySelector('#guidance-finding').disabled); - await root.getByText('Answers that informed this suggestion',{exact:true}).click();await root.locator('details').getByText('You answered:',{exact:true}).waitFor(); - const first=root.locator('.pd-guidance-tool[data-capability=threads]');if(live)assert.equal(await first.locator('select').inputValue(),'Exploring');await first.locator('select').selectOption('Done');await p.waitForFunction(()=>document.querySelector('.pd-guidance-tool[data-capability=threads] select')?.value==='Done'&&!document.querySelector('#guidance-finding').disabled);await p.reload();await first.waitFor();assert.equal(await first.locator('select').inputValue(),'Done'); - await p.route('**/InvestigationCompanion/Update',r=>r.fulfill({status:503,json:{message:'Simulated unconfirmed progress save; previous state retained.'}}));await first.locator('select').selectOption('Skipped');await root.locator('[data-guidance-message]').filter({hasText:'unconfirmed progress'}).waitFor();assert.equal(await first.locator('select').inputValue(),'Done');await p.unroute('**/InvestigationCompanion/Update');await p.reload();await first.waitFor();assert.equal(await first.locator('select').inputValue(),'Done'); - // Right Help opens independently and does not replace guidance. - await p.evaluate(()=>PlotLineHelpDrawer.open('plotLines.workspace'));await p.locator('[data-help-content] .help-drawer-article').waitFor();await p.locator('[data-help-pin]').click();assert.equal(await root.getAttribute('data-collapsed'),'false');assert(await p.locator('[data-help-drawer]').isVisible());assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));assert((await p.locator('.plotline-help-main').boundingBox()).width>=560);await snap('Both-panels-expanded'); - await p.locator('[data-guidance-resize]').focus();for(let n=0;n<12;n++)await p.keyboard.press('ArrowRight');await p.setViewportSize({width:1100,height:1000});await p.waitForTimeout(200);assert((await p.locator('.plotline-help-main').boundingBox()).width>=560);assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));if(live)assert(await p.locator('.plot-workspace-controls').evaluate(n=>{const r=n.closest('.plotline-help-main').getBoundingClientRect();return [...n.querySelectorAll('input:not([type=hidden]),select,button')].every(c=>{const b=c.getBoundingClientRect();return b.left>=r.left&&b.right<=r.right;});}));await snap('Both-panels-minimum-centre');await p.setViewportSize({width:1440,height:1000});for(let n=0;n<12;n++)await p.keyboard.press('ArrowLeft'); - await root.locator('[data-guidance-collapse]').click();assert.equal(await root.getAttribute('data-collapsed'),'true');assert(await root.locator('.pd-investigation-panel').isHidden());await snap('Left-collapsed-tab');await p.reload();await root.locator('[data-guidance-expand]').waitFor();assert.equal(await root.getAttribute('data-collapsed'),'true');await root.locator('[data-guidance-expand]').click();await root.locator('#guidance-finding').waitFor(); - if(live){await root.locator('.pd-guidance-tool[data-capability=timeline] form button').click();await p.waitForURL(/\/Timeline/);await root.locator('#guidance-finding').waitFor();assert.equal(c.pages().length,pages);assert.equal(await root.locator('.pd-guidance-tool[data-capability=timeline]').getAttribute('data-selected'),'true');await snap('Second-destination-Timeline');} - else{await p.goto(`${base}/Writer/Review?bookId=${w.book}&projectId=${w.project}`);await root.locator('#guidance-finding').waitFor();} - await expandRibbon();await p.getByRole('tab',{name:'Writer',exact:true}).click();await p.waitForURL(u=>/\/Writer(?:\/Index)?$/.test(u.pathname));await root.locator('#guidance-finding').waitFor();await expandRibbon();await p.locator('[data-app-back]').click();await p.waitForURL(live?/\/Timeline/:/\/Writer\/Review/);await root.locator('#guidance-finding').waitFor();assert(await first.locator('select').inputValue()==='Done');await snap('Ribbon-Back-retains-guidance'); - await p.setViewportSize({width:800,height:1000});assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));assert((await root.locator('.pd-investigation-panel').boundingBox()).height<=551);await snap('Narrow-in-flow');await p.setViewportSize({width:1440,height:1000}); - state=await c.storageState();await c.close();const reopened=await b.newContext({storageState:state,viewport:{width:1440,height:1000}});await reopened.addInitScript(()=>Object.defineProperty(navigator,'standalone',{value:true}));const q=await reopened.newPage();await q.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`);await q.locator('#guidance-finding').waitFor();assert.equal(await q.locator('.pd-guidance-tool[data-capability=threads] select').inputValue(),'Done'); - await q.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.otherBook}`);await q.waitForFunction(()=>document.querySelector('[data-guidance-content]')?.textContent.includes('No active investigation'));assert.equal(await q.locator('#guidance-finding').count(),0);assert.equal(await q.locator('[data-investigation-companion]').getAttribute('data-collapsed'),'true');await q.locator('[data-guidance-expand]').click();const resume=await q.getByRole('link',{name:'Open saved investigations',exact:true}).getAttribute('href');assert.equal(new URL(resume).searchParams.get('bookId'),String(w.otherBook)); - // In-page book context changes use the same event as Calendar/At This Point and recheck server scope. - await q.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:book-context-changed',{detail:{bookId:0}})));await q.waitForFunction(()=>document.querySelector('[data-guidance-content]')?.textContent.includes('Choose a book'));await q.locator('[data-guidance-expand]').click();assert(!(new URL(await q.getByRole('link',{name:'Choose a book in Writer to resume an investigation'}).getAttribute('href'))).searchParams.has('bookId')); - await q.evaluate(book=>{const url=new URL(location.href);url.searchParams.set('bookId',String(book));history.replaceState(history.state,'',url);document.dispatchEvent(new CustomEvent('plotdirector:book-context-changed',{detail:{bookId:book}}));},w.book);await q.locator('#guidance-finding').waitFor(); - // Server-side failure paths retain the active guidance; forged IDs never expose it. - const token=await q.locator('[data-guidance-token] [name=__RequestVerificationToken]').inputValue();const response=await q.request.post(base+'/InvestigationCompanion/Open',{form:{__RequestVerificationToken:token,bookId:w.book,id:w.investigation,finding:'disconnected',capability:'invented'}});assert.equal(response.status(),400); - const wrong=await q.request.get(base+`/InvestigationCompanion/Evidence?bookId=${w.otherBook}&id=${w.investigation}&finding=disconnected`);assert.equal(wrong.status(),404); - const invalid=await q.request.get(base+`/InvestigationCompanion/Evidence?bookId=${w.book}&id=00000000-0000-0000-0000-000000000000&finding=disconnected`);assert.equal(invalid.status(),404); - - // Old/invalid presentation preferences recover without changing server progress. - await q.evaluate(u=>localStorage.setItem(`plotdirector.investigationPanel.v1.${u.user}.${u.book}`,JSON.stringify({width:-99,positions:'stale'})),{user:w.UserID,book:w.book});await q.reload();await q.locator('#guidance-finding').waitFor();assert.equal(await q.locator('.pd-guidance-tool[data-capability=threads] select').inputValue(),'Done'); - await q.route('**/InvestigationCompanion/Summary?*',r=>r.fulfill({status:503,body:'unavailable'}));await q.reload();await q.locator('[data-guidance-expand]').click();await q.getByRole('button',{name:'Retry',exact:true}).waitFor();await q.unroute('**/InvestigationCompanion/Summary?*');await q.getByRole('button',{name:'Retry',exact:true}).click();await q.locator('#guidance-finding').waitFor(); - // Pin has the same restore-on-navigation meaning as contextual Help. - await q.locator('[data-guidance-pin]').click();await q.reload();await q.waitForFunction(()=>document.querySelector('[data-guidance-content]')?.textContent.includes('Full investigation results'));assert.equal(await q.locator('[data-investigation-companion]').getAttribute('data-collapsed'),'true');await q.locator('[data-guidance-expand]').click();await q.locator('[data-guidance-pin]').click();await q.reload();await q.locator('#guidance-finding').waitFor();assert.equal(await q.locator('[data-investigation-companion]').getAttribute('data-collapsed'),'false'); - const full=await q.getByRole('link',{name:'Full investigation results',exact:true}).getAttribute('href');await q.getByRole('button',{name:'Dismiss guidance',exact:true}).click();await q.waitForFunction(()=>document.querySelector('[data-guidance-content]')?.textContent.includes('No active investigation'));await q.goto(base+full);await q.getByRole('button',{name:'Keep this investigation alongside my work'}).click();await q.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`);await q.waitForFunction(()=>document.querySelector('#guidance-finding'));assert.equal(await q.locator('[data-investigation-companion]').getAttribute('data-collapsed'),'true');await q.locator('[data-guidance-expand]').click();await q.locator('#guidance-finding').waitFor(); - assert.deepEqual(errors,[]);await reopened.close(); - if(live&&process.env.PD_GUIDANCE_OTHER_IDENTITY){ - const other=JSON.parse(fs.readFileSync(process.env.PD_GUIDANCE_OTHER_IDENTITY)),oc=await b.newContext(),op=await oc.newPage();await op.goto(base+'/Account/Login');await op.locator('[name=Email]').fill(other.Email);await op.locator('[name=Password]').fill(other.Password);await Promise.all([op.waitForURL('**/Projects'),op.locator('button[type=submit]').click()]); - const view=await op.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`);assert.equal(view.status(),200);await op.locator('[data-guidance-token]').waitFor({state:'attached'});const ot=await op.locator('[data-guidance-token] [name=__RequestVerificationToken]').inputValue(); - const summary=await op.request.get(`${base}/InvestigationCompanion/Summary?projectId=${w.project}&bookId=${w.book}`);assert.equal(summary.status(),200);assert.equal((await summary.json()).active,false); - assert.equal((await op.request.get(`${base}/InvestigationCompanion/Evidence?bookId=${w.book}&id=${w.investigation}&finding=disconnected`)).status(),404); - assert.equal((await op.request.post(base+'/InvestigationCompanion/Update',{form:{__RequestVerificationToken:ot,bookId:w.book,id:w.investigation,version:0,operation:'activate'}})).status(),404);await oc.close(); - } - console.log('PASS '+(live?'authenticated Development':'isolated Razor/HTTP')+' investigation companion: saved results, same-window destinations, two findings, private server progress, Help coexistence, collapse/expand, refresh and reopened PWA session, Back ribbon action, book isolation, invalid IDs and unavailable destination'); - }finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1}); +// Compatibility entry point: Phase 1.5 placeholder-tab/unpinned-collapse expectations were superseded. +// Without Development credentials this runs lifecycle isolation only, not server persistence qualification. +if(process.env.PD_GUIDANCE_IDENTITY){process.env.PD_UX_IDENTITY=process.env.PD_GUIDANCE_IDENTITY;process.env.PD_UX_SCREENSHOTS=process.env.PD_GUIDANCE_SCREENSHOTS;require('./investigation-ux-correction.cjs');} +else{require('./context-panel-lifecycle.cjs');} diff --git a/PlotLine.Tests/Browser/investigation-ux-correction.cjs b/PlotLine.Tests/Browser/investigation-ux-correction.cjs new file mode 100644 index 00000000..527a3277 --- /dev/null +++ b/PlotLine.Tests/Browser/investigation-ux-correction.cjs @@ -0,0 +1,20 @@ +const{chromium}=require('playwright'),fs=require('fs'),assert=require('node:assert/strict'); +(async()=>{const w=JSON.parse(fs.readFileSync(process.env.PD_UX_IDENTITY)),base='https://dev.plotdirector.com',out=process.env.PD_UX_SCREENSHOTS,b=await chromium.launch(),timings=[];try{const c=await b.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(u=>{Object.defineProperty(navigator,'standalone',{value:true});localStorage.setItem('plotdirector.desktop.v1.'+u,JSON.stringify({dismissedAt:Date.now()}));},w.UserID);const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.exposeFunction('navigationAck',ms=>timings.push({ackMs:ms}));await p.addInitScript(()=>{document.addEventListener('submit',e=>{if(!e.target.matches('[data-guidance-navigation]'))return;const start=performance.now(),observer=new MutationObserver(()=>{if(e.target.textContent.includes('Opening…')){window.navigationAck(performance.now()-start);observer.disconnect();}});observer.observe(e.target,{subtree:true,childList:true,characterData:true});},true);});const shot=async name=>{if(out){fs.mkdirSync(out,{recursive:true});await p.mouse.move(2,995);await p.screenshot({path:out+'/'+name+'.png'});}}; +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()]);const explore=`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.book}`;await p.goto(explore);await p.locator('[data-my-investigations] article').first().waitFor();await shot('My-investigations');const root=p.locator('[data-investigation-companion]'),help=p.locator('[data-help-drawer]'); +// Starting from saved results does not activate guidance. Continue is explicit. +assert(await root.isHidden());assert(await root.locator('[data-guidance-expand]').isHidden()); +const older=p.locator('[data-my-investigations] article').filter({has:p.locator(`input[name=id][value="${w.oldInvestigation}"]`)});await older.getByRole('button',{name:'Continue',exact:true}).click();await p.waitForFunction(()=>document.querySelector('[data-guidance-content]')?.textContent.includes('older investigation'));assert.equal(await root.locator('.pd-guidance-tool').count(),0);await shot('Older-investigation');await p.goto(explore);await p.locator('[data-my-investigations] article').first().waitFor();const card=p.locator('[data-my-investigations] article').filter({has:p.locator(`input[name=id][value="${w.investigation}"]`)});await card.getByRole('button',{name:'Continue',exact:true}).click();await p.locator('[data-conclusion]').waitFor();await root.waitFor();const count=c.pages().length; +for(let n=0;n<3;n++){if(n)await p.goto(`${base}/Writer/Explore/Investigate?bookId=${w.book}&id=${w.investigation}`);const network=[];const capture=r=>{if(r.request().isNavigationRequest()||r.url().includes('/InvestigationCompanion/Summary'))network.push({url:new URL(r.url()).pathname,status:r.status(),timing:r.request().timing(),serverTiming:r.headers()['server-timing']});};p.on('response',capture);const start=Date.now();await p.locator('form[data-guidance-navigation]').first().getByRole('button').click();await p.waitForURL(/PlotLineWorkspace/);const documentMs=Date.now()-start;await root.locator('#guidance-finding').waitFor();timings.push({documentMs,restoredMs:Date.now()-start,network});p.removeListener('response',capture);} +assert.equal(c.pages().length,count);const panelContent=root.locator('.plotline-help-drawer-panel');assert.equal(await root.getAttribute('data-state'),'open');await p.evaluate(()=>PlotLineHelpDrawer.open('plotLines.workspace'));await help.locator('.help-drawer-article').waitFor();await shot('Both-open'); +for(const left of['open','collapsed','closed'])for(const right of['open','collapsed','closed']){ + if(await root.getAttribute('data-state')!=='open')await p.locator('[data-guidance-open]').click();if(left==='collapsed')await root.locator('[data-guidance-collapse]').click();if(left==='closed')await root.locator('[data-guidance-close]').click(); + await p.evaluate(()=>PlotLineHelpDrawer.open('plotLines.workspace'));await help.locator('.help-drawer-article').waitFor();if(right==='collapsed')await help.locator('[data-help-collapse]').click();if(right==='closed')await help.locator('[data-help-close]').click(); + assert.equal(await root.isVisible(),left!=='closed');assert.equal(await panelContent.isVisible(),left==='open');assert.equal(await help.isVisible(),right!=='closed');assert.equal(await help.locator('.plotline-help-drawer-panel').isVisible(),right==='open');} +await p.locator('[data-guidance-open]').click();await p.evaluate(()=>PlotLineHelpDrawer.open('plotLines.workspace'));await help.locator('.help-drawer-article').waitFor();await root.locator('[data-guidance-close]').click();await shot('Help-only');assert(await help.isVisible());await p.locator('[data-guidance-open]').click();await help.locator('[data-help-close]').click();await shot('Investigation-only'); +// A close is presentation only, and a saved selector changes only authorised guidance. +const before=await (await p.request.get(base+`/InvestigationCompanion/Summary?projectId=${w.project}&bookId=${w.book}`)).json();await root.locator('[data-guidance-close]').click();const after=await (await p.request.get(base+`/InvestigationCompanion/Summary?projectId=${w.project}&bookId=${w.book}`)).json();assert.equal(after.summary.version,before.summary.version);await p.reload();assert(await root.isHidden());await p.locator('[data-guidance-open]').click(); +const picker=root.getByLabel('Switch saved investigation');await picker.focus();await picker.locator(`option[value="${w.secondInvestigation}"]`).waitFor({state:'attached'});await picker.selectOption(w.secondInvestigation);await p.waitForFunction(()=>document.querySelector('[data-guidance-content] a')?.href.includes(window.location.origin)&&document.querySelector('[data-guidance-content] a')?.href.includes('id='));await p.waitForFunction(id=>document.querySelector('[data-guidance-content] a')?.href.includes(id),w.secondInvestigation);assert((await root.getByRole('link',{name:'Full investigation results'}).getAttribute('href')).includes(w.secondInvestigation)); +await root.locator('[data-guidance-pin]').click(); // pin (Close unpinned it) +await root.locator('.pd-guidance-tool[data-capability=timeline] form button').click();await p.waitForURL(/Timeline/);await root.locator('#guidance-finding').waitFor();await shot('Timeline');await p.reload();await root.locator('#guidance-finding').waitFor();assert.equal(await root.getAttribute('data-state'),'open'); +await root.locator('[data-guidance-pin]').click();await root.locator('.pd-guidance-tool select').first().selectOption('Done');await p.waitForFunction(()=>document.querySelector('[data-guidance-message]')?.textContent==='');assert.equal(await root.getAttribute('data-state'),'open');await p.reload();assert(await root.isHidden());await p.locator('[data-guidance-open]').click();await p.setViewportSize({width:800,height:1000});await p.evaluate(()=>PlotLineHelpDrawer.open('timeline.overview'));await help.locator('.help-drawer-article').waitFor();assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2));await shot('Narrow-both');await root.locator('[data-guidance-close]').click();assert(await help.isVisible()); +await p.setViewportSize({width:1440,height:1000});await p.goto(explore);await p.locator('[data-my-investigations] article').first().waitFor();assert(await root.isHidden());await p.locator('[data-guidance-open]').click();await root.getByRole('button',{name:'Finish this journey'}).click();await p.waitForFunction(()=>document.querySelector('[data-investigation-companion]')?.dataset.state==='closed');assert.equal((await (await p.request.get(base+`/InvestigationCompanion/Summary?bookId=${w.book}`)).json()).active,false);await p.goto(explore);await p.locator('[data-my-investigations] article').first().waitFor();const original=p.locator('[data-my-investigations] article').filter({has:p.locator(`input[name=id][value="${w.investigation}"]`)});await original.getByRole('link',{name:'Original results'}).click();assert.equal((await (await p.request.get(base+`/InvestigationCompanion/Summary?bookId=${w.book}`)).json()).active,false);await p.goto(explore);await p.locator('[data-my-investigations] article').filter({has:p.locator(`input[name=id][value="${w.investigation}"]`)}).getByRole('button',{name:'Continue',exact:true}).click();await root.locator('#guidance-finding').waitFor();if(await root.locator('[data-guidance-pin]').textContent()==='Pin')await root.locator('[data-guidance-pin]').click();await p.goto(`${base}/Writer/Review?projectId=${w.project}&bookId=${w.book}`);await root.locator('#guidance-finding').waitFor();await p.evaluate(()=>PlotLineHelpDrawer.open('writer3.reviewing'));const prior=[await root.getAttribute('data-state'),await help.getAttribute('data-state')];await p.locator('#reader-focus').click();assert(await root.evaluate(n=>n.inert));assert(await help.evaluate(n=>n.inert));await p.locator('#reader-focus').click();assert.deepEqual([await root.getAttribute('data-state'),await help.getAttribute('data-state')],prior);await shot('Writer-review');assert.deepEqual(errors,[]);fs.writeFileSync(process.env.PD_UX_TIMINGS||'/tmp/ux-timings.json',JSON.stringify(timings,null,2));console.log('PASS authenticated UX correction: saved discovery, nine independent lifecycle pairs, close preserves guidance, explicit reopen, switching, pin/unpin navigation/refresh, no duplicate windows, progress, narrow layout');await c.close();}finally{await b.close()}})().catch(e=>{console.error(e.stack);process.exitCode=1}); diff --git a/PlotLine.Tests/Sql/InvestigationSavedSummariesRegression.sql b/PlotLine.Tests/Sql/InvestigationSavedSummariesRegression.sql new file mode 100644 index 00000000..f04d0270 --- /dev/null +++ b/PlotLine.Tests/Sql/InvestigationSavedSummariesRegression.sql @@ -0,0 +1,13 @@ +IF DB_NAME()<>N'PlotDirector_Development' THROW 51000,'Wrong database',1; +DECLARE @u int=(SELECT UserID FROM dbo.AppUser WHERE Email=N'pwa-browser-writeraudit-20261116@example.invalid' AND DisplayName=N'Disposable Writer Audit 20261116'); +DECLARE @b int=(SELECT TOP(1) BookID FROM dbo.WriterInvestigations WHERE UserID=@u ORDER BY UpdatedUtc DESC); +IF @b IS NULL THROW 51000,'Disposable saved investigations required',1; +DECLARE @r TABLE(ID uniqueidentifier,BookID int,CatalogueVersion varchar(80),Concern nvarchar(100),Status varchar(100),UpdatedUtc datetime2,GuidanceVersion int,IsActive bit,Finished bit); +INSERT @r EXEC dbo.WriterInvestigationSavedSummaries @UserID=@u,@BookID=@b; +IF (SELECT COUNT(*) FROM @r)<2 THROW 51000,'Missing saved investigations',1; +IF EXISTS(SELECT 1 FROM @r WHERE BookID<>@b OR GuidanceVersion<0) THROW 51000,'Bad summary metadata',1; +DELETE @r;INSERT @r EXEC dbo.WriterInvestigationSavedSummaries @UserID=-123456,@BookID=@b; +IF EXISTS(SELECT 1 FROM @r) THROW 51000,'Cross-user list leak',1; +INSERT @r EXEC dbo.WriterInvestigationSavedSummaries @UserID=@u,@BookID=-1; +IF EXISTS(SELECT 1 FROM @r) THROW 51000,'Cross-book list leak',1; +SELECT 'PASS private compact saved list, metadata and author/book isolation' Result; diff --git a/PlotLine/Controllers/InvestigationCompanionController.cs b/PlotLine/Controllers/InvestigationCompanionController.cs index 37420067..d62a38db 100644 --- a/PlotLine/Controllers/InvestigationCompanionController.cs +++ b/PlotLine/Controllers/InvestigationCompanionController.cs @@ -8,7 +8,7 @@ namespace PlotLine.Controllers; public sealed class InvestigationCompanionController(InvestigationAccess gate,IInvestigationGuidanceRepository repository,InvestigationGuidanceService service,IInvestigationRepository investigations):Controller { IActionResult Error(int status,string message){ - if(ControllerContext.ActionDescriptor.ActionName==nameof(Open)){ + if((ControllerContext.ActionDescriptor.ActionName==nameof(Open)||ControllerContext.ActionDescriptor.ActionName==nameof(Update)&&Request.Headers["X-Requested-With"]!="XMLHttpRequest")){ Response.StatusCode=status;ViewData["Failure"]=message; if(int.TryParse(Request.Form["bookId"],out var book))ViewData["BookID"]=book; if(Guid.TryParse(Request.Form["id"],out var id))ViewData["InvestigationID"]=id; @@ -27,6 +27,13 @@ public sealed class InvestigationCompanionController(InvestigationAccess gate,II var(verified,c)=await Verify(r); // same ownership guard as explicit IDs return Json(new{active=true,summary=service.Summary(verified,c),resultsUrl=Url.Action("Index","WriterInvestigations",new{bookId=r.BookID,id=r.ID})}); }); + [HttpGet("/InvestigationCompanion/Saved")] + public Task Saved(int bookId)=>Guard(async()=>{ + var rows=await repository.List(Author,bookId);var result=new List(); + foreach(var row in rows){var c=await service.Catalogue(row.CatalogueVersion);if(c.Synthetic&&!(await HttpContext.RequestServices.GetRequiredService().AuthorizeAsync(User,null,"AdminOnly")).Succeeded)continue; + result.Add(new{row.ID,row.BookID,row.GuidanceVersion,updatedUtc=DateTime.SpecifyKind(row.UpdatedUtc,DateTimeKind.Utc),status=row.Finished?"Journey finished":row.IsActive?"Active guidance · "+row.Status:row.Status,concern=c.Concerns.SingleOrDefault(x=>x.Id==row.Concern)?.Text??"Saved investigation",resultsUrl=Url.Action("Index","WriterInvestigations",new{bookId,id=row.ID}),continueUrl=Url.Action("Update",new{bookId,id=row.ID})});} + return Json(result); + }); [HttpGet("/InvestigationCompanion/Evidence")] public Task Evidence(int bookId,Guid id,string finding)=>Guard(async()=>{ var(r,c)=await Load(null,bookId,id);var(i,_,s)=InvestigationGuidanceService.Decode(r);service.Select(r,c,s,finding,null); @@ -41,9 +48,9 @@ public sealed class InvestigationCompanionController(InvestigationAccess gate,II if(operation=="progress"){if(capability==null||!InvestigationGuidanceService.ProgressStates.Contains(progress))throw new ArgumentException("Choose a progress state.");s.Progress[InvestigationGuidanceService.Key(finding!,capability)]=progress!;} }else if(operation is not("activate" or "dismiss" or "finish"))throw new ArgumentException("Unknown guidance action."); await service.Save(Author,r,s,operation is "select" or "progress"?"save":operation); - if(operation=="activate")return RedirectToAction("Index","WriterInvestigations",new{bookId,id}); + if(operation=="activate"&&Request.Headers["X-Requested-With"]!="XMLHttpRequest")return RedirectToAction("Index","WriterInvestigations",new{bookId,id}); return Json(new{ok=true}); }); [HttpPost("/InvestigationCompanion/Open"),ValidateAntiForgeryToken] - public Task Open(int bookId,Guid id,string finding,string capability)=>Guard(async()=>{var(r,c)=await Load(null,bookId,id);var target=await service.Open(Author,r,c,finding,capability);return RedirectToAction(target.Action,target.Controller,target.Values);}); + public Task Open(int bookId,Guid id,string finding,string capability)=>Guard(async()=>{var timer=System.Diagnostics.Stopwatch.StartNew();var(r,c)=await Load(null,bookId,id);Response.Headers.Append("Server-Timing",FormattableString.Invariant($"guidance-load;dur={timer.Elapsed.TotalMilliseconds:F2}"));var target=await service.Open(Author,r,c,finding,capability,(name,ms)=>Response.Headers.Append("Server-Timing",FormattableString.Invariant($"{name};dur={ms:F2}")));return RedirectToAction(target.Action,target.Controller,target.Values);}); } diff --git a/PlotLine/Controllers/WriterInvestigationsController.cs b/PlotLine/Controllers/WriterInvestigationsController.cs index 494768a0..5792cc72 100644 --- a/PlotLine/Controllers/WriterInvestigationsController.cs +++ b/PlotLine/Controllers/WriterInvestigationsController.cs @@ -43,10 +43,13 @@ public sealed class WriterInvestigationsController(InvestigationAccess gate,IInv }); [HttpPost("/Writer/Explore/Investigate/Open"),ValidateAntiForgeryToken] public Task Open(int bookId,Guid id,int version,string capability)=>Guard(async()=>{ - var(i,c)=await service.Read(Author,bookId,id);await EnsureCatalogue(c);if(version!=i.Version)throw new ArgumentException("Resume the latest version before opening a tool."); - var r=await guidance.Read(Author,i.ProjectID,bookId,id)??throw new KeyNotFoundException(); + var timer=System.Diagnostics.Stopwatch.StartNew(); + var r=await guidance.Read(Author,null,bookId,id)??throw new KeyNotFoundException();Response.Headers.Append("Server-Timing",FormattableString.Invariant($"guidance-read;dur={timer.Elapsed.TotalMilliseconds:F2}"));timer.Restart(); + var i=InvestigationGuidanceService.Decode(r).Investigation;var c=await companion.Catalogue(i.CatalogueVersion);await EnsureCatalogue(c); + Response.Headers.Append("Server-Timing",FormattableString.Invariant($"catalogue-authorization;dur={timer.Elapsed.TotalMilliseconds:F2}")); + if(i.UserID!=Author||i.BookID!=bookId||i.ProjectID!=r.ProjectID)throw new UnauthorizedAccessException();if(version!=i.Version)throw new ArgumentException("Resume the latest version before opening a tool."); var saved=InvestigationGuidanceService.Decode(r);var finding=InvestigationGuidanceService.Recommended(saved.Investigation,saved.Evaluation).FirstOrDefault(h=>c.Hypotheses.Single(x=>x.Id==h).Capabilities.Contains(capability))??throw new ArgumentException("This destination is not currently recommended."); - var target=await companion.Open(Author,r,c,Request.Form["finding"].FirstOrDefault()??finding,capability); + var target=await companion.Open(Author,r,c,Request.Form["finding"].FirstOrDefault()??finding,capability,(name,ms)=>Response.Headers.Append("Server-Timing",FormattableString.Invariant($"{name};dur={ms:F2}"))); return RedirectToAction(target.Action,target.Controller,target.Values); }); [Authorize(Policy="AdminOnly"),HttpGet("/admin/writer-investigations")] diff --git a/PlotLine/Data/InvestigationGuidanceRepository.cs b/PlotLine/Data/InvestigationGuidanceRepository.cs index abe23078..a1cc3da7 100644 --- a/PlotLine/Data/InvestigationGuidanceRepository.cs +++ b/PlotLine/Data/InvestigationGuidanceRepository.cs @@ -7,13 +7,16 @@ public sealed class GuidanceRecord public string InvestigationJson {get;set;}="";public string? EvaluationJson {get;set;}public string? GuidanceJson {get;set;} public int GuidanceVersion {get;set;}public bool IsActive {get;set;}public bool Finished {get;set;} } +public sealed record SavedInvestigation(Guid ID,int BookID,string CatalogueVersion,string Concern,string Status,DateTime UpdatedUtc,int GuidanceVersion,bool IsActive,bool Finished); public interface IInvestigationGuidanceRepository { Task Read(int user,int? project,int? book,Guid? id=null); + Task> List(int user,int book)=>Task.FromResult>([]); Task Save(int user,int book,Guid id,int version,string operation,string json); } public sealed class InvestigationGuidanceRepository(ISqlConnectionFactory factory):IInvestigationGuidanceRepository { public async Task Read(int user,int? project,int? book,Guid? id=null){using var db=factory.CreateConnection();return await db.QuerySingleOrDefaultAsync("dbo.WriterInvestigationGuidanceState",new{Action="read",UserID=user,ProjectID=project,BookID=book,ID=id},commandType:CommandType.StoredProcedure);} + public async Task> List(int user,int book){using var db=factory.CreateConnection();return (await db.QueryAsync("dbo.WriterInvestigationSavedSummaries",new{UserID=user,BookID=book},commandType:CommandType.StoredProcedure)).ToArray();} public async Task Save(int user,int book,Guid id,int version,string operation,string json){using var db=factory.CreateConnection();await db.ExecuteAsync("dbo.WriterInvestigationGuidanceState",new{Action=operation,UserID=user,BookID=book,ID=id,ExpectedVersion=version,Json=json},commandType:CommandType.StoredProcedure);} } diff --git a/PlotLine/Services/Investigations/InvestigationGuidanceService.cs b/PlotLine/Services/Investigations/InvestigationGuidanceService.cs index 4b9ad4e8..0b9823c7 100644 --- a/PlotLine/Services/Investigations/InvestigationGuidanceService.cs +++ b/PlotLine/Services/Investigations/InvestigationGuidanceService.cs @@ -38,12 +38,14 @@ public sealed class InvestigationGuidanceService(IInvestigationGuidanceRepositor state.Finding=finding;state.Capability=capability; } public Task Save(int user,GuidanceRecord r,GuidanceState state,string operation)=>guidance.Save(user,r.BookID,r.ID,r.GuidanceVersion,operation,JsonSerializer.Serialize(state,CatalogueValidator.Json)); - public async Task<(string Controller,string Action,object Values)> Open(int user,GuidanceRecord r,Catalogue c,string finding,string capability) + public async Task<(string Controller,string Action,object Values)> Open(int user,GuidanceRecord r,Catalogue c,string finding,string capability,Action? timed=null) { + var timer=System.Diagnostics.Stopwatch.StartNew(); var(i,_,s)=Decode(r);Select(r,c,s,finding,capability);var d=c.Capabilities.SingleOrDefault(d=>d.Id==capability)??throw new ArgumentException("Tool unavailable."); if(!Available(d,i))throw new ArgumentException("This tool is currently unavailable. Your investigation is retained."); // Opening never completes a step, nor resets an explicit Done/Skipped decision. var key=Key(finding,capability);if(s.Progress.GetValueOrDefault(key,"Not started")=="Not started")s.Progress[key]="Exploring"; - await Save(user,r,s,"activate");return DestinationRegistry.Resolve(d,i.ProjectID,i.BookID,true,i.Answers.ToDictionary(a=>a.Question))!.Value; + timed?.Invoke("eligibility-registry",timer.Elapsed.TotalMilliseconds);timer.Restart(); + await Save(user,r,s,"activate");timed?.Invoke("guidance-save",timer.Elapsed.TotalMilliseconds);return DestinationRegistry.Resolve(d,i.ProjectID,i.BookID,true,i.Answers.ToDictionary(a=>a.Question))!.Value; } } diff --git a/PlotLine/Sql/278_InvestigationSavedSummaries.sql b/PlotLine/Sql/278_InvestigationSavedSummaries.sql new file mode 100644 index 00000000..02b08712 --- /dev/null +++ b/PlotLine/Sql/278_InvestigationSavedSummaries.sql @@ -0,0 +1,18 @@ +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.WriterInvestigationSavedSummaries @UserID int,@BookID int AS +BEGIN + SET NOCOUNT ON; + SELECT TOP(50) i.ID,i.BookID,i.CatalogueVersion,JSON_VALUE(i.Json,'$.Concern') Concern, + CASE WHEN JSON_VALUE(i.Json,'$.CurrentQuestion') IS NOT NULL THEN 'In progress' WHEN e.Event IS NULL THEN 'Older saved investigation' ELSE 'Results available' END Status, + i.UpdatedUtc,ISNULL(g.Version,0) GuidanceVersion,ISNULL(g.IsActive,0) IsActive,ISNULL(g.Finished,0) Finished + FROM dbo.WriterInvestigations i + JOIN dbo.Books b ON b.BookID=i.BookID AND b.ProjectID=i.ProjectID AND b.IsArchived=0 + JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0 + JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1 + LEFT JOIN dbo.WriterInvestigationGuidance g ON g.InvestigationID=i.ID AND g.UserID=@UserID + LEFT JOIN dbo.WriterInvestigationEvents e ON e.InvestigationID=i.ID AND e.Version=i.Version + WHERE i.UserID=@UserID AND i.BookID=@BookID ORDER BY i.UpdatedUtc DESC,i.ID; +END; +GO diff --git a/PlotLine/Sql/279_InvestigationSavedActivity.sql b/PlotLine/Sql/279_InvestigationSavedActivity.sql new file mode 100644 index 00000000..9cfd2fcd --- /dev/null +++ b/PlotLine/Sql/279_InvestigationSavedActivity.sql @@ -0,0 +1,19 @@ +-- Include explicit follow-through in the saved investigation activity timestamp. +SET ANSI_NULLS ON; +SET QUOTED_IDENTIFIER ON; +GO +CREATE OR ALTER PROCEDURE dbo.WriterInvestigationSavedSummaries @UserID int,@BookID int AS +BEGIN + SET NOCOUNT ON; + SELECT TOP(50) i.ID,i.BookID,i.CatalogueVersion,JSON_VALUE(i.Json,'$.Concern') Concern, + CASE WHEN JSON_VALUE(i.Json,'$.CurrentQuestion') IS NOT NULL THEN 'In progress' WHEN e.Event IS NULL THEN 'Older saved investigation' ELSE 'Results available' END Status, + CASE WHEN g.UpdatedUtc>i.UpdatedUtc THEN g.UpdatedUtc ELSE i.UpdatedUtc END UpdatedUtc,ISNULL(g.Version,0) GuidanceVersion,ISNULL(g.IsActive,0) IsActive,ISNULL(g.Finished,0) Finished + FROM dbo.WriterInvestigations i + JOIN dbo.Books b ON b.BookID=i.BookID AND b.ProjectID=i.ProjectID AND b.IsArchived=0 + JOIN dbo.Projects p ON p.ProjectID=b.ProjectID AND p.IsArchived=0 + JOIN dbo.ProjectUserAccess a ON a.ProjectID=p.ProjectID AND a.UserID=@UserID AND a.IsActive=1 + LEFT JOIN dbo.WriterInvestigationGuidance g ON g.InvestigationID=i.ID AND g.UserID=@UserID + LEFT JOIN dbo.WriterInvestigationEvents e ON e.InvestigationID=i.ID AND e.Version=i.Version + WHERE i.UserID=@UserID AND i.BookID=@BookID ORDER BY UpdatedUtc DESC,i.ID; +END; +GO diff --git a/PlotLine/Views/Shared/_ApplicationShell.cshtml b/PlotLine/Views/Shared/_ApplicationShell.cshtml index f80beb77..10a73558 100644 --- a/PlotLine/Views/Shared/_ApplicationShell.cshtml +++ b/PlotLine/Views/Shared/_ApplicationShell.cshtml @@ -127,7 +127,7 @@