PlotDirector/PlotLine.Tests/Browser/writing-context-follow-recovery.cjs

60 lines
9.6 KiB
JavaScript

// Real scripts in Chromium with controlled native/legacy event interleavings. No Word automation.
const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');
(async()=>{const browser=await chromium.launch();try{
const page=await browser.newPage(),errors=[];page.on('pageerror',e=>errors.push(e.message));
const html=`<button id="native-companion-status"><span id="native-companion-status-text">Checking Word…</span></button><main data-writing-context data-scope-book-id="12" data-scope-project-id="7" data-context-url="/Writing/Context/Scene"><span data-writing-context-status-text></span><input name="__RequestVerificationToken" value="fixture"><section data-writing-context-content></section></main>`;
const fragment=(scene)=>`<article data-writing-context-fragment data-project-id="7" data-book-id="12" data-chapter-id="${scene===22?10:11}" data-scene-id="${scene}"><nav><button data-writing-context-tab="overview">Overview</button><button data-writing-context-tab="people">People</button></nav><select data-writing-context-scene-select><option value="22" ${scene===22?'selected':''}>First</option><option value="23" ${scene===23?'selected':''}>Second</option></select><button data-writing-scene-step="${scene===22?23:22}">Next</button><div data-writing-context-panel="overview">Overview saved data</div><div data-writing-context-panel="people">People saved data</div></article>`;
let current=22,wordSaved=true,verified=true,fragmentReads=0,failStatus=false,holdStatus=false,release,reads=0,commands=0,fragmentFailure=false,fragmentConflict=false,holdFragment=false,releaseFragment;
await page.route('https://context.test/**',async r=>{const u=new URL(r.request().url());
if(u.pathname==='/')return r.fulfill({contentType:'text/html',body:html});
if(u.pathname==='/native-companion/status'){
reads++;const snapshot=current;if(holdStatus){holdStatus=false;await new Promise(resolve=>release=resolve);}
return r.fulfill(failStatus?{status:503}:{json:[{instanceId:'instance',sessionId:'session',bookId:12,chapterId:snapshot===22?10:11,sceneId:snapshot,wordAvailable:true,wordSaved,positionVerified:verified,active:true,documentTitle:'Synthetic',expires:new Date(Date.now()+45000).toISOString()}]});}
if(u.pathname==='/Writing/Context/Scene'){
fragmentReads++;assert.equal(u.searchParams.get('instanceId')||'instance','instance');assert.equal(u.searchParams.get('sessionId')||'session','session');
if(holdFragment){holdFragment=false;await new Promise(resolve=>releaseFragment=resolve);}
return r.fulfill(fragmentConflict?{status:409}:fragmentFailure?{status:503}:{contentType:'text/html',body:fragment(Number(u.searchParams.get('sceneId')))});}
if(u.pathname==='/Writing/Context/Navigate'){commands++;assert.ok(new URLSearchParams(r.request().postData()).get('navigationId'));return r.fulfill({json:{message:'Navigation requested in Word.'}});}
return r.fulfill({json:{known:false}});
});
await page.goto('https://context.test/');await page.evaluate(fragment=>document.querySelector('[data-writing-context-content]').innerHTML=fragment,fragment(22));
await page.evaluate(()=>{window.hubHandlers={};window.focusCalls=0;window.focus=()=>focusCalls++;window.intervals=[];window.setInterval=f=>(intervals.push(f),intervals.length);window.signalR={HubConnectionBuilder:class{withUrl(){return this}withAutomaticReconnect(){return this}build(){return{state:'Disconnected',on:(name,fn)=>hubHandlers[name]=fn,onreconnected:()=>{},start:async()=>{},stop:async()=>{}}}}};window.PlotDirectorWritingWorkspace={watchWorkspace:async()=>null};});
for(const name of ['story-position','writing-follow','writing-context','native-companion-status']){
let script=fs.readFileSync(path.resolve(__dirname,'../../PlotLine/wwwroot/js/'+name+'.js'),'utf8');
if(process.env.PD_SCRIPT_BASE)script=await(await page.request.get(process.env.PD_SCRIPT_BASE+'/js/'+name+'.js')).text();
await page.addScriptTag({content:script});
}
const scene=async id=>page.waitForFunction(id=>document.querySelector('[data-writing-context-fragment]').dataset.sceneId===String(id),id);
const pulse=()=>page.evaluate(()=>intervals[0]());await page.waitForFunction(()=>document.querySelector('#native-companion-status').dataset.connected==='true');
await page.click('[data-writing-context-tab=people]');await page.evaluate(()=>{window.elementFocusCalls=0;const original=HTMLElement.prototype.focus;HTMLElement.prototype.focus=function(...args){elementFocusCalls++;return original.apply(this,args);};});
current=23;await pulse();await scene(23);assert.equal(commands,0);assert.equal(await page.evaluate(()=>elementFocusCalls),0,'passive following must not refocus any browser control');assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());
// A delayed legacy broadcast must not override a live native cursor scene.
await page.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:story-position-changed',{detail:{projectId:7,bookId:12,chapterId:10,sceneId:22,source:'WordCompanion'}})));
await page.waitForTimeout(120);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'23','stale legacy position cannot replace live native scene');
const repeated=fragmentReads;
for(let i=0;i<8;i++)await pulse();await page.waitForTimeout(60);assert.equal(commands,0);assert.equal(await page.evaluate(()=>focusCalls),0);assert.equal(fragmentReads,repeated,'unchanged native scenes do not recompute context fragments');
// Status failure must dispatch disconnection, not throw ReferenceError for an out-of-scope leases variable.
failStatus=true;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('disconnected'));
failStatus=false;current=22;await pulse();await scene(22);assert.deepEqual(errors,[]);
// SignalR invalidation during an HTTP read must be drained, not discarded until a 15-second poll.
holdStatus=true;await pulse();await page.waitForFunction(()=>document.querySelector('#native-companion-status').dataset.connected==='true');while(!release)await page.waitForTimeout(10);
const before=reads;current=23;await page.evaluate(()=>hubHandlers.NativePresenceChanged());await page.waitForTimeout(300);release();await scene(23);assert.ok(reads>before,'pending invalidation triggers a trailing authoritative read');
// Failed fragment read can recover on an unchanged authoritative scene, without navigating Word.
fragmentFailure=true;current=22;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent==='Context unavailable');fragmentFailure=false;await pulse();await scene(22);assert.equal(commands,0);
// Programmatic scene changes can browse saved information but may not command Word.
await page.selectOption('[data-writing-context-scene-select]','23');await scene(23);assert.equal(commands,0);
// Genuine keyboard action requests exactly one command; its acknowledgement is passive.
await page.locator('[data-writing-context-scene-select]').press('Home');await scene(22);await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Navigation requested'));assert.equal(commands,1);
current=22;for(let i=0;i<4;i++)await pulse();await page.waitForTimeout(60);assert.equal(commands,1);assert.ok(await page.locator('[data-writing-context-panel=people]').isVisible());assert.deepEqual(errors,[]);
// A pending/unsaved mapping must invalidate an older in-flight scene response.
holdFragment=true;current=23;await pulse();while(!releaseFragment)await page.waitForTimeout(10);
wordSaved=false;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('Save Word'));
releaseFragment();await page.waitForTimeout(150);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22','late fragment cannot restore an earlier cursor after native mapping becomes pending');
wordSaved=true;verified=false;await pulse();await page.waitForTimeout(60);assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22','unverified claimed native scene cannot replace saved context');
verified=true;fragmentConflict=true;await pulse();await page.waitForFunction(()=>document.querySelector('[data-writing-context-status-text]').textContent.includes('awaiting verification'));assert.equal(await page.locator('[data-writing-context-fragment]').getAttribute('data-scene-id'),'22');fragmentConflict=false;await pulse();await scene(23);assert.equal(commands,1);
console.log('PASS pending native response cancellation, unverified mapping refusal, exact-session query parameters and no recomputation for repeated unchanged scenes');
console.log('PASS native/legacy race, cross-chapter cursor following, repeated presence without commands/focus, status failure recovery, in-flight invalidation, unchanged-scene fragment retry, trusted explicit navigation and acknowledgement without feedback; simulated Chromium protocol, not Word');
// Native safety source guard: ordinary polling must never invalidate the ribbon or select a range.
const adapter=fs.readFileSync(path.resolve(__dirname,'../../PlotDirector.NativeCompanion/Vsto/WordAdapter.cs'),'utf8');const observation=adapter.split('private void CaptureSelection()')[1].split('private int DocumentEnd')[0];assert.doesNotMatch(observation,/invalidateRibbon\(|\.Select\(/);assert.match(adapter,/command.Kind=="navigate"/);console.log('PASS native source invariant: selection observation contains no ribbon invalidation or range selection (not runtime Word proof)');
}finally{await browser.close();}})().catch(e=>{console.error(e);process.exit(1);});