PlotDirector/PlotLine.Tests/Browser/writer-word-notifications.cjs

25 lines
7.7 KiB
JavaScript

// Actual MVC/Razor and production JS. SignalR delivery/native receipts controlled; not physical Word/PWA.
const {chromium}=require('playwright'),assert=require('node:assert/strict');
const base=process.env.PD_BROWSER_FIXTURE_URL||'http://127.0.0.1:5238';
const stub=`window.__hubHandlers={};window.signalR={HubConnectionState:{Connected:'Connected',Disconnected:'Disconnected'},HubConnectionBuilder:class{withUrl(url){this.url=url;return this}withAutomaticReconnect(){return this}build(){const handlers=window.__hubHandlers[this.url]||(window.__hubHandlers[this.url]={});return{state:'Connected',on:(name,fn)=>handlers[name]=fn,onreconnected:fn=>handlers.reconnected=fn,onreconnecting:()=>{},onclose:()=>{},start:async()=>{},stop:async()=>{},invoke:async()=>({windows:[],isConnected:false})}}}};`;
(async()=>{const browser=await chromium.launch();try{for(const pwa of [false,true]){
const c=await browser.newContext({viewport:{width:1440,height:1000}});await c.addInitScript(pwa=>{localStorage.setItem('plotdirector.desktop.v1.4',JSON.stringify({dismissedAt:Date.now()}));if(pwa)Object.defineProperty(navigator,'standalone',{value:true});window.__receiptListeners=new Set();const add=window.addEventListener.bind(window),remove=window.removeEventListener.bind(window);window.addEventListener=(type,fn,...args)=>{if(type==='plotdirector:native-presence-changed')__receiptListeners.add(fn);return add(type,fn,...args)};window.removeEventListener=(type,fn,...args)=>{if(type==='plotdirector:native-presence-changed')__receiptListeners.delete(fn);return remove(type,fn,...args)};},pwa);
await c.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:stub}));
const lease={instanceId:'11111111-1111-1111-1111-111111111111',sessionId:'22222222-2222-2222-2222-222222222222',manuscriptId:'33333333-3333-3333-3333-333333333333',bookId:12,wordAvailable:true,wordSaved:true,canAcknowledgeNavigation:true,canChapterSync:true,revision:2,documentTitle:'Synthetic notification fixture',expires:new Date(Date.now()+3600000).toISOString()};
let packet={leases:[lease],canonical:{manuscriptID:lease.manuscriptId},verifiedPositions:[]},state='requested',wrong=null,beforeAccept=false,posts=0,reads=0,active=0,peak=0,hold=false,release;let p;
await c.route('**/native-companion/status*',r=>r.fulfill({json:packet}));await c.route('**/Writer/Work/State?*',r=>r.fulfill({json:{session:null}}));await c.route('**/WriterWord/Availability?*',r=>r.fulfill({json:{chapter:true,scene:true,paragraph:true}}));
const pulse=()=>p.evaluate(()=>__hubHandlers['/hubs/native-companion'].NativePresenceChanged({bookId:12}));
await c.route('**/WriterWord/Navigate',async r=>{posts++;const body=Object.fromEntries(new URLSearchParams(r.request().postData()));if(beforeAccept){state='completed';await pulse();}return r.fulfill({status:202,json:{navigationId:body.navigationId}})});
await c.route('**/WriterWord/Navigation?*',async r=>{reads++;active++;peak=Math.max(peak,active);const result={...Object.fromEntries(new URL(r.request().url()).searchParams),state};if(wrong)result[wrong]='99999999-9999-9999-9999-999999999999';if(hold){hold=false;await new Promise(resolve=>release=resolve);}await r.fulfill({json:result});active--;});
p=await c.newPage();const errors=[],diagnostics=[];p.on('pageerror',e=>errors.push(e.message));p.on('console',m=>{if(m.text().includes('notification-to-receipt'))diagnostics.push(m.text())});
await p.goto(base+'/Writer/Write?projectId=7&bookId=12&objective=true');await p.waitForFunction(()=>window.PlotDirectorNarrativeFocus);await p.evaluate(()=>PlotDirectorNarrativeFocus.set({bookID:12,chapterID:21,sceneID:31}));const button=p.locator('[data-ribbon-word=chapter]'),message=p.locator('[data-word-command]');await message.evaluate(n=>{for(let p=n.parentElement;p;p=p.parentElement)if(p.tagName==='DETAILS')p.open=true;});await p.waitForFunction(()=>!document.querySelector('[data-ribbon-word=chapter]').disabled);await p.locator('[data-work-note]').evaluate(n=>n.value='Retained synthetic note');
const collapse=p.locator('[data-ribbon-collapse]');if(await collapse.count()&&await collapse.getAttribute('aria-expanded')==='false')await collapse.click();const start=Date.now(),firstReceipt=p.waitForResponse(r=>r.url().includes('/WriterWord/Navigation?'));await button.click();await firstReceipt;assert(Date.now()-start<850,'first receipt is immediate, not delayed by the one-second timer');assert.equal(await p.evaluate(()=>__receiptListeners.size),1);assert(!(await message.textContent()).includes('confirmed navigation'));
await pulse();await p.waitForTimeout(80);assert(!(await message.textContent()).includes('confirmed navigation'),'a hint without native completion cannot report success');state='completed';const wake=Date.now();await pulse();await message.filter({hasText:'Word confirmed navigation.'}).waitFor();assert(Date.now()-wake<850,'existing SignalR handler wakes exact receipt before fallback timer');assert.equal(await p.evaluate(()=>__receiptListeners.size),0);assert(diagnostics.length>0);
state='requested';hold=true;const before=reads;await button.click();await p.waitForFunction(()=>__receiptListeners.size===1);while(!release)await p.waitForTimeout(10);await p.evaluate(()=>{for(let i=0;i<500;i++)__hubHandlers['/hubs/native-companion'].NativePresenceChanged({bookId:12})});state='completed';release();release=null;await message.filter({hasText:'Word confirmed navigation.'}).waitFor();assert.equal(peak,1,'receipt requests remain single-flight');assert(reads-before<=3,'duplicate notifications are coalesced');assert.equal(await p.locator('[data-work-note]').inputValue(),'Retained synthetic note');
for(const field of ['navigationId','instanceId','sessionId','manuscriptId']){wrong=field;state='completed';await button.click();await message.filter({hasText:'did not match'}).waitFor();assert.equal(await p.evaluate(()=>__receiptListeners.size),0,'listener released on mismatched receipt');}wrong=null;
beforeAccept=true;await button.click();await message.filter({hasText:'Word confirmed navigation.'}).waitFor();beforeAccept=false;assert.equal(await p.evaluate(()=>__receiptListeners.size),0,'acknowledgement-before-202 race reconciles without a lost wake');
state='requested';const fallbackReceipt=p.waitForResponse(r=>r.url().includes('/WriterWord/Navigation?'));await button.click();await fallbackReceipt;state='completed';await message.filter({hasText:'Word confirmed navigation.'}).waitFor({timeout:2500});assert.equal(await p.evaluate(()=>__receiptListeners.size),0,'missing notification retains polling fallback');
const second={...lease,sessionId:'44444444-4444-4444-4444-444444444444'};packet={...packet,leases:[lease,second]};await p.evaluate(v=>dispatchEvent(new CustomEvent('writer-word-state',{detail:v})),packet);await p.locator('[data-word-document]').selectOption(lease.instanceId+'/'+lease.sessionId);state='requested';await button.click();await message.filter({hasText:'waiting for confirmation'}).waitFor();const priorPosts=posts;packet={...packet,leases:[second]};await p.evaluate(v=>dispatchEvent(new CustomEvent('writer-word-state',{detail:v})),packet);await message.filter({hasText:'not confirmed'}).waitFor();await pulse();await p.waitForTimeout(80);assert.equal(posts,priorPosts);assert(await button.isDisabled());assert.equal(await p.evaluate(()=>__receiptListeners.size),0,'disconnect abort removes pending listener');assert.equal(await p.locator('[data-work-note]').inputValue(),'Retained synthetic note');assert.deepEqual(errors,[]);
console.log('PASS navigation SignalR wake '+(pwa?'simulated PWA':'Chromium')+': immediate/correlated receipts, no false completion, duplicate/inflight/pre-202 races, fallback, R2 disconnect, listener/resource cleanup and retained note.');await c.close();
}}finally{await browser.close();}})().catch(e=>{console.error(e.stack);process.exitCode=1});