Files
aigc-home/e2e/hel818.cjs
T
2026-10-23 18:54:50 +08:00

124 lines
23 KiB
JavaScript

const {chromium}=require(process.env.PLAYWRIGHT_MODULE_PATH||'playwright');
const fs=require('node:fs'),assert=require('node:assert/strict'),http=require('node:http'),cp=require('node:child_process');
const OUT='../evidence/hel818',WEB='http://127.0.0.1:15173',API='http://127.0.0.1:18247';
fs.mkdirSync(OUT+'/shots',{recursive:true});
const report={checks:[],geometry:[],errors:[],animations:[],differences:[]};
const ok=(name,value)=>{report.checks.push({name,pass:!!value});assert(value,name);console.log('PASS',name)};
const wait=ms=>new Promise(r=>setTimeout(r,ms));
const api=async(p,body,method)=>{const r=await fetch(API+p,{method:method||(body?'POST':'GET'),headers:{'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined});assert(r.ok,p+' '+await r.clone().text());const text=await r.text();return text?JSON.parse(text):null};
const geom=(p,selectors)=>p.evaluate(selectors=>Object.fromEntries(Object.entries(selectors).map(([k,sel])=>{const e=document.querySelector(sel);if(!e)return[k,null];const r=e.getBoundingClientRect(),s=getComputedStyle(e);return[k,{x:r.x,y:r.y,width:r.width,height:r.height,font:s.font,color:s.color,bg:s.backgroundColor,border:s.border,shadow:s.boxShadow,radius:s.borderRadius}]})),selectors);
const mode=async(p,name)=>{await p.locator('.sidebar-bottom button[title="主题"]').click();await p.locator('.theme-motion').getByRole('button',{name,exact:true}).click();await p.keyboard.press('Escape');await wait(50)};
const theme=async(p,id)=>{await p.evaluate(id=>{document.documentElement.dataset.theme=id;window.dispatchEvent(new StorageEvent('storage',{key:'aigc-theme',newValue:id}))},id);await wait(100)};
(async()=>{
cp.execFileSync(process.env.HEL732_PYTHON||'python3',['e2e/hel818-fixture.py'],{stdio:'inherit'});
const f=JSON.parse(fs.readFileSync('e2e/shots/reference/canvas818.json'));
const server=http.createServer((req,res)=>{res.setHeader('Content-Type','text/html;charset=utf-8');res.end(fs.readFileSync('../references/canvas-sample.html'))});await new Promise(r=>server.listen(0,'127.0.0.1',r));
const browser=await chromium.launch({args:['--no-sandbox','--disable-dev-shm-usage']});
try{
const ctx=await browser.newContext({viewport:{width:1440,height:900},recordVideo:{dir:OUT+'/recordings'}});
await ctx.route('https://fonts.googleapis.com/**',r=>r.abort());await ctx.route('https://fonts.gstatic.com/**',r=>r.abort());report.fontNetwork='Both app and reference use the same offline fallback fonts; product font sources unchanged.';
await ctx.addInitScript(()=>{if(!localStorage.getItem('calliope.canvas.viewport.1'))localStorage.setItem('calliope.canvas.viewport.1',JSON.stringify({x:0,y:0,zoom:.8}));localStorage.setItem('aigc-lang','zh');if(!localStorage.getItem('aigc-motion'))localStorage.setItem('aigc-motion','off');window.vtCalls=0;const vt=document.startViewTransition?.bind(document);if(vt)document.startViewTransition=(...args)=>{window.vtCalls++;return vt(...args)}});
const p=await ctx.newPage();p.setDefaultTimeout(12000);p.on('pageerror',e=>report.errors.push(e.stack));
await p.goto(WEB+'/canvas/'+f.canvas.id+'?session='+f.session.id);await p.locator('.canvas-card').first().waitFor();await wait(700);
await p.locator('.artifact-node header').first().click();await p.mouse.move(5,5);await p.screenshot({path:OUT+'/shots/initial.png'});
ok('five real cards loaded',await p.locator('.canvas-card').count()===5);
ok('real image files loaded',await p.locator('.canvas-card img').evaluateAll(es=>es.every(e=>e.complete&&e.naturalWidth>0)));
ok('video first frame without autoplay',await p.locator('.canvas-card video').evaluate(e=>e.paused&&e.readyState>=2));
const sample=await ctx.newPage();
for(const [width,height] of [[1440,900],[1366,768],[1280,720]])for(const id of ['night','day','grade','bluehour']){
await p.setViewportSize({width,height});await theme(p,id);await wait(100);
await sample.setViewportSize({width,height});await sample.goto('http://127.0.0.1:'+server.address().port+'/?theme='+id+'&chrome=0');await wait(150);
await sample.screenshot({path:`${OUT}/shots/reference-original-${id}-${width}.png`});
// Runtime-only data/state mapping: source HTML and its CSS stay untouched.
const mapping=await p.evaluate(()=>{const board=document.querySelector('.flow-panel').getBoundingClientRect();return {title:document.querySelector('.title-btn').textContent,zoom:document.querySelector('.zoom-value').textContent,subtitle:document.querySelector('.chat-subtitle')?.textContent,sendDisabled:document.querySelector('.composer button.primary').disabled,cards:[...document.querySelectorAll('.canvas-card')].map(e=>{const r=e.getBoundingClientRect(),m=e.querySelector('.media');return {title:e.querySelector('.title').textContent,foot:e.querySelector('footer').innerText,kind:e.dataset.kind,x:r.x-board.x,y:r.y-board.y,scale:r.width/parseFloat(getComputedStyle(e).width),image:m.querySelector('img')?.src,selected:e.classList.contains('a-in-frame'),status:e.querySelector('.status')?.textContent||''}}),messages:[...document.querySelectorAll('.chat-panel .row')].filter(e=>e.matches('.user,.assistant')).map(e=>({user:e.classList.contains('user'),name:e.querySelector('.agent-tag')?.innerText,text:e.querySelector('.bubble')?.innerText}))}});
const frame=await p.locator('.canvas-card video').screenshot();mapping.video='data:image/png;base64,'+frame.toString('base64');mapping.minimap='data:image/png;base64,'+(await p.locator('.svelte-flow__minimap svg').screenshot()).toString('base64');
await sample.evaluate(mapping=>{
document.querySelector('.zoomv').textContent=mapping.zoom;document.querySelector('.chat-head .sub').textContent=mapping.subtitle;document.querySelector('.cbar .btn.primary').disabled=mapping.sendDisabled;const nativeMap=document.createElement('img');nativeMap.src=mapping.minimap;nativeMap.style.cssText='width:100%;height:100%;display:block';document.querySelector('.minimap .mm').replaceChildren(nativeMap);document.querySelector('.minimap .mmtag')?.remove();
document.querySelector('.demo-badge').remove();document.querySelector('.titlecard .saved').remove();document.querySelector('.tname').firstChild.nodeValue=mapping.title.trim();
document.querySelectorAll('.card').forEach((e,i)=>{const d=mapping.cards[i];e.classList.toggle('sel',d.selected);e.classList.toggle('on',d.selected);e.classList.remove('running');if(d.kind!=='video')e.querySelector('.chead .play')?.remove();e.style.setProperty('left',d.x+'px','important');e.style.setProperty('top',d.y+'px','important');e.style.transform='scale('+d.scale+')';e.style.transformOrigin='top left';e.querySelector('.t').textContent=d.title;const m=e.querySelector('.media');m.replaceChildren();const img=document.createElement('img');img.src=d.image||mapping.video;img.style.cssText='display:block;width:100%;height:100%;object-fit:cover';m.append(img);const badge=document.createElement('span');badge.className='kind';badge.textContent=d.kind==='video'?'video':'image';m.append(badge);const foot=e.querySelector('.cfoot');foot.replaceChildren();const left=document.createElement('span');left.textContent=d.foot.replace(/\s*#\d+$/,'');const grow=document.createElement('span');grow.className='grow';const number=document.createElement('span');number.className='mono';number.textContent=d.foot.match(/#\d+$/)?.[0]||'';foot.append(left,grow,number);const chip=e.querySelector('.chead .pill');if(chip)chip.textContent=d.kind;});
const body=document.querySelector('.chat-body');body.replaceChildren();for(const d of mapping.messages){const row=document.createElement('div');row.className='msg '+(d.user?'me':'ai');const wrap=document.createElement('div');if(!d.user){const tag=document.createElement('div');tag.className='agent-tag';tag.textContent=d.name;wrap.append(tag)}const b=document.createElement('div');b.className='bub';b.textContent=d.text;wrap.append(b);row.append(wrap);body.append(row)}
},mapping);await wait(50);
fs.writeFileSync(`${OUT}/mapping-${id}-${width}.json`,JSON.stringify(mapping,null,2));
const actual=await geom(p,{board:'.flow-panel',title:'.titlecard',controls:'.svelte-flow__controls',minimap:'.svelte-flow__minimap',chat:'.chat-panel',head:'.chat-head',entity:'.entity-node',artifact:'.artifact-node',media:'.entity-node .media'});
const reference=await geom(sample,{board:'.board-wrap',title:'.titlecard',controls:'.ctl',minimap:'.minimap',chat:'.chat',head:'.chat-head',entity:'.card.entity',artifact:'.card.artifact',media:'.card.entity .media'});
report.geometry.push({id,width,height,actual,reference});
const corner=await p.locator('.artifact-node').first().evaluate(e=>({token:getComputedStyle(e).getPropertyValue('--viewfinder-color'),image:getComputedStyle(e).getPropertyValue('--sc-image'),gold:getComputedStyle(e).getPropertyValue('--gold'),inset:getComputedStyle(e,'::after').inset}));report.geometry.at(-1).corner=corner;ok(id+' '+width+' corners use canvas scene',corner.token.includes(corner.image.trim())&&!corner.token.includes(corner.gold.trim()));
ok(id+' '+width+' 26px grid and 1px dot radius',await p.locator('.svelte-flow__background').evaluate(e=>Math.abs(parseFloat(e.querySelector('pattern').getAttribute('width'))-26)<.01&&Math.abs(parseFloat(e.querySelector('circle').getAttribute('r'))-1)<.01));
ok(id+' '+width+' no document overflow',await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
for(const sel of ['.titlecard','.tidy-btn','.svelte-flow__controls','.svelte-flow__minimap','.chat-head','.composer button.primary'])ok(id+' '+width+' '+sel+' reachable',await p.locator(sel).evaluate(e=>{const r=e.getBoundingClientRect();return r.x>=0&&r.y>=0&&r.right<=innerWidth&&r.bottom<=innerHeight}));
ok(id+' '+width+' board matches token',actual.board.bg===({night:'rgb(10, 12, 18)',day:'rgb(230, 224, 211)',grade:'rgb(30, 30, 33)',bluehour:'rgb(12, 19, 48)'}[id]));
await p.screenshot({path:`${OUT}/shots/app-${id}-${width}.png`});
await sample.screenshot({path:`${OUT}/shots/reference-mapped-${id}-${width}.png`});
}
await sample.close();
// Box selection and guarded delete use the real graph interaction.
await p.setViewportSize({width:1440,height:900});await wait(200);const area=await p.locator('.flow-panel').boundingBox();
await p.keyboard.down('Shift');await p.mouse.move(area.x+12,area.y+62);await p.mouse.down();await p.mouse.move(area.x+area.width-190,area.y+510,{steps:12});await p.mouse.up();await p.keyboard.up('Shift');
ok('box selection selects multiple cards',await p.locator('.svelte-flow__node.selected').count()>=2);await p.keyboard.press('Backspace');await wait(150);ok('project entity delete is protected',(await api('/api/canvas/'+f.canvas.id)).nodes.length===5);
const temporary=await api('/api/canvas/'+f.canvas.id+'/nodes',{type:'image',title:'可删除的隔离产物',artifact_path:f.image,status:'done',x:10,y:540});await p.locator('[data-id="cn-'+temporary.id+'"] header').waitFor();await p.locator('.svelte-flow__pane').click({position:{x:20,y:450}});await p.locator('[data-id="cn-'+temporary.id+'"] header').click();await p.locator('[data-id="cn-'+temporary.id+'"]').focus();ok('delete targets only the temporary artifact',await p.locator('.svelte-flow__node.selected').count()===1);await p.keyboard.press('Backspace');await wait(250);ok('unprotected artifact deletes through real API',!(await api('/api/canvas/'+f.canvas.id)).nodes.some(n=>n.id===temporary.id));
const cw=await p.locator('.chat-panel').evaluate(e=>e.getBoundingClientRect().width);await p.locator('.chat-splitter').focus();await p.keyboard.press('ArrowLeft');await wait(100);report.resize={before:cw,after:await p.locator('.chat-panel').evaluate(e=>({width:e.getBoundingClientRect().width,style:e.getAttribute('style')}))};ok('assistant keyboard resizing works',await p.locator('.chat-panel').evaluate(e=>e.getBoundingClientRect().width)>cw);await p.keyboard.press('ArrowRight');
// Rename, editing and theme/mode changes preserve live DOM and view state.
await p.setViewportSize({width:1440,height:900});await theme(p,'night');
await p.locator('.title-btn').click();await p.locator('.title-input').fill('HEL818 画布命名');await p.locator('.title-input').press('Enter');await wait(250);
ok('rename persisted',(await api('/api/canvas/'+f.canvas.id)).canvas.title==='HEL818 画布命名');
const editor=p.locator('.composer .editor');await editor.fill('尚未发送的画布输入');await editor.evaluate(e=>window.keptEditor=e);
const before=await api('/api/canvas/'+f.canvas.id);
await mode(p,'克制');await theme(p,'day');await mode(p,'完整');await theme(p,'grade');await mode(p,'关闭');
ok('theme and modes preserve input DOM/value',await editor.evaluate(e=>e===window.keptEditor&&e.innerText==='尚未发送的画布输入'));
const after=await api('/api/canvas/'+f.canvas.id);ok('theme and modes preserve card/project/viewport state',JSON.stringify(before)===JSON.stringify(after));
for(const label of ['完整','克制','关闭']){
await mode(p,label);const before=await p.evaluate(()=>window.vtCalls);await p.locator('.sidebar-bottom button[title="主题"]').click();const next=(await p.locator('html').getAttribute('data-theme'))==='day'?'夜片场':'日光棚';await p.locator('.choices.compact .choice').filter({hasText:next}).click();await wait(30);
const transition=await p.evaluate(()=>({vtCalls:window.vtCalls,classes:document.documentElement.className,circular:getComputedStyle(document.documentElement).getPropertyValue('--theme-reveal-duration').trim(),fallback:getComputedStyle(document.documentElement).getPropertyValue('--theme-fallback-duration').trim()}));report.animations.push({theme:label,...transition});ok(label+' approved theme transition',label==='完整'?transition.vtCalls>before&&transition.circular==='520ms':label==='克制'?transition.vtCalls===before&&transition.classes.includes('theme-anim')&&transition.fallback==='280ms':transition.vtCalls===before&&!transition.classes.includes('theme-anim'));await wait(550);await p.keyboard.press('Escape');ok(label+' theme UI preserves editor',await editor.evaluate(e=>e===window.keptEditor&&e.innerText==='尚未发送的画布输入'));
}
// Zoom/pan and persistence, lock and tidy still use real controls/API.
await p.locator('.svelte-flow__controls-zoomin').click();await wait(600);const zoomed=(await api('/api/canvas/'+f.canvas.id)).canvas.viewport_json;
ok('zoom persists viewport',JSON.parse(zoomed).zoom>.8);
await p.reload();await p.locator('.canvas-card').first().waitFor();await wait(350);ok('viewport survives reload',(await p.locator('.zoom-value').innerText())===Math.round(JSON.parse(zoomed).zoom*100)+'%');
await p.locator('.svelte-flow__controls-interactive').click();ok('lock toggles interactivity',await p.locator('.svelte-flow__node.draggable').count()===0);await p.locator('.svelte-flow__controls-interactive').click();
await p.locator('.svelte-flow__controls-fitview').click();await wait(300);
const card=p.locator('.entity-node').first();await card.click();await wait(100);ok('entity opens preview',await p.locator('.lightbox').count()>0||await p.getByRole('dialog').count()>0);await p.keyboard.press('Escape');await p.locator('.artifact-node[data-kind=video] .media-btn').click();ok('video card opens preview without inline autoplay',await p.getByRole('dialog').count()>0||await p.locator('.lightbox').count()>0);await p.keyboard.press('Escape');
const box=await card.boundingBox();await p.mouse.move(box.x+60,box.y+18);await p.mouse.down();await p.mouse.move(box.x+100,box.y+50,{steps:8});await p.mouse.up();await wait(400);
ok('drag persists real coordinates',(await api('/api/canvas/'+f.canvas.id)).nodes.some(n=>n.type==='entity'&&n.x!==40&&n.x!==360&&n.x!==656));
await p.locator('.tidy-btn').click();await wait(450);ok('tidy remains usable',await p.locator('.canvas-card').count()===5);
await p.locator('.chat-toggle').click();await wait(100);ok('assistant collapses',await p.locator('.chat-panel').count()===0);await theme(p,'night');await p.screenshot({path:OUT+'/shots/collapsed.png'});await p.locator('.chat-expand').click();
ok('assistant expands',await editor.count()===1);
await p.goto(WEB+'/canvas/'+f.empty.id);await p.locator('.canvas-empty-hint').waitFor();await wait(150);ok('real empty canvas has zero fake cards',await p.locator('.canvas-card').count()===0);await theme(p,'night');await p.screenshot({path:OUT+'/shots/empty-night.png'});await theme(p,'day');await p.screenshot({path:OUT+'/shots/empty-day.png'});
// Upload, workflow and skill menus keep their existing real behavior.
const input=p.locator('.composer .editor');await input.fill('@Qwen');await input.press('End');await input.press('n');await p.locator('.mention-menu').waitFor();ok('workflow menu remains usable',await p.getByRole('option').count()>0);await p.keyboard.press('Escape');await input.fill('/');await input.press('End');await input.press('h');await p.locator('.mention-menu').waitFor();ok('skill menu remains usable',await p.getByRole('option').count()>0);await p.keyboard.press('Escape');await input.fill('未发送的附件与编辑状态');
await p.locator('input[type=file]').setInputFiles(f.image);await p.locator('.tile:not(.uploading)').waitFor();await input.evaluate(e=>window.uploadEditor=e);const tiles=await p.locator('.tile').count();await mode(p,'克制');await theme(p,'grade');ok('theme/motion preserve uploaded attachments and editor',await p.locator('.tile').count()===tiles&&await input.evaluate(e=>e===window.uploadEditor&&e.innerText.includes('未发送')));
// Run only against our fake ComfyUI, capturing real pending/running -> done.
const workflows=JSON.parse(fs.readFileSync('e2e/shots/reference/fixtures.json'));
await p.evaluate(()=>{window.canvasAnimations=[];document.addEventListener('animationstart',e=>{if(e.animationName.startsWith('a-develop')&&e.target.closest('.canvas-card')){const a=e.target.getAnimations()[0];a.pause();a.currentTime=0;window.canvasAnimations.push({name:e.animationName,duration:a.effect.getTiming().duration,frames:a.effect.getKeyframes()})}},true)});
for(const [label,id] of [['完整','night'],['完整','day'],['完整','grade'],['完整','bluehour'],['克制','night'],['克制','day'],['克制','grade'],['克制','bluehour'],['关闭','night']]){
const animationCount=await p.evaluate(()=>window.canvasAnimations.length);await mode(p,label);await theme(p,id);fs.writeFileSync('e2e/fake_mode.json',JSON.stringify({mode:'ok',delay_sec:1,unique_filename:true,image_file:f.image}));
const created=await api('/api/playground/generate',{workflow_id:workflows.dual,input_values:{prompt:'HEL818 isolated canvas arrival',negative:'',seed:42}});
const n=await api('/api/canvas/'+f.empty.id+'/nodes',{type:'image',title:'当前隔离任务 '+created.job.id,job_id:created.job.id,artifact_path:f.image,status:'running',x:80,y:160});
await p.waitForFunction(()=>document.querySelector('.running-badge'));
await p.waitForFunction(id=>!document.querySelector('[data-id="cn-'+id+'"] .running-badge'),n.id,{timeout:30000});
const node=p.locator('[data-id="cn-'+n.id+'"]');
if(label==='关闭'){ok('off has no arrival replay',await node.locator('.a-result-develop').count()===0)}else{
await node.locator('.a-result-develop').waitFor();await p.waitForFunction(count=>window.canvasAnimations.length>count,animationCount);const data=await p.evaluate(()=>window.canvasAnimations.at(-1));report.animations.push({label,id,...data});ok(label+' '+id+' correct reveal duration',data.duration===(label==='完整'?700:350));
await p.screenshot({path:`${OUT}/shots/reveal-${label}-${id}-000.png`});await node.locator('.media-el').evaluate(e=>e.getAnimations()[0].currentTime=e.getAnimations()[0].effect.getTiming().duration/2);await p.screenshot({path:`${OUT}/shots/reveal-${label}-${id}-mid.png`});
await node.locator('.media-btn').dispatchEvent('pointerdown');ok(label+' '+id+' click skips reveal',await node.locator('.a-result-develop').count()===0);
}
await theme(p,id==='day'?'night':'day');ok(label+' '+id+' theme does not replay',await node.locator('.a-result-develop').count()===0);
}
await p.reload();await p.locator('.canvas-card').first().waitFor();ok('history does not replay reveal',await p.locator('.a-result-develop').count()===0);
await p.emulateMedia({reducedMotion:'reduce'});await wait(100);ok('OS reduced motion forces off',await p.locator('html').getAttribute('data-motion')==='off');await p.emulateMedia({reducedMotion:'no-preference'});
// Real chat/tool execution and cancellation against the loopback fake model.
fs.writeFileSync('e2e/fake_mode.json',JSON.stringify({mode:'ok',agent_delay:0}));await p.locator('.composer .editor').fill('请查看画布项目素材');await p.locator('.composer button.primary').click();await p.locator('.chat-panel .tool-card').first().waitFor();await p.locator('.chat-panel .tool-card .head').first().click();ok('real tool parameters expand',await p.locator('.chat-panel .tool-card .head').first().getAttribute('aria-expanded')==='true');await p.waitForFunction(()=>!document.querySelector('.composer .stop'),null,{timeout:30000});
fs.writeFileSync('e2e/fake_mode.json',JSON.stringify({mode:'ok',agent_delay:3}));await p.locator('.composer .editor').fill('请继续整理');await p.locator('.composer button.primary').click();await p.locator('.composer .stop').waitFor();await p.locator('.composer .editor').fill('调整为近景');await p.locator('.composer button.primary').click();await p.locator('.user-bubble').filter({hasText:'调整为近景'}).waitFor();ok('running chat accepts guidance',true);await p.locator('.composer .stop').click();await p.waitForFunction(()=>!document.querySelector('.composer .stop'),null,{timeout:30000});ok('stop cancels real isolated agent run',true);
// Unlink uses the existing confirmation and leaves the project intact.
await p.goto(WEB+'/canvas/'+f.canvas.id+'?session='+f.session.id);await p.locator('.unlink-btn').waitFor();p.once('dialog',d=>d.accept());await p.locator('.unlink-btn').click();await p.waitForURL(u=>!u.pathname.endsWith('/'+f.canvas.id));ok('unlink preserves project and session history',(await api('/api/projects/'+f.project.id)).id===f.project.id&&(await api('/api/agent/sessions/'+f.session.id)).project_id===null);
await p.goto(WEB+'/build-scene');await p.locator('.composer .editor').waitFor();ok('shared composer retains original default button',await p.locator('.composer button.send:not(.stop)').count()===1);await p.screenshot({path:OUT+'/shots/shared-build-scene.png'});
await ctx.close();
const blocked=await browser.newContext({viewport:{width:1280,height:720}});await blocked.addInitScript(()=>{Storage.prototype.getItem=()=>{throw new DOMException('blocked')};Storage.prototype.setItem=()=>{throw new DOMException('blocked')}});const q=await blocked.newPage();q.on('pageerror',e=>report.errors.push(e.stack));await q.goto(WEB+'/canvas/'+f.canvas.id);await q.locator('.canvas-card').first().waitFor();ok('storage unavailable still renders real canvas',await q.locator('.canvas-card').count()===5);await q.screenshot({path:OUT+'/shots/storage-blocked.png'});await blocked.close();
ok('no page errors',report.errors.length===0);
}finally{fs.writeFileSync(OUT+'/results.json',JSON.stringify(report,null,2));await browser.close();await new Promise(r=>server.close(r))}
})().catch(e=>{console.error(e);process.exitCode=1});