gongxiangp2/apps/detail-agent-pi/test/screen-review.test.mjs

721 lines
40 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { validateToolArguments } from '@earendil-works/pi-ai';
import { createAssistantMessageEventStream } from '@earendil-works/pi-ai/compat';
import { activityToolLabel, toolActivity } from '../src/activity-event.mjs';
import { completeCanvas, openAgent } from './fake-canvas.mjs';
import { openProductionOperations, productionOperationTools } from '../src/production-operations.mjs';
import { callProductionTool, closeProductionTurn } from '../src/production-goal.mjs';
import { screenReviewScope } from '../src/screen-review.mjs';
import { ProjectStore } from '../src/store.mjs';
import { WORKER_TURN_LIMIT } from '../src/worker-receipts.mjs';
import { cleanup } from './cleanup.mjs';
import { productionStore } from './production-store-fixture.mjs';
import { summarizeImageWait } from '../src/image-wait-summary.mjs';
const outputId='detail', variantId='oak';
const pixels={type:'image',mimeType:'image/png',
data:'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACklEQVR4nGMAAQAABQABDQottAAAAABJRU5ErkJggg=='};
const pass={verdict:'pass',summary:'商品纹理与文案相符,标注贴合。',imageIssues:[],overlayFixes:[],copyFixes:[]};
const needsFix={
verdict:'needs_fix',summary:'换图后侧边标注仍指向旧结构。',
imageIssues:[{slotId:'slot-2',location:'右侧图位',issue:'裁切隐藏扶手端点',suggestion:'从同款实拍扩大取景'}],
overlayFixes:[{nativeLayerId:202,issue:'尺寸引线与椅背分离',suggestion:'把引线端点移到椅背上沿'}],
copyFixes:[{field:'title-2',issue:'文案把涂装当成木种',suggestion:'改成橡胶木深木色涂装'}],
};
test('waiting returns a bounded mix of pending work, candidates and screen findings',()=>{
const long='需要修改当前画面。'.repeat(1000);
const generation=Array.from({length:100},(_,i)=>({slotId:'slot-'+i,candidateId:'candidate-'+i,
phase:'complete',target:{fieldId:'D01',width:2400,height:1200,aspectRatio:'2:1'},
generationEvidence:{prompt:long,actualPixels:{width:2048,height:1024},actualRatio:'2048:1024'}}));
const checks=generation.map(row=>({...row,verdict:'revise',reason:long}));
const screenChecks=Array.from({length:50},(_,i)=>({page:i+1,...needsFix,summary:long,fieldRequirements:[long]}));
const pendingWork=[{slotId:'slot-live',stage:'checking'}];
const summary=summarizeImageWait({outputId,variantId,generation,checks,screenChecks,pendingWork});
assert.ok(JSON.stringify(summary).length<=10_000);
assert.equal(summary.pendingWork[0].slotId,'slot-live');
assert.equal(summary.generation[0].candidateId,'candidate-0');
assert.deepEqual(summary.generation[0].target,generation[0].target);
assert.deepEqual(summary.generation[0].actualPixels,{width:2048,height:1024});
assert.equal(summary.generation[0].actualRatio,'2048:1024');
assert.equal(summary.checks[0].verdict,'revise');
assert.equal(summary.screenChecks[0].imageIssues[0].suggestion,needsFix.imageIssues[0].suggestion);
assert.ok(summary.omitted.generation>0);
});
async function usePiWorker(t,host,name,reply) {
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-worker-receipt-'));
const scope='a'.repeat(64);
const store=await ProjectStore.open(dir,{scope,project:randomUUID()},{brandId:'qa',shopId:'qa',categoryId:'qa',
platform:'qa',version:'1',source:'worker-receipt-test',rules:['仅使用离线夹具']});
const writes=[];
const appendEvent=store.appendEvent.bind(store);
store.appendEvent=event=>{
const write=appendEvent(event);
writes.push(write);
return write;
};
let calls=0;
const sdk=await openAgent({store,transport:{info:{accountScope:scope,model:{id:'qa-model',protocol:'openai-chat'}},
stream(model,context){
assert.ok(++calls<=WORKER_TURN_LIMIT,'Pi attempted another request after exhausting the worker budget');
const args=reply(calls,context.messages.findLast(message=>message.role==='toolResult'));
const content=[{type:'toolCall',name,id:`submit-${calls}`,arguments:args}];
const output=createAssistantMessageEventStream();
const message={role:'assistant',api:model.api,provider:model.provider,model:model.id,content,stopReason:'toolUse',
timestamp:Date.now(),usage:{input:1,output:1,cacheRead:0,cacheWrite:0,totalTokens:2,
cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}};
queueMicrotask(()=>{
output.push({type:'start',partial:message});
output.push({type:'done',reason:'toolUse',message});
output.end(message);
});
return output;
},
}});
t.after(async()=>{await sdk.dispose();await cleanup(dir);});
host.runDetailAgent=sdk.runDetailAgent;
return {calls:()=>calls,async events(){
await Promise.all(writes);
return (await fs.readFile(path.join(store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(line=>JSON.parse(line));
}};
}
async function fixture(t) {
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-screen-review-'));
t.after(()=>cleanup(dir));
const store=productionStore(dir);
const pages=Array.from({length:18},(_,i)=>`P${i+1}`);
const fields=pages.map((page,i)=>({page,layer:100+i,field:`title-${i+1}`,currentText:'橡胶木桌面'}));
const slots=pages.map((documentId,i)=>({documentId,id:`slot-${i+1}`,fieldId:`pic-${i+1}`,selectedCandidateId:'candidate'}));
const state={revision:7,overlay:true,reads:[],referenceReads:0,colorName:'深木色',slotImageFacts:undefined,
fingerprints:pages.map(page=>`screen-${page}`)};
const summaryFor=(reviews=[])=>({
screensWithOpenIssues:reviews.filter(row=>row.issues?.length&&row.screenFingerprint===state.fingerprints[row.page-1]),
revision:state.revision,
unreviewedScreens:pages.flatMap((pageId,index)=>reviews.some(row=>
row.page===index+1&&row.screenFingerprint===state.fingerprints[index])?[]:[{page:index+1,pageId}]),
screensReadyForReview:pages.flatMap((pageId,index)=>{
const members=slots.filter(slot=>slot.documentId===pageId);
return members.length>1&&members.every(slot=>slot.selectedCandidateId)&&
!reviews.some(row=>row.page===index+1&&row.screenFingerprint===state.fingerprints[index])
?[{page:index+1,name:'细节屏'}]:[];
}),
});
const canvas={
imageRequest:async()=>[],
workflowRead:async()=>({available:true,canvasFirst:true,version:1,outputId,productVariantId:variantId,
revisions:{canvas:state.revision,creation:1},template:{contentHash:'template'},totalSlots:slots.length,slots,
productEvidence:{brief:{name:'木椅',variants:[{id:variantId,colorName:state.colorName}]}}}),
detailCopyFields:async({screenFingerprintPage,screenReviewFingerprints}={})=>({
revision:state.revision,pages,fields,screenFingerprint:state.fingerprints[screenFingerprintPage],
...(screenReviewFingerprints?{progressSummary:summaryFor(screenReviewFingerprints)}:null),
}),
detailCandidateScreen:async({slotId,candidateId})=>{
const page=slots.findIndex(slot=>slot.id===slotId);
return {page,slotId,candidateId,screenFingerprint:state.fingerprints[page],imageSlots:[slotId],
copyFields:fields.filter(field=>field.page===pages[page]),overlayLayers:[],images:[pixels]};
},
detailRender:async({page})=>{
state.reads.push(page);
if(page>=pages.length)throw Error('此屏不属于当前工作画布');
return {page,revision:state.revision,screenFingerprint:state.fingerprints[page],images:[pixels],fields:[slots[page].fieldId],
textClipping:[{nativeLayerId:600+page,clippedInkBounds:[[100,20,7,14]]}],
slotImageFacts:state.slotImageFacts,
textLayers:[{nativeLayerId:700+page,styleDifferences:{fillColor:{template:'#ffffff',current:'#333333'}},
readability:{contrastP10:1.4,contrastP50:2.1},templateReadability:{contrastP10:3.2,contrastP50:4.6}}],
annotationLayout:{lines:[{nativeLayerId:501+page,endpoints:[[10,20],[10,80]]}]},
...(state.overlay?{overlayLayers:[{nativeLayerId:201+page,name:'尺寸标注',text:'45cm',overlapsSlots:[slots[page].fieldId],group:{id:900+page,name:'尺寸组'}},
{nativeLayerId:301+page,name:'尺寸线',overlapsSlots:[slots[page].fieldId],group:{id:900+page,name:'尺寸组'}},
{nativeLayerId:401+page,name:'旧尺寸',text:'旧尺寸',overlapsSlots:[],
belowSlot:[{fieldId:slots[page].fieldId,coverage:1,opacity:0.5,blendMode:'Normal'}]}]}:null)};
},
detailImages:async(_slot,_candidate,options)=>{
assert.equal(options.includeTemplateReference,false);
state.referenceReads++;
return {referenceCount:1,images:[pixels]};
},
read:async()=>({revision:state.revision}),delta:async()=>{},
};
const host={canvas:completeCanvas(canvas),store,productionGoal:{outputId,variantId}};
const actions=await openProductionOperations(host);
host.productionWork=new Map([[JSON.stringify([outputId,variantId]),Promise.resolve(actions)]]);
return {host,actions,state,slots,summaryFor,journal:()=>store.ledger(outputId,variantId).read()};
}
test('候选原图与整屏一起验,采纳匹配指纹后直接沿用错位结论', async t=>{
const {host,actions,state,slots,journal}=await fixture(t);
const candidateId=randomUUID();
const composite={...pixels,data:'composite'};
const screenReview={
...needsFix,imageIssues:[],copyFixes:[{...needsFix.copyFixes[0],field:'title-1'}],
overlayFixes:[{nativeLayerId:201,issue:'右侧尺寸线离开椅腿',suggestion:'将尺寸线端点移到椅腿外沿'}],
};
host.canvas.detailCandidateScreen=async request=>{
assert.equal(request.candidateId,candidateId);
assert.equal(request.fit,'contain');
return {page:0,pageName:'整张 SKU 卡',slotId:'slot-1',candidateId,fit:request.fit,
screenFingerprint:'composed-candidate',imageSlots:['slot-1'],images:[composite],
overlayLayers:[{nativeLayerId:201,name:'右侧尺寸线'}],
copyFields:[{page:'P1',field:'title-1',currentText:'82 CM'}]};
};
host.canvas.detailImages=async(_slot,id,options)=>{
assert.equal(id,candidateId);
assert.equal(options.candidatePixels,true);
return {candidateId,referenceCount:1,images:[pixels,pixels]};
};
host.canvas.requestWrite=async revision=>({allowed:true,revision});
host.canvas.workflowExecute=async({operationId,candidateId,fit})=>{
slots[0].selectedCandidateId=candidateId;
state.fingerprints[0]=fit==='contain'?'composed-candidate':'different-fit';
state.revision++;
return {operationId,candidateId,phase:'submitted'};
};
host.canvas.workflowPoll=async operationId=>({operationId,candidateId,phase:'complete'});
let reviews=0;
host.runDetailAgent=async(_slot,system,input,[tool],images,_scope,captions)=>{
reviews++;
assert.match(system,/按项目锁定的企业 Skill 及小壹补充验图/);
assert.deepEqual(captions,['受审候选原图','候选放入后的整屏合成','同款实拍 P01']);
assert.deepEqual(images,[pixels,composite,pixels]);
const {composite:screen}=JSON.parse(input);
assert.equal(screen.page,1);
assert.equal(screen.overlayLayers[0].nativeLayerId,201);
assert.equal(screen.screenCopy[0].field,'title-1');
const response={candidateId,verdict:'revise',reason:'尺寸线需要对位',
checks:{structure:true,color:true,composition:false,evidence:true},
screenSummary:screenReview.summary,overlayFixes:screenReview.overlayFixes,copyFixes:screenReview.copyFixes};
assert.deepEqual(tool.prepareArguments(response),response);
tool.execute('',response);
};
const [review]=await actions.check_image_slots({candidates:[{slotId:'slot-1',candidateId,fit:'contain'}],wait:true});
assert.deepEqual(review.observation.screenReview.overlayFixes,screenReview.overlayFixes);
const changed=await actions.adopt_production_image({slotId:'slot-1',candidateId,fit:'cover'});
assert.equal(changed.screenReview,undefined);
assert.equal(journal().screenReviews,undefined);
const adopted=await actions.adopt_production_image({slotId:'slot-1',candidateId,fit:'contain'});
assert.equal(adopted.screenReview.screenFingerprint,'composed-candidate');
assert.deepEqual(journal().screenReviews[0][1].issues,
[{nativeLayerId:201,issue:'右侧尺寸线离开椅腿',suggestion:'将尺寸线端点移到椅腿外沿'},
{field:'title-1',issue:'文案把涂装当成木种',suggestion:'改成橡胶木深木色涂装'}]);
const [again]=await actions.check_output_screens({pages:[1]});
assert.equal(again.reused,true);
assert.equal(reviews,1);
});
test('同屏同商品资料复用整屏助手的完整回执,屏指纹或资料变化时重新复核', async t=>{
const {host,actions,state}=await fixture(t);
let reviews=0;
host.runDetailAgent=async(_id,_system,_prompt,[tool])=>{
reviews++;
await tool.execute('',pass);
};
const check=async()=> (await actions.check_output_screens({pages:[0,1]}))[0];
const first=await check();
assert.equal(first.verdict,'pass');
assert.equal(first.page,1);
assert.deepEqual(await actions.read_screen_review({page:0}),await actions.read_screen_review({page:1}));
assert.equal(first.reviewRound,1);
assert.deepEqual(first.issueHistory,[]);
state.revision++;
assert.deepEqual(await check(),{...first,revision:state.revision,reused:true});
assert.equal(reviews,1);
assert.deepEqual(state.reads,[0,0]);
assert.equal(state.referenceReads,1);
state.fingerprints[0]='changed';
assert.equal((await check()).screenFingerprint,'changed');
assert.equal(reviews,2);
state.colorName='浅木色';
const third=await check();
assert.equal(third.reused,true);
assert.equal(third.reviewRound,2);
assert.deepEqual(third.issueHistory,[0]);
const screen=await actions.read_output_screen({page:0});
assert.equal(screen.details.reviewRound,2);
assert.deepEqual(screen.details.issueHistory,[0]);
assert.equal(reviews,2);
await actions.close();
});
test('其它成品采用图变化时,整屏复核使用最新相似度', async t=>{
const {host,actions,state}=await fixture(t);
const distances=[];
host.runDetailAgent=async(_id,_system,input,[tool])=>{
distances.push(JSON.parse(input).slotImageFacts[0].nearest[0].distance);
await tool.execute('',pass);
};
const check=async()=> (await actions.check_output_screens({pages:[1]}))[0];
state.slotImageFacts=[{slotId:'slot-1',nearest:[{slotId:'main-1',sameOutput:false,distance:22}]}];
assert.equal((await check()).verdict,'pass');
assert.equal((await check()).reused,true);
state.slotImageFacts=[{slotId:'slot-1',nearest:[{slotId:'main-1',sameOutput:false,distance:4}]}];
assert.equal((await check()).reused,undefined);
assert.deepEqual(distances,[22,4]);
await actions.close();
});
test('多图位屏齐备后在采纳与验图回执提示,当前画面复核后清除提示', async t=>{
const {host,actions,state,slots}=await fixture(t);
slots[1].documentId='P1';
slots[1].selectedCandidateId=undefined;
const current=await openProductionOperations(host);
assert.deepEqual((await current.review_image_slots({})).screensReadyForReview,[]);
host.canvas.requestWrite=async revision=>({allowed:true,revision});
host.canvas.workflowExecute=async({operationId,candidateId})=>{
slots[1].selectedCandidateId=candidateId;
return {operationId,candidateId,phase:'submitted'};
};
host.canvas.workflowPoll=async operationId=>({operationId,candidateId:'second',phase:'complete'});
const ready=[{page:1,name:'细节屏'}];
const adoption=await current.adopt_production_image({slotId:'slot-2',candidateId:'second'});
assert.deepEqual(adoption.screensReadyForReview,ready);
assert.deepEqual((await current.review_image_slots({})).screensReadyForReview,ready);
host.runDetailAgent=async(_id,_system,_prompt,[tool])=>tool.execute('',pass);
assert.equal((await current.check_output_screens({pages:[1]}))[0].verdict,'pass');
assert.deepEqual((await current.review_image_slots({})).screensReadyForReview,[]);
state.fingerprints[0]='updated';
assert.deepEqual((await current.review_image_slots({})).screensReadyForReview,ready);
await current.close();
await actions.close();
});
test('非当前成品的候选等待验图时直接读取其已保存画布', {timeout:5000}, async t=>{
const {host,actions}=await fixture(t);
const candidateId=randomUUID();
const target={outputId,variantId};
host.canvas.detailHistory=host.canvas.workflowRead;
await actions.suspendCanvas();
host.canvas.detailCandidateScreen=async(request,_signal,scope)=>{
assert.deepEqual(scope,target);
return {...request,page:0,pageName:'首屏',screenFingerprint:'saved',imageSlots:['slot-1'],
images:[pixels],overlayLayers:[],copyFields:[]};
};
host.canvas.detailImages=async(_slot,_candidate,options)=>{
assert.deepEqual(options.targetOutput,target);
return {candidateId,adopted:options.adopted,referenceCount:1,images:[pixels,pixels]};
};
host.runDetailAgent=async(_slot,_system,_input,[tool],images)=>{
assert.equal(images.length,3);
tool.execute('',{candidateId,verdict:'pass',reason:'图文相符',
checks:{structure:true,color:true,composition:true,evidence:true},screenReview:pass});
};
const [review]=await actions.check_image_slots({candidates:[{slotId:'slot-1',candidateId}],wait:true});
assert.equal(review.observation.screenReview.screenFingerprint,'saved');
const [adopted]=await actions.check_image_slots({candidates:[{slotId:'slot-1',candidateId,adopted:true}],wait:true});
assert.equal(adopted.verdict,'pass',JSON.stringify(adopted));
assert.equal(adopted.observation.adoptedCanvas,true);
await actions.close();
});
test('合法图位无法合成预览时仍核对候选原图与实拍,整屏保持待验',async t=>{
const {host,actions,state,slots,journal}=await fixture(t);
const candidateId=randomUUID();
slots[0]={...slots[0],id:'live-slot',fieldId:'D01'};
state.revision++;
host.canvas.detailCandidateScreen=async({slotId},_signal,target)=>{
assert.equal(slotId,'live-slot');
assert.equal(target,undefined);
throw Error('候选图位不是智能图层');
};
host.canvas.detailImages=async(slotId,id)=>{
assert.equal(slotId,'live-slot');
return {candidateId:id,referenceCount:1,images:[pixels,pixels]};
};
host.runDetailAgent=async(_slot,_system,input,[tool],images)=>{
assert.equal(JSON.parse(input).composite,undefined);
assert.equal(images.length,2);
tool.execute('',{candidateId,verdict:'pass',reason:'候选与实拍结构一致',screenVerdict:'pass'});
};
const [review]=await actions.check_image_slots({candidates:[{slotId:'D01',candidateId}],wait:true});
assert.equal(review.verdict,'pass');
assert.match(review.screenNotice,/效果待复核/);
assert.equal(review.observation.screenReview,undefined);
assert.equal(journal().screenReviews?.length??0,0);
await actions.close();
});
test('跨成品整屏复核自动打开目标画布',async t=>{
const {host,state}=await fixture(t);
t.after(()=>closeProductionTurn(host));
const detail={outputId,variantId};
const sku={outputId:'sku_images',variantId:'white'};
host.productionGoal.requestedOutputs=[detail,sku];
host.bindGoalRequestScope=()=>{};
host.canvas.productionOutput=detail;
const workflowRead=host.canvas.workflowRead;
host.canvas.openProductionOutput=async args=>{
assert.deepEqual(args,sku);
assert.deepEqual(state.reads,[]);
host.canvas.productionOutput=sku;
return sku;
};
// The genuine bridge completes the previous save before returning the new binding.
host.canvas.workflowRead=async args=>args.outputId===detail.outputId?workflowRead(args):
{...await workflowRead(args),outputId:sku.outputId,productVariantId:sku.variantId};
host.runDetailAgent=async(_id,_system,_input,[tool],_images,scope)=>{
assert.equal(scope,screenReviewScope(sku.variantId,sku.outputId,1));
tool.execute('',pass);
};
const [reply]=await callProductionTool(host,'check_output_screens',{outputId:sku.outputId,pages:[1]});
assert.equal(reply.verdict,'pass');
assert.equal(host.canvas.productionOutput,sku);
assert.deepEqual(state.reads,[0]);
});
test('screen reviews keep images in the worker and persist findings and passes',async t=>{
const {host,state,journal}=await fixture(t);
state.slotImageFacts=[{slotId:'slot', source:{kind:'generation',requestId:'request'},nearest:[],nearWhiteFlatRatio:0.2,templateNearWhiteFlatRatio:0.1}];
host.runDetailAgent=async(_id,system,input,[tool],images,scope)=>{
const {page,revision,product,overlayLayers,overlayGroups,screenCopy,slots,annotationLayout,textClipping,textLayers,slotImageFacts}=JSON.parse(input);
assert.deepEqual(slotImageFacts,state.slotImageFacts);
assert.deepEqual(textClipping,[{nativeLayerId:599+page,clippedInkBounds:[[100,20,7,14]]}]);
assert.deepEqual(textLayers.map(row=>[row.nativeLayerId,row.styleDifferences.fillColor.current]),[[699+page,'#333333']]);
assert.deepEqual(annotationLayout.lines,[{nativeLayerId:500+page,endpoints:[[10,20],[10,80]]}]);
assert.equal(scope,screenReviewScope(variantId,outputId,page));
assert.match(scope,/^product\/review\/[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/);
assert.equal(revision,7);
assert.equal(product.variant.colorName,'深木色');
assert.deepEqual(overlayLayers[0],{nativeLayerId:200+page,name:'尺寸标注',text:'45cm',overlapsSlots:[slots[0].fieldId],
group:{id:899+page,name:'尺寸组'}});
assert.deepEqual(overlayGroups,[{id:899+page,memberIds:[200+page,300+page]}]);
assert.deepEqual(overlayLayers[2].belowSlot,[{fieldId:slots[0].fieldId,coverage:1,opacity:0.5,blendMode:'Normal'}]);
assert.equal(screenCopy[0].field,`title-${page}`);
assert.equal(slots[0].id,`slot-${page}`);
assert.deepEqual(images,[pixels,pixels]);
assert.match(system,/overlayLayers 中的 nativeLayerId/);
assert.equal(tool.execute('',page===1?pass:{...needsFix,
imageIssues:needsFix.imageIssues.map(issue=>({...issue,slotId:slots[0].id})),
overlayFixes:needsFix.overlayFixes.map(fix=>({...fix,nativeLayerId:200+page})),
copyFixes:needsFix.copyFixes.map(fix=>({...fix,field:`title-${page}`}))}).terminate,true);
};
const receipts=await callProductionTool(host,'check_output_screens',{pages:[1,2,2,17,19]});
assert.deepEqual(receipts,[
{page:1,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P1',templateStyle:null,...pass},{page:2,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P2',templateStyle:null,...needsFix},
{page:17,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P17',templateStyle:null,...needsFix,imageIssues:[{...needsFix.imageIssues[0],slotId:'slot-17'}],
overlayFixes:[{...needsFix.overlayFixes[0],nativeLayerId:217}],copyFixes:[{...needsFix.copyFixes[0],field:'title-17'}]},{page:19,error:'此屏不属于当前工作画布'},
]);
assert.deepEqual(state.reads,[0,1,16]);
assert.equal(state.referenceReads,1);
assert.ok(!JSON.stringify(receipts).includes(pixels.data));
for(const receipt of receipts.filter(row=>!row.error)){
const review=new Map(journal().screenReviews).get(receipt.page-1);
assert.equal(review.screenFingerprint,receipt.screenFingerprint);
assert.deepEqual(review.issues,[...receipt.imageIssues,...receipt.overlayFixes,...receipt.copyFixes]);
}
});
test('Pi drops invalid references and keeps located findings', {timeout:10_000}, async t=>{
const {host,actions}=await fixture(t);
const locationOnly={...needsFix,
imageIssues:needsFix.imageIssues.map(({slotId,...issue})=>issue),
overlayFixes:[{location:'右上方角标',issue:'角标压住标题',suggestion:'挪到标题上方'}],
copyFixes:[{location:'图片下沿',issue:'合成图残留旧规格',suggestion:'改为实际规格'}],
};
const worker=await usePiWorker(t,host,'review_output_screen',()=>({
...locationOnly,
imageIssues:[{...locationOnly.imageIssues[0],slotId:' ',slotNumber:999}],
overlayFixes:[{...locationOnly.overlayFixes[0],nativeLayerId:999}],
copyFixes:[{...locationOnly.copyFixes[0],field:'wrong-field',screenFieldNumber:999}],
}));
const [receipt]=await actions.check_output_screens({pages:[2],wait:true});
assert.deepEqual(receipt,{reviewRound:1,issueHistory:[],page:2,revision:7,screenFingerprint:'screen-P2',templateStyle:null,...locationOnly,
droppedReferences:[
{path:'imageIssues[0].slotId',value:' '},{path:'imageIssues[0].slotNumber',value:999},
{path:'overlayFixes[0].nativeLayerId',value:999},{path:'copyFixes[0].field',value:'wrong-field'},
{path:'copyFixes[0].screenFieldNumber',value:999},
]});
assert.equal(worker.calls(),1);
});
test('waiting screen review returns its last rejection when Pi reaches the turn limit', {timeout:10_000}, async t=>{
const {host,actions}=await fixture(t);
const worker=await usePiWorker(t,host,'review_output_screen',round=>({
...needsFix,overlayFixes:[{...needsFix.overlayFixes[0],nativeLayerId:900+round,location:undefined}],
}));
const [receipt]=await actions.check_output_screens({pages:[2],wait:true});
assert.equal(worker.calls(),WORKER_TURN_LIMIT);
assert.equal(receipt.page,2);
assert.ok(receipt.error.includes(`screen-2 在 ${WORKER_TURN_LIMIT} 轮内未提交有效结论`));
assert.ok(receipt.error.includes(`最后一次退回原因\noverlayFixes[0].nativeLayerId ${900+WORKER_TURN_LIMIT}`));
const [summary]=(await actions.await_image_slots({})).screenChecks;
assert.equal(summary.page,2);
assert.ok(receipt.error.startsWith(summary.error));
assert.ok(summary.error.length<receipt.error.length);
assert.deepEqual(await callProductionTool(host,'read_screen_review',{page:2}),receipt);
const scope=screenReviewScope(variantId,outputId,2);
const events=(await worker.events()).filter(event=>event.slotId==='screen-2'&&event.requestScope===scope);
const starts=events.filter(event=>event.type==='tool_execution_start');
const ends=events.filter(event=>event.type==='tool_execution_end');
assert.equal(starts.length,WORKER_TURN_LIMIT);
assert.equal(ends.length,WORKER_TURN_LIMIT);
assert.ok(ends.every(event=>event.isError&&event.toolName==='review_output_screen'));
assert.ok(ends.every(event=>event.error.includes('overlayFixes[0].nativeLayerId')&&event.error.length<=300),
JSON.stringify(ends[0]));
assert.ok(starts.every(event=>event.error===undefined));
assert.deepEqual(ends.map(event=>event.toolCallId).sort(),starts.map(event=>event.toolCallId).sort());
});
test('await_image_slots releases a candidate review that never submits a valid conclusion', {timeout:10_000}, async t=>{
const {host,actions}=await fixture(t);
const candidateId=randomUUID();
host.canvas.detailImages=async()=>({candidateId,referenceCount:1,images:[pixels,pixels],
relatedCopy:[{field:'wood',label:'木材',text:'橡胶木'}]});
const worker=await usePiWorker(t,host,'review_candidate',(round,previous)=>{
if(round>1){
const reason=previous.content[0].text;
for(const fact of [`candidateId "wrong-${round-1}"`,`本次可用 candidateId "${candidateId}"`,
'本次可用 field [{"field":"wood","label":"木材"},{"field":"title-2"}]'])assert.ok(reason.includes(fact),reason);
}
return {screenReview:pass,candidateId:`wrong-${round}`,verdict:'pass',reason:'与原图相符',
checks:{structure:true,color:true,composition:true,evidence:true},shownFields:[{field:'unknown',location:'画面中央'}]};
});
await actions.check_image_slots({candidates:[{slotId:'slot-2',candidateId}]});
const result=await actions.await_image_slots({slotIds:['slot-2']});
assert.equal(worker.calls(),WORKER_TURN_LIMIT,JSON.stringify(result.checks));
assert.equal(result.checking,0);
assert.equal(result.checks[0].candidateId,candidateId);
assert.ok(result.checks[0].error.includes(`slot-2 在 ${WORKER_TURN_LIMIT} 轮内未提交有效结论`));
assert.ok(result.checks[0].error.includes(`candidateId "wrong-${WORKER_TURN_LIMIT}"`));
});
test('a candidate can correct a schema rejection and submit on the last allowed turn', {timeout:10_000}, async t=>{
const {host,actions}=await fixture(t);
const candidateId=randomUUID();
host.canvas.detailImages=async()=>({candidateId,referenceCount:1,images:[pixels,pixels]});
const worker=await usePiWorker(t,host,'review_candidate',(round,previous)=>{
if(round>1){
assert.equal(previous.isError,true);
assert.match(previous.content[0].text,/reason: expected at least 1 characters/);
assert.ok(previous.content[0].text.includes(`本次可用 candidateId "${candidateId}"`));
}
return {candidateId,verdict:'pass',reason:round===WORKER_TURN_LIMIT?'与原图相符':''};
});
const [receipt]=await actions.check_image_slots({candidates:[{slotId:'slot-2',candidateId}],wait:true});
assert.equal(worker.calls(),WORKER_TURN_LIMIT,receipt.error);
assert.equal(receipt.verdict,'pass');
});
test('finish and progress keep screen reviews across unrelated edits and clear them for changed product inputs',async t=>{
const {host,actions,state,summaryFor}=await fixture(t);
const {canvas}=host;
canvas.finishProduction=async ({complete,screenReviewFingerprints})=>{
assert.equal(complete,true);
assert.deepEqual(screenReviewFingerprints,[{page:1,screenFingerprint:'screen-P1',issues:[]},{page:2,screenFingerprint:'screen-P2',
issues:[...needsFix.imageIssues,...needsFix.overlayFixes,...needsFix.copyFixes]}]);
return {complete,finalized:false,pendingOutputs:[],progressSummary:summaryFor(screenReviewFingerprints)};
};
host.runDetailAgent=async(_id,_system,_prompt,[tool])=>tool.execute('',pass);
await callProductionTool(host,'check_output_screens',{pages:[1]});
host.runDetailAgent=async(_id,_system,_prompt,[tool])=>tool.execute('',needsFix);
await callProductionTool(host,'check_output_screens',{pages:[2]});
const waiting=await actions.await_image_slots({});
const reviewed=await actions.review_image_slots({});
assert.equal(waiting.progressSummary.screensWithOpenIssues,reviewed.progressSummary.screensWithOpenIssues.length);
assert.deepEqual(await actions.read_screen_review({page:2}),
{page:2,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P2',templateStyle:null,...needsFix});
const reopened=await openProductionOperations(host);
assert.deepEqual(await reopened.read_screen_review({page:2}),await actions.read_screen_review({page:2}));
await reopened.close();
assert.deepEqual(reviewed.progressSummary.screensWithOpenIssues.map(row=>row.page),[2]);
assert.ok(!reviewed.progressSummary.unreviewedScreens.some(row=>row.page===2));
state.revision=8;
state.fingerprints[1]='edited-P2';
const plan=await callProductionTool(host,'plan_production',{});
const finish=await callProductionTool(host,'finish_production',{revision:8});
assert.deepEqual(finish.progressSummary,plan.progressSummary);
assert.deepEqual(finish.progressSummary.unreviewedScreens.slice(0,2).map(row=>row.page),[2,3]);
state.colorName='原木色';
const changed=await callProductionTool(host,'plan_production',{});
assert.equal(changed.progressSummary.unreviewedScreens.length,18);
assert.deepEqual(await actions.finishEvidence(),{});
});
test('screen reviews share the six-worker queue and expose asynchronous receipts',async t=>{
const {host,actions}=await fixture(t);
const generationEntered=Promise.withResolvers(), generation=Promise.withResolvers();
const fiveScreens=Promise.withResolvers(), sixScreens=Promise.withResolvers(), screens=Promise.withResolvers();
t.after(()=>{generation.resolve();screens.resolve();});
let active=0,peak=0,started=0;
host.runDetailAgent=async(id,_system,_prompt,[tool])=>{
peak=Math.max(peak,++active);
try{
if(id==='slot-1'){
generationEntered.resolve();
await generation.promise;
return;
}
if(++started===5)fiveScreens.resolve();
if(started===6)sixScreens.resolve();
await screens.promise;
tool.execute('',pass);
}finally{active--;}
};
await actions.delegate_image_slots({jobs:[{slotId:'slot-1',goal:'核对主图'}]});
await generationEntered.promise;
const pages=[1,2,3,4,5,6,7];
assert.deepEqual(await actions.check_output_screens({pages,wait:false}),
pages.map(page=>({page,state:'queued'})));
await fiveScreens.promise;
assert.equal(started,5);
const joined=actions.check_output_screens({pages:[1]});
generation.resolve();
await sixScreens.promise;
assert.equal(started,6);
screens.resolve();
assert.deepEqual(await joined,[{page:1,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:'screen-P1',templateStyle:null,...pass}]);
let result=await actions.await_image_slots({});
while(result.screenChecks.some(row=>row.state==='queued'||row.state==='checking')){
result=await actions.await_image_slots({});
}
await actions.close();
assert.deepEqual(JSON.parse(JSON.stringify(result.screenChecks)),pages.map(page=>({page,revision:7,reviewRound:1,issueHistory:[],screenFingerprint:`screen-P${page}`,...pass})));
assert.equal(started,7);
assert.equal(peak,6);
});
test('screen review refuses unsupported evidence, invalid targets and stale passes',async t=>{
const {host,actions,state,journal}=await fixture(t);
for(const pages of [[],[-1],[1.5],[1,NaN]]){
await assert.rejects(actions.check_output_screens({pages}),/有效屏号/);
}
assert.deepEqual(state.reads,[]);
host.runDetailAgent=()=>assert.fail('missing evidence must not be reviewed');
state.fingerprints[0]=undefined;
assert.equal((await actions.check_output_screens({pages:[1]}))[0].error,'请先读取当前屏画面');
state.fingerprints[0]='screen-P1';
state.overlay=false;
assert.match((await actions.check_output_screens({pages:[1]}))[0].error,/未返回本屏叠加图层清单/);
state.overlay=true;
host.runDetailAgent=async(_id,_system,_prompt,[tool])=>{
const fix={...needsFix,imageIssues:[],copyFixes:[],overlayFixes:[{...needsFix.overlayFixes[0],nativeLayerId:999}]};
tool.execute('',fix);
};
assert.match((await actions.check_output_screens({pages:[2]}))[0].error,/overlayFixes\[0\]\.nativeLayerId 999 不在本屏叠层清单中/);
host.runDetailAgent=async(_id,_system,_prompt,[tool])=>{
tool.execute('',pass);
state.revision++;
state.fingerprints[0]='edited-P1';
};
assert.equal((await actions.check_output_screens({pages:[1]}))[0].error,'本屏已变化,请重新读取当前画面');
assert.equal(journal()?.screenReviews,undefined);
});
test('an unrelated screen edit during a worker review preserves its pass',async t=>{
const {host,actions,state,journal}=await fixture(t);
const render=host.canvas.detailRender;
host.canvas.detailRender=async args=>{
const receipt=await render(args);
state.revision++;
state.fingerprints[1]='edited-before-copy';
return receipt;
};
host.runDetailAgent=async(_id,_system,_prompt,[tool])=>{
state.revision++;
state.fingerprints[1]='edited-before-record';
tool.execute('',pass);
};
const [receipt]=await actions.check_output_screens({pages:[1]});
assert.equal(receipt.verdict,'pass');
assert.equal(journal().screenReviews[0][1].screenFingerprint,'screen-P1');
});
test('screen review tool schema and activity expose the public contract',()=>{
const [,description,schema]=productionOperationTools.find(([name])=>name==='check_output_screens');
const tool={name:'check_output_screens',parameters:schema};
assert.deepEqual(validateToolArguments(tool,{name:tool.name,arguments:{pages:[1,17]}}),{pages:[1,17]});
assert.deepEqual(validateToolArguments(tool,{name:tool.name,arguments:{pages:['1'],wait:'false'}}),{pages:[1],wait:false});
for(const args of [{pages:[-1]},{pages:[]},{pages:['page']},{pages:[2],wait:'sometimes'}]){
assert.throws(()=>validateToolArguments(tool,{name:tool.name,arguments:args}));
}
assert.match(description,/默认等待结论/);
const event={type:'tool_execution_start',toolName:'check_output_screens',toolCallId:'call-9',args:{pages:[1]}};
assert.equal(activityToolLabel(event.toolName),'逐屏检查画布效果');
assert.deepEqual(toolActivity(event,{},123),{version:1,type:'tool',toolCallId:'call-9',
toolName:'check_output_screens',status:'started',summary:'开始:逐屏检查画布效果',
phase:'started',category:'inference',timestampMs:123,scope:{}});
});
test('a reopened canvas can finish with historical screen inference records',async t=>{
const {host,actions}=await fixture(t);
const detailSlot=screenReviewScope(variantId,outputId,17);
const other=screenReviewScope(variantId,'main_images',17);
assert.notEqual(detailSlot,other);
assert.notEqual(detailSlot,screenReviewScope(variantId,outputId,1));
assert.notEqual(detailSlot,screenReviewScope('walnut',outputId,2));
host.broker={status:async()=>({pending:[
{modelRole:'detail',detailSlot,id:'existing-request'},
{modelRole:'detail',detailSlot:other,id:'different-output'},
]})};
assert.deepEqual(await actions.unfinished(),{outputId,variantId,complete:false,stageStatus:'continue'});
assert.equal((await actions.finish_production({revision:7})).production.complete,true);
});
test('review receives the original screen and locates hidden or deleted template layers', async () => {
const {reviewOutputScreen} = await import('../src/screen-review.mjs');
const image = {type:'image',mimeType:'image/jpeg',data:'AA=='};
const templateFidelity = {
changes:[{nativeLayerId:88,deleted:true}],
retainedTemplateText:[{nativeLayerId:89,text:'88 cm'}],
};
const result = await reviewOutputScreen({
page:1,outputId:'detail',variantId:'v',slots:[],
screen:{content:[image,image],details:{revision:2,screenFingerprint:'fingerprint',
overlayLayers:[],templateFidelity}},
references:async()=>({product:{dimensions:{height:42,unit:'cm'}},photos:[image]}),
runAgent:async (_slot,instructions,prompt,[tool],images,_scope,captions)=>{
assert.match(instructions,/品牌资料/);
assert.deepEqual(captions,['当前整屏成片','模板原屏','本款实拍 1']);
assert.equal(images.length,3);
assert.deepEqual(JSON.parse(prompt).templateFidelity,templateFidelity);
tool.execute('receipt',{verdict:'needs_fix',summary:'原稿标注被移除并残留旧数字',
imageIssues:[],copyFixes:[],overlayFixes:[
{nativeLayerId:88,issue:'缺少原稿标注',suggestion:'从原稿复制图层'},
{nativeLayerId:89,issue:'沿用旧尺寸',suggestion:'依据本款确认值修改文字'},
]});
},
});
assert.equal(result.overlayFixes.length,2);
});
test('template screen evidence stays below 4000 characters and can page changes', async () => {
const {compactTemplateFidelity} = await import('../src/template-fidelity.mjs');
const evidence = {changes:Array.from({length:100},(_,index)=>({
nativeLayerId:index+1,name:'模板图层'.repeat(35),hiddenBy:[{nativeLayerId:index+1,visible:false}],
color:{template:'#223344',current:'#333333'},
})),retainedTemplateText:[{nativeLayerId:12,text:'88 cm'}]};
const first=compactTemplateFidelity(evidence);
assert.ok(JSON.stringify(first).length<4000);
assert.equal(first.changeCount,100);
assert.match(first.changes[0].difference,/隐藏.+改色/);
assert.equal(first.retainedTemplateText[0].text,'88 cm');
const next=compactTemplateFidelity(evidence,[],first.nextChangeOffset);
assert.equal(next.changes[0].nativeLayerId,first.changes.length+1);
});
test('screen review accepts pass with only required fields and top-level template style', async t=>{
const {host,actions}=await fixture(t);
await usePiWorker(t,host,'review_output_screen',(round,previous)=>{
if(round===1)return {verdict:'pass',templateStyle:null};
if(round===2){
assert.match(previous.content[0].text,/summary: missing/u);
return {verdict:'needs_fix',summary:'需要修改',templateStyle:null,imageIssues:[{overlayFixes:[]}]};
}
if(round===3){
assert.match(previous.content[0].text,/imageIssues\.0\.(issue|suggestion): missing/u);
assert.match(previous.content[0].text,/imageIssues、overlayFixes、copyFixes 是并列的顶层数组/u);
return {verdict:'needs_fix',summary:'需要修改',templateStyle:null};
}
assert.equal(round,4);
assert.match(previous.content[0].text,/添加至少一项实际问题和修改建议/u);
return {verdict:'pass',summary:'画面通过',templateStyle:null};
});
const [receipt]=await actions.check_output_screens({pages:[2],wait:true});
assert.deepEqual([receipt.verdict,receipt.templateStyle,receipt.imageIssues,receipt.overlayFixes,receipt.copyFixes],
['pass',null,[],[],[]]);
});