const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path');const base=process.env.PD_BROWSER_BASE||'http://127.0.0.1:5238'; (async()=>{const b=await chromium.launch();let step='setup';try{const c=await b.newContext({viewport:{width:1280,height:900}});await c.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'))}));for(const url of ['**/native-companion/status','**/native-companion/connection-state','**/Writing/Context/Position?*'])await c.route(url,r=>r.fulfill({json:url.endsWith('status')?[]:{known:false,connected:false}}));await c.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})});}); await c.route('**/Writing/Context/EditCharacter?*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-edit-fixture?field='+u.searchParams.get('field')})});});await c.route('**/Writing/Context/EditRelationship?*',async r=>r.fulfill({response:await r.fetch({url:base+'/context-relationship-edit-fixture'})})); await c.route('**/Writing/Context/Relationships/Graph?*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-lenses-fixture'+u.search})});});for(const [route,fixture] of [['FamilyIndex','index'],['FamilyTree','tree']])await c.route('**/Writing/Context/Relationships/'+route+'?*',async r=>{const u=new URL(r.request().url());await r.fulfill({response:await r.fetch({url:base+'/context-family-'+fixture+'-fixture'+u.search})});});const p=await c.newPage(),errors=[];p.on('pageerror',e=>errors.push(e.message));await p.goto(base+'/Writing/Context');await p.selectOption('[data-context-tab]','characters');await p.waitForSelector('[data-character-explorer]'); step='all shared modal forms fill content';for(const width of [1280,390]){await p.setViewportSize({width,height:900});for(const field of ['life-status','classification','description','emotion','condition','location','name','alias-add','alias:11']){await p.evaluate(field=>{const host=document.querySelector('[data-character-explorer]'),button=document.createElement('button');button.dataset.contextEdit=field;button.dataset.characterId='5';host.append(button);button.click();button.remove();},field);await p.waitForSelector('[data-context-edit-form]');assert.equal(await p.locator('[data-context-edit-dialog] button:visible').count(),2);assert(await p.locator('[data-context-edit-form]').evaluate(f=>[...f.querySelectorAll('textarea,select,input:not([type=hidden]):not([type=checkbox])')].every(n=>n.getBoundingClientRect().width>=f.clientWidth*.92&&n.scrollWidth<=n.clientWidth+2)));await p.keyboard.press('Escape');await p.waitForFunction(()=>!document.querySelector('[data-context-edit-dialog]').open);}} step='relationship modal shares full-width layout';await p.selectOption('[data-context-tab]','relationships');await p.waitForSelector('[data-context-relationships]');await p.locator('[data-graph-node="5"]').click();await p.locator('[data-relationship-details] details summary').click();await p.locator('[data-inspect-connection="10"]').click();await p.locator('[data-relationship-details] [data-context-relationship-edit]').click();await p.waitForSelector('[data-context-edit-form]');assert(await p.locator('[data-context-edit-form]').evaluate(f=>[...f.querySelectorAll('textarea,select,input:not([type=hidden]):not([type=checkbox])')].every(n=>n.getBoundingClientRect().width>=f.clientWidth*.92)));assert.equal(await p.locator('[data-context-edit-dialog] button:visible').count(),2);await p.keyboard.press('Escape');await p.selectOption('[data-context-tab]','characters');await p.waitForSelector('[data-character-explorer]'); step='main shell registers on existing native connection';const main=await c.newPage();let hubs=0;main.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))hubs++;});await main.goto(base+'/fixture?layout=full');await p.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',12).then(rows=>rows.some(r=>r.kind==='main')));assert.equal(hubs,1); step='scene editor reuses main window with no popup';const originalPages=c.pages().length;await p.click('[data-context-editor]');await main.waitForURL(/\/Scenes\/Edit\/22/);assert.equal(c.pages().length,originalPages);assert.equal(await p.locator('[data-context-tab]').first().inputValue(),'characters'); step='repeat navigation retains one main window';await p.waitForTimeout(550);await main.waitForFunction(()=>window.PlotDirectorPresenceConnection?.state==='Connected');await p.waitForFunction(()=>document.querySelector('[data-context-workspace]').contextController.connection.invoke('MyContextWindows',12).then(rows=>rows.some(r=>r.kind==='main')));await p.click('[data-context-editor]');await p.waitForTimeout(700);assert.equal(c.pages().length,originalPages); step='unsaved main form can decline navigation';await main.waitForTimeout(500);const beforeDirty=main.url();await main.evaluate(()=>{const f=document.createElement('form');f.method='post';f.innerHTML='';document.body.append(f);});await main.locator('[name=SyntheticDraft]').fill('Unsaved draft');main.once('dialog',d=>d.dismiss());await p.waitForTimeout(550);await p.locator('a[href="/Characters?projectId=7"]').click();await p.waitForTimeout(700);assert.equal(main.url(),beforeDirty);assert.equal(c.pages().length,originalPages); step='missing main opens only one named fallback';await main.close();const popupPromise=p.waitForEvent('popup');await p.waitForTimeout(550);await p.locator('a[href="/Characters?projectId=7"]').click();const popup=await popupPromise;await popup.waitForURL(/Characters\?projectId=7/);await popup.waitForFunction(()=>window.PlotDirectorPresenceConnection?.state==='Connected',{},{timeout:7000}).catch(async e=>{const info=await popup.evaluate(()=>({user:document.body.dataset.pdUserId,books:document.body.dataset.pdBookIds,env:window.PlotDirectorContextEnvironment,state:window.PlotDirectorPresenceConnection?.state,ready:document.readyState,title:document.title}));throw Error(e.message+JSON.stringify(info));});await p.waitForTimeout(550);await p.locator('a[href="/Characters?projectId=7"]').click();await p.waitForTimeout(600);assert.equal(c.pages().length,originalPages); assert.deepEqual(errors,[]);console.log('PASS shared Context refinement: all nine character/name modal variants full-width at desktop/mobile, one Save/Cancel, Escape; real registry/main shell reuses native connection and existing main window, repeated navigation creates no popup.'); } catch(e){console.error('FAILED '+step+': '+e.stack);process.exitCode=1;}finally{await b.close();}})();