PlotDirector/PlotLine.Tests/Browser/character-attributes-held-context.cjs

50 lines
5.5 KiB
JavaScript

// Focused saved-character invalidation with the real Context Razor/scripts; disposable HTTP fixtures.
// Actual compiled Razor shell and partials; isolated loopback fixture, no database or Word writes.
const {chromium}=require('playwright');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238';
const fakeSignalR=`window.contextConnections=[];window.signalR={HubConnectionBuilder:class{withUrl(url){this.url=url;return this}withAutomaticReconnect(){return this}build(){const c={url:this.url,state:'Disconnected',handlers:{},on(n,f){const prior=this.handlers[n];this.handlers[n]=(...args)=>{prior?.(...args);f(...args)}},onreconnecting(f){const prior=this.reconnecting;this.reconnecting=(...args)=>{prior?.(...args);f(...args)}},onreconnected(f){const prior=this.reconnected;this.reconnected=(...args)=>{prior?.(...args);f(...args)}},onclose(f){const prior=this.closed;this.closed=(...args)=>{prior?.(...args);f(...args)}},async start(){this.state='Connected'},async stop(){this.state='Disconnected'}};contextConnections.push(c);return c}}};`;
const lease=(extra={})=>({instanceId:'11111111-1111-4111-8111-111111111111',sessionId:'22222222-2222-4222-8222-222222222222',manuscriptId:'33333333-3333-4333-8333-333333333333',bookId:12,chapterId:10,sceneId:22,wordAvailable:true,wordSaved:true,active:true,positionVerified:true,mappingCurrent:true,snapshotRevision:1,revision:1,documentTitle:'Synthetic manuscript',updated:new Date().toISOString(),expires:new Date(Date.now()+45000).toISOString(),...extra});
(async()=>{
const browser=await chromium.launch();let step='setup';
try{
const context=await browser.newContext({viewport:{width:1366,height:768}});
let leases=[lease()],office={connected:false,position:null},revision=1,mode='ok',delayScene=null,requests=[];
await context.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fakeSignalR}));
await context.route('**/native-companion/status',r=>r.fulfill({json:leases}));
await context.route('**/native-companion/connection-state',r=>r.fulfill({json:{known:false,state:'Disconnected'}}));
await context.route('**/NarrativeFocus/Shared?*',r=>r.fulfill({json:{projectID:7,bookID:12,chapterID:10,sceneID:22,version:1,isValid:true}}));
await context.route('**/Writing/Context/Position?*',r=>r.fulfill({json:office}));
await context.route('**/Writing/Context/Navigate',r=>r.fulfill({status:409,json:{message:'No current Word mapping. Saved scene selected.'}}));
await context.route('**/Writing/Context/Tabs/*',async route=>{
const url=new URL(route.request().url());const tool=url.pathname.split('/').at(-1),scene=url.searchParams.get('sceneId');
requests.push({tool,scene,revision});const captured=revision;
if(mode==='expired')return route.fulfill({status:401,body:'Sign in'});
if(mode==='mapping')return route.fulfill({status:409,body:'Mapping pending'});
const response=await route.fetch({url:`${base}/context-tab-fixture/${tool}?sceneId=${scene}`});
const html=(await response.text()).replaceAll('Fixture participant',`Fixture participant · revision ${captured}`);
if(delayScene===scene)await new Promise(resolve=>setTimeout(resolve,350));
try{await route.fulfill({contentType:'text/html',body:html});}catch{/* Navigation may abort an obsolete shared read. */}
});
const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
step='Held Context actual Razor';await page.goto(base+'/Writing/Context?pinned=true');
await page.waitForFunction(()=>window.PlotDirectorSharedFocus?.held&&window.PlotDirectorSharedFocus?.shared?.isValid);
await page.selectOption('[data-context-pane="0"] [data-context-tab]','characters');
await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 1'));
assert.equal(await page.evaluate(()=>contextConnections.length),1);
const before=await page.evaluate(()=>({...document.querySelector('[data-context-workspace]').contextController.position}));
step='Held character data refresh does not follow newer shared position';
await page.evaluate(()=>contextConnections[0].handlers.ManuscriptFocusChanged({projectID:7,bookID:12,chapterID:11,sceneID:23,version:2,isValid:true}));
revision=2;await page.evaluate(()=>contextConnections[0].handlers.ContextInvalidated({projectId:7,kind:'characters'}));
await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 2'));
assert.deepEqual(await page.evaluate(()=>({...document.querySelector('[data-context-workspace]').contextController.position})),before);
assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.held),true);
assert.equal(await page.evaluate(()=>PlotDirectorSharedFocus.shared.sceneID),23);
assert(requests.filter(r=>r.revision===2).every(r=>r.scene==='22'));
const reads=requests.length;await page.evaluate(()=>contextConnections[0].handlers.ContextInvalidated({projectId:999,kind:'characters'}));await page.waitForTimeout(100);assert.equal(requests.length,reads);
assert.equal(await page.evaluate(()=>contextConnections.length),1);assert.deepEqual(errors,[]);
console.log('PASS character invalidation in actual Held Context: character data refreshes at held scene 22 while shared focus moves to 23; unrelated-project hints ignored; one connection; no held position changes');
}catch(e){console.error('FAILED at '+step+'\n'+e.stack);process.exitCode=1;}finally{await browser.close();}
})();