diff --git a/PlotLine.Tests/Browser/investigation-ux-correction.cjs b/PlotLine.Tests/Browser/investigation-ux-correction.cjs index cac0cafe..0d2c69c3 100644 --- a/PlotLine.Tests/Browser/investigation-ux-correction.cjs +++ b/PlotLine.Tests/Browser/investigation-ux-correction.cjs @@ -5,7 +5,9 @@ await p.goto(base+'/Account/Login');await p.locator('[name=Email]').fill(w.Email 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('.investigation 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);} +await p.goto(`${base}/Writer/Explore/Investigate?bookId=${w.book}&id=${w.investigation}`);let submissions=0;const record=r=>{if(r.method()==='POST'&&new URL(r.url()).pathname==='/Writer/Explore/Investigate/Open')submissions++;};p.on('request',record);await p.locator('.investigation form[data-guidance-navigation]').first().evaluate(f=>{f.requestSubmit(f.querySelector('button'));f.requestSubmit(f.querySelector('button'));});await p.waitForURL(/PlotLineWorkspace/);await root.locator('#guidance-finding').waitFor();p.removeListener('request',record);assert.equal(submissions,1); 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();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=>c.getBoundingClientRect().right<=r.right);}));await shot('Both-open'); +for(const lp of[false,true])for(const rp of[false,true]){await p.locator('[data-guidance-open]').click();await p.evaluate(()=>PlotLineHelpDrawer.open('plotLines.workspace'));for(const[control,value]of [[root.locator('[data-guidance-pin]'),lp],[help.locator('[data-help-pin]'),rp]])if((await control.getAttribute('aria-pressed')==='true')!==value)await control.click();await p.reload();await p.waitForFunction(()=>!document.querySelector('[data-guidance-open]').hidden);assert.equal(await root.getAttribute('data-state'),lp?'open':'closed');assert.equal(await help.getAttribute('data-state'),rp?'open':'closed');} 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(); @@ -15,6 +17,6 @@ await p.locator('[data-guidance-open]').click();await p.evaluate(()=>PlotLineHel 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-picker] a')?.href.includes(window.location.origin)&&document.querySelector('[data-guidance-picker] a')?.href.includes('id='));await p.waitForFunction(id=>document.querySelector('[data-guidance-picker] 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 p.evaluate(()=>PlotLineHelpDrawer.open('plotLines.workspace'));if(await help.locator('[data-help-pin]').getAttribute('aria-pressed')!=='true')await help.locator('[data-help-pin]').click();const companionNetwork=[];const trace=r=>{if(r.request().isNavigationRequest()||r.url().includes('/InvestigationCompanion/Summary'))companionNetwork.push({url:new URL(r.url()).pathname,status:r.status(),timing:r.request().timing(),serverTiming:r.headers()['server-timing']});};p.on('response',trace);const companionStart=Date.now();await root.locator('.pd-guidance-tool[data-capability=timeline] form button').click();await p.waitForURL(/Timeline/);timings.push({entryPoint:'companion',documentMs:Date.now()-companionStart,network:companionNetwork});p.removeListener('response',trace);await root.locator('#guidance-finding').waitFor();await help.locator('.help-drawer-article').waitFor();assert.equal(await help.getAttribute('data-state'),'open');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');await p.goto(`${base}/Writer/Explore?projectId=${w.project}&bookId=${w.otherBook}`);await p.waitForFunction(()=>document.querySelector('[data-saved-investigations]')?.textContent.includes('No saved investigations'));assert(await root.isHidden());assert(await p.locator('[data-guidance-open]').isHidden());await p.goto(explore);await root.locator('#guidance-finding').waitFor();assert.equal(await root.getAttribute('data-state'),'open');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/Controllers/InvestigationCompanionController.cs b/PlotLine/Controllers/InvestigationCompanionController.cs index d62a38db..d7c5ce1f 100644 --- a/PlotLine/Controllers/InvestigationCompanionController.cs +++ b/PlotLine/Controllers/InvestigationCompanionController.cs @@ -25,13 +25,13 @@ public sealed class InvestigationCompanionController(InvestigationAccess gate,II if(projectId is not >0&&bookId is not >0)return Json(new{active=false}); var r=await repository.Read(Author,projectId,bookId);if(r==null)return Json(new{active=false}); 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})}); + return Json(new{active=true,hasSnapshot=verified.EvaluationJson!=null,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})});} + 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,hasResults=row.Status=="Results available",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")] diff --git a/PlotLine/wwwroot/js/investigation-companion.js b/PlotLine/wwwroot/js/investigation-companion.js index a27b8b38..3da90d4b 100644 --- a/PlotLine/wwwroot/js/investigation-companion.js +++ b/PlotLine/wwwroot/js/investigation-companion.js @@ -3,7 +3,7 @@ const root=document.querySelector('[data-investigation-companion]');if(!root)return; const layout=root.closest('[data-help-layout]'),content=root.querySelector('[data-guidance-content]'),message=root.querySelector('[data-guidance-message]'),tab=root.querySelector('[data-guidance-expand]'),splitter=layout.querySelector('[data-guidance-resize]'); const token=root.querySelector('[name=__RequestVerificationToken]').value; - let current=null,resultsUrl=null,epoch=0,request,busy=false,preference={},hydrated=false; + let current=null,resultsUrl=null,epoch=0,request,busy=false,preference={},hydrated=false,hasSnapshot=true; const storageKey=()=>`plotdirector.investigationPanel.v1.${root.dataset.user}.${current?.bookID||root.dataset.book||root.dataset.project||'none'}`; const read=()=>{try{const value=JSON.parse(localStorage.getItem(storageKey()));if(!value||typeof value!=='object'||Array.isArray(value))return {};if(!value.positions||typeof value.positions!=='object'||Array.isArray(value.positions))value.positions={};return value;}catch{return {};}}; const pendingKey=`plotdirector.guidance.open.${root.dataset.user}`; @@ -25,7 +25,7 @@ content.replaceChildren();const pickerArea=root.querySelector('[data-guidance-picker]');pickerArea.replaceChildren();message.textContent='';root.querySelector('[data-guidance-title]').textContent=current?.bookTitle||'Your story concern'; if(!current){content.append(element('p','No active investigation for this context.'),startLink());return;} const picker=element('select',null,'form-select');picker.setAttribute('aria-label','Switch saved investigation');const initial=element('option','Switch investigation…');initial.value='';picker.append(initial);picker.addEventListener('focus',async()=>{if(picker.dataset.loaded)return;try{for(const item of await saved(current.bookID)){const option=element('option',item.concern+' · '+item.id.slice(0,8));option.value=item.id;option.dataset.version=item.guidanceVersion;picker.append(option);}picker.dataset.loaded='true';}catch{failure('Saved investigations could not be loaded. Use My Investigations in Explore.');}});picker.addEventListener('change',()=>{const option=picker.selectedOptions[0];if(option.value)activate(option.value,Number(option.dataset.version),current.bookID);});pickerArea.append(picker); - const summary=element('a','Full investigation results');summary.href=resultsUrl;pickerArea.append(summary);content.append(element('h3','Your concern'),element('p',current.concern),element('p',current.message)); + const summary=element('a',hasSnapshot?'Full investigation results':'Saved investigation');summary.href=resultsUrl;pickerArea.append(summary);content.append(element('h3','Your concern'),element('p',current.concern),element('p',current.message)); if(current.findings.length){ const label=element('label','Finding');label.htmlFor='guidance-finding';const select=element('select',null,'form-select');select.id='guidance-finding'; for(const f of current.findings){const o=element('option',f.title);o.value=f.id;select.append(o);}select.value=current.findings.some(f=>f.id===current.finding)?current.finding:current.findings[0].id; @@ -49,7 +49,7 @@ const priorId=current?.id;const stamp=++epoch;request?.abort();request=new AbortController(); try{const url=new URL(root.dataset.summaryUrl,location.origin);if(root.dataset.project)url.searchParams.set('projectId',root.dataset.project);if(root.dataset.book)url.searchParams.set('bookId',root.dataset.book); const response=await fetch(url,{cache:'no-store',signal:request.signal});if(response.redirected||response.status===401){throw Error('Sign in again to resume your saved investigation.');}if(!response.ok)throw Error('Saved guidance could not be loaded. Retry when your connection returns.');const data=await response.json();if(stamp!==epoch)return; - current=data.active?data.summary:null;resultsUrl=data.resultsUrl;preference=read();render();restorePanel(!hydrated||priorId!==current?.id);hydrated=true; + current=data.active?data.summary:null;hasSnapshot=data.hasSnapshot!==false;resultsUrl=data.resultsUrl;preference=read();render();restorePanel(!hydrated||priorId!==current?.id);hydrated=true; }catch(e){if(e.name==='AbortError'||stamp!==epoch)return;current=null;content.replaceChildren(element('p',e.message),btn('Retry',load),startLink());panel.hide();} } async function mutate(operation,extra={}){ @@ -61,7 +61,7 @@ document.addEventListener('plotdirector:book-context-changed',e=>{root.dataset.book=String(e.detail.bookId);current=null;content.replaceChildren(element('p','Loading guidance for the selected book…'));panel.hide();load();}); async function saved(book){const url=new URL(root.dataset.savedUrl,location.origin);url.searchParams.set('bookId',book);const r=await fetch(url,{cache:'no-store'});if(!r.ok)throw Error('Saved investigations unavailable');return r.json();} async function activate(id,version,book){if(busy)return;busy=true;const picker=root.querySelector('[data-guidance-picker] select');if(picker)picker.disabled=true;try{const r=await fetch(root.dataset.updateUrl,{method:'POST',headers:{'X-Requested-With':'XMLHttpRequest'},body:new URLSearchParams({__RequestVerificationToken:token,id,bookId:book,version,operation:'activate'})});if(!r.ok)throw Error('This investigation could not be activated. Refresh and try again.');try{sessionStorage.setItem(pendingKey,id);}catch{}await load();await discover();}catch(e){if(picker){picker.disabled=false;picker.value='';}failure(e.message);}finally{busy=false;}} - async function discover(){const area=document.querySelector('[data-my-investigations]');if(!area)return;const list=area.querySelector('[data-saved-investigations]');try{const rows=await saved(area.dataset.book);list.replaceChildren();if(!rows.length)list.append(element('p','No saved investigations for this book yet. Begin a concern above.'));for(const item of rows){const card=element('article');card.append(element('h3',item.concern),element('p',item.status+' · Last activity: '+new Date(item.updatedUtc).toLocaleString()+' · '+item.id.slice(0,8)));const form=element('form');form.method='post';form.action=item.continueUrl;form.dataset.guidanceActivate='';for(const[name,value]of Object.entries({__RequestVerificationToken:token,bookId:item.bookID,id:item.id,version:item.guidanceVersion,operation:'activate'})){const input=element('input');input.type='hidden';input.name=name;input.value=value;form.append(input);}form.append(element('button','Continue','btn btn-primary'));const results=element('a','Original results');results.href=item.resultsUrl;card.append(form,results);list.append(card);}}catch{list.replaceChildren(element('p','Your saved investigations could not be loaded.'),btn('Retry',discover));}} + async function discover(){const area=document.querySelector('[data-my-investigations]');if(!area)return;const list=area.querySelector('[data-saved-investigations]');try{const rows=await saved(area.dataset.book);list.replaceChildren();if(!rows.length)list.append(element('p','No saved investigations for this book yet. Begin a concern above.'));for(const item of rows){const card=element('article');card.append(element('h3',item.concern),element('p',item.status+' · Last activity: '+new Date(item.updatedUtc).toLocaleString()+' · '+item.id.slice(0,8)));const form=element('form');form.method='post';form.action=item.continueUrl;form.dataset.guidanceActivate='';for(const[name,value]of Object.entries({__RequestVerificationToken:token,bookId:item.bookID,id:item.id,version:item.guidanceVersion,operation:'activate'})){const input=element('input');input.type='hidden';input.name=name;input.value=value;form.append(input);}form.append(element('button','Continue','btn btn-primary'));const results=element('a',item.hasResults?'Original results':'View saved investigation');results.href=item.resultsUrl;card.append(form,results);list.append(card);}}catch{list.replaceChildren(element('p','Your saved investigations could not be loaded.'),btn('Retry',discover));}} document.addEventListener('submit',e=>{const form=e.target;if(!form.matches('[data-guidance-navigation],[data-guidance-activate]'))return;if(form.dataset.pending==='true'){e.preventDefault();return;}form.dataset.pending='true';form.setAttribute('aria-busy','true');const submit=e.submitter;if(submit?.name){const hidden=element('input');hidden.type='hidden';hidden.name=submit.name;hidden.value=submit.value;form.append(hidden);}const id=form.querySelector('[name=id]')?.value||new URL(form.action).searchParams.get('id');if(id)try{sessionStorage.setItem(pendingKey,id);}catch{}requestAnimationFrame(()=>{form.querySelectorAll('button').forEach(b=>{b.dataset.originalText=b.textContent;b.textContent='Opening…';b.disabled=true;});});}); window.addEventListener('pageshow',()=>document.querySelectorAll('[data-pending=true]').forEach(f=>{delete f.dataset.pending;f.removeAttribute('aria-busy');f.querySelectorAll('button').forEach(b=>{b.disabled=false;b.textContent=b.dataset.originalText||b.textContent;});}));discover(); window.addEventListener('pageshow',e=>{if(e.persisted)load();});load();