// 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){this.handlers[n]=f},onreconnecting(f){this.reconnecting=f},onreconnected(f){this.reconnected=f},onclose(f){this.closed=f},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('**/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()).replace('Saved scene summary and provenance',`Saved scene summary and provenance ยท 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='single-pane actual Razor';await page.goto(base+'/Writing/Context'); await page.locator('[data-context-pane="0"] [data-context-tab-fragment][data-scene-id="22"]').waitFor(); assert.equal(await page.evaluate(()=>contextConnections.length),1,'one shared connection, including native status shell'); assert.equal(await page.locator('[data-context-pane="1"]').isVisible(),false); assert.match(await page.locator('[data-context-pane="0"]').innerText(),/viewpoint knowledge|POV/i); step='columns, independent tools';await page.selectOption('[data-context-layout]','columns'); await page.locator('[data-context-pane="1"] [data-context-tab-fragment]').waitFor(); assert.match(await page.locator('[data-context-pane="1"]').innerText(),/Fixture participant/); assert.match(await page.locator('[data-context-pane="1"]').innerText(),/Uncertain/); assert.match(await page.locator('[data-context-pane="1"]').innerText(),/future record/); if(process.env.PD_CONTEXT_EVIDENCE){fs.mkdirSync(process.env.PD_CONTEXT_EVIDENCE,{recursive:true});await page.screenshot({path:process.env.PD_CONTEXT_EVIDENCE+'/columns-1366.png'});} step='same tab twice and shared HTTP request';requests=[]; await page.selectOption('[data-context-pane="1"] [data-context-tab]','overview'); await page.waitForFunction(()=>[...document.querySelectorAll('[data-context-pane-content]')].every(n=>n.textContent.includes('Saved scene summary'))); await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.invalidate()); await page.waitForTimeout(180); assert.equal(requests.length,2,'one new pane initial read plus one shared invalidation read'); const ids=await page.locator('[id]').evaluateAll(nodes=>nodes.map(n=>n.id));assert.equal(ids.length,new Set(ids).size,'no duplicate IDs'); assert.equal(await page.locator('[data-context-pane="0"] [data-context-tab-fragment]').evaluate((n)=>n===document.querySelector('[data-context-pane="1"] [data-context-tab-fragment]')),false); step='divider keyboard and drag';const divider=page.locator('[data-context-divider]');await divider.focus();const initial=Number(await divider.getAttribute('aria-valuenow'));await page.keyboard.press('ArrowRight');assert(Number(await divider.getAttribute('aria-valuenow'))>initial); let box=await divider.boundingBox();await page.mouse.move(box.x+box.width/2,box.y+box.height/2);await page.mouse.down();await page.mouse.move(850,box.y+box.height/2);await page.mouse.up();assert(Number(await divider.getAttribute('aria-valuenow'))>55); step='stacked layout';await page.selectOption('[data-context-layout]','rows');assert.equal(await divider.getAttribute('aria-orientation'),'horizontal');await divider.focus();await page.keyboard.press('ArrowUp'); const a=await page.locator('[data-context-pane="0"]').boundingBox(),b=await page.locator('[data-context-pane="1"]').boundingBox();assert(b.y>a.y+a.height); step='single retains second pane selection';await page.selectOption('[data-context-pane="1"] [data-context-tab]','characters');await page.selectOption('[data-context-layout]','single');await page.selectOption('[data-context-layout]','columns');assert.equal(await page.locator('[data-context-pane="1"] [data-context-tab]').inputValue(),'characters'); step='unrelated-project notifications do not reload panes';const scopedReads=requests.length;await page.evaluate(()=>contextConnections[0].handlers.ContextInvalidated({projectId:999}));await page.waitForTimeout(80);assert.equal(requests.length,scopedReads); step='same scene accepted content and inactive stale selection';revision=2;await page.evaluate(()=>contextConnections[0].handlers.ContextInvalidated({bookId:12}));await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 2')); await page.selectOption('[data-context-pane="0"] [data-context-tab]','characters');await page.selectOption('[data-context-pane="0"] [data-context-tab]','overview');await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 2')); step='rapid scene/chapter navigation and out of order responses';delayScene='23';await page.evaluate(()=>{const c=document.querySelector('[data-context-workspace]').contextController;c.setPosition({projectId:7,bookId:12,chapterId:11,sceneId:23});setTimeout(()=>c.setPosition({projectId:7,bookId:12,chapterId:10,sceneId:22}),30);});await page.waitForTimeout(550);assert.equal(await page.locator('[data-context-pane="0"] [data-context-tab-fragment]').getAttribute('data-scene-id'),'22');delayScene=null; step='dirty/busy deferral';await page.evaluate(()=>document.querySelector('[data-context-pane="0"]').dispatchEvent(new CustomEvent('context-panel-state',{detail:{dirty:true}})));revision=3;await page.evaluate(()=>contextConnections[0].handlers.ContextInvalidated({bookId:12}));await page.waitForTimeout(160);assert.match(await page.locator('[data-context-pane="0"]').innerText(),/revision 2/);assert.match(await page.locator('[data-context-pane="0"] [data-context-pane-status]').innerText(),/editing|busy/); await page.evaluate(()=>document.querySelector('[data-context-pane="0"]').dispatchEvent(new CustomEvent('context-panel-state',{detail:{dirty:false,busy:false}})));await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 3')); step='session expiry and mapping conflict';mode='expired';await page.click('[data-context-refresh]');await page.waitForFunction(()=>document.querySelector('[data-context-pane-status]').textContent.includes('Sign in'));assert.match(await page.locator('[data-context-pane="0"]').innerText(),/revision 3/);mode='mapping';await page.click('[data-context-refresh]');await page.waitForFunction(()=>document.querySelector('[data-context-pane-status]').textContent.includes('mapping'));mode='ok'; step='disconnect and unchanged-position reconnect';revision=4;await page.evaluate(()=>contextConnections[0].reconnecting());assert.match(await page.locator('[data-context-status]').innerText(),/reconnecting/);await page.evaluate(()=>contextConnections[0].reconnected());await page.waitForFunction(()=>document.querySelector('[data-context-pane="0"]').textContent.includes('revision 4')); step='native ambiguity and missing mapping';leases=[lease(),lease({instanceId:'44444444-4444-4444-8444-444444444444',active:true})];await page.evaluate(()=>window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status')));await page.waitForFunction(()=>document.querySelector('[data-context-status]').textContent.includes('Choose a Word document')); await page.click('#native-companion-status');await page.selectOption('#writing-word-document','44444444-4444-4444-8444-444444444444/22222222-2222-4222-8222-222222222222');await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.position.instanceId==='44444444-4444-4444-8444-444444444444');assert.equal(new URL(page.url()).searchParams.get('instanceId'),'44444444-4444-4444-8444-444444444444');await page.reload();await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.position.instanceId==='44444444-4444-4444-8444-444444444444');await page.click('#native-companion-status');assert.equal(await page.locator('#writing-word-document').inputValue(),'44444444-4444-4444-8444-444444444444/22222222-2222-4222-8222-222222222222');await page.selectOption('#writing-word-document','');await page.click('[data-close-word-details]'); leases=[lease({positionVerified:false,positionMessage:'Mapping pending'})];await page.evaluate(()=>window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status')));await page.waitForFunction(()=>document.querySelector('[data-context-status]').textContent.includes('Mapping pending')); step='saved manual reads survive unavailable Word observations';delayScene='23';await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.setPosition({projectId:7,bookId:12,chapterId:11,sceneId:23}));await page.waitForTimeout(40);await page.evaluate(leases=>window.dispatchEvent(new CustomEvent('native-companion-presence',{detail:leases})),leases);await page.waitForSelector('[data-context-pane=\"0\"] [data-context-tab-fragment][data-scene-id=\"23\"]');delayScene=null; step='Office fallback and native precedence';leases=[];office={connected:true,position:{projectId:7,bookId:12,chapterId:11,sceneId:23}};await page.evaluate(()=>window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status')));await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId===23); leases=[lease()];await page.evaluate(()=>window.dispatchEvent(new CustomEvent('plotdirector:refresh-word-status')));await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId===22); step='persistence';await page.selectOption('[data-context-layout]','rows');const identity=await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId);await page.reload();await page.waitForSelector('[data-context-tab-fragment]');assert.equal(await page.locator('[data-context-layout]').inputValue(),'rows');assert.equal(await page.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId),identity); step='cloned window storage';const storage=await page.evaluate(()=>({id:sessionStorage.getItem('plotdirector.context.window.v1')}));const clone=await context.newPage();await clone.addInitScript(s=>sessionStorage.setItem('plotdirector.context.window.v1',s.id),storage);await clone.goto(base+'/Writing/Context');await clone.waitForFunction(id=>document.querySelector('[data-context-workspace]')?.contextController?.windowId!==id,identity);assert.equal(await clone.locator('[data-context-layout]').inputValue(),'single');assert.equal(await page.locator('[data-context-layout]').inputValue(),'rows');await clone.close(); step='multiple windows';const popupPromise=page.waitForEvent('popup');await page.click('[data-context-new]');const popup=await popupPromise;await popup.waitForSelector('[data-context-tab-fragment]');assert.equal(await popup.locator('[data-context-layout]').inputValue(),'single');assert.notEqual(await popup.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.windowId),identity);assert.equal(await popup.evaluate(()=>contextConnections.length),1);await popup.close(); step='laptop, narrow pane, zoom and standalone presentation';for(const [width,height,zoom]of [[1366,768,1],[760,768,1],[683,384,1],[480,700,1.25]]){ await page.setViewportSize({width,height});await page.evaluate(zoom=>document.documentElement.style.zoom=zoom,zoom); for(const layout of ['single','columns','rows']){await page.selectOption('[data-context-layout]',layout);await page.waitForTimeout(40);assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+2),false,`window overflow ${width}/${layout}/${zoom}`);assert(await page.locator('[data-context-pane="0"] [data-context-pane-content]').evaluate(n=>n.clientHeight>30));} } await page.evaluate(()=>{document.documentElement.style.zoom='1';Object.defineProperty(navigator,'standalone',{value:true});}); step='pinned snapshot';leases=[lease({sceneId:23,chapterId:11})];const pinned=await context.newPage();await pinned.goto(base+'/Writing/Context?pinned=true&sceneId=22');await pinned.waitForSelector('[data-context-tab-fragment]');assert.equal(await pinned.evaluate(()=>contextConnections.length),0);assert.equal(await pinned.locator('[data-context-tab-fragment]').getAttribute('data-scene-id'),'22');await pinned.selectOption('[data-context-scene]','23');await pinned.waitForSelector('[data-context-tab-fragment][data-scene-id="23"]');await pinned.close(); step='generic hierarchical registration scopes'; for(const declared of ['None','Book','Chapter','Scene','Paragraph']){ const generic=await context.newPage();let count=0; await generic.route('**/Writing/Context?pinned=true*',async route=>{const response=await route.fetch();await route.fulfill({response,body:(await response.text()).replaceAll('"scope":"Scene"','"scope":"'+declared+'"')});}); await generic.route('**/Writing/Context/Tabs/*',async route=>{count++;const params=new URL(route.request().url()).searchParams,level=['None','Book','Chapter','Scene','Paragraph'].indexOf(declared),fields=['projectId','bookId','chapterId','sceneId','paragraphId'];const attributes=fields.slice(0,level===0?0:level+1).filter(f=>params.has(f)).map(f=>'data-'+f.replace(/[A-Z]/g,c=>'-'+c.toLowerCase())+'="'+params.get(f)+'"').join(' ');await route.fulfill({contentType:'text/html',body:'
Generic reference