PlotDirector/PlotLine.Tests/Browser/ai-allowances.cjs

21 lines
5.2 KiB
JavaScript

// Actual compiled character ribbon, shared confirmation dialog, allowance and admin views; no provider calls.
const {chromium}=require('playwright'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
(async()=>{const installed=process.argv.includes('--installed'),base='http://127.0.0.1:5238',manifestId=base+'/Projects',profile=installed?fs.mkdtempSync(path.join(os.tmpdir(),'pd-ai-pwa-')):null,persistent=installed?await chromium.launchPersistentContext(profile,{headless:false,viewport:{width:1920,height:1080}}):null,browser=installed?persistent.browser():await chromium.launch(),cdp=installed?await browser.newBrowserCDPSession():null;
try{
let page;if(installed){await persistent.pages()[0].goto(base+'/fixture?page=calendar-test');await cdp.send('PWA.install',{manifestId,installUrlOrBundleUrl:base+'/fixture?page=calendar-test'});await cdp.send('PWA.changeAppUserSettings',{manifestId,displayMode:'standalone'});const opened=persistent.waitForEvent('page');await cdp.send('PWA.launch',{manifestId,url:base+'/fixture?page=calendar-test'});page=await opened;await page.waitForLoadState();assert(await page.evaluate(()=>matchMedia('(display-mode: standalone)').matches));}else page=await browser.newPage({viewport:{width:1920,height:1080}});
await page.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'))}));
const errors=[];page.on('pageerror',error=>errors.push(error.message));let allowed=false,posts=[];
await page.route('**/SharedFocus/**',r=>r.fulfill({json:{success:true}}));
await page.route('**/Ai/Quote?*',r=>r.fulfill({json:{allowed,entitled:allowed,name:'Regenerate character biography',cost:10,remaining:100,renewal:'2026-12-01T00:00:00Z',message:allowed?'':'This operation requires an AI-enabled subscription.',upgradeUrl:'/ManageAccount/Subscription'}}));
await page.route('**/Characters/Reanalyse**',r=>{posts.push(r.request().postData());return r.fulfill({json:{success:true,characterID:5,characterEnrichmentRunID:777,status:'Queued',bookID:12,currentMessage:'Synthetic analysis queued'}});});
await page.goto(base+'/character-workspace-fixture');await page.locator('[data-character-reanalyse-button]').waitFor({state:'attached'});
async function open(){await page.locator('[data-character-ribbon] .dropdown-toggle').click();await page.locator('[data-character-reanalyse-button]').click();await page.locator('.pd-ai-confirm').waitFor();}
fs.mkdirSync('/tmp/pd-ai-allowances',{recursive:true});await open();assert((await page.locator('.pd-ai-confirm').innerText()).includes('requires an AI-enabled subscription'));assert.equal(await page.locator('.pd-ai-confirm a').getAttribute('href'),'/ManageAccount/Subscription');assert.equal(posts.length,0);await page.screenshot({path:`/tmp/pd-ai-allowances/${installed?'pwa':'browser'}-restriction.png`});await page.keyboard.press('Escape');await page.locator('.pd-ai-confirm').waitFor({state:'detached'});
allowed=true;await open();assert((await page.locator('.pd-ai-confirm').innerText()).includes('10 AI credits'));await page.getByRole('button',{name:'Cancel',exact:true}).click();assert.equal(posts.length,0);await open();await page.getByRole('button',{name:'Continue · 10 credits',exact:true}).click();await page.waitForFunction(()=>document.querySelector('[data-character-analysis-status]')?.textContent==='Queued');assert.equal(posts.length,1);assert.match(posts[0],/name="expectedCredits"\r\n\r\n10/);assert.match(posts[0],/name="requestID"\r\n\r\n[a-f0-9-]{36}/i);assert(posts[0].includes('__RequestVerificationToken'));
await page.goto(base+'/ai-policy-fixture/admin');assert.equal(await page.locator('form input[name=Action][value=Operation]').count(),1);assert((await page.locator('body').innerText()).includes('Unrecorded'));assert.equal(await page.locator('form').filter({has:page.locator('input[name=SubscriptionLevelID][value="1"]')}).locator('[name=Enabled] option[value=true]').count(),0);
for(const theme of ['plotdirector','modern-light','modern-dark','warm-light','warm-dark','rose-pink','baby-blue']){await page.evaluate(theme=>{document.documentElement.dataset.appTheme=theme;document.documentElement.dataset.bsTheme=theme.endsWith('dark')?'dark':'light';document.documentElement.dataset.theme=theme.endsWith('dark')?'dark':'light';},theme);await page.screenshot({path:`/tmp/pd-ai-allowances/${installed?'pwa':'browser'}-admin-${theme}.png`});}
const allowance=await (await page.request.get(base+'/ai-policy-fixture/allowance')).text();await page.locator('main').first().evaluate((element,html)=>{element.innerHTML=html;},allowance);assert((await page.locator('[data-ai-allowance]').innerText()).includes('88'));await page.screenshot({path:`/tmp/pd-ai-allowances/${installed?'pwa':'browser'}-allowance.png`});
assert.deepEqual(errors,[]);console.log('PASS AI cost confirmation, locked-tier discovery/upgrade link, cancellation, one explicit submission, allowance and admin theme presentation');
}finally{if(installed){await cdp.send('PWA.uninstall',{manifestId}).catch(()=>{});await persistent.close();fs.rmSync(profile,{recursive:true,force:true});}else await browser.close();}
})().catch(error=>{console.error(error);process.exitCode=1;});