Recover navigation availability after capability and mapping changes

This commit is contained in:
Nick Beckley 2026-11-18 22:01:05 +00:00
parent 7793f04ced
commit 9493e737d6
3 changed files with 9 additions and 7 deletions

View File

@ -26,6 +26,7 @@ for(const view of ['list','board','schedule']){await planner.locator('[data-plan
await planner.locator('[data-planner-tab=list]').click();await planner.locator('[data-planner-view=list]').waitFor();const task=planner.locator('[data-activity-id]').filter({hasText:'Revise arrival '+label}).first();await task.locator('details').filter({has:p.locator('summary').filter({hasText:'Edit activity'})}).locator('summary').click();const edit=task.locator('[data-activity-save]');await edit.locator('[name=Notes]').fill('Clarify the turning point before leaving');await edit.locator('button[type=submit]').click();await task.filter({hasText:'Clarify the turning point before leaving'}).waitFor();
for(const status of ['Completed','Next','Deferred','In progress']){const f=task.locator('[data-activity-change]').filter({has:p.locator('[name=status]')});await f.locator('[name=status]').selectOption(status);await f.locator('button').click();await p.waitForFunction(({title,status})=>[...document.querySelectorAll('[data-activity-id]')].some(n=>n.querySelector('h4').textContent===title&&n.querySelector('[data-activity-change] [name=status]').value===status),{title:'Revise arrival '+label,status});}
await task.getByRole('button',{name:/Move down/}).click();await p.waitForTimeout(150);assert.equal((await exportSessions()).length,countBefore);assert.equal((await p.request.post(base+'/WriterActivities/Change',{form:{bookId:s.book,id:crypto.randomUUID(),operation:'status',status:'Completed'}})).status(),400);
for(const view of ['list','board','schedule']){await planner.locator('[data-planner-tab='+view+']').click();await planner.locator('[data-planner-view='+view+']').waitFor();await shot('Plan-'+view);}await planner.locator('[data-planner-tab=list]').click();await planner.locator('[data-planner-view=list]').waitFor();
await task.locator('[data-activity-start] button').click();await p.waitForURL('**/Writer/Write?*');assert((await p.locator('[data-focus-summary]').textContent()).includes('Revise arrival '+label));assert.equal((await exportSessions()).length,countBefore);
await p.goto(url('Review')+'&chapterId='+s.chapter);await p.locator('[data-review-panel]').waitFor();const form=p.locator('[data-review-form]');await p.locator('[data-review-scope-new=Chapter]').click();await form.locator('[name=Observation]').fill('Chapter continuity '+label);await form.locator('[name=Classification]').selectOption('Continuity');await form.locator('[data-review-save]').click();await p.locator('[data-chapter-annotations] [data-observation]').filter({hasText:'Chapter continuity '+label}).waitFor();
const para=p.locator('#reader-content [data-scene-id="'+s.scene+'"]').first();await para.click();await p.waitForFunction(scene=>document.querySelector('[data-review-panel]')?.dataset.selectedScene===String(scene),s.scene);for(const scope of ['Scene','Passage']){await p.locator('[data-review-new]').click();await form.locator('[name=Scope]').selectOption(scope);await form.locator('[name=Observation]').fill(scope+' editorial note '+label);await form.locator('[name=Classification]').selectOption('Pacing');await form.locator('[data-review-save]').click();await p.locator('[data-observation]').filter({hasText:scope+' editorial note '+label}).waitFor();}
@ -35,6 +36,7 @@ const companion=p.locator('[data-writer-companion-toggle]');if(await companion.g
const records=await(await p.request.get(base+'/InvestigationCompanion/Saved?bookId='+s.book)).json();const selected=records.find(r=>r.id===investigation)||records[0];assert.equal((await p.request.post(base+'/InvestigationCompanion/Update',{headers:{'X-Requested-With':'XMLHttpRequest'},form:{bookId:s.book,id:selected.id,version:selected.guidanceVersion,operation:'activate',__RequestVerificationToken:token}})).status(),200);
await p.goto(url('Review')+'&chapterId='+s.chapter);await p.locator('[data-review-panel]').waitFor();await p.waitForFunction(()=>window.PlotDirectorGuidanceSummary?.active);if(await p.locator('[data-guidance-open]').isVisible())await p.locator('[data-guidance-open]').click();await p.evaluate(()=>PlotLineHelpDrawer.open('writer3.review'));await p.locator('.help-drawer-article').waitFor();await shot('Review-investigation-and-help');if(await p.locator('#review-scene-notes').isHidden())await p.locator('[data-editorial-toggle=review-scene-notes]').click();await shot('Review-help-scene-notes');if(await p.locator('#review-scene-notes [data-editorial-close]').isVisible())await p.locator('#review-scene-notes [data-editorial-close]').click();await p.locator('#reader-focus').click();await shot('Focus-reading');await p.locator('a[rel=next]').first().click();await p.waitForURL(new RegExp('chapterId='+s.secondChapter));assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');await p.locator('a[rel=prev]').first().click();await p.waitForURL(new RegExp('chapterId='+s.chapter));assert.equal(await p.locator('.manuscript-reader').getAttribute('data-focus'),'true');
await p.goto(url('Reflect'));await p.locator('.writer-month-grid').waitFor();assert.equal(await p.locator('[data-tab=calendar]').getAttribute('aria-selected'),'true');await shot('Reflect-calendar');await p.locator('[data-tab=sessions]').click();assert(await p.locator('[data-session-history]').isVisible());await p.locator('[data-session-filter]').fill('Synthetic session history');assert(await p.locator('[data-session-history]').evaluate(n=>n.scrollHeight>n.clientHeight));await shot('Reflect-sessions');
await p.goto(url('Review')+'&chapterId='+s.secondChapter);await p.locator('.manuscript-reader').waitFor();await p.goto(url('Plan'));if(await p.locator('[data-ribbon-collapse]').getAttribute('aria-expanded')==='false')await p.locator('[data-ribbon-collapse]').click();await p.locator('#ribbon-panel-writer a[data-command-operation="writer.review"]').click();await p.waitForURL(new RegExp('chapterId='+s.secondChapter));assert.equal(await p.locator('.manuscript-reader').getAttribute('data-chapter-id'),String(s.secondChapter),'Review retains its own valid chapter while moving between workspaces');
await p.goto(base+'/Writer/Journey?bookId='+s.book+'&year=2026&month=10&day=2026-10-15');assert.equal(new URL(p.url()).pathname,'/Writer/Reflect');assert(new URL(p.url()).searchParams.get('month')==='10');
for(const width of [1440,900,800])for(const destination of ['Write','Explore','Plan','Review','Reflect']){await p.setViewportSize({width,height:1000});await p.goto(url(destination));await p.waitForTimeout(120);assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),destination+' overflow '+width);assert((await p.title()).includes(destination));assert(await p.locator('.writer3-header').count()===0,destination+' redundant intro');}
assert.equal(popups,0,'internal flows stay in the same window');assert.deepEqual(errors,[]);console.log('PASS Phase21 authenticated '+(pwa?'simulated PWA':'browser')+': focus/checklist/session independence; inline investigation/recomputation/results/saved scrolling; planner views/status/edit/order/start; editorial scopes and notes; Focus, legacy Reflect, history, same-window and responsive flows');await c.close();}}finally{await browser.close();}})().catch(error=>{console.error(String(error.stack).replaceAll(who.Password,'[redacted]'));process.exitCode=1});

View File

@ -31,7 +31,7 @@ internal static class WriterWordTests
var liveCheckpoints=NativeWorkflowTests.Proxy<IChapterSyncRepository>((n,a)=>n switch{
"List"=>Task.FromResult<IReadOnlyList<ChapterLiveValidation>>([new(){ChapterID=21,SessionID=session,WordRevision=2,StartPosition=200}]),
"Position"=>Task.FromResult<ParagraphPosition?>(new(){HasSnapshot=true,Revision=currentCheckpoint?5:4,ChapterID=21}),_=>throw new Exception(n)});
service=new WriterWordService(null!,access,repo,liveCheckpoints,store);Check(!await service.Navigate(7,12,21,null,instance,session,manuscript,2,Guid.NewGuid()),"list row alone cannot navigate with stale accepted checkpoint hashes");currentCheckpoint=true;Check(await service.Navigate(7,12,21,null,instance,session,manuscript,2,Guid.NewGuid()),"reopened chapter uses checked live position rather than old absolute heading offset");
service=new WriterWordService(null!,access,repo,liveCheckpoints,store);Check(!await service.Navigate(7,12,21,null,instance,session,manuscript,2,Guid.NewGuid()),"list row alone cannot navigate with stale accepted checkpoint hashes");currentCheckpoint=true;Check(await service.Navigate(7,12,21,null,instance,session,manuscript,2,Guid.NewGuid(),validateOnly:true)&&store.TakeNavigation(7,"grant",instance,session)==null,"availability resolves the same target without queueing or moving Word");Check(await service.Navigate(7,12,21,null,instance,session,manuscript,2,Guid.NewGuid()),"reopened chapter uses checked live position rather than old absolute heading offset");
var watch=System.Diagnostics.Stopwatch.StartNew();for(int i=0;i<10000;i++)Check(NavigationPolicy.Current(command,session,2,manuscript,command.ExpiresUtc.AddSeconds(-1),true),"navigation fence");watch.Stop();Console.WriteLine($"MEASURE 10000 navigation execution gates: {watch.Elapsed.TotalMilliseconds:F2}ms; pure managed checks, no Word/COM benchmark.");
}

View File

@ -2,7 +2,7 @@
(()=>{'use strict';let root=document.querySelector('[data-writer-word]');if(root?.dataset.bound)return;if(!root){const template=document.querySelector('[data-word-fallback]');if(!template)return;const holder=document.createElement('details');holder.className='writer3-inset';holder.dataset.wordFallbackProvider='true';holder.hidden=!Number(template.content.querySelector('[data-writer-word]')?.dataset.chapterId);const summary=document.createElement('summary');summary.textContent='Word connection and manuscript';holder.append(summary,template.content.cloneNode(true));document.querySelector('main')?.append(holder);root=holder.querySelector('[data-writer-word]');}if(!root)return;root.dataset.bound='true';
const book=Number(root.dataset.bookId);let chapter=Number(root.dataset.chapterId),scene=Number(root.dataset.sceneId);const state=root.querySelector('[data-word-state]'),position=root.querySelector('[data-word-position]'),freshness=root.querySelector('[data-word-freshness]'),message=root.querySelector('[data-word-command]'),choose=root.querySelector('[data-word-choose]'),select=root.querySelector('[data-word-document]'),nav=root.querySelector('[data-word-navigate]'),sceneNav=root.querySelector('[data-word-scene]'),adopt=root.querySelector('[data-word-adopt]');
const reviewing=root.dataset.wordContext==='review',paragraphButton=root.querySelector('[data-word-paragraph]');
let availabilityKey='',availability={},availabilityEpoch=0;let packet=null,current=null,busy=false,abort=null,checkBusy=false,syncPending=null;const sync=root.querySelector('[data-word-sync]');
let availabilityKey='',availability={},availabilityEpoch=0,availabilityChecked=0;let packet=null,current=null,busy=false,abort=null,checkBusy=false,syncPending=null;const sync=root.querySelector('[data-word-sync]');
const key=l=>l.instanceId+'/'+l.sessionId;new MutationObserver(()=>{for(const status of document.querySelectorAll('[data-word-ribbon-status]'))status.textContent=message.textContent;}).observe(message,{childList:true,subtree:true,characterData:true});
const verified=l=>(packet?.verifiedPositions||[]).find(p=>key(p)===key(l));
const requestStatus=()=>window.dispatchEvent(new Event('plotdirector:refresh-word-status'));
@ -17,10 +17,10 @@ if(data.canonical?.chapterAcceptedUtc)status+=' This chapter last accepted: '+ne
sync.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!(current.canChapterSync||current.canParagraphSync);
for(const button of [nav,sceneNav,paragraphButton])if(button)button.disabled=busy||!!syncPending||!identity||current.wordSaved!==true||!current.canAcknowledgeNavigation;
if(identity&&!current.canAcknowledgeNavigation)position.textContent+=' Update the Word add-in and Companion together to enable confirmed navigation.';
const targetKey=identity&&current.wordSaved===true&&chapter?[chapter,scene,root.dataset.paragraphId,root.dataset.acceptedRevision,key(current),current.manuscriptId,current.revision,data.canonical?.revision].join(':'):'';
if(targetKey!==availabilityKey){availabilityKey=targetKey;availability={};const epoch=++availabilityEpoch;
const targetKey=identity&&current.wordSaved===true&&chapter?[chapter,scene,root.dataset.paragraphId,root.dataset.acceptedRevision,key(current),current.manuscriptId,current.revision,current.canAcknowledgeNavigation,current.canChapterSync,current.canParagraphSync,data.canonical?.revision,data.canonical?.chapterAcceptedUtc,data.canonical?.snapshotUtc].join(':'):'';
if(targetKey!==availabilityKey||(targetKey&&(availability.chapter===false||scene&&availability.scene===false||root.dataset.paragraphId&&availability.paragraph===false)&&Date.now()-availabilityChecked>=5000)){availabilityKey=targetKey;availability={};availabilityChecked=Date.now();const epoch=++availabilityEpoch;
if(targetKey){const query=new URLSearchParams({bookId:book,chapterId:chapter,instanceId:current.instanceId,sessionId:current.sessionId,manuscriptId:current.manuscriptId,revision:current.revision});if(scene)query.set('sceneId',scene);if(root.dataset.paragraphId){query.set('paragraphId',root.dataset.paragraphId);query.set('acceptedRevision',root.dataset.acceptedRevision);}
fetch('/WriterWord/Availability?'+query,{cache:'no-store'}).then(async response=>{if(!response.ok)throw Error();return response.json();}).then(value=>{if(epoch!==availabilityEpoch)return;availability=value;if(packet)render(packet);}).catch(()=>{if(epoch!==availabilityEpoch)return;message.textContent='Verified Word target mapping is unavailable. Check synchronisation or retry the connection.';availabilityKey='';});}
fetch('/WriterWord/Availability?'+query,{cache:'no-store',signal:AbortSignal.timeout(10000)}).then(async response=>{if(!response.ok)throw Error();return response.json();}).then(value=>{if(epoch!==availabilityEpoch)return;availability=value;if(packet)render(packet);}).catch(()=>{if(epoch!==availabilityEpoch)return;message.textContent='Verified Word target mapping is unavailable. Check synchronisation or retry the connection.';availabilityKey='';});}
}
if(nav)nav.disabled ||= availability.chapter!==true;if(sceneNav)sceneNav.disabled ||= availability.scene!==true;if(paragraphButton)paragraphButton.disabled ||= availability.paragraph!==true;
if(nav)nav.disabled ||= !chapter;if(sceneNav)sceneNav.disabled ||= !scene;if(paragraphButton)paragraphButton.disabled ||= !root.dataset.paragraphId;
@ -32,10 +32,10 @@ select.addEventListener('change',()=>render(packet));
window.addEventListener('plotdirector:focus-saved',event=>{abort?.abort();message.textContent='Working target changed. Word has not moved.';chapter=Number(event.detail.chapterID)||0;scene=Number(event.detail.sceneID)||0;root.dataset.chapterId=chapter||'';root.dataset.sceneId=scene||'';root.dataset.paragraphId='';root.dataset.statusUrl='/native-companion/status?writerBookId='+book+'&writerChapterId='+chapter;if(packet)render(packet);requestStatus();});
for(const button of document.querySelectorAll('[data-ribbon-word]'))button.addEventListener('click',()=>{if(button.disabled)return;(button.dataset.ribbonWord==='chapter'?nav:button.dataset.ribbonWord==='scene'?sceneNav:paragraphButton)?.click();});
async function navigate(toScene,toParagraph=false){if(busy||!current||!chapter)return;if(Date.parse(current.expires)<=Date.now()){message.textContent='Word connection expired. Check the connection before navigating.';render({...packet,leases:[]});requestStatus();return;}busy=true;abort=new AbortController();const selected={...current},id=crypto.randomUUID(),dispatch=performance.now();render(packet);message.textContent='Requesting navigation in Word…';const form=new URLSearchParams({bookId:String(book),chapterId:String(chapter),instanceId:selected.instanceId,sessionId:selected.sessionId,manuscriptId:selected.manuscriptId,revision:String(selected.revision),navigationId:id,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});if(toScene)form.set('sceneId',String(scene));if(toParagraph){form.set('paragraphId',root.dataset.paragraphId);form.set('acceptedRevision',root.dataset.acceptedRevision);}try{const response=await fetch('/WriterWord/Navigate',{method:'POST',body:form,signal:abort.signal});const data=await response.json().catch(()=>null);if(!response.ok)throw Error(data?.message||'Navigation could not be requested. Check your connection and sign-in.');message.textContent='Requested in Word; waiting for confirmation.';console.debug('Word navigation',id,'server request ms',Math.round(performance.now()-dispatch));const start=Date.now();let done=false;while(Date.now()-start<30000){await new Promise((resolve,reject)=>{const signal=abort.signal;const cancel=()=>{clearTimeout(timer);reject(new Error('Navigation was not confirmed. Word changed or disconnected.'));};const timer=setTimeout(()=>{signal.removeEventListener('abort',cancel);resolve();},1000);signal.addEventListener('abort',cancel,{once:true});});const receipt=await fetch(`/WriterWord/Navigation?bookId=${book}&instanceId=${selected.instanceId}&sessionId=${selected.sessionId}&navigationId=${id}`,{signal:abort.signal,cache:'no-store'});if(!receipt.ok)throw Error('Navigation confirmation unavailable.');const result=await receipt.json();if(result.state!=='requested'){console.debug('Word navigation',id,'confirmation ms',Math.round(performance.now()-dispatch),result.state);message.textContent=result.state==='completed'?(toParagraph?'Word confirmed navigation to the paragraph start.':'Word confirmed navigation.'):result.state==='failed'?'Word could not navigate. Your work was retained.':'Navigation expired or the document changed. No completion was confirmed.';done=true;break;}}if(!done)message.textContent='Word did not confirm navigation in time. Check the manuscript before retrying.';}catch(error){message.textContent=error.name==='AbortError'?'Navigation was not confirmed. Check Word before retrying.':error.message;}finally{busy=false;abort=null;if(packet)render(packet);requestStatus();}}
async function navigate(toScene,toParagraph=false){if(busy||!current||!chapter)return;if(Date.parse(current.expires)<=Date.now()){message.textContent='Word connection expired. Check the connection before navigating.';render({...packet,leases:[]});requestStatus();return;}busy=true;abort=new AbortController();const selected={...current},id=crypto.randomUUID(),dispatch=performance.now();render(packet);message.textContent='Requesting navigation in Word…';const form=new URLSearchParams({bookId:String(book),chapterId:String(chapter),instanceId:selected.instanceId,sessionId:selected.sessionId,manuscriptId:selected.manuscriptId,revision:String(selected.revision),navigationId:id,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});if(toScene)form.set('sceneId',String(scene));if(toParagraph){form.set('paragraphId',root.dataset.paragraphId);form.set('acceptedRevision',root.dataset.acceptedRevision);}try{const response=await fetch('/WriterWord/Navigate',{method:'POST',body:form,signal:abort.signal});const data=await response.json().catch(()=>null);if(!response.ok)throw Error(data?.message||'Navigation could not be requested. Check your connection and sign-in.');message.textContent='Requested in Word; waiting for confirmation.';console.debug('Word navigation',id,'server request ms',Math.round(performance.now()-dispatch));const start=Date.now();let done=false;while(Date.now()-start<30000){await new Promise((resolve,reject)=>{const signal=abort.signal;const cancel=()=>{clearTimeout(timer);reject(new Error('Navigation was not confirmed. Word changed or disconnected.'));};const timer=setTimeout(()=>{signal.removeEventListener('abort',cancel);resolve();},1000);signal.addEventListener('abort',cancel,{once:true});});const receipt=await fetch(`/WriterWord/Navigation?bookId=${book}&instanceId=${selected.instanceId}&sessionId=${selected.sessionId}&navigationId=${id}`,{signal:abort.signal,cache:'no-store'});if(!receipt.ok)throw Error('Navigation confirmation unavailable.');const result=await receipt.json();if(result.state!=='requested'){console.debug('Word navigation',id,'confirmation ms',Math.round(performance.now()-dispatch),result.state);message.textContent=result.state==='completed'?(toParagraph?'Word confirmed navigation to the paragraph start.':'Word confirmed navigation.'):result.state==='failed'?'Word could not navigate. Your work was retained.':'Navigation expired or the document changed. No completion was confirmed.';done=true;break;}}if(!done)message.textContent='Word did not confirm navigation in time. Check the manuscript before retrying.';}catch(error){availabilityKey='';availability={};message.textContent=error.name==='AbortError'?'Navigation was not confirmed. Check Word before retrying.':error.message;}finally{busy=false;abort=null;if(packet)render(packet);requestStatus();}}
sync.addEventListener('click',async()=>{if(sync.disabled||!current)return;const selected={...current};syncPending={key:key(selected),started:Date.now()};sync.disabled=true;const body=new URLSearchParams({bookId:String(book),instanceId:selected.instanceId,sessionId:selected.sessionId,__RequestVerificationToken:root.querySelector('[name=__RequestVerificationToken]').value});try{const response=await fetch('/manuscript/paragraphs/snapshot',{method:'POST',body,headers:{'X-Requested-With':'XMLHttpRequest'},signal:AbortSignal.timeout(15000)});const result=await response.json();if(!response.ok||response.redirected)throw Error(result.message||'Manuscript check unavailable.');if(syncPending)syncPending.requestId=result.requestId;message.textContent='Saved manuscript check requested; acceptance has not yet been confirmed. '+(result.message||'');}catch(error){syncPending=null;message.textContent=error.message||'Could not request manuscript check.';}finally{requestStatus();}});
paragraphButton?.addEventListener('click',()=>void navigate(false,true));window.addEventListener('review-reference-changed',()=>{if(packet)render(packet);});
nav?.addEventListener('click',()=>void navigate(false));sceneNav?.addEventListener('click',()=>void navigate(true));
root.querySelector('[data-word-check]').addEventListener('click',()=>{if(checkBusy)return;checkBusy=true;message.textContent='Checking reported connection and accepted updates. Use Synchronise in Companion to request a bounded manuscript check.';requestStatus();setTimeout(()=>checkBusy=false,2000);});
root.querySelector('[data-word-check]').addEventListener('click',()=>{if(checkBusy)return;checkBusy=true;availabilityKey='';availability={};message.textContent='Checking reported connection and accepted updates. Use Synchronise in Companion to request a bounded manuscript check.';requestStatus();setTimeout(()=>checkBusy=false,2000);});
window.addEventListener('writer-word-state',event=>render(event.detail));window.addEventListener('native-companion-presence',event=>{if(!event.detail.length&&packet&&!packet.leases?.length&&event.detail.connectionState==='Connected')state.textContent='Companion is connected; open and verify this manuscript in Word.';});window.addEventListener('pagehide',()=>abort?.abort());const initial=document.querySelector('#native-companion-status')?.writerWordState;if(initial)render(initial);
})();