fix: align B3 small button radii and primary disabled states

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
leefer
2026-10-22 11:00:53 +08:00
co-authored by multica-agent
parent 930cca653f
commit 8d7e58645c
6 changed files with 191 additions and 1 deletions
+93
View File
@@ -0,0 +1,93 @@
// HEL-776: real isolated pages; sample controls are state fixtures, never product data.
const {chromium}=require(process.env.PLAYWRIGHT_MODULE_PATH||'playwright');
const fs=require('node:fs'),http=require('node:http'),assert=require('node:assert/strict'),cp=require('node:child_process');
const out='../evidence',WEB='http://127.0.0.1:5173',API='http://127.0.0.1:8247';
const rows=[],checks=[],errors=[],protections=[];
const ok=(name,v)=>{assert(v,name);checks.push(name);console.log('PASS',name)};
const wait=ms=>new Promise(r=>setTimeout(r,ms));
const api=async(path,body,method)=>{const r=await fetch(API+path,{method:method||(body?'POST':'GET'),headers:{'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined});assert(r.ok,await r.clone().text());return r.json()};
const style=loc=>loc.evaluate(e=>{const s=getComputedStyle(e),r=e.getBoundingClientRect();return Object.fromEntries(['opacity','filter','backgroundColor','backgroundImage','color','boxShadow','borderRadius','paddingLeft','paddingRight','fontSize','fontWeight','borderTopColor','borderTopWidth','transform'].map(k=>[k,s[k]]).concat([['height',r.height]]))});
async function settled(p){await p.evaluate(async()=>{await document.fonts.ready;await Promise.all(document.getAnimations().filter(a=>a.effect?.getTiming().iterations!==Infinity).map(a=>a.finished.catch(()=>{})))});await wait(180)}
(async()=>{
fs.mkdirSync(out+'/closeups',{recursive:true});fs.mkdirSync(out+'/operations',{recursive:true});
const server=http.createServer((req,res)=>{res.setHeader('Content-Type','text/html;charset=utf-8');res.end(fs.readFileSync('../materials/夜片场-多主题交互样本.html'))});await new Promise(r=>server.listen(0,'127.0.0.1',r));
const b=await chromium.launch({args:['--no-sandbox','--disable-dev-shm-usage']});const c=await b.newContext();await c.tracing.start({screenshots:process.env.HEL776_PROTECT_ONLY!=='1',snapshots:true,sources:true});
const p=await c.newPage(),sp=await c.newPage();p.setDefaultTimeout(15000);p.on('pageerror',e=>errors.push(e.message));
const proj=(await api('/api/projects')).find(x=>x.title==='隔离验证 · 海岸来信'),path='/api/workbench/projects/'+proj.id+'/stages/storyboard',url=WEB+'/workbench/'+proj.id+'?stage=storyboard';
try{
if(process.env.HEL776_PROTECT_ONLY!=='1'){
for(const [width,height] of [[1440,900],[1366,768],[1280,720]])for(const theme of ['night','day','grade','bluehour']){
await p.setViewportSize({width,height});await sp.setViewportSize({width,height});await sp.goto('http://127.0.0.1:'+server.address().port);await sp.evaluate(t=>document.documentElement.dataset.theme=t,theme);
await p.goto(WEB);await p.evaluate(t=>localStorage.setItem('aigc-theme',t),theme);
for(const page of ['studio','project']){
await p.goto(page==='studio'?WEB:url);await p.locator(page==='studio'?'.studio-hero':'.storyboard-card').first().waitFor();await settled(p);
const scope=page==='studio'?'.home':'.project-workspace';
const controls=p.locator(scope+' .a-btn.secondary');
for(let i=0;i<await controls.count();i++){
const al=controls.nth(i),item=await al.evaluate(e=>({text:e.textContent.trim(),small:e.classList.contains('sm'),disabled:e.disabled,aria:e.getAttribute('aria-disabled')}));
await sp.evaluate(item=>{document.querySelector('#fixture')?.remove();const e=document.createElement('button');e.id='fixture';e.className='btn'+(item.small?' sm':'');e.textContent=item.text;Object.assign(e.style,{position:'fixed',left:'100px',top:'100px'});document.body.append(e)},item);
const sl=sp.locator('#fixture');
for(const state of ['normal','hover','active']){
await al.evaluate(e=>{e.removeAttribute('disabled');e.removeAttribute('aria-disabled')});await p.mouse.move(0,0);await sp.mouse.move(0,0);
if(state!=='normal'){await al.hover();await sl.hover()}if(state==='active'){await p.mouse.down();await sp.mouse.down()}
await wait(180);const actual=await style(al),sample=await style(sl);rows.push({page,theme,width,text:item.text,small:item.small,state,actual,sample});
for(const k of ['backgroundColor','borderTopColor','borderTopWidth','borderRadius','paddingLeft','paddingRight','fontSize','fontWeight','height',...(state==='active'?['transform']:[])])assert.equal(actual[k],sample[k],`${page}/${theme}/${width}/${item.text}/${state}/${k}`);
if(state==='active'){await p.mouse.move(0,0);await sp.mouse.move(0,0);await p.mouse.up();await sp.mouse.up()}
}
await al.evaluate((e,item)=>{if(item.disabled)e.setAttribute('disabled','');if(item.aria!==null)e.setAttribute('aria-disabled',item.aria)},item);
}
ok(`${page} ${theme} ${width}: every normal/small secondary normal/hover/active equals sample`,true);
}
// Native disabled confirmation caused by an actual unsaved edit, then actual save restores it.
await p.goto(url);await p.locator('.storyboard-card').first().waitFor();await p.getByRole('button',{name:'编辑',exact:true}).click();await p.locator('.shot-edit textarea').first().fill('HEL776 '+theme+' '+width);
const confirm=p.locator('[data-testid=stage-confirm-btn]');ok(`${theme} ${width} unsaved draft disables confirmation`,await confirm.isDisabled());
let confirms=0;const onRequest=req=>{if(req.method()==='POST'&&req.url().endsWith('/stages/storyboard/confirm'))confirms++};p.on('request',onRequest);
await sp.evaluate(text=>{document.querySelector('#fixture')?.remove();const e=document.createElement('button');e.id='fixture';e.className='btn primary';e.textContent=text;e.disabled=true;Object.assign(e.style,{position:'fixed',left:'100px',top:'100px'});document.body.append(e)},await confirm.innerText());
for(const state of ['disabled','enabled']){
if(state==='enabled'){
await p.locator('[data-testid=stage-save-btn]').click();await p.locator('.toast.success').waitFor();await p.waitForFunction(()=>!document.querySelector('[data-testid=stage-confirm-btn]').disabled);await sp.locator('#fixture').evaluate(e=>e.disabled=false);
ok(`${theme} ${width} save actually persists draft`,JSON.stringify(await api('/api/workbench/projects/'+proj.id)).includes('HEL776 '+theme+' '+width));
}
await p.mouse.move(0,0);await sp.mouse.move(0,0);await settled(p);const actual=await style(confirm),sample=await style(sp.locator('#fixture'));rows.push({page:'project',theme,width,kind:'primary',state,actual,sample});
for(const k of ['opacity','filter','backgroundColor','backgroundImage','color','boxShadow','borderRadius','height','paddingLeft','fontSize'])assert.equal(actual[k],sample[k],`${theme}/${width}/primary/${state}/${k}`);
if(width===1440){await confirm.screenshot({path:`${out}/closeups/${theme}-${state}-actual.png`});await sp.locator('#fixture').screenshot({path:`${out}/closeups/${theme}-${state}-sample.png`});await p.screenshot({path:`${out}/operations/${theme}-${state}.png`})}
if(state==='disabled'){
const r=await confirm.boundingBox();await p.mouse.click(r.x+r.width/2,r.y+r.height/2);await confirm.evaluate(e=>e.click());await wait(150);ok(`${theme} ${width} disabled native click sends zero requests`,confirms===0);
}
}
const hits=await p.locator('.project-footer').evaluate(e=>{const top=e.getBoundingClientRect().top;return {top,toasts:[...document.querySelectorAll('.toast')].map(t=>t.getBoundingClientRect().bottom),buttons:[...e.querySelectorAll('button')].map(b=>{const r=b.getBoundingClientRect(),hit=document.elementFromPoint(r.x+r.width/2,r.y+r.height/2);return b===hit||b.contains(hit)})}});
ok(`${theme} ${width} toast avoids footer and actions remain hittable`,hits.buttons.every(Boolean)&&hits.toasts.every(bottom=>bottom<=hits.top));
// Bound pending confirmation to verify native duplicate prevention; release to real API.
let release;const gate=new Promise(r=>release=r);await p.route('**/stages/storyboard/confirm',async r=>{await gate;await r.continue()});
const response=p.waitForResponse(r=>r.url().endsWith('/stages/storyboard/confirm')&&r.request().method()==='POST');await confirm.click();await p.locator('[data-testid=stage-confirm-btn]:disabled').waitFor();await confirm.evaluate(e=>e.click());ok(`${theme} ${width} pending confirmation sends one request`,confirms===1);release();assert((await response).ok());await p.waitForURL('**?stage=assets');p.off('request',onRequest);await p.unroute('**/stages/storyboard/confirm');
ok(`${theme} ${width} confirmation succeeds after save`,(await api('/api/workbench/projects/'+proj.id)).stages.find(s=>s.stage_key==='storyboard').status==='confirmed');
// Restore awaiting_confirm through the real draft API, never through a status fixture.
const data=(await api('/api/workbench/projects/'+proj.id)).stages.find(s=>s.stage_key==='storyboard');await api(path,{content:{...data.content,shots:data.content.shots.map((s,i)=>i?s:{...s,description:s.description+' · next'})}},'PATCH');
}
// Search + comparison focus and stable panel regression, all themes at 1440.
await p.setViewportSize({width:1440,height:900});
for(const theme of ['night','day','grade','bluehour']){
await p.goto(WEB);await p.evaluate(t=>localStorage.setItem('aigc-theme',t),theme);await p.reload();const trigger=p.locator('.studio-search');await trigger.click();await p.getByRole('dialog').waitFor();await settled(p);ok(theme+' search stable opacity',await p.locator('.modal-panel').evaluate(e=>getComputedStyle(e).opacity==='1'));await p.keyboard.press('Escape');await p.getByRole('dialog').waitFor({state:'detached'});ok(theme+' search focus restored',await trigger.evaluate(e=>e===document.activeElement));
await p.goto(url);const compare=p.getByRole('button',{name:'对比已确认版',exact:true});await compare.click();await p.getByRole('dialog').waitFor();await settled(p);ok(theme+' compare stable opacity',await p.locator('.modal-panel').evaluate(e=>getComputedStyle(e).opacity==='1'));await p.keyboard.press('Escape');await p.getByRole('dialog').waitFor({state:'detached'});ok(theme+' compare focus restored',await compare.evaluate(e=>e===document.activeElement));
}
}
// Compare each live B1/B2 control with the exact pre-repair shared CSS in the same DOM.
const old=cp.execFileSync('git',['show','930cca6:calliope-web/src/routes/app.css'],{encoding:'utf8'});
for(const route of ['/create','/workflows','/tasks','/settings','/models'])for(const theme of ['night','day','grade','bluehour']){
await p.goto(WEB+route);await p.locator('aside.sidebar').waitFor();await p.evaluate(t=>document.documentElement.dataset.theme=t,theme);await wait(600);await p.mouse.move(0,0);ok(route+' '+theme+' sidebar present',await p.locator('aside.sidebar').isVisible());
const read=()=>p.locator('.a-btn').evaluateAll(es=>es.map(e=>{const s=getComputedStyle(e);return {text:e.textContent.trim(),classes:e.className,style:Object.fromEntries(['opacity','filter','backgroundColor','backgroundImage','color','boxShadow','borderRadius','paddingLeft','height','fontSize'].map(k=>[k,s[k]]))}}));
await p.evaluate(()=>{const host=document.createElement('div');host.id='hel776-default-fixtures';for(const classes of ['primary','primary sm','secondary','secondary sm'])for(const state of ['enabled','disabled','aria-disabled']){const b=document.createElement('button');b.className='a-btn '+classes;b.textContent=classes+' '+state;if(state==='disabled')b.disabled=true;if(state==='aria-disabled')b.setAttribute('aria-disabled','true');host.append(b)}document.body.append(host)});
const actual=await read();await p.evaluate(()=>{window.hel776StateRules=[];for(const sheet of document.styleSheets){let rules;try{rules=sheet.cssRules}catch{continue}for(const r of rules)if(r.selectorText?.includes('.a-btn.primary:disabled')){window.hel776StateRules.push([r,r.style.cssText]);r.style.cssText=''}}});const oldSheet=await p.addStyleTag({content:old});await wait(200);const previous=await read();assert.deepEqual(actual,previous,route+' '+theme+' default controls');await oldSheet.evaluate(e=>e.remove());await p.evaluate(()=>{window.hel776StateRules.forEach(([r,s])=>r.style.cssText=s);document.querySelector('#hel776-default-fixtures').remove()});protections.push({route,theme,actual,previous});
}
if(process.env.HEL776_PROTECT_ONLY==='1')for(const theme of ['night','day','grade','bluehour']){
await p.goto(WEB);await p.evaluate(t=>localStorage.setItem('aigc-theme',t),theme);await p.reload();await p.locator('.studio-hero').waitFor();await settled(p);
const al=p.locator('.home .a-btn.secondary.sm').first();await sp.goto('http://127.0.0.1:'+server.address().port);await sp.evaluate(({theme,text})=>{document.documentElement.dataset.theme=theme;const e=document.createElement('button');e.className='btn sm';e.id='small';e.textContent=text;document.body.append(e)}, {theme,text:await al.innerText()});await al.screenshot({path:out+'/closeups/'+theme+'-small-actual.png'});await sp.locator('#small').screenshot({path:out+'/closeups/'+theme+'-small-sample.png'});
}
ok('no browser page errors',errors.length===0);
}finally{
fs.writeFileSync(out+(process.env.HEL776_PROTECT_ONLY==='1'?'/protection-measurements.json':'/measurements.json'),JSON.stringify(rows,null,2));fs.writeFileSync(out+(process.env.HEL776_PROTECT_ONLY==='1'?'/protection-results.json':'/results.json'),JSON.stringify({checks,errors,protections},null,2));
await c.tracing.stop({path:out+(process.env.HEL776_PROTECT_ONLY==='1'?'/protection-trace.zip':'/trace.zip')});console.log('TRACE_SAVED');
// Bound browser shutdown; always collect an exit code instead of hanging after evidence.
await Promise.race([b.close(),wait(5000).then(()=>{if(b.isConnected())throw Error('browser shutdown exceeded 5s')})]);await new Promise(r=>server.close(r));
}
})().then(()=>process.exit(0)).catch(e=>{console.error(e);process.exit(1)});
+60
View File
@@ -0,0 +1,60 @@
"""HEL-776: run the isolated stack, keep it alive for the audit script, then stop children."""
import os, signal, socket, subprocess, time, urllib.request
from pathlib import Path
root=Path(__file__).resolve().parents[1]
os.chdir(root)
(root/'e2e/shots/hel731').mkdir(parents=True,exist_ok=True)
py=os.environ.get('HEL731_PYTHON','python3')
env=os.environ.copy()
env['PYTHONPATH']=str(root/'calliope-backend/src')
for port in [8247,5173,18188,18189]:
with socket.socket() as probe:
assert probe.connect_ex(('127.0.0.1',port))!=0, f'Test port {port} is already in use'
reference=root/'e2e/shots/reference'
assert not reference.exists(), 'Refuse to overwrite existing isolation data'
processes=[];handles=[]
try:
for name,cmd in [('api',[py,'e2e/reference/server.py']),('comfy',[py,'e2e/fake_comfy.py']),('llm',[py,'e2e/reference/fake_llm.py']),('web',['npm','--prefix','calliope-web','run','dev'])]:
h=open(f'../evidence/checks/{name}.log','w');handles.append(h);processes.append(subprocess.Popen(cmd,stdout=h,stderr=subprocess.STDOUT,env=env,start_new_session=True))
for url in ['http://127.0.0.1:8247/api/health','http://127.0.0.1:5173']:
for i in range(100):
try:
urllib.request.urlopen(url,timeout=2);break
except Exception:
if any(p.poll() is not None for p in processes):raise RuntimeError('A test service failed')
if i==99:raise
time.sleep(.2)
for cmd in [[py,'e2e/seed.py'],[py,'e2e/reference/seed.py']]:subprocess.run(cmd,env=env,check=True)
# seed one project with storyboard content like hel731.cjs does
import json,urllib.request as u
def api(p,b=None,method=None):
req=u.Request('http://127.0.0.1:8247'+p,data=json.dumps(b).encode() if b is not None else None,method=method or ('POST' if b is not None else 'GET'),headers={'Content-Type':'application/json'})
return json.loads(u.urlopen(req, timeout=15).read())
proj=api('/api/projects',{'title':'隔离验证 · 海岸来信','idea':'纸船带回一片树叶'})
fixtures={'script':{'text':'第一场:清晨的海岸,女孩把一只纸船放入海水。她等候着父亲的归来。第二场:纸船带回一片树叶,女孩望向海平面,知道旅程才刚刚开始。'},
'style':{'directions':[{'id':'s1','name':'晨光','description':'暖光','prompt':'warm light'},{'id':'s2','name':'蓝调','description':'冷光','prompt':'blue hour'}]},
'storyboard':{'shots':[{'id':'board-'+str(i),'scene':'1','shot_size':'远景','camera':'固定','description':'女孩沿着海岸走向灯塔,纸船随海风起伏。','dialog':('你好' if i%2 else ''),'duration_sec':5} for i in range(12)]},
'assets':{'assets':[{'id':'asset-a','kind':'character','name':'海边女孩','description':'女孩','prompt':'girl on coast'}]},
'shot':{'shots':[{'id':'shot-a','shot_no':'S1','description':'女孩走向灯塔','prompt':'girl walks toward lighthouse','duration_sec':4}]}}
for stage,content in fixtures.items():
api(f"/api/workbench/projects/{proj['id']}/stages/{stage}",{'content':content},'PATCH')
if stage in ('script','style'):
api(f"/api/workbench/projects/{proj['id']}/stages/{stage}/confirm",({'chosen_style_id':'s1'} if stage=='style' else {}))
print('stack ready, project',proj['id'],flush=True)
Path('../evidence/checks/processes.json').write_text(json.dumps([{'pid':p.pid,'args':p.args} for p in processes],indent=2))
result=subprocess.run(['node','e2e/hel776.cjs'],env=env)
print('TEST_PROCESS_EXIT',result.returncode,flush=True)
raise SystemExit(result.returncode)
finally:
daemon=json.loads(subprocess.check_output(['multica','daemon','status','--output','json']))['pid']
assert all(p.pid != daemon for p in processes)
for p in processes:
if p.poll() is None:os.killpg(p.pid,signal.SIGTERM)
for p in processes:
try:p.wait(timeout=10)
except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
for h in handles:h.close()
import shutil
if reference.exists():shutil.rmtree(reference)
print('CLEANUP: all exact child process groups stopped; disposable reference DB removed',flush=True)