// Development only. All writes target this dedicated synthetic author's owned fixture project. const {chromium}=require('playwright'),fs=require('node:fs'),assert=require('node:assert/strict');const file=process.argv[2];if(!file?.startsWith('/tmp/pd-dev-browser-'))throw Error('Dedicated identity required');const identity=JSON.parse(fs.readFileSync(file));assert.equal(identity.Database,'PlotDirector_Development');assert(identity.Email.startsWith('pwa-browser-'));const f=identity.SpatialFixture;assert(f?.scenes?.length===3);const base='https://dev.plotdirector.com',out='/tmp/pd-spatial-evidence'; (async()=>{const browser=await chromium.launch();let step='login';try{const context=await browser.newContext({viewport:{width:1600,height:1050}}),page=await context.newPage(),errors=[],mutations=[];page.on('pageerror',e=>errors.push(e.message));page.on('request',r=>{if(r.url().includes('/SpatialContext/Mutate'))mutations.push(r.postDataJSON());});await page.goto(base+'/Account/Login');await page.locator('#Email').fill(identity.Email);await page.locator('#Password').fill(identity.Password);await Promise.all([page.waitForURL('**/Projects'),page.locator('form button[type=submit]').click()]);const scope=`projectId=${identity.ProjectID}&bookId=${identity.BookID}&sceneId=${f.scenes[1]}&pinned=true`;await page.goto(base+'/Writing/Context?'+scope);await page.selectOption('[data-context-pane="0"] [data-context-tab]','locations');const pane=i=>page.locator(`[data-context-pane="${i}"]`),shot=name=>page.screenshot({path:`${out}/development-${name}.png`});await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor();const token=await pane(0).locator('[name=__RequestVerificationToken]').inputValue();async function state(){const r=await page.request.get(base+`/SpatialContext/State?bookId=${identity.BookID}&sceneId=${f.scenes[1]}`);assert.equal(r.status(),200);return r.json();}async function mapState(){const r=await page.request.get(base+`/Maps/State?projectId=${identity.ProjectID}&id=${f.mapId}`);assert.equal(r.status(),200);return r.json();}async function waitState(test){for(let i=0;i<30;i++){const value=await state();if(test(value))return value;await page.waitForTimeout(100);}throw Error('Saved state did not reach expected value.');}async function undo(i){await pane(i).getByRole('button',{name:'Undo spatial change',exact:true}).click();}async function chooseLocation(location){const dialog=page.locator('dialog[open]').last();await dialog.locator(`[data-picker-id="${location}"] .pd-location-picker-name`).click();await dialog.getByRole('button',{name:'Choose',exact:true}).click();} console.log('STEP',step='authoritative sequence');let data=await state();assert.deepEqual(data.scenes.map(s=>s.sceneID),f.scenes);assert.equal(data.scenes[0].chapterID,f.chapters[0]);assert.equal(data.scenes[1].chapterID,f.chapters[1]);assert.equal(data.scope.primaryLocationID,f.locations[1]);const originalMap=await mapState(),originalFeature=JSON.stringify(originalMap.features[0]);await shot('locations'); console.log('STEP',step='explicit current-scene assignment while inspecting adjacent');await pane(0).locator('[data-scene-position="-1"] button').first().click();await pane(0).getByRole('heading',{name:'Lounge',exact:true}).waitFor();await pane(0).getByRole('button',{name:'Change current scene location',exact:true}).click();await chooseLocation(f.locations[3]);await waitState(x=>x.scope.primaryLocationID===f.locations[3]);assert.equal(mutations.at(-1).sceneID,f.scenes[1]);assert.equal(mutations.at(-1).locationID,f.locations[3]);await undo(0);await waitState(x=>x.scope.primaryLocationID===f.locations[1]);await pane(0).locator('[data-scene-position="0"] button').filter({hasText:'Bedroom'}).waitFor();await pane(0).locator('[data-scene-position="0"] button').first().click();await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor(); console.log('STEP',step='description and existing protected Undo');await pane(0).getByRole('button',{name:'Edit description',exact:true}).click();await pane(0).locator('textarea').fill('Spatial acceptance prose, saved exactly without AI.');await pane(0).getByRole('button',{name:'Save',exact:true}).click();await pane(0).getByText('Spatial acceptance prose, saved exactly without AI.',{exact:true}).waitFor();await undo(0);await waitState(x=>!x.locations.find(l=>l.locationID===f.locations[1]).description); console.log('STEP',step='rename, classification and canonical type with Undo');await pane(0).getByRole('button',{name:'Rename',exact:true}).click();await pane(0).locator('input[aria-label="name"]').fill('Bedroom renamed in Context');await pane(0).getByRole('button',{name:'Save',exact:true}).click();await pane(0).getByRole('heading',{name:'Bedroom renamed in Context',exact:true}).waitFor();await undo(0);await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor();await pane(0).getByRole('button',{name:'Classification',exact:true}).click();await pane(0).locator('[data-spatial-operation] select').selectOption('Fictional');await pane(0).getByRole('button',{name:'Save',exact:true}).click();await waitState(x=>x.locations.find(l=>l.locationID===f.locations[1]).classification==='Fictional');await undo(0);await waitState(x=>!x.locations.find(l=>l.locationID===f.locations[1]).classification);await pane(0).getByRole('button',{name:'Type',exact:true}).click();const typeDialog=page.locator('dialog[open]').last();await typeDialog.locator('input[type=search]').fill('City');await typeDialog.locator('.pd-location-picker-name').filter({hasText:/^City$/}).click();await typeDialog.getByRole('button',{name:'Choose type',exact:true}).click();await waitState(x=>x.locations.find(l=>l.locationID===f.locations[1]).locationTypeName==='City');await undo(0);await waitState(x=>x.locations.find(l=>l.locationID===f.locations[1]).locationTypeID===null); console.log('STEP',step='atomic create-and-assign and stale-create rollback');let beforeCreate=await state();let response=await page.request.post(base+'/SpatialContext/Create',{headers:{RequestVerificationToken:token},data:{bookID:identity.BookID,sceneID:f.scenes[1],name:'Stale atomic fixture must not remain',parentID:f.locations[0],expected:'2000-01-01T00:00:00'}});assert.equal(response.status(),409);const directoryResponse=await page.request.get(base+`/LocationWorkspace/Picker?projectId=${identity.ProjectID}`);assert(!(await directoryResponse.json()).locations.some(l=>l.name==='Stale atomic fixture must not remain'));response=await page.request.post(base+'/SpatialContext/Create',{headers:{RequestVerificationToken:token},data:{bookID:identity.BookID,sceneID:f.scenes[1],name:`Atomic spatial acceptance alcove ${Date.now()}`,parentID:f.locations[0],expected:beforeCreate.scope.version}});assert.equal(response.status(),200);const created=await response.json();await waitState(x=>x.scope.primaryLocationID===created.id);response=await page.request.post(base+'/SpatialContext/Undo',{headers:{RequestVerificationToken:token},data:{token:created.assignment.undoToken}});assert.equal(response.status(),200);await waitState(x=>x.scope.primaryLocationID===f.locations[1]);await pane(0).locator('[data-scene-position="0"] button').filter({hasText:'Bedroom'}).waitFor();await pane(0).locator('[data-scene-position="0"] button').first().click();await pane(0).getByRole('heading',{name:'Bedroom',exact:true}).waitFor(); console.log('STEP',step='map placement and Undo');const liveMap=await context.newPage();await liveMap.goto(base+`/Maps?projectId=${identity.ProjectID}&id=${f.mapId}`);await liveMap.waitForFunction(()=>!!window.PlotDirectorPresenceConnection&&!!window.PlotDirectorMapWorkspace);await page.bringToFront();await page.selectOption('[data-context-layout]','columns');await page.selectOption('[data-context-pane="1"] [data-context-tab]','maps');await pane(1).locator('iframe').waitFor();await page.waitForFunction(()=>document.querySelector('iframe')?.contentWindow?.PlotDirectorMapWorkspace?.document.features.length===1);const mapFrame=page.frames().find(frame=>frame.url().includes('/SpatialContext/Map'));await shot('locations-maps');await pane(1).getByRole('button',{name:'Place location',exact:true}).click();await pane(1).locator('[data-spatial-operation]').filter({hasText:'Place existing location: Bedroom'}).waitFor();await shot('placement');await mapFrame.locator('#mapsCanvas').click({position:{x:150,y:130}});await waitState(x=>x.maps.some(m=>m.locationID===f.locations[1]));await liveMap.waitForFunction(()=>PlotDirectorMapWorkspace.document.features.length===2);let saved=await mapState();assert.equal(saved.features.filter(x=>x.locationID===f.locations[1]).length,1);assert.equal(JSON.stringify(saved.features.find(x=>x.featureID===originalMap.features[0].featureID)),originalFeature);const marker=saved.features.find(x=>x.locationID===f.locations[1]);const main=await context.newPage();await main.goto(base+`/Maps?projectId=${identity.ProjectID}&id=${f.mapId}&featureId=${marker.featureID}`);await main.waitForFunction(id=>PlotDirectorMapWorkspace?.selected.includes(id),marker.featureID);await main.close();await undo(1);await waitState(x=>!x.maps.some(m=>m.locationID===f.locations[1]));assert.equal((await mapState()).features.length,1);await liveMap.waitForFunction(()=>PlotDirectorMapWorkspace.document.features.length===1);await liveMap.close(); console.log('STEP',step='room association and Undo');const livePlan=await context.newPage();await livePlan.goto(base+`/FloorPlans/Edit/${f.planId}`);await livePlan.waitForSelector('[data-floor-plan-initialized=true]');await page.bringToFront();await page.selectOption('[data-context-pane="1"] [data-context-tab]','floorplans');await pane(1).locator('[data-spatial-floor-canvas]').waitFor();const room=pane(1).locator(`[data-block][data-location-id="${f.locations[2]}"]`);const block=await room.getAttribute('data-block'),geometry=await room.getAttribute('style');await room.click();await pane(1).getByRole('button',{name:'Associate existing location',exact:true}).click();const picker=page.locator('dialog[open]').last();await picker.locator('input[type=search]').fill('Unmapped valley');await chooseLocation(f.locations[4]);await pane(1).getByRole('button',{name:'Confirm',exact:true}).waitFor();await shot('room-association');await pane(1).getByRole('button',{name:'Confirm',exact:true}).click();await pane(1).locator(`[data-block="${block}"][data-location-id="${f.locations[4]}"]`).waitFor();assert.equal(await pane(1).locator(`[data-block="${block}"]`).getAttribute('style'),geometry);await livePlan.locator(`[data-block="${block}"][data-location-id="${f.locations[4]}"]`).waitFor();data=await state();assert.equal(data.locations.find(l=>l.locationID===f.locations[4])?.parentLocationID??null,null);await undo(1);await pane(1).locator(`[data-block="${block}"][data-location-id="${f.locations[2]}"]`).waitFor();await livePlan.locator(`[data-block="${block}"][data-location-id="${f.locations[2]}"]`).waitFor();await livePlan.close();await shot('locations-floorplans'); console.log('STEP',step='live room labels retain viewport');const beforeLabel=await state(),labelLocation=beforeLabel.locations.find(l=>l.locationID===f.locations[2]);let labelResponse=await page.request.post(base+'/LocationWorkspace/Assign',{headers:{RequestVerificationToken:token},data:{projectId:identity.ProjectID,attribute:'name',changes:[{id:f.locations[2],value:'Lounge live label',version:labelLocation.updatedDate}]}});assert.equal(labelResponse.status(),200);const labelUndo=(await labelResponse.json()).undoToken;await pane(1).locator(`[data-block="${block}"] .floor-plan-block-label`).filter({hasText:'Lounge live label'}).waitFor();labelResponse=await page.request.post(base+'/LocationWorkspace/Undo',{headers:{RequestVerificationToken:token},data:{token:labelUndo}});assert.equal(labelResponse.status(),200);await pane(1).locator(`[data-block="${block}"] .floor-plan-block-label`).filter({hasText:/Lounge$/}).waitFor(); console.log('STEP',step='main workspaces remain available');const checks=[];const verification=await context.newPage();for(const route of [`/Locations?projectId=${identity.ProjectID}`,`/Characters?projectId=${identity.ProjectID}`,`/Names?projectId=${identity.ProjectID}`,`/RelationshipMap?projectId=${identity.ProjectID}`,`/Maps?projectId=${identity.ProjectID}&id=${f.mapId}`,`/FloorPlans/Edit/${f.planId}`,`/StoryAssets?projectId=${identity.ProjectID}`]){const response=await verification.goto(base+route);assert.equal(response.status(),200,route);checks.push(route.split('?')[0]);}await verification.close(); console.log('STEP',step='single SignalR in following window');const follow=await context.newPage();let connections=0;follow.on('request',r=>{if(r.url().includes('/hubs/native-companion/negotiate'))connections++;});await follow.goto(base+`/Writing/Context?projectId=${identity.ProjectID}&bookId=${identity.BookID}&sceneId=${f.scenes[1]}`);await follow.waitForFunction(()=>document.querySelector('[data-context-workspace]')?.contextController?.connection?.state==='Connected');await follow.selectOption('[data-context-pane="0"] [data-context-tab]','maps');await follow.selectOption('[data-context-layout]','columns');await follow.selectOption('[data-context-pane="1"] [data-context-tab]','floorplans');await follow.waitForTimeout(500);assert.equal(connections,1);await follow.selectOption('[data-context-pane="0"] [data-context-tab]','locations');await follow.locator('[data-spatial-details] h2').waitFor();await follow.locator('[data-shared-focus-hold]').click();await follow.waitForFunction(()=>PlotDirectorSharedFocus.held);const heldScene=await follow.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId);const heldResponse=await page.request.get(base+`/SpatialContext/State?bookId=${identity.BookID}&sceneId=${heldScene}`),heldData=await heldResponse.json(),heldLocation=heldData.locations.find(l=>l.locationID===heldData.scope.primaryLocationID);assert(heldLocation);const navigatorPage=await context.newPage();await navigatorPage.goto(base+`/Scenes/Edit/${f.scenes[1]}`);await navigatorPage.waitForFunction(()=>!!window.PlotDirectorSharedFocus);const navScene=heldScene===f.scenes[1]?f.scenes[2]:f.scenes[1];assert(await navigatorPage.evaluate(async p=>{if(PlotDirectorSharedFocus.held)await PlotDirectorSharedFocus.toggle();return await PlotDirectorSharedFocus.navigate(p);},{projectID:identity.ProjectID,bookID:identity.BookID,sceneID:navScene}));await follow.waitForFunction(id=>PlotDirectorSharedFocus.shared?.sceneID===id,navScene);assert.equal(await follow.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),heldScene);await page.request.post(base+'/LocationWorkspace/Assign',{headers:{RequestVerificationToken:token},data:{projectId:identity.ProjectID,attribute:'description',changes:[{id:heldLocation.locationID,value:'Held spatial acceptance detail',version:heldLocation.updatedDate}]}}).then(async r=>{assert.equal(r.status(),200);identity.HeldUndo=(await r.json()).undoToken;});await follow.getByText('Held spatial acceptance detail',{exact:true}).waitFor();assert.equal(await follow.evaluate(()=>document.querySelector('[data-context-workspace]').contextController.position.sceneId),heldScene);await follow.locator('[data-shared-focus-hold]').click();await follow.waitForFunction(()=>!PlotDirectorSharedFocus.held);await follow.waitForFunction(id=>document.querySelector('[data-context-workspace]').contextController.position.sceneId===id,navScene);await page.request.post(base+'/LocationWorkspace/Undo',{headers:{RequestVerificationToken:token},data:{token:identity.HeldUndo}});delete identity.HeldUndo;await navigatorPage.close();await follow.close();assert.deepEqual(errors,[]);fs.writeFileSync(`${out}/development-results.json`,JSON.stringify({passed:true,source:'authenticated Development',fixturesOnly:true,sceneSequence:f.scenes,checks,signalRConnections:connections,errors},null,2));console.log('PASS authenticated Development spatial sequence, targeted description/scene assignment, real protected Undo, map placement/reveal, room association, geometry preservation, main directories, one SignalR connection.');}catch(e){console.error('FAIL',step,e);process.exitCode=1;}finally{await browser.close();}})();