PlotDirector/PlotLine.Tests/Browser/context-my-windows.cjs

33 lines
8.0 KiB
JavaScript

// Real SignalR transport. Isolated loopback data by default; opt-in real Development uses disposable identity/scope.
const {chromium}=require('playwright'),fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');
const live=!!process.env.PD_CONTEXT_IDENTITY,base=live?'https://dev.plotdirector.com':(process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238');
(async()=>{const browser=await chromium.launch();let step='setup';try{
const scope=live?JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_SCOPE)):{project:7,book:12,chapter:10,scene:22};
const who=live?JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)):null;
if(live){assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,scope.user);assert(who.Email.startsWith('pwa-browser-'));}
const contexts=[];const pages=[];const counts=[];
for(let i=0;i<2;i++){
const context=await browser.newContext({viewport:{width:1366,height:768}});contexts.push(context);
if(!live){await context.route('**/cdn.jsdelivr.net/**signalr*',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(path.join(__dirname,'node_modules/@microsoft/signalr/dist/browser/signalr.min.js'))}));await context.route('**/native-companion/status',r=>r.fulfill({json:[]}));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:{connected:false,position:null}}));await context.route('**/Writing/Context/Tabs/*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-tab-fixture/'+u.pathname.split('/').at(-1)+u.search})});});}
const page=await context.newPage();pages.push(page);const count={hub:0,word:0,reads:0};counts.push(count);page.on('request',r=>{if(r.url().includes('/hubs/')&&r.url().includes('/negotiate'))count.hub++;if(r.url().includes('/Writing/Context/Navigate')||r.url().includes('/WriterWord/Navigate'))count.word++;if(r.url().includes('/Writing/Context/Tabs/'))count.reads++;});
if(live){await page.goto(base+'/Account/Login');await page.locator('[name=Email]').fill(who.Email);await page.locator('[name=Password]').fill(who.Password);await Promise.all([page.waitForURL(u=>u.pathname!=='/Account/Login'),page.locator('button[type=submit]').click()]);}
count.hub=0;count.word=0;count.reads=0;
await page.goto(`${base}/Writing/Context?projectId=${scope.project}&bookId=${scope.book}&sceneId=${scope.scene}`);await page.waitForSelector('[data-context-tab-fragment]');await page.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection?.state==='Connected');
}
const [source,destination]=pages;
step='two independently authenticated browser sessions';await source.waitForFunction(book=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',book).then(w=>w.length===2&&w.every(x=>x.panes[0].available)),scope.book);
const target=await destination.evaluate(()=>({windowID:document.querySelector('[data-context-workspace]').contextController.windowId,connection:document.querySelector('[data-context-workspace]').contextController.connection.connectionId}));
const command={version:1,bookID:scope.book,originPaneID:'0',action:'scene.focus',storyPoint:{chapterID:scope.chapter,sceneID:scope.scene},targetWindowID:target.windowID,targetSessionID:target.connection,targetPaneID:'0'};
await source.evaluate(()=>{window.receipts=[];document.querySelector('[data-context-workspace]').contextController.connection.on('ContextInteractionResult',r=>receipts.push(r));});
const before=counts.map(x=>x.reads),position=await source.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position);
step='targeted command and authoritative recipient read';const result=await source.evaluate(c=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('SendContextInteraction',c),command);assert.equal(result.status,'delivered');await destination.waitForSelector('.context-reference-focus');await source.waitForFunction(()=>receipts.some(r=>r.status==='focused'));
assert.equal(counts[0].reads,before[0]);assert.equal(counts[1].reads,before[1]+1);assert.equal(await source.locator('.context-reference-focus').count(),0);assert.deepEqual(await source.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position),position);assert(counts.every(x=>x.word===0&&x.hub===1));
step='no-handler does not replace a tool';await destination.selectOption('[data-context-pane="0"] [data-context-tab]','characters');await destination.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',Number(document.querySelector('[data-context-workspace]').dataset.scopeBookId)).then(rows=>rows.find(r=>r.windowID===document.querySelector('[data-context-workspace]').contextController.windowId)?.panes[0].toolID==='characters'));
const absent=await source.evaluate(c=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('SendContextInteraction',c),command);assert.equal(absent.status,'no-handler');assert.equal(await destination.locator('[data-context-tab]').first().inputValue(),'characters');
step='character handler focuses only intended recipient';await destination.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.announcement.panes[0].available);await destination.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('RegisterContextWindow',document.querySelector('[data-context-workspace]').contextController.announcement));const charBefore=counts.map(x=>x.reads);const characterCommand={...command,action:'character.focus',characterID:live?scope.characters?.[0]:5};if(characterCommand.characterID){const focused=await source.evaluate(c=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('SendContextInteraction',c),characterCommand);assert.equal(focused.status,'delivered');await destination.waitForSelector(`[data-context-character="${characterCommand.characterID}"].context-reference-focus`);await source.waitForFunction(id=>receipts.some(r=>r.commandID===id&&r.status==='focused'),focused.commandID);assert.equal(counts[0].reads,charBefore[0]);assert.equal(counts[1].reads,charBefore[1]+1);assert.deepEqual(await destination.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position),position);}
step='cross-user and cross-book rejection';for(const change of [{targetUserID:999},{bookID:2147483647},{storyPoint:{chapterID:scope.chapter,sceneID:2147483647}}])assert(await source.evaluate(async c=>{try{await document.querySelector('[data-context-workspace]').contextController.connection.invoke('SendContextInteraction',c);return false}catch{return true}},{...command,...change}));
step='disconnect and reconnect registration';await destination.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.connection.stop());await source.waitForFunction(book=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',book).then(w=>w.length===1),scope.book);await destination.evaluate(()=>document.dispatchEvent(new Event('visibilitychange')));await source.waitForFunction(book=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',book).then(w=>w.length===2),scope.book);
assert.equal(await destination.locator('[data-context-tab]').first().inputValue(),'characters');assert.equal(counts[1].word,0);
for(const context of contexts)await context.close();console.log('PASS My Windows real SignalR: two independent sessions, exact recipient and pane read, no unrelated mutation/Word navigation, no-handler, cross-user/book/story-point rejection and reconnect capability recovery'+(live?' on Development':' in isolated host'));
} catch(error){console.error('FAILED '+step+': '+error.message);process.exitCode=1;}finally{await browser.close();}})();