PlotDirector/PlotLine.Tests/Browser/native-integration-development.cjs

33 lines
12 KiB
JavaScript

// Explicit live Development test only. Run serially. --analyse opts into the configured paid AI provider on a short synthetic chapter. Provision/clean up with --dev-browser-identity; never use an author account.
const {chromium,request}=require('playwright');
const fs=require('fs'),assert=require('assert/strict'),crypto=require('crypto');
let step='initialise';const analyse=process.argv.includes('--analyse');
(async()=>{const identityPath=process.argv[2];assert.equal(process.platform,'linux');assert.ok(identityPath?.startsWith('/tmp/pd-dev-browser-'),'Explicit private Development fixture identity required');assert.equal(fs.statSync(identityPath).mode&0o077,0);const identity=JSON.parse(fs.readFileSync(identityPath,'utf8'));assert.equal(identity.Database,'PlotDirector_Development');assert.match(identity.Email,/^pwa-browser-[a-f0-9]+@example\.invalid$/);assert.ok(Number.isSafeInteger(identity.UserID)&&identity.UserID>0);const browser=await chromium.launch();let agent;try{
const context=await browser.newContext({viewport:{width:1400,height:1000}});await context.route('**/signalr.min.js',r=>r.fulfill({contentType:'application/javascript',body:fs.readFileSync(require.resolve('@microsoft/signalr/dist/browser/signalr.min.js'),'utf8')}));
const page=await context.newPage();const base='https://dev.plotdirector.com';step='normal login';await page.goto(base+'/Account/Login');await page.locator('input[name=Email]').fill(identity.Email);await page.locator('input[name=Password]').fill(identity.Password);await Promise.all([page.waitForURL(u=>u.pathname!='/Account/Login'),page.locator('form:has(input[name=Password]) button[type=submit]').click()]);
async function post(path,fields={}){const csrf=await page.locator('input[name=__RequestVerificationToken]').first().inputValue();const response=await context.request.post(base+path,{form:{...fields,__RequestVerificationToken:csrf}});assert.ok(response.ok(),`Form failed: ${path} HTTP ${response.status()}`);await page.goto(base+'/onboarding');}
step='isolated wizard project and book';await page.goto(base+'/onboarding');await post('/onboarding/start-import');await post('/onboarding/writing-journey',{WritingJourney:'AlreadyStarted'});await post('/onboarding/writing-software',{WritingSoftware:'MicrosoftWord'});const existingPanel=page.locator('[data-onboarding-scan-panel]');if(await existingPanel.count()===0){const projects=page.locator('input[name=SelectedProjectID]');if(analyse)assert.equal(await projects.count(),0,'AI smoke requires a fresh fixture identity, not a populated test book');await post('/onboarding/project',await projects.count()?{Mode:'Select',SelectedProjectID:await projects.first().inputValue()}:{Mode:'Create',ProjectName:'Native integration isolated verification'});const books=page.locator('input[name=SelectedBookID]');await post('/onboarding/book',await books.count()?{Mode:'Select',SelectedBookID:await books.first().inputValue()}:{Mode:'Create',BookTitle:'Native integration synthetic manuscript'});}
const bookId=Number(await page.locator('[data-onboarding-scan-panel]').getAttribute('data-book-id'));assert.ok(bookId>0,'Wizard did not create an authorised test book');
step='normal browser-approved desktop pairing';const verifier=crypto.randomBytes(32).toString('hex'),challenge=crypto.createHash('sha256').update(verifier).digest('hex').toUpperCase();const bare=await request.newContext({baseURL:base});let response=await bare.post('/api/native-companion/pair',{data:{challenge}});assert.ok(response.ok());const {code}=await response.json();const approval=await context.newPage();await approval.goto(base+'/native-companion/authorize?code='+encodeURIComponent(code));const csrf=await approval.locator('input[name=__RequestVerificationToken]').inputValue();response=await context.request.post(base+'/native-companion/authorize',{form:{code,__RequestVerificationToken:csrf}});assert.ok(response.ok());response=await bare.post('/api/native-companion/token',{data:{code,verifier}});assert.ok(response.ok());const {accessToken}=await response.json();assert.ok(accessToken);agent=await request.newContext({baseURL:base,extraHTTPHeaders:{Authorization:'Bearer '+accessToken}});await bare.dispose();await approval.close();
const instanceId=crypto.randomUUID(),sessionId=crypto.randomUUID(),manuscriptId=crypto.randomUUID();let sequence=0;const presence={bookId,manuscriptId,revision:1,active:true,wordAvailable:true,wordSaved:true,canCapture:true,documentTitle:'Synthetic native handoff verification'};
async function heartbeat(){const reply=await agent.post(`/api/native-companion/instances/${instanceId}/documents/${sessionId}/presence`,{data:{...presence,sequence:++sequence}});assert.ok(reply.ok(),'Presence rejected');return reply.json();}
step='live native registration and header';await heartbeat();await page.reload();await page.waitForFunction(()=>document.querySelector('#native-companion-status')?.dataset.connected==='true');assert.equal(await page.locator('#native-companion-status').count(),1);
const statuses=await(await context.request.get(base+'/native-companion/status')).json();assert.ok(statuses.some(s=>s.bookId===bookId&&s.sessionId===sessionId&&s.wordSaved===true));
step='existing wizard capture command';await page.locator('[data-onboarding-scan-start]').waitFor({state:'visible'});await page.waitForFunction(()=>!document.querySelector('[data-onboarding-scan-start]').disabled);await page.locator('[data-onboarding-scan-start]').click();let command;
for(let i=0;i<30&&!command;i++){await new Promise(r=>setTimeout(r,150));command=(await heartbeat()).navigation;}assert.equal(command?.kind,'wizard-capture');assert.equal(command.sessionId,sessionId);
const heading='Synthetic Chapter One\r',body=(analyse?'At dawn, a traveller reached the closed station and found a porter waiting beside the locked gate. The last train had gone during the night. A storm had damaged the road, and the traveller carried medicine intended for the village beyond the hills. The porter explained that the bridge was unsafe. He could offer a dry room and a place beside the fire, but he would not open the gate. The traveller set the parcel on the bench and asked whether anyone knew another way across. For a moment neither spoke. Rain tapped against the roof. Then the porter took an old map from his coat and pointed to a narrow crossing upstream. It would take most of the morning to reach it. He warned that the path was steep and offered to accompany the traveller as far as the river. The traveller accepted, divided the parcel between two bags, and helped the porter gather a rope and two lamps. Before leaving, they wrote a note for the next railway worker and fastened it to the office door. Their plan was uncertain, but they now had a route and a shared reason to attempt it.':'This is isolated synthetic manuscript prose. It must survive the native handoff exactly.')+'\r';const end=heading.length+body.length;
step='durable authenticated native intake';response=await agent.post('/api/native-companion/manuscript-capture',{data:{requestId:command.id,instanceId,sessionId,manuscriptId,revision:1,end,paragraphs:[{start:0,end:heading.length,paragraphIndex:1,outlineLevel:1,text:heading,completesParagraph:true,markerTags:[]},{start:heading.length,end,paragraphIndex:2,outlineLevel:10,text:body,completesParagraph:true,markerTags:[]}]}});assert.ok(response.ok(),'Capture was not accepted');assert.equal((await response.json()).captureRequestId,command.id);
await page.waitForURL(u=>u.pathname==='/onboarding/scan-review');assert.match(await page.locator('main').innerText(),/Synthetic Chapter One/);
step='review survives companion disconnection';response=await agent.delete(`/api/native-companion/instances/${instanceId}/documents/${sessionId}/presence?throughSequence=${sequence}`);assert.ok(response.ok());await page.reload();assert.match(await page.locator('main').innerText(),/Synthetic Chapter One/);assert.deepEqual(await(await context.request.get(base+'/native-companion/status')).json(),[]);
fs.writeFileSync('/tmp/native-integration-live-check.sql',`IF DB_NAME()<>N'PlotDirector_Development' THROW 51000,'Wrong database',1;\nIF NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptCaptures WHERE UserID=${identity.UserID} AND PreviewID='${command.id}' AND JSON_VALUE(Payload,'$.Chapters[0].ChapterText')=N'${body.replaceAll("'","''")}') THROW 51000,'Durable native source mismatch',1;\nPRINT 'PASS live wizard capture persisted exact synthetic prose in Development';\n`,{mode:0o600});
if(analyse){
step='explicit existing server analysis with Word disconnected';await page.getByRole('button',{name:'Continue to Scene Detection',exact:true}).click();await page.waitForURL(u=>u.pathname==='/onboarding');await page.waitForFunction(()=>{const b=document.querySelector('[data-onboarding-build-start]');return b&&!b.disabled;});await page.locator('[data-onboarding-build-start]').click();await page.waitForURL(u=>u.pathname==='/onboarding/build-complete',{timeout:240000});assert.match(await page.locator('main').innerText(),/Scene structure has been detected/);
presence.cursorStart=heading.length+1;const mapped=await heartbeat();assert.ok(mapped.sceneId>0&&mapped.chapterId>0,'Approved source did not resolve a trustworthy saved scene');await agent.delete(`/api/native-companion/instances/${instanceId}/documents/${sessionId}/presence?throughSequence=${sequence}`);
fs.appendFileSync('/tmp/native-integration-live-check.sql',`IF NOT EXISTS(SELECT 1 FROM dbo.OnboardingManuscriptBuilds WHERE UserID=${identity.UserID} AND PreviewID='${command.id}' AND Status=N'Complete' AND MarkerStatus=N'NotRequested' AND ScenesCreated>0) THROW 51000,'Native server build did not complete independently',1;\nIF NOT EXISTS(SELECT 1 FROM dbo.SceneManuscriptSources WHERE BookID=${bookId} AND HASHBYTES('SHA2_256',LTRIM(RTRIM(REPLACE(SourceText,CHAR(13),N''))))=0x${crypto.createHash('sha256').update(Buffer.from(body.trim(),'utf16le')).digest('hex')}) THROW 51000,'Canonical manuscript prose differs from the accepted source',1;\nPRINT 'PASS actual existing AI scene analysis completed after Word disconnection; canonical prose retained and trusted scene mapping resolved';\n`);
}
step='real dedicated Context and Intent windows';await page.goto(base+'/native-companion/workspace?bookId='+bookId);const opened=[];context.on('page',p=>opened.push(p));await page.locator('[data-native-open-role=Context]').click();await page.waitForTimeout(700);await page.locator('[data-native-open-role=Intent]').click();await page.waitForTimeout(700);await page.locator('[data-native-open-role=Context]').click();await page.locator('[data-native-open-role=Intent]').click();await page.waitForTimeout(400);assert.equal(opened.length,2,'Repeated launches created duplicate windows');
for(const popup of opened){await popup.waitForSelector('#native-workspace');assert.equal(await popup.locator('.pd-ribbon,.pd-titlebar').count(),0,'Dedicated window contains application chrome');await popup.waitForSelector('#native-story-workspace',{state:'visible'});assert.ok((await popup.locator('#native-story-workspace').boundingBox()).height>=250);assert.match(await popup.locator('#native-presence-status').innerText(),/disconnected|unavailable/);}
console.log('PASS live Development: normal account/wizard/book creation, browser-approved sign-in, exact native registration/header, wizard capture routing, durable intake, disconnected chapter review, and two reused chrome-free Context/Intent windows. '+(analyse?'Synthetic source only; explicit existing AI scene analysis and scene mapping verified; run the generated SQL probe for canonical prose integrity.':'Synthetic source only; no AI request or canonical import.'));
}finally{if(agent)await agent.dispose();await browser.close();}
})().catch(error=>{fs.writeFileSync('/tmp/native-integration-development-smoke-error.txt',String(error.stack),{mode:0o600});console.error('FAIL Development smoke at '+step+'; private diagnostic recorded.');process.exit(1);});