Files
Agent-Workbench/scripts/ci-desktop-smoke.mjs

112 lines
11 KiB
JavaScript

import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import net from 'node:net';
import { randomUUID } from 'node:crypto';
import { chromium, _electron } from 'playwright';
import { HostController } from '../src/core/desktop/host-controller.mjs';
import { observeWindowsProcess } from '../src/core/desktop/process-identity.mjs';
import { desktopExecutableIdentity } from '../src/core/desktop/app-installation.mjs';
import { projectEnvironment } from '../src/core/process-environment.mjs';
import { browserInstallation } from '../src/core/browser/browser-driver.mjs';
import { openWorkbenchTool } from './ui-navigation.mjs';
import { fileDigest, writeNewJson, loopbackPortStatus } from './ci-utils.mjs';
const args=process.argv.slice(2);
if(args.includes('--help')) {console.log('node scripts/ci-desktop-smoke.mjs --evidence NEW_DIRECTORY — actual product Microsoft Edge and hidden Electron through locked Playwright against an owned new host/project. No model, external project, formal configuration or installation.');process.exit(0);}
if(args.length!==2 || args[0]!=='--evidence')throw new Error('Use --help');
assert.equal(process.platform,'win32');
const appRoot=process.cwd(),evidence=path.resolve(args[1]);fs.mkdirSync(evidence);
const ownedRoot=path.join(appRoot,'.qa','ci-smoke-'+randomUUID().slice(0,8)),dataRoot=path.join(ownedRoot,'data'),projectRoot=path.join(ownedRoot,'project');fs.mkdirSync(projectRoot,{recursive:true});
const original=Buffer.from('# Owned CI project\n\nSource retained while actual web and Electron entry paths are exercised.\n');
fs.writeFileSync(path.join(projectRoot,'README.md'),original,{flag:'wx'});
const reservation=net.createServer();await new Promise(resolve=>reservation.listen(0,'127.0.0.1',resolve));const port=reservation.address().port;await new Promise(resolve=>reservation.close(resolve));
const controller=new HostController({appRoot,dataRoot,port,nodePath:process.execPath,timeoutMs:60000});
const report={schemaVersion:1,passed:false,startedAt:new Date().toISOString(),ownedRoot,port,groups:[],screenshots:[],pageErrors:[],externalRequests:[],scope:'Actual isolated product Microsoft Edge/Electron through locked Playwright and owned source/data only; no model or formal installation.'};
let browser,application,electronPid,hostIdentity,activePage,stage='host-start';
const record=(name,detail={})=>report.groups.push({name,passed:true,...detail});
const watched=new WeakSet();
const watch=(page)=>{activePage=page;if(watched.has(page))return;watched.add(page);page.on('pageerror',error=>report.pageErrors.push(error.message));page.on('request',request=>{const url=new URL(request.url());if(['http:','https:'].includes(url.protocol) && !(url.hostname==='127.0.0.1' && Number(url.port)===port))report.externalRequests.push(request.url());});};
async function capture(page,mode,width,height){
const id=mode+'-'+width,file=path.join(evidence,id+'.png');
if(mode==='electron'){
await application.evaluate(({BrowserWindow},size)=>BrowserWindow.getAllWindows()[0].setContentSize(...size),[width,height]);
await page.waitForFunction(size=>innerWidth===size[0] && innerHeight===size[1],[width,height]);
}else await page.setViewportSize({width,height});
const dialog=page.getByRole('dialog',{name:'模型中心',exact:true});
await dialog.getByRole('heading',{name:'新任务默认模型',exact:true}).waitFor({timeout:30000});
await dialog.getByRole('combobox',{name:'新任务默认模型',exact:true}).and(page.locator('select:enabled')).waitFor({timeout:30000});
const painted=await dialog.evaluate(async element=>{
await document.fonts.ready;
await Promise.all(element.getAnimations({subtree:true}).filter(animation=>animation.effect?.getTiming().iterations!==Infinity).map(animation=>animation.finished.catch(()=>{})));
const frames=[];await new Promise(resolve=>requestAnimationFrame(first=>{frames.push(first);requestAnimationFrame(second=>{frames.push(second);resolve();});}));
return{fontStatus:document.fonts.status,frames};
});
assert.equal(painted.fontStatus,'loaded');assert.ok(painted.frames[1]>painted.frames[0]);
if(mode==='electron'){
const value=await application.evaluate(async({BrowserWindow})=>{const window=BrowserWindow.getAllWindows()[0];const [width,height]=window.getContentSize();const image=await window.capturePage({x:0,y:0,width,height},{stayHidden:true,stayAwake:true});return{base64:image.toPNG().toString('base64'),visible:window.isVisible(),size:image.getSize()};});
assert.equal(value.visible,false);assert.equal(value.size.width,width);assert.equal(value.size.height,height);fs.writeFileSync(file,Buffer.from(value.base64,'base64'),{flag:'wx'});
}else await page.screenshot({path:file,fullPage:false});
writeNewJson(path.join(evidence,id+'.dom.json'),{title:await page.title(),width,height,painted,html:await page.content(),overflow:await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth)});
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false,'Document overflows');
const bytes=fs.readFileSync(file);assert.equal(bytes.subarray(1,4).toString(),'PNG');assert.ok(bytes.length>1000);
report.screenshots.push({file,width,height,sha256:fileDigest(file),bytes:bytes.length});
}
async function userPath(page,mode,projectId){
watch(page);await page.locator('.connection.connected').waitFor({timeout:30000});assert.match(await page.title(),/Orven/i);
await page.getByRole('combobox',{name:'当前项目',exact:true}).selectOption(projectId);
record(mode+' project selection and connected build');
await openWorkbenchTool(page,'打开模型中心');await page.getByRole('dialog',{name:'模型中心',exact:true}).waitFor();
await capture(page,mode,1280,900);await page.keyboard.press('Escape');
if(mode==='electron')await application.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows()[0].setContentSize(390,844));else await page.setViewportSize({width:390,height:844});
await openWorkbenchTool(page,'打开模型中心');await page.getByRole('dialog',{name:'模型中心',exact:true}).waitFor();
await capture(page,mode,390,844);await page.keyboard.press('Escape');
record(mode+' actual model center at 1280 and 390');
}
try{
hostIdentity=(await controller.start()).identity;report.host={pid:hostIdentity.pid,createdAt:hostIdentity.createdAt};
const project=await controller.api('/projects',{method:'POST',input:{root:projectRoot}}),session=await controller.api('/sessions',{method:'POST',input:{projectId:project.id}});
record('owned new host/project/session',{projectId:project.id,sessionId:session.id});
stage='product-edge';const edge=browserInstallation(appRoot);assert.equal(edge.status,'available','Product Microsoft Edge is required');report.edge=edge;browser=await chromium.launch({executablePath:edge.executable.path,headless:true});report.edgeVersion=browser.version();
const page=await browser.newPage({viewport:{width:1280,height:900}});watch(page);await page.goto(controller.url);await userPath(page,'web',project.id);await browser.close();browser=null;
stage='electron';const executable=desktopExecutableIdentity(appRoot).path;
application=await _electron.launch({executablePath:executable,args:[path.join(appRoot,'dist-desktop/main.cjs'),'--app-root',appRoot,'--data-root',dataRoot,'--node',process.execPath,'--port',String(port),'--hidden-window'],cwd:appRoot,env:projectEnvironment(),timeout:60000});
electronPid=await application.evaluate(()=>process.pid);report.electron={pid:electronPid,executable,sha256:fileDigest(executable),version:await application.evaluate(()=>process.versions.electron)};
const window=await application.firstWindow();
// Keep this owned QA window hidden while giving its renderer foreground
// frame scheduling. This affects capture only and ends with the process.
await application.evaluate(({BrowserWindow})=>BrowserWindow.getAllWindows()[0].webContents.setBackgroundThrottling(false));
report.electron.capturePolicy={hiddenWindow:true,backgroundThrottling:false,requireLoadedModelCard:true,waitForFontsAndTwoFrames:true};
await userPath(window,'electron',project.id);
const status=await controller.status();assert.equal(status.identity.pid,hostIdentity.pid);assert.ok(status.desktopWindows.entries.some(entry=>entry.pid===electronPid));
record('same owned host and actual registered Electron');
const center=await controller.api('/model-center');assert.equal(center.attempts.length,0,'No model request is permitted in CI smoke');
assert.deepEqual(fs.readFileSync(path.join(projectRoot,'README.md')),original);assert.deepEqual(report.pageErrors,[]);assert.deepEqual(report.externalRequests,[]);
record('original source retained; zero model attempts or outside page requests');
report.passed=true;
}catch(error){
report.failure={stage,name:error.name,message:error.message,stack:error.stack};process.exitCode=1;
if(activePage&&!activePage.isClosed()){
try{
const domFile=path.join(evidence,'failure-'+stage+'.html'),imageFile=path.join(evidence,'failure-'+stage+'.png');
fs.writeFileSync(domFile,await activePage.content(),{flag:'wx'});
if(stage==='electron'&&application){
const base64=await application.evaluate(async({BrowserWindow})=>{const window=BrowserWindow.getAllWindows()[0];const [width,height]=window.getContentSize();return(await window.capturePage({x:0,y:0,width,height},{stayHidden:true,stayAwake:true})).toPNG().toString('base64');});
fs.writeFileSync(imageFile,Buffer.from(base64,'base64'),{flag:'wx'});
}else await activePage.screenshot({path:imageFile,fullPage:true,timeout:10000});
report.failureCapture={url:activePage.url(),dom:{file:domFile,bytes:fs.statSync(domFile).size,sha256:fileDigest(domFile)},image:{file:imageFile,bytes:fs.statSync(imageFile).size,sha256:fileDigest(imageFile)}};
}catch(captureError){report.failureCaptureError={message:captureError.message};}
}
}
finally{
try{if(browser)await browser.close();if(application)await application.close();
if(await controller.health())report.hostStop=await controller.stop();
const deadline=Date.now()+15000;while(electronPid && observeWindowsProcess(electronPid) && Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,100));
assert.equal(electronPid?!!observeWindowsProcess(electronPid):false,false,'Owned Electron did not exit');assert.equal(await controller.health(),null,'Owned port still responds');
report.portObservation=await loopbackPortStatus(port);assert.equal(report.portObservation.status,'refused','Recorded CI port still accepts TCP connections');
report.cleanup={hostExited:hostIdentity?observeWindowsProcess(hostIdentity.pid)===null:true,electronExited:electronPid?observeWindowsProcess(electronPid)===null:true,portClosed:report.portObservation.status==='refused'};
assert.equal(report.cleanup.hostExited,true);
}catch(error){report.passed=false;report.cleanupFailure={message:error.message,stack:error.stack};process.exitCode=1;}
report.finishedAt=new Date().toISOString();writeNewJson(path.join(evidence,'result.json'),report);console.log(JSON.stringify({passed:report.passed,groups:report.groups.length,screenshots:report.screenshots.length,report:path.join(evidence,'result.json'),failure:report.failure?.message,cleanupFailure:report.cleanupFailure?.message}));
}