PlotDirector/PlotLine.Tests/Browser/writer-workspace.cjs

121 lines
9.6 KiB
JavaScript

const { chromium } = require('playwright');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const base = 'http://127.0.0.1:5238';
(async () => {
const browser = await chromium.launch();
try {
for (const pwa of [false,true]) {
const context = await browser.newContext({viewport:{width:1600,height:1000}});
if (pwa) await context.addInitScript(() => Object.defineProperty(navigator,'standalone',{value:true}));
const page = await context.newPage();
const errors=[];page.on('pageerror',error=>{errors.push(error.message);console.error(page.url(),error.stack);}); context.on('page',popup=>popup.on('pageerror',error=>errors.push(error.message)));
// Use the real SDK, production Hub/presence services, full Razor layout and scripts.
// Only the first network negotiation is failed; subsequent traffic reaches the loopback Hub.
await context.route('**/signalr.min.js',route=>route.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8') + `
;window.__writerConnections=[];const originalHubBuild=signalR.HubConnectionBuilder.prototype.build;signalR.HubConnectionBuilder.prototype.build=function(){const connection=originalHubBuild.call(this);window.__writerConnections.push(connection);return connection;};`}));
let negotiations=0;
await page.route('**/hubs/word-companion-follow/negotiate?*',route=>++negotiations===1?route.fulfill({status:503,body:'Transient fixture outage'}):route.continue());
await page.goto(base+'/fixture?page=writer&layout=full');
await page.waitForFunction(()=>!!window.PlotDirectorWritingWorkspace);
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-word]').textContent==='Unavailable');
assert.equal(negotiations,1,'Initial failed connection is not retried in a tight loop');
const start=page.getByRole('button',{name:'Start / Reapply Workspace',exact:true});
await page.evaluate(()=>{window.__originalWindowOpen=window.open;window.open=()=>null;});
await start.click();
await page.waitForFunction(()=>!document.querySelector('[data-start-writing-workspace]').disabled);
assert.ok(negotiations>=2,'A user command must retry after the initial connection failure');
assert.equal(await page.locator('[data-writing-workspace-word]').textContent(),'Not connected');
await page.evaluate(()=>window.open=window.__originalWindowOpen);
const windows=[];
for(const role of ['context','intent']){
const opened=context.waitForEvent('page');
await page.locator(`[data-open-writing-${role}]`).click();
const popup=await opened;await popup.waitForLoadState();
assert.equal(await popup.locator('[data-writing-mode]').count(),1,'Production writing-window view renders successfully');
windows.push(popup);
}
const identities=await Promise.all(context.pages().map(tab=>tab.evaluate(()=>window.PlotDirectorWritingWorkspace.getBrowserWindowId())));
assert.equal(new Set(identities).size,3,'Launcher, Context and Intent must have distinct presence identities even when sessionStorage is cloned from an opener');
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-context]').textContent==='Open' && document.querySelector('[data-writing-workspace-intent]').textContent==='Open');
for(const popup of windows){
const before=await popup.evaluate(()=>window.PlotDirectorWritingWorkspace.getBrowserWindowId());
await popup.reload();await popup.waitForFunction(()=>!!window.PlotDirectorWritingWorkspace);
assert.equal(await popup.evaluate(()=>window.PlotDirectorWritingWorkspace.getBrowserWindowId()),before,'Reload preserves the identity owned by this window');
}
await page.locator('[data-focus-writing-context]').click();
await page.locator('[data-focus-writing-intent]').click();
assert.equal(context.pages().length,3,'Focus commands reuse the existing writing windows');
const oldContext=windows[0];
const oldContextUrl=oldContext.url();
await page.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:story-position-changed',{detail:{projectId:7,bookId:13}})));
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-book]').textContent==='Book 13');
await page.evaluate(async()=>{
await window.PlotDirectorWritingWorkspace.watchWorkspace({projectID:7,bookID:13});
document.addEventListener('plotdirector:writing-workspace-status',event=>{
if((event.detail?.bookID||event.detail?.BookID)===12)window.__labelDuringOtherBookUpdate=document.querySelector('[data-writing-workspace-book]').textContent;
});
});
await oldContext.evaluate(()=>window.__writerConnections.at(-1).invoke('WritingWindowHeartbeat',{
browserWindowID:window.PlotDirectorWritingWorkspace.getBrowserWindowId(),projectID:7,bookID:12,writingRole:'Context',currentRoute:location.pathname
}));
await page.waitForFunction(()=>window.__labelDuringOtherBookUpdate!==undefined);
assert.equal(await page.evaluate(()=>window.__labelDuringOtherBookUpdate),'Book 13','Another book heartbeat cannot change the selected workspace');
await page.locator('[data-open-writing-context]').click();
await page.waitForFunction(()=>!document.querySelector('[data-open-writing-context]').disabled);
assert.equal(context.pages().length,4,'Changing books opens a separately scoped Context window');
assert.equal(oldContext.url(),oldContextUrl,'The first book context is preserved');
const secondContext=context.pages().find(tab=>tab!==page&&!windows.includes(tab));
await secondContext.waitForLoadState();
assert.equal(new URL(secondContext.url()).searchParams.get('bookId'),'13');
await secondContext.close();
await page.evaluate(()=>document.dispatchEvent(new CustomEvent('plotdirector:story-position-changed',{detail:{projectId:7,bookId:12}})));
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-book]').textContent==='Book 12');
const beforeRestart=negotiations;
await page.evaluate(()=>window.__writerConnections.at(-1).stop());
await start.click();
await page.waitForFunction(()=>!document.querySelector('[data-start-writing-workspace]').disabled);
assert.ok(negotiations>beforeRestart,'A terminal disconnect permits a fresh connection');
assert.equal(context.pages().length,3,'Reapply reuses existing Context/Intent windows');
for(const popup of windows)await popup.close();
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-context]').textContent==='Not open');
await page.evaluate(()=>{window.__originalWindowOpen=window.open;window.open=()=>null;});
await page.getByRole('button',{name:'Open Context',exact:true}).click();
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-message]').textContent.includes('blocked'));
assert.equal(await page.getByRole('button',{name:'Open Context',exact:true}).isEnabled(),true);
await page.evaluate(()=>window.open=window.__originalWindowOpen);
await page.route('**/Locations?*',async route=>route.fulfill({response:await page.request.get(base+'/fixture?desktop=Locations')}));
for(let pass=0;pass<3;pass++){
await page.getByRole('tab',{name:'World',exact:true}).click();
await page.getByRole('link',{name:'Locations',exact:true}).first().click();
await page.waitForURL('**/Locations?*');
assert(await page.locator('.location-page').isVisible());
await page.getByRole('tab',{name:'Project',exact:true}).click();
await page.getByRole('link',{name:'Writer',exact:true}).first().click();
await page.waitForURL(url=>url.pathname==='/Writer');
await page.waitForFunction(()=>document.querySelector('[data-writing-workspace-word]').textContent!=='Checking...');
assert(await page.getByRole('button',{name:'Start / Reapply Workspace',exact:true}).isEnabled());
}
await page.evaluate(()=>{window.__screenDetails=window.getScreenDetails;Object.defineProperty(window,'getScreenDetails',{value:undefined,configurable:true});});
await page.getByRole('button',{name:'Detect displays',exact:true}).click();
await page.waitForFunction(()=>!document.querySelector('[data-detect-writing-displays]').disabled);
assert.match(await page.locator('[data-writing-workspace-message]').textContent(),/unavailable/);
const focus= pwa ? page.locator('[data-pwa-context-controls]').getByRole('button',{name:'Focus',exact:true}) : page.locator('.writer-dashboard-heading').getByRole('button',{name:'Focus',exact:true});
await focus.click();
await page.waitForURL(url=>url.pathname==='/Writer'&&url.searchParams.get('projectId')==='7');
for(const [name,route] of [['Writing Plans','WritingPlans'],['Schedule Setup','ScheduleSetup'],['Schedule Preview','SchedulePreview']]){
const host=pwa?page.locator('[data-pwa-context-controls]'):page.locator('.writer-dashboard-heading');
const link=host.getByRole('link',{name,exact:true,includeHidden:true});
const menu=link.locator('xpath=ancestor::details[@data-compact="true"]').last();
if(await menu.count()&&!(await menu.evaluate(node=>node.open)))await menu.locator(':scope > summary').click();
const response=page.waitForResponse(response=>response.request().isNavigationRequest()&&new URL(response.url()).pathname==='/Writer/'+route);
await link.click();assert.equal((await response).status(),200,name+' real controller/view route');
await page.goto(base+'/Writer');
}
assert.deepEqual(errors,[]);
await context.close();
}
console.log('PASS full-layout Writer browser/PWA negotiation recovery, terminal reconnect, actual Context/Intent windows, blocked pop-ups and repeated section navigation');
} finally {await browser.close();}
})().catch(error=>{console.error(error);process.exitCode=1;});