import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import test from 'node:test'; import { validateToolArguments } from '@earendil-works/pi-ai'; import { mergeReviewCopy, extractPageLiveCopy, resolveLiveSlotCopy } from '../src/copy-image-alignment.mjs'; import { reviewProductionCandidate } from '../src/candidate-review.mjs'; import { openProductionOperations } from '../src/production-operations.mjs'; import { completeCanvas } from './fake-canvas.mjs'; import { callProductionTool, closeProductionTurn } from '../src/production-goal.mjs'; import { cleanup } from './cleanup.mjs'; import { productionStore } from './production-store-fixture.mjs'; const slot={id:'leg-slot',fieldId:'P02-leg',label:'桌腿特写'}; const pages=['P01','P02']; const fields=[ {layer:1,page:'P02',field:'title',label:'标题',currentText:'加厚桌腿'}, {layer:2,page:'P02',field:'detail',role:'正文',currentText:'桌腿与横梁用榫接固定'}, {layer:3,page:'P02',field:'tag',relatedFields:['leg-slot'],currentText:'实木横梁'}, {layer:4,page:'P02',field:'sample',currentText:'模板样例',templateSample:true}, {layer:5,page:'P02',field:'blank',currentText:' '}, {layer:6,page:'P01',field:'hero',currentText:'圆形桌面'}, ]; const journalCopy=[{field:'title',text:'圆润桌面',pictures:['P02-leg'],sources:['P01']}]; test('live text replaces stale journal copy and includes all supported selling points on the screen',()=>{ const result=resolveLiveSlotCopy({slot,copyFields:fields,pages,journalCopy}); assert.deepEqual(result.map(({field,text,binding})=>[field,text,binding]),[ ['title','加厚桌腿','direct'], ['detail','桌腿与横梁用榫接固定','same_screen'], ['tag','实木横梁','direct'], ]); assert.equal(result[0].sources,undefined); assert.deepEqual(resolveLiveSlotCopy({slot,copyFields:[{...fields[0],currentText:''}],journalCopy}),[]); }); test('declared page and native document IDs locate a screen without guessing the field prefix',()=>{ const copyFields=fields.slice(0,2); for(const location of [{page:'P02'},{pageId:'P02'},{documentId:'P02'}]){ const result=resolveLiveSlotCopy({slot:{...slot,...location},copyFields,pages}); assert.deepEqual(result.map(row=>row.binding),['same_screen','same_screen']); } assert.deepEqual(resolveLiveSlotCopy({slot,copyFields,pages}),[]); assert.deepEqual(resolveLiveSlotCopy({slot,journalCopy}).map(row=>row.text),['圆润桌面']); const repeated={...fields[0],page:'P01',currentText:'另一屏的同名文字格'}; const result=resolveLiveSlotCopy({slot:{...slot,page:'P02'},copyFields:[...copyFields,repeated],journalCopy}); assert.equal(result.find(row=>row.field==='title').text,'加厚桌腿'); }); test('merge keeps native linked text alongside recorded copy and prefers the live screen on duplicate fields',()=>{ const copy=[{field:'title',text:'旧文案'},{field:'label',text:'来自台账'}]; const relatedCopy=[{fieldId:'title',text:'原生关联文案'},{fieldId:'tag',text:'实木横梁'}]; const liveScreenCopy=[{field:'title',text:'加厚桌腿',binding:'direct'}]; assert.deepEqual(mergeReviewCopy({copy,relatedCopy,liveScreenCopy}).map(row=>[row.field,row.text]),[ ['title','加厚桌腿'],['label','来自台账'],['tag','实木横梁'], ]); }); const passedScreen={verdict:'pass',summary:'整屏通过',imageIssues:[],overlayFixes:[],copyFixes:[]}; const composedScreen=image=>({image,details:{page:0,slots:[slot],overlayLayers:[],screenCopy:[]}}); test('candidate review records the observed subject and alignment while accepting the five original checks',async()=>{ const image={type:'image',data:'fixture',mimeType:'image/png'}; const checks={structure:true,color:true,templateStyle:true,composition:true,evidence:true}; for(const alignment of [{shownSubject:'桌面俯拍',copyAlignment:false},{}]){ const {shownSubject,copyAlignment}=alignment; const result=await reviewProductionCandidate({ canvas:{detailImages:async()=>({candidateId:'candidate',referenceCount:1,images:[image,image], relatedCopy:[{fieldId:'tag',text:'实木横梁'}]})}, screen:composedScreen(image),slot,candidateId:'candidate',copy:journalCopy, liveScreenCopy:[{field:'title',text:'加厚桌腿',binding:'direct'}], async runAgent(_slot,instructions,prompt,[tool]){ assert.match(instructions,/shownSubject.*shownFields/u); const {screenCopy}=JSON.parse(prompt); assert.deepEqual(screenCopy.map(row=>row.text),['加厚桌腿','实木横梁']); const assessment={screenVerdict:'pass',candidateId:'candidate',verdict:'revise',reason:'桌腿未入画', ...(shownSubject?{shownSubject}:{}), checks:{...checks,...(copyAlignment===false?{copyAlignment}:{})}}; assert.deepEqual(validateToolArguments(tool,{name:tool.name,arguments:assessment}),assessment); await tool.execute('review',assessment); }, }); assert.equal(result.shownSubject,shownSubject); assert.equal(result.observation.shownSubject,shownSubject); assert.equal(result.checks.copyAlignment,copyAlignment); for(const key of ['viewpoint','accessories','ratioAndCrop','originalComposition','visibleScene', 'purposeWithoutTitle','productScale','forbiddenMarks','productIdentity','textAndFacts']){ assert.ok(Object.hasOwn(result.checks,key),key); } assert.deepEqual(result.observation.reviewedCopy,[['tag','实木横梁'],['title','加厚桌腿']]); } }); for (const referenceMode of ['composition-only','none']) test(`candidate review uses product photos and current screen for ${referenceMode}`,async()=>{ const image=data=>({type:'image',data,mimeType:'image/png'}); const photo=image('photo'), layout=image('layout'), candidate=image('candidate'), extra=image('extra'); const source={candidateId:'candidate',referenceCount:2,originalReferenceIndex:1,layoutCount:1, images:[image('other shot'),photo,layout,candidate], candidatePrompt:'主体居中,左侧留白',candidateOriginal:extra,bareCandidate:extra,textRegionPreview:extra,actionReviewDetail:extra, hasWhiteTopBand:true,whiteSideBands:['left'],textRegionEdgeObstructions:true}; const result=await reviewProductionCandidate({ canvas:{detailImages:async(_slot,_candidate,options)=>{assert.deepEqual(options,{candidatePixels:true,includeTemplateReference:false});return source;}}, screen:composedScreen(extra),referenceMode,slot,candidateId:'candidate',rule:{crop:true,actionReviewRegion:[0,0,50,50]}, async runAgent(_slot,_instructions,prompt,[tool],images,_scope,captions){ assert.deepEqual(images,[candidate,extra,photo]); assert.deepEqual(captions,['受审候选原图','候选放入后的整屏合成','同款实拍 P02']); assert.equal(JSON.parse(prompt).candidatePrompt,referenceMode==='composition-only'?source.candidatePrompt:undefined); assert.doesNotMatch(prompt,/pixelFindings|hasWhiteTopBand|extraViews/u); await tool.execute('review',{screenReview:passedScreen,candidateId:'candidate',verdict:'pass',reason:'清楚呈现桌腿', checks:{structure:true,color:true,composition:true,evidence:true}}); }, }); assert.equal(result.verdict,'pass'); assert.equal(result.observation.pixelFindings,undefined); }); test('production delegation and screen rendering use live copy after a direct canvas edit',async t=>{ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-copy-alignment-')); t.after(()=>cleanup(dir)); const live=structuredClone(fields); live[0].currentText='圆润桌面'; let delegated; const textLayers=[{nativeLayerId:4,readability:{contrastP10:2.5},styleDifferences:{}}]; const overlayLayers=[ {nativeLayerId:41,mapped:false,text:'旧尺寸 140 cm',bounds:[10,20,80,44],overlapsSlots:[slot.id]}, {nativeLayerId:42,mapped:true,text:null,bounds:[32,40,90,130],overlapsSlots:[slot.id]}, ]; const host={store:productionStore(dir),productionGoal:{outputId:'detail',variantId:'oak'},canvas:{ imageRequest:async()=>[], workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak', template:{contentHash:'fixture'},totalSlots:1,slots:[slot]}), detailCopyFields:async options=>{ assert.equal(options.includeFilled,true); return {fields:structuredClone(live),pages,revision:2}; }, detailRender:async({page,region,zoom})=>({ page,revision:2,overlayLayers:page===1?overlayLayers:[],textLayers:page===1?textLayers:[], annotationLayout:{texts:[],lines:[],crossings:[]}, ...(region?{regionPreview:{bounds:region,zoom},images:[{type:'image',mimeType:'image/jpeg',data:'crop'}]}:{images:[]}), }), readCanvas:async({layer})=>({context:{layers:[{id:layer,visible:true,effectiveVisible:layer!==7}]}}), delta:async()=>{}, },async runDetailAgent(_slot,instructions,prompt){ assert.match(instructions,/screenCopy 是画布实时文案/u); delegated=JSON.parse(prompt); }}; completeCanvas(host.canvas); const actions=await openProductionOperations(host); await actions.write_copy_fields({revision:2,recordOnly:true,items:[ {layer:1,text:'圆润桌面',pictures:[slot.fieldId],sources:['P01']}, ]}); live[0].currentText='加厚桌腿'; await actions.delegate_image_slots({jobs:[{slotId:slot.id,goal:'展示加厚桌腿'}]}); await actions.await_image_slots({slotIds:[slot.id]}); assert.deepEqual(delegated.screenCopy.map(row=>row.text),['加厚桌腿','桌腿与横梁用榫接固定','实木横梁']); live.push({layer:7,page:'P02',field:'hidden',currentText:'已隐藏分组的旧文案'}); const {details,content}=await actions.read_output_screen({page:2}); const crop=await actions.read_output_screen({page:2,region:[20,30,100,80],zoom:2}); assert.deepEqual(crop.details.regionPreview,{bounds:[20,30,100,80],zoom:2}); assert.deepEqual(crop.details.annotationLayout,details.annotationLayout); assert.deepEqual(crop.content[1],{type:'image',mimeType:'image/jpeg',data:'crop'}); assert.deepEqual(details.overlayLayers,overlayLayers); assert.deepEqual(details.textLayers,textLayers); assert.deepEqual(JSON.parse(content[0].text).overlayLayers,overlayLayers); const multi=await actions.read_output_screen({pages:[1,2]}); assert.deepEqual(multi.details.screens.map(screen=>screen.overlayLayers),[[],overlayLayers]); assert.deepEqual(multi.details.screens.map(screen=>screen.textLayers),[[],textLayers]); assert.deepEqual(details.screenCopy,extractPageLiveCopy({pageIndex:1,pages,fields})); assert.deepEqual(details.screenCopy.map(row=>[row.field,row.text,row.templateSample]),[ ['title','加厚桌腿',false],['detail','桌腿与横梁用榫接固定',false],['tag','实木横梁',false],['sample','模板样例',true], ]); assert.equal((await actions.read_output_screen({page:3})).details.screenCopy,undefined); await actions.close(); }); test('switching outputs discards the prior canvas copy reads and uses the new live copy for review',async t=>{ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-output-copy-')); const revision=2; const variantId='oak'; const copyByOutput={detail:'加厚桌腿',main_images:'圆角桌面',sku_images:'白橡木色'}; const slotByOutput={detail:slot,main_images:{...slot,selectedCandidateId:'candidate'},sku_images:{...slot,id:'sku-slot'}}; const reviewed=[]; let outputId; let edits; const image={type:'image',data:'fixture',mimeType:'image/png'}; const host={store:productionStore(dir),productionGoal:{},bindGoalRequestScope(){},canvas:completeCanvas({ openProductionOutput:async binding=>{ outputId=binding.outputId; return binding; }, imageRequest:async()=>[], workflowRead:async()=>({available:true,canvasFirst:true,outputId,productVariantId:variantId, template:{contentHash:'fixture'},totalSlots:1,slots:[{...slot,documentId:pages[1]}]}), detailHistory:async({targetOutput})=>({outputId:targetOutput.outputId,productVariantId:variantId, template:{contentHash:'fixture'},slots:[slotByOutput[targetOutput.outputId]]}), detailCopyFields:async({targetOutput}={})=>({revision,pages, fields:[{...fields[0],currentText:copyByOutput[targetOutput?.outputId??outputId]}]}), detailRender:async({page})=>({page,revision,images:[]}), detailCandidateScreen:async({slotId,candidateId})=>({slotId,candidateId,page:1, screenFingerprint:'fixture',imageSlots:[slotId],overlayLayers:[], copyFields:[{...fields[0],currentText:copyByOutput[outputId]}],images:[image]}), detailImages:async()=>({candidateId:'candidate',referenceCount:1,images:[image,image]}), commitDetailCopy:async value=>{ edits=value; return {appliedLayers:[],revision}; }, delta:async()=>{}, }),async runDetailAgent(_slot,_instructions,prompt,[tool]){ const {screenCopy}=JSON.parse(prompt); reviewed.push(screenCopy[0].text); await tool.execute('review',{screenReview:passedScreen,candidateId:'candidate',verdict:'pass',reason:'主角匹配', shownSubject:screenCopy[0].text,checks:{structure:true,color:true,templateStyle:true, composition:true,evidence:true,copyAlignment:true}}); }}; t.after(async()=>{await closeProductionTurn(host); await cleanup(dir);}); const action=(name,args={})=>callProductionTool(host,name,args); await action('open_production_output',{outputId:'detail',variantId}); host.productionGoal.requestedOutputs=Object.keys(copyByOutput).map(outputId=>({outputId,variantId})); for(const [target,text] of Object.entries(copyByOutput)){ const reply=await action('read_copy_fields',{outputId:target,variantId,pageId:pages[1]}); assert.equal(reply.fields[0].currentText,text); } assert.equal(outputId,'detail'); const mainProgress=await action('review_image_slots',{outputId:'main_images',variantId}); assert.equal(mainProgress.coverage.coveredFields,1); assert.equal(mainProgress.pictures[0].selectedCandidateId,'candidate'); assert.deepEqual(mainProgress.progressSummary.unfilledImageSlots,[]); const skuProgress=await action('review_image_slots',{outputId:'sku_images',variantId}); assert.equal(skuProgress.coverage.coveredFields,0); assert.deepEqual(skuProgress.progressSummary.unfilledImageSlots.map(row=>row.slotId),['sku-slot']); const detail=await action('read_copy_fields'); assert.equal(detail.fields[0].currentText,'加厚桌腿'); await action('write_copy_fields',{revision,recordOnly:true,items:[ {layer:1,text:'加厚桌腿',pictures:[slot.fieldId],sources:['仅详情图使用']}, ]}); await action('open_production_output',{outputId:'main_images',variantId}); const write={revision:detail.revision,items:[{layer:1,text:'确认圆角桌面'}]}; const {details}=await action('read_output_screen',{page:2}); assert.deepEqual(details.screenCopy.map(row=>row.text),['圆角桌面']); await action('write_copy_fields',{...write,revision:details.copyRevision??details.revision}); assert.equal(edits[0].text,'确认圆角桌面'); assert.equal(edits[0].expectedText,undefined); await action('check_image_slots',{wait:true,candidates:[{slotId:slot.id,candidateId:'candidate'}]}); assert.deepEqual(reviewed,['圆角桌面']); const journal=host.store.ledger('main_images',variantId).read(); assert.deepEqual(journal.items[slot.id].review.observation.reviewedCopy,[['title','圆角桌面']]); }); test('legacy field decisions remain readable after reopening and visible old values are reported through handoff',async t=>{ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-field-requirements-')); t.after(()=>cleanup(dir)); const sample='座高62.26cm'; const live=[ {layer:1,page:'P01',field:'seat',label:'座高',originalText:sample,currentText:sample,visible:true}, {layer:2,page:'P01',field:'title',currentText:'标题',visible:true}, {layer:3,page:'P01',field:'material',currentText:'',visible:true}, ]; let overlayLayers=[]; const host={store:productionStore(dir),productionGoal:{outputId:'detail',variantId:'oak'},canvas:{ imageRequest:async()=>[], workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak', template:{contentHash:'fixture'},totalSlots:0,slots:[],productEvidence:{brief:{dimensions:{座高:'450',unit:'mm'}}}}), detailCopyFields:async({pageId})=>({fields:live.map(({originalText,...row})=>pageId?{...row,originalText}:row),pages:['P01'],revision:1}), detailRender:async()=>({revision:1,overlayLayers,images:[]}), }}; completeCanvas(host.canvas); const fieldRequirements=[ {layer:1,page:'P01',field:'seat',decision:'改写',basis:'本款规格表座高 450 mm'}, {layer:2,page:'P01',field:'title',decision:'保留',basis:'标题适用于本款'}, {layer:3,page:'P01',field:'material',decision:'待核实',basis:'规格表未列材质'}, ]; await fs.writeFile(path.join(dir,'production-detail-oak.json'),JSON.stringify({ binding:JSON.stringify(['fixture','oak']),items:{}, copyInputs:JSON.stringify([{dimensions:{座高:'450',unit:'mm'}},null,false,null]), fieldRequirements:Object.fromEntries(fieldRequirements.map(row=>[row.layer,row])), copyStyleMappings:{1:'default'}, })); const actions=await openProductionOperations(host); const plan=await actions.plan_production(); assert.deepEqual(plan.fieldConflicts.map(({field,templateValue,productValue})=>[field,templateValue,productValue]), [['seat','62.26cm','450 mm']]); t.after(()=>actions.close()); assert.deepEqual((await actions.read_output_screen({})).details.fieldRequirements,fieldRequirements); const finish=async()=> (await actions.finish_production({revision:1})).production; assert.equal((await finish()).visibleConflicts[0].state,'old_visible'); live[0].currentText='座高 450 mm'; overlayLayers=[{nativeLayerId:4,text:sample,mapped:false}]; assert.equal((await finish()).visibleConflicts[0].state,'both_visible'); overlayLayers=[]; const delivered=await finish(); assert.equal(delivered.visibleConflictCount,0); assert.deepEqual(delivered.fieldRequirements,fieldRequirements); });