Files
aigc-home/e2e/krea-api-document.mjs
T

117 lines
14 KiB
JavaScript

// Batch164 local GET-only:230 saved/5 Notes/85 exact/2 VHS gaps/13 unknown/4 hosts.
import fs from 'node:fs';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright');
const out='.local-evidence/krea-api-document/browser';fs.mkdirSync(out,{recursive:true});
const checks=[],requests=[],errors=[],blockedFonts=[],assertionGroups={},interceptions=[];let group='aggregate';
const textRenderings=[];
function check(condition,label){assert.ok(condition,label);checks.push(label);assertionGroups[group]=(assertionGroups[group]||0)+1;console.log('PASS '+label);}
function assertLocalUrl(raw){
const u=new URL(String(raw));assert.ok(u.protocol==='http:'&&['127.0.0.1','localhost'].includes(u.hostname)&&['8247','5173'].includes(u.port)&&!u.username&&!u.password,'Refused before request: '+u);return u;
}
function localFetch(raw){assertLocalUrl(raw);return fetch(raw);}
for(const raw of ['http://6.0.0.1:8247/api/workflows','http://127.0.0.1:9999/','https://example.invalid/','http://127.0.0.1:8247@evil.invalid/']){assert.throws(()=>assertLocalUrl(raw));check(true,'URL预检拒绝且未发送 '+raw);}
for(const raw of ['http://127.0.0.1:8247/api/workflows','http://127.0.0.1:5173/connections'])assertLocalUrl(raw);
const browser=await chromium.launch({headless:true,executablePath:process.env.BROWSER_EXECUTABLE});
try {
const page=await browser.newPage({viewport:{width:1440,height:1000}});
await page.routeWebSocket('**/*',ws=>{ws.close();}); // No HMR socket transport is needed for read-only checks.
await page.route('**/*',route=>{
const u=new URL(route.request().url());
if(u.hostname==='fonts.googleapis.com'){blockedFonts.push(String(u));return route.fulfill({contentType:'text/css',body:''});}
try{assertLocalUrl(u);}catch(e){errors.push(String(e));return route.abort();}
if(route.request().method()!=='GET'||u.pathname==='/api/view'||(/\.(mp4|png|wav|mp3|webm)$/i.test(u.pathname)&&u.pathname!=='/favicon.png')){errors.push('Forbidden request '+u);return route.abort();}
return route.continue();
});
page.on('request',r=>{if(r.url().includes('/api/'))requests.push({method:r.method(),url:r.url()});});
page.on('pageerror',e=>errors.push(e.message));
requests.push({method:'GET',url:'http://127.0.0.1:8247/api/workflows'});
const records=await(await localFetch('http://127.0.0.1:8247/api/workflows')).json();
const reviews=JSON.parse(fs.readFileSync('calliope-backend/src/calliope/comfyui/source_reviews.json'));
const path='example_ComfyUI_workflows/Krea2_t2i_20260818_API.json';
const paths=[path,...Object.keys(reviews).filter(p=>p!==path&&reviews[p].fixed_version_document)];
const details=[];let actualGetRaw;
for(const p of paths){const r=records.find(r=>r.source_repo_path===p);assert.ok(r,p);const url=`http://127.0.0.1:8247/api/workflows/${r.id}`;requests.push({method:'GET',url});const raw=await(await localFetch(url)).text();const d=JSON.parse(raw);details.push(d);assert.deepEqual(d.doc_json.fixed_version,{...reviews[p].fixed_version_document,matched:true});if(p===path)actualGetRaw=raw;}
check(details.length===146&&details.reduce((n,d)=>n+d.doc_json.fixed_version.fields.length,0)===10257,'146参考/10257保存项');
check(details.slice(1).reduce((n,d)=>n+(d.doc_json.source_notes?.length||0),0)===287,'旧145/287注释摘要冻结');
const original=JSON.parse(fs.readFileSync(path));
const audit=JSON.parse(fs.readFileSync('docs/hel-892/krea-api-document-evidence/original-audit.json'));
fs.writeFileSync(out+'/actual-get.json',actualGetRaw);
const isolated=JSON.parse(fs.readFileSync('docs/hel-892/krea-api-document-evidence/actual-Krea2_t2i_20260818_API.json'));
assert.deepEqual(details[0].doc_json,isolated);check(true,'actual GET=隔离doc JSON内容/解析类型,不称HTTP原字节');
await page.goto(assertLocalUrl('http://127.0.0.1:5173/connections').href,{waitUntil:'networkidle'});
const dialog=page.getByRole('dialog',{name:'工作流说明'});
const fixedCard=dialog.locator('.card').filter({has:page.getByText('固定版本参数说明',{exact:true})});
async function begin(name){const row=page.locator('.wf-row').filter({has:page.getByText(name,{exact:true})}).first();const button=row.getByRole('button',{name:'说明',exact:true});await button.focus();await page.keyboard.press('Enter');return button;}
async function loaded(){await dialog.getByText('用途与来源',{exact:true}).waitFor();await dialog.evaluate(el=>Promise.all(el.getAnimations().map(a=>a.finished)));}
async function shot(name,locator){if(locator){await locator.evaluate(el=>el.scrollIntoView({block:'start'}));await dialog.locator('.drawer-body').evaluate(el=>el.scrollTop=Math.max(0,el.scrollTop-60));}await page.screenshot({path:out+'/'+name+'.png'});}
for(const width of [1440,390]){
await page.setViewportSize({width,height:width===390?844:1000});
for(const d of details){
group=d===details[0]?'new_API':'old_145';const b=d.doc_json.fixed_version,button=await begin(d.name);await loaded();
check((await dialog.innerText()).includes(b.user_overview),`${width}/${d.id}中文用途`);
check(await fixedCard.locator('[data-fixed-field]').count()===b.fields.length,`${width}/${d.id}字段数保持`);
check(!d.is_enabled&&!d.doc_completed_at&&!d.exec_verified_at,`${width}/${d.id}资格关闭/时间空`);
check(await dialog.locator('.drawer-body').evaluate(el=>el.scrollWidth<=el.clientWidth),`${width}/${d.id}无溢出`);
if(d!==details[0]){await page.keyboard.press('Escape');await dialog.waitFor({state:'hidden'});check(await button.evaluate(el=>el===document.activeElement),`${width}/${d.id}旧摘要关闭焦点`);continue;}
await shot(width+'-default');
check(b.sources.length===0&&b.comments.length===0&&b.node_bindings.length===24&&b.node_bindings.every(n=>!n.implementation_verified&&n.scope==='root'),`${width}24root未知/零准确来源/零Note`);
check(Object.values(original).every(n=>Object.keys(n).sort().join(',')==='_meta,class_type,inputs'),`${width}原件无version/mode/widgets/画布/子图`);
await dialog.getByText('核对范围与来源依据',{exact:true}).click();
const flowText=await fixedCard.innerText();
for(const line of b.flow)check(flowText.includes(line),`${width}原流程/标题/引用 ${b.flow.indexOf(line)}`);
for(const e of b.api_references){assert.deepEqual(original[e.target_node_id].inputs[e.input_name],e.original);check(e.output_index===0&&e.original.length===2,`${width}原34引用 ${e.pointer}`);}
for(const i of [0,1,2,3,4,5,7,8,9])await shot(width+'-flow-'+i,fixedCard.getByText(b.flow[i],{exact:true}));
for(const f of b.fields){
assert.deepEqual(original[f.node_id].inputs[f.field],f.value);check(f.pointer===`/${f.node_id}/inputs/${f.field}`&&!('named_pointer'in f)&&!('named_value'in f)&&!('widget_index'in f),`${width}唯一原具名指针 ${f.pointer}`);
const summary=fixedCard.locator(`details[data-fixed-field="${f.pointer}"] > summary`);await summary.focus();await page.keyboard.press('Enter');const box=summary.locator('..');
check(await box.evaluate(el=>el.open),`${width}/${f.pointer}键盘展开`);
const rendered=await box.locator(':scope > pre').textContent();
if(typeof f.value==='string')assert.equal(rendered,f.value);else assert.deepEqual(JSON.parse(rendered),f.value);
check(true,`${width}/${f.pointer}DOM原串或解析值/类型`);
const text=await box.innerText();check(text.includes(f.effect)&&text.includes(f.schema_default)&&text.includes(f.unit)&&text.includes(f.execution_note),`${width}/${f.pointer}实现/单位/范围未知`);
await box.getByText('来源依据',{exact:true}).click();check((await box.innerText()).includes(f.pointer)&&(await box.innerText()).includes(f.json_type),`${width}/${f.pointer}指针/类型可见`);
check(await dialog.locator('.drawer-body').evaluate(el=>el.scrollWidth<=el.clientWidth),`${width}/${f.pointer}展开无溢出`);
if(audit.strings.some(s=>s.node_id===f.node_id)&&f.field==='value'){
const a=audit.strings.find(s=>s.node_id===f.node_id),hash=crypto.createHash('sha256').update(rendered).digest('hex');check(hash===a.sha256&&Array.from(rendered).length===a.characters&&rendered.split('\n').length-1===a.LF&&rendered.endsWith('\n')===a.tail_LF,`${width}/${f.node_id}完整英文/前空格/尾LF/SHA`);textRenderings.push({viewport:width,node_id:f.node_id,raw_decoded_sha256:hash,dom_utf8_sha256:hash,report_json_value_sha256:crypto.createHash('sha256').update(JSON.stringify(f.value)).digest('hex')});await shot(width+'-text-'+f.node_id.replaceAll(':','_'),summary);
}
if(['152.lora_name','146.seed','172.denoise','171:153.sampling_mode.temperature','160.value','161.value','171:154.delimiter','171:162.delimiter'].includes(f.node_id+'.'+f.field))await shot(width+'-field-'+f.node_id.replaceAll(':','_')+'-'+f.field,summary);
await summary.click();
}
check(await dialog.locator('img,canvas,video,audio,iframe').count()===0,`${width}纯文本不加载媒体`);
await dialog.getByRole('button',{name:'关闭',exact:true}).focus();await page.keyboard.press('Tab');check(await dialog.evaluate(el=>el.contains(document.activeElement)),`${width}Tab焦点保留`);await page.keyboard.press('Shift+Tab');check(await dialog.evaluate(el=>el.contains(document.activeElement)),`${width}ShiftTab焦点保留`);
await page.keyboard.press('Escape');await dialog.waitFor({state:'hidden'});check(await button.evaluate(el=>el===document.activeElement),`${width}新API归还焦点`);
}
}
group='shared_regressions';
for(const name of ['旧工作流回退(隔离测试夹具)','空说明回退(隔离测试夹具)']){await begin(name);await loaded();check((await dialog.innerText()).includes('隔离库旧条目回退测试'),'旧/空说明回退 '+name);await page.keyboard.press('Escape');}
// Missing summary and mismatched bindings are tested with local GET fixtures, without writes.
for(const variant of ['missing-overview','mismatched','html-summary']){
const d=structuredClone(details[0]);
if(variant==='missing-overview')delete d.doc_json.fixed_version.user_overview;
if(variant==='mismatched')d.doc_json.fixed_version={matched:false,notice:'固定版本参数说明待核对:源文件、声明版本或说明依据未匹配,未采用旧定义。'};
if(variant==='html-summary')d.doc_json.fixed_version.user_overview='<img src="https://example.invalid/forbidden">仅纯文本';
await page.route(`**/api/workflows/${d.id}`,route=>{interceptions.push({variant,url:route.request().url()});return route.fulfill({json:d});});
const responseReady=page.waitForResponse(r=>new URL(r.url()).pathname===`/api/workflows/${d.id}`&&r.status()===200);
await begin(d.name);const fixtureResponse=await responseReady;await fixtureResponse.finished();
const returned=await fixtureResponse.json();assert.deepEqual(returned,d);
const expectedSummary=variant==='missing-overview'?'这张图的用途和操作重点可在下方使用步骤中查看;目标环境与实际效果仍待核对。':variant==='mismatched'?d.doc_json.fixed_version.notice:d.doc_json.fixed_version.user_overview;
await dialog.getByText(expectedSummary,{exact:true}).waitFor({timeout:20000});await loaded();
if(variant==='missing-overview')check((await dialog.innerText()).includes('这张图的用途和操作重点可在下方使用步骤中查看;目标环境与实际效果仍待核对。'),'缺摘要自然中文回退');
if(variant==='mismatched')check((await dialog.innerText()).includes(d.doc_json.fixed_version.notice)&&!await dialog.getByText('核对范围与来源依据',{exact:true}).count(),'错绑定提示明确且不展示旧字段');
if(variant==='html-summary')check((await dialog.innerText()).includes(d.doc_json.fixed_version.user_overview)&&await dialog.locator('img').count()===0,'摘要HTML仅纯文本不创建图像或请求');
check(!(await dialog.innerText()).includes('undefined'),'回退不暴露undefined');await page.keyboard.press('Escape');await page.unroute(`**/api/workflows/${d.id}`);
}
let release,entered,delivered;const hold=new Promise(r=>release=r),intercept=new Promise(r=>entered=r),done=new Promise(r=>delivered=r);
await page.route(`**/api/workflows/${details[0].id}`,async route=>{interceptions.push({variant:"late",url:route.request().url()});entered();await hold;await route.fulfill({json:details[0]});delivered();});
await begin(details[0].name);await intercept;await page.keyboard.press('Escape');await begin(details[1].name);await loaded();release();await done;
check((await dialog.innerText()).includes(details[1].doc_json.fixed_version.user_overview)&&await fixedCard.locator('summary').filter({hasText:/^节点 [\d:]+ · /}).count()===details[1].doc_json.fixed_version.fields.length,'迟到新图响应不覆盖旧图摘要/字段');await page.keyboard.press('Escape');await page.unroute(`**/api/workflows/${details[0].id}`);
await page.route(`**/api/workflows/${details[0].id}`,route=>{interceptions.push({variant:'failure',url:route.request().url()});return route.fulfill({status:500,json:{detail:'隔离失败夹具'}});});await begin(details[0].name);await dialog.getByRole('alert').waitFor({timeout:20000});check(await dialog.getByRole('button',{name:'重试',exact:true}).isVisible(),'GET失败显示重试');check(await dialog.getByText('用途与来源',{exact:true}).count()===0,'读取失败隐藏旧摘要');await page.unroute(`**/api/workflows/${details[0].id}`);await dialog.getByRole('button',{name:'重试',exact:true}).click();await loaded();check((await dialog.innerText()).includes(details[0].doc_json.fixed_version.user_overview),'重试恢复摘要');await page.keyboard.press('Escape');
check(errors.length===0,'无脚本错误或禁止请求 '+JSON.stringify(errors));check(requests.every(r=>r.method==='GET'&&new URL(r.url).hostname==='127.0.0.1'&&!r.url.includes('/api/view')),'全程本地GET无写/生成/目标/历史预览请求');
const polling=requests.filter(r=>['/api/jobs','/api/events'].includes(new URL(r.url).pathname));
const fixed=requests.filter(r=>!polling.includes(r));
const frequencies=rs=>Object.fromEntries([...new Set(rs.map(r=>new URL(r.url).pathname))].sort().map(p=>[p,rs.filter(r=>new URL(r.url).pathname===p).length]));
fs.writeFileSync(`${out}/browser-results.json`,JSON.stringify({request_accounting:{fixed_count:fixed.length,fixed_paths:frequencies(fixed),polling_count:polling.length,polling_paths:frequencies(polling),polling_tolerance:1,reason:'固定请求逐路径核账;events零差额,只允许已证末次jobs至多1差额;禁止请求零容忍。'},assertion_count:checks.length,assertionGroups,text_renderings:textRenderings,interceptions,checks,requests,errors,blockedFonts,viewports:[1440,390]},null,2));
} finally {await browser.close();}