ZZZ Digital Lab

Back to HushBrief

scripts/browser-check.mjs

import { chromium } from 'playwright';
import assert from 'node:assert/strict';
import { mkdir, mkdtemp, writeFile, readFile, rm, realpath } from 'node:fs/promises';
import { resolve, sep } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
const root=resolve(import.meta.dirname,'..');
const output=resolve(root,'output/playwright');
const cache=resolve(root,'.cache');
await mkdir(output,{recursive:true});await mkdir(cache,{recursive:true});
const profile=await mkdtemp(resolve(cache,'chrome-check-'));
const checks=[];const errors=[];const external=[];const requests=[];
const report={checkedAt:new Date().toISOString(),browser:'',profile:'fresh temporary profile; no sign-in; deleted after closing',checks,nano:null,errors,externalRequests:external};
let context;
async function waitForText(page,selector,text){
  await page.waitForFunction(({selector,text})=>document.querySelector(selector)?.textContent?.includes(text),{selector,text},{timeout:15000});
}
try {
  context=await chromium.launchPersistentContext(profile,{
    executablePath:process.env.CHROME_EXE||'C:/Program Files/Google/Chrome/Application/chrome.exe',
    headless:process.env.HEADLESS==='true',viewport:{width:1440,height:1050},
    acceptDownloads:true,downloadsPath:output,
    args:['--no-first-run','--no-default-browser-check'],
    ignoreDefaultArgs:['--disable-component-update']
  });
  const page=context.pages()[0]||await context.newPage();
  page.on('pageerror',e=>errors.push(e.message));
  page.on('request',r=>{
    const url=new URL(r.url());
    if(url.pathname==='/api/fake-cloud')requests.push(JSON.parse(r.postData()||'{}'));
    if(url.protocol.startsWith('http')&&url.hostname!=='127.0.0.1')external.push(url.origin);
  });
  await page.goto('http://127.0.0.1:4173',{waitUntil:'networkidle'});
  report.browser=await page.evaluate(()=>navigator.userAgent.match(/Chrome\/[^ ]+/)?.[0]||'unknown');
  const headings=await page.getByRole('heading').allTextContents();
  assert.ok(headings.includes('Working notes'));assert.ok(headings.includes('The cloud boundary'));
  checks.push('Initial page, headings and actual detection rendered');
  assert.match(await page.locator('#mode-notice').innerText(),/fake backend/);
  assert.match(await page.locator('#route').innerText(),/Not run yet/);
  await page.keyboard.press('Tab');
  assert.equal(await page.locator('.skip-link').evaluate(el=>el===document.activeElement),true);
  await page.keyboard.press('Enter');
  assert.equal(await page.locator('#notes').evaluate(el=>el===document.activeElement),true);
  assert.equal(await page.getByLabel('Private working notes').count(),1);
  assert.equal(await page.getByRole('region',{name:'Cloud payload preview'}).getAttribute('tabindex'),'0');
  checks.push('First-run rehearsal and not-run labels, keyboard skip link, notes label and focusable preview');
  const packet=await page.locator('#packet').textContent();
  for(const s of ['maya@example.test','8123 4567','18,000'])assert.ok(!packet.includes(s));
  assert.equal(await page.locator('#masked').textContent(),'3 masked');
  assert.equal(await page.locator('#private-notice').textContent(),'1 private note withheld from the handoff');
  assert.equal(await page.locator('#private-notice').isVisible(),true);
  checks.push('Email, phone and marked private passage absent from preview');
  await page.locator('#rehearsal summary').click();
  await page.locator('#sim-nano').selectOption('unavailable');
  await page.getByRole('button',{name:'Create handoff'}).click();
  await waitForText(page,'#route','Local rules');
  assert.equal(requests.length,0);assert.equal(await page.locator('.action-card').count(),3);
  assert.doesNotMatch(await page.locator('#cards').innerText(),/18,000|\[private note withheld\]/);
  checks.push('No consent: local fallback with three actions and zero fake-cloud requests');
  await page.locator('#consent').check();
  await page.getByRole('button',{name:'Create handoff'}).click();
  await waitForText(page,'#route','Fake cloud');
  assert.equal(requests.length,1);assert.equal(requests[0].notes,packet);
  checks.push('Consented unavailable-Nano route: real loopback HTTP, exact redacted packet');
  const downloadPromise=page.waitForEvent('download');
  await page.getByRole('button',{name:'Export Markdown'}).click();
  const download=await downloadPromise;
  assert.equal(download.suggestedFilename(),'hushbrief-handoff.md');
  await download.saveAs(resolve(output,'handoff-sample.md'));
  const markdown=await readFile(resolve(output,'handoff-sample.md'),'utf8');
  assert.ok(markdown.split('- [ ]')[0].includes('1 private note withheld from the handoff'));
  assert.doesNotMatch(markdown,/18,000|\[\[private:|\[private note withheld\]/i);
  checks.push('Markdown export downloads with the private-span notice in its header and no private content');
  await page.screenshot({path:resolve(output,'desktop.png'),fullPage:true});
  await page.locator('#notes').fill('TODO: Review changed notes.\n[[private: SECRET]]');
  assert.equal(await page.locator('#consent').isChecked(),false);
  assert.equal(await page.locator('#export').isDisabled(),true);
  checks.push('Editing revokes cloud permission and invalidates export');
  await page.locator('#cloud-fail').check();await page.locator('#consent').check();
  await page.getByRole('button',{name:'Create handoff'}).click();
  await waitForText(page,'#status','Model or network unavailable');
  assert.equal(await page.locator('.action-card').count(),1);
  checks.push('Simulated cloud 503 recovers locally');
  assert.match(await page.locator('#attempt').innerText(),/Fake-cloud HTTP route attempted/);
  assert.equal(await page.locator('#recovery').isVisible(),true);
  checks.push('Recovery keeps local output source separate from attempted fake-cloud route');
  await page.locator('#cloud-fail').uncheck();
  await page.locator('#sim-nano').selectOption('available');
  await page.getByRole('button',{name:'Create handoff'}).click();
  await waitForText(page,'#route','Simulated Nano');
  assert.doesNotMatch(await page.locator('#cards').innerText(),/SECRET|\[private note withheld\]/);
  checks.push('Simulated device run has an explicit rehearsal label');
  await page.locator('#notes').fill('TODO: Review public contact maya@example.test.\n[[private: TODO: Review hidden budget.]]\n[[private: TODO: Send hidden tail.');
  assert.equal(await page.locator('#private-notice').textContent(),'2 private notes withheld from the handoff');
  await page.locator('#run').click();await waitForText(page,'#route','Simulated Nano');
  assert.equal(await page.locator('.action-card').count(),1);
  assert.match(await page.locator('#cards').innerText(),/maya@example.test/);
  assert.doesNotMatch(await page.locator('#cards').innerText(),/hidden|\[private note withheld\]/);
  const privateDownloadPromise=page.waitForEvent('download');
  await page.getByRole('button',{name:'Export Markdown'}).click();
  const privateDownload=await privateDownloadPromise;
  await privateDownload.saveAs(resolve(output,'handoff-device-private.md'));
  const privateMarkdown=await readFile(resolve(output,'handoff-device-private.md'),'utf8');
  assert.ok(privateMarkdown.split('- [ ]')[0].includes('2 private notes withheld from the handoff'));
  assert.match(privateMarkdown,/maya@example.test/);assert.doesNotMatch(privateMarkdown,/hidden|\[private note withheld\]/);
  checks.push('Device rehearsal with closed and unclosed spans keeps contacts, drops private actions, and exports the plural notice');
  await page.locator('#notes').fill('TODO: <img src=x onerror=alert(1)>');
  assert.equal(await page.locator('#private-notice').isVisible(),false);
  await page.locator('#sim-nano').selectOption('unavailable');
  await page.getByRole('button',{name:'Create handoff'}).click();
  await waitForText(page,'#route','Local rules');
  assert.equal(await page.locator('#cards img').count(),0);
  checks.push('Adversarial note is rendered as text, no HTML execution');
  await page.getByRole('button',{name:'Clear workspace'}).click();
  assert.equal(await page.locator('#notes').inputValue(),'');
  assert.equal(await page.locator('.action-card').count(),0);
  assert.equal(await page.locator('#result-title').textContent(),'The next shift starts here');
  assert.equal(await page.locator('#consent').isChecked(),false);
  checks.push('Clear removes input, result title, cards and permission');
  await page.locator('#run').click();
  assert.equal(await page.locator('#notes').getAttribute('aria-invalid'),'true');
  assert.match(await page.locator('#input-error').innerText(),/Load example/);
  assert.equal(await page.locator('#notes').evaluate(el=>el===document.activeElement),true);
  await page.locator('#notes').fill('A quiet day with no explicit tasks.');
  await page.locator('#run').click();
  await waitForText(page,'#route','Local rules');
  assert.match(await page.locator('#cards').innerText(),/No action lines found/);
  assert.equal(await page.locator('#export').isDisabled(),true);
  checks.push('Empty input has an announced error and focus; zero-action output gives a useful next step');
  await page.locator('#sample').click();
  let releaseRequest;
  const gate=new Promise(resolve=>{releaseRequest=resolve});
  await page.route('**/api/fake-cloud',async route=>{await gate;await route.continue()});
  await page.locator('#consent').check();
  await page.locator('#run').click();
  assert.equal(await page.locator('#export').isDisabled(),true);
  await page.locator('#notes').fill('TODO: Changed while processing.');
  releaseRequest();
  await waitForText(page,'#status','Result discarded');
  assert.equal(await page.locator('#export').isDisabled(),true);
  await page.unroute('**/api/fake-cloud');
  checks.push('In-flight edits discard the stale result and cannot export a previous handoff');
  await page.waitForFunction(()=>navigator.serviceWorker.controller!==null,undefined,{timeout:15000});
  await page.evaluate(async()=>{await navigator.serviceWorker.ready;if(!navigator.serviceWorker.controller)await new Promise(resolve=>navigator.serviceWorker.addEventListener('controllerchange',resolve,{once:true}));});
  await context.setOffline(true);
  await page.reload({waitUntil:'networkidle'});
  await page.screenshot({path:resolve(output,'offline-diagnostic.png'),fullPage:true});
  console.log('Offline diagnostic:',await page.evaluate(async()=>({title:document.title,body:document.body.innerText.slice(0,200),controller:!!navigator.serviceWorker.controller,cacheNames:await caches.keys()})));
  await page.getByRole('button',{name:'Create handoff'}).click();
  await waitForText(page,'#status','Offline.');
  checks.push('Actual browser offline reload and local extraction work through service worker');
  await context.setOffline(false);
  await page.setViewportSize({width:390,height:844});
  assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
  await page.screenshot({path:resolve(output,'mobile.png'),fullPage:true});
  checks.push('390px layout has no horizontal overflow');
  for(const width of [320,640]){
    await page.setViewportSize({width,height:900});
    assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
  }
  checks.push('320px and 640px responsive layouts have no horizontal overflow');
  await page.setViewportSize({width:1440,height:1050});

  // Separate diagnostic: direct Chrome Prompt API on this fresh profile, not a Firebase claim.
  report.nano=await page.evaluate(async()=>{
    if(!globalThis.LanguageModel?.availability)return{apiPresent:false,availability:'unsupported',inference:false};
    try{return{apiPresent:true,availability:await LanguageModel.availability({expectedInputs:[{type:'text',languages:['en']}],expectedOutputs:[{type:'text',languages:['en']}]}),inference:false}}
    catch(e){return{apiPresent:true,availability:'error',inference:false,error:e.name+': '+e.message}}
  });
  console.log('Chrome probe:',JSON.stringify(report.nano));
  if(['available','downloadable','downloading'].includes(report.nano.availability)){
    await page.evaluate(()=>{
      const button=document.createElement('button');button.id='nano-probe';button.textContent='Run isolated Nano probe';document.body.append(button);
      globalThis.__nanoProbe={state:'idle'};
      button.onclick=()=>{
        globalThis.__nanoProbe={state:'running',progress:0};
        LanguageModel.create({
          expectedInputs:[{type:'text',languages:['en']}],expectedOutputs:[{type:'text',languages:['en']}],
          monitor(m){m.addEventListener('downloadprogress',e=>{globalThis.__nanoProbe.progress=e.loaded;})}
        }).then(async session=>{
          try{const text=await session.prompt('Reply with the single word READY.');globalThis.__nanoProbe={state:'success',text};}
          finally{session.destroy()}
        }).catch(e=>{globalThis.__nanoProbe={state:'error',error:e.name+': '+e.message}});
      };
    });
    await page.locator('#nano-probe').click();
    for(let i=0;i<8;i++){
      await delay(5000);const state=await page.evaluate(()=>globalThis.__nanoProbe);
      console.log('Nano probe progress:',JSON.stringify(state));
      if(['success','error'].includes(state.state))break;
    }
    const state=await page.evaluate(()=>globalThis.__nanoProbe);
    report.nano={...report.nano,...state,inference:state.state==='success',boundedAttemptSeconds:40};
  }
  assert.equal(errors.length,0);
  assert.equal(external.length,0);
  checks.push('No browser page exceptions or external app requests observed');
  report.status='passed';
} catch(e) {
  report.status='failed';report.failure=e.stack||String(e);process.exitCode=1;
} finally {
  if(context)await context.close();
  const actual=await realpath(profile);const allowed=await realpath(cache);
  if(!actual.startsWith(allowed+sep)||!actual.split(sep).at(-1).startsWith('chrome-check-'))throw Error('Unexpected temporary profile path');
  await rm(actual,{recursive:true,force:true,maxRetries:3,retryDelay:300});
  await writeFile(resolve(output,'browser-report.json'),JSON.stringify(report,null,2));
  console.log(JSON.stringify(report,null,2));
}