50 lines
18 KiB
JavaScript
50 lines
18 KiB
JavaScript
// Real authenticated Development database + SignalR acceptance; synthetic fixture only.
|
|
const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');
|
|
const base=process.env.PD_SHARED_FOCUS_URL||'http://127.0.0.1:5258';
|
|
(async()=>{
|
|
const who=JSON.parse(fs.readFileSync(process.env.PD_CONTEXT_IDENTITY)),s=JSON.parse(fs.readFileSync('/tmp/shared-focus-browser-scope.json'));
|
|
assert.equal(who.Database,'PlotDirector_Development');assert.equal(who.UserID,s.user);assert(who.Email.startsWith('pwa-browser-'));
|
|
const installed=process.argv.includes('--installed');const profile=installed?fs.mkdtempSync('/tmp/pd-shared-focus-pwa-'):null;const persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1500,height:1000}}):null;const browser=persistent?.browser()||await chromium.launch();let step='login';const errors=[];
|
|
try{
|
|
const c=persistent||await browser.newContext({viewport:{width:1500,height:1000}});
|
|
await c.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')}));
|
|
await c.addInitScript(user=>{try{localStorage.setItem('plotdirector.desktop.v1.'+user,JSON.stringify({dismissedAt:Date.now()}));}catch{}},who.UserID);
|
|
const sockets=new WeakMap();let wordCommands=0;c.on('request',r=>{if(/\/(WriterWord|Writing\/Context)\/Navigate/.test(new URL(r.url()).pathname))wordCommands++;});c.on('page',p=>{const rows=[];sockets.set(p,rows);p.on('websocket',socket=>{const row={url:socket.url(),closed:false};rows.push(row);socket.on('close',()=>row.closed=true);});p.on('pageerror',e=>{errors.push(e.message);console.error('Browser error: '+e.message);});});
|
|
const login=await c.newPage();await login.goto(base+'/Account/Login');await login.locator('[name=Email]').fill(who.Email);await login.locator('[name=Password]').fill(who.Password);await Promise.all([login.waitForURL(u=>u.pathname!='/Account/Login'),login.locator('button[type=submit]').click()]);
|
|
let desktop;if(installed){await login.goto(`${base}/Projects/Details/${s.project}`);desktop=await browser.newBrowserCDPSession();await desktop.send('PWA.install',{manifestId:base+'/Projects',installUrlOrBundleUrl:`${base}/Projects/Details/${s.project}`});await desktop.send('PWA.changeAppUserSettings',{manifestId:base+'/Projects',displayMode:'standalone'});}
|
|
async function surface(url){if(!installed){const p=await c.newPage();await p.goto(url);return p;}const opened=c.waitForEvent('page');await desktop.send('PWA.launch',{manifestId:base+'/Projects',url});const p=await opened;await p.waitForLoadState();assert(await p.evaluate(()=>matchMedia('(display-mode: standalone)').matches));return p;}
|
|
const contextURL=`${base}/Writing/Context?projectId=${s.project}&bookId=${s.book}&sceneId=${s.scene1}`;
|
|
const ready=async p=>{await p.waitForFunction(()=>window.PlotDirectorSharedFocus&&document.querySelector('[data-context-workspace]')?.contextController?.connection?.state==='Connected');await p.waitForSelector('[data-context-tab-fragment]');};
|
|
const scene=async(p,id)=>p.waitForFunction(id=>document.querySelector('[data-context-workspace]').contextController.position.sceneId===id,id);
|
|
const current=p=>p.evaluate(()=>window.PlotDirectorSharedFocus.shared);
|
|
const a=await surface(contextURL);await ready(a);
|
|
step='Context alone publishes without Word';await a.selectOption('[data-context-scene]',String(s.scene2));await a.waitForFunction(id=>window.PlotDirectorSharedFocus.shared?.sceneID===id,s.scene2);await a.selectOption('[data-context-scene]',String(s.scene1));await a.waitForFunction(id=>window.PlotDirectorSharedFocus.shared?.sceneID===id,s.scene1);
|
|
await a.click('[data-shared-focus-hold]');await a.selectOption('[data-context-scene]',String(s.scene2));await scene(a,s.scene2);assert.equal((await current(a)).sceneID,s.scene1);
|
|
const b=await surface(contextURL);await ready(b);await scene(b,s.scene1);assert.equal(await b.evaluate(()=>PlotDirectorSharedFocus.held),false);
|
|
assert.notEqual(await a.evaluate(()=>PlotDirectorSharedFocus.windowID),await b.evaluate(()=>PlotDirectorSharedFocus.windowID));
|
|
await a.waitForTimeout(450);let heldFocusFetches=0;a.on('request',r=>{if(new URL(r.url()).pathname.startsWith('/Writing/Context/Tabs/'))heldFocusFetches++;});step='Review alone/Context paragraph publication';const review=await surface(`${base}/Writer/Review?projectId=${s.project}&bookId=${s.book}&chapterId=${s.chapter1}`);await review.waitForFunction(()=>window.PlotDirectorSharedFocus?.shared?.chapterID);await review.waitForSelector(`.manuscript-reader [data-paragraph-id="${s.paragraph2}"]`);
|
|
const before=(await current(review)).version;await review.mouse.wheel(0,200);await review.waitForTimeout(300);assert.equal((await current(review)).version,before,'scroll is local');
|
|
await review.locator(`.manuscript-reader [data-paragraph-id="${s.paragraph2}"]`).click();await scene(b,s.scene2);await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);await review.waitForFunction(p=>PlotDirectorSharedFocus.shared.paragraphID===p,s.paragraph2);
|
|
step='Next crosses chapters without Word';await b.locator('[data-context-next]').click();await scene(b,s.scene3);await review.waitForSelector(`.manuscript-reader [data-paragraph-id="${s.paragraph3}"]`);await scene(a,s.scene2);
|
|
assert.equal(heldFocusFetches,0,'shared focus alone does not refetch a held pane');await b.click('[data-context-previous]');await scene(b,s.scene2);await b.click('[data-context-next]');await scene(b,s.scene3);const latest=(await current(b)).version;await a.click('[data-context-go-focus]');await scene(a,s.scene3);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);assert.equal((await current(a)).version,latest);await a.selectOption('[data-context-scene]',String(s.scene2));await scene(a,s.scene2);await a.reload();await ready(a);await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);
|
|
step='release catches latest without publishing';await a.click('[data-shared-focus-hold]');await scene(a,s.scene3);assert.equal((await current(a)).version,latest);assert.equal((await current(b)).version,latest);
|
|
step='held Review local navigation';await review.locator('[data-shared-focus-hold]:visible').first().click();await review.evaluate(s=>PlotDirectorSharedFocus.navigate({chapterID:s.chapter1,paragraphID:s.paragraph1}),s);await review.waitForSelector(`.manuscript-reader [data-paragraph-id="${s.paragraph1}"]`);assert.equal((await current(review)).version,latest);await scene(b,s.scene3);await review.evaluate(()=>{const r=document.querySelector('.manuscript-reader'),resolve=r.readerResolveFocus,locate=r.readerLocateFocus;window.__heldFallbackMoves=0;r.readerResolveFocus=()=>({paragraph:r.querySelector('[data-paragraph-id]'),precise:false});r.readerLocateFocus=(...args)=>{window.__heldFallbackMoves++;return locate(...args);};window.__restoreHeldReader=()=>{r.readerResolveFocus=resolve;r.readerLocateFocus=locate;};document.dispatchEvent(new Event('reader:updated'));});await review.waitForFunction(()=>/held reference no longer/.test(document.querySelector('[data-review-focus-notice]').textContent));await review.waitForTimeout(120);assert.equal(await review.evaluate(()=>window.__heldFallbackMoves),0,'a missing held accepted passage cannot trigger fallback navigation');console.log('PASS held Review missing accepted-passage resolver: no fallback navigation or retarget.');await review.evaluate(()=>window.__restoreHeldReader());await review.locator('[data-shared-focus-hold]:visible').first().click();await review.waitForSelector(`.manuscript-reader [data-paragraph-id="${s.paragraph3}"]`);
|
|
step='rapid navigation serializes latest intent';await b.evaluate(async s=>{void PlotDirectorSharedFocus.navigate({sceneID:s.scene1});void PlotDirectorSharedFocus.navigate({sceneID:s.scene2});void PlotDirectorSharedFocus.navigate({sceneID:s.scene3});},s);await b.waitForFunction(s=>PlotDirectorSharedFocus.shared.sceneID===s.scene3&&PlotDirectorSharedFocus.shared.version>0,s);await b.waitForTimeout(700);assert.equal((await current(b)).sceneID,s.scene3);
|
|
step='duplicate/delayed events cannot overwrite';const stable=await current(b);await b.evaluate(p=>{const conn=document.querySelector('[data-context-workspace]').contextController.connection;const handlers=Object.values(conn).find(v=>Array.isArray(v?.manuscriptfocuschanged))?.manuscriptfocuschanged;if(!handlers)throw Error('Focus receiver was not registered');for(const handler of handlers)handler({...p,version:p.version-1,sceneID:1});},stable);assert.equal((await current(b)).sceneID,s.scene3);
|
|
step='held cross-scene relationship invalidation in split panes';await a.click('[data-shared-focus-hold]');await a.selectOption('[data-context-scene]',String(s.scene2));await scene(a,s.scene2);await a.selectOption('[data-context-layout]','columns');await a.selectOption('[data-context-pane="0"] [data-context-tab]','relationships');await a.selectOption('[data-context-pane="1"] [data-context-tab]','characters');await a.waitForSelector('[data-context-pane="0"] [data-context-tab-fragment]');await a.waitForSelector('[data-context-pane="1"] [data-context-tab-fragment]');
|
|
await a.click('[data-relationship-lens=story]');await a.waitForTimeout(400);let graphAfter=null;let invalidated=0,refreshed=new Set();a.on('response',async r=>{const u=new URL(r.url());if(u.pathname==='/Writing/Context/Relationships/Graph'&&r.ok())graphAfter=await r.json().catch(()=>null);if(u.pathname.startsWith('/Writing/Context/Tabs/')){invalidated++;refreshed.add(u.pathname);}});
|
|
const edit=await surface(`${base}/Characters/Workspace/Operation/${s.character1}?relationshipId=${s.relationship}&eventId=${s.relationshipEvent}&operation=event-edit`);const changeNote='Changed earlier-scene fixture '+Date.now();await edit.locator('[name=Notes]').fill(changeNote);await edit.locator('[name=Intensity]').fill('8');
|
|
const saved=await edit.evaluate(async()=>{const form=document.querySelector('form');const response=await fetch(form.action,{method:'POST',body:new FormData(form)});return {status:response.status,text:await response.text()};});assert.equal(saved.status,200,saved.text.slice(0,200));assert.match(saved.text,/saved/);
|
|
await a.waitForFunction(()=>window.PlotDirectorSharedFocus.held===true);await a.waitForTimeout(1800);assert(refreshed.has('/Writing/Context/Tabs/relationships')&&refreshed.has('/Writing/Context/Tabs/characters'),'both affected visible panes refreshed');assert.equal(graphAfter?.links?.find(l=>l.id===s.relationship)?.notes,changeNote,'held later-scene graph contains the new earlier-scene note');await scene(a,s.scene2);assert.equal((await current(a)).sceneID,s.scene3);
|
|
step='reconnect catches current shared reference';await b.evaluate(async()=>{const c=document.querySelector('[data-context-workspace]').contextController.connection;await c.stop();await c.start();await PlotDirectorSharedFocus.refresh(true);});await scene(b,s.scene3);
|
|
step='new window does not inherit Hold';const fresh=await surface(contextURL);await ready(fresh);await scene(fresh,s.scene3);assert.equal(await fresh.evaluate(()=>PlotDirectorSharedFocus.held),false);
|
|
if(s.emptyChapter){step='chapter-only and empty-chapter toolbar boundaries';const command=async name=>{const menu=review.locator('.pd-ribbon-panel:not([hidden]) .pd-ribbon-focus details[data-compact=true]');if(await menu.count()&&!await menu.evaluate(n=>n.open))await menu.locator('summary').click();await review.locator('.pd-ribbon-panel:not([hidden]) [data-global-focus='+name+']').click();await review.waitForFunction(()=>document.querySelector('.pd-ribbon-panel:not([hidden]) [data-global-focus=previous]')?.disabled===false);};await review.evaluate(s=>PlotDirectorNarrativeFocus.set({chapterID:s.chapter2}),s);await review.waitForFunction(s=>PlotDirectorSharedFocus.local.chapterID===s.chapter2&&!PlotDirectorSharedFocus.local.sceneID,s);await command('next');await scene(b,s.scene3);await review.evaluate(s=>PlotDirectorNarrativeFocus.set({chapterID:s.emptyChapter}),s);await review.waitForFunction(s=>document.querySelector('.manuscript-reader').dataset.chapterId===String(s.emptyChapter),s);await command('next');await scene(b,s.scene3);await review.evaluate(s=>PlotDirectorNarrativeFocus.set({chapterID:s.emptyChapter}),s);await review.waitForFunction(s=>document.querySelector('.manuscript-reader').dataset.chapterId===String(s.emptyChapter),s);await command('previous');await scene(b,s.scene2);await scene(a,s.scene2);await review.evaluate(s=>PlotDirectorNarrativeFocus.set({chapterID:s.chapter2,sceneID:s.scene3}),s);await scene(b,s.scene3);console.log('PASS actual Review toolbar: chapter-only Next stays in its own chapter; empty-chapter Previous/Next reaches the canonical neighbor without moving held Context.');}
|
|
step='duplicated session state cannot inherit Hold';const clone=await c.newPage();const storage=await a.evaluate(()=>Object.fromEntries(Object.entries(sessionStorage).filter(([k])=>k.startsWith('pd.shared-focus')||k==='plotdirector.context.window.v1')));await clone.addInitScript(values=>{for(const[k,v]of Object.entries(values))sessionStorage.setItem(k,v);},storage);await clone.goto(contextURL);await ready(clone);await clone.waitForFunction(id=>!PlotDirectorSharedFocus.held&&PlotDirectorSharedFocus.windowID!==id,await a.evaluate(()=>PlotDirectorSharedFocus.windowID));await scene(clone,s.scene3);
|
|
step='hidden affected cached tab is fetched when activated';const beforeHidden=invalidated;await a.selectOption('[data-context-pane="0"] [data-context-tab]','overview');await a.waitForTimeout(600);assert(invalidated>beforeHidden);await scene(a,s.scene2);
|
|
step='responsive Hold control';for(const width of[1500,760,390]){await a.setViewportSize({width,height:900});assert(await a.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+2),'Context overflow at '+width);}await a.setViewportSize({width:1500,height:1000});
|
|
if(process.argv.includes('--restart')){step='actual server restart recovery';const revision=(await current(b)).version;await b.evaluate(()=>{const root=document.querySelector('[data-context-workspace]');root.contextController.connection.onreconnected(()=>window.__sharedFocusRestartRecovered=true);root.addEventListener('context-connection-ready',()=>window.__sharedFocusRestartRecovered=true,{once:true});});fs.writeFileSync('/tmp/shared-focus-restart-ready','ready');await b.waitForFunction(()=>window.__sharedFocusRestartRecovered,null,{timeout:55000});await scene(b,s.scene3);await a.waitForFunction(()=>[...document.querySelectorAll('[data-shared-focus-status]')].some(n=>/no longer valid/.test(n.textContent)));await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);assert.equal((await current(b)).version,revision);await a.selectOption('[data-context-scene]',String(s.scene1));await scene(a,s.scene1);assert.equal((await current(a)).version,revision);console.log('PASS actual loopback server restart: latest focus persisted, SignalR reconnected, held scene retained and an offline structural change was validated without redirect.');}
|
|
if(process.argv.includes('--structure')){step='structural archive retains held reference';const result=await edit.evaluate(async s=>{const token=document.querySelector('[name=__RequestVerificationToken]').value;const response=await fetch('/Scenes/Archive',{method:'POST',body:new URLSearchParams({id:s.scene2,chapterId:s.chapter1,__RequestVerificationToken:token})});return response.status;},s);assert.equal(result,200);await a.waitForFunction(()=>[...document.querySelectorAll('[data-shared-focus-status]')].some(n=>/no longer valid/.test(n.textContent)));await scene(a,s.scene2);assert.equal(await a.evaluate(()=>PlotDirectorSharedFocus.held),true);await a.selectOption('[data-context-scene]',String(s.scene1));await scene(a,s.scene1);assert.equal((await current(a)).sceneID,s.scene3);const version=(await current(a)).version;const archived=await edit.evaluate(async s=>{const token=document.querySelector('[name=__RequestVerificationToken]').value;return(await fetch('/Scenes/Archive',{method:'POST',body:new URLSearchParams({id:s.scene3,chapterId:s.chapter2,__RequestVerificationToken:token})})).status;},s);assert.equal(archived,200);await a.evaluate(()=>PlotDirectorSharedFocus.refresh());assert.equal((await current(a)).isValid,false);await a.evaluate(()=>{const conn=document.querySelector('[data-context-workspace]').contextController.connection;const handlers=Object.values(conn).find(v=>Array.isArray(v?.manuscriptfocuschanged))?.manuscriptfocuschanged;for(const handler of handlers||[])handler({...PlotDirectorSharedFocus.shared,isValid:true});});assert.equal((await current(a)).isValid,false,'duplicate focus packets cannot undo authoritative same-revision invalidity');await a.click('[data-shared-focus-hold]');await a.waitForFunction(()=>!PlotDirectorSharedFocus.held);await scene(a,s.scene1);assert.equal((await current(a)).version,version);assert.equal((await current(a)).isValid,false,'same-revision invalidity must replace cached validity before Release');await b.selectOption('[data-context-scene]',String(s.scene1));await b.waitForFunction(s=>PlotDirectorSharedFocus.shared.sceneID===s.scene1&&PlotDirectorSharedFocus.shared.isValid,s);console.log('PASS structural safety: local invalid reference retained; Release rejects an invalid shared point even at the same revision, retains valid local position, and does not publish.');}
|
|
assert.equal(wordCommands,0,'shared navigation never depends on or automatically invokes Word navigation');for(const p of[a,b,fresh,clone])assert.equal(sockets.get(p).filter(s=>!s.closed&&s.url.includes('/hubs/native-companion')).length,1,'one existing SignalR connection per Context window');assert.deepEqual(errors,[]);console.log('PASS real authenticated browser + SQL + SignalR: Context alone, Review↔Context without Word, scroll local, exact paragraphs/chapter crossing, per-window Hold, refresh/release, rapid/obsolete ordering, cross-scene relationship save refreshes both held panes, reconnect, new/duplicated-window isolation, Previous/Go without Word, hidden tabs and responsive Hold.');
|
|
}catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await persistent?.close();await browser.close();if(profile)fs.rmSync(profile,{recursive:true,force:true});}
|
|
})();
|